harperdb 4.3.19 → 4.3.21

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.
Files changed (86) hide show
  1. package/README.md +3 -3
  2. package/bin/harperdb.js +58 -58
  3. package/bin/lite.js +20 -20
  4. package/index.d.ts +1 -0
  5. package/launchServiceScripts/launchInstallNATSServer.js +2 -2
  6. package/launchServiceScripts/launchNatsIngestService.js +20 -20
  7. package/launchServiceScripts/launchNatsReplyService.js +20 -20
  8. package/launchServiceScripts/launchUpdateNodes4-0-0.js +20 -20
  9. package/npm-shrinkwrap.json +1057 -1245
  10. package/package.json +16 -8
  11. package/resources/Resource.d.ts +5 -6
  12. package/resources/ResourceInterface.d.ts +56 -13
  13. package/resources/Table.d.ts +19 -19
  14. package/resources/databases.d.ts +17 -18
  15. package/server/jobs/jobProcess.js +20 -20
  16. package/server/threads/threadServer.js +20 -20
  17. package/studio/build-local/asset-manifest.json +36 -36
  18. package/studio/build-local/index.html +1 -1
  19. package/studio/build-local/static/css/main.6c0f1b63.css +13 -0
  20. package/studio/build-local/static/js/{424.7d57284b.chunk.js → 424.ad87c8fd.chunk.js} +1 -1
  21. package/studio/build-local/static/js/{662.02ce7b65.chunk.js → 662.92e32ffc.chunk.js} +1 -1
  22. package/studio/build-local/static/js/723.c58acced.chunk.js +2 -0
  23. package/studio/build-local/static/js/807.510f66df.chunk.js +2 -0
  24. package/studio/build-local/static/js/browse-csvupload.453237f3.chunk.js +1 -0
  25. package/studio/build-local/static/js/browse-datatable.b9ef2d28.chunk.js +1 -0
  26. package/studio/build-local/static/js/browse-entitymanager.50827a5a.chunk.js +1 -0
  27. package/studio/build-local/static/js/browse-jsonviewer.a2534004.chunk.js +1 -0
  28. package/studio/build-local/static/js/custom-functions.dd7e182c.chunk.js +1 -0
  29. package/studio/build-local/static/js/instance-charts.34d15f02.chunk.js +1 -0
  30. package/studio/build-local/static/js/instance-cluster.5bce430c.chunk.js +1 -0
  31. package/studio/build-local/static/js/instance-config.70c17b53.chunk.js +1 -0
  32. package/studio/build-local/static/js/instance-query.4f6eec62.chunk.js +1 -0
  33. package/studio/build-local/static/js/instance-roles.507a4ed0.chunk.js +1 -0
  34. package/studio/build-local/static/js/instance-status.ce9d7f64.chunk.js +1 -0
  35. package/studio/build-local/static/js/instance-users-datatable.190640fd.chunk.js +1 -0
  36. package/studio/build-local/static/js/{instance-users-edit.436e0908.chunk.js → instance-users-edit.d2444479.chunk.js} +1 -1
  37. package/studio/build-local/static/js/instance-users.eabfbbde.chunk.js +1 -0
  38. package/studio/build-local/static/js/instance.a163623f.chunk.js +1 -0
  39. package/studio/build-local/static/js/instances.6b88a87c.chunk.js +1 -0
  40. package/studio/build-local/static/js/{main.05c1913d.js → main.a22f6951.js} +2 -2
  41. package/studio/build-local/static/js/offline-app.7371216b.chunk.js +1 -0
  42. package/studio/build-local/static/js/online-app.db436eec.chunk.js +1 -0
  43. package/studio/build-local/static/js/organization-billing.b2f260f0.chunk.js +1 -0
  44. package/studio/build-local/static/js/organization-users.b6171b18.chunk.js +1 -0
  45. package/studio/build-local/static/js/organization.7800f16a.chunk.js +1 -0
  46. package/studio/build-local/static/js/organizations.8bb505f2.chunk.js +1 -0
  47. package/studio/build-local/static/js/profile.292bdd86.chunk.js +1 -0
  48. package/studio/build-local/static/js/roles-jsonviewer.c11f1816.chunk.js +1 -0
  49. package/studio/build-local/static/js/signIn.b11bdc50.chunk.js +1 -0
  50. package/studio/build-local/static/js/signUp.564d4e0b.chunk.js +1 -0
  51. package/studio/build-local/static/js/structure-reloader.b6de4091.chunk.js +1 -0
  52. package/studio/build-local/static/js/topnav.4fd41d60.chunk.js +1 -0
  53. package/utility/scripts/restartHdb.js +20 -20
  54. package/studio/build-local/static/css/main.038ec116.css +0 -13
  55. package/studio/build-local/static/js/723.36068040.chunk.js +0 -2
  56. package/studio/build-local/static/js/807.3473ab0a.chunk.js +0 -2
  57. package/studio/build-local/static/js/browse-csvupload.5e77eb8a.chunk.js +0 -1
  58. package/studio/build-local/static/js/browse-datatable.cd71d518.chunk.js +0 -1
  59. package/studio/build-local/static/js/browse-entitymanager.09237801.chunk.js +0 -1
  60. package/studio/build-local/static/js/browse-jsonviewer.fcccabdc.chunk.js +0 -1
  61. package/studio/build-local/static/js/custom-functions.98af4a5e.chunk.js +0 -1
  62. package/studio/build-local/static/js/instance-charts.f1a1969d.chunk.js +0 -1
  63. package/studio/build-local/static/js/instance-cluster.0dc3ac1b.chunk.js +0 -1
  64. package/studio/build-local/static/js/instance-config.19223fab.chunk.js +0 -1
  65. package/studio/build-local/static/js/instance-query.ed7e59f5.chunk.js +0 -1
  66. package/studio/build-local/static/js/instance-roles.9c3f140d.chunk.js +0 -1
  67. package/studio/build-local/static/js/instance-status.1687cd77.chunk.js +0 -1
  68. package/studio/build-local/static/js/instance-users-datatable.ced7813f.chunk.js +0 -1
  69. package/studio/build-local/static/js/instance-users.12c0c117.chunk.js +0 -1
  70. package/studio/build-local/static/js/instance.b8863754.chunk.js +0 -1
  71. package/studio/build-local/static/js/instances.5bd051eb.chunk.js +0 -1
  72. package/studio/build-local/static/js/offline-app.b3ad12ac.chunk.js +0 -1
  73. package/studio/build-local/static/js/online-app.2ac03c15.chunk.js +0 -1
  74. package/studio/build-local/static/js/organization-billing.a8014c6f.chunk.js +0 -1
  75. package/studio/build-local/static/js/organization-users.523136d9.chunk.js +0 -1
  76. package/studio/build-local/static/js/organization.0abc89ca.chunk.js +0 -1
  77. package/studio/build-local/static/js/organizations.e536b86f.chunk.js +0 -1
  78. package/studio/build-local/static/js/profile.92f9be59.chunk.js +0 -1
  79. package/studio/build-local/static/js/roles-jsonviewer.5fe72bc9.chunk.js +0 -1
  80. package/studio/build-local/static/js/signIn.97bded2f.chunk.js +0 -1
  81. package/studio/build-local/static/js/signUp.482f9fe4.chunk.js +0 -1
  82. package/studio/build-local/static/js/structure-reloader.9322abd3.chunk.js +0 -1
  83. package/studio/build-local/static/js/topnav.5e7913a5.chunk.js +0 -1
  84. /package/studio/build-local/static/js/{723.36068040.chunk.js.LICENSE.txt → 723.c58acced.chunk.js.LICENSE.txt} +0 -0
  85. /package/studio/build-local/static/js/{807.3473ab0a.chunk.js.LICENSE.txt → 807.510f66df.chunk.js.LICENSE.txt} +0 -0
  86. /package/studio/build-local/static/js/{main.05c1913d.js.LICENSE.txt → main.a22f6951.js.LICENSE.txt} +0 -0
@@ -1,32 +1,32 @@
1
- "use strict";var Oq=Object.create;var cc=Object.defineProperty;var bq=Object.getOwnPropertyDescriptor;var yq=Object.getOwnPropertyNames;var Nq=Object.getPrototypeOf,Iq=Object.prototype.hasOwnProperty;var a=(e,t)=>cc(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)cc(e,r,{get:t[r],enumerable:!0})},_O=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yq(t))!Iq.call(e,s)&&s!==r&&cc(e,s,{get:()=>t[s],enumerable:!(n=bq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Oq(Nq(e)):{},_O(t||!e||!e.__esModule?cc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>_O(cc({},"__esModule",{value:!0}),e);var EO=g((jae,fO)=>{var wq=require("fast-glob"),{statSync:Dh,existsSync:Lh,readFileSync:Cq,writeFileSync:Dq}=require("fs"),{spawnSync:Lq,spawn:Mq,execFileSync:Jae}=require("child_process"),{isMainThread:Pq}=require("worker_threads"),{join:Xs,relative:dO}=require("path"),{PACKAGE_ROOT:bn}=P(),{tmpdir:Uq,platform:vq}=require("os");require("source-map-support").install();var Bq=["resources","server","dataLayer","components"],uc="ts-build",Mh,Hq=__filename.endsWith("tsBuild.js");if(Hq){if(Pq){let r;try{Dh(Xs(bn,uc)),r=!0}catch{}if(r)for(let n of wq.sync(Bq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=Dh(Xs(bn,n)).mtimeMs-5e3,i=Dh(Xs(bn,uc,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Mh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Mh=!0;if(Mh){let n=Xs(bn,"node_modules/.bin/tsc");vq()==="win32"&&(n+=".cmd");let s=Lq(n,{cwd:bn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Xs(Uq(),"harperdb-tsc.pid"),o;if(Lh(i))try{process.kill(+Cq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Mq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});Dq(i,c.pid.toString()),c.unref()}}}}let e=fO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=dO(bn,n[0]),o;i.startsWith(uc)?o=Xs(bn,dO(uc,i)):o=Xs(bn,uc,i);let c=Xs(o,r),u=c+".js";if(Lh(u))return u;if(c.includes(".")&&Lh(c))return c}return t(r,n,s)}}});var P=g((ece,wO)=>{"use strict";var an=require("path"),xq=require("fs"),{relative:Xae,join:Zae}=an,{existsSync:Gq}=xq;function qq(){let e=__dirname;for(;!Gq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(qq,"getHDBPackageRoot");var Zs=qq(),hO="js",e_=hO,Fq="harperdb-config.yaml",kq="defaultConfig.yaml",Vq="hdb",mO=`harperdb.${e_}`,pO=`customFunctionsServer.${e_}`,$q=`restartHdb.${e_}`,Uh="HarperDB",Zl="Custom Functions",t_="Clustering Hub",r_="Clustering Leaf",Yq="Clustering Ingest Service",Kq="Clustering Reply Service",Wq="foreground.pid",Qq="hdb.pid",zq="data",Jq={HDB:Uh,CLUSTERING_HUB:t_,CLUSTERING_LEAF:r_,CLUSTERING_INGEST_SERVICE:Yq,CLUSTERING_REPLY_SERVICE:Kq,CUSTOM_FUNCTIONS:Zl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},jq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Xq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Zq={harperdb:Uh,"clustering hub":t_,"clustering leaf":r_,"custom functions":Zl,custom_functions:Zl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},eF={CLUSTERING_HUB_PROC_DESCRIPTOR:t_,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_},Ph={HDB:an.join(Zs,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(Zs,"server/customFunctions"),CLUSTERING_HUB:an.join(Zs,"server/nats"),CLUSTERING_LEAF:an.join(Zs,"server/nats")},tF={HDB:an.join(Ph.HDB,mO),CUSTOM_FUNCTIONS:an.join(Ph.CUSTOM_FUNCTIONS,pO)},rF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(Zs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},nF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},SO="support@harperdb.io",sF="customer-success@harperdb.io",TO=1,iF=4141,gO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oF="https://www.harperdb.io/product",aF=`For support, please submit a request at ${gO} or contact ${SO}`,RO=`For license support, please contact ${sF}`,cF="None of the specified records were found.",uF="hash attribute not found",lF=`Your current license only supports ${TO} role. ${RO}`,_F="Your current license only supports 3 connections to a node.",dF="127.0.0.1",fF=1,EF=/^\.$/,hF=/^\.\.$/,mF="U+002E",pF=/\//g,SF="U+002F",TF=/U\+002F/g,gF=/^U\+002E$/,RF=/^U\+002EU\+002E$/,AF="d",OF=999999,bF="*",yF="--max-old-space-size=",NF="system",IF="__hdb_hash",wF=".harperdb",CF=".hdb",DF="keys",LF="hdb_boot_properties.file",MF=".updateConfig.json",PF="SIGTSTP",UF=24,vF=6e4,BF=448,HF="blob",xF="trash",GF="database",qF="schema",FF="transactions",kF=".count",VF="id",$F="PROCESS_NAME",AO={SETTINGS_PATH_KEY:"settings_path"},OO=require("lodash"),YF={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"},KF={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},WF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},QF={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"},zF={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"},Pr="hdb_internal:",JF={CREATE_SCHEMA:Pr+"create_schema",CREATE_TABLE:Pr+"create_table",CREATE_ATTRIBUTE:Pr+"create_attribute",ADD_USER:Pr+"add_user",ALTER_USER:Pr+"alter_user",DROP_USER:Pr+"drop_user",HDB_NODES:Pr+"hdb_nodes",HDB_USERS:Pr+"hdb_users",HDB_WORKERS:Pr+"hdb_workers",CATCHUP:Pr+"catchup",SCHEMA_CATCHUP:Pr+"schema_catchup",WORKER_ROOM:Pr+"cluster_workers"},jF={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"},XF="060493.ks",ZF=".license",ek={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={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"},tk={CSV:".csv",JSON:".json"},rk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},nk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},lc={};lc[ee.INSERT]=ee.INSERT;lc[ee.UPDATE]=ee.UPDATE;lc[ee.UPSERT]=ee.UPSERT;lc[ee.DELETE]=ee.DELETE;var He=Object.create(null);He[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;He[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;He[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;He[ee.READ_LOG]=ee.READ_LOG;He[ee.ADD_NODE]=ee.ADD_NODE;He[ee.LIST_USERS]=ee.LIST_USERS;He[ee.LIST_ROLES]=ee.LIST_ROLES;He[ee.USER_INFO]=ee.USER_INFO;He[ee.SQL]=ee.SQL;He[ee.GET_JOB]=ee.GET_JOB;He[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;He[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;He[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;He[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;He[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;He[ee.REMOVE_NODE]=ee.REMOVE_NODE;He[ee.RESTART]=ee.RESTART;He[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;He[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;He[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;He[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;He[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;He[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;He[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;He[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var sk={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},ik={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},bO={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"},ok=OO.invert(bO),ak={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"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",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:"operationsApi_tls",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_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers",TLS:"tls",CLONED:"cloned"},yO={settings_path:AO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:I.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,customfunctions_tls:I.TLS,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,http_maxheadersize:I.HTTP_MAXHEADERSIZE,http_threadrange:I.HTTP_THREADRANGE,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:I.OPERATIONSAPI_TLS,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,storage_maxtransactionqueuetime:I.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls:I.TLS,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];yO[t.toLowerCase()]=t}var ck={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},uk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.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"},lk={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"},_k={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},dk={VERSION_DEFAULT:"2.2.0"},fk={DEVELOPMENT:8192,DEFAULT:512},Ek={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"},hk={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"},mk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},NO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},pk=Symbol("metadata"),Sk="__clustering__",Tk=Object.values(NO),gk=15984864e5,IO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Rk=OO.invert(IO),Ak={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"},Ok=111,bk=`\r
2
- `,yk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Nk=["*","%"],Ik="unauthorized_access",wk="func_val",Ck={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Dk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Lk={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Mk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Pk={HTTP:"http"},Uk={STOPPED:"stopped",ONLINE:"online"},vk="3.x.x",Bk={SUCCESS:"success",FAILURE:"failure"},Hk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};wO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:SO,HDB_SUPPORT_URL:gO,HDB_PRICING_URL:oF,SUPPORT_HELP_MSG:aF,LICENSE_HELP_MSG:RO,HDB_PROC_NAME:mO,HDB_PROC_DESCRIPTOR:Uh,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_,CLUSTERING_HUB_PROC_DESCRIPTOR:t_,SYSTEM_SCHEMA_NAME:NF,HASH_FOLDER_NAME:IF,HDB_HOME_DIR_NAME:wF,UPDATE_FILE_NAME:MF,LICENSE_KEY_DIR_NAME:DF,BOOT_PROPS_FILE_NAME:LF,JOB_TYPE_ENUM:uk,JOB_STATUS_ENUM:ek,SYSTEM_TABLE_NAMES:QF,SYSTEM_TABLE_HASH_ATTRIBUTES:zF,OPERATIONS_ENUM:ee,VALID_S3_FILE_TYPES:tk,S3_BUCKET_AUTH_KEYS:rk,VALID_SQL_OPS_ENUM:nk,GEO_CONVERSION_ENUM:ik,HDB_SETTINGS_NAMES:bO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:ok,SERVICE_ACTIONS_ENUM:sk,CLUSTER_MESSAGE_TYPE_ENUM:lk,CLUSTER_CONNECTION_DIRECTION_ENUM:_k,CLUSTER_EVENTS_DEFS_ENUM:Ek,PERIOD_REGEX:EF,DOUBLE_PERIOD_REGEX:hF,UNICODE_PERIOD:mF,FORWARD_SLASH_REGEX:pF,UNICODE_FORWARD_SLASH:SF,ESCAPED_FORWARD_SLASH_REGEX:TF,ESCAPED_PERIOD_REGEX:gF,ESCAPED_DOUBLE_PERIOD_REGEX:RF,REG_KEY_FILE_NAME:XF,RESTART_TIMEOUT_MS:vF,HDB_FILE_PERMISSIONS:BF,DATABASES_DIR_NAME:GF,LEGACY_DATABASES_DIR_NAME:qF,TRANSACTIONS_DIR_NAME:FF,LIMIT_COUNT_NAME:kF,ID_ATTRIBUTE_STRING:VF,INSERT_MODULE_ENUM:KF,UPGRADE_JSON_FIELD_NAMES_ENUM:WF,RESTART_CODE:PF,RESTART_CODE_NUM:UF,CLUSTER_OPERATIONS:lc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:jF,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pr,INTERNAL_SC_CHANNELS:JF,CLUSTERING_MESSAGE_TYPES:Ak,HDB_FILE_SUFFIX:CF,BLOB_FOLDER_NAME:HF,HDB_TRASH_DIR:xF,ORIGINATOR_SET_VALUE:Ok,LICENSE_VALUES:dk,RAM_ALLOCATION_ENUM:fk,TIME_STAMP_NAMES_ENUM:NO,TIME_STAMP_NAMES:Tk,PERMS_UPDATE_RELEASE_TIMESTAMP:gk,SEARCH_NOT_FOUND_MESSAGE:cF,SEARCH_ATTRIBUTE_NOT_FOUND:uF,LICENSE_ROLE_DENIED_RESPONSE:lF,LICENSE_MAX_CONNS_REACHED:_F,BASIC_LICENSE_MAX_NON_CU_ROLES:TO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:iF,VALUE_SEARCH_COMPARATORS:IO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Rk,LICENSE_FILE_NAME:ZF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:hk,NEW_LINE:bk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:fF,MOMENT_DAYS_TAG:AF,API_TURNOVER_SEC:OF,LOOPBACK:dF,CODE_EXTENSION:e_,WILDCARD_SEARCH_VALUE:bF,NODE_ERROR_CODES:mk,JAVASCRIPT_EXTENSION:hO,PERMS_CRUD_ENUM:yk,UNAUTHORIZED_PERMISSION_NAME:Ik,SEARCH_WILDCARDS:Nk,FUNC_VAL:wk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Ck,JWT_ENUM:Dk,CLUSTERING_FLAG:Sk,ITC_EVENT_TYPES:Lk,CUSTOM_FUNCTION_PROC_NAME:pO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Zl,SERVICES:Mk,THREAD_TYPES:Pk,MEM_SETTING_KEY:yF,HDB_RESTART_SCRIPT:$q,PROCESS_DESCRIPTORS:Jq,SERVICE_SERVERS:tF,SERVICE_SERVERS_CWD:Ph,PROCESS_DESCRIPTORS_VALIDATE:Zq,LAUNCH_SERVICE_SCRIPTS:rF,LOG_LEVELS:Xq,PROCESS_NAME_ENV_PROP:$F,LOG_NAMES:jq,PM2_PROCESS_STATUSES:Uk,CONFIG_PARAM_MAP:yO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:Fq,HDB_DEFAULT_CONFIG_FILE:kq,ROLE_TYPES_ENUM:nF,BOOT_PROP_PARAMS:AO,INSTALL_PROMPTS:YF,HDB_ROOT_DIR_NAME:Vq,CLUSTERING_PROCESSES:eF,FOREGROUND_PID_FILE:Wq,PACKAGE_ROOT:Zs,PRE_4_0_0_VERSION:vk,DATABASES_PARAM_CONFIG:ck,METADATA_PROPERTY:pk,AUTH_AUDIT_STATUS:Bk,AUTH_AUDIT_TYPES:Hk,HDB_PID_FILE:Qq,DEFAULT_DATABASE_NAME:zq,LEGACY_CONFIG_PARAMS:ak};EO()});var vh=g((rce,LO)=>{"use strict";var CO=require("minimist");LO.exports=xk;function xk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=DO(process.env),n=DO(CO(process.argv))):(r=process.env,n=CO(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(xk,"assignCMDENVVariables");function DO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(DO,"objKeysToLowerCase")});var $=g((sce,kh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Gk,threadId:qk}=require("worker_threads"),ps=require("path"),UO=require("yaml"),vO=require("properties-reader"),Tt=P(),MO=vh(),Fk=require("os"),{PACKAGE_ROOT:Hh}=P(),{_assignPackageExport:kk}=require("../index"),dc={};for(let e in console)dc[e]||(dc[e]=console[e]);var ar={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},BO={STDOUT:"stdOut",STDERR:"stdErr"},Vk=ps.join(Hh,"logs"),$k=ps.join(Hh,"config/yaml/",Tt.HDB_DEFAULT_CONFIG_FILE),Yk=1e4,ms,Kn,or,n_,s_,fc,ko,_c;_c===void 0&&HO();kh.exports={notify:qO,fatal:FO,error:Ec,warn:Fh,info:i_,debug:qh,trace:Gh,setLogLevel:Xk,log_level:or,loggerWithTag:Kk,suppressLogging:Wk,initLogSettings:HO,setupConsoleLogging:xO,logCustomLevel:Jk,closeLogFile:xh,getLogFilePath:()=>fc,OUTPUTS:BO,AuthAuditLog:tV};kk("logger",kh.exports);function HO(e=!1){try{if(_c===void 0||e){xh();let t=jk(),r=MO(["ROOTPATH"]);try{_c=vO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Bi.pathExistsSync(ps.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE)))throw n}({level:or,config_log_path:s_,to_file:ms,to_stream:Kn}=Zk(r.ROOTPATH?ps.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE):_c.get("settings_path"))),n_=Tt.LOG_NAMES.HDB,fc=ps.join(s_,n_)}}catch(t){if(_c=void 0,t.code===Tt.NODE_ERROR_CODES.ENOENT||t.code===Tt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=MO(Object.keys(Tt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Tt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Tt.CONFIG_PARAMS.LOGGING_LEVEL){or=u;continue}if(c===Tt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Kn=u;continue}c===Tt.CONFIG_PARAMS.LOGGING_FILE&&(ms=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=eV();ms=ms===void 0?s:ms,ms=PO(ms),Kn=Kn===void 0?i:Kn,Kn=PO(Kn),or=or===void 0?n:or,s_=Vk,n_=Tt.LOG_NAMES.INSTALL,fc=ps.join(s_,n_);return}throw Ec("Error initializing log settings"),Ec(t),t}process.env.DEV_MODE&&(Kn=!0),xO()}a(HO,"initLogSettings");var Bh=!0;function xO(){Fo("error",Ec),Fo("warn",Fh),Fo("log",i_),Fo("info",i_),Fo("debug",qh),Fo("trace",Gh)}a(xO,"setupConsoleLogging");function Fo(e,t){console[e]=function(...r){if(Bh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return dc[e](...r)}}a(Fo,"logConsole");function Kk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(qO),fatal:r(FO),error:r(Ec),warn:r(Fh),info:r(i_),debug:r(qh),trace:r(Gh)};function r(n){return function(...s){return n(t,...s)}}}a(Kk,"loggerWithTag");function Wk(e){try{Bh=!1,e()}finally{Bh=!0}}a(Wk,"suppressLogging");var Qk=Gk?.name?.replace(/ /g,"-")||"main";function Ss(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||Qk+"/"+qk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
3
- `}a(Ss,"createLogRecord");function hc(e){ms&&GO(e),Kn&&process.stdout.write(e)}a(hc,"logStdOut");function o_(e){ms&&GO(e),Kn&&process.stderr.write(e)}a(o_,"logStdErr");function GO(e){zk(),ko?Bi.appendFileSync(ko,e):dc.log(e)}a(GO,"logToFile");function xh(){try{Bi.closeSync(ko)}catch{}ko=null}a(xh,"closeLogFile");function zk(){if(!ko){try{if(!fc)debugger;ko=Bi.openSync(fc,"a")}catch(e){dc.error(e)}setTimeout(()=>{xh()},Yk).unref()}}a(zk,"openLogFile");function i_(...e){ar[or]<=ar.info&&hc(Ss("info",e))}a(i_,"info");function Gh(...e){ar[or]<=ar.trace&&hc(Ss("trace",e))}a(Gh,"trace");function Ec(...e){ar[or]<=ar.error&&o_(Ss("error",e))}a(Ec,"error");function qh(...e){ar[or]<=ar.debug&&hc(Ss("debug",e))}a(qh,"debug");function qO(...e){ar[or]<=ar.notify&&hc(Ss("notify",e))}a(qO,"notify");function FO(...e){ar[or]<=ar.fatal&&o_(Ss("fatal",e))}a(FO,"fatal");function Fh(...e){ar[or]<=ar.warn&&o_(Ss("warn",e))}a(Fh,"warn");function Jk(e,t,...r){t===BO.STDERR?o_(Ss(e,r)):hc(Ss(e,r))}a(Jk,"logCustomLevel");function jk(){let e;try{e=Fk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ps.join(e,Tt.HDB_HOME_DIR_NAME,Tt.BOOT_PROPS_FILE_NAME);return Bi.existsSync(t)||(t=ps.join(Hh,"utility/hdb_boot_properties.file")),t}a(jk,"getPropsFilePath");function Xk(e){or=e}a(Xk,"setLogLevel");function PO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(PO,"autoCastBoolean");function Zk(e){try{if(e.includes("config/settings.js")){let o=vO(e);return{level:o.get(Tt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ps.dirname(o.get(Tt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UO.parseDocument(Bi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===Tt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Zk,"getLogConfig");function eV(){try{let e=UO.parseDocument(Bi.readFileSync($k,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(eV,"getDefaultConfig");function tV(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(tV,"AuthAuditLog")});var VO=g((oce,kO)=>{"use strict";var rV=require("util"),nV=require("path"),sV=require("child_process"),iV=rV.promisify(sV.execFile),oV=1e3*1e3*10;kO.exports={findPs:aV};async function aV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await iV("ps",["wwxo",`pid,${r}`],{maxBuffer:oV});for(let s of n.trim().split(`
4
- `).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:nV.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(aV,"findPs")});var ft=g((cce,YO)=>{"use strict";var cV="__dbis__",uV="__txns__",lV="__environment_name__",_V="__dbi_defintion__",dV={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"},fV=["__createdtime__","__updatedtime__"],EV="\uFFFF",$O={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hV=Object.values($O);YO.exports={AUDIT_STORE_NAME:uV,INTERNAL_DBIS_NAME:cV,DBI_DEFINITION_NAME:_V,SEARCH_TYPES:dV,TIMESTAMP_NAMES:fV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:lV,TRANSACTIONS_DBI_NAMES_ENUM:$O,TRANSACTIONS_DBIS:hV,OVERFLOW_MARKER:EV}});var Ur=g((uce,eb)=>{"use strict";var KO=P(),WO=ft(),QO={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},zO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),JO={500:zO("There was an error processing your request."),400:"Invalid request"},mV=JO[QO.INTERNAL_SERVER_ERROR],pV={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.`},SV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},TV={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"},gV={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 ${WO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${WO.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"},RV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${KO.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 ${KO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},jO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},AV={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."},OV={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`},bV={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"},yV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},NV={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},XO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},ZO={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}`},IV={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."},wV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},CV={...jO,...TV,...pV,...AV,...OV,...bV,...yV,...NV,...RV,...XO,...ZO,...IV,...wV,...SV};eb.exports={CHECK_LOGS_WRAPPER:zO,HDB_ERROR_MSGS:CV,DEFAULT_ERROR_MSGS:JO,DEFAULT_ERROR_RESP:mV,HTTP_STATUS_CODES:QO,LMDB_ERRORS_ENUM:gV,AUTHENTICATION_ERROR_MSGS:jO,VALIDATION_ERROR_MSGS:XO,ITC_ERRORS:ZO}});var ne=g((_ce,nb)=>{"use strict";var Vo=Ur(),DV=$(),LV=P(),a_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,tb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&DV[s](i)}},Vh=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}},$h=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function tb(e,t,r,n=LV.LOG_LEVELS.ERROR,s=null,i=!1){if(rb(e))return e;let o=new a_(e,t,r,n,s);return i&&delete o.stack,o}a(tb,"handleHDBError");function rb(e){return e.__proto__.constructor.name===a_.name}a(rb,"isHDBError");nb.exports={isHDBError:rb,handleHDBError:tb,ClientError:Vh,ServerError:$h,hdb_errors:Vo}});var Je=g((fce,lb)=>{"use strict";var gc=P(),MV=z(),cr=Z(),Rc=require("path"),PV=require("minimist"),sb=require("fs-extra"),ib=require("lodash");cr.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:mc,SYSTEM_SCHEMA_NAME:c_}=gc,pc,Sc,Tc;function ob(){if(pc!==void 0)return pc;if(cr.getHdbBasePath()!==void 0)return pc=cr.get(ei.STORAGE_PATH)||Rc.join(cr.getHdbBasePath(),gc.DATABASES_DIR_NAME),pc}a(ob,"getBaseSchemaPath");function ab(){if(Sc!==void 0)return Sc;if(cr.getHdbBasePath()!==void 0)return Sc=ub(c_),Sc}a(ab,"getSystemSchemaPath");function cb(){if(Tc!==void 0)return Tc;if(cr.getHdbBasePath()!==void 0)return Tc=cr.get(gc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Rc.join(cr.getHdbBasePath(),gc.TRANSACTIONS_DIR_NAME),Tc}a(cb,"getTransactionAuditStoreBasePath");function UV(e,t){let r=cr.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Rc.join(cb(),e.toString())}a(UV,"getTransactionAuditStorePath");function ub(e,t){e=e.toString(),t=t&&t.toString();let r=cr.get(gc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Rc.join(ob(),e)}a(ub,"getSchemaPath");function vV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,PV(process.argv));let n=r[ei.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!MV.isObject(n))throw o;i=n}for(let o of i){let c=o[c_];if(!c)continue;let u=cr.get(ei.DATABASES);u=u??{};let _=c?.tables?.[t]?.[mc.PATH];if(_)return ib.set(u,[c_,mc.TABLES,t,mc.PATH],_),cr.setProperty(ei.DATABASES,u),_;let l=c?.[mc.PATH];if(l)return ib.set(u,[c_,mc.PATH],l),cr.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!sb.pathExistsSync(s))throw new Error(s+" does not exist");let i=Rc.join(s,e);return sb.mkdirsSync(i),cr.setProperty(ei.STORAGE_PATH,s),i}return ab()}a(vV,"initSystemSchemaPaths");function BV(){pc=void 0,Sc=void 0,Tc=void 0}a(BV,"resetPaths");lb.exports={getBaseSchemaPath:ob,getSystemSchemaPath:ab,getTransactionAuditStorePath:UV,getTransactionAuditStoreBasePath:cb,getSchemaPath:ub,initSystemSchemaPaths:vV,resetPaths:BV}});var vr=g((pce,hb)=>{"use strict";var HV=Ur().LMDB_ERRORS_ENUM,hce=require("lmdb"),xV=ft(),mce=require("buffer").Buffer,{OVERFLOW_MARKER:_b,MAX_SEARCH_KEY_LENGTH:u_}=xV,db=["number","string","symbol","boolean","bigint"];function GV(e){if(e=e?.primaryStore||e,!e)throw new Error(HV.ENV_REQUIRED)}a(GV,"validateEnv");function qV(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(qV,"stringifyData");function FV(e){return e instanceof Date?e.valueOf():e}a(FV,"convertKeyValueToWrite");function kV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(db.includes(typeof e))return e.length>u_?[e.slice(0,u_)+_b]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(db.includes(typeof i))i.length>u_?r.push(i.slice(0,u_)+_b):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(kV,"getIndexedValues");var l_=0,fb=0;function Eb(){fb=Date.now()-performance.now()}a(Eb,"adjustStartTime");Eb();var VV=6e4;setInterval(Eb,VV).unref();function $V(){let e=performance.now()+fb;return e>l_?(l_=e,e):(l_+=488e-6,l_)}a($V,"getNextMonotonicTime");hb.exports={validateEnv:GV,stringifyData:qV,convertKeyValueToWrite:FV,getNextMonotonicTime:$V,getIndexedValues:kV}});var mb,yn,Yh,Ac=Re(()=>{mb=require("events"),yn=class extends mb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Yh;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)}},Yh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Hi={};Fe(Hi,{server:()=>it});var pb,it,ur=Re(()=>{pb=require("../index"),it={};(0,pb._assignPackageExport)("server",it)});var Qh={};Fe(Qh,{loadGQLSchema:()=>WV,start:()=>Wh,startOnMainThread:()=>KV});function Wh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let Q=H(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(H,"getProperty");let T=S.name.value,R=[],b={table:null,database:null,properties:R};E.set(T,b);for(let v of S.directives){if(v.name.value==="table"){for(let F of v.arguments)b[F.name.value]=F.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=T),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,f.push(b)}if(v.name.value==="sealed"&&(b.sealed=!0),v.name.value==="export"){b.export=!0;for(let F of v.arguments)F.name.value==="name"&&(b.export={name:F.value.value})}}let C=!1;for(let v of S.fields){let F=H(v.type);F.name=v.name.value,R.push(F);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(F.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")F.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let J of M.arguments)Q[J.name.value]=J.value.value;F.relationship=Q}else if(M.name.value==="createdTime")F.assignCreatedTime=!0;else if(M.name.value==="updatedTime")F.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")F.expiresAt=!0;else if(M.name.value==="allow"){let Q=F.authorizedRoles=[];for(let J of M.arguments)J.name.value==="role"&&Q.push(J.value.value)}}b.type=T,T==="Query"&&(h=b)}function p(S){let T=E.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):YV.includes(S.type)||(0,Sb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of E.values())for(let T of S.properties)p(T);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Kh.dirname)(n),S.tableClass):i.set((0,Kh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Kh,Sb,YV,KV,WV,Tb=Re(()=>{Kh=require("path");Ae();Sb=B(je()),YV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Wh,"start");KV=Wh,WV=Wh({ensureTable:Et}).handleFile});async function __(e){let t=(0,Ab.pathToFileURL)(e).toString();return QV?(Oc||(Oc=zV(jV)),(await(await Oc).import(t)).namespace):import(t)}async function zV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Oc=new Compartment({console,Math,Date,fetch:JV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Rb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Vt,tables:Br,databases:ot})}};let n=await(0,gb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Oc}function JV(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 jV(){return{Resource:Vt,tables:Br}}var gb,Rb,Ab,QV,Oc,zh=Re(()=>{Nn();Ae();gb=require("fs/promises"),Rb=require("path"),Ab=require("url"),QV=!1;a(__,"secureImport");a(zV,"getCompartment");a(JV,"secureOnlyFetch");a(jV,"getGlobalVars")});var jh={};Fe(jh,{handleFile:()=>XV});async function XV(e,t,r,n){let s=new Map,i=await __(r);c(i.default)&&n.set((0,Jh.dirname)(t),i.default),o(i,(0,Jh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var Jh,Ob=Re(()=>{zh();Jh=require("path");a(XV,"handleFile")});var Zh={};Fe(Zh,{start:()=>ZV});function ZV({resources:e}){e.set("login",Xh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Xh,bb=Re(()=>{Nn();a(ZV,"start");Xh=class extends Vt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var Lb={};Fe(Lb,{parse:()=>tm,streamAsJSON:()=>bc,stringify:()=>xi});function bc(e){return new em({value:e})}function yb(e){return console.error(e),JSON.stringify(e.toString())}function Nb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function xi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Cb)return Db(e);if(t.resolution)return t.resolution.then(()=>xi(e));throw t}}function Db(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=Db(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+xi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function tm(e){return r$.test(e)?e$.parse(e):JSON.parse(e)}var Ib,wb,e$,t$,Cb,em,r$,rm=Re(()=>{Ib=require("stream"),wb=B(require("json-bigint-fixes")),e$=(0,wb.default)({useNativeBigInt:!0}),t$=1e4,Cb={};BigInt.prototype.toJSON=function(){throw Cb};a(bc,"streamAsJSON");em=class extends Ib.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),yb)}catch(s){yield yb(s)}else yield xi(t)}else yield xi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Nb(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>t$?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 Nb(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(yb,"handleError");a(Nb,"when");a(xi,"stringify");a(Db,"jsStringify");r$=/[[,:]\s*-?\d{16,}/;a(tm,"parse")});var $b=g((Pce,Vb)=>{"use strict";var nm=require("recursive-iterator"),n$=require("alasql"),sm=require("clone"),Mb=z(),{handleHDBError:Pb,hdb_errors:s$}=ne(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:vb}=s$,{getDatabases:i$}=(Ae(),ie(ke)),o$=["DISTINCT_ARRAY"],Bb=Symbol("validateTables"),im=Symbol("validateTable"),Mce=Symbol("getAllColumns"),Hb=Symbol("validateAllColumns"),d_=Symbol("findColumn"),xb=Symbol("validateOrderBy"),yc=Symbol("validateSegment"),om=Symbol("validateColumn"),Gb=Symbol("setColumnsForTable"),qb=Symbol("checkColumnsForAsterisk"),Fb=Symbol("validateGroupBy"),kb=Symbol("hasColumns"),am=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Bb](),this[qb](),this[Hb]()}[Bb](){if(this[kb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[im](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[im](t.table)})}}[kb](){let t=!1,r=new nm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[im](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=i$();if(!r[t.databaseid])throw Pb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),vb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Pb(new Error,Ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),vb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=sm(s);i.table=sm(t),this.attributes.push(i)})}[d_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[qb](){let t=new nm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Gb](r.tableid)}[Gb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new n$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Hb](){this[yc](this.statement.columns,!1),this[yc](this.statement.joins,!1),this[yc](this.statement.where,!1),this[Fb](this.statement.group,!1),this[yc](this.statement.order,!0)}[yc](t,r){if(!t)return;let n=new nm(t),s=[];for(let{node:i,path:o}of n)!Mb.isEmpty(i)&&!Mb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[xb](i):s.push(this[om](i)));return s}[Fb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&o$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=sm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[d_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[d_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[xb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[om](t)}[om](t){let r=this[d_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Vb.exports=am});var Kb=g((vce,Yb)=>{"use strict";var cm=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Yb.exports=cm});var Qb=g((Hce,Wb)=>{"use strict";var um=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Wb.exports=um});var Xb={};Fe(Xb,{HAS_EXPIRATION:()=>mm,LAST_TIMESTAMP_PLACEHOLDER:()=>wc,LOCAL_TIMESTAMP:()=>a$,METADATA:()=>Nc,NO_TIMESTAMP:()=>_m,PENDING_LOCAL_TIME:()=>pm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>hm,RecordEncoder:()=>Em,TIMESTAMP_ASSIGN_LAST:()=>u$,TIMESTAMP_ASSIGN_NEW:()=>Jb,TIMESTAMP_ASSIGN_PREVIOUS:()=>jb,TIMESTAMP_PLACEHOLDER:()=>f_,TIMESTAMP_RECORD_PREVIOUS:()=>dm,getUpdateRecord:()=>Sm,handleLocalTimeForGets:()=>p_});function _$(){return Ic[0]=Ic[0]^64,c$.getFloat64(0)}function p_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[Nc];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?.[Nc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Nc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Gi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Gi.length;u++){let _=Gi[u].deref();(!_||_.isDone||_.isCommitted)&&Gi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Sm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?dm|jb:_m:$o=u?i?.localTime?dm|16384:Jb|16384:_m,l>0&&(c|=mm),h_=c,fm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(E_=e.encoder.encode(f)),E&&i?.localTime){let R=i?.localTime,b=r.get(R);if(b){let C=Ut(b).previousLocalTime;return r.put(R,m_(o,t,n,C,T,d,E_),{ifVersion:p}),S}}r.put(wc,m_(o,t,n,i?.localTime?1:0,T,d,E_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var zb,lm,f_,wc,hm,a$,Nc,Ic,c$,_m,Jb,u$,jb,dm,mm,pm,l$,E_,$o,h_,fm,Em,Gi,Cc=Re(()=>{zb=require("msgpackr");ti();lm=B($()),f_=new Uint8Array([1,1,1,1,4,64,0,0]),wc=new Uint8Array([1,1,1,1,1,0,0,0]),hm=new Uint8Array([1,1,1,1,3,64,0,0]),a$=Symbol("local-timestamp"),Nc=Symbol("metadata"),Ic=new Uint8Array(8),c$=new DataView(Ic.buffer,0,8),_m=0,Jb=0,u$=1,jb=3,dm=4,mm=16,pm=1,$o=0,h_=-1,fm=0,Em=class extends zb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||h_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=h_,u=fm;c>=0&&(i+=2,h_=-1,u&&(i+=8,fm=0));let _=l$=r.call(this,n,s|2048|i);E_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(f_[4]=o,f_[5]=o>>8,_.set(f_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(Ic,0,c),c+=8;else for(let d=0;d<8;d++)Ic[d]=t[c++];u=_$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&mm&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[Nc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(_$,"getTimestamp");a(p_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(lm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):lm.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(Sm,"getUpdateRecord")});var Dc=g((kce,ey)=>{"use strict";var Zb=Z(),d$=P(),{RecordEncoder:f$}=(Cc(),ie(Xb)),Fce=require("fs");Zb.initSync();var E$=Zb.get(d$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Tm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=E$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:f$})}};ey.exports=Tm});var Lc=g(($ce,ty)=>{"use strict";var Hr=Z(),cn=P();Hr.initSync();var S_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Hr.get(cn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ty.exports=S_;S_.MAX_DBS=1e4});var We=g((Kce,_y)=>{"use strict";var Rm=require("lmdb"),In=require("fs-extra"),xr=require("path"),T_=vr(),sy=$(),lr=Ur().LMDB_ERRORS_ENUM,g_=Qb(),Am=Dc(),iy=Lc(),ri=ft(),ry=P(),{table:h$,resetDatabases:m$}=(Ae(),ie(ke)),ny=Z(),wn=ri.INTERNAL_DBIS_NAME,oy=ri.DBI_DEFINITION_NAME,p$="data.mdb",S$="lock.mdb",Mc=".mdb",T$="-lock",gm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=un(t,r),this.key_type=this.dbi[ri.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ri.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!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 R_(e,t){if(e===void 0)throw new Error(lr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(lr.ENV_NAME_REQUIRED)}a(R_,"pathEnvNameValidation");async function Om(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(lr.INVALID_BASE_PATH):n}try{let n=xr.join(e,t+Mc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(xr.join(e,t,p$),In.constants.R_OK|In.constants.F_OK),xr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(lr.INVALID_ENVIRONMENT)}else throw new Error(lr.INVALID_ENVIRONMENT);throw n}}a(Om,"validateEnvironmentPath");function A_(e,t){if(T_.validateEnv(e),t===void 0)throw new Error(lr.DBI_NAME_REQUIRED)}a(A_,"validateEnvDBIName");async function g$(e,t,r=!1,n=!1){R_(e,t);let s=xr.basename(e);t=t.toString();let i=ny.get(ry.CONFIG_PARAMS.DATABASES);i||ny.setProperty(ry.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Om(e,t,n),ay(e,t,r)}catch(o){if(o.message===lr.INVALID_ENVIRONMENT){let c=xr.join(e,t);await In.mkdirp(n?c:e);let u=new iy(n?c:c+Mc,!1),_=Rm.open(u);_.dbis=Object.create(null);let l=new Am(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=bm(e,t,r);return _[ri.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(g$,"createEnvironment");async function R$(e,t,r,n=!0){R_(e,t),t=t.toString();let s=xr.join(e,t);return h$({table:t,database:xr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(R$,"copyEnvironment");async function ay(e,t,r=!1){R_(e,t),t=t.toString();let n=bm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await Om(e,t),i=xr.join(e,t+Mc),o=s!=i,c=new iy(s,o),u=Rm.open(c);u.dbis=Object.create(null);let _=uy(u);for(let l=0;l<_.length;l++)un(u,_[l]);return u[ri.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(ay,"openEnvironment");async function A$(e,t,r=!1){R_(e,t),t=t.toString();let n=xr.join(e,t+Mc),s=await Om(e,t);if(global.lmdb_map!==void 0){let i=bm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await cy(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+T$:xr.join(xr.dirname(s),S$))}a(A$,"deleteEnvironment");async function cy(e){T_.validateEnv(e);let t=e[ri.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(cy,"closeEnvironment");function bm(e,t,r=!1){let s=`${xr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(bm,"getCachedEnvironmentName");function O$(e){T_.validateEnv(e);let t=Object.create(null),r=un(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new g_,s)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(O$,"listDBIDefinitions");function uy(e){T_.validateEnv(e);let t=[],r=un(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(uy,"listDBIs");function b$(e,t){let n=un(e,wn).getEntry(t),s=new g_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(b$,"getDBIDefinition");function ly(e,t,r,n=!r){if(A_(e,t),t=t.toString(),t===wn)throw new Error(lr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return un(e,t)}catch(s){if(s.message===lr.DBI_DOES_NOT_EXIST){let i=new Am(r,n===!0),o=e.openDB(t,i),c=new g_(r===!0,n);return o[oy]=c,un(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(ly,"createDBI");function un(e,t){if(A_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=b$(e,t):r=new g_,r===void 0)throw new Error(lr.DBI_DOES_NOT_EXIST);let n;try{let s=new Am(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(lr.DBI_DOES_NOT_EXIST):s}return n[oy]=r,e.dbis[t]=n,n}a(un,"openDBI");function y$(e,t){A_(e,t),t=t.toString();let r=un(e,t),n=r.getStats();return r[ri.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(y$,"statDBI");async function N$(e,t){try{let r=xr.join(e,t+Mc);return(await In.stat(r)).size}catch{throw new Error(lr.INVALID_ENVIRONMENT)}}a(N$,"environmentDataSize");function I$(e,t){if(A_(e,t),t=t.toString(),t===wn)throw new Error(lr.CANNOT_DROP_INTERNAL_DBIS_NAME);un(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],un(e,wn).removeSync(t)}a(I$,"dropDBI");function w$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{un(e,i)}catch(o){if(o.message===lr.DBI_DOES_NOT_EXIST)ly(e,i,i!==t,i===t),n=!0;else throw o}}n&&m$()}a(w$,"initializeDBIs");_y.exports={openDBI:un,openEnvironment:ay,createEnvironment:g$,listDBIs:uy,listDBIDefinitions:O$,createDBI:ly,dropDBI:I$,statDBI:y$,deleteEnvironment:A$,initializeDBIs:w$,TransactionCursor:gm,environmentDataSize:N$,copyEnvironment:R$,closeEnvironment:cy}});var fy=g((Qce,dy)=>{"use strict";var ym=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};dy.exports=ym});var hy=g((Jce,Ey)=>{"use strict";var Nm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Ey.exports=Nm});var py=g((Xce,my)=>{"use strict";var Im=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};my.exports=Im});var Yo=g((nue,gy)=>{"use strict";var C$=We(),D$=fy(),L$=hy(),M$=py(),Wn=vr(),Pc=Ur().LMDB_ERRORS_ENUM,P$=ft(),Ts=P(),U$=z(),v$=require("uuid"),eue=require("lmdb"),{handleHDBError:B$,hdb_errors:H$}=ne(),{OVERFLOW_MARKER:tue,MAX_SEARCH_KEY_LENGTH:rue}=P$,Sy=Z();Sy.initSync();var O_=Sy.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),wm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function x$(e,t,r,n,s=Wn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new D$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ty(_,!0,s);let l=G$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Dm(o,c,n,i,s)}a(x$,"insertRecords");function G$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){O_&&_.prefetch(u.map(l=>({key:l,value:s})),b_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}O_&&e.dbis[t].prefetch([s],b_),e.dbis[t].put(s,n,n[qi])})}a(G$,"insertRecord");function q$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(q$,"removeSkippedRecords");function Ty(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[wm]))&&(e[wm]=r||Wn.getNextMonotonicTime()):delete e[wm]}a(Ty,"setTimestamps");function Cm(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),C$.initializeDBIs(e,t,r)}a(Cm,"initializeTransaction");async function F$(e,t,r,n,s=Wn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new L$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Lm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Dm(c,u,n,i,s,o)}a(F$,"updateRecords");async function k$(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Mm(e,t,r,n)}catch(u){throw B$(u,u.message,H$.HTTP_STATUS_CODES.BAD_REQUEST)}Cm(e,t,r);let i=new M$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;U$.isEmpty(_[t])?(l=v$.v4(),_[t]=l):l=_[t];let d=Lm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Dm(o,c,n,i,s)}a(k$,"upsertRecords");async function Dm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Wn.getNextMonotonicTime(),q$(r,i),n}a(Dm,"finalizeWrite");function Lm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Ty(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&s.original_records.push(_);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let R=Wn.getIndexedValues(T);if(R){O_&&S.prefetch(R.map(b=>({key:b,value:n})),b_);for(let b=0,C=R.length;b<C;b++)S.remove(R[b],n)}if(R=Wn.getIndexedValues(p),R){O_&&S.prefetch(R.map(b=>({key:b,value:n})),b_);for(let b=0,C=R.length;b<C;b++)S.put(R[b],n)}}let f=Object.assign({},_,r);c.put(n,f,f[qi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Lm(e,t,r,n,s,i,o))}a(Lm,"updateUpsertRecord");function V$(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Pc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Pc.WRITE_ATTRIBUTES_REQUIRED):new Error(Pc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(V$,"validateBasic");function Mm(e,t,r,n){if(V$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Pc.RECORDS_REQUIRED):new Error(Pc.RECORDS_MUST_BE_ARRAY)}a(Mm,"validateWrite");function b_(){}a(b_,"noop");gy.exports={insertRecords:x$,updateRecords:F$,upsertRecords:k$}});var Fi=g((iue,$$)=>{$$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var zn=g((oue,Oy)=>{"use strict";var Ay=z(),Ry=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ni={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},Y$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number(),Qn.array()).required(),K$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()),W$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()).required();function Q$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ni.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(Q$,"checkValidTable");function z$(e,t){return Ay.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(z$,"validateSchemaExists");function J$(e,t){let r=t.state.ancestors[0].schema;return Ay.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(J$,"validateTableExists");function j$(e,t){return e.toLowerCase()===Ry.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Ry.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(j$,"validateSchemaName");Oy.exports={common_validators:ni,schema_regex:Ko,hdb_schema_table:Y$,validateSchemaExists:z$,validateTableExists:J$,validateSchemaName:j$,checkValidTable:Q$,hdb_database:K$,hdb_table:W$}});var Xe=g((cue,by)=>{"use strict";var _r=require("validate.js");_r.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||_r.validators.type.checks[t](e)?null:` must be a '${t}' value`};_r.validators.type.checks={Object:function(e){return _r.isObject(e)&&!_r.isArray(e)},Array:_r.isArray,Integer:_r.isInteger,Number:_r.isNumber,String:_r.isString,Date:_r.isDate,Boolean:function(e){return typeof e=="boolean"}};_r.validators.hasValidFileExt=function(e,t){return _r.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};by.exports={validateObject:X$,validateObjectAsync:Z$,validateBySchema:e1};function X$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=_r(e,t,{format:"flat"});return r?new Error(r):null}a(X$,"validateObject");async function Z$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await _r.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Z$,"validateObjectAsync");function e1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(e1,"validateBySchema")});var y_=g((lue,yy)=>{var{common_validators:Jn}=zn(),vc=Xe(),Uc="is required",gt={database:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},schema:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},table:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},hash_attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length}};function 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 t1(e){return e=Bc(e),gt.table.presence=!1,gt.attribute.presence=!1,gt.hash_attribute.presence=!1,vc.validateObject(e,gt)}a(t1,"schema_object");function r1(e){return e=Bc(e),gt.table.presence={message:Uc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,vc.validateObject(e,gt)}a(r1,"table_object");function n1(e){return e=Bc(e),gt.table.presence={message:Uc},gt.attribute.presence=!1,vc.validateObject(e,gt)}a(n1,"create_table_object");function s1(e){return e=Bc(e),gt.table.presence={message:Uc},gt.attribute.presence={message:Uc},gt.hash_attribute.presence=!1,vc.validateObject(e,gt)}a(s1,"attribute_object");function i1(e){return e=Bc(e),gt.table.presence={message:Uc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,vc.validateObject(e,gt)}a(i1,"describe_table");function o1(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(o1,"validateTableResidence");yy.exports={schema_object:t1,create_table_object:n1,table_object:r1,attribute_object:s1,describe_table:i1,validateTableResidence:o1}});var Iy=g((due,Ny)=>{"use strict";var a1=require("uuid"),Pm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||a1.v4(),this.schema_table=`${this.schema}.${this.table}`}};Ny.exports=Pm});var N_=g((Eue,wy)=>{"use strict";var c1=Iy(),Um=class extends c1{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};wy.exports=Um});var Dy=g((mue,Cy)=>{"use strict";Cy.exports=l1;var u1="inserted";function l1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===u1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(l1,"returnObject")});var I_=g((Sue,vy)=>{"use strict";var _1=P(),vm=We(),d1=Yo(),{getSystemSchemaPath:f1,getSchemaPath:E1}=Je(),h1=Fi(),m1=y_(),p1=N_(),S1=Dy(),{handleHDBError:Ly,hdb_errors:Py}=ne(),My=z(),{HTTP_STATUS_CODES:T1}=Py,Bm=h1.hdb_attribute,Uy=[];for(let e=0;e<Bm.attributes.length;e++)Uy.push(Bm.attributes[e].attribute);var g1="inserted";vy.exports=R1;async function R1(e){let t=m1.attribute_object(e);if(t)throw Ly(new Error,t.message,Py.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&My.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Ly(new Error,r,T1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=My.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new p1(e.schema,e.table,e.attribute,e.id);try{let i=await vm.openEnvironment(E1(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}`);vm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await vm.openEnvironment(f1(),_1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await d1.insertRecords(o,Bm.hash_attribute,Uy,[s]);return S1(g1,c,{records:[s]},u)}catch(i){throw i}}a(R1,"lmdbCreateAttribute")});var xm=g((gue,Hy)=>{var{hdb_table:A1,hdb_database:By}=zn(),O1=Xe(),Hm=require("joi"),b1={undefined:"undefined",null:"null"},y1=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||b1[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),N1=Hm.object({database:By,schema:By,table:A1,records:Hm.array().items(Hm.object().custom(y1)).required()});Hy.exports=function(e){return O1.validateBySchema(e,N1)}});var Hc=g((Oue,Gy)=>{"use strict";var gs=z(),xy=$(),Aue=xm(),{getDatabases:I1}=(Ae(),ie(ke)),{ClientError:ki}=ne();Gy.exports=w1;function w1(e){if(gs.isEmpty(e))throw new ki("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=I1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new ki(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gs.isEmptyOrZeroLength(o[r]))throw xy.error("a valid hash attribute must be provided with update record:",o),new ki("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw xy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new ki(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(w1,"insertUpdateValidate")});var xc=g((yue,qy)=>{"use strict";var C1=P().OPERATIONS_ENUM,Gm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=C1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};qy.exports=Gm});var Gc=g((wue,ky)=>{"use strict";var Iue=xc(),w_=P(),qm=z(),Fy=$(),D1=require("uuid"),{handleHDBError:C_,hdb_errors:L1}=ne(),{HDB_ERROR_MSGS:D_,HTTP_STATUS_CODES:L_}=L1;ky.exports=M1;function M1(e,t,r){for(let s=0;s<t.length;s++)P1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];U1(i,r,e.operation)}}a(M1,"processRows");function P1(e){if(Buffer.byteLength(String(e))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw C_(new Error,D_.ATTR_NAME_LENGTH_ERR(e),L_.BAD_REQUEST,void 0,void 0,!0);if(qm.isEmptyOrZeroLength(e)||qm.isEmpty(e.trim()))throw C_(new Error,D_.ATTR_NAME_NULLISH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(P1,"validateAttribute");function U1(e,t,r){if(!e.hasOwnProperty(t)||qm.isEmptyOrZeroLength(e[t])){if(r===w_.OPERATIONS_ENUM.INSERT||r===w_.OPERATIONS_ENUM.UPSERT){e[t]=D1.v4();return}throw Fy.error("Update transaction aborted due to record with no hash value:",e),C_(new Error,D_.RECORD_MISSING_HASH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Fy.error(e),C_(new Error,D_.HASH_VAL_LENGTH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(U1,"validateHash")});var $y=g((Due,Vy)=>{"use strict";var Fm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Vy.exports=Fm});var Wy=g((Mue,Ky)=>{"use strict";var km=We(),v1=$(),Yy=Ur().LMDB_ERRORS_ENUM;Ky.exports=B1;async function B1(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 km.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Yy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await km.closeEnvironment(global.lmdb_map[n]),await km.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Yy.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){v1.error(t)}}a(B1,"cleanLMDBMap")});var Rs=g((Uue,jy)=>{"use strict";var qc=require("crypto"),H1=Z(),{CONFIG_PARAMS:x1}=P(),zy="aes-256-cbc",G1=32,q1=16,Vm=64,Jy=32,F1=Vm+Jy,Qy=new Map;jy.exports={encrypt:k1,decrypt:V1,createNatsTableStreamName:$1};function k1(e){let t=qc.randomBytes(G1),r=qc.randomBytes(q1),n=qc.createCipheriv(zy,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(k1,"encrypt");function V1(e){let t=e.substr(0,Vm),r=e.substr(Vm,Jy),n=e.substr(F1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=qc.createDecipheriv(zy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(V1,"decrypt");function $1(e,t){let r=H1.get(x1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Qy.get(r);return n||(n=qc.createHash("md5").update(r).digest("hex"),Qy.set(r,n)),n}a($1,"createNatsTableStreamName")});var As=g((Hue,Zy)=>{"use strict";var Bue=Gr(),M_=$(),Xy=y_(),Y1=Rs(),P_=z(),{handleHDBError:U_,hdb_errors:K1}=ne(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:$m}=K1,W1=Z();W1.initSync();var{getDatabases:Ym}=(Ae(),ie(ke));Zy.exports={describeAll:Q1,describeTable:B_,describeSchema:z1};async function Q1(e){try{let t=P_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Ym(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let E in d)try{let f;if(t||n)f=await B_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await B_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){M_.error(f)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return M_.error("Got an error in describeAll"),M_.error(t),U_(new Error,v_.DESCRIBE_ALL_ERR)}}a(Q1,"describeAll");async function B_(e,t){P_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=Xy.describe_table(e);if(i)throw i;let c=Ym()[r];if(!c)throw U_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let u=c[n];if(!u)throw U_(new Error,v_.TABLE_NOT_FOUND(e.schema,e.table),$m.NOT_FOUND);function _(E){l.push(Object.assign({},{attribute:E.attribute,type:E.type,elements:E.elements?.type,indexed:E.indexed,is_primary_key:E.isPrimaryKey,assigned_created_time:E.assignCreatedTime,assigned_updated_time:E.assignUpdatedTime,nullable:E.nullable,properties:E.properties?E.properties.map(f=>({type:f.type,name:f.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let E={};s.forEach(f=>{f.describe&&(E[f.attribute_name]=!0)}),u.attributes.forEach(f=>{E[f.name]&&_(f)})}else u.attributes?.forEach(E=>_(E));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(E=>E.isPrimaryKey||E.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=Y1.createNatsTableStreamName(d.schema,d.name);try{let E=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=E.recordCount,d.estimated_record_range=E.estimatedRange;let f=u.auditStore;if(f)for(let h of f.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(E){M_.warn(`unable to stat table dbi due to ${E}`)}return d}a(B_,"descTable");async function z1(e){P_.transformReq(e);let t=Xy.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Ym()[n];if(!i)throw U_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),P_.isEmpty(u)||u.describe){let _=await B_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(z1,"describeSchema")});var Os=g((Fue,sN)=>{var J1=Fi(),{callbackify:tN,promisify:j1}=require("util"),{getDatabases:rN}=(Ae(),ie(ke));sN.exports={setSchemaDataToGlobal:eN,getTableSchema:X1,getSystemSchema:Z1,setSchemaDataToGlobalAsync:j1(eN)};var nN=As(),Gue=tN(nN.describeAll),que=tN(nN.describeTable);function eN(e){global.hdb_schema=rN(),e&&e()}a(eN,"setSchemaDataToGlobal");function X1(e,t,r){let n=rN()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(X1,"getTableSchema");function Z1(){return J1}a(Z1,"getSystemSchema")});var qr=g((Vue,cN)=>{"use strict";var x_=xm(),$t=z(),eY=require("util"),G_=Cn(),tY=Os(),iN=$(),{handleHDBError:Vi,hdb_errors:rY}=ne(),{HTTP_STATUS_CODES:$i}=rY,nY=eY.promisify(tY.getTableSchema),sY="updated",oN="inserted",aN="upserted";cN.exports={insert:oY,update:aY,upsert:cY,validation:iY,flush:uY};async function iY(e){if($t.isEmpty(e))throw new Error("invalid update parameters defined.");if($t.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if($t.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await nY(e.schema,e.table),r=x_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&$t.isEmptyOrZeroLength(c[n]))throw iN.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(!$t.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw iN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!$t.isEmpty(c[n])&&c[n]!==""&&s.has($t.autoCast(c[n]))&&(c.skip=!0),s.add($t.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(iY,"validation");async function oY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.createRecords(e);return H_(oN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(oY,"insertData");async function aY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.updateRecords(e);return $t.isEmpty(n.existing_rows)?H_(sY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):H_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(aY,"updateData");async function cY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.upsertRecords(e);return H_(aN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(cY,"upsertData");function H_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===oN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===aN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(H_,"returnObject");function uY(e){return $t.transformReq(e),G_.flush(e.schema,e.table)}a(uY,"flush")});var Wm=g((Yue,_N)=>{var lY=Xe(),Km=require("joi"),{hdb_table:_Y,hdb_database:uN}=zn(),lN={schema:uN,database:uN,table:_Y},dY={date:Km.date().iso().required()},fY={timestamp:Km.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};_N.exports=function(e,t){let r=t==="timestamp"?{...lN,...fY}:{...lN,...dY},n=Km.object(r);return lY.validateBySchema(e,n)}});var EN=g((Kue,fN)=>{var EY=Xe(),Qm=require("joi"),{hdb_table:hY,hdb_database:dN}=zn(),mY=Qm.object({schema:dN,database:dN,table:hY,hash_values:Qm.array().required(),ids:Qm.array()});fN.exports=function(e){return EY.validateBySchema(e,mY)}});var mN=g((Wue,hN)=>{"use strict";var zm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Jm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},jm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};hN.exports={InsertObject:zm,NoSQLSeachObject:Jm,DeleteResponseObject:jm}});var oi=g((zue,RN)=>{"use strict";var SN=Wm(),pY=EN(),Yi=z(),pN=require("moment"),TN=$(),{promisify:SY,callbackify:TY}=require("util"),Ki=P(),gY=Os(),Xm=SY(gY.getTableSchema),Zm=Cn(),{DeleteResponseObject:RY}=mN(),{handleHDBError:si,hdb_errors:AY}=ne(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:ii}=AY,OY="records successfully deleted",bY=TY(gN);RN.exports={delete:bY,deleteRecord:gN,deleteFilesBefore:yY,deleteAuditLogsBefore:NY};async function yY(e){let t=SN(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!pN(e.date,pN.ISO_8601).isValid())throw si(new Error,q_.INVALID_DATE,ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_DATE,!0);let n=Yi.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,n,!0);let s=await Zm.deleteRecordsBefore(e);if(await Xm(e.schema,e.table),TN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(yY,"deleteFilesBefore");async function NY(e){let t=SN(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw si(new Error,q_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let n=await Zm.deleteAuditLogsBefore(e);return await Xm(e.schema,e.table),TN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(NY,"deleteAuditLogsBefore");async function gN(e){e.ids&&(e.hash_values=e.ids);let t=pY(e);if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Xm(e.schema,e.table);let n=await Zm.deleteRecords(e);return Yi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${OY}`),n}catch(n){if(n.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let s=new RY;return s.message=Ki.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(gN,"deleteRecord")});var F_=g((jue,bN)=>{var IY=require("crypto"),AN=9;function wY(e){let t=DY(AN),r=ON(e+t);return t+r}a(wY,"createHash");function CY(e,t){let r=e?.substr(0,AN),n=r+ON(t+r);return e===n}a(CY,"validateHash");function DY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(DY,"generateSalt");function ON(e){return IY.createHash("md5").update(e).digest("hex")}a(ON,"md5");bN.exports={hash:wY,validate:CY}});var NN=g((Zue,yN)=>{var ep=Xe(),jt={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 LY(e){return jt.password.presence=!0,jt.username.presence=!0,jt.role.presence=!0,jt.active.presence=!0,ep.validateObject(e,jt)}a(LY,"addUserValidation");function MY(e){return jt.password.presence=!1,jt.username.presence=!0,jt.role.presence=!1,jt.active.presence=!1,ep.validateObject(e,jt)}a(MY,"alterUserValidation");function PY(e){return jt.password.presence=!1,jt.username.presence=!0,jt.role.presence=!1,jt.active.presence=!1,ep.validateObject(e,jt)}a(PY,"dropUserValidation");yN.exports={addUserValidation:LY,alterUserValidation:MY,dropUserValidation:PY}});var Ve=g((rle,wN)=>{"use strict";var{platform:tle}=require("os"),UY="nats-server.zip",tp="nats-server",vY=process.platform==="win32"?`${tp}.exe`:tp,BY=/^[^\s.,*>]+$/,IN="__request__",HY=a(e=>`${e}.${IN}`,"REQUEST_SUBJECT"),xY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},GY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},qY={HUB:"hub.pid",LEAF:"leaf.pid"},FY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},kY={SUCCESS:"success",ERROR:"error"},VY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},$Y={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},YY={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},KY={debug:"-D",trace:"-DVV"};wN.exports={NATS_SERVER_ZIP:UY,NATS_SERVER_NAME:tp,NATS_BINARY_NAME:vY,PID_FILES:qY,NATS_CONFIG_FILES:GY,SERVER_SUFFIX:FY,NATS_TERM_CONSTRAINTS_RX:BY,REQUEST_SUFFIX:IN,UPDATE_REMOTE_RESPONSE_STATUSES:kY,CLUSTER_STATUS_STATUSES:VY,REQUEST_SUBJECT:HY,SUBJECT_PREFIXES:$Y,MSG_HEADERS:xY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:KY,LOG_LEVEL_HIERARCHY:YY}});var DN=g((sle,CN)=>{"use strict";var WY={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 Dq=Object.create;var _c=Object.defineProperty;var Lq=Object.getOwnPropertyDescriptor;var Mq=Object.getOwnPropertyNames;var Pq=Object.getPrototypeOf,Uq=Object.prototype.hasOwnProperty;var a=(e,t)=>_c(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)_c(e,r,{get:t[r],enumerable:!0})},fO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Mq(t))!Uq.call(e,s)&&s!==r&&_c(e,s,{get:()=>t[s],enumerable:!(n=Lq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Dq(Pq(e)):{},fO(t||!e||!e.__esModule?_c(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>fO(_c({},"__esModule",{value:!0}),e);var mO=g((oce,hO)=>{var vq=require("fast-glob"),{statSync:Lh,existsSync:Mh,readFileSync:Bq,writeFileSync:Hq}=require("fs"),{spawnSync:xq,spawn:Gq,execFileSync:ice}=require("child_process"),{isMainThread:qq}=require("worker_threads"),{join:Zs,relative:EO}=require("path"),{PACKAGE_ROOT:bn}=P(),{tmpdir:Fq,platform:kq}=require("os");require("source-map-support").install();var Vq=["resources","server","dataLayer","components"],dc="ts-build",Ph,$q=__filename.endsWith("tsBuild.js");if($q){if(qq){let r;try{Lh(Zs(bn,dc)),r=!0}catch{}if(r)for(let n of vq.sync(Vq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=Lh(Zs(bn,n)).mtimeMs-5e3,i=Lh(Zs(bn,dc,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Ph=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Ph=!0;if(Ph){let n=Zs(bn,"node_modules/.bin/tsc");kq()==="win32"&&(n+=".cmd");let s=xq(n,{cwd:bn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Zs(Fq(),"harperdb-tsc.pid"),o;if(Mh(i))try{process.kill(+Bq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Gq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});Hq(i,c.pid.toString()),c.unref()}}}}let e=hO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=EO(bn,n[0]),o;i.startsWith(dc)?o=Zs(bn,EO(dc,i)):o=Zs(bn,dc,i);let c=Zs(o,r),u=c+".js";if(Mh(u))return u;if(c.includes(".")&&Mh(c))return c}return t(r,n,s)}}});var P=g((uce,DO)=>{"use strict";var an=require("path"),Yq=require("fs"),{relative:ace,join:cce}=an,{existsSync:Kq}=Yq;function Wq(){let e=__dirname;for(;!Kq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Wq,"getHDBPackageRoot");var ei=Wq(),pO="js",i_=pO,Qq="harperdb-config.yaml",zq="defaultConfig.yaml",Jq="hdb",SO=`harperdb.${i_}`,TO=`customFunctionsServer.${i_}`,jq=`restartHdb.${i_}`,vh="HarperDB",s_="Custom Functions",o_="Clustering Hub",a_="Clustering Leaf",Xq="Clustering Ingest Service",Zq="Clustering Reply Service",eF="foreground.pid",tF="hdb.pid",rF="data",nF={HDB:vh,CLUSTERING_HUB:o_,CLUSTERING_LEAF:a_,CLUSTERING_INGEST_SERVICE:Xq,CLUSTERING_REPLY_SERVICE:Zq,CUSTOM_FUNCTIONS:s_,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},sF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},iF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},oF={harperdb:vh,"clustering hub":o_,"clustering leaf":a_,"custom functions":s_,custom_functions:s_,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},aF={CLUSTERING_HUB_PROC_DESCRIPTOR:o_,CLUSTERING_LEAF_PROC_DESCRIPTOR:a_},Uh={HDB:an.join(ei,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(ei,"server/customFunctions"),CLUSTERING_HUB:an.join(ei,"server/nats"),CLUSTERING_LEAF:an.join(ei,"server/nats")},cF={HDB:an.join(Uh.HDB,SO),CUSTOM_FUNCTIONS:an.join(Uh.CUSTOM_FUNCTIONS,TO)},uF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(ei,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(ei,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(ei,"launchServiceScripts/launchUpdateNodes4-0-0.js")},lF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},gO="support@harperdb.io",_F="customer-success@harperdb.io",RO=1,dF=4141,AO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",fF="https://www.harperdb.io/product",EF=`For support, please submit a request at ${AO} or contact ${gO}`,OO=`For license support, please contact ${_F}`,hF="None of the specified records were found.",mF="hash attribute not found",pF=`Your current license only supports ${RO} role. ${OO}`,SF="Your current license only supports 3 connections to a node.",TF="127.0.0.1",gF=1,RF=/^\.$/,AF=/^\.\.$/,OF="U+002E",bF=/\//g,yF="U+002F",NF=/U\+002F/g,IF=/^U\+002E$/,wF=/^U\+002EU\+002E$/,CF="d",DF=999999,LF="*",MF="--max-old-space-size=",PF="system",UF="__hdb_hash",vF=".harperdb",BF=".hdb",HF="keys",xF="hdb_boot_properties.file",GF=".updateConfig.json",qF="SIGTSTP",FF=24,kF=6e4,VF=448,$F="blob",YF="trash",KF="database",WF="schema",QF="transactions",zF=".count",JF="id",jF="PROCESS_NAME",bO={SETTINGS_PATH_KEY:"settings_path"},yO=require("lodash"),XF={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},ZF={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},ek={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},tk={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"},rk={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"},Pr="hdb_internal:",nk={CREATE_SCHEMA:Pr+"create_schema",CREATE_TABLE:Pr+"create_table",CREATE_ATTRIBUTE:Pr+"create_attribute",ADD_USER:Pr+"add_user",ALTER_USER:Pr+"alter_user",DROP_USER:Pr+"drop_user",HDB_NODES:Pr+"hdb_nodes",HDB_USERS:Pr+"hdb_users",HDB_WORKERS:Pr+"hdb_workers",CATCHUP:Pr+"catchup",SCHEMA_CATCHUP:Pr+"schema_catchup",WORKER_ROOM:Pr+"cluster_workers"},sk={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"},ik="060493.ks",ok=".license",ak={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={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"},ck={CSV:".csv",JSON:".json"},uk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},lk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},fc={};fc[ee.INSERT]=ee.INSERT;fc[ee.UPDATE]=ee.UPDATE;fc[ee.UPSERT]=ee.UPSERT;fc[ee.DELETE]=ee.DELETE;var He=Object.create(null);He[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;He[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;He[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;He[ee.READ_LOG]=ee.READ_LOG;He[ee.ADD_NODE]=ee.ADD_NODE;He[ee.LIST_USERS]=ee.LIST_USERS;He[ee.LIST_ROLES]=ee.LIST_ROLES;He[ee.USER_INFO]=ee.USER_INFO;He[ee.SQL]=ee.SQL;He[ee.GET_JOB]=ee.GET_JOB;He[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;He[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;He[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;He[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;He[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;He[ee.REMOVE_NODE]=ee.REMOVE_NODE;He[ee.RESTART]=ee.RESTART;He[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;He[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;He[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;He[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;He[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;He[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;He[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;He[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var _k={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},dk={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},NO={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"},fk=yO.invert(NO),Ek={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",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:"operationsApi_tls",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_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers",TLS:"tls",CLONED:"cloned"},IO={settings_path:bO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:I.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,customfunctions_tls:I.TLS,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,http_maxheadersize:I.HTTP_MAXHEADERSIZE,http_threadrange:I.HTTP_THREADRANGE,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:I.OPERATIONSAPI_TLS,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,storage_maxtransactionqueuetime:I.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls:I.TLS,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];IO[t.toLowerCase()]=t}var hk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},mk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.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",restart_service:"restart_service"},pk={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"},Sk={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Tk={VERSION_DEFAULT:"2.2.0"},gk={DEVELOPMENT:8192,DEFAULT:512},Rk={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"},Ak={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"},Ok={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},wO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},bk=Symbol("metadata"),yk="__clustering__",Nk=Object.values(wO),Ik=15984864e5,CO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},wk=yO.invert(CO),Ck={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"},Dk=111,Lk=`\r
2
+ `,Mk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Pk=["*","%"],Uk="unauthorized_access",vk="func_val",Bk={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Hk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},xk={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",START_JOB:"start_job",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Gk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},qk={HTTP:"http"},Fk={STOPPED:"stopped",ONLINE:"online"},kk="3.x.x",Vk={SUCCESS:"success",FAILURE:"failure"},$k={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};DO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:gO,HDB_SUPPORT_URL:AO,HDB_PRICING_URL:fF,SUPPORT_HELP_MSG:EF,LICENSE_HELP_MSG:OO,HDB_PROC_NAME:SO,HDB_PROC_DESCRIPTOR:vh,CLUSTERING_LEAF_PROC_DESCRIPTOR:a_,CLUSTERING_HUB_PROC_DESCRIPTOR:o_,SYSTEM_SCHEMA_NAME:PF,HASH_FOLDER_NAME:UF,HDB_HOME_DIR_NAME:vF,UPDATE_FILE_NAME:GF,LICENSE_KEY_DIR_NAME:HF,BOOT_PROPS_FILE_NAME:xF,JOB_TYPE_ENUM:mk,JOB_STATUS_ENUM:ak,SYSTEM_TABLE_NAMES:tk,SYSTEM_TABLE_HASH_ATTRIBUTES:rk,OPERATIONS_ENUM:ee,VALID_S3_FILE_TYPES:ck,S3_BUCKET_AUTH_KEYS:uk,VALID_SQL_OPS_ENUM:lk,GEO_CONVERSION_ENUM:dk,HDB_SETTINGS_NAMES:NO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:fk,SERVICE_ACTIONS_ENUM:_k,CLUSTER_MESSAGE_TYPE_ENUM:pk,CLUSTER_CONNECTION_DIRECTION_ENUM:Sk,CLUSTER_EVENTS_DEFS_ENUM:Rk,PERIOD_REGEX:RF,DOUBLE_PERIOD_REGEX:AF,UNICODE_PERIOD:OF,FORWARD_SLASH_REGEX:bF,UNICODE_FORWARD_SLASH:yF,ESCAPED_FORWARD_SLASH_REGEX:NF,ESCAPED_PERIOD_REGEX:IF,ESCAPED_DOUBLE_PERIOD_REGEX:wF,REG_KEY_FILE_NAME:ik,RESTART_TIMEOUT_MS:kF,HDB_FILE_PERMISSIONS:VF,DATABASES_DIR_NAME:KF,LEGACY_DATABASES_DIR_NAME:WF,TRANSACTIONS_DIR_NAME:QF,LIMIT_COUNT_NAME:zF,ID_ATTRIBUTE_STRING:JF,INSERT_MODULE_ENUM:ZF,UPGRADE_JSON_FIELD_NAMES_ENUM:ek,RESTART_CODE:qF,RESTART_CODE_NUM:FF,CLUSTER_OPERATIONS:fc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:sk,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pr,INTERNAL_SC_CHANNELS:nk,CLUSTERING_MESSAGE_TYPES:Ck,HDB_FILE_SUFFIX:BF,BLOB_FOLDER_NAME:$F,HDB_TRASH_DIR:YF,ORIGINATOR_SET_VALUE:Dk,LICENSE_VALUES:Tk,RAM_ALLOCATION_ENUM:gk,TIME_STAMP_NAMES_ENUM:wO,TIME_STAMP_NAMES:Nk,PERMS_UPDATE_RELEASE_TIMESTAMP:Ik,SEARCH_NOT_FOUND_MESSAGE:hF,SEARCH_ATTRIBUTE_NOT_FOUND:mF,LICENSE_ROLE_DENIED_RESPONSE:pF,LICENSE_MAX_CONNS_REACHED:SF,BASIC_LICENSE_MAX_NON_CU_ROLES:RO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:dF,VALUE_SEARCH_COMPARATORS:CO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:wk,LICENSE_FILE_NAME:ok,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Ak,NEW_LINE:Lk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:gF,MOMENT_DAYS_TAG:CF,API_TURNOVER_SEC:DF,LOOPBACK:TF,CODE_EXTENSION:i_,WILDCARD_SEARCH_VALUE:LF,NODE_ERROR_CODES:Ok,JAVASCRIPT_EXTENSION:pO,PERMS_CRUD_ENUM:Mk,UNAUTHORIZED_PERMISSION_NAME:Uk,SEARCH_WILDCARDS:Pk,FUNC_VAL:vk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Bk,JWT_ENUM:Hk,CLUSTERING_FLAG:yk,ITC_EVENT_TYPES:xk,CUSTOM_FUNCTION_PROC_NAME:TO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:s_,SERVICES:Gk,THREAD_TYPES:qk,MEM_SETTING_KEY:MF,HDB_RESTART_SCRIPT:jq,PROCESS_DESCRIPTORS:nF,SERVICE_SERVERS:cF,SERVICE_SERVERS_CWD:Uh,PROCESS_DESCRIPTORS_VALIDATE:oF,LAUNCH_SERVICE_SCRIPTS:uF,LOG_LEVELS:iF,PROCESS_NAME_ENV_PROP:jF,LOG_NAMES:sF,PM2_PROCESS_STATUSES:Fk,CONFIG_PARAM_MAP:IO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:Qq,HDB_DEFAULT_CONFIG_FILE:zq,ROLE_TYPES_ENUM:lF,BOOT_PROP_PARAMS:bO,INSTALL_PROMPTS:XF,HDB_ROOT_DIR_NAME:Jq,CLUSTERING_PROCESSES:aF,FOREGROUND_PID_FILE:eF,PACKAGE_ROOT:ei,PRE_4_0_0_VERSION:kk,DATABASES_PARAM_CONFIG:hk,METADATA_PROPERTY:bk,AUTH_AUDIT_STATUS:Vk,AUTH_AUDIT_TYPES:$k,HDB_PID_FILE:tF,DEFAULT_DATABASE_NAME:rF,LEGACY_CONFIG_PARAMS:Ek};mO()});var Bh=g((_ce,PO)=>{"use strict";var LO=require("minimist");PO.exports=Yk;function Yk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=MO(process.env),n=MO(LO(process.argv))):(r=process.env,n=LO(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(Yk,"assignCMDENVVariables");function MO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(MO,"objKeysToLowerCase")});var $=g((fce,Vh)=>{"use strict";var Hi=require("fs-extra"),{workerData:Kk,threadId:Wk}=require("worker_threads"),Ss=require("path"),BO=require("yaml"),HO=require("properties-reader"),Tt=P(),UO=Bh(),Qk=require("os"),{PACKAGE_ROOT:xh}=P(),{_assignPackageExport:zk}=require("../index"),hc={};for(let e in console)hc[e]||(hc[e]=console[e]);var cr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},xO={STDOUT:"stdOut",STDERR:"stdErr"},Jk=Ss.join(xh,"logs"),jk=Ss.join(xh,"config/yaml/",Tt.HDB_DEFAULT_CONFIG_FILE),Xk=1e4,ps,Wn,ar,c_,u_,mc,ko,Ec;Ec===void 0&&GO();Vh.exports={notify:kO,fatal:VO,error:pc,warn:kh,info:l_,debug:Fh,trace:qh,setLogLevel:iV,log_level:ar,loggerWithTag:Zk,suppressLogging:eV,initLogSettings:GO,setupConsoleLogging:qO,logCustomLevel:nV,closeLogFile:Gh,getLogFilePath:()=>mc,OUTPUTS:xO,AuthAuditLog:cV};zk("logger",Vh.exports);function GO(e=!1){try{if(Ec===void 0||e){Gh();let t=sV(),r=UO(["ROOTPATH"]);try{Ec=HO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Hi.pathExistsSync(Ss.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE)))throw n}({level:ar,config_log_path:u_,to_file:ps,to_stream:Wn}=oV(r.ROOTPATH?Ss.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE):Ec.get("settings_path"))),c_=Tt.LOG_NAMES.HDB,mc=Ss.join(u_,c_)}}catch(t){if(Ec=void 0,t.code===Tt.NODE_ERROR_CODES.ENOENT||t.code===Tt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=UO(Object.keys(Tt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Tt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Tt.CONFIG_PARAMS.LOGGING_LEVEL){ar=u;continue}if(c===Tt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Wn=u;continue}c===Tt.CONFIG_PARAMS.LOGGING_FILE&&(ps=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=aV();ps=ps===void 0?s:ps,ps=vO(ps),Wn=Wn===void 0?i:Wn,Wn=vO(Wn),ar=ar===void 0?n:ar,u_=Jk,c_=Tt.LOG_NAMES.INSTALL,mc=Ss.join(u_,c_);return}throw pc("Error initializing log settings"),pc(t),t}process.env.DEV_MODE&&(Wn=!0),qO()}a(GO,"initLogSettings");var Hh=!0;function qO(){Fo("error",pc),Fo("warn",kh),Fo("log",l_),Fo("info",l_),Fo("debug",Fh),Fo("trace",qh)}a(qO,"setupConsoleLogging");function Fo(e,t){console[e]=function(...r){if(Hh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return hc[e](...r)}}a(Fo,"logConsole");function Zk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(kO),fatal:r(VO),error:r(pc),warn:r(kh),info:r(l_),debug:r(Fh),trace:r(qh)};function r(n){return function(...s){return n(t,...s)}}}a(Zk,"loggerWithTag");function eV(e){try{Hh=!1,e()}finally{Hh=!0}}a(eV,"suppressLogging");var tV=Kk?.name?.replace(/ /g,"-")||"main";function Ts(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||tV+"/"+Wk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
3
+ `}a(Ts,"createLogRecord");function Sc(e){ps&&FO(e),Wn&&process.stdout.write(e)}a(Sc,"logStdOut");function __(e){ps&&FO(e),Wn&&process.stderr.write(e)}a(__,"logStdErr");function FO(e){rV(),ko?Hi.appendFileSync(ko,e):hc.log(e)}a(FO,"logToFile");function Gh(){try{Hi.closeSync(ko)}catch{}ko=null}a(Gh,"closeLogFile");function rV(){if(!ko){try{if(!mc)debugger;ko=Hi.openSync(mc,"a")}catch(e){hc.error(e)}setTimeout(()=>{Gh()},Xk).unref()}}a(rV,"openLogFile");function l_(...e){cr[ar]<=cr.info&&Sc(Ts("info",e))}a(l_,"info");function qh(...e){cr[ar]<=cr.trace&&Sc(Ts("trace",e))}a(qh,"trace");function pc(...e){cr[ar]<=cr.error&&__(Ts("error",e))}a(pc,"error");function Fh(...e){cr[ar]<=cr.debug&&Sc(Ts("debug",e))}a(Fh,"debug");function kO(...e){cr[ar]<=cr.notify&&Sc(Ts("notify",e))}a(kO,"notify");function VO(...e){cr[ar]<=cr.fatal&&__(Ts("fatal",e))}a(VO,"fatal");function kh(...e){cr[ar]<=cr.warn&&__(Ts("warn",e))}a(kh,"warn");function nV(e,t,...r){t===xO.STDERR?__(Ts(e,r)):Sc(Ts(e,r))}a(nV,"logCustomLevel");function sV(){let e;try{e=Qk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Ss.join(e,Tt.HDB_HOME_DIR_NAME,Tt.BOOT_PROPS_FILE_NAME);return Hi.existsSync(t)||(t=Ss.join(xh,"utility/hdb_boot_properties.file")),t}a(sV,"getPropsFilePath");function iV(e){ar=e}a(iV,"setLogLevel");function vO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(vO,"autoCastBoolean");function oV(e){try{if(e.includes("config/settings.js")){let o=HO(e);return{level:o.get(Tt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Ss.dirname(o.get(Tt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=BO.parseDocument(Hi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===Tt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(oV,"getLogConfig");function aV(){try{let e=BO.parseDocument(Hi.readFileSync(jk,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(aV,"getDefaultConfig");function cV(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(cV,"AuthAuditLog")});var YO=g((hce,$O)=>{"use strict";var uV=require("util"),lV=require("path"),_V=require("child_process"),dV=uV.promisify(_V.execFile),fV=1e3*1e3*10;$O.exports={findPs:EV};async function EV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await dV("ps",["wwxo",`pid,${r}`],{maxBuffer:fV});for(let s of n.trim().split(`
4
+ `).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:lV.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(EV,"findPs")});var ft=g((pce,WO)=>{"use strict";var hV="__dbis__",mV="__txns__",pV="__environment_name__",SV="__dbi_defintion__",TV={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"},gV=["__createdtime__","__updatedtime__"],RV="\uFFFF",KO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},AV=Object.values(KO);WO.exports={AUDIT_STORE_NAME:mV,INTERNAL_DBIS_NAME:hV,DBI_DEFINITION_NAME:SV,SEARCH_TYPES:TV,TIMESTAMP_NAMES:gV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:pV,TRANSACTIONS_DBI_NAMES_ENUM:KO,TRANSACTIONS_DBIS:AV,OVERFLOW_MARKER:RV}});var Ur=g((Sce,rb)=>{"use strict";var QO=P(),zO=ft(),JO={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},jO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),XO={500:jO("There was an error processing your request."),400:"Invalid request"},OV=XO[JO.INTERNAL_SERVER_ERROR],bV={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.`},yV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},NV={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"},IV={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 ${zO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${zO.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"},wV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${QO.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 ${QO.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"},ZO={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"},CV={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."},DV={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`},LV={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"},MV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},PV={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`},eb={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.`},tb={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}`},UV={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."},vV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},BV={...ZO,...NV,...bV,...CV,...DV,...LV,...MV,...PV,...wV,...eb,...tb,...UV,...vV,...yV};rb.exports={CHECK_LOGS_WRAPPER:jO,HDB_ERROR_MSGS:BV,DEFAULT_ERROR_MSGS:XO,DEFAULT_ERROR_RESP:OV,HTTP_STATUS_CODES:JO,LMDB_ERRORS_ENUM:IV,AUTHENTICATION_ERROR_MSGS:ZO,VALIDATION_ERROR_MSGS:eb,ITC_ERRORS:tb}});var ne=g((gce,ib)=>{"use strict";var Vo=Ur(),HV=$(),xV=P(),d_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,nb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&HV[s](i)}},$h=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}},Yh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function nb(e,t,r,n=xV.LOG_LEVELS.ERROR,s=null,i=!1){if(sb(e))return e;let o=new d_(e,t,r,n,s);return i&&delete o.stack,o}a(nb,"handleHDBError");function sb(e){return e.__proto__.constructor.name===d_.name}a(sb,"isHDBError");ib.exports={isHDBError:sb,handleHDBError:nb,ClientError:$h,ServerError:Yh,hdb_errors:Vo}});var je=g((Ace,db)=>{"use strict";var Oc=P(),GV=z(),ur=Z(),bc=require("path"),qV=require("minimist"),ob=require("fs-extra"),ab=require("lodash");ur.initSync();var{CONFIG_PARAMS:ti,DATABASES_PARAM_CONFIG:Tc,SYSTEM_SCHEMA_NAME:f_}=Oc,gc,Rc,Ac;function cb(){if(gc!==void 0)return gc;if(ur.getHdbBasePath()!==void 0)return gc=ur.get(ti.STORAGE_PATH)||bc.join(ur.getHdbBasePath(),Oc.DATABASES_DIR_NAME),gc}a(cb,"getBaseSchemaPath");function ub(){if(Rc!==void 0)return Rc;if(ur.getHdbBasePath()!==void 0)return Rc=_b(f_),Rc}a(ub,"getSystemSchemaPath");function lb(){if(Ac!==void 0)return Ac;if(ur.getHdbBasePath()!==void 0)return Ac=ur.get(Oc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||bc.join(ur.getHdbBasePath(),Oc.TRANSACTIONS_DIR_NAME),Ac}a(lb,"getTransactionAuditStoreBasePath");function FV(e,t){let r=ur.get(ti.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||bc.join(lb(),e.toString())}a(FV,"getTransactionAuditStorePath");function _b(e,t){e=e.toString(),t=t&&t.toString();let r=ur.get(Oc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||bc.join(cb(),e)}a(_b,"getSchemaPath");function kV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,qV(process.argv));let n=r[ti.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!GV.isObject(n))throw o;i=n}for(let o of i){let c=o[f_];if(!c)continue;let u=ur.get(ti.DATABASES);u=u??{};let _=c?.tables?.[t]?.[Tc.PATH];if(_)return ab.set(u,[f_,Tc.TABLES,t,Tc.PATH],_),ur.setProperty(ti.DATABASES,u),_;let l=c?.[Tc.PATH];if(l)return ab.set(u,[f_,Tc.PATH],l),ur.setProperty(ti.DATABASES,u),l}}let s=r[ti.STORAGE_PATH.toUpperCase()];if(s){if(!ob.pathExistsSync(s))throw new Error(s+" does not exist");let i=bc.join(s,e);return ob.mkdirsSync(i),ur.setProperty(ti.STORAGE_PATH,s),i}return ub()}a(kV,"initSystemSchemaPaths");function VV(){gc=void 0,Rc=void 0,Ac=void 0}a(VV,"resetPaths");db.exports={getBaseSchemaPath:cb,getSystemSchemaPath:ub,getTransactionAuditStorePath:FV,getTransactionAuditStoreBasePath:lb,getSchemaPath:_b,initSystemSchemaPaths:kV,resetPaths:VV}});var vr=g((Nce,pb)=>{"use strict";var $V=Ur().LMDB_ERRORS_ENUM,bce=require("lmdb"),YV=ft(),yce=require("buffer").Buffer,{OVERFLOW_MARKER:fb,MAX_SEARCH_KEY_LENGTH:E_}=YV,Eb=["number","string","symbol","boolean","bigint"];function KV(e){if(e=e?.primaryStore||e,!e)throw new Error($V.ENV_REQUIRED)}a(KV,"validateEnv");function WV(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(WV,"stringifyData");function QV(e){return e instanceof Date?e.valueOf():e}a(QV,"convertKeyValueToWrite");function zV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(Eb.includes(typeof e))return e.length>E_?[e.slice(0,E_)+fb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(Eb.includes(typeof i))i.length>E_?r.push(i.slice(0,E_)+fb):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(zV,"getIndexedValues");var h_=0,hb=0;function mb(){hb=Date.now()-performance.now()}a(mb,"adjustStartTime");mb();var JV=6e4;setInterval(mb,JV).unref();function jV(){let e=performance.now()+hb;return e>h_?(h_=e,e):(h_+=488e-6,h_)}a(jV,"getNextMonotonicTime");pb.exports={validateEnv:KV,stringifyData:WV,convertKeyValueToWrite:QV,getNextMonotonicTime:jV,getIndexedValues:zV}});var Sb,yn,Kh,yc=Re(()=>{Sb=require("events"),yn=class extends Sb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Kh;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)}},Kh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var xi={};Fe(xi,{server:()=>at});var Tb,at,lr=Re(()=>{Tb=require("../index"),at={};(0,Tb._assignPackageExport)("server",at)});var zh={};Fe(zh,{loadGQLSchema:()=>e$,start:()=>Qh,startOnMainThread:()=>ZV});function Qh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let Q=H(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(H,"getProperty");let T=S.name.value,R=[],b={table:null,database:null,properties:R};E.set(T,b);for(let v of S.directives){if(v.name.value==="table"){for(let F of v.arguments)b[F.name.value]=F.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=T),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,f.push(b)}if(v.name.value==="sealed"&&(b.sealed=!0),v.name.value==="export"){b.export=!0;for(let F of v.arguments)F.name.value==="name"&&(b.export={name:F.value.value})}}let C=!1;for(let v of S.fields){let F=H(v.type);F.name=v.name.value,R.push(F);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(F.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")F.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let J of M.arguments)Q[J.name.value]=J.value.value;F.relationship=Q}else if(M.name.value==="createdTime")F.assignCreatedTime=!0;else if(M.name.value==="updatedTime")F.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")F.expiresAt=!0;else if(M.name.value==="allow"){let Q=F.authorizedRoles=[];for(let J of M.arguments)J.name.value==="role"&&Q.push(J.value.value)}}b.type=T,T==="Query"&&(h=b)}function p(S){let T=E.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):XV.includes(S.type)||(0,gb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of E.values())for(let T of S.properties)p(T);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Wh.dirname)(n),S.tableClass):i.set((0,Wh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Wh,gb,XV,ZV,e$,Rb=Re(()=>{Wh=require("path");Ae();gb=B(We()),XV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Qh,"start");ZV=Qh,e$=Qh({ensureTable:Et}).handleFile});async function m_(e){let t=(0,bb.pathToFileURL)(e).toString();return t$?(Nc||(Nc=r$(s$)),(await(await Nc).import(t)).namespace):import(t)}async function r$(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Nc=new Compartment({console,Math,Date,fetch:n$,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Ob.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:$t,tables:Br,databases:ct})}};let n=await(0,Ab.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Nc}function n$(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 s$(){return{Resource:$t,tables:Br}}var Ab,Ob,bb,t$,Nc,Jh=Re(()=>{Nn();Ae();Ab=require("fs/promises"),Ob=require("path"),bb=require("url"),t$=!1;a(m_,"secureImport");a(r$,"getCompartment");a(n$,"secureOnlyFetch");a(s$,"getGlobalVars")});var Xh={};Fe(Xh,{handleFile:()=>i$});async function i$(e,t,r,n){let s=new Map,i=await m_(r);c(i.default)&&n.set((0,jh.dirname)(t),i.default),o(i,(0,jh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var jh,yb=Re(()=>{Jh();jh=require("path");a(i$,"handleFile")});var em={};Fe(em,{start:()=>o$});function o$({resources:e}){e.set("login",Zh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Zh,Nb=Re(()=>{Nn();a(o$,"start");Zh=class extends $t{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var Pb={};Fe(Pb,{parse:()=>rm,streamAsJSON:()=>Ic,stringify:()=>Gi});function Ic(e){return new tm({value:e})}function Ib(e){return console.error(e),JSON.stringify(e.toString())}function wb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Gi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Lb)return Mb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Mb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=Mb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Gi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function rm(e){return u$.test(e)?a$.parse(e):JSON.parse(e)}var Cb,Db,a$,c$,Lb,tm,u$,nm=Re(()=>{Cb=require("stream"),Db=B(require("json-bigint-fixes")),a$=(0,Db.default)({useNativeBigInt:!0}),c$=1e4,Lb={};BigInt.prototype.toJSON=function(){throw Lb};a(Ic,"streamAsJSON");tm=class extends Cb.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),Ib)}catch(s){yield Ib(s)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);wb(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>c$?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 wb(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(Ib,"handleError");a(wb,"when");a(Gi,"stringify");a(Mb,"jsStringify");u$=/[[,:]\s*-?\d{16,}/;a(rm,"parse")});var Kb=g((kce,Yb)=>{"use strict";var sm=require("recursive-iterator"),l$=require("alasql"),im=require("clone"),Ub=z(),{handleHDBError:vb,hdb_errors:_$}=ne(),{HDB_ERROR_MSGS:Bb,HTTP_STATUS_CODES:Hb}=_$,{getDatabases:d$}=(Ae(),ie(ke)),f$=["DISTINCT_ARRAY"],xb=Symbol("validateTables"),om=Symbol("validateTable"),Fce=Symbol("getAllColumns"),Gb=Symbol("validateAllColumns"),p_=Symbol("findColumn"),qb=Symbol("validateOrderBy"),wc=Symbol("validateSegment"),am=Symbol("validateColumn"),Fb=Symbol("setColumnsForTable"),kb=Symbol("checkColumnsForAsterisk"),Vb=Symbol("validateGroupBy"),$b=Symbol("hasColumns"),cm=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[xb](),this[kb](),this[Gb]()}[xb](){if(this[$b]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[om](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[om](t.table)})}}[$b](){let t=!1,r=new sm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[om](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=d$();if(!r[t.databaseid])throw vb(new Error,Bb.SCHEMA_NOT_FOUND(t.databaseid),Hb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw vb(new Error,Bb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Hb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=im(s);i.table=im(t),this.attributes.push(i)})}[p_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[kb](){let t=new sm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Fb](r.tableid)}[Fb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new l$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Gb](){this[wc](this.statement.columns,!1),this[wc](this.statement.joins,!1),this[wc](this.statement.where,!1),this[Vb](this.statement.group,!1),this[wc](this.statement.order,!0)}[wc](t,r){if(!t)return;let n=new sm(t),s=[];for(let{node:i,path:o}of n)!Ub.isEmpty(i)&&!Ub.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[qb](i):s.push(this[am](i)));return s}[Vb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&f$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=im(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[p_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[p_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[qb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[am](t)}[am](t){let r=this[p_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Yb.exports=cm});var Qb=g(($ce,Wb)=>{"use strict";var um=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Wb.exports=um});var Jb=g((Kce,zb)=>{"use strict";var lm=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};zb.exports=lm});var ey={};Fe(ey,{HAS_EXPIRATION:()=>pm,LAST_TIMESTAMP_PLACEHOLDER:()=>Lc,LOCAL_TIMESTAMP:()=>E$,METADATA:()=>Cc,NO_TIMESTAMP:()=>dm,PENDING_LOCAL_TIME:()=>Sm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>mm,RecordEncoder:()=>hm,TIMESTAMP_ASSIGN_LAST:()=>m$,TIMESTAMP_ASSIGN_NEW:()=>Xb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Zb,TIMESTAMP_PLACEHOLDER:()=>S_,TIMESTAMP_RECORD_PREVIOUS:()=>fm,getUpdateRecord:()=>Tm,handleLocalTimeForGets:()=>A_});function S$(){return Dc[0]=Dc[0]^64,h$.getFloat64(0)}function A_(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?.[Cc];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?.[Cc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Cc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,qi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<qi.length;u++){let _=qi[u].deref();(!_||_.isDone||_.isCommitted)&&qi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Tm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?fm|Zb:dm:$o=u?i?.localTime?fm|16384:Xb|16384:dm,l>0&&(c|=pm),g_=c,Em=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(T_=e.encoder.encode(f)),E&&i?.localTime){let R=i?.localTime,b=r.get(R);if(b){let C=vt(b).previousLocalTime;return r.put(R,R_(o,t,n,C,T,d,T_),{ifVersion:p}),S}}r.put(Lc,R_(o,t,n,i?.localTime?1:0,T,d,T_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var jb,_m,S_,Lc,mm,E$,Cc,Dc,h$,dm,Xb,m$,Zb,fm,pm,Sm,p$,T_,$o,g_,Em,hm,qi,Mc=Re(()=>{jb=require("msgpackr");ri();_m=B($()),S_=new Uint8Array([1,1,1,1,4,64,0,0]),Lc=new Uint8Array([1,1,1,1,1,0,0,0]),mm=new Uint8Array([1,1,1,1,3,64,0,0]),E$=Symbol("local-timestamp"),Cc=Symbol("metadata"),Dc=new Uint8Array(8),h$=new DataView(Dc.buffer,0,8),dm=0,Xb=0,m$=1,Zb=3,fm=4,pm=16,Sm=1,$o=0,g_=-1,Em=0,hm=class extends jb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||g_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=g_,u=Em;c>=0&&(i+=2,g_=-1,u&&(i+=8,Em=0));let _=p$=r.call(this,n,s|2048|i);T_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(S_[4]=o,S_[5]=o>>8,_.set(S_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(Dc,0,c),c+=8;else for(let d=0;d<8;d++)Dc[d]=t[c++];u=S$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&pm&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[Cc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(S$,"getTimestamp");a(A_,"handleLocalTimeForGets");qi=[];setInterval(()=>{for(let e=0;e<qi.length;e++){let t=qi[e].deref();!t||t.isDone||t.isCommitted?qi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(_m.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):_m.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(Tm,"getUpdateRecord")});var Pc=g((jce,ry)=>{"use strict";var ty=Z(),T$=P(),{RecordEncoder:g$}=(Mc(),ie(ey)),Jce=require("fs");ty.initSync();var R$=ty.get(T$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,gm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=R$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:g$})}};ry.exports=gm});var Uc=g((Zce,ny)=>{"use strict";var Hr=Z(),cn=P();Hr.initSync();var O_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Hr.get(cn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ny.exports=O_;O_.MAX_DBS=1e4});var Qe=g((tue,fy)=>{"use strict";var Am=require("lmdb"),In=require("fs-extra"),xr=require("path"),b_=vr(),oy=$(),_r=Ur().LMDB_ERRORS_ENUM,y_=Jb(),Om=Pc(),ay=Uc(),ni=ft(),sy=P(),{table:A$,resetDatabases:O$}=(Ae(),ie(ke)),iy=Z(),wn=ni.INTERNAL_DBIS_NAME,cy=ni.DBI_DEFINITION_NAME,b$="data.mdb",y$="lock.mdb",vc=".mdb",N$="-lock",Rm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=un(t,r),this.key_type=this.dbi[ni.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ni.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Am.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function N_(e,t){if(e===void 0)throw new Error(_r.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(_r.ENV_NAME_REQUIRED)}a(N_,"pathEnvNameValidation");async function bm(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(_r.INVALID_BASE_PATH):n}try{let n=xr.join(e,t+vc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(xr.join(e,t,b$),In.constants.R_OK|In.constants.F_OK),xr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(_r.INVALID_ENVIRONMENT)}else throw new Error(_r.INVALID_ENVIRONMENT);throw n}}a(bm,"validateEnvironmentPath");function I_(e,t){if(b_.validateEnv(e),t===void 0)throw new Error(_r.DBI_NAME_REQUIRED)}a(I_,"validateEnvDBIName");async function I$(e,t,r=!1,n=!1){N_(e,t);let s=xr.basename(e);t=t.toString();let i=iy.get(sy.CONFIG_PARAMS.DATABASES);i||iy.setProperty(sy.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await bm(e,t,n),uy(e,t,r)}catch(o){if(o.message===_r.INVALID_ENVIRONMENT){let c=xr.join(e,t);await In.mkdirp(n?c:e);let u=new ay(n?c:c+vc,!1),_=Am.open(u);_.dbis=Object.create(null);let l=new Om(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=ym(e,t,r);return _[ni.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(I$,"createEnvironment");async function w$(e,t,r,n=!0){N_(e,t),t=t.toString();let s=xr.join(e,t);return A$({table:t,database:xr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(w$,"copyEnvironment");async function uy(e,t,r=!1){N_(e,t),t=t.toString();let n=ym(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await bm(e,t),i=xr.join(e,t+vc),o=s!=i,c=new ay(s,o),u=Am.open(c);u.dbis=Object.create(null);let _=_y(u);for(let l=0;l<_.length;l++)un(u,_[l]);return u[ni.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(uy,"openEnvironment");async function C$(e,t,r=!1){N_(e,t),t=t.toString();let n=xr.join(e,t+vc),s=await bm(e,t);if(global.lmdb_map!==void 0){let i=ym(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await ly(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+N$:xr.join(xr.dirname(s),y$))}a(C$,"deleteEnvironment");async function ly(e){b_.validateEnv(e);let t=e[ni.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(ly,"closeEnvironment");function ym(e,t,r=!1){let s=`${xr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(ym,"getCachedEnvironmentName");function D$(e){b_.validateEnv(e);let t=Object.create(null),r=un(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new y_,s)}catch{oy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(D$,"listDBIDefinitions");function _y(e){b_.validateEnv(e);let t=[],r=un(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(_y,"listDBIs");function L$(e,t){let n=un(e,wn).getEntry(t),s=new y_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{oy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(L$,"getDBIDefinition");function dy(e,t,r,n=!r){if(I_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return un(e,t)}catch(s){if(s.message===_r.DBI_DOES_NOT_EXIST){let i=new Om(r,n===!0),o=e.openDB(t,i),c=new y_(r===!0,n);return o[cy]=c,un(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(dy,"createDBI");function un(e,t){if(I_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=L$(e,t):r=new y_,r===void 0)throw new Error(_r.DBI_DOES_NOT_EXIST);let n;try{let s=new Om(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(_r.DBI_DOES_NOT_EXIST):s}return n[cy]=r,e.dbis[t]=n,n}a(un,"openDBI");function M$(e,t){I_(e,t),t=t.toString();let r=un(e,t),n=r.getStats();return r[ni.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(M$,"statDBI");async function P$(e,t){try{let r=xr.join(e,t+vc);return(await In.stat(r)).size}catch{throw new Error(_r.INVALID_ENVIRONMENT)}}a(P$,"environmentDataSize");function U$(e,t){if(I_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_DROP_INTERNAL_DBIS_NAME);un(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],un(e,wn).removeSync(t)}a(U$,"dropDBI");function v$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{un(e,i)}catch(o){if(o.message===_r.DBI_DOES_NOT_EXIST)dy(e,i,i!==t,i===t),n=!0;else throw o}}n&&O$()}a(v$,"initializeDBIs");fy.exports={openDBI:un,openEnvironment:uy,createEnvironment:I$,listDBIs:_y,listDBIDefinitions:D$,createDBI:dy,dropDBI:U$,statDBI:M$,deleteEnvironment:C$,initializeDBIs:v$,TransactionCursor:Rm,environmentDataSize:P$,copyEnvironment:w$,closeEnvironment:ly}});var hy=g((nue,Ey)=>{"use strict";var Nm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Ey.exports=Nm});var py=g((iue,my)=>{"use strict";var Im=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};my.exports=Im});var Ty=g((aue,Sy)=>{"use strict";var wm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Sy.exports=wm});var Yo=g((due,Ay)=>{"use strict";var B$=Qe(),H$=hy(),x$=py(),G$=Ty(),Qn=vr(),Bc=Ur().LMDB_ERRORS_ENUM,q$=ft(),gs=P(),F$=z(),k$=require("uuid"),uue=require("lmdb"),{handleHDBError:V$,hdb_errors:$$}=ne(),{OVERFLOW_MARKER:lue,MAX_SEARCH_KEY_LENGTH:_ue}=q$,gy=Z();gy.initSync();var w_=gy.get(gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Cm=gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Fi=gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function Y$(e,t,r,n,s=Qn.getNextMonotonicTime()){Pm(e,t,r,n),Dm(e,t,r);let i=new H$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ry(_,!0,s);let l=K$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Lm(o,c,n,i,s)}a(Y$,"insertRecords");function K$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][gs.FUNC_VAL],n[o]=c)}let u=Qn.getIndexedValues(c),_=e.dbis[o];if(u){w_&&_.prefetch(u.map(l=>({key:l,value:s})),C_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}w_&&e.dbis[t].prefetch([s],C_),e.dbis[t].put(s,n,n[Fi])})}a(K$,"insertRecord");function W$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(W$,"removeSkippedRecords");function Ry(e,t,r){let n=r>0;(n||!Number.isInteger(e[Fi]))&&(e[Fi]=r||(r=Qn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[Cm]))&&(e[Cm]=r||Qn.getNextMonotonicTime()):delete e[Cm]}a(Ry,"setTimestamps");function Dm(e,t,r){r.indexOf(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),B$.initializeDBIs(e,t,r)}a(Dm,"initializeTransaction");async function Q$(e,t,r,n,s=Qn.getNextMonotonicTime()){Pm(e,t,r,n),Dm(e,t,r);let i=new x$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Mm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Lm(c,u,n,i,s,o)}a(Q$,"updateRecords");async function z$(e,t,r,n,s=Qn.getNextMonotonicTime()){try{Pm(e,t,r,n)}catch(u){throw V$(u,u.message,$$.HTTP_STATUS_CODES.BAD_REQUEST)}Dm(e,t,r);let i=new G$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;F$.isEmpty(_[t])?(l=k$.v4(),_[t]=l):l=_[t];let d=Mm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Lm(o,c,n,i,s)}a(z$,"upsertRecords");async function Lm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Qn.getNextMonotonicTime(),W$(r,i),n}a(Lm,"finalizeWrite");function Mm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Ry(r,!l,o),Number.isInteger(r[Fi])&&_[Fi]>r[Fi])return!1;l&&s.original_records.push(_);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][gs.FUNC_VAL],r[h]=p)}if(p===T)continue;let R=Qn.getIndexedValues(T);if(R){w_&&S.prefetch(R.map(b=>({key:b,value:n})),C_);for(let b=0,C=R.length;b<C;b++)S.remove(R[b],n)}if(R=Qn.getIndexedValues(p),R){w_&&S.prefetch(R.map(b=>({key:b,value:n})),C_);for(let b=0,C=R.length;b<C;b++)S.put(R[b],n)}}let f=Object.assign({},_,r);c.put(n,f,f[Fi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Mm(e,t,r,n,s,i,o))}a(Mm,"updateUpsertRecord");function J$(e,t,r){if(Qn.validateEnv(e),t===void 0)throw new Error(Bc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Bc.WRITE_ATTRIBUTES_REQUIRED):new Error(Bc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(J$,"validateBasic");function Pm(e,t,r,n){if(J$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Bc.RECORDS_REQUIRED):new Error(Bc.RECORDS_MUST_BE_ARRAY)}a(Pm,"validateWrite");function C_(){}a(C_,"noop");Ay.exports={insertRecords:Y$,updateRecords:Q$,upsertRecords:z$}});var ki=g((Eue,j$)=>{j$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Jn=g((hue,yy)=>{"use strict";var by=z(),Oy=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zn=require("joi"),si={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},X$=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number(),zn.array()).required(),Z$=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number()),e1=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number()).required();function t1(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>si.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(t1,"checkValidTable");function r1(e,t){return by.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(r1,"validateSchemaExists");function n1(e,t){let r=t.state.ancestors[0].schema;return by.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(n1,"validateTableExists");function s1(e,t){return e.toLowerCase()===Oy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Oy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(s1,"validateSchemaName");yy.exports={common_validators:si,schema_regex:Ko,hdb_schema_table:X$,validateSchemaExists:r1,validateTableExists:n1,validateSchemaName:s1,checkValidTable:t1,hdb_database:Z$,hdb_table:e1}});var Xe=g((pue,Ny)=>{"use strict";var dr=require("validate.js");dr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||dr.validators.type.checks[t](e)?null:` must be a '${t}' value`};dr.validators.type.checks={Object:function(e){return dr.isObject(e)&&!dr.isArray(e)},Array:dr.isArray,Integer:dr.isInteger,Number:dr.isNumber,String:dr.isString,Date:dr.isDate,Boolean:function(e){return typeof e=="boolean"}};dr.validators.hasValidFileExt=function(e,t){return dr.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};Ny.exports={validateObject:i1,validateObjectAsync:o1,validateBySchema:a1};function i1(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=dr(e,t,{format:"flat"});return r?new Error(r):null}a(i1,"validateObject");async function o1(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await dr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(o1,"validateObjectAsync");function a1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(a1,"validateBySchema")});var D_=g((Tue,Iy)=>{var{common_validators:jn}=Jn(),xc=Xe(),Hc="is required",gt={database:{presence:!1,format:jn.schema_format,length:jn.schema_length},schema:{presence:!1,format:jn.schema_format,length:jn.schema_length},table:{presence:!0,format:jn.schema_format,length:jn.schema_length},attribute:{presence:!0,format:jn.schema_format,length:jn.schema_length},hash_attribute:{presence:!0,format:jn.schema_format,length:jn.schema_length}};function Gc(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(Gc,"makeAttributesStrings");function c1(e){return e=Gc(e),gt.table.presence=!1,gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(c1,"schema_object");function u1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(u1,"table_object");function l1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,xc.validateObject(e,gt)}a(l1,"create_table_object");function _1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence={message:Hc},gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(_1,"attribute_object");function d1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(d1,"describe_table");function f1(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(f1,"validateTableResidence");Iy.exports={schema_object:c1,create_table_object:l1,table_object:u1,attribute_object:_1,describe_table:d1,validateTableResidence:f1}});var Cy=g((Rue,wy)=>{"use strict";var E1=require("uuid"),Um=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||E1.v4(),this.schema_table=`${this.schema}.${this.table}`}};wy.exports=Um});var L_=g((Oue,Dy)=>{"use strict";var h1=Cy(),vm=class extends h1{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};Dy.exports=vm});var My=g((yue,Ly)=>{"use strict";Ly.exports=p1;var m1="inserted";function p1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===m1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(p1,"returnObject")});var M_=g((Iue,Hy)=>{"use strict";var S1=P(),Bm=Qe(),T1=Yo(),{getSystemSchemaPath:g1,getSchemaPath:R1}=je(),A1=ki(),O1=D_(),b1=L_(),y1=My(),{handleHDBError:Py,hdb_errors:vy}=ne(),Uy=z(),{HTTP_STATUS_CODES:N1}=vy,Hm=A1.hdb_attribute,By=[];for(let e=0;e<Hm.attributes.length;e++)By.push(Hm.attributes[e].attribute);var I1="inserted";Hy.exports=w1;async function w1(e){let t=O1.attribute_object(e);if(t)throw Py(new Error,t.message,vy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Uy.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Py(new Error,r,N1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Uy.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new b1(e.schema,e.table,e.attribute,e.id);try{let i=await Bm.openEnvironment(R1(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}`);Bm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Bm.openEnvironment(g1(),S1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await T1.insertRecords(o,Hm.hash_attribute,By,[s]);return y1(I1,c,{records:[s]},u)}catch(i){throw i}}a(w1,"lmdbCreateAttribute")});var Gm=g((Cue,Gy)=>{var{hdb_table:C1,hdb_database:xy}=Jn(),D1=Xe(),xm=require("joi"),L1={undefined:"undefined",null:"null"},M1=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||L1[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),P1=xm.object({database:xy,schema:xy,table:C1,records:xm.array().items(xm.object().custom(M1)).required()});Gy.exports=function(e){return D1.validateBySchema(e,P1)}});var qc=g((Mue,Fy)=>{"use strict";var Rs=z(),qy=$(),Lue=Gm(),{getDatabases:U1}=(Ae(),ie(ke)),{ClientError:Vi}=ne();Fy.exports=v1;function v1(e){if(Rs.isEmpty(e))throw new Vi("invalid update parameters defined.");if(Rs.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(Rs.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=U1()[e.schema]?.[e.table];if(Rs.isEmpty(t))throw new Vi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Rs.isEmptyOrZeroLength(o[r]))throw qy.error("a valid hash attribute must be provided with update record:",o),new Vi("a valid hash attribute must be provided with update record, check log for more info");if(!Rs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw qy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Vi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Rs.isEmpty(o[r])&&o[r]!==""&&n.has(Rs.autoCast(o[r]))&&(o.skip=!0),n.add(Rs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(v1,"insertUpdateValidate")});var Fc=g((Uue,ky)=>{"use strict";var B1=P().OPERATIONS_ENUM,qm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=B1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};ky.exports=qm});var kc=g((Hue,$y)=>{"use strict";var Bue=Fc(),P_=P(),Fm=z(),Vy=$(),H1=require("uuid"),{handleHDBError:U_,hdb_errors:x1}=ne(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:B_}=x1;$y.exports=G1;function G1(e,t,r){for(let s=0;s<t.length;s++)q1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];F1(i,r,e.operation)}}a(G1,"processRows");function q1(e){if(Buffer.byteLength(String(e))>P_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw U_(new Error,v_.ATTR_NAME_LENGTH_ERR(e),B_.BAD_REQUEST,void 0,void 0,!0);if(Fm.isEmptyOrZeroLength(e)||Fm.isEmpty(e.trim()))throw U_(new Error,v_.ATTR_NAME_NULLISH_ERR,B_.BAD_REQUEST,void 0,void 0,!0)}a(q1,"validateAttribute");function F1(e,t,r){if(!e.hasOwnProperty(t)||Fm.isEmptyOrZeroLength(e[t])){if(r===P_.OPERATIONS_ENUM.INSERT||r===P_.OPERATIONS_ENUM.UPSERT){e[t]=H1.v4();return}throw Vy.error("Update transaction aborted due to record with no hash value:",e),U_(new Error,v_.RECORD_MISSING_HASH_ERR,B_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>P_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Vy.error(e),U_(new Error,v_.HASH_VAL_LENGTH_ERR,B_.BAD_REQUEST,void 0,void 0,!0)}a(F1,"validateHash")});var Ky=g((Gue,Yy)=>{"use strict";var km=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Yy.exports=km});var zy=g((Fue,Qy)=>{"use strict";var Vm=Qe(),k1=$(),Wy=Ur().LMDB_ERRORS_ENUM;Qy.exports=V1;async function V1(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 Vm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Wy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await Vm.closeEnvironment(global.lmdb_map[n]),await Vm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Wy.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){k1.error(t)}}a(V1,"cleanLMDBMap")});var As=g((Vue,Zy)=>{"use strict";var Vc=require("crypto"),$1=Z(),{CONFIG_PARAMS:Y1}=P(),jy="aes-256-cbc",K1=32,W1=16,$m=64,Xy=32,Q1=$m+Xy,Jy=new Map;Zy.exports={encrypt:z1,decrypt:J1,createNatsTableStreamName:j1};function z1(e){let t=Vc.randomBytes(K1),r=Vc.randomBytes(W1),n=Vc.createCipheriv(jy,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(z1,"encrypt");function J1(e){let t=e.substr(0,$m),r=e.substr($m,Xy),n=e.substr(Q1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Vc.createDecipheriv(jy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(J1,"decrypt");function j1(e,t){let r=$1.get(Y1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Jy.get(r);return n||(n=Vc.createHash("md5").update(r).digest("hex"),Jy.set(r,n)),n}a(j1,"createNatsTableStreamName")});var Os=g((Kue,tN)=>{"use strict";var Yue=Gr(),$c=$(),eN=D_(),X1=As(),H_=z(),{handleHDBError:x_,hdb_errors:Z1}=ne(),{HDB_ERROR_MSGS:G_,HTTP_STATUS_CODES:Ym}=Z1,eY=Z();eY.initSync();var{getDatabases:Km}=(Ae(),ie(ke)),tY=require("fs-extra");tN.exports={describeAll:rY,describeTable:q_,describeSchema:nY};async function rY(e){try{let t=H_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Km(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let E in d)try{let f;if(t||n)f=await q_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await q_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){$c.error(f)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return $c.error("Got an error in describeAll"),$c.error(t),x_(new Error,G_.DESCRIBE_ALL_ERR)}}a(rY,"describeAll");async function q_(e,t){H_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=eN.describe_table(e);if(i)throw i;let c=Km()[r];if(!c)throw x_(new Error,G_.SCHEMA_NOT_FOUND(e.schema),Ym.NOT_FOUND);let u=c[n];if(!u)throw x_(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(h=>({type:h.type,name:h.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(h=>{h.describe&&(f[h.attribute_name]=!0)}),u.attributes.forEach(h=>{f[h.name]&&_(h)})}else u.attributes?.forEach(f=>_(f));let d;try{d=(await tY.stat(u.primaryStore.env.path)).size}catch(f){$c.warn("unable to get database size",f)}let E={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,db_size:d};E.clustering_stream_name=X1.createNatsTableStreamName(E.schema,E.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=f.recordCount,E.estimated_record_range=f.estimatedRange;let h=u.auditStore;if(h)for(let p of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=p[0];if(!E.last_updated_record&&u.indices.__updatedtime__)for(let p of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=p}catch(f){$c.warn(`unable to stat table dbi due to ${f}`)}return E}a(q_,"descTable");async function nY(e){H_.transformReq(e);let t=eN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Km()[n];if(!i)throw x_(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]),H_.isEmpty(u)||u.describe){let _=await q_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(nY,"describeSchema")});var bs=g((Jue,oN)=>{var sY=ki(),{callbackify:nN,promisify:iY}=require("util"),{getDatabases:sN}=(Ae(),ie(ke));oN.exports={setSchemaDataToGlobal:rN,getTableSchema:oY,getSystemSchema:aY,setSchemaDataToGlobalAsync:iY(rN)};var iN=Os(),Que=nN(iN.describeAll),zue=nN(iN.describeTable);function rN(e){global.hdb_schema=sN(),e&&e()}a(rN,"setSchemaDataToGlobal");function oY(e,t,r){let n=sN()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(oY,"getTableSchema");function aY(){return sY}a(aY,"getSystemSchema")});var qr=g((Xue,lN)=>{"use strict";var k_=Gm(),Yt=z(),cY=require("util"),V_=Cn(),uY=bs(),aN=$(),{handleHDBError:$i,hdb_errors:lY}=ne(),{HTTP_STATUS_CODES:Yi}=lY,_Y=cY.promisify(uY.getTableSchema),dY="updated",cN="inserted",uN="upserted";lN.exports={insert:EY,update:hY,upsert:mY,validation:fY,flush:pY};async function fY(e){if(Yt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Yt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Yt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await _Y(e.schema,e.table),r=k_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Yt.isEmptyOrZeroLength(c[n]))throw aN.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(!Yt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw aN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Yt.isEmpty(c[n])&&c[n]!==""&&s.has(Yt.autoCast(c[n]))&&(c.skip=!0),s.add(Yt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(fY,"validation");async function EY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=k_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await V_.createRecords(e);return F_(cN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(EY,"insertData");async function hY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=k_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await V_.updateRecords(e);return Yt.isEmpty(n.existing_rows)?F_(dY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):F_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(hY,"updateData");async function mY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=k_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await V_.upsertRecords(e);return F_(uN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(mY,"upsertData");function F_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===cN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===uN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(F_,"returnObject");function pY(e){return Yt.transformReq(e),V_.flush(e.schema,e.table)}a(pY,"flush")});var Qm=g((ele,fN)=>{var SY=Xe(),Wm=require("joi"),{hdb_table:TY,hdb_database:_N}=Jn(),dN={schema:_N,database:_N,table:TY},gY={date:Wm.date().iso().required()},RY={timestamp:Wm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};fN.exports=function(e,t){let r=t==="timestamp"?{...dN,...RY}:{...dN,...gY},n=Wm.object(r);return SY.validateBySchema(e,n)}});var mN=g((tle,hN)=>{var AY=Xe(),zm=require("joi"),{hdb_table:OY,hdb_database:EN}=Jn(),bY=zm.object({schema:EN,database:EN,table:OY,hash_values:zm.array().required(),ids:zm.array()});hN.exports=function(e){return AY.validateBySchema(e,bY)}});var SN=g((rle,pN)=>{"use strict";var Jm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},jm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Xm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};pN.exports={InsertObject:Jm,NoSQLSeachObject:jm,DeleteResponseObject:Xm}});var ai=g((sle,ON)=>{"use strict";var gN=Qm(),yY=mN(),Ki=z(),TN=require("moment"),RN=$(),{promisify:NY,callbackify:IY}=require("util"),Wi=P(),wY=bs(),Zm=NY(wY.getTableSchema),ep=Cn(),{DeleteResponseObject:CY}=SN(),{handleHDBError:ii,hdb_errors:DY}=ne(),{HDB_ERROR_MSGS:$_,HTTP_STATUS_CODES:oi}=DY,LY="records successfully deleted",MY=IY(AN);ON.exports={delete:MY,deleteRecord:AN,deleteFilesBefore:PY,deleteAuditLogsBefore:UY};async function PY(e){let t=gN(e,"date");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!TN(e.date,TN.ISO_8601).isValid())throw ii(new Error,$_.INVALID_DATE,oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,$_.INVALID_DATE,!0);let n=Ki.checkSchemaTableExist(e.schema,e.table);if(n)throw ii(new Error,n,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,n,!0);let s=await ep.deleteRecordsBefore(e);if(await Zm(e.schema,e.table),RN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(PY,"deleteFilesBefore");async function UY(e){let t=gN(e,"timestamp");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ii(new Error,$_.INVALID_VALUE("Timestamp"),oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,$_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let n=await ep.deleteAuditLogsBefore(e);return await Zm(e.schema,e.table),RN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(UY,"deleteAuditLogsBefore");async function AN(e){e.ids&&(e.hash_values=e.ids);let t=yY(e);if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await Zm(e.schema,e.table);let n=await ep.deleteRecords(e);return Ki.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${LY}`),n}catch(n){if(n.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let s=new CY;return s.message=Wi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(AN,"deleteRecord")});var Y_=g((ole,NN)=>{var vY=require("crypto"),bN=9;function BY(e){let t=xY(bN),r=yN(e+t);return t+r}a(BY,"createHash");function HY(e,t){let r=e?.substr(0,bN),n=r+yN(t+r);return e===n}a(HY,"validateHash");function xY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(xY,"generateSalt");function yN(e){return vY.createHash("md5").update(e).digest("hex")}a(yN,"md5");NN.exports={hash:BY,validate:HY}});var wN=g((cle,IN)=>{var tp=Xe(),Zt={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 GY(e){return Zt.password.presence=!0,Zt.username.presence=!0,Zt.role.presence=!0,Zt.active.presence=!0,tp.validateObject(e,Zt)}a(GY,"addUserValidation");function qY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,tp.validateObject(e,Zt)}a(qY,"alterUserValidation");function FY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,tp.validateObject(e,Zt)}a(FY,"dropUserValidation");IN.exports={addUserValidation:GY,alterUserValidation:qY,dropUserValidation:FY}});var Ve=g((_le,DN)=>{"use strict";var{platform:lle}=require("os"),kY="nats-server.zip",rp="nats-server",VY=process.platform==="win32"?`${rp}.exe`:rp,$Y=/^[^\s.,*>]+$/,CN="__request__",YY=a(e=>`${e}.${CN}`,"REQUEST_SUBJECT"),KY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},WY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},QY={HUB:"hub.pid",LEAF:"leaf.pid"},zY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},JY={SUCCESS:"success",ERROR:"error"},jY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},XY={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},ZY={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},eK={debug:"-D",trace:"-DVV"};DN.exports={NATS_SERVER_ZIP:kY,NATS_SERVER_NAME:rp,NATS_BINARY_NAME:VY,PID_FILES:QY,NATS_CONFIG_FILES:WY,SERVER_SUFFIX:zY,NATS_TERM_CONSTRAINTS_RX:$Y,REQUEST_SUFFIX:CN,UPDATE_REMOTE_RESPONSE_STATUSES:JY,CLUSTER_STATUS_STATUSES:jY,REQUEST_SUBJECT:YY,SUBJECT_PREFIXES:XY,MSG_HEADERS:KY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:eK,LOG_LEVEL_HIERARCHY:ZY}});var MN=g((fle,LN)=>{"use strict";var tK={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
- `)},QY="certificate.pem",zY="privateKey.pem",JY="ca.pem";CN.exports={CERTIFICATE_VALUES:WY,CERTIFICATE_PEM_NAME:QY,PRIVATEKEY_PEM_NAME:zY,CA_PEM_NAME:JY}});var rp=g((ole,BN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),jY=require("os"),{boolean:be,string:Xt,number:et,array:k_}=oe.types(),{totalmem:LN}=require("os"),Wi=require("path"),XY=$(),V_=z(),ile=DN(),MN=P(),ZY=Xe(),PN="log",eK="components",tK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",rK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",nK="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",sK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",iK="rootPath config parameter is undefined",oK="clustering.enabled config parameter is undefined",Qi=et.min(0).required(),$_=k_.items({host:Xt.required(),port:Qi}).empty(null),jn,vN=!1;BN.exports={configValidator:aK,routesValidator:fK,route_constraints:$_};function aK(e,t=!1){if(vN=t,jn=e.rootPath,V_.isEmpty(jn))throw iK;let r=be.required(),n=et.min(0).max(1e3).empty(null).default(dK),s=Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Fc),i=Xt.optional().empty(null),o=Xt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(Fc),u=oe.custom(uK).empty(null).default(Fc),_=e.clustering?.enabled;if(V_.isEmpty(_))throw oK;let l=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:Qi,routes:$_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Qi}).required()}).required(),network:oe.object({port:Qi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Qi,routes:$_}).required(),streams:oe.object({maxAge:et.min(120).allow(null).optional(),maxBytes:et.min(1).allow(null).optional(),maxMsgs:et.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:Xt.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:et.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:et}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:Xt.custom(_K).optional().empty(null),maxSize:Xt.custom(lK).optional().empty(null),path:Xt.optional().empty(null).default(Fc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:k_.optional(),headersTimeout:et.min(1).optional(),keepAliveTimeout:et.min(1).optional(),port:et.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Fc),securePort:et.optional().empty(null),timeout:et.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:Qi,securePort:Qi,mtls:oe.alternatives([be.optional(),oe.object({user:Xt.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:et.optional(),cors:be.optional(),corsAccessList:k_.optional(),headersTimeout:et.min(1).optional(),port:et.min(0).optional().empty(null),securePort:et.min(0).optional().empty(null),maxHeaderSize:et.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:Xt.optional(),certificateAuthority:i,required:be.optional()})]),threadRange:oe.alternatives([k_.optional(),Xt.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:et.min(1).optional(),host:Xt.optional(),waitForDebugger:be.optional()})),maxHeapMemory:et.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:Xt.optional(),threshold:et.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:et.optional(),maxFreeSpaceToRetain:et.optional()}).required(),ignoreScripts:be.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(aK,"configValidator");function cK(e){return vN||UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(cK,"doesPathExist");function uK(e,t){oe.assert(e,Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=cK(e);if(r)return t.message(r)}a(uK,"validatePath");function lK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(tK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(nK):e}a(lK,"validateRotationMaxSize");function _K(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(rK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(sK):e}a(_K,"validateRotationInterval");function dK(e,t){let r=t.state.path.join("."),n=jY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||LN();return i=Math.round(Math.min(i,LN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),XY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(dK,"setDefaultThreads");function Fc(e,t){let r=t.state.path.join(".");if(!V_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(V_.isEmpty(jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(jn,eK);case"logging.root":return Wi.join(jn,PN);case"clustering.leafServer.streams.path":return Wi.join(jn,"clustering","leaf");case"storage.path":let n=Wi.join(jn,MN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(n)?n:Wi.join(jn,MN.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(jn,PN);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(jn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Fc,"setDefaultRoot");function fK(e){let t=oe.object({routes:$_});return ZY.validateBySchema({routes:e},t)}a(fK,"routesValidator")});var fr=g((ule,YN)=>{"use strict";var kr=P(),vt=z(),It=$(),{configValidator:EK,routesValidator:HN}=rp(),dr=require("fs-extra"),hK=require("yaml"),Dn=require("path"),mK=require("is-number"),GN=require("properties-reader"),pK=require("lodash"),{handleHDBError:SK}=ne(),{HTTP_STATUS_CODES:TK,HDB_ERROR_MSGS:Y_}=Ur(),cle=require("minimist"),{server:gK}=(ur(),ie(Hi)),{DATABASES_PARAM_CONFIG:kc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,RK="Unable to get config value because config is uninitialized",AK="Config successfully initialized",OK="Error backing up config file",bK="Empty parameter sent to getConfigValue",qN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),yK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",xN={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"},K_,wt,W_;YN.exports={createConfigFile:NK,getDefaultConfig:IK,getConfigValue:kN,initConfig:sp,flattenConfig:Qo,updateConfigValue:VN,updateConfigObject:CK,getConfiguration:MK,setConfiguration:PK,readConfigFile:op,getClusteringRoutes:UK,initOldConfig:$N,getConfigFromFile:vK,getConfigFilePath:zi,addConfig:BK,deleteConfigFromFile:HK,getConfigObj:xK};function NK(e,t=!1){let r=ai(qN);K_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=np(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){It.error(d)}}}n&&FN(r,n),ip(r,t);let s=r.toJSON();wt=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);dr.createFileSync(o),dr.writeFileSync(o,String(r)),It.trace(`Config file written to ${o}`)}a(NK,"createConfigFile");function FN(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!vt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(kc.TABLES))for(let i in n[s][kc.TABLES])for(let o in n[s][kc.TABLES][i]){let c=n[s][kc.TABLES][i][o],u=[Fr.DATABASES,s,kc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Fr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){It.error("Error parsing schemas CLI/env config arguments",n)}}a(FN,"setSchemasConfig");function IK(e){if(K_===void 0){let r=ai(qN);K_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return K_[t.toLowerCase()]}a(IK,"getDefaultConfig");function kN(e){if(e==null){It.error(bK);return}if(wt===void 0){It.trace(RK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return wt[t.toLowerCase()]}a(kN,"getConfigValue");function zi(e=vt.getPropsFilePath()){let t=vt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):GN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function sp(e=!1){if(wt===void 0||e){let t;if(!vt.noBootFile()){t=vt.getPropsFilePath();try{dr.accessSync(t,dr.constants.F_OK|dr.constants.R_OK)}catch(i){throw It.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{$N(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ai(r)}catch(i){if(i.code===kr.NODE_ERROR_CODES.ENOENT){It.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 It.error(i),new Error(`Error reading HarperDB config file at ${r}`)}wK(n,r),ip(n);let s=n.toJSON();if(gK.config=s,wt=Qo(s),wt.logging_rotation_rotate)for(let i in xN)wt[i]&&It.error(`Config ${xN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);It.trace(AK)}}a(sp,"initConfig");function wK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(It.trace("Updating config file with missing config params"),dr.writeFileSync(t,String(e)))}a(wK,"checkForUpdatedConfig");function ip(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=EK(r,t);if(n.error)throw Y_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(ip,"validateConfig");function CK(e,t){wt===void 0&&(wt={});let r=Ln[e.toLowerCase()];if(r===void 0){It.trace(`Unable to update config object because config param '${e}' does not exist`);return}wt[r.toLowerCase()]=t}a(CK,"updateConfigObject");function VN(e,t,r=void 0,n=!1,s=!1,i=!1){wt===void 0&&sp();let o=kN(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ai(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=np(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===wt[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===wt[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=np(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){It.error(T)}}}_&&FN(u,_),ip(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&DK(c,l),dr.writeFileSync(d,String(u)),s&&(wt=Qo(u.toJSON())),It.trace(`Config parameter: ${e} updated with value: ${t}`)}a(VN,"updateConfigValue");function DK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);dr.copySync(e,r),It.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){It.error(OK),It.error(r)}}a(DK,"backupConfigFile");var LK=["databases"];function Qo(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)),W_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!LK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function np(e,t){if(e===Fr.CLUSTERING_NODENAME||e===Fr.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(mK(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(np,"castConfigValue");function MK(){let e=vt.getPropsFilePath(),t=zi(e);return ai(t).toJSON()}a(MK,"getConfiguration");async function PK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return VN(void 0,void 0,s,!0),yK}catch(i){throw typeof i=="string"||i instanceof String?SK(i,i,TK.BAD_REQUEST,void 0,void 0,!0):i}}a(PK,"setConfiguration");function op(){let e=vt.getPropsFilePath();try{dr.accessSync(e,dr.constants.F_OK|dr.constants.R_OK)}catch(n){if(!vt.noBootFile())throw It.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ai(t).toJSON()}a(op,"readConfigFile");function ai(e){return hK.parseDocument(dr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ai,"parseYamlDoc");function UK(){let e=op(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=vt.isEmptyOrZeroLength(t)?[]:t;let r=HN(t);if(r)throw Y_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=vt.isEmptyOrZeroLength(n)?[]:n;let s=HN(n);if(s)throw Y_.CONFIG_VALIDATION(s.message);if(!vt.isEmptyOrZeroLength(n)&&!vt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!vt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Y_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(UK,"getClusteringRoutes");function $N(e){let t=GN(e);wt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(vt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?wt[s]=Dn.dirname(n):wt[s]=n}return wt}a($N,"initOldConfig");function vK(e){let t=op();return pK.get(t,e.replaceAll("_","."))}a(vK,"getConfigFromFile");async function BK(e,t){let r=ai(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await dr.writeFile(zi(),String(r))}a(BK,"addConfig");function HK(e){let t=zi(vt.getPropsFilePath()),r=ai(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);dr.writeFileSync(s,String(r))}a(HK,"deleteConfigFromFile");function xK(){return W_||(sp(),W_)}a(xK,"getConfigObj")});var WN=g((_le,KN)=>{"use strict";var Q_=P(),z_=class{static{a(this,"BaseLicense")}constructor(t=0,r=Q_.RAM_ALLOCATION_ENUM.DEFAULT,n=Q_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},ap=class extends z_{static{a(this,"ExtendedLicense")}constructor(t=0,r=Q_.RAM_ALLOCATION_ENUM.DEFAULT,n=Q_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};KN.exports={BaseLicense:z_,ExtendedLicense:ap}});var Ji=g((fle,ZN)=>{"use strict";var Jo=require("fs-extra"),zN=F_(),JN=require("crypto"),GK=require("moment"),qK=require("uuid").v4,Zt=$(),up=require("path"),FK=z(),ci=P(),{totalmem:QN}=require("os"),kK=WN().ExtendedLicense,zo="invalid license key format",VK="061183",$K="mofi25",YK="aes-256-cbc",KK=16,WK=32,jN=Z();jN.initSync();var cp;ZN.exports={validateLicense:XN,generateFingerPrint:zK,licenseSearch:dp,getLicense:XK,checkMemoryLimit:ZK};function lp(){return up.join(jN.getHdbBasePath(),ci.LICENSE_KEY_DIR_NAME,ci.LICENSE_FILE_NAME)}a(lp,"getLicenseDirPath");function QK(){let e=lp();return up.join(e,ci.LICENSE_FILE_NAME)}a(QK,"getLicenseFilePath");function _p(){let e=lp();return up.join(e,ci.REG_KEY_FILE_NAME)}a(_p,"getFingerPrintFilePath");async function zK(){let e=_p();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await JK();throw Zt.error(`Error writing fingerprint file to ${e}`),Zt.error(t),new Error("There was an error generating the fingerprint")}}a(zK,"generateFingerPrint");async function JK(){let e=qK(),t=zN.hash(e),r=_p();try{await Jo.mkdirp(lp()),await Jo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Zt.error(`Error writing fingerprint file to ${r}`),Zt.error(n),new Error("There was an error generating the fingerprint")}return t}a(JK,"writeFingerprint");function XN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ci.RAM_ALLOCATION_ENUM.DEFAULT,version:ci.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Zt.error("empty license key passed to validate."),r;let n=_p(),s=!1;try{s=Jo.statSync(n)}catch(i){Zt.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{Zt.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)],KK);let u=Buffer.concat([Buffer.from(i)],WK),_=JN.createDecipheriv(YK,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 f=jK(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),Zt.error(zo),new Error(zo)}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(zo),Zt.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<GK().valueOf()&&(r.valid_date=!1),zN.validate(o[1],`${VK}${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(XN,"validateLicense");function jK(e,t){try{let r=JN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Zt.warn("Check old license failed")}}a(jK,"checkOldLicense");function dp(){let e=new kK,t=[];try{t=Jo.readFileSync(QK(),"utf-8").split(ci.NEW_LINE)}catch(r){r.code==="ENOENT"?Zt.info("no license file found"):Zt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(FK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=XN(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){Zt.error("There was an error parsing the license string."),Zt.error(s),e.ram_allocation=ci.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return cp=e,e}a(dp,"licenseSearch");async function XK(){return cp||await dp(),cp}a(XK,"getLicense");function ZK(){let e=dp().ram_allocation,t=process.constrainedMemory?.()||QN();if(t=Math.round(Math.min(t,QN())/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(ZK,"checkMemoryLimit")});var ln=g((Sle,hI)=>{"use strict";var nI="username is required",sI="nothing to update, must supply active, role or password to update",iI="password cannot be an empty string",oI="If role is specified, it cannot be empty.",aI="active must be true or false";hI.exports={addUser:cW,alterUser:uW,dropUser:_W,getSuperUser:hW,userInfo:dW,listUsers:j_,listUsersExternal:fW,setUsersToGlobal:Xo,findAndValidateUser:fI,getClusterUser:mW,USERNAME_REQUIRED:nI,ALTERUSER_NOTHING_TO_UPDATE:sI,EMPTY_PASSWORD:iI,EMPTY_ROLE:oI,ACTIVE_BOOLEAN:aI};var cI=qr(),eW=oi(),hp=F_(),uI=NN(),lI=Gr(),mp=bs(),Vr=z(),_I=require("validate.js"),Oe=$(),{promisify:tW}=require("util"),pp=Rs(),eI=P(),tI=Ve(),rW=fr(),hle=Z(),mle=Ji(),nW=Fi(),{table:ple}=(Ae(),ie(ke)),{handleHDBError:Xn,hdb_errors:sW}=ne(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:fp,HDB_ERROR_MSGS:jo}=sW,{UserEventMsg:Sp}=Mn(),Ep=require("lodash"),{server:Tp}=(ur(),ie(Hi)),iW=$();Tp.getUser=(e,t)=>fI(e,t,t!=null);var dI={username:!0,active:!0,role:!0,password:!0},rI=new Map,J_=lI.searchByValue,oW=lI.searchByHash,aW=tW(eW.delete);async function cW(e){let t=_I.cleanAttributes(e,dI),r=uI.addUserValidation(t);if(r)throw Xn(new Error,r.message,Zn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await J_(n),s=s&&Array.from(s)}catch(u){throw Oe.error("There was an error searching for a role in add user"),Oe.error(u),u}if(!s||s.length<1)throw Xn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Xn(new Error,jo.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await cI.insert(i)}catch(u){throw Oe.error("There was an error searching for a user."),Oe.error(u),u}Oe.debug(o);try{await Xo()}catch(u){throw Oe.error("Got an error setting users to global"),Oe.error(u),u}if(o.skipped_hashes.length===1)throw Xn(new Error,jo.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],mp.signalUserChange(new Sp(process.pid)),`${c.username} successfully added`}a(cW,"addUser");async function uW(e){let t=_I.cleanAttributes(e,dI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(nI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(sI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(iI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(aI);let r=lW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password)),t.role==="")throw new Error(oI);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 J_(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),Xn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),Xn(new Error,c,Zn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await cI.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await Xo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return mp.signalUserChange(new Sp(process.pid)),s}a(uW,"alterUser");function lW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(lW,"isClusterUser");async function _W(e){try{let t=uI.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 Xn(new Error,jo.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await aW(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await Xo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return mp.signalUserChange(new Sp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(_W,"dropUser");async function dW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Ep.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await oW(r)}catch(s){throw Oe.error("Got an error searching for a role."),Oe.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Oe.error(r),r}return t}a(dW,"userInfo");async function fW(){let e;try{e=await j_()}catch(t){throw Oe.error("Got an error listing users."),Oe.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(fW,"listUsersExternal");async function j_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await J_(e)}catch(o){throw Oe.error("Got an error searching for roles."),Oe.error(o),o}let r={};for(let o of t)r[o.id]=Ep.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await J_(n)}catch(o){throw Oe.error("Got an error searching for users."),Oe.error(o),o}let i=new Map;for(let o of s)o=Ep.cloneDeep(o),o.role=r[o.role],EW(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),Vr.errorizeMessage(e)}return null}a(j_,"listUsers");function EW(e){try{if(!e){Oe.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(nW)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Oe.error("Got an error trying to set system permissions."),Oe.error(t)}}a(EW,"appendSystemTablesToRole");async function Xo(){try{let e=await j_();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(Xo,"setUsersToGlobal");async function fI(e,t,r=!0){global.hdb_users||await Xo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Xn(new Error,fp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Xn(new Error,fp.USER_INACTIVE,Zn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(rI.get(t)===n.password)return s;if(hp.validate(n.password,t))rI.set(t,n.password);else throw Xn(new Error,fp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(fI,"findAndValidateUser");async function hW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(hW,"getSuperUser");async function mW(){let e=await j_(),t=rW.getConfigFromFile(eI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===eI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=pp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+tI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+tI.SERVER_SUFFIX.ADMIN,r}a(mW,"getClusterUser");var EI=[];Tp.invalidateUser=function(e){for(let t of EI)try{t(e)}catch(r){iW.error("Error invalidating user",r)}};Tp.onInvalidatedUser=function(e){EI.push(e)}});var $c=g((Ale,TI)=>{"use strict";var ji=$(),$r=P(),pW=Wy(),gle=Os(),Rle=As(),SW=ln(),{validateEvent:mI}=Mn(),Vc=Cn(),TW=require("process"),{resetDatabases:gW}=(Ae(),ie(ke)),RW={[$r.ITC_EVENT_TYPES.SCHEMA]:AW,[$r.ITC_EVENT_TYPES.USER]:SI};async function AW(e){let t=mI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await pW(e.message),await OW(e.message)}a(AW,"schemaHandler");async function OW(e){try{Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=gW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(OW,"syncSchemaMetadata");var pI=[];async function SI(e){try{try{Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=mI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${$r.HDB_ITC_CLIENT_PREFIX}${TW.pid} received user event:`,e),await SW.setUsersToGlobal();for(let r of pI)r()}catch(t){ji.error(t)}}a(SI,"userHandler");SI.addListener=function(e){pI.push(e)};TI.exports=RW});var Mn=g((wle,RI)=>{"use strict";var ble=$(),gp=z(),bW=P(),{ITC_ERRORS:Yc}=Ur(),{parentPort:yle,threadId:yW,isMainThread:NW,workerData:Nle}=require("worker_threads"),{onMessageFromWorkers:IW,broadcast:Ile,broadcastWithAcknowledgement:wW}=je();RI.exports={sendItcEvent:CW,validateEvent:gI,SchemaEventMsg:DW,UserEventMsg:LW};var X_;IW(async(e,t)=>{X_=X_||$c(),gI(e),X_[e.type]&&await X_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function CW(e){return!NW&&e.message&&(e.message.originator=yW),wW(e)}a(CW,"sendItcEvent");function gI(e){if(typeof e!="object")return Yc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||gp.isEmpty(e.type))return Yc.MISSING_TYPE;if(!e.hasOwnProperty("message")||gp.isEmpty(e.message))return Yc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||gp.isEmpty(e.message.originator))return Yc.MISSING_ORIGIN;if(bW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yc.INVALID_EVENT(e.type)}a(gI,"validateEvent");function DW(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(DW,"SchemaEventMsg");function LW(e){this.originator=e}a(LW,"UserEventMsg")});var bs=g((Lle,yI)=>{"use strict";var AI=P(),Dle=z(),Z_=$(),OI=$y(),Zo,{sendItcEvent:bI}=Mn();function MW(e){try{Z_.trace("signalSchemaChange called with message:",e),Zo=Zo||$c();let t=new OI(AI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),bI(t)}catch(t){Z_.error(t)}}a(MW,"signalSchemaChange");function PW(e){try{Z_.trace("signalUserChange called with message:",e),Zo=Zo||$c();let t=new OI(AI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),bI(t)}catch(t){Z_.error(t)}}a(PW,"signalUserChange");yI.exports={signalSchemaChange:MW,signalUserChange:PW}});var ed=g((Ple,II)=>{"use strict";var NI=z(),UW=P(),vW=$(),BW=I_(),HW=N_(),xW=bs(),{SchemaEventMsg:GW}=Mn(),qW="already exists in";II.exports=FW;async function FW(e,t,r){if(NI.isEmptyOrZeroLength(r))return r;let n=[];NI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await kW(e,t.schema,t.name,i)})),s}a(FW,"lmdbCheckForNewAttributes");async function kW(e,t,r,n){let s=new HW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await VW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(qW))vW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(kW,"createNewAttribute");async function VW(e){let t;return t=await BW(e),xW.signalSchemaChange(new GW(process.pid,UW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(VW,"createAttribute")});var ea=g((vle,wI)=>{"use strict";var Rp=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};wI.exports=Rp});var DI=g((Hle,CI)=>{"use strict";var $W=ea(),YW=P().OPERATIONS_ENUM,Ap=class extends $W{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(YW.INSERT,r,n,s,i),this.records=t}};CI.exports=Ap});var MI=g((Gle,LI)=>{"use strict";var KW=ea(),WW=P().OPERATIONS_ENUM,Op=class extends KW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(WW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};LI.exports=Op});var UI=g((Fle,PI)=>{"use strict";var QW=ea(),zW=P().OPERATIONS_ENUM,bp=class extends QW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(zW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};PI.exports=bp});var BI=g((Vle,vI)=>{"use strict";var JW=ea(),jW=P().OPERATIONS_ENUM,yp=class extends JW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(jW.DELETE,n,s,t,i),this.original_records=r}};vI.exports=yp});var Kc=g((Kle,qI)=>{"use strict";var Yle=require("path"),HI=We(),XW=DI(),ZW=MI(),eQ=UI(),tQ=BI(),ta=ft(),xI=z(),{CONFIG_PARAMS:rQ}=P(),GI=Z();GI.initSync();var td=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:nQ}=Je();qI.exports=sQ;async function sQ(e,t){if(GI.get(rQ.LOGGING_AUDITLOG)===!1)return;let r=nQ(e.schema,e.table),n=await HI.openEnvironment(r,e.table,!0),s=iQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){HI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),xI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(sQ,"writeTransaction");function iQ(e,t){let r=xI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===td.INSERT)return new XW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.UPDATE)return new ZW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.UPSERT)return new eQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.DELETE)return new tQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(iQ,"createTransactionObject")});var Np=g((zle,FI)=>{"use strict";var oQ=Hc(),Qle=xc(),Wc=P(),aQ=Gc(),cQ=Yo().insertRecords,uQ=We(),lQ=$(),_Q=ed(),{getSchemaPath:dQ}=Je(),fQ=Kc();FI.exports=EQ;async function EQ(e){try{let{schema_table:t,attributes:r}=oQ(e);aQ(e,r,t.hash_attribute),e.schema!==Wc.SYSTEM_SCHEMA_NAME&&(r.includes(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await _Q(e.hdb_auth_header,t,r),s=dQ(e.schema,e.table),i=await uQ.openEnvironment(s,e.table),o=await cQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await fQ(e,o)}catch(c){lQ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(EQ,"lmdbCreateRecords")});var $I=g((jle,VI)=>{"use strict";var kI=P(),hQ=Np(),mQ=xc(),pQ=require("fs-extra"),{getSchemaPath:SQ}=Je();VI.exports=TQ;async function TQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mQ(kI.SYSTEM_SCHEMA_NAME,kI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await hQ(r),await pQ.mkdirp(SQ(e.schema))}a(TQ,"lmdbCreateSchema")});var KI=g((Zle,YI)=>{"use strict";var Ip=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};YI.exports=Ip});var JI=g((s_e,zI)=>{"use strict";var WI=We(),wp=vr(),Cp=Ur().LMDB_ERRORS_ENUM,gQ=ft(),QI=$(),t_e=z(),RQ=require("lmdb"),AQ=KI(),OQ=P(),{OVERFLOW_MARKER:r_e,MAX_SEARCH_KEY_LENGTH:n_e}=gQ,bQ=OQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function yQ(e,t,r,n){if(wp.validateEnv(e),t===void 0)throw new Error(Cp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Cp.IDS_REQUIRED):new Error(Cp.IDS_MUST_BE_ITERABLE);try{let s=WI.listDBIs(e);WI.initializeDBIs(e,t,s);let i=new AQ,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[bQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,RQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let R=e.dbis[T],b=h[T];if(b!=null)try{let C=wp.getIndexedValues(b);if(C)for(let H=0,v=C.length;H<v;H++)R.remove(C[H],o)}catch{QI.warn(`cannot delete from attribute: ${T}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){QI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=wp.getNextMonotonicTime(),i}catch(s){throw s}}a(yQ,"deleteRecords");zI.exports={deleteRecords:yQ}});var Qc=g((o_e,XI)=>{"use strict";var ra=z(),NQ=JI(),IQ=We(),{getSchemaPath:wQ}=Je(),CQ=Kc(),DQ=$();XI.exports=LQ;async function LQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return jI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=wQ(e.schema,e.table),i=await IQ.openEnvironment(s,e.table),o=await NQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await CQ(e,o)}catch(c){DQ.error(`unable to write transaction due to ${c.message}`)}return jI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(LQ,"lmdbDeleteRecords");function jI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(jI,"createDeleteResponse")});var Lp=g((u_e,ZI)=>{"use strict";var MQ=P(),c_e=vr();function Dp(e,t){let r=Object.create(null);if(t.length===1&&MQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(Dp,"parseRow");function PQ(e,t,r,n){let s=Dp(r,e);n.push(s)}a(PQ,"searchAll");function UQ(e,t,r,n){let s=Dp(r,e);n[t]=s}a(UQ,"searchAllToMap");function vQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(vQ,"iterateDBI");function Xi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Xi,"pushResults");function BQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(BQ,"endsWith");function HQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(HQ,"contains");function xQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(xQ,"greaterThanCompare");function GQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(GQ,"greaterThanEqualCompare");function qQ(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a(qQ,"lessThanCompare");function FQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(FQ,"lessThanEqualCompare");ZI.exports={parseRow:Dp,searchAll:PQ,searchAllToMap:UQ,iterateDBI:vQ,endsWith:BQ,contains:HQ,greaterThanCompare:xQ,greaterThanEqualCompare:GQ,lessThanCompare:qQ,lessThanEqualCompare:FQ,pushResults:Xi}});var na=g((E_e,ow)=>{"use strict";var ui=We(),__e=$(),Yr=vr(),rd=ft(),ht=Ur().LMDB_ERRORS_ENUM,d_e=z(),kQ=P(),nd=Lp(),{parseRow:VQ}=nd,f_e=require("lmdb"),{OVERFLOW_MARKER:ew,MAX_SEARCH_KEY_LENGTH:$Q}=rd;function tw(e,t,r,n=!1,s=void 0,i=void 0){return Zi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(tw,"iterateFullIndex");function zc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(e,t,r,(l,d,E,f)=>{let R={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return f===r?(R.values=!1,d.getRange(R).map(b=>({value:b}))):d.getRange(R)})}a(zc,"iterateRangeBetween");function Zi(e,t,r,n){let s=e.database||e,i=ui.openDBI(s,r);i[rd.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ui.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Zi,"setupTransaction");function rw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(ew)){if(!s)if(r)s=ui.openDBI(e,r);else{let u=ui.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ui.openDBI(e,u[_]),!s[rd.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(rw,"getOverflowCheck");function YQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(sd(r),r=Jc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>VQ(_.value,r))))}a(YQ,"searchAll");function KQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);sd(r),r=Jc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of tw(e,t,t,n,s,i))o.set(c,nd.parseRow(u,r));return o}a(KQ,"searchAllToMap");function WQ(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=tw(e,void 0,t,r,n,s),c=o.transaction,u=rw(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(WQ,"iterateDBI");function QQ(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return ui.statDBI(e,t).entryCount}a(QQ,"countAll");function zQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,t,r,(c,u,_,l)=>(n=Yr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(zQ,"equals");function JQ(e,t,r){return li(e,t,r),ui.openDBI(e,t).getValuesCount(r)}a(JQ,"count");function jQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return l.DONE}}),l.filter(E=>E)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(jQ,"startsWith");function XQ(e,t,r,n,s=!1,i=void 0,o=void 0){return nw(e,t,r,n,s,i,o,!0)}a(XQ,"endsWith");function nw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),Zi(e,null,r,(u,_,l,d)=>{let E=rw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(ew)?_.getValues(f,{transaction:u}).map(p=>{let S=E(f,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[rd.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(nw,"contains");function ZQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),zc(e,t,r,n,u,s,i,o,!0,!1)}a(ZQ,"greaterThan");function ez(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),zc(e,t,r,n,u,s,i,o,!1,!1)}a(ez,"greaterThanEqual");function tz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),zc(e,t,r,u,n,s,i,o,!1,!0)}a(tz,"lessThan");function rz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),zc(e,t,r,u,n,s,i,o,!1,!1)}a(rz,"lessThanEqual");function nz(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ht.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ht.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ht.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return zc(e,t,r,n,s,i,o,c)}a(nz,"between");function sz(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(sd(r),r=Jc(s,r),n===void 0)throw new Error(ht.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=nd.parseRow(c,r)),o}a(sz,"searchByHash");function iz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(iz,"checkHashExists");function oz(e,t,r,n,s=[]){return iw(e,t,r,n,s),sw(e,t,r,n,s).map(i=>i[1])}a(oz,"batchSearchByHash");function az(e,t,r,n,s=[]){iw(e,t,r,n,s);let i=new Map;for(let[o,c]of sw(e,t,r,n,s))i.set(o,c);return i}a(az,"batchSearchByHashToMap");function sw(e,t,r,n,s=[]){return Zi(e,t,t,(i,o,c)=>{r=Jc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,nd.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(sw,"batchHashSearch");function iw(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(sd(r),n==null)throw new Error(ht.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ht.IDS_MUST_BE_ITERABLE)}a(iw,"initializeBatchSearchByHash");function sd(e){if(!Array.isArray(e))throw e===void 0?new Error(ht.FETCH_ATTRIBUTES_REQUIRED):new Error(ht.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(sd,"validateFetchAttributes");function li(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.SEARCH_VALUE_REQUIRED);if(r?.length>$Q)throw new Error(ht.SEARCH_VALUE_TOO_LARGE)}a(li,"validateComparisonFunctions");function Jc(e,t){return t.length===1&&kQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ui.listDBIs(e)),t}a(Jc,"setGetWholeRowAttributes");ow.exports={searchAll:YQ,searchAllToMap:KQ,count:JQ,countAll:QQ,equals:zQ,startsWith:jQ,endsWith:XQ,contains:nw,searchByHash:sz,setGetWholeRowAttributes:Jc,batchSearchByHash:oz,batchSearchByHashToMap:az,checkHashExists:iz,iterateDBI:WQ,greaterThan:ZQ,greaterThanEqual:ez,lessThan:tz,lessThanEqual:rz,between:nz}});var sa=g((m_e,_w)=>{var aw=require("lodash"),cw=Xe(),fe=require("joi"),cz=z(),{hdb_schema_table:jc,checkValidTable:uw,hdb_table:lw,hdb_database:id}=zn(),{handleHDBError:uz,hdb_errors:lz}=ne(),{getDatabases:_z}=(Ae(),ie(ke)),{HTTP_STATUS_CODES:dz}=lz,fz=fe.object({database:id,schema:id,table:lw,search_attribute:jc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(jc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),Ez=fe.object({database:id,schema:id,table:lw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(jc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(jc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(jc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});_w.exports=function(e,t){let r=null;switch(t){case"value":r=cw.validateBySchema(e,fz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(uw("database",e.schema)),i(uw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=cw.validateBySchema(e,Ez);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=cz.checkGlobalSchemaTable(e.schema,e.table);if(s)return uz(new Error,s,dz.NOT_FOUND);let o=_z()[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,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=aw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!aw.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=g((S_e,dw)=>{"use strict";var hz=We(),mz=sa(),{getSchemaPath:pz}=Je();dw.exports=Sz;function Sz(e){let t=mz(e,"hashes");if(t)throw t;let r=pz(e.schema,e.table);return hz.openEnvironment(r,e.table)}a(Sz,"initialize")});var Pp=g((g_e,fw)=>{"use strict";var Tz=na(),gz=Mp();fw.exports=Rz;async function Rz(e){let t=await gz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Tz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Rz,"lmdbGetDataByHash")});var ia=g((A_e,Ew)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};Ew.exports=Up});var mw=g((y_e,hw)=>{"use strict";var b_e=ia(),Az=na(),Oz=Mp();hw.exports=bz;async function bz(e){let t=await Oz(e),r=global.hdb_schema[e.schema][e.table];return Az.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(bz,"lmdbSearchByHash")});var es=g((I_e,pw)=>{"use strict";var vp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};pw.exports=vp});var od=g((C_e,Ow)=>{"use strict";var er=na(),yz=We(),Nz=z(),Ee=ft(),eo=P(),Iz=Fi(),Sw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:wz}=Je(),ys=eo.SEARCH_WILDCARDS;async function Cz(e,t,r){let n;e.schema===eo.SYSTEM_SCHEMA_NAME?n=Iz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Aw(e,n.hash_attribute,r,t);return gw(e,s,n.hash_attribute,r)}a(Cz,"prepSearch");async function gw(e,t,r,n){let s=wz(e.schema,e.table),i=await yz.openEnvironment(s,e.table),o=Rw(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(Dz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Tw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?Tw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?er.batchSearchByHashToMap(c,r,e.get_attributes,_):er.batchSearchByHash(c,r,e.get_attributes,_)}a(gw,"executeSearch");function Rw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=er.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=er.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=er.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=er.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return er.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return er.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return er.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return er.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=er.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=er.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=er.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=er.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=er.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Rw,"searchByType");function Tw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Tw,"createMapFromIterable");function Dz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(Dz,"checkToFetchMore");function Aw(e,t,r,n){if(Nz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),ys.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(ys[0])<0&&s.indexOf(ys[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(ys.indexOf(i)>=0&&ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(ys.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(ys[0])||s.includes(ys[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(Sw.UNKNOWN_SEARCH_TYPE)}else switch(n){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Sw.UNKNOWN_SEARCH_TYPE)}}a(Aw,"createSearchTypeFromSearchObject");Ow.exports={executeSearch:gw,createSearchTypeFromSearchObject:Aw,prepSearch:Cz,searchByType:Rw}});var yw=g((M_e,bw)=>{"use strict";var L_e=es(),Lz=sa(),Mz=z(),Pz=P(),Uz=od();bw.exports=vz;function vz(e,t){if(!Mz.isEmpty(t)&&Pz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Lz(e,"value");if(n)throw n;return Uz.prepSearch(e,t,!0)}a(vz,"lmdbGetDataByValue")});var Xc=g((v_e,Nw)=>{"use strict";var U_e=es(),Bz=sa(),Hz=z(),xz=P(),Gz=od();Nw.exports=qz;async function qz(e,t){if(!Hz.isEmpty(t)&&xz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Bz(e,"value");if(n)throw n;return Gz.prepSearch(e,t,!1)}a(qz,"lmdbSearchByValue")});var ww=g((x_e,Iw)=>{"use strict";var H_e=ft(),Bp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},Hp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},xp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Iw.exports={SearchByConditionsObject:Bp,SearchCondition:Hp,SortAttribute:xp}});var Pw=g((k_e,Mw)=>{"use strict";var q_e=ww().SearchByConditionsObject,Fz=es(),kz=sa(),Gp=na(),ad=ft(),{Resource:F_e}=(Nn(),ie(qp)),Lw=od(),Vz=Lp(),$z=require("lodash"),{getSchemaPath:Yz}=Je(),Cw=We(),{handleHDBError:Kz,hdb_errors:Wz}=ne(),{HTTP_STATUS_CODES:Qz}=Wz,zz=1e8;Mw.exports=Jz;async function Jz(e){let t=kz(e,"conditions");if(t)throw Kz(t,t.message,Qz.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=Yz(e.schema,e.table),n=await Cw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Cw.openDBI(n,_.search_attribute);let i=$z.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===ad.SEARCH_TYPES.EQUALS?_.estimated_count=Gp.count(n,_.search_attribute,_.search_value):l===ad.SEARCH_TYPES.CONTAINS||l===ad.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=zz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Dw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Lw.filterByType),d=l.length,E=Gp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>Vz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Dw(o,e,E,s.hash_attribute);c=c.concat(f)}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=Gp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Jz,"lmdbSearchByConditions");async function Dw(e,t,r,n){let s=new Fz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===ad.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Lw.searchByType(e,s,i,n).map(o=>o.value)}a(Dw,"executeConditionSearch")});var oa=g(($_e,Uw)=>{"use strict";var jz=P().OPERATIONS_ENUM,Fp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=jz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Uw.exports=Fp});var kp=g((K_e,kw)=>{"use strict";var xw=es(),Gw=oa(),qw=Xc(),Fw=Qc(),Er=P(),vw=z(),Bw=We(),{getTransactionAuditStorePath:Xz,getSchemaPath:Zz}=Je(),Hw=$();kw.exports=e2;async function e2(e){try{if(vw.isEmpty(global.hdb_schema[e.schema])||vw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await t2(e),await r2(e);let t=Zz(e.schema,e.table);try{await Bw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Xz(e.schema,e.table);await Bw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(e2,"lmdbDropTable");async function t2(e){let t=new xw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await qw(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new Gw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Fw(s)}a(t2,"deleteAttributesFromSystem");async function r2(e){let t=new xw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await qw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new Gw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Fw(s)}catch(i){throw i}}a(r2,"dropTableFromSystem")});var $w=g((Q_e,Vw)=>{"use strict";var n2=require("fs-extra"),s2=es(),i2=ia(),o2=oa(),a2=kp(),c2=Qc(),u2=Pp(),l2=Xc(),Ns=P(),{getSchemaPath:_2}=Je(),{handleHDBError:d2,hdb_errors:f2}=ne(),{HDB_ERROR_MSGS:E2,HTTP_STATUS_CODES:h2}=f2;Vw.exports=m2;async function m2(e){let t;try{t=await p2(e.schema);let r=new s2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await l2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await a2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new o2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await c2(s);let i=_2(t);await n2.remove(i)}catch(r){throw r}}a(m2,"lmdbDropSchema");async function p2(e){let t=new i2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await u2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw d2(new Error,E2.SCHEMA_NOT_FOUND(e),h2.NOT_FOUND,void 0,void 0,!0);return n}a(p2,"validateDropSchema")});var cd=g((J_e,Yw)=>{"use strict";var Vp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Yw.exports=Vp});var Ww=g((Z_e,Kw)=>{"use strict";var S2=require("fs-extra"),ud=We(),{getTransactionAuditStorePath:T2}=Je(),$p=ft(),X_e=cd();Kw.exports=g2;async function g2(e){let t;try{let r=T2(e.schema,e.table);await S2.mkdirp(r),t=await ud.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{ud.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),ud.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),ud.createDBI(t,$p.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(g2,"createTransactionsAuditEnvironment")});var jw=g((tde,Jw)=>{"use strict";var Yp=P(),Qw=We(),R2=Yo(),{getSystemSchemaPath:A2,getSchemaPath:O2}=Je(),b2=Fi(),y2=I_(),Kp=N_(),N2=$(),I2=Ww(),Qp=b2.hdb_table,zw=[];for(let e=0;e<Qp.attributes.length;e++)zw.push(Qp.attributes[e].attribute);Jw.exports=w2;async function w2(e,t){let r=O2(t.schema,t.table),n=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Kp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Qw.createEnvironment(r,t.table),e!==void 0){let o=await Qw.openEnvironment(A2(),Yp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await R2.insertRecords(o,Qp.hash_attribute,zw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Wp(n),await Wp(s),await Wp(i)}await I2(t)}catch(o){throw o}}a(w2,"lmdbCreateTable");async function Wp(e){try{await y2(e)}catch(t){N2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Wp,"createAttribute")});var Zw=g((nde,Xw)=>{"use strict";var C2=Hc(),D2=Gc(),L2=ed(),Zc=P(),M2=Yo().updateRecords,P2=We(),{getSchemaPath:U2}=Je(),v2=Kc(),B2=$();Xw.exports=H2;async function H2(e){try{let{schema_table:t,attributes:r}=C2(e);D2(e,r,t.hash_attribute),e.schema!==Zc.SYSTEM_SCHEMA_NAME&&(r.includes(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await L2(e.hdb_auth_header,t,r),s=U2(e.schema,e.table),i=await P2.openEnvironment(s,e.table),o=await M2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await v2(e,o)}catch(c){B2.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(H2,"lmdbUpdateRecords")});var tC=g((ide,eC)=>{"use strict";var x2=P().OPERATIONS_ENUM,zp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=x2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};eC.exports=zp});var nC=g((cde,rC)=>{"use strict";var ade=tC(),G2=Hc(),q2=Gc(),F2=ed(),eu=P(),k2=Yo().upsertRecords,V2=We(),{getSchemaPath:$2}=Je(),Y2=Kc(),K2=$(),{handleHDBError:W2,hdb_errors:Q2}=ne();rC.exports=z2;async function z2(e){let t;try{t=G2(e)}catch(u){throw W2(u,u.message,Q2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;q2(e,n,r.hash_attribute),e.schema!==eu.SYSTEM_SCHEMA_NAME&&(n.includes(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await F2(e.hdb_auth_header,r,n),i=$2(e.schema,e.table),o=await V2.openEnvironment(i,e.table),c=await k2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await Y2(e,c)}catch(u){K2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(z2,"lmdbUpsertRecords")});var iC=g((lde,sC)=>{"use strict";var Jp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};sC.exports=Jp});var aC=g((dde,oC)=>{"use strict";var jp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};oC.exports=jp});var lC=g((hde,uC)=>{"use strict";var Xp=We(),{getTransactionAuditStorePath:J2}=Je(),Ede=iC(),tu=ft(),j2=z(),cC=aC(),X2=require("util").promisify,Z2=X2(setTimeout),eJ=1e4,tJ=100;uC.exports=rJ;async function rJ(e){let t=J2(e.schema,e.table),r=await Xp.openEnvironment(t,e.table,!0),n=Xp.listDBIs(r);Xp.initializeDBIs(r,tu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new cC;do s=await nJ(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await Z2(tJ);while(s.transactions_deleted>0);return i}a(rJ,"deleteAuditLogsBefore");async function nJ(e,t){let r=new cC;try{let n=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];j2.isEmpty(c)||(s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>eJ)break}return await s,r}catch(n){throw n}}a(nJ,"deleteTransactions")});var dC=g((pde,_C)=>{"use strict";var Zp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};_C.exports=Zp});var EC=g((gde,fC)=>{"use strict";var sJ=es(),iJ=oa(),Tde=dC(),ts=P(),oJ=z(),eS=We(),aJ=Fi(),cJ=Xc(),uJ=Qc(),{getSchemaPath:lJ}=Je();fC.exports=_J;async function _J(e,t=!0){let r;e.schema===ts.SYSTEM_SCHEMA_NAME?r=aJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await fJ(e),s=lJ(e.schema,e.table),i=await eS.openEnvironment(s,e.table);return t===!0&&await dJ(e,i,r.hash_attribute),eS.dropDBI(i,e.attribute),n}a(_J,"lmdbDropAttribute");async function dJ(e,t,r){let n=eS.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(dJ,"removeAttributeFromAllObjects");async function fJ(e){let t=new sJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await cJ(t)).filter(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(oJ.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new iJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return uJ(i)}a(fJ,"dropAttributeFromSystem")});var gC=g((Ode,TC)=>{"use strict";var tS=We(),aa=ft(),Ade=vr(),rS=P(),hC=z(),{getTransactionAuditStorePath:EJ}=Je(),hJ=na(),ld=ea(),mJ=$();TC.exports=pJ;async function pJ(e){let t=EJ(e.schema,e.table),r=await tS.openEnvironment(t,e.table,!0),n=tS.listDBIs(r);tS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return mC(r,e.search_values);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,TJ(r,e.search_values,s);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return SJ(r,e.search_values);default:return mC(r)}}a(pJ,"readAuditLog");function mC(e,t=[0,Date.now()]){hC.isEmpty(t[0])&&(t[0]=0),hC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new ld,s))}a(mC,"searchTransactionsByTimestamp");function SJ(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,SC(e,i))}return Object.fromEntries(r)}a(SJ,"searchTransactionsByUsername");function TJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=hJ.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=SC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);pC(u,"records",r,l,o),pC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(TJ,"searchTransactionsByHashValues");function pC(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new ld(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new ld(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(pC,"loopRecords");function SC(e,t){let r=[];try{let n=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new ld,i);r.push(o)}}catch(i){mJ.warn(i)}return r}catch(n){throw n}}a(SC,"batchSearchTransactions")});var AC=g((Ide,RC)=>{"use strict";var{getSchemaPath:yde}=Je(),Nde=We(),{database:gJ}=(Ae(),ie(ke));RC.exports={writeTransaction:RJ};async function RJ(e,t,r){return gJ({database:e,table:t}).transaction(r)}a(RJ,"writeTransaction")});var NC=g((Cde,yC)=>{"use strict";var{getSchemaPath:OC}=Je(),bC=We();yC.exports={flush:AJ,resetReadTxn:OJ};async function AJ(e,t){return(await bC.openEnvironment(OC(e,t),t.toString())).flushed}a(AJ,"flush");async function OJ(e,t){try{(await bC.openEnvironment(OC(e,t),t.toString())).resetReadTxn()}catch{}}a(OJ,"resetReadTxn")});var DC=g((Lde,CC)=>{"use strict";var{Readable:bJ}=require("stream"),{getDatabases:yJ}=(Ae(),ie(ke)),{readSync:NJ,openSync:IJ,createReadStream:IC}=require("fs"),{open:wJ}=require("lmdb"),wC=Dc(),CJ=Lc(),{AUDIT_STORE_OPTIONS:DJ}=(ti(),ie(LC)),{INTERNAL_DBIS_NAME:LJ,AUDIT_STORE_NAME:MJ}=ft();CC.exports=UJ;var nS=32768,PJ=100;async function UJ(e){let t=e.database||e.schema||"data",r=yJ()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=wJ({noSync:!0,maxDbs:CJ.MAX_DBS}),E,f=d.openDB(LJ,new wC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,b){b.encoding="binary",b.encoder=void 0;let C=d.openDB(R,b),H=l.openDB(R,b);for(let{key:v,version:F,value:M}of H.getRange({start:null,transaction:h,versions:H.useVersions}))E=C.put(v,M,F),p++%PJ===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(C=>R.startsWith?.(C+"/"))){f.put(R,b);let[,C]=R.split("/"),H=!C,v=new wC(!H,H);await S(R,v)}e.include_audit&&await S(MJ,Object.assign({},DJ)),await E;let T=IC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=IJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(nS);NJ(c,_,0,nS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=IC(null,{fd:c,start:nS}),E=new bJ.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(UJ,"getBackup")});var UC=g((Pde,PC)=>{"use strict";var vJ=$(),{handleHDBError:BJ}=ne(),HJ=Kb(),xJ=I_(),GJ=Np(),qJ=$I(),FJ=Qc(),kJ=Pp(),VJ=mw(),$J=yw(),YJ=Xc(),KJ=Pw(),WJ=$w(),QJ=jw(),zJ=Zw(),JJ=nC(),jJ=lC(),XJ=kp(),ZJ=EC(),e4=gC(),t4=AC(),MC=NC(),r4=DC(),sS=class extends HJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return KJ(t)}async getDataByHash(t){return await kJ(t)}async searchByHash(t){return await VJ(t)}async getDataByValue(t,r){return await $J(t,r)}async searchByValue(t){return await YJ(t)}async createSchema(t){return await qJ(t)}async dropSchema(t){return await WJ(t)}async createTable(t,r){return await QJ(t,r)}async dropTable(t){return await XJ(t)}async createAttribute(t){return await xJ(t)}async createRecords(t){return await GJ(t)}async updateRecords(t){return await zJ(t)}async upsertRecords(t){try{return await JJ(t)}catch(r){throw BJ(r,null,null,vJ.ERR,r)}}async deleteRecords(t){return await FJ(t)}async dropAttribute(t){return await ZJ(t)}async deleteAuditLogsBefore(t){return await jJ(t)}async readAuditLog(t){return await e4(t)}writeTransaction(t,r,n){return t4.writeTransaction(t,r,n)}flush(t,r){return MC.flush(t,r)}resetReadTxn(t,r){return MC.resetReadTxn(t,r)}getBackup(t){return r4(t)}};PC.exports=sS});function o4(){i4=setInterval(function(){for(let e of iS)if(e.stale){let t=e[ye]?.url;xC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},s4).unref()}var oS,HC,xC,GC,qC,FC,vC,iS,n4,ru,BC,to,_d,s4,i4,aS=Re(()=>{oS=B(vr()),HC=B(ne()),xC=B($());Nn();GC=B(Z()),qC=B(P()),FC=B(z()),vC=100,iS=new Set,n4=(0,FC.convertToMS)(GC.get(qC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,to=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),iS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(iS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(ru&&!this.overloadChecked&&performance.now()-BC>n4)throw new HC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,oS.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[f===0?"before":"beforeIntermediate"];if(T){let R=T();h?h.push?h.push(R):h=[h,R]:h=R}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),u=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let E=d.store.ifVersion(d.key,d.entry?.version??null,u);s=s||E}else u();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<vC>>n?u():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return ru||(ru=s,BC=performance.now(),ru.then(()=>{ru=null})),s.then(d=>d?(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}))):(_&&(_.retryRisk=(_.retryRisk||0)+vC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},_d=class extends to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,oS.getNextMonotonicTime)())}getReadTxn(){}},s4=3e4;a(o4,"startMonitoringTxns");o4()});function Ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new to;e.timestamp&&(n.timestamp=e.timestamp),n[ye]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var kC,ro=Re(()=>{kC=require("../index");Nn();aS();a(Ze,"transaction");(0,kC._assignPackageExport)("transaction",Ze);Ze.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ze.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var jC={};Fe(jC,{ResourceBridge:()=>lS});function _S({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 $C(e,t){let r=rs(e),n=_S(e,r);if(!r)throw new Pn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&fd(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function rs(e){let t=e.database||e.schema||c4,r=hr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,a4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function YC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*KC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var WC,dd,Pn,QC,zC,Un,cS,uS,JC,a4,c4,u4,l4,VC,lS,XC=Re(()=>{"use strict";WC=B(UC()),dd=B(sa()),Pn=B(ne());Ae();QC=B(Hc()),zC=B(Gc()),Un=B(P()),cS=B(bs()),uS=B(Mn()),JC=B(z());ro();Ed();({HDB_ERROR_MSGS:a4}=Pn.hdb_errors),c4="data",u4=1e4,l4=10,lS=class extends WC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),VC=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,dd.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=rs(t);if(!n)throw new Pn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:_S(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Pn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}Et({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await rs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=rs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){rs(t).dropTable()}createSchema(t){return nu({database:t.schema,table:null}),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await dS(t.schema),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.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,VC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,QC.default)(t);(0,zC.default)(t,n,r.primaryKey);let s,i=hr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(E=>E.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=fd(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=hr()[t.schema][t.table],n={user:t.hdb_user};return Ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return YC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=hr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,JC.async_set_timeout)(l4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%u4===0&&await _();return u.length>0&&await _(),s?YC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,dd.default)(t,"hashes");if(r)throw r;return $C(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of $C(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,dd.default)(t,"value");if(n)throw n;let s=rs(t);if(!s)throw new Pn.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===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:_S(t,s)})}async getDataByValue(t,r){let n=new Map,s=rs(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){rs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return rs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=rs(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of KC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return KC(r,t.search_values?.[0],t.search_values?.[1])}}};a(_S,"getSelect");a($C,"getRecords");a(rs,"getTable");a(YC,"createDeleteResponse");a(KC,"groupRecordsInHistory")});var Cn=g((Qde,ZC)=>{"use strict";var{ResourceBridge:_4}=(XC(),ie(jC)),d4=Z();d4.initSync();var hd;function f4(){return hd||(hd=new _4,hd)}a(f4,"getBridge");ZC.exports=f4()});var nD=g((Jde,rD)=>{"use strict";var eD=require("lodash"),su=require("mathjs"),E4=require("jsonata"),tD=z();rD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?eD.uniqWith(e,eD.isEqual):e,searchJSON:h4,mad:iu.bind(null,su.mad),mean:iu.bind(null,su.mean),mode:iu.bind(null,su.mode),prod:iu.bind(null,su.prod),median:iu.bind(null,su.median)};function iu(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(iu,"aggregateFunction");function h4(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(tD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),tD.isEmpty(this.__ala__.res[r])){let n=E4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(h4,"searchJSON")});var iD=g((Xde,sD)=>{"use strict";var Rt=require("moment"),fS="YYYY-MM-DDTHH:mm:ss.SSSZZ";Rt.suppressDeprecationWarnings=!0;sD.exports={current_date:()=>Rt().utc().format("YYYY-MM-DD"),current_time:()=>Rt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Rt(e).utc().format("YYYY");case"month":return Rt(e).utc().format("MM");case"day":return Rt(e).utc().format("DD");case"hour":return Rt(e).utc().format("HH");case"minute":return Rt(e).utc().format("mm");case"second":return Rt(e).utc().format("ss");case"millisecond":return Rt(e).utc().format("SSS");default:break}},date:e=>Rt(e).utc().format(fS),date_format:(e,t)=>Rt(e).utc().format(t),date_add:(e,t,r)=>Rt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Rt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Rt(e).utc(),s=Rt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Rt().utc().valueOf(),get_server_time:()=>Rt().format(fS),offset_utc:(e,t)=>Rt(e).utc().utcOffset(t).format(fS)}});var uD=g((Zde,cD)=>{"use strict";var m4=require("@turf/area"),p4=require("@turf/length"),S4=require("@turf/circle"),T4=require("@turf/difference"),g4=require("@turf/distance"),R4=require("@turf/boolean-contains"),A4=require("@turf/boolean-equal"),O4=require("@turf/boolean-disjoint"),b4=require("@turf/helpers"),oD=P(),Se=z(),Is=$();cD.exports={geoArea:y4,geoLength:N4,geoCircle:I4,geoDifference:w4,geoDistance:aD,geoNear:C4,geoContains:D4,geoEqual:L4,geoCrosses:M4,geoConvert:P4};function y4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return m4.default(e)}catch(t){return Is.trace(t,e),NaN}}a(y4,"geoArea");function N4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return p4.default(e,{units:t||"kilometers"})}catch(r){return Is.trace(r,e),NaN}}a(N4,"geoLength");function I4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return S4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(I4,"geoCircle");function w4(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 T4(e,t)}catch(r){return Is.trace(r,e,t),NaN}}a(w4,"geoDifference");function aD(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 g4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(aD,"geoDistance");function C4(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return aD(e,t,n)<=r}catch(s){return Is.trace(s,e,t),!1}}a(C4,"geoNear");function D4(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 R4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(D4,"geoContains");function L4(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 A4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(L4,"geoEqual");function M4(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!O4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(M4,"geoCrosses");function P4(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(oD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(oD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),b4[t](e,r)}a(P4,"geoConvert")});var md=g((tfe,lD)=>{var no=nD(),Kr=iD(),ns=uD();lD.exports=e=>{e.aggr.mad=e.aggr.MAD=no.mad,e.aggr.mean=e.aggr.MEAN=no.mean,e.aggr.mode=e.aggr.MODE=no.mode,e.aggr.prod=e.aggr.PROD=no.prod,e.aggr.median=e.aggr.MEDIAN=no.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=no.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=no.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ns.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ns.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ns.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ns.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ns.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ns.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ns.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ns.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ns.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ns.geoNear}});var ED=g((rfe,fD)=>{"use strict";var ou=require("lodash"),mr=require("alasql");mr.options.cache=!1;var U4=md(),_D=require("clone"),pd=require("recursive-iterator"),_e=$(),De=z(),ca=Cn(),v4=P(),{hdb_errors:B4}=ne(),{getDatabases:dD}=(Ae(),ie(ke)),H4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";U4(mr);var ES=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw _e.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(n),new Error(vn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(n),new Error(vn)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(n),new Error(vn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(n),new Error(vn)}try{return t=await this._finalSQL(),t}catch(n){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(n),new Error(vn)}}_getColumns(){let t=new pd(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(_D(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=ou.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=dD()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new pd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new mr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new mr.yy.LogicValue({value:i}):n instanceof mr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new mr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new pd(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(v4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(De.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&ou.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await mr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(_D(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(H4)>-1&&this.tables.forEach(s=>{let i={columnid:dD()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=ou.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ca.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let E=await ca.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ca.getDataByValue(c,f.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ca.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(vn)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof mr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new mr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new mr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new mr.yy.FuncValue:new mr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,p=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${p}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${p}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";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(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let 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 E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await mr.promise(h,t),t=null}catch(f){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let p=E[f];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),p=ou.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let R=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new pd(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=ou.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(vn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ca.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.get(E);for(let h=0;h<_;h++){let p=s.columns[h],S=f[p]===void 0?null:f[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();_e.trace(`Final SQL: ${s}`),n=await mr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),_e.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return _e.error(B4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ca.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};fD.exports=ES});var Gr=g((sfe,hD)=>{"use strict";var x4=$b();hD.exports={searchByConditions:q4,searchByHash:F4,searchByValue:k4,search:V4};var hS=Cn(),{transformReq:mS}=z(),G4=ED();async function q4(e){return mS(e),hS.searchByConditions(e)}a(q4,"searchByConditions");async function F4(e){mS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of hS.searchByHash(e))r&&t.push(r);return t}a(F4,"searchByHash");async function k4(e){mS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of hS.searchByValue(e))t.push(r);return t}a(k4,"searchByValue");function V4(e,t){try{let r=new x4(e);r.validate(),new G4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(V4,"search")});var Sd=g((ofe,mD)=>{"use strict";var $4=Cn();mD.exports={writeTransaction:Y4};function Y4(e,t,r){return $4.writeTransaction(e,t,r)}a(Y4,"writeTransaction")});var gD=g((ufe,TD)=>{"use strict";var K4=Gr(),W4=Os(),pD=$(),Q4=qr(),cfe=Sd(),z4=require("clone"),SS=require("alasql"),J4=md(),SD=require("util"),j4=SD.promisify(W4.getTableSchema),X4=SD.promisify(K4.search),Z4=P(),pS=z();J4(SS);TD.exports={update:t3};var e3="There was a problem performing this update. Please check the logs and try again.";async function t3({statement:e,hdb_user:t}){let r=await j4(e.table.databaseid,e.table.tableid),n=r3(e.columns);pS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=z4(s),c=pS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=SS.parse(u).statements[0],l=await X4(_),d=n3(n,l);return s3(o,d,t)}a(t3,"update");function r3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=SS.compile(`SELECT ${r.expression.toString()} AS [${Z4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw pD.error(t),new Error(e3)}}a(r3,"createUpdateRecord");function n3(e,t){return pS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(n3,"buildUpdateRecords");async function s3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await Q4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){pD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(s3,"updateRecords")});var AD=g((ffe,RD)=>{var i3=require("alasql"),o3=Gr(),a3=$(),c3=Cn(),gS=require("util"),TS=z(),u3=P(),l3=Os(),_fe=Sd(),dfe=qr(),_3="record",d3="successfully deleted",f3=gS.callbackify(p3),E3=gS.promisify(o3.search),h3=gS.promisify(l3.getTableSchema);RD.exports={convertDelete:f3};function m3(e){return`${e.deleted_hashes.length} ${_3}${e.deleted_hashes.length===1?"":"s"} ${d3}`}a(m3,"generateReturnMessage");async function p3({statement:e,hdb_user:t}){let r=await h3(e.table.databaseid,e.table.tableid);TS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=TS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=i3.parse(o).statements[0],u={operation:u3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await E3(c);let _=await c3.deleteRecords(u);return TS.isEmptyOrZeroLength(_.message)&&(_.message=m3(_)),delete _.txn_time,_}catch(_){throw a3.error(_),_.hdb_code?_.message:_}}a(p3,"convertDelete")});var ID=g((hfe,ND)=>{"use strict";var S3=As(),{hdb_errors:OD}=ne(),{getDatabases:bD}=(Ae(),ie(ke));ND.exports={checkSchemaExists:yD,checkSchemaTableExists:T3,schema_describe:S3};async function yD(e){if(!bD()[e])return OD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(yD,"checkSchemaExists");async function T3(e,t){let r=await yD(e);if(r)return r;if(!bD()[e][t])return OD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(T3,"checkSchemaTableExists")});var au=g((pfe,g3)=>{g3.exports={name:"harperdb",version:"4.3.19",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.535.0","@aws-sdk/lib-storage":"3.535.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.12",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.16.0",yaml:"2.4.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.22.11","newman-reporter-teamcity":"0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var du={};Fe(du,{addAnalyticsListener:()=>_u,recordAction:()=>pr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>R3});function R3(e){BD=e}function pr(e,t,r,n,s){if(!BD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Rd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},Rd.set(i,o)}Td||A3()}function Wr(e,t,r,n,s){pr(!!e,t,r,n,s)}function _u(e){GD.push(e)}function A3(){Td=performance.now(),setTimeout(async()=>{let e=performance.now()-Td;Td=0;let t=[],r={time:Date.now(),period:e,threadId:so.threadId,metrics:t};for(let[s,i]of Rd){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 qD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:f,count:h}:f),l=f;u=E}}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 FD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of GD)s(t);Rd=new Map,so.parentPort?so.parentPort.postMessage({type:xD,report:r}):$D({report:r})},HD).unref()}async function O3(e,t=6e4){let r=OS(),n=kD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,cu.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,cu.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:R}=S;for(let b of T||[]){let{path:C,method:H,type:v,metric:F,count:M,total:Q,distribution:J,threads:j,...ae}=b;M||(M=1);let ce=F+(C?"-"+C:"");H!==void 0&&(ce+="-"+H),v!==void 0&&(ce+="-"+v);let ge=c.get(ce);if(ge){if(ge.threads){let Ne=ge.threads[R];if(Ne)ge=Ne;else{ge.threads[R]=Object.assign({},ae);continue}}ge.count||(ge.count=1);let Ge=ge.count;for(let Ne in ae){let ve=ae[Ne];typeof ve=="number"&&(ge[Ne]=(ge[Ne]*Ge+ve*M)/(Ge+M))}ge.count+=M,Q>=0&&(ge.total+=Q,ge.ratio=ge.total/ge.count)}else ge=Object.assign({period:t},b),delete ge.distribution,c.set(ce,ge),ge.byThread&&(ge.threads=[],ge.threads[R]=Object.assign({},ae),_.push(ge));if(J){J=J.map(Ne=>typeof Ne=="number"?{value:Ne,count:1}:Ne);let Ge=u.get(ce);Ge?Ge.push(...J):u.set(ce,J)}}await FD()}for(let p of _){let{path:S,method:T,type:R,metric:b,count:C,total:H,distribution:v,threads:F,...M}=p;F=F.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let J=0;for(let j of F){let ae=j[Q];typeof ae=="number"&&(J+=ae)}p[Q]=J}p.count=F.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ne,ve)=>Ne.value>ve.value?1:-1);let R=T.count-1,b=[],C=0,H=0,v;for(let Ne of qD){let ve=R*Ne;for(;C<ve;)v=S[H++],C+=v.count,H===1&&C--;let zl=S[H>1?H-2:0];v||(v=S[0]),b.push(v.value-(v.value-zl.value)*(C-ve)/v.count)}let[F,M,Q,J,j,ae,ce,ge,Ge]=b;Object.assign(T,{p1:F,p10:M,p25:Q,median:J,p75:j,p90:ae,p95:ce,p99:ge,p999:Ge})}let d;for(let[p,S]of c)S.id=(0,gd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let p=(0,gd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-wD,active:h-CD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}wD=f,CD=h}async function DD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function OS(){return LD||(LD=Et({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function kD(){return MD||(MD=Et({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function N3(){VD=!0;let e=(0,lu.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await O3(HD,e),await DD(OS(),b3),await DD(kD(),y3)},Math.min(e/2,2147483647)).unref()}function $D(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(PD+=n.mean*n.count);r.totalBytesProcessed=PD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(UD.get(t))}),UD.set(t,t.performance.eventLoopUtilization())),r.id=(0,gd.getNextMonotonicTime)(),OS().primaryStore.put(r.id,r),VD||N3(),I3&&(YD=C3(r))}async function C3(e){if(await YD,!_i){let r=(0,uu.dirname)((0,cu.getLogFilePath)());try{_i=await(0,RS.open)((0,uu.join)(r,"analytics.log"),"r+")}catch{_i=await(0,RS.open)((0,uu.join)(r,"analytics.log"),"w+")}}let t=(await _i.stat()).size;if(t>w3){let r=Buffer.alloc(t);await _i.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await _i.write(r,{position:0}),await _i.truncate(r.length),t=r.length}await _i.write(JSON.stringify(e)+`
8
- `,t)}var so,vD,cu,uu,RS,gd,lu,AS,Rd,BD,Td,HD,xD,GD,qD,wD,CD,FD,b3,y3,LD,MD,VD,PD,UD,I3,YD,_i,w3,ws=Re(()=>{so=require("worker_threads"),vD=B(je());Ae();cu=B($()),uu=require("path"),RS=require("fs/promises"),gd=B(vr()),lu=B(Z()),AS=B(P());ur();(0,lu.initSync)();Rd=new Map,BD=(0,lu.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(R3,"setAnalyticsEnabled");a(pr,"recordAction");it.recordAnalytics=pr;a(Wr,"recordActionBinary");Td=0,HD=1e3,xD="analytics-report",GD=[];a(_u,"addAnalyticsListener");qD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(A3,"sendAnalytics");a(O3,"aggregation");wD=0,CD=0,FD=a(()=>new Promise(setImmediate),"rest");a(DD,"cleanup");b3=36e5,y3=31536e6;a(OS,"getRawAnalyticsTable");a(kD,"getAnalyticsTable");(0,vD.setChildListenerByType)(xD,$D);a(N3,"startScheduledTasks");PD=0,UD=new Map,I3=!1;a($D,"recordAnalytics");w3=1e6;a(C3,"logAnalytics")});var wS=g((Dfe,rL)=>{"use strict";var{decode:D3}=require("msgpackr"),{isMainThread:Ife,parentPort:wfe,threadId:Cfe}=require("worker_threads"),bd=at(),ua=Ve(),NS=P(),tr=$(),yS=Z(),L3=P(),{onMessageByType:M3}=je(),QD=Rs(),{recordAction:P3,recordActionBinary:U3}=(ws(),ie(du)),{publishToStream:v3}=bd,{ConsumerEvents:KD}=require("nats"),B3=Gr(),{promisify:H3}=require("util"),zD=H3(setTimeout),yd=1e4,Nd,Od,x3,G3,JD,fu=new Map,la=new Map;rL.exports={initialize:jD,ingestConsumer:IS,setSubscription:q3,setIgnoreOrigin:V3,getDatabaseSubscriptions:k3,updateConsumer:XD};async function jD(){M3(NS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await XD(n)}),JD=!0,tr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await bd.getNATSReferences();Nd=e,Od=e.info.server_name,x3=t,G3=r}a(jD,"initialize");async function XD(e){if(e.status==="start"){let{js:t,jsm:r}=await ZD(e.node_domain_name);IS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=fu.get(e.stream_name+e.node_domain_name);t&&(tr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),fu.set(e.stream_name+e.node_domain_name,"close")),la.get(e.node_domain_name)==="failed"&&la.set(e.node_domain_name,"close")}}a(XD,"updateConsumer");var Id=new Map;function q3(e,t,r){let n=Id.get(e);n||Id.set(e,n=new Map),n.set(t,r),JD||jD().then(F3)}a(q3,"setSubscription");async function F3(){let e=await B3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+ua.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await ZD(r),!n))break;let{schema:o,table:c}=i,u=QD.createNatsTableStreamName(o,c);IS(u,n,s,r)}}}a(F3,"accessConsumers");async function ZD(e){let t,r,n=1;for(;!r;)try{t=await Nd.jetstream({domain:e}),r=await Nd.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(la.get(e)==="close")break;la.set(e,"failed"),n%10===1&&tr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<yd?n++*100:yd;await zD(i)}return{js:t,jsm:r}}a(ZD,"connectToRemoteJS");function k3(){return Id}a(k3,"getDatabaseSubscriptions");var eL;function V3(e){eL=e}a(V3,"setIgnoreOrigin");var tL=100,WD=new Array(tL),Ad=0;async function IS(e,t,r,n){let{connection:s}=await bd.getNATSReferences();Nd=s,Od=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,Od),tr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(la.get(n)==="close")break;o%10===1&&tr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(tr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await bd.createConsumer(r,e,Od,new Date(Date.now()).toISOString()));let l=o++*100<yd?o++*100:yd;await zD(l)}let c=!1,u;for(;!c;){if(fu.get(e+n)==="close"||la.get(n)==="close"){fu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:yS.get(NS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),fu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===KD.ConsumerDeleted&&(await u.close(),c=!0),l.type===KD.HeartbeatsMissed){let d=l.data;tr.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===100&&(tr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await WD[Ad],WD[Ad]=$3(l).catch(d=>{tr.error(d)}),++Ad>=tL&&(Ad=0)}catch(l){l.message==="consumer deleted"?(tr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):tr.error("Error consuming clustering ingest, restarting consumer",l)}}}a(IS,"ingestConsumer");async function $3(e){let t=D3(e.data);P3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),tr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=yS.get(NS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(ua.MSG_HEADERS.TRANSACTED_NODES)&&r.values(ua.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(ua.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!eL),U3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(ua.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:E,expiresAt:f}=t;tr.trace("processing message:",o,c,_,(l?"records: "+l.map(C=>C?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),tr.trace(`messageProcessor nats msg id: ${e.headers.get(ua.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(C=>h=C),{timestamp:S,user:T,node_name:R}=E||{},b=Id.get(c)?.get(_);if(!b)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,b.send(t);else if(l.length===1&&!u)b.send({type:bS(o),value:l[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:T,nodeName:R});else{let C=l.map((H,v)=>({type:bS(o),value:H,expiresAt:f,id:d?.[v],table:_}));for(;u;)C.push({type:bS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;b.send({type:"transaction",writes:C,table:_,timestamp:S,onCommit:h,user:T,nodeName:R})}yS.get(L3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&v3(e.subject.split(".").slice(0,-1).join("."),QD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){tr.error(o)}e.ack()}a($3,"messageProcessor");function bS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(bS,"convertOperation")});var at=g((Hfe,TL)=>{"use strict";var Bt=Z();Bt.initSync();var Y3=require("fs-extra"),K3=require("semver"),mu=require("path"),{monotonicFactory:W3}=require("ulidx"),sL=W3(),Q3=require("util"),iL=require("child_process"),z3=Q3.promisify(iL.exec),J3=iL.spawn,Yt=Ve(),Ie=P(),wd=z(),Bn=$(),Cd=Rs(),j3=Sd(),Eu=fr(),{broadcast:X3,onMessageByType:Z3,getWorkerIndex:ej}=je(),{isMainThread:oL}=require("worker_threads"),{Encoder:tj,decode:MS}=require("msgpackr"),aL=new tj,{isEmpty:co}=wd,cL=ln(),Mfe=48*36e11;oL&&Z3(Ie.ITC_EVENT_TYPES.RESTART,()=>{Sr=void 0,ao=void 0});var{connect:rj,StorageType:nj,RetentionPolicy:sj,AckPolicy:PS,DeliverPolicy:US,DiscardPolicy:ij,NatsConnection:Pfe,JetStreamManager:Ufe,JetStreamClient:vfe,StringCodec:Bfe,JSONCodec:oj,createInbox:vS,headers:aj,ErrorCode:nL}=require("nats"),{PACKAGE_ROOT:cj}=P(),uj=au(),{recordAction:lj}=(ws(),ie(du)),uL=oj(),_j="clustering",dj=uj.engines[Yt.NATS_SERVER_NAME],fj=mu.join(cj,"dependencies"),LS=mu.join(fj,`${process.platform}-${process.arch}`,Yt.NATS_BINARY_NAME),CS,DS,hu,io,oo;TL.exports={runCommand:lL,checkNATSServerInstalled:Ej,createConnection:BS,getConnection:pu,getJetStreamManager:Su,getJetStream:dL,getNATSReferences:ss,getServerList:mj,createLocalStream:HS,listStreams:fL,deleteLocalStream:pj,getServerConfig:_a,listRemoteStreams:Sj,viewStream:Tj,viewStreamIterator:gj,publishToStream:Rj,request:bj,reloadNATS:xS,reloadNATSHub:yj,reloadNATSLeaf:Nj,extractServerName:Oj,requestErrorHandler:Ij,createLocalTableStream:pL,createTableStreams:Dj,purgeTableStream:SL,purgeSchemaTableStreams:Lj,getStreamInfo:Mj,updateLocalStreams:Uj,closeConnection:hj,getJsmServerName:Dd,addNatsMsgHeader:EL,clearClientCache:_L,updateRemoteConsumer:wj,createConsumer:hL,updateConsumerIterator:Cj};async function lL(e,t=void 0){let{stdout:r,stderr:n}=await z3(e,{cwd:t});if(n)throw new Error(n.replace(`
6
+ `)},rK="certificate.pem",nK="privateKey.pem",sK="ca.pem";LN.exports={CERTIFICATE_VALUES:tK,CERTIFICATE_PEM_NAME:rK,PRIVATEKEY_PEM_NAME:nK,CA_PEM_NAME:sK}});var np=g((hle,xN)=>{"use strict";var BN=require("fs-extra"),oe=require("joi"),iK=require("os"),{boolean:be,string:er,number:rt,array:K_}=oe.types(),{totalmem:PN}=require("os"),Qi=require("path"),oK=$(),W_=z(),Ele=MN(),UN=P(),aK=Xe(),vN="log",cK="components",uK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",lK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",_K="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",dK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",fK="rootPath config parameter is undefined",EK="clustering.enabled config parameter is undefined",zi=rt.min(0).required(),Q_=K_.items({host:er.required(),port:zi}).empty(null),Xn,HN=!1;xN.exports={configValidator:hK,routesValidator:RK,route_constraints:Q_};function hK(e,t=!1){if(HN=t,Xn=e.rootPath,W_.isEmpty(Xn))throw fK;let r=be.required(),n=rt.min(0).max(1e3).empty(null).default(gK),s=er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Yc),i=er.optional().empty(null),o=er.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(Yc),u=oe.custom(pK).empty(null).default(Yc),_=e.clustering?.enabled;if(W_.isEmpty(_))throw EK;let l=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:zi,routes:Q_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:zi}).required()}).required(),network:oe.object({port:zi}).required()}).required(),leafServer:oe.object({network:oe.object({port:zi,routes:Q_}).required(),streams:oe.object({maxAge:rt.min(120).allow(null).optional(),maxBytes:rt.min(1).allow(null).optional(),maxMsgs:rt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:er.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:rt.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:rt}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:er.custom(TK).optional().empty(null),maxSize:er.custom(SK).optional().empty(null),path:er.optional().empty(null).default(Yc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:K_.optional(),headersTimeout:rt.min(1).optional(),keepAliveTimeout:rt.min(1).optional(),port:rt.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Yc),securePort:rt.optional().empty(null),timeout:rt.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:zi,securePort:zi,mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:rt.optional(),cors:be.optional(),corsAccessList:K_.optional(),headersTimeout:rt.min(1).optional(),port:rt.min(0).optional().empty(null),securePort:rt.min(0).optional().empty(null),maxHeaderSize:rt.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})]),threadRange:oe.alternatives([K_.optional(),er.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:rt.min(1).optional(),host:er.optional(),waitForDebugger:be.optional()})),maxHeapMemory:rt.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:er.optional(),threshold:rt.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:rt.optional(),maxFreeSpaceToRetain:rt.optional()}).required(),ignoreScripts:be.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(hK,"configValidator");function mK(e){return HN||BN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(mK,"doesPathExist");function pK(e,t){oe.assert(e,er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=mK(e);if(r)return t.message(r)}a(pK,"validatePath");function SK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(uK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(_K):e}a(SK,"validateRotationMaxSize");function TK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(lK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(dK):e}a(TK,"validateRotationInterval");function gK(e,t){let r=t.state.path.join("."),n=iK.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||PN();return i=Math.round(Math.min(i,PN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),oK.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(gK,"setDefaultThreads");function Yc(e,t){let r=t.state.path.join(".");if(!W_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(W_.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Qi.join(Xn,cK);case"logging.root":return Qi.join(Xn,vN);case"clustering.leafServer.streams.path":return Qi.join(Xn,"clustering","leaf");case"storage.path":let n=Qi.join(Xn,UN.LEGACY_DATABASES_DIR_NAME);return BN.existsSync(n)?n:Qi.join(Xn,UN.DATABASES_DIR_NAME);case"logging.rotation.path":return Qi.join(Xn,vN);case"operationsApi.network.domainSocket":return r==null?null:Qi.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Yc,"setDefaultRoot");function RK(e){let t=oe.object({routes:Q_});return aK.validateBySchema({routes:e},t)}a(RK,"routesValidator")});var Er=g((Sle,WN)=>{"use strict";var kr=P(),Bt=z(),It=$(),{configValidator:AK,routesValidator:GN}=np(),fr=require("fs-extra"),OK=require("yaml"),Dn=require("path"),bK=require("is-number"),FN=require("properties-reader"),yK=require("lodash"),{handleHDBError:NK}=ne(),{HTTP_STATUS_CODES:IK,HDB_ERROR_MSGS:z_}=Ur(),ple=require("minimist"),{server:wK}=(lr(),ie(xi)),{DATABASES_PARAM_CONFIG:Kc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,CK="Unable to get config value because config is uninitialized",DK="Config successfully initialized",LK="Error backing up config file",MK="Empty parameter sent to getConfigValue",kN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),PK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",qN={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"},J_,wt,j_;WN.exports={createConfigFile:UK,getDefaultConfig:vK,getConfigValue:$N,initConfig:ip,flattenConfig:Qo,updateConfigValue:YN,updateConfigObject:HK,getConfiguration:qK,setConfiguration:FK,readConfigFile:ap,getClusteringRoutes:kK,initOldConfig:KN,getConfigFromFile:VK,getConfigFilePath:Ji,addConfig:$K,deleteConfigFromFile:YK,getConfigObj:KK};function UK(e,t=!1){let r=ci(kN);J_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=sp(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){It.error(d)}}}n&&VN(r,n),op(r,t);let s=r.toJSON();wt=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);fr.createFileSync(o),fr.writeFileSync(o,String(r)),It.trace(`Config file written to ${o}`)}a(UK,"createConfigFile");function VN(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Bt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Kc.TABLES))for(let i in n[s][Kc.TABLES])for(let o in n[s][Kc.TABLES][i]){let c=n[s][Kc.TABLES][i][o],u=[Fr.DATABASES,s,Kc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Fr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){It.error("Error parsing schemas CLI/env config arguments",n)}}a(VN,"setSchemasConfig");function vK(e){if(J_===void 0){let r=ci(kN);J_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return J_[t.toLowerCase()]}a(vK,"getDefaultConfig");function $N(e){if(e==null){It.error(MK);return}if(wt===void 0){It.trace(CK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return wt[t.toLowerCase()]}a($N,"getConfigValue");function Ji(e=Bt.getPropsFilePath()){let t=Bt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):FN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ji,"getConfigFilePath");function ip(e=!1){if(wt===void 0||e){let t;if(!Bt.noBootFile()){t=Bt.getPropsFilePath();try{fr.accessSync(t,fr.constants.F_OK|fr.constants.R_OK)}catch(i){throw It.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ji(t),n;if(r.includes("config/settings.js"))try{KN(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ci(r)}catch(i){if(i.code===kr.NODE_ERROR_CODES.ENOENT){It.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 It.error(i),new Error(`Error reading HarperDB config file at ${r}`)}BK(n,r),op(n);let s=n.toJSON();if(wK.config=s,wt=Qo(s),wt.logging_rotation_rotate)for(let i in qN)wt[i]&&It.error(`Config ${qN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);It.trace(DK)}}a(ip,"initConfig");function BK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(It.trace("Updating config file with missing config params"),fr.writeFileSync(t,String(e)))}a(BK,"checkForUpdatedConfig");function op(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=AK(r,t);if(n.error)throw z_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(op,"validateConfig");function HK(e,t){wt===void 0&&(wt={});let r=Ln[e.toLowerCase()];if(r===void 0){It.trace(`Unable to update config object because config param '${e}' does not exist`);return}wt[r.toLowerCase()]=t}a(HK,"updateConfigObject");function YN(e,t,r=void 0,n=!1,s=!1,i=!1){wt===void 0&&ip();let o=$N(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ci(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=sp(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===wt[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===wt[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=sp(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){It.error(T)}}}_&&VN(u,_),op(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&xK(c,l),fr.writeFileSync(d,String(u)),s&&(wt=Qo(u.toJSON())),It.trace(`Config parameter: ${e} updated with value: ${t}`)}a(YN,"updateConfigValue");function xK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);fr.copySync(e,r),It.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){It.error(LK),It.error(r)}}a(xK,"backupConfigFile");var GK=["databases"];function Qo(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)),j_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!GK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function sp(e,t){if(e===Fr.CLUSTERING_NODENAME||e===Fr.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(bK(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(sp,"castConfigValue");function qK(){let e=Bt.getPropsFilePath(),t=Ji(e);return ci(t).toJSON()}a(qK,"getConfiguration");async function FK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return YN(void 0,void 0,s,!0),PK}catch(i){throw typeof i=="string"||i instanceof String?NK(i,i,IK.BAD_REQUEST,void 0,void 0,!0):i}}a(FK,"setConfiguration");function ap(){let e=Bt.getPropsFilePath();try{fr.accessSync(e,fr.constants.F_OK|fr.constants.R_OK)}catch(n){if(!Bt.noBootFile())throw It.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ji(e);return ci(t).toJSON()}a(ap,"readConfigFile");function ci(e){return OK.parseDocument(fr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ci,"parseYamlDoc");function kK(){let e=ap(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Bt.isEmptyOrZeroLength(t)?[]:t;let r=GN(t);if(r)throw z_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Bt.isEmptyOrZeroLength(n)?[]:n;let s=GN(n);if(s)throw z_.CONFIG_VALIDATION(s.message);if(!Bt.isEmptyOrZeroLength(n)&&!Bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.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 z_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(kK,"getClusteringRoutes");function KN(e){let t=FN(e);wt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Bt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?wt[s]=Dn.dirname(n):wt[s]=n}return wt}a(KN,"initOldConfig");function VK(e){let t=ap();return yK.get(t,e.replaceAll("_","."))}a(VK,"getConfigFromFile");async function $K(e,t){let r=ci(Ji());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await fr.writeFile(Ji(),String(r))}a($K,"addConfig");function YK(e){let t=Ji(Bt.getPropsFilePath()),r=ci(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);fr.writeFileSync(s,String(r))}a(YK,"deleteConfigFromFile");function KK(){return j_||(ip(),j_)}a(KK,"getConfigObj")});var zN=g((gle,QN)=>{"use strict";var X_=P(),Z_=class{static{a(this,"BaseLicense")}constructor(t=0,r=X_.RAM_ALLOCATION_ENUM.DEFAULT,n=X_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},cp=class extends Z_{static{a(this,"ExtendedLicense")}constructor(t=0,r=X_.RAM_ALLOCATION_ENUM.DEFAULT,n=X_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};QN.exports={BaseLicense:Z_,ExtendedLicense:cp}});var ji=g((Ale,tI)=>{"use strict";var Jo=require("fs-extra"),jN=Y_(),XN=require("crypto"),WK=require("moment"),QK=require("uuid").v4,tr=$(),lp=require("path"),zK=z(),ui=P(),{totalmem:JN}=require("os"),JK=zN().ExtendedLicense,zo="invalid license key format",jK="061183",XK="mofi25",ZK="aes-256-cbc",eW=16,tW=32,ZN=Z();ZN.initSync();var up;tI.exports={validateLicense:eI,generateFingerPrint:nW,licenseSearch:fp,getLicense:oW,checkMemoryLimit:aW};function _p(){return lp.join(ZN.getHdbBasePath(),ui.LICENSE_KEY_DIR_NAME,ui.LICENSE_FILE_NAME)}a(_p,"getLicenseDirPath");function rW(){let e=_p();return lp.join(e,ui.LICENSE_FILE_NAME)}a(rW,"getLicenseFilePath");function dp(){let e=_p();return lp.join(e,ui.REG_KEY_FILE_NAME)}a(dp,"getFingerPrintFilePath");async function nW(){let e=dp();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await sW();throw tr.error(`Error writing fingerprint file to ${e}`),tr.error(t),new Error("There was an error generating the fingerprint")}}a(nW,"generateFingerPrint");async function sW(){let e=QK(),t=jN.hash(e),r=dp();try{await Jo.mkdirp(_p()),await Jo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw tr.error(`Error writing fingerprint file to ${r}`),tr.error(n),new Error("There was an error generating the fingerprint")}return t}a(sW,"writeFingerprint");function eI(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ui.RAM_ALLOCATION_ENUM.DEFAULT,version:ui.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return tr.error("empty license key passed to validate."),r;let n=dp(),s=!1;try{s=Jo.statSync(n)}catch(i){tr.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{tr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(XK),c=o[1];c=Buffer.concat([Buffer.from(c)],eW);let u=Buffer.concat([Buffer.from(i)],tW),_=XN.createDecipheriv(ZK,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 f=iW(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),tr.error(zo),new Error(zo)}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(zo),tr.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<WK().valueOf()&&(r.valid_date=!1),jN.validate(o[1],`${jK}${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||tr.error("Invalid licence"),r}a(eI,"validateLicense");function iW(e,t){try{let r=XN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{tr.warn("Check old license failed")}}a(iW,"checkOldLicense");function fp(){let e=new JK,t=[];try{t=Jo.readFileSync(rW(),"utf-8").split(ui.NEW_LINE)}catch(r){r.code==="ENOENT"?tr.info("no license file found"):tr.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(zK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=eI(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){tr.error("There was an error parsing the license string."),tr.error(s),e.ram_allocation=ui.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return up=e,e}a(fp,"licenseSearch");async function oW(){return up||await fp(),up}a(oW,"getLicense");function aW(){let e=fp().ram_allocation,t=process.constrainedMemory?.()||JN();if(t=Math.round(Math.min(t,JN())/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(aW,"checkMemoryLimit")});var ln=g((Ile,pI)=>{"use strict";var iI="username is required",oI="nothing to update, must supply active, role or password to update",aI="password cannot be an empty string",cI="If role is specified, it cannot be empty.",uI="active must be true or false";pI.exports={addUser:mW,alterUser:pW,dropUser:TW,getSuperUser:OW,userInfo:gW,listUsers:td,listUsersExternal:RW,setUsersToGlobal:Xo,findAndValidateUser:hI,getClusterUser:bW,USERNAME_REQUIRED:iI,ALTERUSER_NOTHING_TO_UPDATE:oI,EMPTY_PASSWORD:aI,EMPTY_ROLE:cI,ACTIVE_BOOLEAN:uI};var lI=qr(),cW=ai(),mp=Y_(),_I=wN(),dI=Gr(),pp=ys(),Vr=z(),fI=require("validate.js"),Oe=$(),{promisify:uW}=require("util"),Sp=As(),rI=P(),nI=Ve(),lW=Er(),ble=Z(),yle=ji(),_W=ki(),{table:Nle}=(Ae(),ie(ke)),{handleHDBError:Zn,hdb_errors:dW}=ne(),{HTTP_STATUS_CODES:es,AUTHENTICATION_ERROR_MSGS:Ep,HDB_ERROR_MSGS:jo}=dW,{UserEventMsg:Tp}=Mn(),hp=require("lodash"),{server:gp}=(lr(),ie(xi)),fW=$();gp.getUser=(e,t)=>hI(e,t,t!=null);var EI={username:!0,active:!0,role:!0,password:!0},sI=new Map,ed=dI.searchByValue,EW=dI.searchByHash,hW=uW(cW.delete);async function mW(e){let t=fI.cleanAttributes(e,EI),r=_I.addUserValidation(t);if(r)throw Zn(new Error,r.message,es.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await ed(n),s=s&&Array.from(s)}catch(u){throw Oe.error("There was an error searching for a role in add user"),Oe.error(u),u}if(!s||s.length<1)throw Zn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),es.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Zn(new Error,jo.DUP_ROLES_FOUND(t.role),es.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=Sp.encrypt(t.password)),t.password=mp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await lI.insert(i)}catch(u){throw Oe.error("There was an error searching for a user."),Oe.error(u),u}Oe.debug(o);try{await Xo()}catch(u){throw Oe.error("Got an error setting users to global"),Oe.error(u),u}if(o.skipped_hashes.length===1)throw Zn(new Error,jo.USER_ALREADY_EXISTS(t.username),es.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],pp.signalUserChange(new Tp(process.pid)),`${c.username} successfully added`}a(mW,"addUser");async function pW(e){let t=fI.cleanAttributes(e,EI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(iI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(oI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(aI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(uI);let r=SW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Sp.encrypt(t.password)),t.password=mp.hash(t.password)),t.role==="")throw new Error(cI);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 ed(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),Zn(new Error,c,es.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),Zn(new Error,c,es.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await lI.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await Xo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return pp.signalUserChange(new Tp(process.pid)),s}a(pW,"alterUser");function SW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(SW,"isClusterUser");async function TW(e){try{let t=_I.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 Zn(new Error,jo.USER_NOT_EXIST(e.username),es.NOT_FOUND,void 0,void 0,!0);let n;try{n=await hW(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await Xo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return pp.signalUserChange(new Tp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(TW,"dropUser");async function gW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=hp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await EW(r)}catch(s){throw Oe.error("Got an error searching for a role."),Oe.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Oe.error(r),r}return t}a(gW,"userInfo");async function RW(){let e;try{e=await td()}catch(t){throw Oe.error("Got an error listing users."),Oe.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(RW,"listUsersExternal");async function td(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await ed(e)}catch(o){throw Oe.error("Got an error searching for roles."),Oe.error(o),o}let r={};for(let o of t)r[o.id]=hp.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await ed(n)}catch(o){throw Oe.error("Got an error searching for users."),Oe.error(o),o}let i=new Map;for(let o of s)o=hp.cloneDeep(o),o.role=r[o.role],AW(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),Vr.errorizeMessage(e)}return null}a(td,"listUsers");function AW(e){try{if(!e){Oe.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(_W)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Oe.error("Got an error trying to set system permissions."),Oe.error(t)}}a(AW,"appendSystemTablesToRole");async function Xo(){try{let e=await td();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(Xo,"setUsersToGlobal");async function hI(e,t,r=!0){global.hdb_users||await Xo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Zn(new Error,Ep.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Zn(new Error,Ep.USER_INACTIVE,es.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(sI.get(t)===n.password)return s;if(mp.validate(n.password,t))sI.set(t,n.password);else throw Zn(new Error,Ep.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}return s}a(hI,"findAndValidateUser");async function OW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(OW,"getSuperUser");async function bW(){let e=await td(),t=lW.getConfigFromFile(rI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===rI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Sp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+nI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+nI.SERVER_SUFFIX.ADMIN,r}a(bW,"getClusterUser");var mI=[];gp.invalidateUser=function(e){for(let t of mI)try{t(e)}catch(r){fW.error("Error invalidating user",r)}};gp.onInvalidatedUser=function(e){mI.push(e)}});var Qc=g((Lle,RI)=>{"use strict";var Xi=$(),$r=P(),yW=zy(),Cle=bs(),Dle=Os(),NW=ln(),{validateEvent:SI}=Mn(),Wc=Cn(),IW=require("process"),{resetDatabases:wW}=(Ae(),ie(ke)),CW={[$r.ITC_EVENT_TYPES.SCHEMA]:DW,[$r.ITC_EVENT_TYPES.USER]:gI};async function DW(e){let t=SI(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await yW(e.message),await LW(e.message)}a(DW,"schemaHandler");async function LW(e){try{Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=wW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(LW,"syncSchemaMetadata");var TI=[];async function gI(e){try{try{Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Xi.warn(r)}let t=SI(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${$r.HDB_ITC_CLIENT_PREFIX}${IW.pid} received user event:`,e),await NW.setUsersToGlobal();for(let r of TI)r()}catch(t){Xi.error(t)}}a(gI,"userHandler");gI.addListener=function(e){TI.push(e)};RI.exports=CW});var Mn=g((Hle,OI)=>{"use strict";var Ple=$(),Rp=z(),MW=P(),{ITC_ERRORS:zc}=Ur(),{parentPort:Ule,threadId:PW,isMainThread:UW,workerData:vle}=require("worker_threads"),{onMessageFromWorkers:vW,broadcast:Ble,broadcastWithAcknowledgement:BW}=We();OI.exports={sendItcEvent:HW,validateEvent:AI,SchemaEventMsg:xW,UserEventMsg:GW};var rd;vW(async(e,t)=>{rd=rd||Qc(),AI(e),rd[e.type]&&await rd[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function HW(e){return!UW&&e.message&&(e.message.originator=PW),BW(e)}a(HW,"sendItcEvent");function AI(e){if(typeof e!="object")return zc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Rp.isEmpty(e.type))return zc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Rp.isEmpty(e.message))return zc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Rp.isEmpty(e.message.originator))return zc.MISSING_ORIGIN;if(MW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return zc.INVALID_EVENT(e.type)}a(AI,"validateEvent");function xW(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(xW,"SchemaEventMsg");function GW(e){this.originator=e}a(GW,"UserEventMsg")});var ys=g((qle,II)=>{"use strict";var bI=P(),Gle=z(),nd=$(),yI=Ky(),Zo,{sendItcEvent:NI}=Mn();function qW(e){try{nd.trace("signalSchemaChange called with message:",e),Zo=Zo||Qc();let t=new yI(bI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),NI(t)}catch(t){nd.error(t)}}a(qW,"signalSchemaChange");function FW(e){try{nd.trace("signalUserChange called with message:",e),Zo=Zo||Qc();let t=new yI(bI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),NI(t)}catch(t){nd.error(t)}}a(FW,"signalUserChange");II.exports={signalSchemaChange:qW,signalUserChange:FW}});var sd=g((kle,CI)=>{"use strict";var wI=z(),kW=P(),VW=$(),$W=M_(),YW=L_(),KW=ys(),{SchemaEventMsg:WW}=Mn(),QW="already exists in";CI.exports=zW;async function zW(e,t,r){if(wI.isEmptyOrZeroLength(r))return r;let n=[];wI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await JW(e,t.schema,t.name,i)})),s}a(zW,"lmdbCheckForNewAttributes");async function JW(e,t,r,n){let s=new YW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await jW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(QW))VW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(JW,"createNewAttribute");async function jW(e){let t;return t=await $W(e),KW.signalSchemaChange(new WW(process.pid,kW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(jW,"createAttribute")});var ea=g(($le,DI)=>{"use strict";var Ap=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};DI.exports=Ap});var MI=g((Kle,LI)=>{"use strict";var XW=ea(),ZW=P().OPERATIONS_ENUM,Op=class extends XW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(ZW.INSERT,r,n,s,i),this.records=t}};LI.exports=Op});var UI=g((Qle,PI)=>{"use strict";var eQ=ea(),tQ=P().OPERATIONS_ENUM,bp=class extends eQ{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(tQ.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};PI.exports=bp});var BI=g((Jle,vI)=>{"use strict";var rQ=ea(),nQ=P().OPERATIONS_ENUM,yp=class extends rQ{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(nQ.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};vI.exports=yp});var xI=g((Xle,HI)=>{"use strict";var sQ=ea(),iQ=P().OPERATIONS_ENUM,Np=class extends sQ{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(iQ.DELETE,n,s,t,i),this.original_records=r}};HI.exports=Np});var Jc=g((t_e,kI)=>{"use strict";var e_e=require("path"),GI=Qe(),oQ=MI(),aQ=UI(),cQ=BI(),uQ=xI(),ta=ft(),qI=z(),{CONFIG_PARAMS:lQ}=P(),FI=Z();FI.initSync();var id=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:_Q}=je();kI.exports=dQ;async function dQ(e,t){if(FI.get(lQ.LOGGING_AUDITLOG)===!1)return;let r=_Q(e.schema,e.table),n=await GI.openEnvironment(r,e.table,!0),s=fQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){GI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),qI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(dQ,"writeTransaction");function fQ(e,t){let r=qI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===id.INSERT)return new oQ(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.UPDATE)return new aQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.UPSERT)return new cQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.DELETE)return new uQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(fQ,"createTransactionObject")});var Ip=g((s_e,VI)=>{"use strict";var EQ=qc(),n_e=Fc(),jc=P(),hQ=kc(),mQ=Yo().insertRecords,pQ=Qe(),SQ=$(),TQ=sd(),{getSchemaPath:gQ}=je(),RQ=Jc();VI.exports=AQ;async function AQ(e){try{let{schema_table:t,attributes:r}=EQ(e);hQ(e,r,t.hash_attribute),e.schema!==jc.SYSTEM_SCHEMA_NAME&&(r.includes(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await TQ(e.hdb_auth_header,t,r),s=gQ(e.schema,e.table),i=await pQ.openEnvironment(s,e.table),o=await mQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await RQ(e,o)}catch(c){SQ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(AQ,"lmdbCreateRecords")});var KI=g((o_e,YI)=>{"use strict";var $I=P(),OQ=Ip(),bQ=Fc(),yQ=require("fs-extra"),{getSchemaPath:NQ}=je();YI.exports=IQ;async function IQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new bQ($I.SYSTEM_SCHEMA_NAME,$I.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await OQ(r),await yQ.mkdirp(NQ(e.schema))}a(IQ,"lmdbCreateSchema")});var QI=g((c_e,WI)=>{"use strict";var wp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};WI.exports=wp});var XI=g((f_e,jI)=>{"use strict";var zI=Qe(),Cp=vr(),Dp=Ur().LMDB_ERRORS_ENUM,wQ=ft(),JI=$(),l_e=z(),CQ=require("lmdb"),DQ=QI(),LQ=P(),{OVERFLOW_MARKER:__e,MAX_SEARCH_KEY_LENGTH:d_e}=wQ,MQ=LQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function PQ(e,t,r,n){if(Cp.validateEnv(e),t===void 0)throw new Error(Dp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Dp.IDS_REQUIRED):new Error(Dp.IDS_MUST_BE_ITERABLE);try{let s=zI.listDBIs(e);zI.initializeDBIs(e,t,s);let i=new DQ,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[MQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,CQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let R=e.dbis[T],b=h[T];if(b!=null)try{let C=Cp.getIndexedValues(b);if(C)for(let H=0,v=C.length;H<v;H++)R.remove(C[H],o)}catch{JI.warn(`cannot delete from attribute: ${T}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){JI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=Cp.getNextMonotonicTime(),i}catch(s){throw s}}a(PQ,"deleteRecords");jI.exports={deleteRecords:PQ}});var Xc=g((h_e,ew)=>{"use strict";var ra=z(),UQ=XI(),vQ=Qe(),{getSchemaPath:BQ}=je(),HQ=Jc(),xQ=$();ew.exports=GQ;async function GQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return ZI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=BQ(e.schema,e.table),i=await vQ.openEnvironment(s,e.table),o=await UQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await HQ(e,o)}catch(c){xQ.error(`unable to write transaction due to ${c.message}`)}return ZI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(GQ,"lmdbDeleteRecords");function ZI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(ZI,"createDeleteResponse")});var Mp=g((S_e,tw)=>{"use strict";var qQ=P(),p_e=vr();function Lp(e,t){let r=Object.create(null);if(t.length===1&&qQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(Lp,"parseRow");function FQ(e,t,r,n){let s=Lp(r,e);n.push(s)}a(FQ,"searchAll");function kQ(e,t,r,n){let s=Lp(r,e);n[t]=s}a(kQ,"searchAllToMap");function VQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(VQ,"iterateDBI");function Zi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Zi,"pushResults");function $Q(e,t,r,n,s,i){t.toString().endsWith(e)&&Zi(t,r,n,s,i)}a($Q,"endsWith");function YQ(e,t,r,n,s,i){t.toString().includes(e)&&Zi(t,r,n,s,i)}a(YQ,"contains");function KQ(e,t,r,n,s,i){t>e&&Zi(t,r,n,s,i)}a(KQ,"greaterThanCompare");function WQ(e,t,r,n,s,i){t>=e&&Zi(t,r,n,s,i)}a(WQ,"greaterThanEqualCompare");function QQ(e,t,r,n,s,i){t<e&&Zi(t,r,n,s,i)}a(QQ,"lessThanCompare");function zQ(e,t,r,n,s,i){t<=e&&Zi(t,r,n,s,i)}a(zQ,"lessThanEqualCompare");tw.exports={parseRow:Lp,searchAll:FQ,searchAllToMap:kQ,iterateDBI:VQ,endsWith:$Q,contains:YQ,greaterThanCompare:KQ,greaterThanEqualCompare:WQ,lessThanCompare:QQ,lessThanEqualCompare:zQ,pushResults:Zi}});var na=g((O_e,cw)=>{"use strict";var li=Qe(),g_e=$(),Yr=vr(),od=ft(),ht=Ur().LMDB_ERRORS_ENUM,R_e=z(),JQ=P(),ad=Mp(),{parseRow:jQ}=ad,A_e=require("lmdb"),{OVERFLOW_MARKER:rw,MAX_SEARCH_KEY_LENGTH:XQ}=od;function nw(e,t,r,n=!1,s=void 0,i=void 0){return eo(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(nw,"iterateFullIndex");function Zc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return eo(e,t,r,(l,d,E,f)=>{let R={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return f===r?(R.values=!1,d.getRange(R).map(b=>({value:b}))):d.getRange(R)})}a(Zc,"iterateRangeBetween");function eo(e,t,r,n){let s=e.database||e,i=li.openDBI(s,r);i[od.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&li.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(eo,"setupTransaction");function sw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(rw)){if(!s)if(r)s=li.openDBI(e,r);else{let u=li.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=li.openDBI(e,u[_]),!s[od.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(sw,"getOverflowCheck");function ZQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return eo(e,t,t,(o,c,u)=>(cd(r),r=eu(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>jQ(_.value,r))))}a(ZQ,"searchAll");function ez(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);cd(r),r=eu(e.database||e,r);let o=new Map;for(let{key:c,value:u}of nw(e,t,t,n,s,i))o.set(c,ad.parseRow(u,r));return o}a(ez,"searchAllToMap");function tz(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=nw(e,void 0,t,r,n,s),c=o.transaction,u=sw(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(tz,"iterateDBI");function rz(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return li.statDBI(e,t).entryCount}a(rz,"countAll");function nz(e,t,r,n,s=!1,i=void 0,o=void 0){return _i(e,r,n),eo(e,t,r,(c,u,_,l)=>(n=Yr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(nz,"equals");function sz(e,t,r){return _i(e,t,r),li.openDBI(e,t).getValuesCount(r)}a(sz,"count");function iz(e,t,r,n,s=!1,i=void 0,o=void 0){return _i(e,r,n),eo(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return l.DONE}}),l.filter(E=>E)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(iz,"startsWith");function oz(e,t,r,n,s=!1,i=void 0,o=void 0){return iw(e,t,r,n,s,i,o,!0)}a(oz,"endsWith");function iw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return _i(e,r,n),eo(e,null,r,(u,_,l,d)=>{let E=sw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(rw)?_.getValues(f,{transaction:u}).map(p=>{let S=E(f,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[od.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(iw,"contains");function az(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Zc(e,t,r,n,u,s,i,o,!0,!1)}a(az,"greaterThan");function cz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Zc(e,t,r,n,u,s,i,o,!1,!1)}a(cz,"greaterThanEqual");function uz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Zc(e,t,r,u,n,s,i,o,!1,!0)}a(uz,"lessThan");function lz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Zc(e,t,r,u,n,s,i,o,!1,!1)}a(lz,"lessThanEqual");function _z(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ht.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ht.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ht.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Zc(e,t,r,n,s,i,o,c)}a(_z,"between");function dz(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(cd(r),r=eu(s,r),n===void 0)throw new Error(ht.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=ad.parseRow(c,r)),o}a(dz,"searchByHash");function fz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(fz,"checkHashExists");function Ez(e,t,r,n,s=[]){return aw(e,t,r,n,s),ow(e,t,r,n,s).map(i=>i[1])}a(Ez,"batchSearchByHash");function hz(e,t,r,n,s=[]){aw(e,t,r,n,s);let i=new Map;for(let[o,c]of ow(e,t,r,n,s))i.set(o,c);return i}a(hz,"batchSearchByHashToMap");function ow(e,t,r,n,s=[]){return eo(e,t,t,(i,o,c)=>{r=eu(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,ad.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(ow,"batchHashSearch");function aw(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(cd(r),n==null)throw new Error(ht.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ht.IDS_MUST_BE_ITERABLE)}a(aw,"initializeBatchSearchByHash");function cd(e){if(!Array.isArray(e))throw e===void 0?new Error(ht.FETCH_ATTRIBUTES_REQUIRED):new Error(ht.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(cd,"validateFetchAttributes");function _i(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.SEARCH_VALUE_REQUIRED);if(r?.length>XQ)throw new Error(ht.SEARCH_VALUE_TOO_LARGE)}a(_i,"validateComparisonFunctions");function eu(e,t){return t.length===1&&JQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=li.listDBIs(e)),t}a(eu,"setGetWholeRowAttributes");cw.exports={searchAll:ZQ,searchAllToMap:ez,count:sz,countAll:rz,equals:nz,startsWith:iz,endsWith:oz,contains:iw,searchByHash:dz,setGetWholeRowAttributes:eu,batchSearchByHash:Ez,batchSearchByHashToMap:hz,checkHashExists:fz,iterateDBI:tz,greaterThan:az,greaterThanEqual:cz,lessThan:uz,lessThanEqual:lz,between:_z}});var sa=g((y_e,fw)=>{var uw=require("lodash"),lw=Xe(),fe=require("joi"),mz=z(),{hdb_schema_table:tu,checkValidTable:_w,hdb_table:dw,hdb_database:ud}=Jn(),{handleHDBError:pz,hdb_errors:Sz}=ne(),{getDatabases:Tz}=(Ae(),ie(ke)),{HTTP_STATUS_CODES:gz}=Sz,Rz=fe.object({database:ud,schema:ud,table:dw,search_attribute:tu,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(tu,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),Az=fe.object({database:ud,schema:ud,table:dw,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(tu,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(tu,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(tu,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()});fw.exports=function(e,t){let r=null;switch(t){case"value":r=lw.validateBySchema(e,Rz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(_w("database",e.schema)),i(_w("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=lw.validateBySchema(e,Az);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=mz.checkGlobalSchemaTable(e.schema,e.table);if(s)return pz(new Error,s,gz.NOT_FOUND);let o=Tz()[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,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=uw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!uw.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 Pp=g((I_e,Ew)=>{"use strict";var Oz=Qe(),bz=sa(),{getSchemaPath:yz}=je();Ew.exports=Nz;function Nz(e){let t=bz(e,"hashes");if(t)throw t;let r=yz(e.schema,e.table);return Oz.openEnvironment(r,e.table)}a(Nz,"initialize")});var Up=g((C_e,hw)=>{"use strict";var Iz=na(),wz=Pp();hw.exports=Cz;async function Cz(e){let t=await wz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Iz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Cz,"lmdbGetDataByHash")});var ia=g((L_e,mw)=>{"use strict";var vp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};mw.exports=vp});var Sw=g((U_e,pw)=>{"use strict";var P_e=ia(),Dz=na(),Lz=Pp();pw.exports=Mz;async function Mz(e){let t=await Lz(e),r=global.hdb_schema[e.schema][e.table];return Dz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(Mz,"lmdbSearchByHash")});var ts=g((B_e,Tw)=>{"use strict";var Bp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Tw.exports=Bp});var ld=g((x_e,yw)=>{"use strict";var rr=na(),Pz=Qe(),Uz=z(),Ee=ft(),to=P(),vz=ki(),gw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:Bz}=je(),Ns=to.SEARCH_WILDCARDS;async function Hz(e,t,r){let n;e.schema===to.SYSTEM_SCHEMA_NAME?n=vz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=bw(e,n.hash_attribute,r,t);return Aw(e,s,n.hash_attribute,r)}a(Hz,"prepSearch");async function Aw(e,t,r,n){let s=Bz(e.schema,e.table),i=await Pz.openEnvironment(s,e.table),o=Ow(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(xz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Rw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?Rw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?rr.batchSearchByHashToMap(c,r,e.get_attributes,_):rr.batchSearchByHash(c,r,e.get_attributes,_)}a(Aw,"executeSearch");function Ow(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=rr.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=rr.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=rr.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=rr.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return rr.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return rr.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return rr.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return rr.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=rr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=rr.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=rr.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=rr.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=rr.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Ow,"searchByType");function Rw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Rw,"createMapFromIterable");function xz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(xz,"checkToFetchMore");function bw(e,t,r,n){if(Uz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Ns.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Ns[0])<0&&s.indexOf(Ns[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(Ns.indexOf(i)>=0&&Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Ns.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(Ns[0])||s.includes(Ns[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(gw.UNKNOWN_SEARCH_TYPE)}else switch(n){case to.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case to.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case to.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case to.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case to.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(gw.UNKNOWN_SEARCH_TYPE)}}a(bw,"createSearchTypeFromSearchObject");yw.exports={executeSearch:Aw,createSearchTypeFromSearchObject:bw,prepSearch:Hz,searchByType:Ow}});var Iw=g((F_e,Nw)=>{"use strict";var q_e=ts(),Gz=sa(),qz=z(),Fz=P(),kz=ld();Nw.exports=Vz;function Vz(e,t){if(!qz.isEmpty(t)&&Fz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Gz(e,"value");if(n)throw n;return kz.prepSearch(e,t,!0)}a(Vz,"lmdbGetDataByValue")});var ru=g(($_e,ww)=>{"use strict";var V_e=ts(),$z=sa(),Yz=z(),Kz=P(),Wz=ld();ww.exports=Qz;async function Qz(e,t){if(!Yz.isEmpty(t)&&Kz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=$z(e,"value");if(n)throw n;return Wz.prepSearch(e,t,!1)}a(Qz,"lmdbSearchByValue")});var Dw=g((W_e,Cw)=>{"use strict";var K_e=ft(),Hp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},xp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Gp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Cw.exports={SearchByConditionsObject:Hp,SearchCondition:xp,SortAttribute:Gp}});var vw=g((j_e,Uw)=>{"use strict";var z_e=Dw().SearchByConditionsObject,zz=ts(),Jz=sa(),qp=na(),_d=ft(),{Resource:J_e}=(Nn(),ie(Fp)),Pw=ld(),jz=Mp(),Xz=require("lodash"),{getSchemaPath:Zz}=je(),Lw=Qe(),{handleHDBError:eJ,hdb_errors:tJ}=ne(),{HTTP_STATUS_CODES:rJ}=tJ,nJ=1e8;Uw.exports=sJ;async function sJ(e){let t=Jz(e,"conditions");if(t)throw eJ(t,t.message,rJ.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=Zz(e.schema,e.table),n=await Lw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Lw.openDBI(n,_.search_attribute);let i=Xz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===_d.SEARCH_TYPES.EQUALS?_.estimated_count=qp.count(n,_.search_attribute,_.search_value):l===_d.SEARCH_TYPES.CONTAINS||l===_d.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=nJ}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Mw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Pw.filterByType),d=l.length,E=qp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>jz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Mw(o,e,E,s.hash_attribute);c=c.concat(f)}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=qp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(sJ,"lmdbSearchByConditions");async function Mw(e,t,r,n){let s=new zz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===_d.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Pw.searchByType(e,s,i,n).map(o=>o.value)}a(Mw,"executeConditionSearch")});var oa=g((Z_e,Bw)=>{"use strict";var iJ=P().OPERATIONS_ENUM,kp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=iJ.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Bw.exports=kp});var Vp=g((tde,$w)=>{"use strict";var qw=ts(),Fw=oa(),kw=ru(),Vw=Xc(),hr=P(),Hw=z(),xw=Qe(),{getTransactionAuditStorePath:oJ,getSchemaPath:aJ}=je(),Gw=$();$w.exports=cJ;async function cJ(e){try{if(Hw.isEmpty(global.hdb_schema[e.schema])||Hw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await uJ(e),await lJ(e);let t=aJ(e.schema,e.table);try{await xw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Gw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=oJ(e.schema,e.table);await xw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Gw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(cJ,"lmdbDropTable");async function uJ(e){let t=new qw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await kw(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new Fw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Vw(s)}a(uJ,"deleteAttributesFromSystem");async function lJ(e){let t=new qw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await kw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new Fw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Vw(s)}catch(i){throw i}}a(lJ,"dropTableFromSystem")});var Kw=g((nde,Yw)=>{"use strict";var _J=require("fs-extra"),dJ=ts(),fJ=ia(),EJ=oa(),hJ=Vp(),mJ=Xc(),pJ=Up(),SJ=ru(),Is=P(),{getSchemaPath:TJ}=je(),{handleHDBError:gJ,hdb_errors:RJ}=ne(),{HDB_ERROR_MSGS:AJ,HTTP_STATUS_CODES:OJ}=RJ;Yw.exports=bJ;async function bJ(e){let t;try{t=await yJ(e.schema);let r=new dJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await SJ(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await hJ(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new EJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await mJ(s);let i=TJ(t);await _J.remove(i)}catch(r){throw r}}a(bJ,"lmdbDropSchema");async function yJ(e){let t=new fJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await pJ(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw gJ(new Error,AJ.SCHEMA_NOT_FOUND(e),OJ.NOT_FOUND,void 0,void 0,!0);return n}a(yJ,"validateDropSchema")});var dd=g((ide,Ww)=>{"use strict";var $p=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Ww.exports=$p});var zw=g((cde,Qw)=>{"use strict";var NJ=require("fs-extra"),fd=Qe(),{getTransactionAuditStorePath:IJ}=je(),Yp=ft(),ade=dd();Qw.exports=wJ;async function wJ(e){let t;try{let r=IJ(e.schema,e.table);await NJ.mkdirp(r),t=await fd.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{fd.createDBI(t,Yp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),fd.createDBI(t,Yp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),fd.createDBI(t,Yp.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(wJ,"createTransactionsAuditEnvironment")});var Zw=g((lde,Xw)=>{"use strict";var Kp=P(),Jw=Qe(),CJ=Yo(),{getSystemSchemaPath:DJ,getSchemaPath:LJ}=je(),MJ=ki(),PJ=M_(),Wp=L_(),UJ=$(),vJ=zw(),zp=MJ.hdb_table,jw=[];for(let e=0;e<zp.attributes.length;e++)jw.push(zp.attributes[e].attribute);Xw.exports=BJ;async function BJ(e,t){let r=LJ(t.schema,t.table),n=new Wp(t.schema,t.table,Kp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Wp(t.schema,t.table,Kp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Wp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Jw.createEnvironment(r,t.table),e!==void 0){let o=await Jw.openEnvironment(DJ(),Kp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await CJ.insertRecords(o,zp.hash_attribute,jw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Qp(n),await Qp(s),await Qp(i)}await vJ(t)}catch(o){throw o}}a(BJ,"lmdbCreateTable");async function Qp(e){try{await PJ(e)}catch(t){UJ.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Qp,"createAttribute")});var tC=g((dde,eC)=>{"use strict";var HJ=qc(),xJ=kc(),GJ=sd(),nu=P(),qJ=Yo().updateRecords,FJ=Qe(),{getSchemaPath:kJ}=je(),VJ=Jc(),$J=$();eC.exports=YJ;async function YJ(e){try{let{schema_table:t,attributes:r}=HJ(e);xJ(e,r,t.hash_attribute),e.schema!==nu.SYSTEM_SCHEMA_NAME&&(r.includes(nu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(nu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(nu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(nu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await GJ(e.hdb_auth_header,t,r),s=kJ(e.schema,e.table),i=await FJ.openEnvironment(s,e.table),o=await qJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await VJ(e,o)}catch(c){$J.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(YJ,"lmdbUpdateRecords")});var nC=g((Ede,rC)=>{"use strict";var KJ=P().OPERATIONS_ENUM,Jp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=KJ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};rC.exports=Jp});var iC=g((pde,sC)=>{"use strict";var mde=nC(),WJ=qc(),QJ=kc(),zJ=sd(),su=P(),JJ=Yo().upsertRecords,jJ=Qe(),{getSchemaPath:XJ}=je(),ZJ=Jc(),e2=$(),{handleHDBError:t2,hdb_errors:r2}=ne();sC.exports=n2;async function n2(e){let t;try{t=WJ(e)}catch(u){throw t2(u,u.message,r2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;QJ(e,n,r.hash_attribute),e.schema!==su.SYSTEM_SCHEMA_NAME&&(n.includes(su.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(su.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(su.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(su.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await zJ(e.hdb_auth_header,r,n),i=XJ(e.schema,e.table),o=await jJ.openEnvironment(i,e.table),c=await JJ(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await ZJ(e,c)}catch(u){e2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(n2,"lmdbUpsertRecords")});var aC=g((Tde,oC)=>{"use strict";var jp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};oC.exports=jp});var uC=g((Rde,cC)=>{"use strict";var Xp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};cC.exports=Xp});var dC=g((bde,_C)=>{"use strict";var Zp=Qe(),{getTransactionAuditStorePath:s2}=je(),Ode=aC(),iu=ft(),i2=z(),lC=uC(),o2=require("util").promisify,a2=o2(setTimeout),c2=1e4,u2=100;_C.exports=l2;async function l2(e){let t=s2(e.schema,e.table),r=await Zp.openEnvironment(t,e.table,!0),n=Zp.listDBIs(r);Zp.initializeDBIs(r,iu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new lC;do s=await _2(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await a2(u2);while(s.transactions_deleted>0);return i}a(l2,"deleteAuditLogsBefore");async function _2(e,t){let r=new lC;try{let n=e.dbis[iu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[iu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];i2.isEmpty(c)||(s=e.dbis[iu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[iu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>c2)break}return await s,r}catch(n){throw n}}a(_2,"deleteTransactions")});var EC=g((Nde,fC)=>{"use strict";var eS=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};fC.exports=eS});var mC=g((Cde,hC)=>{"use strict";var d2=ts(),f2=oa(),wde=EC(),rs=P(),E2=z(),tS=Qe(),h2=ki(),m2=ru(),p2=Xc(),{getSchemaPath:S2}=je();hC.exports=T2;async function T2(e,t=!0){let r;e.schema===rs.SYSTEM_SCHEMA_NAME?r=h2[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await R2(e),s=S2(e.schema,e.table),i=await tS.openEnvironment(s,e.table);return t===!0&&await g2(e,i,r.hash_attribute),tS.dropDBI(i,e.attribute),n}a(T2,"lmdbDropAttribute");async function g2(e,t,r){let n=tS.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(g2,"removeAttributeFromAllObjects");async function R2(e){let t=new d2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await m2(t)).filter(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(E2.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new f2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return p2(i)}a(R2,"dropAttributeFromSystem")});var AC=g((Mde,RC)=>{"use strict";var rS=Qe(),aa=ft(),Lde=vr(),nS=P(),pC=z(),{getTransactionAuditStorePath:A2}=je(),O2=na(),Ed=ea(),b2=$();RC.exports=y2;async function y2(e){let t=A2(e.schema,e.table),r=await rS.openEnvironment(t,e.table,!0),n=rS.listDBIs(r);rS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case nS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return SC(r,e.search_values);case nS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,I2(r,e.search_values,s);case nS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return N2(r,e.search_values);default:return SC(r)}}a(y2,"readAuditLog");function SC(e,t=[0,Date.now()]){pC.isEmpty(t[0])&&(t[0]=0),pC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new Ed,s))}a(SC,"searchTransactionsByTimestamp");function N2(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,gC(e,i))}return Object.fromEntries(r)}a(N2,"searchTransactionsByUsername");function I2(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=O2.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=gC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);TC(u,"records",r,l,o),TC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(I2,"searchTransactionsByHashValues");function TC(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new Ed(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new Ed(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(TC,"loopRecords");function gC(e,t){let r=[];try{let n=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new Ed,i);r.push(o)}}catch(i){b2.warn(i)}return r}catch(n){throw n}}a(gC,"batchSearchTransactions")});var bC=g((Bde,OC)=>{"use strict";var{getSchemaPath:Ude}=je(),vde=Qe(),{database:w2}=(Ae(),ie(ke));OC.exports={writeTransaction:C2};async function C2(e,t,r){return w2({database:e,table:t}).transaction(r)}a(C2,"writeTransaction")});var wC=g((xde,IC)=>{"use strict";var{getSchemaPath:yC}=je(),NC=Qe();IC.exports={flush:D2,resetReadTxn:L2};async function D2(e,t){return(await NC.openEnvironment(yC(e,t),t.toString())).flushed}a(D2,"flush");async function L2(e,t){try{(await NC.openEnvironment(yC(e,t),t.toString())).resetReadTxn()}catch{}}a(L2,"resetReadTxn")});var MC=g((qde,LC)=>{"use strict";var{Readable:M2}=require("stream"),{getDatabases:P2}=(Ae(),ie(ke)),{readSync:U2,openSync:v2,createReadStream:CC}=require("fs"),{open:B2}=require("lmdb"),DC=Pc(),H2=Uc(),{AUDIT_STORE_OPTIONS:x2}=(ri(),ie(PC)),{INTERNAL_DBIS_NAME:G2,AUDIT_STORE_NAME:q2}=ft();LC.exports=k2;var sS=32768,F2=100;async function k2(e){let t=e.database||e.schema||"data",r=P2()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=B2({noSync:!0,maxDbs:H2.MAX_DBS}),E,f=d.openDB(G2,new DC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,b){b.encoding="binary",b.encoder=void 0;let C=d.openDB(R,b),H=l.openDB(R,b);for(let{key:v,version:F,value:M}of H.getRange({start:null,transaction:h,versions:H.useVersions}))E=C.put(v,M,F),p++%F2===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(C=>R.startsWith?.(C+"/"))){f.put(R,b);let[,C]=R.split("/"),H=!C,v=new DC(!H,H);await S(R,v)}e.include_audit&&await S(q2,Object.assign({},x2)),await E;let T=CC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=v2(o.path);return o.transaction(()=>{let _=Buffer.alloc(sS);U2(c,_,0,sS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=CC(null,{fd:c,start:sS}),E=new M2.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(k2,"getBackup")});var BC=g((kde,vC)=>{"use strict";var V2=$(),{handleHDBError:$2}=ne(),Y2=Qb(),K2=M_(),W2=Ip(),Q2=KI(),z2=Xc(),J2=Up(),j2=Sw(),X2=Iw(),Z2=ru(),e4=vw(),t4=Kw(),r4=Zw(),n4=tC(),s4=iC(),i4=dC(),o4=Vp(),a4=mC(),c4=AC(),u4=bC(),UC=wC(),l4=MC(),iS=class extends Y2{static{a(this,"LMDBBridge")}async searchByConditions(t){return e4(t)}async getDataByHash(t){return await J2(t)}async searchByHash(t){return await j2(t)}async getDataByValue(t,r){return await X2(t,r)}async searchByValue(t){return await Z2(t)}async createSchema(t){return await Q2(t)}async dropSchema(t){return await t4(t)}async createTable(t,r){return await r4(t,r)}async dropTable(t){return await o4(t)}async createAttribute(t){return await K2(t)}async createRecords(t){return await W2(t)}async updateRecords(t){return await n4(t)}async upsertRecords(t){try{return await s4(t)}catch(r){throw $2(r,null,null,V2.ERR,r)}}async deleteRecords(t){return await z2(t)}async dropAttribute(t){return await a4(t)}async deleteAuditLogsBefore(t){return await i4(t)}async readAuditLog(t){return await c4(t)}writeTransaction(t,r,n){return u4.writeTransaction(t,r,n)}flush(t,r){return UC.flush(t,r)}resetReadTxn(t,r){return UC.resetReadTxn(t,r)}getBackup(t){return l4(t)}};vC.exports=iS});function E4(){f4=setInterval(function(){for(let e of oS)if(e.stale){let t=e[ye]?.url;qC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},d4).unref()}var aS,GC,qC,FC,kC,VC,HC,oS,_4,ou,xC,ro,hd,d4,f4,cS=Re(()=>{aS=B(vr()),GC=B(ne()),qC=B($());Nn();FC=B(Z()),kC=B(P()),VC=B(z()),HC=100,oS=new Set,_4=(0,VC.convertToMS)(FC.get(kC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,ro=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),oS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(oS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(ou&&!this.overloadChecked&&performance.now()-xC>_4)throw new GC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,aS.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[f===0?"before":"beforeIntermediate"];if(T){let R=T();h?h.push?h.push(R):h=[h,R]:h=R}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),u=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let E=d.store.ifVersion(d.key,d.entry?.version??null,u);s=s||E}else u();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<HC>>n?u():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return ou||(ou=s,xC=performance.now(),ou.then(()=>{ou=null})),s.then(d=>d?(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}))):(_&&(_.retryRisk=(_.retryRisk||0)+HC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},hd=class extends ro{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,aS.getNextMonotonicTime)())}getReadTxn(){}},d4=3e4;a(E4,"startMonitoringTxns");E4()});function Ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new ro;e.timestamp&&(n.timestamp=e.timestamp),n[ye]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var $C,no=Re(()=>{$C=require("../index");Nn();cS();a(Ze,"transaction");(0,$C._assignPackageExport)("transaction",Ze);Ze.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ze.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var ZC={};Fe(ZC,{ResourceBridge:()=>_S});function dS({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 KC(e,t){let r=ns(e),n=dS(e,r);if(!r)throw new Pn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&pd(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 ns(e){let t=e.database||e.schema||m4,r=mr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,h4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function WC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*QC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var zC,md,Pn,JC,jC,Un,uS,lS,XC,h4,m4,p4,S4,YC,_S,eD=Re(()=>{"use strict";zC=B(BC()),md=B(sa()),Pn=B(ne());Ae();JC=B(qc()),jC=B(kc()),Un=B(P()),uS=B(ys()),lS=B(Mn()),XC=B(z());no();Sd();({HDB_ERROR_MSGS:h4}=Pn.hdb_errors),m4="data",p4=1e4,S4=10,_S=class extends zC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),YC=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,md.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ns(t);if(!n)throw new Pn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:dS(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Pn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}Et({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ns(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ns(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ns(t).dropTable()}createSchema(t){return ca({database:t.schema,table:null}),uS.signalSchemaChange(new lS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await fS(t.schema),uS.signalSchemaChange(new lS.SchemaEventMsg(process.pid,Un.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,YC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,JC.default)(t);(0,jC.default)(t,n,r.primaryKey);let s,i=mr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(E=>E.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=pd(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=mr()[t.schema][t.table],n={user:t.hdb_user};return Ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return WC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=mr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,XC.async_set_timeout)(S4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%p4===0&&await _();return u.length>0&&await _(),s?WC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,md.default)(t,"hashes");if(r)throw r;return KC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of KC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,md.default)(t,"value");if(n)throw n;let s=ns(t);if(!s)throw new Pn.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===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:dS(t,s)})}async getDataByValue(t,r){let n=new Map,s=ns(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){ns({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ns(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ns(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of QC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return QC(r,t.search_values?.[0],t.search_values?.[1])}}};a(dS,"getSelect");a(KC,"getRecords");a(ns,"getTable");a(WC,"createDeleteResponse");a(QC,"groupRecordsInHistory")});var Cn=g((nfe,tD)=>{"use strict";var{ResourceBridge:T4}=(eD(),ie(ZC)),g4=Z();g4.initSync();var Td;function R4(){return Td||(Td=new T4,Td)}a(R4,"getBridge");tD.exports=R4()});var iD=g((ife,sD)=>{"use strict";var rD=require("lodash"),au=require("mathjs"),A4=require("jsonata"),nD=z();sD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?rD.uniqWith(e,rD.isEqual):e,searchJSON:O4,mad:cu.bind(null,au.mad),mean:cu.bind(null,au.mean),mode:cu.bind(null,au.mode),prod:cu.bind(null,au.prod),median:cu.bind(null,au.median)};function cu(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(cu,"aggregateFunction");function O4(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(nD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),nD.isEmpty(this.__ala__.res[r])){let n=A4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(O4,"searchJSON")});var aD=g((afe,oD)=>{"use strict";var Rt=require("moment"),ES="YYYY-MM-DDTHH:mm:ss.SSSZZ";Rt.suppressDeprecationWarnings=!0;oD.exports={current_date:()=>Rt().utc().format("YYYY-MM-DD"),current_time:()=>Rt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Rt(e).utc().format("YYYY");case"month":return Rt(e).utc().format("MM");case"day":return Rt(e).utc().format("DD");case"hour":return Rt(e).utc().format("HH");case"minute":return Rt(e).utc().format("mm");case"second":return Rt(e).utc().format("ss");case"millisecond":return Rt(e).utc().format("SSS");default:break}},date:e=>Rt(e).utc().format(ES),date_format:(e,t)=>Rt(e).utc().format(t),date_add:(e,t,r)=>Rt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Rt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Rt(e).utc(),s=Rt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Rt().utc().valueOf(),get_server_time:()=>Rt().format(ES),offset_utc:(e,t)=>Rt(e).utc().utcOffset(t).format(ES)}});var _D=g((cfe,lD)=>{"use strict";var b4=require("@turf/area"),y4=require("@turf/length"),N4=require("@turf/circle"),I4=require("@turf/difference"),w4=require("@turf/distance"),C4=require("@turf/boolean-contains"),D4=require("@turf/boolean-equal"),L4=require("@turf/boolean-disjoint"),M4=require("@turf/helpers"),cD=P(),Se=z(),ws=$();lD.exports={geoArea:P4,geoLength:U4,geoCircle:v4,geoDifference:B4,geoDistance:uD,geoNear:H4,geoContains:x4,geoEqual:G4,geoCrosses:q4,geoConvert:F4};function P4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return b4.default(e)}catch(t){return ws.trace(t,e),NaN}}a(P4,"geoArea");function U4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return y4.default(e,{units:t||"kilometers"})}catch(r){return ws.trace(r,e),NaN}}a(U4,"geoLength");function v4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return N4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(v4,"geoCircle");function B4(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return I4(e,t)}catch(r){return ws.trace(r,e,t),NaN}}a(B4,"geoDifference");function uD(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 w4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(uD,"geoDistance");function H4(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return uD(e,t,n)<=r}catch(s){return ws.trace(s,e,t),!1}}a(H4,"geoNear");function x4(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 C4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(x4,"geoContains");function G4(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 D4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(G4,"geoEqual");function q4(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!L4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(q4,"geoCrosses");function F4(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(cD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(cD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),M4[t](e,r)}a(F4,"geoConvert")});var gd=g((lfe,dD)=>{var so=iD(),Kr=aD(),ss=_D();dD.exports=e=>{e.aggr.mad=e.aggr.MAD=so.mad,e.aggr.mean=e.aggr.MEAN=so.mean,e.aggr.mode=e.aggr.MODE=so.mode,e.aggr.prod=e.aggr.PROD=so.prod,e.aggr.median=e.aggr.MEDIAN=so.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=so.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=so.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ss.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ss.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ss.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ss.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ss.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ss.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ss.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ss.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ss.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ss.geoNear}});var mD=g((_fe,hD)=>{"use strict";var uu=require("lodash"),pr=require("alasql");pr.options.cache=!1;var k4=gd(),fD=require("clone"),Rd=require("recursive-iterator"),_e=$(),De=z(),ua=Cn(),V4=P(),{hdb_errors:$4}=ne(),{getDatabases:ED}=(Ae(),ie(ke)),Y4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";k4(pr);var hS=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw _e.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(n),new Error(vn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(n),new Error(vn)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(n),new Error(vn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(n),new Error(vn)}try{return t=await this._finalSQL(),t}catch(n){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(n),new Error(vn)}}_getColumns(){let t=new Rd(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(fD(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=uu.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=ED()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Rd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new pr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new pr.yy.LogicValue({value:i}):n instanceof pr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new pr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Rd(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(V4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(De.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&uu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(fD(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(Y4)>-1&&this.tables.forEach(s=>{let i={columnid:ED()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=uu.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ua.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let E=await ua.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ua.getDataByValue(c,f.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ua.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(vn)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof pr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new pr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new pr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new pr.yy.FuncValue:new pr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,p=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${p}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${p}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";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(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let 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 E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await pr.promise(h,t),t=null}catch(f){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let p=E[f];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),p=uu.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let R=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new Rd(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=uu.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(vn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ua.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.get(E);for(let h=0;h<_;h++){let p=s.columns[h],S=f[p]===void 0?null:f[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();_e.trace(`Final SQL: ${s}`),n=await pr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),_e.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return _e.error($4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ua.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};hD.exports=hS});var Gr=g((ffe,pD)=>{"use strict";var K4=Kb();pD.exports={searchByConditions:Q4,searchByHash:z4,searchByValue:J4,search:j4};var mS=Cn(),{transformReq:pS}=z(),W4=mD();async function Q4(e){return pS(e),mS.searchByConditions(e)}a(Q4,"searchByConditions");async function z4(e){pS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of mS.searchByHash(e))r&&t.push(r);return t}a(z4,"searchByHash");async function J4(e){pS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of mS.searchByValue(e))t.push(r);return t}a(J4,"searchByValue");function j4(e,t){try{let r=new K4(e);r.validate(),new W4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(j4,"search")});var Ad=g((hfe,SD)=>{"use strict";var X4=Cn();SD.exports={writeTransaction:Z4};function Z4(e,t,r){return X4.writeTransaction(e,t,r)}a(Z4,"writeTransaction")});var AD=g((Sfe,RD)=>{"use strict";var ej=Gr(),tj=bs(),TD=$(),rj=qr(),pfe=Ad(),nj=require("clone"),TS=require("alasql"),sj=gd(),gD=require("util"),ij=gD.promisify(tj.getTableSchema),oj=gD.promisify(ej.search),aj=P(),SS=z();sj(TS);RD.exports={update:uj};var cj="There was a problem performing this update. Please check the logs and try again.";async function uj({statement:e,hdb_user:t}){let r=await ij(e.table.databaseid,e.table.tableid),n=lj(e.columns);SS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=nj(s),c=SS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=TS.parse(u).statements[0],l=await oj(_),d=_j(n,l);return dj(o,d,t)}a(uj,"update");function lj(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=TS.compile(`SELECT ${r.expression.toString()} AS [${aj.FUNC_VAL}] FROM ?`)}),t}catch(t){throw TD.error(t),new Error(cj)}}a(lj,"createUpdateRecord");function _j(e,t){return SS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(_j,"buildUpdateRecords");async function dj(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await rj.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){TD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(dj,"updateRecords")});var bD=g((Afe,OD)=>{var fj=require("alasql"),Ej=Gr(),hj=$(),mj=Cn(),RS=require("util"),gS=z(),pj=P(),Sj=bs(),gfe=Ad(),Rfe=qr(),Tj="record",gj="successfully deleted",Rj=RS.callbackify(yj),Aj=RS.promisify(Ej.search),Oj=RS.promisify(Sj.getTableSchema);OD.exports={convertDelete:Rj};function bj(e){return`${e.deleted_hashes.length} ${Tj}${e.deleted_hashes.length===1?"":"s"} ${gj}`}a(bj,"generateReturnMessage");async function yj({statement:e,hdb_user:t}){let r=await Oj(e.table.databaseid,e.table.tableid);gS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=gS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=fj.parse(o).statements[0],u={operation:pj.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await Aj(c);let _=await mj.deleteRecords(u);return gS.isEmptyOrZeroLength(_.message)&&(_.message=bj(_)),delete _.txn_time,_}catch(_){throw hj.error(_),_.hdb_code?_.message:_}}a(yj,"convertDelete")});var CD=g((bfe,wD)=>{"use strict";var Nj=Os(),{hdb_errors:yD}=ne(),{getDatabases:ND}=(Ae(),ie(ke));wD.exports={checkSchemaExists:ID,checkSchemaTableExists:Ij,schema_describe:Nj};async function ID(e){if(!ND()[e])return yD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(ID,"checkSchemaExists");async function Ij(e,t){let r=await ID(e);if(r)return r;if(!ND()[e][t])return yD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Ij,"checkSchemaTableExists")});var lu=g((Nfe,wj)=>{wj.exports={name:"harperdb",version:"4.3.21",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.635.0","@aws-sdk/lib-storage":"3.635.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.14",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.4.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.17.1",yaml:"2.4.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.22.11","newman-reporter-teamcity":"0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var hu={};Fe(hu,{addAnalyticsListener:()=>Eu,recordAction:()=>Sr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>Cj});function Cj(e){xD=e}function Sr(e,t,r,n,s){if(!xD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=yd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},yd.set(i,o)}Od||Dj()}function Wr(e,t,r,n,s){Sr(!!e,t,r,n,s)}function Eu(e){FD.push(e)}function Dj(){Od=performance.now(),setTimeout(async()=>{let e=performance.now()-Od;Od=0;let t=[],r={time:Date.now(),period:e,threadId:io.threadId,metrics:t};for(let[s,i]of yd){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 kD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:f,count:h}:f),l=f;u=E}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await VD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:io.threadId,byThread:!0,...n});for(let s of FD)s(t);yd=new Map,io.parentPort?io.parentPort.postMessage({type:qD,report:r}):KD({report:r})},GD).unref()}async function Lj(e,t=6e4){let r=bS(),n=$D(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,_u.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,_u.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:R}=S;for(let b of T||[]){let{path:C,method:H,type:v,metric:F,count:M,total:Q,distribution:J,threads:j,...ae}=b;M||(M=1);let ce=F+(C?"-"+C:"");H!==void 0&&(ce+="-"+H),v!==void 0&&(ce+="-"+v);let ge=c.get(ce);if(ge){if(ge.threads){let Ne=ge.threads[R];if(Ne)ge=Ne;else{ge.threads[R]=Object.assign({},ae);continue}}ge.count||(ge.count=1);let Ge=ge.count;for(let Ne in ae){let ve=ae[Ne];typeof ve=="number"&&(ge[Ne]=(ge[Ne]*Ge+ve*M)/(Ge+M))}ge.count+=M,Q>=0&&(ge.total+=Q,ge.ratio=ge.total/ge.count)}else ge=Object.assign({period:t},b),delete ge.distribution,c.set(ce,ge),ge.byThread&&(ge.threads=[],ge.threads[R]=Object.assign({},ae),_.push(ge));if(J){J=J.map(Ne=>typeof Ne=="number"?{value:Ne,count:1}:Ne);let Ge=u.get(ce);Ge?Ge.push(...J):u.set(ce,J)}}await VD()}for(let p of _){let{path:S,method:T,type:R,metric:b,count:C,total:H,distribution:v,threads:F,...M}=p;F=F.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let J=0;for(let j of F){let ae=j[Q];typeof ae=="number"&&(J+=ae)}p[Q]=J}p.count=F.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ne,ve)=>Ne.value>ve.value?1:-1);let R=T.count-1,b=[],C=0,H=0,v;for(let Ne of kD){let ve=R*Ne;for(;C<ve;)v=S[H++],C+=v.count,H===1&&C--;let e_=S[H>1?H-2:0];v||(v=S[0]),b.push(v.value-(v.value-e_.value)*(C-ve)/v.count)}let[F,M,Q,J,j,ae,ce,ge,Ge]=b;Object.assign(T,{p1:F,p10:M,p25:Q,median:J,p75:j,p90:ae,p95:ce,p99:ge,p999:Ge})}let d;for(let[p,S]of c)S.id=(0,bd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let p=(0,bd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-DD,active:h-LD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}DD=f,LD=h}async function MD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function bS(){return PD||(PD=Et({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function $D(){return UD||(UD=Et({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function Uj(){YD=!0;let e=(0,fu.get)(OS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Lj(GD,e),await MD(bS(),Mj),await MD($D(),Pj)},Math.min(e/2,2147483647)).unref()}function KD(e,t){let r=e.report;r.threadId=t?.threadId||io.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(vD+=n.mean*n.count);r.totalBytesProcessed=vD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(BD.get(t))}),BD.set(t,t.performance.eventLoopUtilization())),r.id=(0,bd.getNextMonotonicTime)(),bS().primaryStore.put(r.id,r),YD||Uj(),vj&&(WD=Hj(r))}async function Hj(e){if(await WD,!di){let r=(0,du.dirname)((0,_u.getLogFilePath)());try{di=await(0,AS.open)((0,du.join)(r,"analytics.log"),"r+")}catch{di=await(0,AS.open)((0,du.join)(r,"analytics.log"),"w+")}}let t=(await di.stat()).size;if(t>Bj){let r=Buffer.alloc(t);await di.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await di.write(r,{position:0}),await di.truncate(r.length),t=r.length}await di.write(JSON.stringify(e)+`
8
+ `,t)}var io,HD,_u,du,AS,bd,fu,OS,yd,xD,Od,GD,qD,FD,kD,DD,LD,VD,Mj,Pj,PD,UD,YD,vD,BD,vj,WD,di,Bj,Cs=Re(()=>{io=require("worker_threads"),HD=B(We());Ae();_u=B($()),du=require("path"),AS=require("fs/promises"),bd=B(vr()),fu=B(Z()),OS=B(P());lr();(0,fu.initSync)();yd=new Map,xD=(0,fu.get)(OS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(Cj,"setAnalyticsEnabled");a(Sr,"recordAction");at.recordAnalytics=Sr;a(Wr,"recordActionBinary");Od=0,GD=1e3,qD="analytics-report",FD=[];a(Eu,"addAnalyticsListener");kD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(Dj,"sendAnalytics");a(Lj,"aggregation");DD=0,LD=0,VD=a(()=>new Promise(setImmediate),"rest");a(MD,"cleanup");Mj=36e5,Pj=31536e6;a(bS,"getRawAnalyticsTable");a($D,"getAnalyticsTable");(0,HD.setChildListenerByType)(qD,KD);a(Uj,"startScheduledTasks");vD=0,BD=new Map,vj=!1;a(KD,"recordAnalytics");Bj=1e6;a(Hj,"logAnalytics")});var CS=g((Gfe,sL)=>{"use strict";var{decode:xj}=require("msgpackr"),{isMainThread:Bfe,parentPort:Hfe,threadId:xfe}=require("worker_threads"),wd=ut(),la=Ve(),IS=P(),nr=$(),NS=Z(),Gj=P(),{onMessageByType:qj}=We(),JD=As(),{recordAction:Fj,recordActionBinary:kj}=(Cs(),ie(hu)),{publishToStream:Vj}=wd,{ConsumerEvents:QD}=require("nats"),$j=Gr(),{promisify:Yj}=require("util"),jD=Yj(setTimeout),Cd=1e4,Dd,Id,Kj,Wj,XD,mu=new Map,_a=new Map;sL.exports={initialize:ZD,ingestConsumer:wS,setSubscription:Qj,setIgnoreOrigin:jj,getDatabaseSubscriptions:Jj,updateConsumer:eL};async function ZD(){qj(IS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await eL(n)}),XD=!0,nr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await wd.getNATSReferences();Dd=e,Id=e.info.server_name,Kj=t,Wj=r}a(ZD,"initialize");async function eL(e){if(e.status==="start"){let{js:t,jsm:r}=await tL(e.node_domain_name);wS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=mu.get(e.stream_name+e.node_domain_name);t&&(nr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),mu.set(e.stream_name+e.node_domain_name,"close")),_a.get(e.node_domain_name)==="failed"&&_a.set(e.node_domain_name,"close")}}a(eL,"updateConsumer");var Ld=new Map;function Qj(e,t,r){let n=Ld.get(e);n||Ld.set(e,n=new Map),n.set(t,r),XD||ZD().then(zj)}a(Qj,"setSubscription");async function zj(){let e=await $j.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+la.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await tL(r),!n))break;let{schema:o,table:c}=i,u=JD.createNatsTableStreamName(o,c);wS(u,n,s,r)}}}a(zj,"accessConsumers");async function tL(e){let t,r,n=1;for(;!r;)try{t=await Dd.jetstream({domain:e}),r=await Dd.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(_a.get(e)==="close")break;_a.set(e,"failed"),n%10===1&&nr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Cd?n++*100:Cd;await jD(i)}return{js:t,jsm:r}}a(tL,"connectToRemoteJS");function Jj(){return Ld}a(Jj,"getDatabaseSubscriptions");var rL;function jj(e){rL=e}a(jj,"setIgnoreOrigin");var nL=100,zD=new Array(nL),Nd=0;async function wS(e,t,r,n){let{connection:s}=await wd.getNATSReferences();Dd=s,Id=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,Id),nr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(_a.get(n)==="close")break;o%10===1&&nr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(nr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await wd.createConsumer(r,e,Id,new Date(Date.now()).toISOString()));let l=o++*100<Cd?o++*100:Cd;await jD(l)}let c=!1,u;for(;!c;){if(mu.get(e+n)==="close"||_a.get(n)==="close"){mu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:NS.get(IS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),mu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===QD.ConsumerDeleted&&(await u.close(),c=!0),l.type===QD.HeartbeatsMissed){let d=l.data;nr.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===100&&(nr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await zD[Nd],zD[Nd]=Xj(l).catch(d=>{nr.error(d)}),++Nd>=nL&&(Nd=0)}catch(l){l.message==="consumer deleted"?(nr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):nr.error("Error consuming clustering ingest, restarting consumer",l)}}}a(wS,"ingestConsumer");async function Xj(e){let t=xj(e.data);Fj(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),nr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=NS.get(IS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(la.MSG_HEADERS.TRANSACTED_NODES)&&r.values(la.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(la.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!rL),kj(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(la.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:E,expiresAt:f}=t;nr.trace("processing message:",o,c,_,(l?"records: "+l.map(C=>C?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),nr.trace(`messageProcessor nats msg id: ${e.headers.get(la.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(C=>h=C),{timestamp:S,user:T,node_name:R}=E||{},b=Ld.get(c)?.get(_);if(!b)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,b.send(t);else if(l.length===1&&!u)b.send({type:yS(o),value:l[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:T,nodeName:R});else{let C=l.map((H,v)=>({type:yS(o),value:H,expiresAt:f,id:d?.[v],table:_}));for(;u;)C.push({type:yS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;b.send({type:"transaction",writes:C,table:_,timestamp:S,onCommit:h,user:T,nodeName:R})}NS.get(Gj.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Vj(e.subject.split(".").slice(0,-1).join("."),JD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){nr.error(o)}e.ack()}a(Xj,"messageProcessor");function yS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(yS,"convertOperation")});var ut=g((Kfe,RL)=>{"use strict";var Ht=Z();Ht.initSync();var Zj=require("fs-extra"),e3=require("semver"),Tu=require("path"),{monotonicFactory:t3}=require("ulidx"),oL=t3(),r3=require("util"),aL=require("child_process"),n3=r3.promisify(aL.exec),s3=aL.spawn,Kt=Ve(),Ie=P(),Md=z(),Bn=$(),Pd=As(),i3=Ad(),pu=Er(),{broadcast:o3,onMessageByType:a3,getWorkerIndex:c3}=We(),{isMainThread:cL}=require("worker_threads"),{Encoder:u3,decode:PS}=require("msgpackr"),uL=new u3,{isEmpty:uo}=Md,lL=ln(),Ffe=48*36e11;cL&&a3(Ie.ITC_EVENT_TYPES.RESTART,()=>{Tr=void 0,co=void 0});var{connect:l3,StorageType:_3,RetentionPolicy:d3,AckPolicy:US,DeliverPolicy:vS,DiscardPolicy:f3,NatsConnection:kfe,JetStreamManager:Vfe,JetStreamClient:$fe,StringCodec:Yfe,JSONCodec:E3,createInbox:BS,headers:h3,ErrorCode:iL}=require("nats"),{PACKAGE_ROOT:m3}=P(),p3=lu(),{recordAction:S3}=(Cs(),ie(hu)),_L=E3(),T3="clustering",g3=p3.engines[Kt.NATS_SERVER_NAME],R3=Tu.join(m3,"dependencies"),MS=Tu.join(R3,`${process.platform}-${process.arch}`,Kt.NATS_BINARY_NAME),DS,LS,Su,oo,ao;RL.exports={runCommand:dL,checkNATSServerInstalled:A3,createConnection:HS,getConnection:gu,getJetStreamManager:Ru,getJetStream:EL,getNATSReferences:is,getServerList:b3,createLocalStream:xS,listStreams:hL,deleteLocalStream:y3,getServerConfig:da,listRemoteStreams:N3,viewStream:I3,viewStreamIterator:w3,publishToStream:C3,request:M3,reloadNATS:GS,reloadNATSHub:P3,reloadNATSLeaf:U3,extractServerName:L3,requestErrorHandler:v3,createLocalTableStream:TL,createTableStreams:x3,purgeTableStream:gL,purgeSchemaTableStreams:G3,getStreamInfo:q3,updateLocalStreams:k3,closeConnection:O3,getJsmServerName:Ud,addNatsMsgHeader:mL,clearClientCache:fL,updateRemoteConsumer:B3,createConsumer:pL,updateConsumerIterator:H3};async function dL(e,t=void 0){let{stdout:r,stderr:n}=await n3(e,{cwd:t});if(n)throw new Error(n.replace(`
9
9
  `,""));return r.replace(`
10
- `,"")}a(lL,"runCommand");async function Ej(){try{await Y3.access(LS)}catch{return!1}let e=await lL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return K3.eq(t,dj)}a(Ej,"checkNATSServerInstalled");async function BS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await cL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await rj({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),_L()}),i}a(BS,"createConnection");function _L(){Sr=void 0,io=void 0,oo=void 0,ao=void 0}a(_L,"clearClientCache");async function hj(){Sr&&(await Sr.drain(),Sr=void 0,io=void 0,oo=void 0,ao=void 0)}a(hj,"closeConnection");var Sr,ao;async function pu(){return ao||(ao=BS(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Sr=await ao),Sr||ao}a(pu,"getConnection");async function Su(){if(io)return io;co(Sr)&&await pu();let{domain:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await Sr.jetstreamManager({domain:e,timeout:6e4}),io}a(Su,"getJetStreamManager");async function dL(){if(oo)return oo;co(Sr)&&await pu();let{domain:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=Sr.jetstream({domain:e,timeout:6e4}),oo}a(dL,"getJetStream");async function ss(){let e=Sr||await pu(),t=io||await Su(),r=oo||await dL();return{connection:e,jsm:t,js:r}}a(ss,"getNATSReferences");async function mj(e){let t=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await cL.getClusterUser(),s=await BS(t,r,n),i=vS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=uL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await wd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(mj,"getServerList");async function HS(e,t){let{jsm:r}=await ss(),n=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:nj.File,retention:sj.Limits,subjects:t,discard:ij.Old,max_msgs:s,max_bytes:i,max_age:n})}a(HS,"createLocalStream");async function fL(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(fL,"listStreams");async function pj(e){let{jsm:t}=await ss();await t.streams.delete(e)}a(pj,"deleteLocalStream");async function Sj(e){let{connection:t}=await ss(),r=[],n=vS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(uL.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(Sj,"listRemoteStreams");async function Tj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=sL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=MS(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Yt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Tj,"viewStream");async function*gj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=sL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=MS(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Yt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(gj,"viewStreamIterator");async function Rj(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=EL(n,r);let{js:s}=await ss(),i=await Dd(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:aL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),lj(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return mL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await HS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(Rj,"publishToStream");function EL(e,t){t===void 0&&(t=aj());let r=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Yt.MSG_HEADERS.ORIGIN)&&r&&t.append(Yt.MSG_HEADERS.ORIGIN,r),t}a(EL,"addNatsMsgHeader");function _a(e){e=e.toLowerCase();let t=mu.join(Bt.get(Ie.CONFIG_PARAMS.ROOTPATH),_j);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.HUB,config_file:Yt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:mu.join(t,Yt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.LEAF,config_file:Yt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.LEAF,pid_file_path:mu.join(t,Yt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(_a,"getServerConfig");async function hL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:PS.Explicit,durable_name:r,deliver_policy:US.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(hL,"createConsumer");async function Aj(e,t,r){await e.consumers.delete(t,r)}a(Aj,"removeConsumer");function Oj(e){return e.split(".")[1]}a(Oj,"extractServerName");async function bj(e,t,r=6e4,n=vS()){if(!wd.isObject(t))throw new Error("data param must be an object");let s=aL.encode(t),{connection:i}=await ss(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MS(c.data)}a(bj,"request");function xS(e){return new Promise(async(t,r)=>{let n=J3(LS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(xS,"reloadNATS");async function yj(){let{pid_file_path:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(yj,"reloadNATSHub");async function Nj(){let{pid_file_path:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(Nj,"reloadNATSLeaf");function Ij(e,t,r){let n;switch(e.code){case nL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case nL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Ij,"requestErrorHandler");async function wj(e,t){let r=t+Yt.SERVER_SUFFIX.LEAF,{connection:n}=await ss(),{jsm:s}=await Bj(r),{schema:i,table:o}=e,c=Cd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await mL(async()=>{if(e.subscribe===!0)await hL(s,c,n.info.server_name,u);else try{await Aj(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(wj,"updateRemoteConsumer");async function Cj(e,t,r,n){let s=Cd.createNatsTableStreamName(e,t),i=r+Yt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!oL&&ej()<Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await X3(o),n==="stop"&&await wd.async_set_timeout(1e3)}a(Cj,"updateConsumerIterator");function mL(e){return j3.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(mL,"exclusiveLock");async function pL(e,t){let r=Cd.createNatsTableStreamName(e,t),n=await Dd(),s=Pj(e,t,n);await HS(r,[s])}a(pL,"createLocalTableStream");async function Dj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await pL(n,s)}}a(Dj,"createTableStreams");async function SL(e,t,r=void 0){if(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Cd.createNatsTableStreamName(e,t),{domain:s}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await pu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(SL,"purgeTableStream");async function Lj(e,t){if(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await SL(e,t[r])}a(Lj,"purgeSchemaTableStreams");async function Mj(e){return(await Su()).streams.info(e)}a(Mj,"getStreamInfo");function Pj(e,t,r){return`${Yt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Pj,"createSubjectName");async function Dd(){if(hu)return hu;if(hu=(await Su())?.nc?.info?.server_name,hu===void 0)throw new Error("Unable to get jetstream manager server name");return hu}a(Dd,"getJsmServerName");async function Uj(){let e=await Su(),t=await Dd(),r=await fL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=vj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(Uj,"updateLocalStreams");function vj(e){let{config:t}=e,r=!1,n=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(vj,"updateStreamLimits");async function Bj(e){let t,r;try{t=await Sr.jetstream({domain:e}),r=await Sr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Bj,"connectToRemoteJS")});var Tu=g((qfe,OL)=>{"use strict";var da=y_(),fa=ID(),Hj=$(),xj=require("uuid").v4,Gfe=require("clone"),Md=bs(),Ea=P(),Gj=require("util"),di=Cn(),{handleHDBError:Tr,hdb_errors:qj}=ne(),{HDB_ERROR_MSGS:Ld,HTTP_STATUS_CODES:gr}=qj,{SchemaEventMsg:Pd}=Mn(),gL=at(),{getDatabases:Fj}=(Ae(),ie(ke)),{transformReq:ha}=z();OL.exports={createSchema:kj,createSchemaStructure:RL,createTable:Vj,createTableStructure:AL,createAttribute:Qj,dropSchema:$j,dropTable:Yj,dropAttribute:Kj,getBackup:zj};async function kj(e){let t=await RL(e);return Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema)),t}a(kj,"createSchema");async function RL(e){let t=da.schema_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);if(ha(e),!await fa.checkSchemaExists(e.schema))throw Tr(new Error,Ld.SCHEMA_EXISTS_ERR(e.schema),gr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,Ld.SCHEMA_EXISTS_ERR(e.schema),!0);return await di.createSchema(e),`database '${e.schema}' successfully created`}a(RL,"createSchemaStructure");async function Vj(e){return ha(e),e.hash_attribute=e.primary_key??e.hash_attribute,await AL(e)}a(Vj,"createTable");async function AL(e){let t=da.create_table_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);if(da.validateTableResidence(e.residence),!await fa.checkSchemaTableExists(e.schema,e.table))throw Tr(new Error,Ld.TABLE_EXISTS_ERR(e.schema,e.table),gr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,Ld.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:xj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await di.createTable(n,e);else throw Tr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",gr.BAD_REQUEST);else await di.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(AL,"createTableStructure");async function $j(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=da.schema_object(e),n=t??r;if(n)throw Tr(n,n.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let s=await fa.checkSchemaExists(e.schema);if(s)throw Tr(new Error,s,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,s,!0);let i=await fa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await di.dropSchema(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema)),await gL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a($j,"dropSchema");async function Yj(e){let t=da.table_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw Tr(new Error,r,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);return await di.dropTable(e),await gL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Yj,"dropTable");async function Kj(e){let t=da.attribute_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw Tr(new Error,r,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Tr(new Error,"You cannot drop a hash attribute",gr.BAD_REQUEST,void 0,void 0,!0);if(Ea.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Tr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,gr.BAD_REQUEST,void 0,void 0,!0);try{return await di.dropAttribute(e),Wj(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Hj.error(`Got an error deleting attribute ${Gj.inspect(e)}.`),n}}a(Kj,"dropAttribute");function Wj(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(Wj,"dropAttributeFromGlobal");async function Qj(e){ha(e);let t=Fj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Tr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,gr.BAD_REQUEST,void 0,void 0,!0);return await di.createAttribute(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Qj,"createAttribute");function zj(e){return di.getBackup(e)}a(zj,"getBackup")});var yL=g((kfe,bL)=>{"use strict";var{OPERATIONS_ENUM:Jj}=P(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Jj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};bL.exports=GS});var qS=g((Yfe,DL)=>{"use strict";var jj=Cn(),$fe=yL(),Ud=z(),vd=P(),Xj=Z(),{handleHDBError:NL,hdb_errors:Zj}=ne(),{HDB_ERROR_MSGS:IL,HTTP_STATUS_CODES:wL}=Zj,eX=Object.values(vd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),CL="To use this operation audit log must be enabled in harperdb-config.yaml";DL.exports=tX;async function tX(e){if(Ud.isEmpty(e.schema))throw new Error(IL.SCHEMA_REQUIRED_ERR);if(Ud.isEmpty(e.table))throw new Error(IL.TABLE_REQUIRED_ERR);if(!Xj.get(vd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw NL(new Error,CL,wL.BAD_REQUEST,vd.LOG_LEVELS.ERROR,CL,!0);let t=Ud.checkSchemaTableExist(e.schema,e.table);if(t)throw NL(new Error,t,wL.NOT_FOUND,vd.LOG_LEVELS.ERROR,t,!0);if(!Ud.isEmpty(e.search_type)&&eX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await jj.readAuditLog(e)}a(tX,"readAuditLog")});var ML=g((Wfe,LL)=>{"use strict";var{OPERATIONS_ENUM:rX}=P(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=rX.GET_BACKUP,this.schema=t,this.table=r}};LL.exports=FS});var vL=g((jfe,UL)=>{"use strict";var nX=Cn(),zfe=ML(),kS=z(),sX=P(),Jfe=Z(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:PL,HTTP_STATUS_CODES:aX}=oX;UL.exports=cX;async function cX(e){if(kS.isEmpty(e.schema))throw new Error(PL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(PL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw iX(new Error,t,aX.NOT_FOUND,sX.LOG_LEVELS.ERROR,t,!0);return await nX.getBackup(read_audit_log_object)}a(cX,"getBackup")});var FL=g((Zfe,qL)=>{var fi=require("validate.js"),HL=Xe(),ma=P(),{handleHDBError:uX,hdb_errors:lX}=ne(),{HDB_ERROR_MSGS:mt,HTTP_STATUS_CODES:_X}=lX,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),dX={STRUCTURE_USER:"structure_user"},BL=Object.values(ma.ROLE_TYPES_ENUM),fX="attribute_permissions",EX="attribute_name",{PERMS_CRUD_ENUM:pa}=ma,hX=[fX,...Object.values(pa)],xL=[pa.READ,pa.INSERT,pa.UPDATE],mX=[EX,...xL];function pX(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,GL(e,t)}a(pX,"addRoleValidation");function SX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,GL(e,t)}a(SX,"alterRoleValidation");function TX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,HL.validateObject(e,t)}a(TX,"dropRoleValidation");var gX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function GL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)gX.includes(n[o])||s.push(n[o]);s.length>0&&At(mt.INVALID_ROLE_JSON_KEYS(s),r);let i=HL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{At(o,r)}),e.permission){let o=RX(e);o&&At(o,r),BL.forEach(c=>{e.permission[c]&&!fi.isBoolean(e.permission[c])&&At(mt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(BL.indexOf(o)<0){if(o===dX.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]||At(mt.SCHEMA_NOT_FOUND(d),r)}continue}At(mt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){At(mt.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]){At(mt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{hX.includes(l)||At(mt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(pa).forEach(l=>{fi.isDefined(_[l])?fi.isBoolean(_[l])||At(mt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):At(mt.TABLE_PERM_MISSING(l),r,o,u)}),fi.isDefined(_.attribute_permissions)){if(!fi.isArray(_.attribute_permissions)){At(mt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{At(mt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(p=>{!mX.includes(p)&&p!==pa.DELETE&&At(mt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!fi.isDefined(f.attribute_name)){At(mt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){At(mt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}xL.forEach(p=>{fi.isDefined(f[p])?fi.isBoolean(f[p])||At(mt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):At(mt.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${u}`;At(mt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return AX(r)}a(GL,"customValidate");qL.exports={addRoleValidation:pX,alterRoleValidation:SX,dropRoleValidation:TX};function RX(e){let{operation:t,permission:r}=e;if(t===ma.OPERATIONS_ENUM.ADD_ROLE||t===ma.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return mt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ma.ROLE_TYPES_ENUM.SUPER_USER:ma.ROLE_TYPES_ENUM.CLUSTER_USER;return mt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(RX,"validateNoSUPerms");function AX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:mt.ROLE_PERMS_ERROR,...e};return uX(new Error,n,_X.BAD_REQUEST)}else return null}a(AX,"generateRolePermResponse");function At(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(At,"addPermError")});var zS=g((tEe,YL)=>{"use strict";var kL=qr(),VL=Gr(),OX=oi(),YS=FL(),KS=bs(),bX=require("uuid").v4,yX=require("util"),Bd=P(),NX=z(),WS=VL.searchByValue,IX=VL.searchByHash,wX=yX.promisify(OX.delete),CX=es(),DX=ia(),{hdb_errors:LX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:$L,HTTP_STATUS_CODES:gu}=LX,{UserEventMsg:QS}=Mn();YL.exports={addRole:MX,alterRole:PX,dropRole:UX,listRoles:vX};function $S(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a($S,"scrubRoleDetails");async function MX(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await WS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,$L.ROLE_ALREADY_EXISTS(e.role),gu.CONFLICT,void 0,void 0,!0);e.id||(e.id=bX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await kL.insert(s),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(MX,"addRole");async function PX(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await kL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",gu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(PX,"alterRole");async function UX(e){let t=YS.dropRoleValidation(e);if(t)throw uo(new Error,t,gu.BAD_REQUEST,void 0,void 0,!0);let r=new DX(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await IX(r));if(n.length===0)throw uo(new Error,$L.ROLE_NOT_FOUND,gu.NOT_FOUND,void 0,void 0,!0);let s=new CX(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(s)),o=!1;if(NX.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,gu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await wX(c),KS.signalUserChange(new QS(process.pid)),`${n[0].role} successfully deleted`}a(UX,"dropRole");async function vX(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(vX,"listRoles")});var zL=g((nEe,QL)=>{"use strict";var BX=Z(),Ei=require("joi"),HX=Xe(),KL=require("moment"),xX=require("fs-extra"),JS=require("path"),GX=require("lodash"),Ru=P(),{LOG_LEVELS:lo}=P(),qX="YYYY-MM-DD hh:mm:ss",FX=JS.resolve(__dirname,"../logs");QL.exports=function(e){return HX.validateBySchema(e,kX)};var kX=Ei.object({from:Ei.custom(WL),until:Ei.custom(WL),level:Ei.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:Ei.valid("asc","desc"),limit:Ei.number().min(1),start:Ei.number().min(0),log_name:Ei.custom(VX)});function WL(e,t){if(KL(e,KL.ISO_8601).format(qX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(WL,"validateDatetime");function VX(e,t){if(GX.invert(Ru.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=BX.get(Ru.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Ru.LOG_NAMES.HDB:e,i=s===Ru.LOG_NAMES.INSTALL?JS.join(FX,Ru.LOG_NAMES.INSTALL):JS.join(n,s);return xX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(VX,"validateReadLogPath")});var XS=g((iEe,jL)=>{"use strict";var Hd=P(),$X=$(),YX=Z(),KX=zL(),jS=require("path"),JL=require("fs-extra"),{once:WX}=require("events"),{handleHDBError:QX,hdb_errors:zX}=ne(),{PACKAGE_ROOT:JX}=P(),jX=jS.join(JX,"logs"),XX=1e3,ZX=200;jL.exports=eZ;async function eZ(e){let t=KX(e);if(t)throw QX(t,t.message,zX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=YX.get(Hd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Hd.LOG_NAMES.HDB:e.log_name,s=n===Hd.LOG_NAMES.INSTALL?jS.join(jX,Hd.LOG_NAMES.INSTALL):jS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?XX:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,p=0;E==="desc"&&!u&&!l&&(p=Math.max(JL.statSync(s).size-(h+5)*ZX,0));let S=JL.createReadStream(s,{start:p});S.on("error",v=>{$X.error(v)});let T=0,R=[],b="",C;S.on("data",v=>{let F=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=b+v;let M=0,Q;for(;(Q=F.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),H(C));let[J,j,ae]=Q,ce=ae.split("] ["),ge=ce[0],Ge=ce[1];ce.splice(0,2),C={timestamp:j,thread:ge,level:Ge,tags:ce,message:""},M=Q.index+J.length}b=v.slice(M)}),S.on("end",v=>{S.destroyed||C&&(C.message=b.trim(),H(C))}),S.resume();function H(v){let F,M,Q;switch(!0){case(i&&c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),v.level===o&&F>=M&&F<=Q&&T<f?T++:v.level===o&&F>=M&&F<=Q&&(hi(v,E,R),T++,T===h&&S.destroy());break;case(i&&c):F=new Date(v.timestamp),M=new Date(u),v.level===o&&F>=M&&T<f?T++:v.level===o&&F>=M&&(hi(v,E,R),T++,T===h&&S.destroy());break;case(i&&_):F=new Date(v.timestamp),Q=new Date(l),v.level===o&&F<=Q&&T<f?T++:v.level===o&&F<=Q&&(hi(v,E,R),T++,T===h&&S.destroy());break;case(c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),F>=M&&F<=Q&&T<f?T++:F>=M&&F<=Q&&(hi(v,E,R),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(hi(v,E,R),T++,T===h&&S.destroy());break;case c:F=new Date(v.timestamp),M=new Date(u),F>=M&&T<f?T++:F>=M&&T>=f&&(hi(v,E,R),T++,T===h&&S.destroy());break;case _:F=new Date(v.timestamp),Q=new Date(l),F<=Q&&T<f?T++:F<=Q&&T>=f&&(hi(v,E,R),T++,T===h&&S.destroy());break;default:T<f?T++:(hi(v,E,R),T++,T===h&&S.destroy())}}return a(H,"onLogMessage"),await WX(S,"close"),R}a(eZ,"readLog");function hi(e,t,r){t==="desc"?tZ(e,r):t==="asc"?rZ(e,r):r.push(e)}a(hi,"pushLineToResult");function tZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(tZ,"insertDescending");function rZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(rZ,"insertAscending")});var xd=g((lEe,tM)=>{"use strict";var ZS=require("joi"),{string:Au,boolean:XL,date:nZ}=ZS.types(),sZ=Xe(),{validateSchemaExists:aEe,validateTableExists:cEe,validateSchemaName:uEe}=zn(),iZ=P(),oZ=Ve(),ZL=Z();ZL.initSync();var aZ=Au.invalid(ZL.get(iZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(oZ.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(),eM={operation:Au.valid("add_node","update_node","set_node_replication"),node_name:aZ,subscriptions:ZS.array().items({table:Au.optional(),schema:Au.optional(),database:Au.optional(),subscribe:XL.required(),publish:XL.required().custom(uZ),start_time:nZ.iso()}).min(1).required()};function cZ(e){return sZ.validateBySchema(e,ZS.object(eM))}a(cZ,"addUpdateNodeValidator");function uZ(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(uZ,"checkForFalsy");tM.exports={addUpdateNodeValidator:cZ,validation_schema:eM}});var nM=g((dEe,rM)=>{var lZ=Xe(),_Z={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};rM.exports=function(e){return lZ.validateObject(e,_Z)}});var Gd=g((fEe,sM)=>{"use strict";var dZ=P().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=dZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};sM.exports=eT});var oM=g((hEe,iM)=>{"use strict";var fZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};iM.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:fZ,JWTRSAKeys:rT}});var yu=g((pEe,lM)=>{"use strict";var bu=require("jsonwebtoken"),nT=require("fs-extra"),sT=z(),_n=P(),{handleHDBError:Rr,hdb_errors:EZ}=ne(),{HTTP_STATUS_CODES:Ar,AUTHENTICATION_ERROR_MSGS:Or}=EZ,Ou=$(),aM=F_(),aT=ln(),hZ=qr().update,mZ=Gd(),pZ=bs(),{UserEventMsg:SZ}=Mn(),mi=Z();mi.initSync();var iT=require("path"),{JWTTokens:TZ,JWTRSAKeys:gZ,TOKEN_TYPE_ENUM:qd}=oM(),RZ=mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",AZ=mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Fd="RS256",oT;lM.exports={createTokens:OZ,validateOperationToken:yZ,refreshOperationToken:bZ,validateRefreshToken:uM};async function OZ(e){if(sT.isEmpty(e)||typeof e!="object")throw Rr(new Error,Or.INVALID_AUTH_OBJECT,Ar.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw Rr(new Error,Or.USERNAME_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw Rr(new Error,Or.PASSWORD_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw Rr(new Error,Or.INVALID_CREDENTIALS,Ar.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Ou.error(E),Rr(new Error,Or.INVALID_CREDENTIALS,Ar.UNAUTHORIZED,void 0,void 0,!0)}let r=await kd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await cM(i,r.private_key,r.passphrase),c=await bu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:AZ,algorithm:Fd,subject:qd.REFRESH}),u=aM.hash(c),_=new mZ(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await hZ(_)}catch(E){Ou.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Rr(new Error,Or.REFRESH_TOKEN_SAVE_FAILED,Ar.INTERNAL_SERVER_ERROR);return pZ.signalUserChange(new SZ(process.pid)),new TZ(o,c)}a(OZ,"createTokens");async function cM(e,t,r){return await bu.sign(e,{key:t,passphrase:r},{expiresIn:RZ,algorithm:Fd,subject:qd.OPERATION})}a(cM,"signOperationToken");async function kd(){if(oT===void 0)try{let e=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new gZ(i,s,n)}catch(e){throw Ou.error(e),Rr(new Error,Or.NO_ENCRYPTION_KEYS,Ar.INTERNAL_SERVER_ERROR)}return oT}a(kd,"getJWTRSAKeys");async function bZ(e){if(!e)throw Rr(new Error,Or.INVALID_BODY,Ar.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Rr(new Error,Or.REFRESH_TOKEN_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);await uM(e.refresh_token);let t=await kd(),r=await bu.decode(e.refresh_token);return{operation_token:await cM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(bZ,"refreshOperationToken");async function yZ(e){try{let t=await kd(),r=await bu.verify(e,t.public_key,{algorithms:Fd,subject:qd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Ou.warn(t),t.name&&t.name==="TokenExpiredError"?Rr(new Error,Or.TOKEN_EXPIRED,Ar.FORBIDDEN):Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED)}}a(yZ,"validateOperationToken");async function uM(e){let t;try{let r=await kd(),n=await bu.verify(e,r.public_key,{algorithms:Fd,subject:qd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Ou.warn(r),r.name&&r.name==="TokenExpiredError"?Rr(new Error,Or.TOKEN_EXPIRED,Ar.FORBIDDEN):Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED)}if(!aM.validate(t.refresh_token,e))throw Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED);return t}a(uM,"validateRefreshToken")});var cT=g((gEe,fM)=>{"use strict";var NZ=nM(),Sa=require("passport"),IZ=require("passport-local").Strategy,wZ=require("passport-http").BasicStrategy,CZ=require("util"),DZ=ln(),dM=CZ.callbackify(DZ.findAndValidateUser),TEe=Ur(),LZ=P(),_M=yu();Sa.use(new IZ(function(e,t,r){dM(e,t,r)}));Sa.use(new wZ(function(e,t,r){dM(e,t,r)}));Sa.serializeUser(function(e,t){t(null,e)});Sa.deserializeUser(function(e,t){t(null,e)});function MZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Sa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===LZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?_M.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):_M.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Sa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(MZ,"authorize");function PZ(e,t){let r=NZ(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(PZ,"checkPermissions");fM.exports={authorize:MZ,checkPermissions:PZ}});var pi=g((AEe,EM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};EM.exports={Node:uT,NodeSubscription:lT}});var mM=g((bEe,hM)=>{"use strict";var UZ=P().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=UZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};hM.exports=_T});var Nu=g((NEe,pM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};pM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var TM=g((wEe,SM)=>{"use strict";var ET=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};SM.exports=ET});var AM=g((PEe,RM)=>{"use strict";var vZ=TM(),DEe=ft(),gM=We(),BZ=$(),{getSchemaPath:LEe,getTransactionAuditStorePath:MEe}=Je(),{getDatabases:HZ}=(Ae(),ie(ke));RM.exports=xZ;async function xZ(e){let t=new vZ;try{let r=HZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await gM.environmentDataSize(schema_path,e.name),o=await gM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){BZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(xZ,"lmdbGetTableSize")});var bM=g((vEe,OM)=>{"use strict";var hT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};OM.exports=hT});var Ta=g((FEe,wM)=>{"use strict";var GZ=require("fs-extra"),qZ=require("path"),rr=require("systeminformation"),Si=$(),yM=at(),HEe=Ve(),$d=P(),FZ=AM(),kZ=As(),{getThreadInfo:NM}=je(),NT=Z();NT.initSync();var VZ=bM(),{openEnvironment:xEe}=We(),{getSchemaPath:GEe}=Je(),{database:qEe,databases:mT}=(Ae(),ie(ke)),Vd;wM.exports={getHDBProcessInfo:gT,getNetworkInfo:AT,getDiskInfo:RT,getMemoryInfo:TT,getCPUInfo:ST,getTimeInfo:pT,getSystemInformation:OT,systemInformation:$Z,getTableSize:bT,getMetrics:yT};function pT(){return rr.time()}a(pT,"getTimeInfo");async function ST(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await rr.cpu();l.cpu_speed=await rr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...R}=await rr.currentLoad();return R.cpus=[],T.forEach(b=>{let{raw_load:C,raw_load_idle:H,raw_load_irq:v,raw_load_nice:F,raw_load_system:M,raw_load_user:Q,...J}=b;R.cpus.push(J)}),l.current_load=R,l}catch(e){return Si.error(`error in getCPUInfo: ${e}`),{}}}a(ST,"getCPUInfo");async function TT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await rr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Si.error(`error in getMemoryInfo: ${e}`),{}}}a(TT,"getMemoryInfo");async function gT(){let e={core:[],clustering:[]};try{let t=await rr.processes(),r;try{r=Number.parseInt(await GZ.readFile(qZ.join(NT.get($d.CONFIG_PARAMS.ROOTPATH),$d.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===$d.NODE_ERROR_CODES.ENOENT)Si.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Si.error(`error in getHDBProcessInfo: ${t}`),e}}a(gT,"getHDBProcessInfo");async function RT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await rr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await rr.fsStats();return e.read_write=_,e.size=await rr.fsSize(),e}catch(t){return Si.error(`error in getDiskInfo: ${t}`),e}}a(RT,"getDiskInfo");async function AT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await rr.networkInterfaceDefault(),e.latency=await rr.inetChecksite("google.com"),(await rr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await rr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Si.error(`error in getNetworkInfo: ${t}`),e}}a(AT,"getNetworkInfo");async function OT(){if(Vd!==void 0)return Vd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await rr.osInfo();e=c;let u=await rr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Vd=e,Vd}catch(t){return Si.error(`error in getSystemInformation: ${t}`),e}}a(OT,"getSystemInformation");async function bT(){let e=[],t=await kZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await FZ(n));return e}a(bT,"getTableSize");async function yT(){let e={};for(let t in mT){let r=e[t]={},n=r.tables={};for(let s in mT[t])try{let i=mT[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Si.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(yT,"getMetrics");async function IM(){if(NT.get($d.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await yM.getNATSReferences(),t=await yM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(IM,"getNatsStreamInfo");async function $Z(e){let t=new VZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await OT(),t.time=pT(),t.cpu=await ST(),t.memory=await TT(),t.disk=await RT(),t.network=await AT(),t.harperdb_processes=await gT(),t.table_size=await bT(),t.metrics=await yT(),t.threads=await NM(),t.replication=await IM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await OT();break;case"time":t.time=pT();break;case"cpu":t.cpu=await ST();break;case"memory":t.memory=await TT();break;case"disk":t.disk=await RT();break;case"network":t.network=await AT();break;case"harperdb_processes":t.harperdb_processes=await gT();break;case"table_size":t.table_size=await bT();break;case"database_metrics":case"metrics":t.metrics=await yT();break;case"threads":t.threads=await NM();break;case"replication":t.replication=await IM();break;default:break}return t}a($Z,"systemInformation")});var Kd=g((VEe,CM)=>{"use strict";CM.exports={version:YZ,printVersion:KZ};var Yd=au();function YZ(){if(Yd)return Yd.version}a(YZ,"version");function KZ(){Yd&&console.log(`HarperDB Version ${Yd.version}`)}a(KZ,"printVersion")});var dn=g((WEe,PM)=>{"use strict";var WZ=qr(),IT=z(),QZ=require("util"),_o=P(),DM=Z();DM.initSync();var zZ=cT(),LM=Gr(),{Node:YEe,NodeSubscription:KEe}=pi(),JZ=ia(),jZ=mM(),{RemotePayloadObject:XZ,RemotePayloadSubscription:ZZ}=Nu(),{handleHDBError:e5,hdb_errors:t5}=ne(),{HTTP_STATUS_CODES:r5,HDB_ERROR_MSGS:n5}=t5,s5=es(),i5=Ta(),o5=Kd(),{getDatabases:a5}=(Ae(),ie(ke)),c5=QZ.promisify(zZ.authorize),u5=LM.searchByHash,l5=LM.searchByValue;PM.exports={authHeaderToUser:_5,isEmpty:d5,getNodeRecord:f5,upsertNodeRecord:E5,buildNodePayloads:h5,checkClusteringEnabled:m5,getAllNodeRecords:p5,getSystemInfo:S5,reverseSubscription:MM};async function _5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await c5(t,null),e}a(_5,"authHeaderToUser");function d5(e){return e==null}a(d5,"isEmpty");async function f5(e){let t=new JZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return u5(t)}a(f5,"getNodeRecord");async function E5(e){let t=new jZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return WZ.upsert(t)}a(E5,"upsertNodeRecord");function MM(e){if(IT.isEmpty(e.subscribe)||IT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(MM,"reverseSubscription");function h5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=IT.getTableHashAttribute(u,_),{subscribe:d,publish:E}=MM(c),f=a5()[u]?.[_],h=new ZZ(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new XZ(r,t,s,n)}a(h5,"buildNodePayloads");function m5(){if(!DM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw e5(new Error,n5.CLUSTERING_NOT_ENABLED,r5.BAD_REQUEST,void 0,void 0,!0)}a(m5,"checkClusteringEnabled");async function p5(){let e=new s5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await l5(e))}a(p5,"getAllNodeRecords");async function S5(){let e=await i5.getSystemInformation();return{hdb_version:o5.version(),node_version:e.node_version,platform:e.platform}}a(S5,"getSystemInfo")});var wT=g((zEe,FM)=>{"use strict";var Wd=at(),UM=z(),vM=Ve(),BM=P(),Qd=$(),HM=Tu(),T5=cd(),{RemotePayloadObject:g5}=Nu(),{handleHDBError:xM,hdb_errors:R5}=ne(),{HTTP_STATUS_CODES:GM}=R5,{NodeSubscription:qM}=pi();FM.exports=A5;async function A5(e,t){let r;try{r=await Wd.request(`${t}.${vM.REQUEST_SUFFIX}`,new g5(BM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Qd.trace("Response from remote describe all request:",r)}catch(o){Qd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Wd.requestErrorHandler(o,"add_node",t);throw xM(new Error,c,GM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===vM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw xM(new Error,o,GM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===BM.SYSTEM_SCHEMA_NAME){await Wd.createLocalTableStream(u,c);let h=new qM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=UM.doesSchemaExist(u),l=n[u]!==void 0,d=c?UM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(Qd.trace(`addNode creating schema: ${u}`),await HM.createSchema({operation:"create_schema",schema:u})),!d&&E){Qd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new T5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await HM.createTable(h)}await Wd.createLocalTableStream(u,c);let f=new qM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(A5,"reviewSubscriptions")});var Xd=g((jEe,$M)=>{"use strict";var{handleHDBError:zd,hdb_errors:O5}=ne(),{HTTP_STATUS_CODES:Jd}=O5,{addUpdateNodeValidator:b5}=xd(),jd=$(),VM=P(),kM=Ve(),y5=z(),Iu=at(),wu=dn(),N5=Z(),I5=wT(),{Node:w5,NodeSubscription:C5}=pi(),{broadcast:D5}=je(),L5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",M5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",P5=N5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME);$M.exports=U5;async function U5(e,t=!1){jd.trace("addNode called with:",e),wu.checkClusteringEnabled();let r=b5(e);if(r)throw zd(r,r.message,Jd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await wu.getNodeRecord(n);if(!y5.isEmptyOrZeroLength(d))throw zd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Jd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await I5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=L5,o;let c=wu.buildNodePayloads(s,P5,VM.OPERATIONS_ENUM.ADD_NODE,await wu.getSystemInfo()),u=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new C5(f.schema,f.table,f.publish,f.subscribe))}jd.trace("addNode sending remote payload:",c);let _;try{_=await Iu.request(`${n}.${kM.REQUEST_SUFFIX}`,c)}catch(d){jd.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let p=s[f];p.publish=!1,p.subscribe=!1,await Iu.updateRemoteConsumer(p,n)}let E=Iu.requestErrorHandler(d,"add_node",n);throw zd(new Error,E,Jd.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===kM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw zd(new Error,d,Jd.INTERNAL_SERVER_ERROR,"error",d)}jd.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await Iu.updateRemoteConsumer(f,n),f.subscribe===!0&&await Iu.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new w5(n,u,_.system_info);return await wu.upsertNodeRecord(l),D5({type:"nats_update"}),i.length>0?o.message=M5:o.message=`Successfully added '${n}' to manifest`,o}a(U5,"addNode")});var LT=g((ehe,WM)=>{"use strict";var{handleHDBError:CT,hdb_errors:v5}=ne(),{HTTP_STATUS_CODES:DT}=v5,{addUpdateNodeValidator:B5}=xd(),Cu=$(),KM=P(),YM=Ve(),ZEe=z(),Du=at(),Lu=dn(),H5=Z(),{cloneDeep:x5}=require("lodash"),G5=wT(),{Node:q5,NodeSubscription:F5}=pi(),{broadcast:k5}=je(),V5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",$5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Y5=H5.get(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=K5;async function K5(e){Cu.trace("updateNode called with:",e),Lu.checkClusteringEnabled();let t=B5(e);if(t)throw CT(t,t.message,DT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Lu.getNodeRecord(r);s.length>0&&(n=x5(s));let{added:i,skipped:o}=await G5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=V5,c;let u=Lu.buildNodePayloads(i,Y5,KM.OPERATIONS_ENUM.UPDATE_NODE,await Lu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Cu.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Cu.trace("updateNode sending remote payload:",u);let _;try{_=await Du.request(`${r}.${YM.REQUEST_SUFFIX}`,u)}catch(l){Cu.error(`updateNode received error from request: ${l}`);let d=Du.requestErrorHandler(l,"update_node",r);throw CT(new Error,d,DT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw CT(new Error,l,DT.INTERNAL_SERVER_ERROR,"error",l)}Cu.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Du.updateRemoteConsumer(E,r),E.subscribe===!0?await Du.updateConsumerIterator(E.schema,E.table,r,"start"):await Du.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new q5(r,[],_.system_info)]),await W5(n[0],i,_.system_info),o.length>0?c.message=$5:c.message=`Successfully updated '${r}'`,c}a(K5,"updateNode");async function W5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new F5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Lu.upsertNodeRecord(n),k5({type:"nats_update"})}a(W5,"updateNodeTable")});var XM=g((rhe,jM)=>{"use strict";var JM=require("joi"),{string:QM}=JM.types(),Q5=Xe(),zM=P(),z5=Z(),J5=Ve();jM.exports=j5;function j5(e){let t=QM.invalid(z5.get(zM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(J5.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=JM.object({operation:QM.valid(zM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Q5.validateBySchema(e,r)}a(j5,"removeNodeValidator")});var ef=g((she,nP)=>{"use strict";var{handleHDBError:ZM,hdb_errors:X5}=ne(),{HTTP_STATUS_CODES:eP}=X5,Z5=XM(),Mu=$(),tP=dn(),e8=z(),Zd=P(),rP=Ve(),MT=at(),t8=Z(),{RemotePayloadObject:r8}=Nu(),{NodeSubscription:n8}=pi(),s8=oa(),i8=oi(),{broadcast:o8}=je(),a8=t8.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);nP.exports=c8;async function c8(e){Mu.trace("removeNode called with:",e),tP.checkClusteringEnabled();let t=Z5(e);if(t)throw ZM(t,t.message,eP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await tP.getNodeRecord(r);if(e8.isEmptyOrZeroLength(n))throw ZM(new Error,`Node '${r}' was not found.`,eP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new r8(Zd.OPERATIONS_ENUM.REMOVE_NODE,a8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await MT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await MT.updateRemoteConsumer(new n8(l.schema,l.table,!1,!1),r)}catch(d){Mu.error(d)}}try{i=await MT.request(`${r}.${rP.REQUEST_SUFFIX}`,s),Mu.trace("Remove node reply from remote node:",r,i)}catch(u){Mu.error("removeNode received error from request:",u),o=!0}let c=new s8(Zd.SYSTEM_SCHEMA_NAME,Zd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await i8.deleteRecord(c),o8({type:"nats_update"}),i?.status===rP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Mu.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(c8,"removeNode")});var oP=g((ohe,iP)=>{"use strict";var sP=require("joi"),{string:u8,array:l8}=sP.types(),_8=Xe(),d8=xd();iP.exports=f8;function f8(e){let t=sP.object({operation:u8.valid("configure_cluster").required(),connections:l8.items(d8.validation_schema).required()});return _8.validateBySchema(e,t)}a(f8,"configureClusterValidator")});var PT=g((che,_P)=>{"use strict";var E8=P(),tf=$(),h8=z(),m8=ef(),p8=Xd(),aP=dn(),S8=oP(),{handleHDBError:cP,hdb_errors:T8}=ne(),{HTTP_STATUS_CODES:uP}=T8,g8="Configure cluster complete.",R8="Failed to configure the cluster. Check the logs for more details.",A8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";_P.exports=O8;async function O8(e){tf.trace("configure cluster called with:",e),aP.checkClusteringEnabled();let t=S8(e);if(t)throw cP(t,t.message,uP.BAD_REQUEST,void 0,void 0,!0);let r=await aP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await lP(m8,{operation:E8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}tf.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await lP(p8,d,d.node_name);s.push(E)}tf.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(tf.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(h8.isEmptyOrZeroLength(o))return{message:g8,connections:c};if(u)return{message:A8,failed_nodes:o,connections:c};throw cP(new Error,R8,uP.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(O8,"configureCluster");async function lP(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(lP,"functionWrapper")});var hP=g((lhe,EP)=>{"use strict";var Pu=require("joi"),b8=Xe(),{validateSchemaExists:dP,validateTableExists:y8,validateSchemaName:fP}=zn(),N8=Pu.object({operation:Pu.string().valid("purge_stream"),schema:Pu.string().custom(dP).custom(fP).optional(),database:Pu.string().custom(dP).custom(fP).optional(),table:Pu.string().custom(y8).required()});function I8(e){return b8.validateBySchema(e,N8)}a(I8,"purgeStreamValidator");EP.exports=I8});var UT=g((dhe,mP)=>{"use strict";var{handleHDBError:w8,hdb_errors:C8}=ne(),{HTTP_STATUS_CODES:D8}=C8,L8=hP(),M8=at(),P8=dn();mP.exports=U8;async function U8(e){e.schema=e.schema??e.database;let t=L8(e);if(t)throw w8(t,t.message,D8.BAD_REQUEST,void 0,void 0,!0);P8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await M8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(U8,"purgeStream")});var HT=g((Ehe,AP)=>{"use strict";var BT=dn(),v8=at(),TP=Z(),rf=P(),fo=Ve(),B8=z(),vT=$(),{RemotePayloadObject:H8}=Nu(),{ErrorCode:pP}=require("nats"),SP=TP.get(rf.CONFIG_PARAMS.CLUSTERING_ENABLED),gP=TP.get(rf.CONFIG_PARAMS.CLUSTERING_NODENAME);AP.exports={clusterStatus:x8,buildNodeStatus:RP};async function x8(){let e={node_name:gP,is_enabled:SP,connections:[]};if(!SP)return e;let t=await BT.getAllNodeRecords();if(B8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(RP(t[n],e.connections));return await Promise.allSettled(r),e}a(x8,"clusterStatus");async function RP(e,t){let r=e.name,n=new H8(rf.OPERATIONS_ENUM.CLUSTER_STATUS,gP,void 0,await BT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await v8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,vT.error(`Error getting node status from ${r} `,s))}catch(u){vT.warn(`Error getting node status from ${r}`,u),u.code===pP.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===pP.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new G8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==rf.PRE_4_0_0_VERSION&&await BT.upsertNodeRecord(u)}catch(u){vT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(RP,"buildNodeStatus");function G8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(G8,"NodeStatusObject")});var GT=g((mhe,OP)=>{"use strict";var{handleHDBError:q8,hdb_errors:F8}=ne(),{HTTP_STATUS_CODES:k8}=F8,V8=at(),$8=dn(),xT=z(),nf=require("joi"),Y8=Xe(),K8=2e3,W8=nf.object({timeout:nf.number().min(1),connected_nodes:nf.boolean(),routes:nf.boolean()});OP.exports=Q8;async function Q8(e){$8.checkClusteringEnabled();let t=Y8.validateBySchema(e,W8);if(t)throw q8(t,t.message,k8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||xT.autoCastBoolean(n),o=s===void 0||xT.autoCastBoolean(s),c={nodes:[]},u=await V8.getServerList(r??K8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(p=>({host:p.split(":")[0],port:xT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Q8,"clusterNetwork")});var IP=g((She,NP)=>{"use strict";var qT=require("joi"),bP=Xe(),{route_constraints:yP}=rp();NP.exports={setRoutesValidator:z8,deleteRoutesValidator:J8};function z8(e){let t=qT.object({server:qT.valid("hub","leaf").required(),routes:yP.required()});return bP.validateBySchema(e,t)}a(z8,"setRoutesValidator");function J8(e){let t=qT.object({routes:yP.required()});return bP.validateBySchema(e,t)}a(J8,"deleteRoutesValidator")});var kT=g((ghe,LP)=>{"use strict";var Eo=fr(),FT=z(),sf=P(),wP=IP(),{handleHDBError:CP,hdb_errors:j8}=ne(),{HTTP_STATUS_CODES:DP}=j8,X8="cluster routes successfully set",Z8="cluster routes successfully deleted";LP.exports={setRoutes:e6,getRoutes:t6,deleteRoutes:r6};function e6(e){let t=wP.setRoutesValidator(e);if(t)throw CP(t,t.message,DP.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=FT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:X8,set:o,skipped:i}}a(e6,"setRoutes");function t6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(t6,"getRoutes");function r6(e){let t=wP.deleteRoutesValidator(e);if(t)throw CP(t,t.message,DP.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],E=!1;for(let f=0,h=n.length;f<h;f++){let p=n[f];if(d.host===p.host&&d.port===p.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=FT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=FT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:Z8,deleted:i,skipped:o}}a(r6,"deleteRoutes")});var PP=g((Ahe,MP)=>{"use strict";var Uu=require("alasql"),ho=require("recursive-iterator"),Hn=$(),n6=z(),vu=P(),VT=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,i6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>vu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!vu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][vu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=s6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!vu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Uu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function s6(e){return e.filter(t=>t[vu.PERMS_CRUD_ENUM.READ])}a(s6,"filterReadRestrictedAttrs");function i6(e,t,r,n,s){o6(e,t,r,n,s)}a(i6,"interpretAST");function Bu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Bu,"addSchemaTableToMap");function o6(e,t,r,n,s){if(!e){Hn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?l6(e,t,r):e instanceof Uu.yy.Select?a6(e,t,r,n,s):e instanceof Uu.yy.Update?c6(e,t,r):e instanceof Uu.yy.Delete?u6(e,t,r):Hn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(o6,"getRecordAttributesAST");function a6(e,t,r,n,s){if(!e){Hn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(n6.isEmptyOrZeroLength(i)){Hn.error("No schema specified");return}e.from.forEach(c=>{Bu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Bu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Hn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Hn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(a6,"getSelectAttributes");function c6(e,t,r){if(!e){Hn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(c6,"getUpdateAttributes");function u6(e,t,r){if(!e){Hn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(u6,"getDeleteAttributes");function l6(e,t,r){if(!e){Hn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;Bu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.into.tableid,s,i.columnid,t,r)}a(l6,"getInsertAttributes");function $T(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a($T,"pushAttribute");MP.exports=VT});var WT=g((bhe,HP)=>{var of=Ji(),UP=require("chalk"),Qr=$(),vP=require("prompt"),{promisify:_6}=require("util"),YT=P(),d6=require("fs-extra"),f6=require("path"),E6=z(),h6=Kd(),BP=Z();BP.initSync();var m6=require("moment"),p6=_6(vP.get),S6=f6.join(BP.getHdbBasePath(),YT.LICENSE_KEY_DIR_NAME,YT.LICENSE_FILE_NAME,YT.LICENSE_FILE_NAME);HP.exports={getFingerprint:g6,setLicense:T6,parseLicense:KT,register:R6,getRegistrationInfo:O6};async function T6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await KT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(T6,"setLicense");async function g6(){let e={};try{e=await of.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(g6,"getFingerprint");async function KT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=of.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await d6.writeFile(S6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(KT,"parseLicense");async function R6(){let e=await A6();return KT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(R6,"register");async function A6(){let e=await of.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:UP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:UP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{vP.start()}catch(n){Qr.error(n)}let r;try{r=await p6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(A6,"promptForRegistration");async function O6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await of.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(E6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=h6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=m6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(O6,"getRegistrationInfo")});var GP=g((Nhe,xP)=>{"use strict";var b6=Ve(),QT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+b6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};xP.exports=QT});var kP=g((whe,FP)=>{"use strict";var qP=Ve(),zT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+qP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+qP.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"}};FP.exports=zT});var $P=g((Dhe,VP)=>{"use strict";var JT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};VP.exports=JT});var KP=g((Mhe,YP)=>{"use strict";var y6=Ve(),jT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+y6.SERVER_SUFFIX.ADMIN,this.password=r}};YP.exports=jT});var eg=g((Uhe,zP)=>{"use strict";var ga=require("path"),uf=require("fs-extra"),N6=GP(),I6=kP(),w6=$P(),C6=KP(),XT=ln(),Aa=z(),br=fr(),cf=P(),Hu=Ve(),{CONFIG_PARAMS:pt}=cf,Oa=$(),xu=Z(),WP=Rs(),ZT=at(),Ra="clustering",D6=1e4,QP=50;zP.exports={generateNatsConfig:M6,removeNatsConfig:P6,getHubConfigPath:L6};function L6(){let e=xu.get(pt.ROOTPATH);return ga.join(e,Ra,Hu.NATS_CONFIG_FILES.HUB_SERVER)}a(L6,"getHubConfigPath");async function M6(e=!1,t=void 0){xu.initSync();let r=xu.get(pt.ROOTPATH),n=ga.join(r,Ra,Hu.PID_FILES.HUB),s=ga.join(r,Ra,Hu.PID_FILES.LEAF),i=br.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ga.join(r,Ra,Hu.NATS_CONFIG_FILES.HUB_SERVER),c=ga.join(r,Ra,Hu.NATS_CONFIG_FILES.LEAF_SERVER),u=br.getConfigFromFile(pt.CLUSTERING_TLS_CERTIFICATE),_=br.getConfigFromFile(pt.CLUSTERING_TLS_PRIVATEKEY),l=br.getConfigFromFile(pt.CLUSTERING_TLS_CERT_AUTH),d=br.getConfigFromFile(pt.CLUSTERING_TLS_INSECURE),E=br.getConfigFromFile(pt.CLUSTERING_TLS_VERIFY),f=br.getConfigFromFile(pt.CLUSTERING_NODENAME),h=br.getConfigFromFile(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await ZT.checkNATSServerInstalled()||lf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await XT.listUsers(),S=br.getConfigFromFile(pt.CLUSTERING_USER),T=await XT.getClusterUser();(Aa.isEmpty(T)||T.active!==!0)&&lf(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await af(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await af(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await af(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),await af(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],b=[];for(let[J,j]of p.entries())j.role.role===cf.ROLE_TYPES_ENUM.CLUSTER_USER&&j.active&&(R.push(new C6(j.username,WP.decrypt(j.hash))),b.push(new w6(j.username,WP.decrypt(j.hash))));let C=[],{hub_routes:H}=br.getClusteringRoutes();if(!Aa.isEmptyOrZeroLength(H))for(let J of H)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${J.host}:${J.port}`);let v=new N6(br.getConfigFromFile(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,br.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NAME),br.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,R,b);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Aa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===cf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await uf.writeJson(o,v),Oa.trace(`Hub server config written to ${o}`));let F=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=new I6(br.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[F],[M],R,b,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===cf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await uf.writeJson(c,Q),Oa.trace(`Leaf server config written to ${c}`))}a(M6,"generateNatsConfig");async function af(e){let t=xu.get(e);return Aa.isEmpty(t)&&lf(`port undefined for '${e}'`),await Aa.isPortTaken(t)&&lf(`'${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(af,"isPortAvailable");function lf(e){let t=`Error generating clustering config: ${e}`;Oa.error(t),console.error(t),process.exit(1)}a(lf,"generateNatsConfigError");async function P6(e){let{port:t,config_file:r}=ZT.getServerConfig(e),{username:n,decrypt_hash:s}=await XT.getClusterUser(),i=0,o=2e3;for(;i<QP;){try{let l=await ZT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Oa.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=QP)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&Oa.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Aa.async_set_timeout(_)}let c="0".repeat(D6),u=ga.join(xu.get(pt.ROOTPATH),Ra,r);await uf.writeFile(u,c),await uf.remove(u),Oa.notify(e,"started.")}a(P6,"removeNatsConfig")});var tU=g((Bhe,eU)=>{"use strict";var zr=Z(),U6=Ji(),he=P(),Gu=Ve(),Cs=require("path"),{PACKAGE_ROOT:df}=P(),JP=Z(),_f=z(),ba="/dev/null",v6=Cs.join(df,"launchServiceScripts"),jP=Cs.join(df,"utility/scripts"),B6=Cs.join(jP,he.HDB_RESTART_SCRIPT),XP=Cs.resolve(df,"dependencies",`${process.platform}-${process.arch}`,Gu.NATS_BINARY_NAME);function ZP(){let t=U6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return _f.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_f.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:df}}a(ZP,"generateMainServerConfig");var H6=9930;function x6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=JP.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==H6?"-"+n:""),script:XP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(x6,"generateNatsHubServerConfig");var G6=9940;function q6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=JP.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==G6?"-"+n:""),script:XP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(q6,"generateNatsLeafServerConfig");function F6(){zr.initSync();let e=Cs.join(zr.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:v6,autorestart:!1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ba,t.error_file=ba),t}a(F6,"generateClusteringUpgradeV4ServiceConfig");function k6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return _f.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_f.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:jP},script:B6}}a(k6,"generateRestart");function V6(){return{apps:[ZP()]}}a(V6,"generateAllServiceConfigs");eU.exports={generateAllServiceConfigs:V6,generateMainServerConfig:ZP,generateRestart:k6,generateNatsHubServerConfig:x6,generateNatsLeafServerConfig:q6,generateClusteringUpgradeV4ServiceConfig:F6}});var hU=g((Ghe,EU)=>{"use strict";var Ue=P(),$6=z(),Ls=eg(),ff=at(),Ds=Ve(),Ti=tU(),Ef=Z(),gi=$(),Y6=dn(),{startWorker:rU,onMessageFromWorkers:K6}=je(),W6=Ta(),xhe=require("util"),Q6=require("child_process"),z6=require("fs"),{execFile:J6}=Q6,we;EU.exports={enterPM2Mode:j6,start:Ri,stop:tg,reload:sU,restart:iU,list:rg,describe:aU,connect:Ms,kill:r9,startAllServices:n9,startService:ng,getUniqueServicesList:cU,restartAllServices:s9,isServiceRegistered:uU,reloadStopStart:lU,restartHdb:oU,deleteProcess:e9,startClusteringProcesses:dU,startClusteringThreads:fU,isHdbRestartRunning:t9,isClusteringRunning:o9,stopClustering:i9,reloadClustering:a9};var qu=!1;K6(e=>{e.type==="restart"&&Ef.initSync(!0)});function j6(){qu=!0}a(j6,"enterPM2Mode");function Ms(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{gi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var yr,X6=10,nU;function Ri(e,t=!1){if(qu)return Z6(e);let r=J6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=yr.indexOf(r);o>-1&&yr.splice(o,1),!nU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<X6&&(z6.existsSync(Ls.getHubConfigPath())?Ri(e):(await Ls.generateNatsConfig(!0),Ri(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Ef.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[E]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),yr=[],!yr&&!t){let i=a(()=>{nU=!0,yr&&(yr.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)}yr.push(r)}a(Ri,"start");function Z6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(Z6,"startWithPM2");function tg(e){if(!qu){for(let t of yr||[])t.name===e&&(yr.splice(yr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(tg,"stop");function sU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(sU,"reload");function iU(e){if(!qu)for(let t of yr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(iU,"restart");function e9(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(e9,"deleteProcess");async function oU(){await Ri(Ti.generateRestart())}a(oU,"restartHdb");async function t9(){let e=await rg();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(t9,"isHdbRestartRunning");function rg(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(rg,"list");function aU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(aU,"describe");function r9(){if(!qu){for(let e of yr||[])e.kill();yr=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(r9,"kill");async function n9(){try{await dU(),await fU(),await Ri(Ti.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(n9,"startAllServices");async function ng(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ti.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ti.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ti.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ti.generateNatsHubServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ti.generateNatsLeafServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ti.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ri(r)}catch(r){throw we?.disconnect(),r}}a(ng,"startService");async function cU(){try{let e=await rg(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(cU,"getUniqueServicesList");async function s9(e=[]){try{let t=!1,r=await cU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Ue.PROCESS_DESCRIPTORS.HDB?t=!0:await iU(o))}t&&await lU(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(s9,"restartAllServices");async function uU(e){if(yr?.find(r=>r.name===e))return!0;let t=await W6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(uU,"isServiceRegistered");async function lU(e){let t=Ef.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??Ef.get(Ue.CONFIG_PARAMS.THREADS),r=await aU(e),n=$6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await tg(e),await ng(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await oU():await sU(e)}a(lU,"reloadStopStart");var _U;async function dU(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await ng(r,e)}}a(dU,"startClusteringProcesses");async function fU(){_U=rU(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await ff.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await ff.updateLocalStreams();let e=await Y6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){gi.info("Starting clustering upgrade 4.0.0 process"),rU(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fU,"startClusteringThreads");async function i9(){for(let e in Ue.CLUSTERING_PROCESSES)if(e!==Ue.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ue.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await _U.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await tg(t)}}a(i9,"stopClustering");async function o9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await uU(t)===!1)return!1}return!0}a(o9,"isClusteringRunning");async function a9(){await Ls.generateNatsConfig(!0),await ff.reloadNATSHub(),await ff.reloadNATSLeaf(),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(a9,"reloadClustering")});var AU={};Fe(AU,{compactOnStart:()=>c9,copyDb:()=>RU});async function c9(){ku.notify("Running compact on start"),console.log("Running compact on start");let e=(0,sg.get)(Ai.CONFIG_PARAMS.ROOTPATH),t=new Map,r=hr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,hf.join)(e,"backup",n+".mdb"),o=(0,hf.join)(e,Ai.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await mU(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await RU(n,o),console.log("Backing up",n,"to",i),await(0,mo.move)(s,i,{overwrite:!0})}Fu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,mo.move)(i,s,{overwrite:!0}),await(0,mo.remove)((0,hf.join)(e,Ai.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Fu()}catch(n){ku.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ig.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,mo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Fu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await mU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
10
+ `,"")}a(dL,"runCommand");async function A3(){try{await Zj.access(MS)}catch{return!1}let e=await dL(`${MS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return e3.eq(t,g3)}a(A3,"checkNATSServerInstalled");async function HS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await lL.getClusterUser();if(uo(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await l3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),fL()}),i}a(HS,"createConnection");function fL(){Tr=void 0,oo=void 0,ao=void 0,co=void 0}a(fL,"clearClientCache");async function O3(){Tr&&(await Tr.drain(),Tr=void 0,oo=void 0,ao=void 0,co=void 0)}a(O3,"closeConnection");var Tr,co;async function gu(){return co||(co=HS(Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Tr=await co),Tr||co}a(gu,"getConnection");async function Ru(){if(oo)return oo;uo(Tr)&&await gu();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=await Tr.jetstreamManager({domain:e,timeout:6e4}),oo}a(Ru,"getJetStreamManager");async function EL(){if(ao)return ao;uo(Tr)&&await gu();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ao=Tr.jetstream({domain:e,timeout:6e4}),ao}a(EL,"getJetStream");async function is(){let e=Tr||await gu(),t=oo||await Ru(),r=ao||await EL();return{connection:e,jsm:t,js:r}}a(is,"getNATSReferences");async function b3(e){let t=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await lL.getClusterUser(),s=await HS(t,r,n),i=BS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=_L.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await Md.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(b3,"getServerList");async function xS(e,t){let{jsm:r}=await is(),n=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:_3.File,retention:d3.Limits,subjects:t,discard:f3.Old,max_msgs:s,max_bytes:i,max_age:n})}a(xS,"createLocalStream");async function hL(){let{jsm:e}=await is(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(hL,"listStreams");async function y3(e){let{jsm:t}=await is();await t.streams.delete(e)}a(y3,"deleteLocalStream");async function N3(e){let{connection:t}=await is(),r=[],n=BS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(_L.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(N3,"listRemoteStreams");async function I3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=oL(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=vS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=PS(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Kt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(I3,"viewStream");async function*w3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=oL(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=vS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=PS(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Kt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(w3,"viewStreamIterator");async function C3(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=mL(n,r);let{js:s}=await is(),i=await Ud(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:uL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),S3(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return SL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await xS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(C3,"publishToStream");function mL(e,t){t===void 0&&(t=h3());let r=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Kt.MSG_HEADERS.ORIGIN)&&r&&t.append(Kt.MSG_HEADERS.ORIGIN,r),t}a(mL,"addNatsMsgHeader");function da(e){e=e.toLowerCase();let t=Tu.join(Ht.get(Ie.CONFIG_PARAMS.ROOTPATH),T3);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return uo(LS)&&(LS={port:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.HUB,config_file:Kt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Tu.join(t,Kt.PID_FILES.HUB),hdb_nats_path:t}),LS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return uo(DS)&&(DS={port:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,config_file:Kt.NATS_CONFIG_FILES.LEAF_SERVER,domain:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,pid_file_path:Tu.join(t,Kt.PID_FILES.LEAF),hdb_nats_path:t}),DS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(da,"getServerConfig");async function pL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:US.Explicit,durable_name:r,deliver_policy:vS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(pL,"createConsumer");async function D3(e,t,r){await e.consumers.delete(t,r)}a(D3,"removeConsumer");function L3(e){return e.split(".")[1]}a(L3,"extractServerName");async function M3(e,t,r=6e4,n=BS()){if(!Md.isObject(t))throw new Error("data param must be an object");let s=uL.encode(t),{connection:i}=await is(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return PS(c.data)}a(M3,"request");function GS(e){return new Promise(async(t,r)=>{let n=s3(MS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(GS,"reloadNATS");async function P3(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await GS(e)}a(P3,"reloadNATSHub");async function U3(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await GS(e)}a(U3,"reloadNATSLeaf");function v3(e,t,r){let n;switch(e.code){case iL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case iL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(v3,"requestErrorHandler");async function B3(e,t){let r=t+Kt.SERVER_SUFFIX.LEAF,{connection:n}=await is(),{jsm:s}=await $3(r),{schema:i,table:o}=e,c=Pd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await SL(async()=>{if(e.subscribe===!0)await pL(s,c,n.info.server_name,u);else try{await D3(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(B3,"updateRemoteConsumer");async function H3(e,t,r,n){let s=Pd.createNatsTableStreamName(e,t),i=r+Kt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!cL&&c3()<Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=CS();await c(o)}await o3(o),n==="stop"&&await Md.async_set_timeout(1e3)}a(H3,"updateConsumerIterator");function SL(e){return i3.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(SL,"exclusiveLock");async function TL(e,t){let r=Pd.createNatsTableStreamName(e,t),n=await Ud(),s=F3(e,t,n);await xS(r,[s])}a(TL,"createLocalTableStream");async function x3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await TL(n,s)}}a(x3,"createTableStreams");async function gL(e,t,r=void 0){if(Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Pd.createNatsTableStreamName(e,t),{domain:s}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await gu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(gL,"purgeTableStream");async function G3(e,t){if(Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await gL(e,t[r])}a(G3,"purgeSchemaTableStreams");async function q3(e){return(await Ru()).streams.info(e)}a(q3,"getStreamInfo");function F3(e,t,r){return`${Kt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(F3,"createSubjectName");async function Ud(){if(Su)return Su;if(Su=(await Ru())?.nc?.info?.server_name,Su===void 0)throw new Error("Unable to get jetstream manager server name");return Su}a(Ud,"getJsmServerName");async function k3(){let e=await Ru(),t=await Ud(),r=await hL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=V3(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(k3,"updateLocalStreams");function V3(e){let{config:t}=e,r=!1,n=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(V3,"updateStreamLimits");async function $3(e){let t,r;try{t=await Tr.jetstream({domain:e}),r=await Tr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a($3,"connectToRemoteJS")});var Au=g((zfe,yL)=>{"use strict";var fa=D_(),Ea=CD(),Y3=$(),K3=require("uuid").v4,Qfe=require("clone"),Bd=ys(),ha=P(),W3=require("util"),fi=Cn(),{handleHDBError:gr,hdb_errors:Q3}=ne(),{HDB_ERROR_MSGS:vd,HTTP_STATUS_CODES:Rr}=Q3,{SchemaEventMsg:Hd}=Mn(),AL=ut(),{getDatabases:z3}=(Ae(),ie(ke)),{transformReq:ma}=z();yL.exports={createSchema:J3,createSchemaStructure:OL,createTable:j3,createTableStructure:bL,createAttribute:rX,dropSchema:X3,dropTable:Z3,dropAttribute:eX,getBackup:nX};async function J3(e){let t=await OL(e);return Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),t}a(J3,"createSchema");async function OL(e){let t=fa.schema_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(ma(e),!await Ea.checkSchemaExists(e.schema))throw gr(new Error,vd.SCHEMA_EXISTS_ERR(e.schema),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,vd.SCHEMA_EXISTS_ERR(e.schema),!0);return await fi.createSchema(e),`database '${e.schema}' successfully created`}a(OL,"createSchemaStructure");async function j3(e){return ma(e),e.hash_attribute=e.primary_key??e.hash_attribute,await bL(e)}a(j3,"createTable");async function bL(e){let t=fa.create_table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(fa.validateTableResidence(e.residence),!await Ea.checkSchemaTableExists(e.schema,e.table))throw gr(new Error,vd.TABLE_EXISTS_ERR(e.schema,e.table),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,vd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:K3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await fi.createTable(n,e);else throw gr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Rr.BAD_REQUEST);else await fi.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(bL,"createTableStructure");async function X3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=fa.schema_object(e),n=t??r;if(n)throw gr(n,n.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let s=await Ea.checkSchemaExists(e.schema);if(s)throw gr(new Error,s,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,s,!0);let i=await Ea.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await fi.dropSchema(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),await AL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(X3,"dropSchema");async function Z3(e){let t=fa.table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);return await fi.dropTable(e),await AL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Z3,"dropTable");async function eX(e){let t=fa.attribute_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw gr(new Error,"You cannot drop a hash attribute",Rr.BAD_REQUEST,void 0,void 0,!0);if(ha.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw gr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Rr.BAD_REQUEST,void 0,void 0,!0);try{return await fi.dropAttribute(e),tX(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Y3.error(`Got an error deleting attribute ${W3.inspect(e)}.`),n}}a(eX,"dropAttribute");function tX(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(tX,"dropAttributeFromGlobal");async function rX(e){ma(e);let t=z3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw gr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Rr.BAD_REQUEST,void 0,void 0,!0);return await fi.createAttribute(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(rX,"createAttribute");function nX(e){return fi.getBackup(e)}a(nX,"getBackup")});var IL=g((jfe,NL)=>{"use strict";var{OPERATIONS_ENUM:sX}=P(),qS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=sX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};NL.exports=qS});var FS=g((eEe,ML)=>{"use strict";var iX=Cn(),Zfe=IL(),xd=z(),Gd=P(),oX=Z(),{handleHDBError:wL,hdb_errors:aX}=ne(),{HDB_ERROR_MSGS:CL,HTTP_STATUS_CODES:DL}=aX,cX=Object.values(Gd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),LL="To use this operation audit log must be enabled in harperdb-config.yaml";ML.exports=uX;async function uX(e){if(xd.isEmpty(e.schema))throw new Error(CL.SCHEMA_REQUIRED_ERR);if(xd.isEmpty(e.table))throw new Error(CL.TABLE_REQUIRED_ERR);if(!oX.get(Gd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw wL(new Error,LL,DL.BAD_REQUEST,Gd.LOG_LEVELS.ERROR,LL,!0);let t=xd.checkSchemaTableExist(e.schema,e.table);if(t)throw wL(new Error,t,DL.NOT_FOUND,Gd.LOG_LEVELS.ERROR,t,!0);if(!xd.isEmpty(e.search_type)&&cX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await iX.readAuditLog(e)}a(uX,"readAuditLog")});var UL=g((rEe,PL)=>{"use strict";var{OPERATIONS_ENUM:lX}=P(),kS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=lX.GET_BACKUP,this.schema=t,this.table=r}};PL.exports=kS});var HL=g((oEe,BL)=>{"use strict";var _X=Cn(),sEe=UL(),VS=z(),dX=P(),iEe=Z(),{handleHDBError:fX,hdb_errors:EX}=ne(),{HDB_ERROR_MSGS:vL,HTTP_STATUS_CODES:hX}=EX;BL.exports=mX;async function mX(e){if(VS.isEmpty(e.schema))throw new Error(vL.SCHEMA_REQUIRED_ERR);if(VS.isEmpty(e.table))throw new Error(vL.TABLE_REQUIRED_ERR);let t=VS.checkSchemaTableExist(e.schema,e.table);if(t)throw fX(new Error,t,hX.NOT_FOUND,dX.LOG_LEVELS.ERROR,t,!0);return await _X.getBackup(read_audit_log_object)}a(mX,"getBackup")});var VL=g((cEe,kL)=>{var Ei=require("validate.js"),GL=Xe(),pa=P(),{handleHDBError:pX,hdb_errors:SX}=ne(),{HDB_ERROR_MSGS:mt,HTTP_STATUS_CODES:TX}=SX,$S=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),gX={STRUCTURE_USER:"structure_user"},xL=Object.values(pa.ROLE_TYPES_ENUM),RX="attribute_permissions",AX="attribute_name",{PERMS_CRUD_ENUM:Sa}=pa,OX=[RX,...Object.values(Sa)],qL=[Sa.READ,Sa.INSERT,Sa.UPDATE],bX=[AX,...qL];function yX(e){let t=$S();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,FL(e,t)}a(yX,"addRoleValidation");function NX(e){let t=$S();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,FL(e,t)}a(NX,"alterRoleValidation");function IX(e){let t=$S();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,GL.validateObject(e,t)}a(IX,"dropRoleValidation");var wX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function FL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)wX.includes(n[o])||s.push(n[o]);s.length>0&&At(mt.INVALID_ROLE_JSON_KEYS(s),r);let i=GL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{At(o,r)}),e.permission){let o=CX(e);o&&At(o,r),xL.forEach(c=>{e.permission[c]&&!Ei.isBoolean(e.permission[c])&&At(mt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(xL.indexOf(o)<0){if(o===gX.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]||At(mt.SCHEMA_NOT_FOUND(d),r)}continue}At(mt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){At(mt.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]){At(mt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{OX.includes(l)||At(mt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(Sa).forEach(l=>{Ei.isDefined(_[l])?Ei.isBoolean(_[l])||At(mt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):At(mt.TABLE_PERM_MISSING(l),r,o,u)}),Ei.isDefined(_.attribute_permissions)){if(!Ei.isArray(_.attribute_permissions)){At(mt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{At(mt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(p=>{!bX.includes(p)&&p!==Sa.DELETE&&At(mt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!Ei.isDefined(f.attribute_name)){At(mt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){At(mt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}qL.forEach(p=>{Ei.isDefined(f[p])?Ei.isBoolean(f[p])||At(mt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):At(mt.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${u}`;At(mt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return DX(r)}a(FL,"customValidate");kL.exports={addRoleValidation:yX,alterRoleValidation:NX,dropRoleValidation:IX};function CX(e){let{operation:t,permission:r}=e;if(t===pa.OPERATIONS_ENUM.ADD_ROLE||t===pa.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return mt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?pa.ROLE_TYPES_ENUM.SUPER_USER:pa.ROLE_TYPES_ENUM.CLUSTER_USER;return mt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(CX,"validateNoSUPerms");function DX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:mt.ROLE_PERMS_ERROR,...e};return pX(new Error,n,TX.BAD_REQUEST)}else return null}a(DX,"generateRolePermResponse");function At(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(At,"addPermError")});var JS=g((lEe,WL)=>{"use strict";var $L=qr(),YL=Gr(),LX=ai(),KS=VL(),WS=ys(),MX=require("uuid").v4,PX=require("util"),qd=P(),UX=z(),QS=YL.searchByValue,vX=YL.searchByHash,BX=PX.promisify(LX.delete),HX=ts(),xX=ia(),{hdb_errors:GX,handleHDBError:lo}=ne(),{HDB_ERROR_MSGS:KL,HTTP_STATUS_CODES:Ou}=GX,{UserEventMsg:zS}=Mn();WL.exports={addRole:qX,alterRole:FX,dropRole:kX,listRoles:VX};function YS(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(YS,"scrubRoleDetails");async function qX(e){let t=KS.addRoleValidation(e);if(t)throw t;e=YS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await QS(r)||[])}catch(i){throw lo(i)}if(n&&n.length>0)throw lo(new Error,KL.ROLE_ALREADY_EXISTS(e.role),Ou.CONFLICT,void 0,void 0,!0);e.id||(e.id=MX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await $L.insert(s),WS.signalUserChange(new zS(process.pid)),e=YS(e),e}a(qX,"addRole");async function FX(e){let t=KS.alterRoleValidation(e);if(t)throw t;e=YS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await $L.update(r)}catch(s){throw lo(s)}if(n&&n?.message==="updated 0 of 1 records")throw lo(new Error,"Invalid role id",Ou.BAD_REQUEST,void 0,void 0,!0);return await WS.signalUserChange(new zS(process.pid)),e}a(FX,"alterRole");async function kX(e){let t=KS.dropRoleValidation(e);if(t)throw lo(new Error,t,Ou.BAD_REQUEST,void 0,void 0,!0);let r=new xX(qd.SYSTEM_SCHEMA_NAME,qd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await vX(r));if(n.length===0)throw lo(new Error,KL.ROLE_NOT_FOUND,Ou.NOT_FOUND,void 0,void 0,!0);let s=new HX(qd.SYSTEM_SCHEMA_NAME,qd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await QS(s)),o=!1;if(UX.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw lo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Ou.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await BX(c),WS.signalUserChange(new zS(process.pid)),`${n[0].role} successfully deleted`}a(kX,"dropRole");async function VX(){return QS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(VX,"listRoles")});var jL=g((dEe,JL)=>{"use strict";var $X=Z(),hi=require("joi"),YX=Xe(),QL=require("moment"),KX=require("fs-extra"),jS=require("path"),WX=require("lodash"),bu=P(),{LOG_LEVELS:_o}=P(),QX="YYYY-MM-DD hh:mm:ss",zX=jS.resolve(__dirname,"../logs");JL.exports=function(e){return YX.validateBySchema(e,JX)};var JX=hi.object({from:hi.custom(zL),until:hi.custom(zL),level:hi.valid(_o.NOTIFY,_o.FATAL,_o.ERROR,_o.WARN,_o.INFO,_o.DEBUG,_o.TRACE),order:hi.valid("asc","desc"),limit:hi.number().min(1),start:hi.number().min(0),log_name:hi.custom(jX)});function zL(e,t){if(QL(e,QL.ISO_8601).format(QX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(zL,"validateDatetime");function jX(e,t){if(WX.invert(bu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=$X.get(bu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?bu.LOG_NAMES.HDB:e,i=s===bu.LOG_NAMES.INSTALL?jS.join(zX,bu.LOG_NAMES.INSTALL):jS.join(n,s);return KX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(jX,"validateReadLogPath")});var ZS=g((EEe,ZL)=>{"use strict";var Fd=P(),XX=$(),ZX=Z(),eZ=jL(),XS=require("path"),XL=require("fs-extra"),{once:tZ}=require("events"),{handleHDBError:rZ,hdb_errors:nZ}=ne(),{PACKAGE_ROOT:sZ}=P(),iZ=XS.join(sZ,"logs"),oZ=1e3,aZ=200;ZL.exports=cZ;async function cZ(e){let t=eZ(e);if(t)throw rZ(t,t.message,nZ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=ZX.get(Fd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Fd.LOG_NAMES.HDB:e.log_name,s=n===Fd.LOG_NAMES.INSTALL?XS.join(iZ,Fd.LOG_NAMES.INSTALL):XS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?oZ:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,p=0;E==="desc"&&!u&&!l&&(p=Math.max(XL.statSync(s).size-(h+5)*aZ,0));let S=XL.createReadStream(s,{start:p});S.on("error",v=>{XX.error(v)});let T=0,R=[],b="",C;S.on("data",v=>{let F=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=b+v;let M=0,Q;for(;(Q=F.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),H(C));let[J,j,ae]=Q,ce=ae.split("] ["),ge=ce[0],Ge=ce[1];ce.splice(0,2),C={timestamp:j,thread:ge,level:Ge,tags:ce,message:""},M=Q.index+J.length}b=v.slice(M)}),S.on("end",v=>{S.destroyed||C&&(C.message=b.trim(),H(C))}),S.resume();function H(v){let F,M,Q;switch(!0){case(i&&c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),v.level===o&&F>=M&&F<=Q&&T<f?T++:v.level===o&&F>=M&&F<=Q&&(mi(v,E,R),T++,T===h&&S.destroy());break;case(i&&c):F=new Date(v.timestamp),M=new Date(u),v.level===o&&F>=M&&T<f?T++:v.level===o&&F>=M&&(mi(v,E,R),T++,T===h&&S.destroy());break;case(i&&_):F=new Date(v.timestamp),Q=new Date(l),v.level===o&&F<=Q&&T<f?T++:v.level===o&&F<=Q&&(mi(v,E,R),T++,T===h&&S.destroy());break;case(c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),F>=M&&F<=Q&&T<f?T++:F>=M&&F<=Q&&(mi(v,E,R),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(mi(v,E,R),T++,T===h&&S.destroy());break;case c:F=new Date(v.timestamp),M=new Date(u),F>=M&&T<f?T++:F>=M&&T>=f&&(mi(v,E,R),T++,T===h&&S.destroy());break;case _:F=new Date(v.timestamp),Q=new Date(l),F<=Q&&T<f?T++:F<=Q&&T>=f&&(mi(v,E,R),T++,T===h&&S.destroy());break;default:T<f?T++:(mi(v,E,R),T++,T===h&&S.destroy())}}return a(H,"onLogMessage"),await tZ(S,"close"),R}a(cZ,"readLog");function mi(e,t,r){t==="desc"?uZ(e,r):t==="asc"?lZ(e,r):r.push(e)}a(mi,"pushLineToResult");function uZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(uZ,"insertDescending");function lZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(lZ,"insertAscending")});var kd=g((TEe,nM)=>{"use strict";var eT=require("joi"),{string:yu,boolean:eM,date:_Z}=eT.types(),dZ=Xe(),{validateSchemaExists:mEe,validateTableExists:pEe,validateSchemaName:SEe}=Jn(),fZ=P(),EZ=Ve(),tM=Z();tM.initSync();var hZ=yu.invalid(tM.get(fZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(EZ.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),rM={operation:yu.valid("add_node","update_node","set_node_replication"),node_name:hZ,subscriptions:eT.array().items({table:yu.optional(),schema:yu.optional(),database:yu.optional(),subscribe:eM.required(),publish:eM.required().custom(pZ),start_time:_Z.iso()}).min(1).required()};function mZ(e){return dZ.validateBySchema(e,eT.object(rM))}a(mZ,"addUpdateNodeValidator");function pZ(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(pZ,"checkForFalsy");nM.exports={addUpdateNodeValidator:mZ,validation_schema:rM}});var iM=g((REe,sM)=>{var SZ=Xe(),TZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};sM.exports=function(e){return SZ.validateObject(e,TZ)}});var Vd=g((AEe,oM)=>{"use strict";var gZ=P().OPERATIONS_ENUM,tT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=gZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};oM.exports=tT});var cM=g((bEe,aM)=>{"use strict";var RZ={OPERATION:"operation",REFRESH:"refresh"},rT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},nT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};aM.exports={JWTTokens:rT,TOKEN_TYPE_ENUM:RZ,JWTRSAKeys:nT}});var wu=g((NEe,dM)=>{"use strict";var Iu=require("jsonwebtoken"),sT=require("fs-extra"),iT=z(),_n=P(),{handleHDBError:Ar,hdb_errors:AZ}=ne(),{HTTP_STATUS_CODES:Or,AUTHENTICATION_ERROR_MSGS:br}=AZ,Nu=$(),uM=Y_(),cT=ln(),OZ=qr().update,bZ=Vd(),yZ=ys(),{UserEventMsg:NZ}=Mn(),pi=Z();pi.initSync();var oT=require("path"),{JWTTokens:IZ,JWTRSAKeys:wZ,TOKEN_TYPE_ENUM:$d}=cM(),CZ=pi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?pi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",DZ=pi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?pi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Yd="RS256",aT;dM.exports={createTokens:LZ,validateOperationToken:PZ,refreshOperationToken:MZ,validateRefreshToken:_M};async function LZ(e){if(iT.isEmpty(e)||typeof e!="object")throw Ar(new Error,br.INVALID_AUTH_OBJECT,Or.BAD_REQUEST,void 0,void 0,!0);if(iT.isEmpty(e.username))throw Ar(new Error,br.USERNAME_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);if(iT.isEmpty(e.password))throw Ar(new Error,br.PASSWORD_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await cT.findAndValidateUser(e.username,e.password),!t)throw Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Nu.error(E),Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}let r=await Kd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await lM(i,r.private_key,r.passphrase),c=await Iu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:DZ,algorithm:Yd,subject:$d.REFRESH}),u=uM.hash(c),_=new bZ(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await OZ(_)}catch(E){Nu.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Ar(new Error,br.REFRESH_TOKEN_SAVE_FAILED,Or.INTERNAL_SERVER_ERROR);return yZ.signalUserChange(new NZ(process.pid)),new IZ(o,c)}a(LZ,"createTokens");async function lM(e,t,r){return await Iu.sign(e,{key:t,passphrase:r},{expiresIn:CZ,algorithm:Yd,subject:$d.OPERATION})}a(lM,"signOperationToken");async function Kd(){if(aT===void 0)try{let e=oT.join(pi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=oT.join(pi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=oT.join(pi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await sT.readFile(e)).toString(),s=(await sT.readFile(t)).toString(),i=(await sT.readFile(r)).toString();aT=new wZ(i,s,n)}catch(e){throw Nu.error(e),Ar(new Error,br.NO_ENCRYPTION_KEYS,Or.INTERNAL_SERVER_ERROR)}return aT}a(Kd,"getJWTRSAKeys");async function MZ(e){if(!e)throw Ar(new Error,br.INVALID_BODY,Or.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Ar(new Error,br.REFRESH_TOKEN_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);await _M(e.refresh_token);let t=await Kd(),r=await Iu.decode(e.refresh_token);return{operation_token:await lM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(MZ,"refreshOperationToken");async function PZ(e){try{let t=await Kd(),r=await Iu.verify(e,t.public_key,{algorithms:Yd,subject:$d.OPERATION});return await cT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Nu.warn(t),t.name&&t.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}}a(PZ,"validateOperationToken");async function _M(e){let t;try{let r=await Kd(),n=await Iu.verify(e,r.public_key,{algorithms:Yd,subject:$d.REFRESH});t=await cT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Nu.warn(r),r.name&&r.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}if(!uM.validate(t.refresh_token,e))throw Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED);return t}a(_M,"validateRefreshToken")});var uT=g((CEe,hM)=>{"use strict";var UZ=iM(),Ta=require("passport"),vZ=require("passport-local").Strategy,BZ=require("passport-http").BasicStrategy,HZ=require("util"),xZ=ln(),EM=HZ.callbackify(xZ.findAndValidateUser),wEe=Ur(),GZ=P(),fM=wu();Ta.use(new vZ(function(e,t,r){EM(e,t,r)}));Ta.use(new BZ(function(e,t,r){EM(e,t,r)}));Ta.serializeUser(function(e,t){t(null,e)});Ta.deserializeUser(function(e,t){t(null,e)});function qZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Ta.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===GZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?fM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):fM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ta.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(qZ,"authorize");function FZ(e,t){let r=UZ(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(FZ,"checkPermissions");hM.exports={authorize:qZ,checkPermissions:FZ}});var Si=g((LEe,mM)=>{"use strict";var lT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},_T=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};mM.exports={Node:lT,NodeSubscription:_T}});var SM=g((PEe,pM)=>{"use strict";var kZ=P().OPERATIONS_ENUM,dT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=kZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};pM.exports=dT});var Cu=g((vEe,TM)=>{"use strict";var fT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},ET=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};TM.exports={RemotePayloadObject:fT,RemotePayloadSubscription:ET}});var RM=g((HEe,gM)=>{"use strict";var hT=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};gM.exports=hT});var bM=g((kEe,OM)=>{"use strict";var VZ=RM(),GEe=ft(),AM=Qe(),$Z=$(),{getSchemaPath:qEe,getTransactionAuditStorePath:FEe}=je(),{getDatabases:YZ}=(Ae(),ie(ke));OM.exports=KZ;async function KZ(e){let t=new VZ;try{let r=YZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await AM.environmentDataSize(schema_path,e.name),o=await AM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){$Z.warn(`unable to stat table dbi due to ${r}`)}return t}a(KZ,"lmdbGetTableSize")});var NM=g(($Ee,yM)=>{"use strict";var mT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};yM.exports=mT});var ga=g((JEe,DM)=>{"use strict";var WZ=require("fs-extra"),QZ=require("path"),sr=require("systeminformation"),Ti=$(),IM=ut(),KEe=Ve(),Qd=P(),zZ=bM(),JZ=Os(),{getThreadInfo:wM}=We(),IT=Z();IT.initSync();var jZ=NM(),{openEnvironment:WEe}=Qe(),{getSchemaPath:QEe}=je(),{database:zEe,databases:pT}=(Ae(),ie(ke)),Wd;DM.exports={getHDBProcessInfo:RT,getNetworkInfo:OT,getDiskInfo:AT,getMemoryInfo:gT,getCPUInfo:TT,getTimeInfo:ST,getSystemInformation:bT,systemInformation:XZ,getTableSize:yT,getMetrics:NT};function ST(){return sr.time()}a(ST,"getTimeInfo");async function TT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await sr.cpu();l.cpu_speed=await sr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...R}=await sr.currentLoad();return R.cpus=[],T.forEach(b=>{let{raw_load:C,raw_load_idle:H,raw_load_irq:v,raw_load_nice:F,raw_load_system:M,raw_load_user:Q,...J}=b;R.cpus.push(J)}),l.current_load=R,l}catch(e){return Ti.error(`error in getCPUInfo: ${e}`),{}}}a(TT,"getCPUInfo");async function gT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await sr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ti.error(`error in getMemoryInfo: ${e}`),{}}}a(gT,"getMemoryInfo");async function RT(){let e={core:[],clustering:[]};try{let t=await sr.processes(),r;try{r=Number.parseInt(await WZ.readFile(QZ.join(IT.get(Qd.CONFIG_PARAMS.ROOTPATH),Qd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Qd.NODE_ERROR_CODES.ENOENT)Ti.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ti.error(`error in getHDBProcessInfo: ${t}`),e}}a(RT,"getHDBProcessInfo");async function AT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await sr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await sr.fsStats();return e.read_write=_,e.size=await sr.fsSize(),e}catch(t){return Ti.error(`error in getDiskInfo: ${t}`),e}}a(AT,"getDiskInfo");async function OT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await sr.networkInterfaceDefault(),e.latency=await sr.inetChecksite("google.com"),(await sr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await sr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ti.error(`error in getNetworkInfo: ${t}`),e}}a(OT,"getNetworkInfo");async function bT(){if(Wd!==void 0)return Wd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await sr.osInfo();e=c;let u=await sr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Wd=e,Wd}catch(t){return Ti.error(`error in getSystemInformation: ${t}`),e}}a(bT,"getSystemInformation");async function yT(){let e=[],t=await JZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await zZ(n));return e}a(yT,"getTableSize");async function NT(){let e={};for(let t in pT){let r=e[t]={},n=r.tables={};for(let s in pT[t])try{let i=pT[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Ti.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(NT,"getMetrics");async function CM(){if(IT.get(Qd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await IM.getNATSReferences(),t=await IM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(CM,"getNatsStreamInfo");async function XZ(e){let t=new jZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await bT(),t.time=ST(),t.cpu=await TT(),t.memory=await gT(),t.disk=await AT(),t.network=await OT(),t.harperdb_processes=await RT(),t.table_size=await yT(),t.metrics=await NT(),t.threads=await wM(),t.replication=await CM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await bT();break;case"time":t.time=ST();break;case"cpu":t.cpu=await TT();break;case"memory":t.memory=await gT();break;case"disk":t.disk=await AT();break;case"network":t.network=await OT();break;case"harperdb_processes":t.harperdb_processes=await RT();break;case"table_size":t.table_size=await yT();break;case"database_metrics":case"metrics":t.metrics=await NT();break;case"threads":t.threads=await wM();break;case"replication":t.replication=await CM();break;default:break}return t}a(XZ,"systemInformation")});var Jd=g((XEe,LM)=>{"use strict";LM.exports={version:ZZ,printVersion:e5};var zd=lu();function ZZ(){if(zd)return zd.version}a(ZZ,"version");function e5(){zd&&console.log(`HarperDB Version ${zd.version}`)}a(e5,"printVersion")});var dn=g((rhe,vM)=>{"use strict";var t5=qr(),wT=z(),r5=require("util"),fo=P(),MM=Z();MM.initSync();var n5=uT(),PM=Gr(),{Node:ehe,NodeSubscription:the}=Si(),s5=ia(),i5=SM(),{RemotePayloadObject:o5,RemotePayloadSubscription:a5}=Cu(),{handleHDBError:c5,hdb_errors:u5}=ne(),{HTTP_STATUS_CODES:l5,HDB_ERROR_MSGS:_5}=u5,d5=ts(),f5=ga(),E5=Jd(),{getDatabases:h5}=(Ae(),ie(ke)),m5=r5.promisify(n5.authorize),p5=PM.searchByHash,S5=PM.searchByValue;vM.exports={authHeaderToUser:T5,isEmpty:g5,getNodeRecord:R5,upsertNodeRecord:A5,buildNodePayloads:O5,checkClusteringEnabled:b5,getAllNodeRecords:y5,getSystemInfo:N5,reverseSubscription:UM};async function T5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await m5(t,null),e}a(T5,"authHeaderToUser");function g5(e){return e==null}a(g5,"isEmpty");async function R5(e){let t=new s5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return p5(t)}a(R5,"getNodeRecord");async function A5(e){let t=new i5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return t5.upsert(t)}a(A5,"upsertNodeRecord");function UM(e){if(wT.isEmpty(e.subscribe)||wT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(UM,"reverseSubscription");function O5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=wT.getTableHashAttribute(u,_),{subscribe:d,publish:E}=UM(c),f=h5()[u]?.[_],h=new a5(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new o5(r,t,s,n)}a(O5,"buildNodePayloads");function b5(){if(!MM.get(fo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw c5(new Error,_5.CLUSTERING_NOT_ENABLED,l5.BAD_REQUEST,void 0,void 0,!0)}a(b5,"checkClusteringEnabled");async function y5(){let e=new d5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await S5(e))}a(y5,"getAllNodeRecords");async function N5(){let e=await f5.getSystemInformation();return{hdb_version:E5.version(),node_version:e.node_version,platform:e.platform}}a(N5,"getSystemInfo")});var CT=g((she,VM)=>{"use strict";var jd=ut(),BM=z(),HM=Ve(),xM=P(),Xd=$(),GM=Au(),I5=dd(),{RemotePayloadObject:w5}=Cu(),{handleHDBError:qM,hdb_errors:C5}=ne(),{HTTP_STATUS_CODES:FM}=C5,{NodeSubscription:kM}=Si();VM.exports=D5;async function D5(e,t){let r;try{r=await jd.request(`${t}.${HM.REQUEST_SUFFIX}`,new w5(xM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Xd.trace("Response from remote describe all request:",r)}catch(o){Xd.error(`addNode received error from describe all request to remote node: ${o}`);let c=jd.requestErrorHandler(o,"add_node",t);throw qM(new Error,c,FM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===HM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw qM(new Error,o,FM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===xM.SYSTEM_SCHEMA_NAME){await jd.createLocalTableStream(u,c);let h=new kM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=BM.doesSchemaExist(u),l=n[u]!==void 0,d=c?BM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(Xd.trace(`addNode creating schema: ${u}`),await GM.createSchema({operation:"create_schema",schema:u})),!d&&E){Xd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new I5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await GM.createTable(h)}await jd.createLocalTableStream(u,c);let f=new kM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(D5,"reviewSubscriptions")});var rf=g((ohe,KM)=>{"use strict";var{handleHDBError:Zd,hdb_errors:L5}=ne(),{HTTP_STATUS_CODES:ef}=L5,{addUpdateNodeValidator:M5}=kd(),tf=$(),YM=P(),$M=Ve(),P5=z(),Du=ut(),Lu=dn(),U5=Z(),v5=CT(),{Node:B5,NodeSubscription:H5}=Si(),{broadcast:x5}=We(),G5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",q5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",F5=U5.get(YM.CONFIG_PARAMS.CLUSTERING_NODENAME);KM.exports=k5;async function k5(e,t=!1){tf.trace("addNode called with:",e),Lu.checkClusteringEnabled();let r=M5(e);if(r)throw Zd(r,r.message,ef.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Lu.getNodeRecord(n);if(!P5.isEmptyOrZeroLength(d))throw Zd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,ef.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await v5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=G5,o;let c=Lu.buildNodePayloads(s,F5,YM.OPERATIONS_ENUM.ADD_NODE,await Lu.getSystemInfo()),u=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new H5(f.schema,f.table,f.publish,f.subscribe))}tf.trace("addNode sending remote payload:",c);let _;try{_=await Du.request(`${n}.${$M.REQUEST_SUFFIX}`,c)}catch(d){tf.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let p=s[f];p.publish=!1,p.subscribe=!1,await Du.updateRemoteConsumer(p,n)}let E=Du.requestErrorHandler(d,"add_node",n);throw Zd(new Error,E,ef.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===$M.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Zd(new Error,d,ef.INTERNAL_SERVER_ERROR,"error",d)}tf.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await Du.updateRemoteConsumer(f,n),f.subscribe===!0&&await Du.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new B5(n,u,_.system_info);return await Lu.upsertNodeRecord(l),x5({type:"nats_update"}),i.length>0?o.message=q5:o.message=`Successfully added '${n}' to manifest`,o}a(k5,"addNode")});var MT=g((uhe,zM)=>{"use strict";var{handleHDBError:DT,hdb_errors:V5}=ne(),{HTTP_STATUS_CODES:LT}=V5,{addUpdateNodeValidator:$5}=kd(),Mu=$(),QM=P(),WM=Ve(),che=z(),Pu=ut(),Uu=dn(),Y5=Z(),{cloneDeep:K5}=require("lodash"),W5=CT(),{Node:Q5,NodeSubscription:z5}=Si(),{broadcast:J5}=We(),j5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",X5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Z5=Y5.get(QM.CONFIG_PARAMS.CLUSTERING_NODENAME);zM.exports=e8;async function e8(e){Mu.trace("updateNode called with:",e),Uu.checkClusteringEnabled();let t=$5(e);if(t)throw DT(t,t.message,LT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Uu.getNodeRecord(r);s.length>0&&(n=K5(s));let{added:i,skipped:o}=await W5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=j5,c;let u=Uu.buildNodePayloads(i,Z5,QM.OPERATIONS_ENUM.UPDATE_NODE,await Uu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Mu.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Mu.trace("updateNode sending remote payload:",u);let _;try{_=await Pu.request(`${r}.${WM.REQUEST_SUFFIX}`,u)}catch(l){Mu.error(`updateNode received error from request: ${l}`);let d=Pu.requestErrorHandler(l,"update_node",r);throw DT(new Error,d,LT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===WM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw DT(new Error,l,LT.INTERNAL_SERVER_ERROR,"error",l)}Mu.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Pu.updateRemoteConsumer(E,r),E.subscribe===!0?await Pu.updateConsumerIterator(E.schema,E.table,r,"start"):await Pu.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new Q5(r,[],_.system_info)]),await t8(n[0],i,_.system_info),o.length>0?c.message=X5:c.message=`Successfully updated '${r}'`,c}a(e8,"updateNode");async function t8(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new z5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Uu.upsertNodeRecord(n),J5({type:"nats_update"})}a(t8,"updateNodeTable")});var eP=g((_he,ZM)=>{"use strict";var XM=require("joi"),{string:JM}=XM.types(),r8=Xe(),jM=P(),n8=Z(),s8=Ve();ZM.exports=i8;function i8(e){let t=JM.invalid(n8.get(jM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(s8.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=XM.object({operation:JM.valid(jM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return r8.validateBySchema(e,r)}a(i8,"removeNodeValidator")});var sf=g((fhe,iP)=>{"use strict";var{handleHDBError:tP,hdb_errors:o8}=ne(),{HTTP_STATUS_CODES:rP}=o8,a8=eP(),vu=$(),nP=dn(),c8=z(),nf=P(),sP=Ve(),PT=ut(),u8=Z(),{RemotePayloadObject:l8}=Cu(),{NodeSubscription:_8}=Si(),d8=oa(),f8=ai(),{broadcast:E8}=We(),h8=u8.get(nf.CONFIG_PARAMS.CLUSTERING_NODENAME);iP.exports=m8;async function m8(e){vu.trace("removeNode called with:",e),nP.checkClusteringEnabled();let t=a8(e);if(t)throw tP(t,t.message,rP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await nP.getNodeRecord(r);if(c8.isEmptyOrZeroLength(n))throw tP(new Error,`Node '${r}' was not found.`,rP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new l8(nf.OPERATIONS_ENUM.REMOVE_NODE,h8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await PT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await PT.updateRemoteConsumer(new _8(l.schema,l.table,!1,!1),r)}catch(d){vu.error(d)}}try{i=await PT.request(`${r}.${sP.REQUEST_SUFFIX}`,s),vu.trace("Remove node reply from remote node:",r,i)}catch(u){vu.error("removeNode received error from request:",u),o=!0}let c=new d8(nf.SYSTEM_SCHEMA_NAME,nf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await f8.deleteRecord(c),E8({type:"nats_update"}),i?.status===sP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(vu.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(m8,"removeNode")});var cP=g((hhe,aP)=>{"use strict";var oP=require("joi"),{string:p8,array:S8}=oP.types(),T8=Xe(),g8=kd();aP.exports=R8;function R8(e){let t=oP.object({operation:p8.valid("configure_cluster").required(),connections:S8.items(g8.validation_schema).required()});return T8.validateBySchema(e,t)}a(R8,"configureClusterValidator")});var UT=g((phe,fP)=>{"use strict";var A8=P(),of=$(),O8=z(),b8=sf(),y8=rf(),uP=dn(),N8=cP(),{handleHDBError:lP,hdb_errors:I8}=ne(),{HTTP_STATUS_CODES:_P}=I8,w8="Configure cluster complete.",C8="Failed to configure the cluster. Check the logs for more details.",D8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";fP.exports=L8;async function L8(e){of.trace("configure cluster called with:",e),uP.checkClusteringEnabled();let t=N8(e);if(t)throw lP(t,t.message,_P.BAD_REQUEST,void 0,void 0,!0);let r=await uP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await dP(b8,{operation:A8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}of.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await dP(y8,d,d.node_name);s.push(E)}of.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(of.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(O8.isEmptyOrZeroLength(o))return{message:w8,connections:c};if(u)return{message:D8,failed_nodes:o,connections:c};throw lP(new Error,C8,_P.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(L8,"configureCluster");async function dP(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(dP,"functionWrapper")});var pP=g((The,mP)=>{"use strict";var Bu=require("joi"),M8=Xe(),{validateSchemaExists:EP,validateTableExists:P8,validateSchemaName:hP}=Jn(),U8=Bu.object({operation:Bu.string().valid("purge_stream"),schema:Bu.string().custom(EP).custom(hP).optional(),database:Bu.string().custom(EP).custom(hP).optional(),table:Bu.string().custom(P8).required()});function v8(e){return M8.validateBySchema(e,U8)}a(v8,"purgeStreamValidator");mP.exports=v8});var vT=g((Rhe,SP)=>{"use strict";var{handleHDBError:B8,hdb_errors:H8}=ne(),{HTTP_STATUS_CODES:x8}=H8,G8=pP(),q8=ut(),F8=dn();SP.exports=k8;async function k8(e){e.schema=e.schema??e.database;let t=G8(e);if(t)throw B8(t,t.message,x8.BAD_REQUEST,void 0,void 0,!0);F8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await q8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(k8,"purgeStream")});var xT=g((Ohe,bP)=>{"use strict";var HT=dn(),V8=ut(),RP=Z(),af=P(),Eo=Ve(),$8=z(),BT=$(),{RemotePayloadObject:Y8}=Cu(),{ErrorCode:TP}=require("nats"),gP=RP.get(af.CONFIG_PARAMS.CLUSTERING_ENABLED),AP=RP.get(af.CONFIG_PARAMS.CLUSTERING_NODENAME);bP.exports={clusterStatus:K8,buildNodeStatus:OP};async function K8(){let e={node_name:AP,is_enabled:gP,connections:[]};if(!gP)return e;let t=await HT.getAllNodeRecords();if($8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(OP(t[n],e.connections));return await Promise.allSettled(r),e}a(K8,"clusterStatus");async function OP(e,t){let r=e.name,n=new Y8(af.OPERATIONS_ENUM.CLUSTER_STATUS,AP,void 0,await HT.getSystemInfo()),s,i,o=Eo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await V8.request(Eo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===Eo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Eo.CLUSTER_STATUS_STATUSES.CLOSED,BT.error(`Error getting node status from ${r} `,s))}catch(u){BT.warn(`Error getting node status from ${r}`,u),u.code===TP.NoResponders?o=Eo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===TP.Timeout?o=Eo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Eo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new W8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==af.PRE_4_0_0_VERSION&&await HT.upsertNodeRecord(u)}catch(u){BT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(OP,"buildNodeStatus");function W8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(W8,"NodeStatusObject")});var qT=g((yhe,yP)=>{"use strict";var{handleHDBError:Q8,hdb_errors:z8}=ne(),{HTTP_STATUS_CODES:J8}=z8,j8=ut(),X8=dn(),GT=z(),cf=require("joi"),Z8=Xe(),e6=2e3,t6=cf.object({timeout:cf.number().min(1),connected_nodes:cf.boolean(),routes:cf.boolean()});yP.exports=r6;async function r6(e){X8.checkClusteringEnabled();let t=Z8.validateBySchema(e,t6);if(t)throw Q8(t,t.message,J8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||GT.autoCastBoolean(n),o=s===void 0||GT.autoCastBoolean(s),c={nodes:[]},u=await j8.getServerList(r??e6),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(p=>({host:p.split(":")[0],port:GT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(r6,"clusterNetwork")});var CP=g((Ihe,wP)=>{"use strict";var FT=require("joi"),NP=Xe(),{route_constraints:IP}=np();wP.exports={setRoutesValidator:n6,deleteRoutesValidator:s6};function n6(e){let t=FT.object({server:FT.valid("hub","leaf").required(),routes:IP.required()});return NP.validateBySchema(e,t)}a(n6,"setRoutesValidator");function s6(e){let t=FT.object({routes:IP.required()});return NP.validateBySchema(e,t)}a(s6,"deleteRoutesValidator")});var VT=g((Che,PP)=>{"use strict";var ho=Er(),kT=z(),uf=P(),DP=CP(),{handleHDBError:LP,hdb_errors:i6}=ne(),{HTTP_STATUS_CODES:MP}=i6,o6="cluster routes successfully set",a6="cluster routes successfully deleted";PP.exports={setRoutes:c6,getRoutes:u6,deleteRoutes:l6};function c6(e){let t=DP.setRoutesValidator(e);if(t)throw LP(t,t.message,MP.BAD_REQUEST,void 0,void 0,!0);let r=ho.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=kT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:o6,set:o,skipped:i}}a(c6,"setRoutes");function u6(){let e=ho.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(u6,"getRoutes");function l6(e){let t=DP.deleteRoutesValidator(e);if(t)throw LP(t,t.message,MP.BAD_REQUEST,void 0,void 0,!0);let r=ho.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],E=!1;for(let f=0,h=n.length;f<h;f++){let p=n[f];if(d.host===p.host&&d.port===p.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=kT.isEmptyOrZeroLength(n)?null:n,ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=kT.isEmptyOrZeroLength(s)?null:s,ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:a6,deleted:i,skipped:o}}a(l6,"deleteRoutes")});var vP=g((Lhe,UP)=>{"use strict";var Hu=require("alasql"),mo=require("recursive-iterator"),Hn=$(),_6=z(),xu=P(),$T=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,f6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>xu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!xu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][xu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=d6(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(_=>!xu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Hu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function d6(e){return e.filter(t=>t[xu.PERMS_CRUD_ENUM.READ])}a(d6,"filterReadRestrictedAttrs");function f6(e,t,r,n,s){E6(e,t,r,n,s)}a(f6,"interpretAST");function Gu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Gu,"addSchemaTableToMap");function E6(e,t,r,n,s){if(!e){Hn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Hu.yy.Insert?S6(e,t,r):e instanceof Hu.yy.Select?h6(e,t,r,n,s):e instanceof Hu.yy.Update?m6(e,t,r):e instanceof Hu.yy.Delete?p6(e,t,r):Hn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(E6,"getRecordAttributesAST");function h6(e,t,r,n,s){if(!e){Hn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(_6.isEmptyOrZeroLength(i)){Hn.error("No schema specified");return}e.from.forEach(c=>{Gu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Gu(c.table,t,r,n,s)});let o=new mo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Hn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new mo(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new mo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new mo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Hn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(h6,"getSelectAttributes");function m6(e,t,r){if(!e){Hn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.table.databaseid;Gu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(m6,"getUpdateAttributes");function p6(e,t,r){if(!e){Hn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new mo(e.where),s=e.table.databaseid;Gu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(p6,"getDeleteAttributes");function S6(e,t,r){if(!e){Hn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.into.databaseid;Gu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.into.tableid,s,i.columnid,t,r)}a(S6,"getInsertAttributes");function YT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(YT,"pushAttribute");UP.exports=$T});var QT=g((Phe,GP)=>{var lf=ji(),BP=require("chalk"),Qr=$(),HP=require("prompt"),{promisify:T6}=require("util"),KT=P(),g6=require("fs-extra"),R6=require("path"),A6=z(),O6=Jd(),xP=Z();xP.initSync();var b6=require("moment"),y6=T6(HP.get),N6=R6.join(xP.getHdbBasePath(),KT.LICENSE_KEY_DIR_NAME,KT.LICENSE_FILE_NAME,KT.LICENSE_FILE_NAME);GP.exports={getFingerprint:w6,setLicense:I6,parseLicense:WT,register:C6,getRegistrationInfo:L6};async function I6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await WT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(I6,"setLicense");async function w6(){let e={};try{e=await lf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(w6,"getFingerprint");async function WT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=lf.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await g6.writeFile(N6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(WT,"parseLicense");async function C6(){let e=await D6();return WT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(C6,"register");async function D6(){let e=await lf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:BP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:BP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{HP.start()}catch(n){Qr.error(n)}let r;try{r=await y6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(D6,"promptForRegistration");async function L6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await lf.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(A6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=O6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=b6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(L6,"getRegistrationInfo")});var FP=g((vhe,qP)=>{"use strict";var M6=Ve(),zT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+M6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};qP.exports=zT});var $P=g((Hhe,VP)=>{"use strict";var kP=Ve(),JT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+kP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+kP.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"}};VP.exports=JT});var KP=g((Ghe,YP)=>{"use strict";var jT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};YP.exports=jT});var QP=g((Fhe,WP)=>{"use strict";var P6=Ve(),XT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+P6.SERVER_SUFFIX.ADMIN,this.password=r}};WP.exports=XT});var tg=g((Vhe,jP)=>{"use strict";var Ra=require("path"),ff=require("fs-extra"),U6=FP(),v6=$P(),B6=KP(),H6=QP(),ZT=ln(),Oa=z(),yr=Er(),df=P(),qu=Ve(),{CONFIG_PARAMS:pt}=df,ba=$(),Fu=Z(),zP=As(),eg=ut(),Aa="clustering",x6=1e4,JP=50;jP.exports={generateNatsConfig:q6,removeNatsConfig:F6,getHubConfigPath:G6};function G6(){let e=Fu.get(pt.ROOTPATH);return Ra.join(e,Aa,qu.NATS_CONFIG_FILES.HUB_SERVER)}a(G6,"getHubConfigPath");async function q6(e=!1,t=void 0){Fu.initSync();let r=Fu.get(pt.ROOTPATH),n=Ra.join(r,Aa,qu.PID_FILES.HUB),s=Ra.join(r,Aa,qu.PID_FILES.LEAF),i=yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ra.join(r,Aa,qu.NATS_CONFIG_FILES.HUB_SERVER),c=Ra.join(r,Aa,qu.NATS_CONFIG_FILES.LEAF_SERVER),u=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERTIFICATE),_=yr.getConfigFromFile(pt.CLUSTERING_TLS_PRIVATEKEY),l=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERT_AUTH),d=yr.getConfigFromFile(pt.CLUSTERING_TLS_INSECURE),E=yr.getConfigFromFile(pt.CLUSTERING_TLS_VERIFY),f=yr.getConfigFromFile(pt.CLUSTERING_NODENAME),h=yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await eg.checkNATSServerInstalled()||Ef("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await ZT.listUsers(),S=yr.getConfigFromFile(pt.CLUSTERING_USER),T=await ZT.getClusterUser();(Oa.isEmpty(T)||T.active!==!0)&&Ef(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await _f(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await _f(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await _f(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),await _f(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],b=[];for(let[J,j]of p.entries())j.role.role===df.ROLE_TYPES_ENUM.CLUSTER_USER&&j.active&&(R.push(new H6(j.username,zP.decrypt(j.hash))),b.push(new B6(j.username,zP.decrypt(j.hash))));let C=[],{hub_routes:H}=yr.getClusteringRoutes();if(!Oa.isEmptyOrZeroLength(H))for(let J of H)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${J.host}:${J.port}`);let v=new U6(yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NAME),yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,R,b);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Oa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===df.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ff.writeJson(o,v),ba.trace(`Hub server config written to ${o}`));let F=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=new v6(yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[F],[M],R,b,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===df.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ff.writeJson(c,Q),ba.trace(`Leaf server config written to ${c}`))}a(q6,"generateNatsConfig");async function _f(e){let t=Fu.get(e);return Oa.isEmpty(t)&&Ef(`port undefined for '${e}'`),await Oa.isPortTaken(t)&&Ef(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(_f,"isPortAvailable");function Ef(e){let t=`Error generating clustering config: ${e}`;ba.error(t),console.error(t),process.exit(1)}a(Ef,"generateNatsConfigError");async function F6(e){let{port:t,config_file:r}=eg.getServerConfig(e),{username:n,decrypt_hash:s}=await ZT.getClusterUser(),i=0,o=2e3;for(;i<JP;){try{let l=await eg.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){ba.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=JP)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&ba.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Oa.async_set_timeout(_)}let c="0".repeat(x6),u=Ra.join(Fu.get(pt.ROOTPATH),Aa,r);await ff.writeFile(u,c),await ff.remove(u),ba.notify(e,"started.")}a(F6,"removeNatsConfig")});var nU=g((Yhe,rU)=>{"use strict";var zr=Z(),k6=ji(),he=P(),ku=Ve(),Ds=require("path"),{PACKAGE_ROOT:mf}=P(),XP=Z(),hf=z(),ya="/dev/null",V6=Ds.join(mf,"launchServiceScripts"),ZP=Ds.join(mf,"utility/scripts"),$6=Ds.join(ZP,he.HDB_RESTART_SCRIPT),eU=Ds.resolve(mf,"dependencies",`${process.platform}-${process.arch}`,ku.NATS_BINARY_NAME);function tU(){let t=k6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return hf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=hf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:mf}}a(tU,"generateMainServerConfig");var Y6=9930;function K6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",ku.NATS_CONFIG_FILES.HUB_SERVER),r=Ds.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=XP.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==Y6?"-"+n:""),script:eU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(K6,"generateNatsHubServerConfig");var W6=9940;function Q6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",ku.NATS_CONFIG_FILES.LEAF_SERVER),r=Ds.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=XP.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==W6?"-"+n:""),script:eU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(Q6,"generateNatsLeafServerConfig");function z6(){zr.initSync();let e=Ds.join(zr.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:V6,autorestart:!1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ya,t.error_file=ya),t}a(z6,"generateClusteringUpgradeV4ServiceConfig");function J6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return hf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=hf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:ZP},script:$6}}a(J6,"generateRestart");function j6(){return{apps:[tU()]}}a(j6,"generateAllServiceConfigs");rU.exports={generateAllServiceConfigs:j6,generateMainServerConfig:tU,generateRestart:J6,generateNatsHubServerConfig:K6,generateNatsLeafServerConfig:Q6,generateClusteringUpgradeV4ServiceConfig:z6}});var pU=g((Qhe,mU)=>{"use strict";var Ue=P(),X6=z(),Ms=tg(),pf=ut(),Ls=Ve(),gi=nU(),Sf=Z(),Ri=$(),Z6=dn(),{startWorker:sU,onMessageFromWorkers:e9}=We(),t9=ga(),Whe=require("util"),r9=require("child_process"),n9=require("fs"),{execFile:s9}=r9,we;mU.exports={enterPM2Mode:i9,start:Ai,stop:rg,reload:oU,restart:aU,list:ng,describe:uU,connect:Ps,kill:l9,startAllServices:_9,startService:sg,getUniqueServicesList:lU,restartAllServices:d9,isServiceRegistered:_U,reloadStopStart:dU,restartHdb:cU,deleteProcess:c9,startClusteringProcesses:EU,startClusteringThreads:hU,isHdbRestartRunning:u9,isClusteringRunning:E9,stopClustering:f9,reloadClustering:h9};var Vu=!1;e9(e=>{e.type==="restart"&&Sf.initSync(!0)});function i9(){Vu=!0}a(i9,"enterPM2Mode");function Ps(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{Ri.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ps,"connect");var Nr,o9=10,iU;function Ai(e,t=!1){if(Vu)return a9(e);let r=s9(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Nr.indexOf(r);o>-1&&Nr.splice(o,1),!iU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<o9&&(n9.existsSync(Ms.getHubConfigPath())?Ai(e):(await Ms.generateNatsConfig(!0),Ai(e),await new Promise(c=>setTimeout(c,3e3)),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Sf.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?Ri.OUTPUTS.STDERR:Ri.OUTPUTS.STDOUT;Ri.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ls.LOG_LEVELS[E]}if(Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?Ri.OUTPUTS.STDERR:Ri.OUTPUTS.STDOUT;Ri.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Nr=[],!Nr&&!t){let i=a(()=>{iU=!0,Nr&&(Nr.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)}Nr.push(r)}a(Ai,"start");function a9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(a9,"startWithPM2");function rg(e){if(!Vu){for(let t of Nr||[])t.name===e&&(Nr.splice(Nr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(rg,"stop");function oU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(oU,"reload");function aU(e){if(!Vu)for(let t of Nr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(aU,"restart");function c9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(c9,"deleteProcess");async function cU(){await Ai(gi.generateRestart())}a(cU,"restartHdb");async function u9(){let e=await ng();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(u9,"isHdbRestartRunning");function ng(){return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(ng,"list");function uU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(uU,"describe");function l9(){if(!Vu){for(let e of Nr||[])e.kill();Nr=[];return}return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(l9,"kill");async function _9(){try{await EU(),await hU(),await Ai(gi.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(_9,"startAllServices");async function sg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=gi.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=gi.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=gi.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=gi.generateNatsHubServerConfig(),await Ai(r,t),await Ms.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=gi.generateNatsLeafServerConfig(),await Ai(r,t),await Ms.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=gi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ai(r)}catch(r){throw we?.disconnect(),r}}a(sg,"startService");async function lU(){try{let e=await ng(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(lU,"getUniqueServicesList");async function d9(e=[]){try{let t=!1,r=await lU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Ue.PROCESS_DESCRIPTORS.HDB?t=!0:await aU(o))}t&&await dU(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(d9,"restartAllServices");async function _U(e){if(Nr?.find(r=>r.name===e))return!0;let t=await t9.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(_U,"isServiceRegistered");async function dU(e){let t=Sf.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??Sf.get(Ue.CONFIG_PARAMS.THREADS),r=await uU(e),n=X6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await rg(e),await sg(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await cU():await oU(e)}a(dU,"reloadStopStart");var fU;async function EU(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await sg(r,e)}}a(EU,"startClusteringProcesses");async function hU(){fU=sU(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await pf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await pf.updateLocalStreams();let e=await Z6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){Ri.info("Starting clustering upgrade 4.0.0 process"),sU(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(hU,"startClusteringThreads");async function f9(){for(let e in Ue.CLUSTERING_PROCESSES)if(e!==Ue.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ue.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await fU.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await rg(t)}}a(f9,"stopClustering");async function E9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await _U(t)===!1)return!1}return!0}a(E9,"isClusteringRunning");async function h9(){await Ms.generateNatsConfig(!0),await pf.reloadNATSHub(),await pf.reloadNATSLeaf(),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(h9,"reloadClustering")});var bU={};Fe(bU,{compactOnStart:()=>m9,copyDb:()=>OU});async function m9(){Yu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,ig.get)(Oi.CONFIG_PARAMS.ROOTPATH),t=new Map,r=mr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,Tf.join)(e,"backup",n+".mdb"),o=(0,Tf.join)(e,Oi.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await SU(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await OU(n,o),console.log("Backing up",n,"to",i),await(0,po.move)(s,i,{overwrite:!0})}$u();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,po.move)(i,s,{overwrite:!0}),await(0,po.remove)((0,Tf.join)(e,Oi.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));$u()}catch(n){Yu.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,og.updateConfigValue)(Oi.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,po.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw $u(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await SU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
11
11
  Total record count before compaction: ${i}, total after: ${c}.
12
- Database backup has not been removed and can be found here: ${s}`;ku.error(u),console.error(u)}(0,sg.get)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,mo.remove)(s))}(0,ig.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function mU(e){let t=await(0,gU.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function RU(e,t){console.log("copyDb start");let r=hr()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,pU.open)(new SU.default(t)),c=o.openDB(mf.INTERNAL_DBIS_NAME),u,_=0,l=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:l})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=Sf(),T?h.compression=T:delete h.compression,S?.dictionary?.toString()===T?.dictionary?.toString()&&(S=null,T=null)),c.put(f,h),!(p||h.indexed))continue;let R=new TU.default(!p,p);R.encoding="binary",R.compression=S;let b=n.openDB(f,R);b.decoder=null,R.compression=T;let C=o.openDB(f,R);C.encoder=null,console.log("copying",f,"from",e,"to",t),await E(b,C,p,l)}let d=n.openDB(mf.AUDIT_STORE_NAME,pf);console.log("copying audit log"),E(i,d,!1,l);async function E(f,h,p,S){let T=0,R=0;for(let{key:b,value:C,version:H}of f.getRange({start:null,versions:p,transaction:S}))u=h.put(b,C,H),T++,S.openTimer&&(S.openTimer=0),R+=(b?.length||10)+C.length,_++>5e3&&(await u,console.log("copied",T,"entries",R,"bytes"),_=0);console.log("finish copying, copied",T,"entries",R,"bytes")}a(E,"copyDbi"),await u,console.log("copied database "+e+" to "+t)}finally{l.done(),o.close()}}var pU,hf,mo,sg,SU,TU,mf,Ai,gU,ig,ku,OU=Re(()=>{Ae();pU=require("lmdb"),hf=require("path"),mo=require("fs-extra"),sg=B(Z()),SU=B(Lc()),TU=B(Dc()),mf=B(ft()),Ai=B(P());ti();gU=B(As()),ig=B(fr()),ku=B($());a(c9,"compactOnStart");a(mU,"getTotalDBRecordCount");a(RU,"copyDb")});var Af=g((Yhe,DU)=>{"use strict";var u9=require("minimist"),{isMainThread:ag,parentPort:NU}=require("worker_threads"),tt=P(),{PROCESS_DESCRIPTORS_VALIDATE:Vu}=tt,is=$(),cg=z(),gf=eg(),Tf=at(),$he=Ve(),IU=fr(),os=hU(),bU=Ta(),{compactOnStart:l9}=(OU(),ie(AU)),_9=vh(),{restartWorkers:Rf,onMessageByType:d9}=je(),{handleHDBError:f9,hdb_errors:E9}=ne(),{HTTP_STATUS_CODES:h9}=E9,Yu=Z();Yu.initSync();var $u=`Restarting HarperDB. This may take up to ${tt.RESTART_TIMEOUT_MS/1e3} seconds.`,m9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",yU="Clustering is not enabled so cannot be restarted",p9="Invalid service",ya,fn;DU.exports={restart:wU,restartService:ug};ag&&d9(tt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ug({service:e.workerType}):wU({operation:"restart"})});async function wU(e){fn=Object.keys(e).length===0,ya=await os.isServiceRegistered(tt.HDB_PROC_DESCRIPTOR);let t=u9(process.argv);if(t.service){await ug(t);return}if(fn&&!ya){console.error(m9);return}if(fn&&console.log($u),ya){os.enterPM2Mode(),is.notify($u);let r=_9(Object.keys(tt.CONFIG_PARAM_MAP),!0);return cg.isEmptyOrZeroLength(Object.keys(r))||IU.updateConfigValue(void 0,void 0,r,!0,!0),S9(),$u}return ag?(is.notify($u),Yu.get(tt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await l9(),setTimeout(()=>{Rf()},50)):NU.postMessage({type:tt.ITC_EVENT_TYPES.RESTART}),$u}a(wU,"restart");async function ug(e){let{service:t}=e;if(tt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw f9(new Error,p9,h9.BAD_REQUEST,void 0,void 0,!0);if(ya=await os.isServiceRegistered(tt.HDB_PROC_DESCRIPTOR),!ag)return NU.postMessage({type:tt.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Vu.clustering:if(!Yu.get(tt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=yU;break}fn&&console.log("Restarting clustering"),is.notify("Restarting clustering"),await CU();break;case Vu.clustering_config:case Vu["clustering config"]:if(!Yu.get(tt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=yU;break}fn&&console.log("Restarting clustering_config"),is.notify("Restarting clustering_config"),await os.reloadClustering();break;case"custom_functions":case"custom functions":case Vu.harperdb:case Vu.http_workers:if(fn&&!ya){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}fn&&console.log("Restarting http_workers"),is.notify("Restarting http_workers"),fn?await os.restart(tt.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Rf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(is.error(r),fn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ug,"restartService");async function S9(){await CU(),await os.restart(tt.HDB_PROC_DESCRIPTOR),await cg.async_set_timeout(2e3),Yu.get(tt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await og(),fn&&(await Tf.closeConnection(),process.exit(0))}a(S9,"restartPM2Mode");async function CU(){if(!IU.getConfigFromFile(tt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await bU.getHDBProcessInfo()).clustering.length===0)is.trace("Clustering not running, restart will start clustering services"),await gf.generateNatsConfig(!0),await os.startClusteringProcesses(),await os.startClusteringThreads(),await og(),fn&&await Tf.closeConnection();else{await gf.generateNatsConfig(!0),ya?(is.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await os.restart(tt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await os.restart(tt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await bU.getHDBProcessInfo()).clustering.forEach(s=>{is.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await cg.async_set_timeout(3e3),await og(),await Tf.updateLocalStreams(),fn&&await Tf.closeConnection(),is.trace("Restart clustering restarting ingest and reply service threads");let t=Rf(tt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Rf(tt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(CU,"restartClustering");async function og(){await gf.removeNatsConfig(tt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await gf.removeNatsConfig(tt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(og,"removeNatsConfig")});var FU=g((Qhe,qU)=>{"use strict";var Whe=require("lodash"),Nr=P(),{handleHDBError:LU,hdb_errors:T9}=ne(),{HDB_ERROR_MSGS:g9,HTTP_STATUS_CODES:R9}=T9,lg=$();qU.exports={getRolePermissions:O9};var po=Object.create(null),A9=a(e=>({key:e,perms:{}}),"perms_template_obj"),vU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),BU=a((e=!1,t=!1,r=!1,n=!1)=>({[Nr.PERMS_CRUD_ENUM.READ]:e,[Nr.PERMS_CRUD_ENUM.INSERT]:t,[Nr.PERMS_CRUD_ENUM.UPDATE]:r,[Nr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),_g=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...BU(t,r,n,s)}),"table_perms_template"),MU=a((e,t=BU())=>({attribute_name:e,describe:GU(t),[Ku]:t[Ku],[dg]:t[dg],[fg]:t[fg]}),"attr_perms_template"),PU=a((e,t=!1)=>({attribute_name:e,describe:t,[Ku]:t}),"timestamp_attr_perms_template"),{READ:Ku,INSERT:dg,UPDATE:fg}=Nr.PERMS_CRUD_ENUM,HU=Object.values(Nr.PERMS_CRUD_ENUM),xU=[Ku,dg,fg];function O9(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[Nr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(po[t]&&po[t].key===n)return po[t].perms;let s=b9(e,r);return po[t]?po[t].key=n:po[t]=A9(n),po[t].perms=s,s}catch(r){if(!e[Nr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Nr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Nr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw lg.error(n),lg.debug(r),LU(new Error,g9.OUTDATED_PERMS_TRANSLATION_ERROR,R9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
13
- ${r.stack}`;throw lg.error(n),LU(new Error)}}}a(O9,"getRolePermissions");function b9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Nr.SYSTEM_SCHEMA_NAME]=n[Nr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=y9(t[i]);return}r[i]=vU(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=N9(c,u);r[i].describe||HU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=_g()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=_g()})}),r}a(b9,"translateRolePermissions");function y9(e){let t=vU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=_g(!0,!0,!0,!0,!0)}),t}a(y9,"createStructureUserPermissions");function N9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,E=l;return Nr.TIME_STAMP_NAMES.includes(d)&&(E=PU(d,l[Ku])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=MU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=GU(l),s.attribute_permissions.push(l),c||I9(l,u)}else if(_!==o){let l;Nr.TIME_STAMP_NAMES.includes(_)?l=PU(_):l=MU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=UU(s),s}else return e.describe=UU(e),e}a(N9,"getTableAttrPerms");function UU(e){return HU.filter(t=>e[t]).length>0}a(UU,"getSchemaTableDescribePerm");function GU(e){return xU.filter(t=>e[t]).length>0}a(GU,"getAttributeDescribePerm");function I9(e,t){xU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(I9,"checkForHashPerms")});var kU={};Fe(kU,{Resources:()=>Of,keyArrayToString:()=>Na,resetResources:()=>w9,resources:()=>Oi});function w9(){return Oi=new Of}function Na(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Of,Oi,Wu=Re(()=>{ro();Of=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(w9,"resetResources");a(Na,"keyArrayToString")});var VU={};Fe(VU,{Headers:()=>bi,appendHeader:()=>Eg});function Eg(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var bi,Qu=Re(()=>{bi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(Eg,"appendHeader")});var zu={};Fe(zu,{authentication:()=>jU,bypassAuth:()=>v9,login:()=>H9,logout:()=>x9,start:()=>B9});function v9(){JU=!0}async function jU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?M9?L9:[]:D9?C9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new bi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return bf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),bf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(bf){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(f)){let S=p.indexOf(";");u=p.slice(f.length,S===-1?p.length:S),_=await YU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new Ia.AuthAuditLog(f,h,Ht.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===Ht.AUTH_AUDIT_STATUS.SUCCESS?$U.notify(S):$U.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await it.getUser(f,null,null),l(f,Ht.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Ia.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=So.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),p=n.slice(f+1),S,T;try{switch(h){case"Basic":let R=atob(p),b=R.indexOf(":");S=R.slice(0,b),T=R.slice(b+1),d=S||T?await it.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,yf.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,yf.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(R){return U9&&(So.get(p)||(So.set(p,p),l(S,Ht.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:To({error:R.message},e)})}So.set(n,d),P9&&l(d.username,Ht.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await it.getUser(_.user,null,e):(JU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,WU.getSuperUser)());bf&&(e.session.update=function(f){if(!u){u=(0,QU.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):E?.headers?.set&&E.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")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=u,YU.put(f)},e.login=async function(f,h){e.user=await it.getUser(f,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 E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Oi.loginPath?(E.status=302,E.headers.set("Location",Oi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new bi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function B9({server:e,port:t}){e.http(jU,{port:t||"all"}),KU||(KU=!0,setInterval(()=>{So=new Map},En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),zU.user.addListener(()=>{So=new Map}))}async function H9(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function x9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var WU,yf,QU,En,Ht,Ia,zU,$U,C9,D9,L9,M9,YU,bf,JU,P9,U9,So,KU,Nf=Re(()=>{WU=B(ln());ur();Wu();yf=B(yu());Ae();QU=require("uuid"),En=B(Z()),Ht=B(P()),Ia=B($()),zU=B($c());Qu();wa();$U=(0,Ia.loggerWithTag)("auth-event");En.initSync();C9=En.get(Ht.CONFIG_PARAMS.HTTP_CORSACCESSLIST),D9=En.get(Ht.CONFIG_PARAMS.HTTP_CORS),L9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),M9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),YU=Et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),bf=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,JU=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,P9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,U9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;it.onInvalidatedUser(()=>{So=new Map});a(v9,"bypassAuth");a(jU,"authentication");a(B9,"start");a(H9,"login");a(x9,"logout")});var sv=g((ime,nv)=>{"use strict";var Ce=require("joi"),XU=require("fs-extra"),ZU=require("path"),Us=Xe(),ev=Z(),tv=P(),rv=$(),{hdb_errors:G9}=ne(),{HDB_ERROR_MSGS:nr}=G9,Ps=/^[a-zA-Z0-9-_]+$/;nv.exports={getDropCustomFunctionValidator:F9,setCustomFunctionValidator:k9,addComponentValidator:K9,dropCustomFunctionProjectValidator:W9,packageComponentValidator:Q9,deployComponentValidator:z9,setComponentFileValidator:V9,getComponentFileValidator:Y9,dropComponentFileValidator:$9};function If(e,t,r){try{let n=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),s=ZU.join(n,t);return XU.existsSync(s)?e?t:r.message(nr.PROJECT_EXISTS):e?r.message(nr.NO_PROJECT):t}catch(n){return rv.error(n),r.message(nr.VALIDATION_ERR)}}a(If,"checkProjectExists");function Ju(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ju,"checkFilePath");function q9(e,t,r,n){try{let s=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),i=ZU.join(s,e,t,r+".js");return XU.existsSync(i)?r:n.message(nr.NO_FILE)}catch(s){return rv.error(s),n.message(nr.VALIDATION_ERR)}}a(q9,"checkFileExists");function F9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Ps).custom(q9.bind(null,e.project,e.type)).custom(Ju).required().messages({"string.pattern.base":nr.BAD_FILE_NAME})});return Us.validateBySchema(e,t)}a(F9,"getDropCustomFunctionValidator");function k9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(Ju).required(),function_content:Ce.string().required()});return Us.validateBySchema(e,t)}a(k9,"setCustomFunctionValidator");function V9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),file:Ce.string().custom(Ju).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Us.validateBySchema(e,t)}a(V9,"setComponentFileValidator");function $9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),file:Ce.string().custom(Ju).optional()});return Us.validateBySchema(e,t)}a($9,"dropComponentFileValidator");function Y9(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(Ju).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Us.validateBySchema(e,t)}a(Y9,"getComponentFileValidator");function K9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!1)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME})});return Us.validateBySchema(e,t)}a(K9,"addComponentValidator");function W9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME})});return Us.validateBySchema(e,t)}a(W9,"dropCustomFunctionProjectValidator");function Q9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return Us.validateBySchema(e,t)}a(Q9,"packageComponentValidator");function z9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":nr.BAD_PACKAGE}),package:Ce.string().optional()});return Us.validateBySchema(e,t)}a(z9,"deployComponentValidator")});var Lf=g((ame,_v)=>{"use strict";var wf=require("joi"),Cf=require("path"),iv=require("fs-extra"),{exec:J9}=require("child_process"),j9=require("util"),ov=j9.promisify(J9),ju=P(),{handleHDBError:Ca,hdb_errors:X9}=ne(),{HTTP_STATUS_CODES:Da}=X9,Xu=Z(),Z9=Xe(),La=$();Xu.initSync();var hg=Xu.get(ju.CONFIG_PARAMS.COMPONENTSROOT),av="npm install --omit=dev --json",e7=`${av} --dry-run`;_v.exports={installModules:s7,auditModules:i7,installAllRootModules:t7,uninstallRootModule:r7,linkHarperdb:n7};async function t7(e=!1){await Df(),await Zu(e?"npm install --ignore-scripts":"npm install",Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(t7,"installAllRootModules");async function r7(e){await Zu(`npm uninstall ${e}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(r7,"uninstallRootModule");async function n7(){await Df(),await Zu(`npm link ${ju.PACKAGE_ROOT}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"linkHarperdb");async function Zu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ov(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
14
- `,""))}return n&&!n.includes("Debugger listening")&&La.error("Error running NPM command:",e,n),La.trace(r,n),r?.replace(`
15
- `,"")}a(Zu,"runCommand");async function s7(e){La.info(`starting installModules for request: ${e}`);let t=lv(e);if(t)throw Ca(t,t.message,Da.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?e7:av;await Df(),await uv(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=Cf.join(hg,u),l,d=null;try{let{stdout:E,stderr:f}=await ov(s,{cwd:_});l=E?E.replace(`
12
+ Database backup has not been removed and can be found here: ${s}`;Yu.error(u),console.error(u)}(0,ig.get)(Oi.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,po.remove)(s))}(0,og.updateConfigValue)(Oi.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function SU(e){let t=await(0,AU.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function OU(e,t){console.log("copyDb start");let r=mr()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,TU.open)(new gU.default(t)),c=o.openDB(gf.INTERNAL_DBIS_NAME),u,_=0,l=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:l})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=Af(),T?h.compression=T:delete h.compression,S?.dictionary?.toString()===T?.dictionary?.toString()&&(S=null,T=null)),c.put(f,h),!(p||h.indexed))continue;let R=new RU.default(!p,p);R.encoding="binary",R.compression=S;let b=n.openDB(f,R);b.decoder=null,R.compression=T;let C=o.openDB(f,R);C.encoder=null,console.log("copying",f,"from",e,"to",t),await E(b,C,p,l)}let d=n.openDB(gf.AUDIT_STORE_NAME,Rf);console.log("copying audit log"),E(i,d,!1,l);async function E(f,h,p,S){let T=0,R=0;for(let{key:b,value:C,version:H}of f.getRange({start:null,versions:p,transaction:S}))u=h.put(b,C,H),T++,S.openTimer&&(S.openTimer=0),R+=(b?.length||10)+C.length,_++>5e3&&(await u,console.log("copied",T,"entries",R,"bytes"),_=0);console.log("finish copying, copied",T,"entries",R,"bytes")}a(E,"copyDbi"),await u,console.log("copied database "+e+" to "+t)}finally{l.done(),o.close()}}var TU,Tf,po,ig,gU,RU,gf,Oi,AU,og,Yu,yU=Re(()=>{Ae();TU=require("lmdb"),Tf=require("path"),po=require("fs-extra"),ig=B(Z()),gU=B(Uc()),RU=B(Pc()),gf=B(ft()),Oi=B(P());ri();AU=B(Os()),og=B(Er()),Yu=B($());a(m9,"compactOnStart");a(SU,"getTotalDBRecordCount");a(OU,"copyDb")});var zu=g((tme,LU)=>{"use strict";var p9=require("minimist"),{isMainThread:ug,parentPort:ag,threadId:Zhe}=require("worker_threads"),nt=P(),{PROCESS_DESCRIPTORS_VALIDATE:Ku}=nt,os=$(),lg=z(),bf=tg(),Of=ut(),eme=Ve(),wU=Er(),as=pU(),NU=ga(),{compactOnStart:S9}=(yU(),ie(bU)),T9=Bh(),{restartWorkers:yf,onMessageByType:g9}=We(),{handleHDBError:R9,hdb_errors:A9}=ne(),{HTTP_STATUS_CODES:O9}=A9,Qu=Z();Qu.initSync();var Wu=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,b9="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",y9="Invalid service",Na,fn;LU.exports={restart:CU,restartService:_g};ug&&g9(nt.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await _g({service:e.workerType}):CU({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function CU(e){fn=Object.keys(e).length===0,Na=await as.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=p9(process.argv);if(t.service){await _g(t);return}if(fn&&!Na){console.error(b9);return}if(fn&&console.log(Wu),Na){as.enterPM2Mode(),os.notify(Wu);let r=T9(Object.keys(nt.CONFIG_PARAM_MAP),!0);return lg.isEmptyOrZeroLength(Object.keys(r))||wU.updateConfigValue(void 0,void 0,r,!0,!0),N9(),Wu}return ug?(os.notify(Wu),Qu.get(nt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await S9(),setTimeout(()=>{yf()},50)):ag.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Wu}a(CU,"restart");async function _g(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw R9(new Error,y9,O9.BAD_REQUEST,void 0,void 0,!0);if(Na=await as.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!ug)return ag.postMessage({type:nt.ITC_EVENT_TYPES.RESTART,workerType:t}),new Promise(n=>{ag.on("message",s=>{s.type==="restart-complete"&&n()})});let r;switch(t){case Ku.clustering:if(!Qu.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=IU;break}fn&&console.log("Restarting clustering"),os.notify("Restarting clustering"),await DU();break;case Ku.clustering_config:case Ku["clustering config"]:if(!Qu.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=IU;break}fn&&console.log("Restarting clustering_config"),os.notify("Restarting clustering_config"),await as.reloadClustering();break;case"custom_functions":case"custom functions":case Ku.harperdb:case Ku.http_workers:if(fn&&!Na){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}fn&&console.log("Restarting http_workers"),os.notify("Restarting http_workers"),fn?await as.restart(nt.HDB_PROC_DESCRIPTOR):await yf("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(os.error(r),fn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(_g,"restartService");async function N9(){await DU(),await as.restart(nt.HDB_PROC_DESCRIPTOR),await lg.async_set_timeout(2e3),Qu.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await cg(),fn&&(await Of.closeConnection(),process.exit(0))}a(N9,"restartPM2Mode");async function DU(){if(!wU.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await NU.getHDBProcessInfo()).clustering.length===0)os.trace("Clustering not running, restart will start clustering services"),await bf.generateNatsConfig(!0),await as.startClusteringProcesses(),await as.startClusteringThreads(),await cg(),fn&&await Of.closeConnection();else{await bf.generateNatsConfig(!0),Na?(os.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await as.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await as.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await NU.getHDBProcessInfo()).clustering.forEach(s=>{os.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await lg.async_set_timeout(3e3),await cg(),await Of.updateLocalStreams(),fn&&await Of.closeConnection(),os.trace("Restart clustering restarting ingest and reply service threads");let t=yf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=yf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(DU,"restartClustering");async function cg(){await bf.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await bf.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(cg,"removeNatsConfig")});var kU=g((sme,FU)=>{"use strict";var nme=require("lodash"),Ir=P(),{handleHDBError:MU,hdb_errors:I9}=ne(),{HDB_ERROR_MSGS:w9,HTTP_STATUS_CODES:C9}=I9,dg=$();FU.exports={getRolePermissions:L9};var So=Object.create(null),D9=a(e=>({key:e,perms:{}}),"perms_template_obj"),BU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),HU=a((e=!1,t=!1,r=!1,n=!1)=>({[Ir.PERMS_CRUD_ENUM.READ]:e,[Ir.PERMS_CRUD_ENUM.INSERT]:t,[Ir.PERMS_CRUD_ENUM.UPDATE]:r,[Ir.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),fg=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...HU(t,r,n,s)}),"table_perms_template"),PU=a((e,t=HU())=>({attribute_name:e,describe:qU(t),[Ju]:t[Ju],[Eg]:t[Eg],[hg]:t[hg]}),"attr_perms_template"),UU=a((e,t=!1)=>({attribute_name:e,describe:t,[Ju]:t}),"timestamp_attr_perms_template"),{READ:Ju,INSERT:Eg,UPDATE:hg}=Ir.PERMS_CRUD_ENUM,xU=Object.values(Ir.PERMS_CRUD_ENUM),GU=[Ju,Eg,hg];function L9(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[Ir.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(So[t]&&So[t].key===n)return So[t].perms;let s=M9(e,r);return So[t]?So[t].key=n:So[t]=D9(n),So[t].perms=s,s}catch(r){if(!e[Ir.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Ir.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Ir.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw dg.error(n),dg.debug(r),MU(new Error,w9.OUTDATED_PERMS_TRANSLATION_ERROR,C9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
13
+ ${r.stack}`;throw dg.error(n),MU(new Error)}}}a(L9,"getRolePermissions");function M9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ir.SYSTEM_SCHEMA_NAME]=n[Ir.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=P9(t[i]);return}r[i]=BU(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=U9(c,u);r[i].describe||xU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=fg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=fg()})}),r}a(M9,"translateRolePermissions");function P9(e){let t=BU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=fg(!0,!0,!0,!0,!0)}),t}a(P9,"createStructureUserPermissions");function U9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,E=l;return Ir.TIME_STAMP_NAMES.includes(d)&&(E=UU(d,l[Ju])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=PU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=qU(l),s.attribute_permissions.push(l),c||v9(l,u)}else if(_!==o){let l;Ir.TIME_STAMP_NAMES.includes(_)?l=UU(_):l=PU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=vU(s),s}else return e.describe=vU(e),e}a(U9,"getTableAttrPerms");function vU(e){return xU.filter(t=>e[t]).length>0}a(vU,"getSchemaTableDescribePerm");function qU(e){return GU.filter(t=>e[t]).length>0}a(qU,"getAttributeDescribePerm");function v9(e,t){GU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(v9,"checkForHashPerms")});var VU={};Fe(VU,{Resources:()=>Nf,keyArrayToString:()=>Ia,resetResources:()=>B9,resources:()=>bi});function B9(){return bi=new Nf}function Ia(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Nf,bi,ju=Re(()=>{no();Nf=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(B9,"resetResources");a(Ia,"keyArrayToString")});var $U={};Fe($U,{Headers:()=>yi,appendHeader:()=>mg});function mg(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var yi,Xu=Re(()=>{yi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(mg,"appendHeader")});var Zu={};Fe(Zu,{authentication:()=>XU,bypassAuth:()=>V9,login:()=>Y9,logout:()=>K9,start:()=>$9});function V9(){jU=!0}async function XU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?q9?G9:[]:x9?H9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new yi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return If&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),If&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(If){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(f)){let S=p.indexOf(";");u=p.slice(f.length,S===-1?p.length:S),_=await KU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new wa.AuthAuditLog(f,h,xt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===xt.AUTH_AUDIT_STATUS.SUCCESS?YU.notify(S):YU.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await at.getUser(f,null,null),l(f,xt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,wa.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=To.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),p=n.slice(f+1),S,T;try{switch(h){case"Basic":let R=atob(p),b=R.indexOf(":");S=R.slice(0,b),T=R.slice(b+1),d=S||T?await at.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,wf.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,wf.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(R){return k9&&(To.get(p)||(To.set(p,p),l(S,xt.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:go({error:R.message},e)})}To.set(n,d),F9&&l(d.username,xt.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await at.getUser(_.user,null,e):(jU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,QU.getSuperUser)());If&&(e.session.update=function(f){if(!u){u=(0,zU.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):E?.headers?.set&&E.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")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=u,KU.put(f)},e.login=async function(f,h){e.user=await at.getUser(f,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 E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&bi.loginPath?(E.status=302,E.headers.set("Location",bi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new yi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function $9({server:e,port:t}){e.http(XU,{port:t||"all"}),WU||(WU=!0,setInterval(()=>{To=new Map},En.get(xt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),JU.user.addListener(()=>{To=new Map}))}async function Y9(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 K9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var QU,wf,zU,En,xt,wa,JU,YU,H9,x9,G9,q9,KU,If,jU,F9,k9,To,WU,Cf=Re(()=>{QU=B(ln());lr();ju();wf=B(wu());Ae();zU=require("uuid"),En=B(Z()),xt=B(P()),wa=B($()),JU=B(Qc());Xu();Ca();YU=(0,wa.loggerWithTag)("auth-event");En.initSync();H9=En.get(xt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),x9=En.get(xt.CONFIG_PARAMS.HTTP_CORS),G9=En.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),q9=En.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),KU=Et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),If=En.get(xt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,jU=En.get(xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,F9=En.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,k9=En.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,To=new Map;at.onInvalidatedUser(()=>{To=new Map});a(V9,"bypassAuth");a(XU,"authentication");a($9,"start");a(Y9,"login");a(K9,"logout")});var iv=g((hme,sv)=>{"use strict";var Ce=require("joi"),ZU=require("fs-extra"),ev=require("path"),vs=Xe(),tv=Z(),rv=P(),nv=$(),{hdb_errors:W9}=ne(),{HDB_ERROR_MSGS:ir}=W9,Us=/^[a-zA-Z0-9-_]+$/;sv.exports={getDropCustomFunctionValidator:z9,setCustomFunctionValidator:J9,addComponentValidator:e7,dropCustomFunctionProjectValidator:t7,packageComponentValidator:r7,deployComponentValidator:n7,setComponentFileValidator:j9,getComponentFileValidator:Z9,dropComponentFileValidator:X9};function Df(e,t,r){try{let n=tv.get(rv.CONFIG_PARAMS.COMPONENTSROOT),s=ev.join(n,t);return ZU.existsSync(s)?e?t:r.message(ir.PROJECT_EXISTS):e?r.message(ir.NO_PROJECT):t}catch(n){return nv.error(n),r.message(ir.VALIDATION_ERR)}}a(Df,"checkProjectExists");function el(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(el,"checkFilePath");function Q9(e,t,r,n){try{let s=tv.get(rv.CONFIG_PARAMS.COMPONENTSROOT),i=ev.join(s,e,t,r+".js");return ZU.existsSync(i)?r:n.message(ir.NO_FILE)}catch(s){return nv.error(s),n.message(ir.VALIDATION_ERR)}}a(Q9,"checkFileExists");function z9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Us).custom(Q9.bind(null,e.project,e.type)).custom(el).required().messages({"string.pattern.base":ir.BAD_FILE_NAME})});return vs.validateBySchema(e,t)}a(z9,"getDropCustomFunctionValidator");function J9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(el).required(),function_content:Ce.string().required()});return vs.validateBySchema(e,t)}a(J9,"setCustomFunctionValidator");function j9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(el).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(j9,"setComponentFileValidator");function X9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(el).optional()});return vs.validateBySchema(e,t)}a(X9,"dropComponentFileValidator");function Z9(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(el).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(Z9,"getComponentFileValidator");function e7(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!1)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(e7,"addComponentValidator");function t7(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(t7,"dropCustomFunctionProjectValidator");function r7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return vs.validateBySchema(e,t)}a(r7,"packageComponentValidator");function n7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":ir.BAD_PACKAGE}),package:Ce.string().optional()});return vs.validateBySchema(e,t)}a(n7,"deployComponentValidator")});var Uf=g((pme,dv)=>{"use strict";var Lf=require("joi"),Mf=require("path"),ov=require("fs-extra"),{exec:s7}=require("child_process"),i7=require("util"),av=i7.promisify(s7),tl=P(),{handleHDBError:Da,hdb_errors:o7}=ne(),{HTTP_STATUS_CODES:La}=o7,rl=Z(),a7=Xe(),Ma=$();rl.initSync();var pg=rl.get(tl.CONFIG_PARAMS.COMPONENTSROOT),cv="npm install --omit=dev --json",c7=`${cv} --dry-run`;dv.exports={installModules:d7,auditModules:f7,installAllRootModules:u7,uninstallRootModule:l7,linkHarperdb:_7};async function u7(e=!1){await Pf(),await nl(e?"npm install --ignore-scripts":"npm install",rl.get(tl.CONFIG_PARAMS.ROOTPATH))}a(u7,"installAllRootModules");async function l7(e){await nl(`npm uninstall ${e}`,rl.get(tl.CONFIG_PARAMS.ROOTPATH))}a(l7,"uninstallRootModule");async function _7(){await Pf(),await nl(`npm link ${tl.PACKAGE_ROOT}`,rl.get(tl.CONFIG_PARAMS.ROOTPATH))}a(_7,"linkHarperdb");async function nl(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await av(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
14
+ `,""))}return n&&!n.includes("Debugger listening")&&Ma.error("Error running NPM command:",e,n),Ma.trace(r,n),r?.replace(`
15
+ `,"")}a(nl,"runCommand");async function d7(e){Ma.info(`starting installModules for request: ${e}`);let t=_v(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?c7:cv;await Pf(),await lv(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 _=Mf.join(pg,u),l,d=null;try{let{stdout:E,stderr:f}=await av(s,{cwd:_});l=E?E.replace(`
16
16
  `,""):null,d=f?f.replace(`
17
- `,""):null}catch(E){E.stderr?i[u].npm_error=cv(E.stderr):i[u].npm_error=E.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 La.info(`finished installModules with response ${i}`),i}a(s7,"installModules");function cv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
18
- `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(cv,"parseNPMStdErr");async function i7(e){La.info(`starting auditModules for request: ${e}`);let t=lv(e);if(t)throw Ca(t,t.message,Da.BAD_REQUEST);let{projects:r}=e;await Df(),await uv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Cf.join(hg,o);n[o]={npm_output:null,npm_error:null};try{let u=await Zu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=cv(u.stderr)}}return La.info(`finished auditModules with response ${n}`),n}a(i7,"auditModules");async function Df(){try{return await Zu("npm -v"),!0}catch{throw Ca(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Da.BAD_REQUEST,void 0,void 0,!0)}}a(Df,"checkNPMInstalled");async function uv(e){if(!Array.isArray(e)||e.length===0)throw Ca(new Error,"projects argument must be an array with at least 1 element",Da.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Cf.join(hg,i.toString());if(!await iv.pathExists(o)){t.push(i);continue}let u=Cf.join(o,"package.json");await iv.pathExists(u)||r.push(i)}if(t.length>0)throw Ca(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Da.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ca(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Da.BAD_REQUEST,void 0,void 0,!0)}a(uv,"checkProjectPaths");function lv(e){let t=wf.object({projects:wf.array().min(1).items(wf.string()).required(),dry_run:wf.boolean().default(!1)});return Z9.validateBySchema(e,t)}a(lv,"modulesValidator")});var pg=g((ume,mv)=>{"use strict";var Ma=require("fs-extra"),mg=require("path"),Mf=$(),dv=z(),Pf=P(),hv=Z(),o7=fr();mv.exports=a7;async function a7(){let e=c7(),t=hv.get(Pf.CONFIG_PARAMS.ROOTPATH),r=mg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Pf.PACKAGE_ROOT}},s=mg.join(t,"node_modules");await Ma.ensureDir(s);let i,o=!0,c=!1;try{i=await Ma.readJson(r)}catch(u){if(dv.isEmptyOrZeroLength(e))return;if(u.code!==Pf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!dv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await fv(_);n.dependencies[u]=l+_}if(!o){Mf.notify("Installing components"),await Ev(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await fv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Mf.notify("Removing component",u),c=!0);c&&(Mf.notify("Updating components."),await Ev(r,n,i))}a(a7,"installComponents");function c7(){let e=o7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(c7,"getComponentsConfig");async function fv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":mg.extname(e)||await Ma.pathExists(e)?"file:":"github:"}a(fv,"getPkgPrefix");async function Ev(e,t,r){Mf.trace("npm installing components package.json",t),await Ma.writeFile(e,JSON.stringify(t,null," "));try{await Lf().installAllRootModules(hv.get(Pf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ma.writeFile(e,JSON.stringify(r,null," ")):await Ma.unlink(e),n}}a(Ev,"installPackages")});var gg=g((dme,gv)=>{"use strict";var $e=require("fs-extra"),Sg=require("fast-glob"),Te=require("path"),Sv=require("tar-fs"),_me=require("uuid").v4,Tg=require("normalize-path"),as=sv(),Ct=$(),Qe=P(),Ot=Z(),el=fr(),u7=z(),{PACKAGE_ROOT:l7}=P(),{handleHDBError:xt,hdb_errors:_7}=ne(),{basename:d7}=require("path"),f7=pg(),Tv=Z(),E7=P(),{Readable:h7}=require("stream"),{isMainThread:m7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:Gt}=_7,p7=Te.join(l7,"application-template"),pv=Te.join(Ot.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function S7(){Ct.trace("getting custom api status");let e={};try{e={port:Ot.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw xt(new Error,go.FUNCTION_STATUS,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,t)}return e}a(S7,"customFunctionsStatus");function T7(){Ct.trace("getting custom api endpoints");let e={},t=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{Sg.sync(Tg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:Sg.sync(Tg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:Sg.sync(Tg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw xt(new Error,go.GET_FUNCTIONS,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,r)}return e}a(T7,"getCustomFunctions");function g7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("getting custom api endpoint file content");let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return $e.readFileSync(o,{encoding:"utf8"})}catch(c){throw xt(new Error,go.GET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(g7,"getCustomFunction");function R7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.setCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("setting custom function file content");let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return $e.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw xt(new Error,go.SET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(R7,"setCustomFunction");function A7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("dropping custom function file");let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return $e.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw xt(new Error,go.DROP_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,o)}}a(A7,"dropCustomFunction");function O7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.addComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("adding component");let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return $e.mkdirSync(s,{recursive:!0}),$e.copySync(p7,s),`Successfully added project: ${n}`}catch(s){throw xt(new Error,go.ADD_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,s)}}a(O7,"addComponent");function b7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.dropCustomFunctionProjectValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("dropping custom function project");let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Ot.get(Qe.CONFIG_PARAMS.APPS);if(!u7.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return el.updateConfigValue(Qe.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return $e.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw xt(new Error,go.DROP_FUNCTION_PROJECT,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,i)}}a(b7,"dropCustomFunctionProject");async function y7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.packageComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ct.trace("packaging component",n);let s;try{s=await $e.realpath(Te.join(r,n))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{s=await $e.realpath(Te.join(Ot.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await $e.ensureDir(pv);let i=Te.join(pv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),Sv.pack(s,o).pipe($e.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=$e.readFileSync(i,{encoding:"base64"});return await $e.remove(i),{project:n,payload:c}}a(y7,"packageComponent");async function N7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.deployComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ct.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await $e.emptyDir(o);let E=h7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Sv.extract(o,{finish:h})).on("error",p)});let f=await $e.readdir(o);f.length===1&&f[0]==="package"&&(await $e.copy(Te.join(o,"package"),o),await $e.remove(Te.join(o,"package")))}if(await el.addConfig(n,{package:i}),!s){await f7();let E=Tv.get(E7.CONFIG_PARAMS.ROOTPATH);o=Te.join(E,"node_modules",n)}if(m7)return;let c=new Map;c.isWorker=!0;let u=(vf(),ie(Uf)),_;u.setErrorReporter(E=>_=E);let l=d7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ct.info("Installed component"),`Successfully deployed: ${n}`}a(N7,"deployComponent");async function I7(){let e=el.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await $e.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 E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await $e.stat(d),f={name:Te.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return Ct.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(Ot.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(vf(),ie(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 n}a(I7,"getComponents");async function w7(e){let t=as.getComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let n=el.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(Tv.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await $e.stat(Te.join(n,e.project,e.file));return{message:await $e.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(w7,"getComponentFile");async function C7(e){let t=as.setComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await $e.ensureFile(n),await $e.outputFile(n,e.payload,r)):await $e.ensureDir(n),"Successfully set component: "+e.file}a(C7,"setComponentFile");async function D7(e){let t=as.dropComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(Ot.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await $e.pathExists(n)&&await $e.remove(n),el.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(D7,"dropComponent");gv.exports={customFunctionsStatus:S7,getCustomFunctions:T7,getCustomFunction:g7,setCustomFunction:R7,dropCustomFunction:A7,addComponent:O7,dropCustomFunctionProject:b7,packageComponent:y7,deployComponent:N7,getComponents:I7,getComponentFile:w7,setComponentFile:C7,dropComponent:D7}});var Rg=g((Eme,Av)=>{"use strict";var cs=require("joi"),Rv=Xe();Av.exports={readTransactionLogValidator:L7,deleteTransactionLogsBeforeValidator:M7};function L7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),from:cs.date().timestamp(),to:cs.date().timestamp(),limit:cs.number().min(1)});return Rv.validateBySchema(e,t)}a(L7,"readTransactionLogValidator");function M7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),timestamp:cs.date().timestamp().required()});return Rv.validateBySchema(e,t)}a(M7,"deleteTransactionLogsBeforeValidator")});var Bf=g((mme,Iv)=>{"use strict";var Ag=P(),tl=at(),Ov=z(),bv=Z(),yv=Rs(),{handleHDBError:Pa,hdb_errors:P7}=ne(),{HTTP_STATUS_CODES:Ua}=P7,{readTransactionLogValidator:U7,deleteTransactionLogsBeforeValidator:v7}=Rg(),Nv="This operation relies on clustering and cannot run with it disable.",B7="Logs successfully deleted from transaction log.",H7="All logs successfully deleted from transaction log.";Iv.exports={readTransactionLog:x7,deleteTransactionLogsBefore:G7};async function*x7(e){let t=U7(e);if(t)throw Pa(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Ag.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pa(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Ov.checkSchemaTableExist(r,n);if(s)throw Pa(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=yv.createNatsTableStreamName(r,n),o=await tl.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Ag.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(x7,"readTransactionLog");async function G7(e){let t=v7(e);if(t)throw Pa(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Ag.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pa(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Ov.checkSchemaTableExist(r,n);if(i)throw Pa(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=yv.createNatsTableStreamName(r,n),{jsm:c}=await tl.getNATSReferences(),u=await tl.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=B7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=H7):d=(await tl.viewStream(o,parseInt(s),1))[0].nats_sequence,await tl.purgeTableStream(r,n,{seq:d}),l}a(G7,"deleteTransactionLogsBefore")});var Cv=g((Sme,wv)=>{"use strict";var Og=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};wv.exports=Og});var Lv=g((gme,Dv)=>{"use strict";var bg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Dv.exports=bg});var Ng=g((Ame,Pv)=>{"use strict";var Mv=Cv(),q7=Lv(),{HDB_ERROR_MSGS:F7}=Ur(),yg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=F7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new Mv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new q7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Mv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};Pv.exports=yg});var qf=g((bme,zv)=>{"use strict";var Ig=qr(),Hf=Gr(),mn=Tu(),sl=As(),wg=oi(),k7=qS(),V7=vL(),il=ln(),xf=zS(),Dt=$(),$7=XS(),Y7=Xd(),K7=LT(),W7=ef(),Q7=PT(),z7=UT(),J7=HT(),j7=GT(),Cg=kT(),vs=z(),X7=PP(),Dg=WT(),Bv=Af(),hn=P(),Hv=FU(),Z7=Ta(),xv=yu(),Gv=(Nf(),ie(zu)),qv=fr(),Jr=gg(),eee=require("alasql"),Fv=Bf(),kv=Lf(),Vv=Ng(),{handleHDBError:Ir,hdb_errors:$v}=ne(),{HDB_ERROR_MSGS:Kt,HTTP_STATUS_CODES:rl}=$v,V=new Map,Yv="delete",yi="insert",Bs="read",Ro="update",nl="describe",Uv=sl.describeSchema.name,vv=sl.describeTable.name,Kv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},tee="catchup",ree="handleGetJob",nee="handleGetJobsByStartDate",Gf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},see=[mn.createTable.name,mn.createAttribute.name,mn.dropTable.name,mn.dropAttribute.name],Wv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(Ig.insert.name,new W(!1,[yi]));V.set(Ig.update.name,new W(!1,[Ro]));V.set(Ig.upsert.name,new W(!1,[yi,Ro]));V.set(Hf.searchByConditions.name,new W(!1,[Bs]));V.set(Hf.searchByHash.name,new W(!1,[Bs]));V.set(Hf.searchByValue.name,new W(!1,[Bs]));V.set(Hf.search.name,new W(!1,[Bs]));V.set(mn.createSchema.name,new W(!0,[]));V.set(mn.createTable.name,new W(!0,[]));V.set(mn.createAttribute.name,new W(!1,[yi]));V.set(mn.dropSchema.name,new W(!0,[]));V.set(mn.dropTable.name,new W(!0,[]));V.set(mn.dropAttribute.name,new W(!0,[]));V.set(sl.describeSchema.name,new W(!1,[Bs]));V.set(sl.describeTable.name,new W(!1,[Bs]));V.set(wg.deleteRecord.name,new W(!1,[Yv]));V.set(il.addUser.name,new W(!0,[]));V.set(il.alterUser.name,new W(!0,[]));V.set(il.dropUser.name,new W(!0,[]));V.set(il.listUsersExternal.name,new W(!0,[]));V.set(xf.listRoles.name,new W(!0,[]));V.set(xf.addRole.name,new W(!0,[]));V.set(xf.alterRole.name,new W(!0,[]));V.set(xf.dropRole.name,new W(!0,[]));V.set($7.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(K7.name,new W(!0,[]));V.set(W7.name,new W(!0,[]));V.set(Q7.name,new W(!0,[]));V.set(z7.name,new W(!0,[]));V.set(Cg.setRoutes.name,new W(!0,[]));V.set(Cg.getRoutes.name,new W(!0,[]));V.set(Cg.deleteRoutes.name,new W(!0,[]));V.set(qv.setConfiguration.name,new W(!0,[]));V.set(J7.clusterStatus.name,new W(!0,[]));V.set(j7.name,new W(!0,[]));V.set(Dg.getFingerprint.name,new W(!0,[]));V.set(Dg.setLicense.name,new W(!0,[]));V.set(wg.deleteFilesBefore.name,new W(!0,[]));V.set(wg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Bv.restart.name,new W(!0,[]));V.set(Bv.restartService.name,new W(!0,[]));V.set(k7.name,new W(!0,[]));V.set(V7.name,new W(!0,[Bs]));V.set(Z7.systemInformation.name,new W(!0,[]));V.set(qv.getConfiguration.name,new W(!0,[]));V.set(Fv.readTransactionLog.name,new W(!0,[]));V.set(Fv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(kv.installModules.name,new W(!0,[]));V.set(kv.auditModules.name,new W(!0,[]));V.set(xv.createTokens.name,new W(!1,[]));V.set(xv.refreshOperationToken.name,new W(!1,[]));V.set(Gv.login.name,new W(!1,[]));V.set(Gv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Dg.getRegistrationInfo.name,new W(!1,[]));V.set(il.userInfo.name,new W(!1,[]));V.set(sl.describeAll.name,new W(!1,[]));V.set(ree,new W(!1,[]));V.set(nee,new W(!0,[]));V.set(tee,new W(!0,[]));V.set(Gf.CSV_DATA_LOAD,new W(!1,[yi,Ro]));V.set(Gf.CSV_URL_LOAD,new W(!1,[yi,Ro]));V.set(Gf.CSV_FILE_LOAD,new W(!1,[yi,Ro]));V.set(Gf.IMPORT_FROM_S3,new W(!1,[yi,Ro]));V.set(Wv.EXPORT_TO_S3,new W(!0,[]));V.set(Wv.EXPORT_LOCAL,new W(!0,[]));V.set(hn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Yv]));V.set(hn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(hn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(hn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));zv.exports={verifyPerms:oee,verifyPermsAst:iee,verifyBulkLoadAttributePerms:cee};function iee(e,t,r){if(vs.isEmptyOrZeroLength(e))throw Dt.info("verify_perms_ast has an empty user parameter"),Ir(new Error);if(vs.isEmptyOrZeroLength(t))throw Dt.info("verify_perms_ast has an empty user parameter"),Ir(new Error);if(vs.isEmptyOrZeroLength(r))throw Dt.info("verify_perms_ast has a null operation parameter"),Ir(new Error);try{let n=new Vv,s=new X7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Dt.info("No schemas defined in verifyPermsAst(), will not continue."),Ir(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Kv[r])throw Ir(new Error,Kt.DROP_SYSTEM,rl.FORBIDDEN);if(c&&!u)return null;let _=Hv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof eee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let l=Qv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=Mg(t.role.permission,E,d[f]);Lg(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw Ir(n)}}a(iee,"verifyPermsAst");function oee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Dt.info("null required parameter in verifyPerms"),Ir(new Error,Kt.DEFAULT_INVALID_REQUEST,rl.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new Vv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return Dt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Kt.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(hn.SYSTEM_SCHEMA_NAME)||s===hn.SYSTEM_SCHEMA_NAME;if(l&&Kv[r])throw Ir(new Error,Kt.DROP_SYSTEM,rl.FORBIDDEN);if(u&&!l||_===!0&&(r===mn.createSchema.name||r===mn.dropSchema.name))return null;if(see.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=Hv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Uv||r===vv){if(s===hn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Kt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Uv&&(!d[s]||!d[s][nl]))return c.handleInvalidItem(Kt.SCHEMA_NOT_FOUND(s));if(r===vv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][nl]))return c.handleInvalidItem(Kt.TABLE_NOT_FOUND(s,i))}}let E=Qv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&hn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[hn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[hn.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=aee(e),h=Mg(e.hdb_user.role.permission,s,i);return Lg(f,h,r,i,s,c,n),c.getPermsResponse()}a(oee,"verifyPerms");function Qv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw Dt.info("hasPermissions has an invalid parameter"),Ir(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw Dt.info(`operation ${t} not found.`),Ir(new Error,Kt.OP_NOT_FOUND(t),rl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Dt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][nl]===!1){n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[nl]===!1)n.addInvalidItem(Kt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!vs.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let p=f[h],S=d[p];(S==null||S===!1)&&(Dt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(u,l,E)}catch(E){let f=Kt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Dt.error(f),Dt.error(E),Ir($v.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(Qv,"hasPermissions");function Lg(e,t,r,n,s,i,o){if(!e||!t)throw Dt.info("no attributes specified in checkAttributePerms."),Ir(new Error);let c=V.get(r).perms;if(!c||c==="")throw Dt.info(`no permissions found for ${r} in checkAttributePerms().`),Ir(new Error);if(vs.isEmptyOrZeroLength(t))return Dt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[nl]===!1){i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(hn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Bs)throw Ir(new Error,Kt.SYSTEM_TIMESTAMP_PERMS_ERR,rl.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Lg,"checkAttributePerms");function aee(e){let t=new Set;try{if(e.action)return t;if(e.operation===hn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Dt.info(r)}return t}a(aee,"getRecordAttributes");function Mg(e,t,r){let n=new Map;if(vs.isEmpty(e))return Dt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Dt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Mg,"getAttributePermissions");function cee(e,t,r,n,s,i,o){let c=new Set(i),u=Mg(e,n,s);Lg(c,u,t,s,n,o,r)}a(cee,"verifyBulkLoadAttributePerms")});var kf=g((Nme,e0)=>{"use strict";e0.exports={evaluateSQL:Ree,processAST:Zv,convertSQLToAST:Xv,checkASTPermissions:jv};var uee=qr(),Jv=require("util"),lee=Jv.callbackify(uee.insert),_ee=Gr().search,dee=gD().update,fee=Jv.callbackify(dee),Eee=AD().convertDelete,Ni=require("alasql"),hee=qf(),Ff=$(),mee=md(),pee=z(),ol=P(),{hdb_errors:See,handleHDBError:Pg}=ne(),{HTTP_STATUS_CODES:Ug}=See;mee(Ni);var Tee=403,gee="There was a problem performing this insert. Please check the logs and try again.",vg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Ree(e,t){let r=e.parsed_sql_object;if(!r){r=Xv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ni.yy.Insert?n=s.into.databaseid:s instanceof Ni.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ni.yy.Update||s instanceof Ni.yy.Delete?n=s.table.databaseid:Ff.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ni.yy.Select)&&pee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Zv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Ree,"evaluateSQL");function jv(e,t){let r;try{r=hee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(jv,"checkASTPermissions");function Xv(e){let t=new vg;if(!e)throw Pg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ni.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
19
- `);throw n[1]?Pg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Pg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Xv,"convertSQLToAST");function Zv(e,t,r){try{let n=Aee;if(!e.bypass_auth&&!t.permissions_checked){let i=jv(e,t);if(i&&i.length>0)return r(Tee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ol.VALID_SQL_OPS_ENUM.SELECT:n=_ee,s=t.ast.statements[0];break;case ol.VALID_SQL_OPS_ENUM.INSERT:n=Oee;break;case ol.VALID_SQL_OPS_ENUM.UPDATE:n=fee;break;case ol.VALID_SQL_OPS_ENUM.DELETE:n=Eee;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(Zv,"processAST");function Aee(e,t){Ff.info(e),t("unknown sql statement")}a(Aee,"nullFunction");function Oee({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=bee(i,e.values)}catch(o){return r(o)}lee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Ff.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Oee,"convertInsert");function bee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ni.compile(`SELECT ${s.toString()} AS [${ol.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Ff.error(r),new Error(gee)}}a(bee,"createDataObjects")});var Bg=g((wme,r0)=>{"use strict";var{S3:yee,GetObjectCommand:Nee}=require("@aws-sdk/client-s3");r0.exports={getFileStreamFromS3:Iee,getS3AuthObj:t0};async function Iee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await t0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Nee(r))).Body}a(Iee,"getFileStreamFromS3");function t0(e,t,r){return new yee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(t0,"getS3AuthObj")});var Vf=g((Dme,_0)=>{"use strict";var xg=Gr(),wee=kf(),Cee=Bg(),{AsyncParser:Dee,Transform:Lee}=require("json2csv"),cl=require("stream"),jr=z(),Hg=require("fs-extra"),Mee=require("path"),pn=$(),{promisify:i0}=require("util"),al=z(),{handleHDBError:bt,hdb_errors:Pee}=ne(),{HDB_ERROR_MSGS:wr,HTTP_STATUS_CODES:yt}=Pee,{streamAsJSON:Uee}=(rm(),ie(Lb)),{Upload:vee}=require("@aws-sdk/lib-storage"),n0=["search_by_value","search_by_hash","sql","search_by_conditions"],s0=["json","csv"],o0="json",a0="csv",Bee="Successfully exported JSON locally.",Hee="Successfully exported CSV locally.",xee=1e3,Gee=xg.searchByHash,qee=xg.searchByValue,Fee=i0(wee.evaluateSQL),kee=i0(cl.finished);_0.exports={export_to_s3:Kee,export_local:Vee,toCsvStream:c0};async function Vee(e){pn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=u0(e);if(!jr.isEmpty(t))throw pn.error(t),bt(new Error,t,yt.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw pn.error(wr.MISSING_VALUE("path")),bt(new Error,wr.MISSING_VALUE("path"),yt.BAD_REQUEST,void 0,void 0,!0);let r=(jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Mee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jr.buildFolderPath(e.path,r);await $ee(e.path);let s=await l0(e);return await Yee(n,e.format,s)}a(Vee,"export_local");async function $ee(e){if(pn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw bt(new Error,`Invalid path: ${e}`,yt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Hg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,pn.error(n),bt(new Error,n,yt.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 pn.error(r),bt(new Error,r,yt.BAD_REQUEST,void 0,void 0,!0)}return!0}a($ee,"confirmPath");async function Yee(e,t,r){if(pn.trace("in saveToLocal"),al.isEmptyOrZeroLength(e))throw bt(new Error,wr.INVALID_VALUE("file_path"),yt.BAD_REQUEST,void 0,void 0,!0);if(al.isEmptyOrZeroLength(t))throw bt(new Error,wr.INVALID_VALUE("Source format"),yt.BAD_REQUEST,void 0,void 0,!0);if(al.isEmpty(r))throw bt(new Error,wr.NOT_FOUND("Data"),yt.BAD_REQUEST,void 0,void 0,!0);if(t===o0){let n=Hg.createWriteStream(e);return Uee(r).pipe(n),await kee(n),{message:Bee,path:e}}else if(t===a0){let n=Hg.createWriteStream(e),s=cl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Dee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Hee,path:e}}throw bt(new Error,wr.INVALID_VALUE("format"),yt.BAD_REQUEST)}a(Yee,"saveToLocal");async function Kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw bt(new Error,wr.MISSING_VALUE("S3 object"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw bt(new Error,wr.MISSING_VALUE("aws_access_key_id"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw bt(new Error,wr.MISSING_VALUE("aws_secret_access_key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw bt(new Error,wr.MISSING_VALUE("bucket"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw bt(new Error,wr.MISSING_VALUE("key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw bt(new Error,wr.MISSING_VALUE("region"),yt.BAD_REQUEST);let t=u0(e);if(!jr.isEmpty(t))throw bt(new Error,t,yt.BAD_REQUEST);pn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await l0(e)}catch(u){throw pn.error(u),u}let n,s=await Cee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new cl.PassThrough;if(e.format===a0){i=e.s3.key+".csv";let u=c0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===o0){i=e.s3.key+".json";let u=new cl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%xee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw bt(new Error,wr.INVALID_VALUE("format"),yt.BAD_REQUEST);return new vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Kee,"export_to_s3");function c0(e,t){let r=cl.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new Lee(n,s);return r.pipe(i)}a(c0,"toCsvStream");function u0(e){if(pn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(s0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${s0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(n0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${n0.join(", ")}`}a(u0,"exportCoreValidation");async function l0(e){pn.trace("in getRecords");let t,r;if(al.isEmpty(e.search_operation)||al.isEmptyOrZeroLength(e.search_operation.operation))throw bt(new Error,wr.INVALID_VALUE("Search operation"),yt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qee;break;case"search_by_hash":t=Gee;break;case"search_by_conditions":t=xg.searchByConditions;break;case"sql":t=Fee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,pn.error(r),bt(new Error,r,yt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(l0,"getRecords")});var T0={};Fe(T0,{contentTypes:()=>kg,findBestSerializer:()=>Kf,getDeserializer:()=>Oo,registerContentHandlers:()=>Vg,serialize:()=>Wf,serializeMessage:()=>To});function Wee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register(zee,{serializers:[{regex:/^application\/json$/,serializer:bc},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(ll).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Yf.Readable.from((0,us.encodeIter)(t,ll)):(0,us.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,$f.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,us.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ao.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Kf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,E={q:1};for(let h of l){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=qt.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(qt.keys()).join(", "))}};n=qt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Wf(e,t,r){let n=f0&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Kf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>f0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function To(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return ul(e);let r=t.serialize;if(r)return r(e);let n=Kf(t);return r=t.serialize=n.serializer.serialize,r(e)}function Jee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Oo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=qt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=qt.get(e)?.deserialize||E0(e,n);return o=>Jee(o).then(i)}return e&&qt.get(e)?.deserialize||E0(e,n)}function E0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function jee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var $f,us,Ao,Hs,Yf,h0,Gg,qg,m0,p0,ul,Fg,ll,qt,kg,d0,S0,Qee,zee,f0,wa=Re(()=>{rm();$f=B(Vf()),us=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),Yf=require("stream");ur();h0=require("../index"),Gg=B(Z()),qg=B(P()),m0=B(require("yaml")),p0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,ul=p0?xi:JSON.stringify,Fg=p0?tm:JSON.parse,ll={useRecords:!1,useToJSON:!0},qt=new Map,kg=qt;it.contentTypes=kg;(0,h0._assignPackageExport)("contentTypes",kg);qt.set("application/json",{serializeStream:bc,serialize:ul,deserialize:Fg,q:.8});d0=new Ao.Encoder(ll);qt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(ll).end(e)},serialize:d0.encode,deserialize:d0.decode,q:1});qt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Yf.Readable.from((0,us.encodeIter)(e,ll)):(0,us.pack)(e)},serialize:us.pack,deserialize:us.unpack,q:.9});qt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,$f.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,$f.toCsvStream)(e,e?.getColumns?.())},q:.1});qt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});qt.set("text/yaml",{serialize(e){return m0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});qt.set("text/event-stream",{serializeStream:function(e){return Yf.Readable.from(jee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
20
- `),e.data){let r=e.data;typeof r=="object"&&(r=ul(r)),t+="data: "+r+`
17
+ `,""):null}catch(E){E.stderr?i[u].npm_error=uv(E.stderr):i[u].npm_error=E.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 Ma.info(`finished installModules with response ${i}`),i}a(d7,"installModules");function uv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
18
+ `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(uv,"parseNPMStdErr");async function f7(e){Ma.info(`starting auditModules for request: ${e}`);let t=_v(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r}=e;await Pf(),await lv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Mf.join(pg,o);n[o]={npm_output:null,npm_error:null};try{let u=await nl("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=uv(u.stderr)}}return Ma.info(`finished auditModules with response ${n}`),n}a(f7,"auditModules");async function Pf(){try{return await nl("npm -v"),!0}catch{throw Da(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",La.BAD_REQUEST,void 0,void 0,!0)}}a(Pf,"checkNPMInstalled");async function lv(e){if(!Array.isArray(e)||e.length===0)throw Da(new Error,"projects argument must be an array with at least 1 element",La.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Mf.join(pg,i.toString());if(!await ov.pathExists(o)){t.push(i);continue}let u=Mf.join(o,"package.json");await ov.pathExists(u)||r.push(i)}if(t.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,La.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,La.BAD_REQUEST,void 0,void 0,!0)}a(lv,"checkProjectPaths");function _v(e){let t=Lf.object({projects:Lf.array().min(1).items(Lf.string()).required(),dry_run:Lf.boolean().default(!1)});return a7.validateBySchema(e,t)}a(_v,"modulesValidator")});var Tg=g((Tme,pv)=>{"use strict";var Pa=require("fs-extra"),Sg=require("path"),vf=$(),fv=z(),Bf=P(),mv=Z(),E7=Er();pv.exports=h7;async function h7(){let e=m7(),t=mv.get(Bf.CONFIG_PARAMS.ROOTPATH),r=Sg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Bf.PACKAGE_ROOT}},s=Sg.join(t,"node_modules");await Pa.ensureDir(s);let i,o=!0,c=!1;try{i=await Pa.readJson(r)}catch(u){if(fv.isEmptyOrZeroLength(e))return;if(u.code!==Bf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!fv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await Ev(_);n.dependencies[u]=l+_}if(!o){vf.notify("Installing components"),await hv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await Ev(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(vf.notify("Removing component",u),c=!0);c&&(vf.notify("Updating components."),await hv(r,n,i))}a(h7,"installComponents");function m7(){let e=E7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(m7,"getComponentsConfig");async function Ev(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":Sg.extname(e)||await Pa.pathExists(e)?"file:":"github:"}a(Ev,"getPkgPrefix");async function hv(e,t,r){vf.trace("npm installing components package.json",t),await Pa.writeFile(e,JSON.stringify(t,null," "));try{await Uf().installAllRootModules(mv.get(Bf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Pa.writeFile(e,JSON.stringify(r,null," ")):await Pa.unlink(e),n}}a(hv,"installPackages")});var Ag=g((Ame,Rv)=>{"use strict";var $e=require("fs-extra"),gg=require("fast-glob"),Te=require("path"),Tv=require("tar-fs"),Rme=require("uuid").v4,Rg=require("normalize-path"),cs=iv(),Ct=$(),ze=P(),Ot=Z(),sl=Er(),p7=z(),{PACKAGE_ROOT:S7}=P(),{handleHDBError:Gt,hdb_errors:T7}=ne(),{basename:g7}=require("path"),R7=Tg(),gv=Z(),A7=P(),{Readable:O7}=require("stream"),{isMainThread:b7}=require("worker_threads"),{HDB_ERROR_MSGS:Ro,HTTP_STATUS_CODES:qt}=T7,y7=Te.join(S7,"application-template"),Sv=Te.join(Ot.get(ze.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function N7(){Ct.trace("getting custom api status");let e={};try{e={port:Ot.get(ze.CONFIG_PARAMS.HTTP_PORT),directory:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Gt(new Error,Ro.FUNCTION_STATUS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,t)}return e}a(N7,"customFunctionsStatus");function I7(){Ct.trace("getting custom api endpoints");let e={},t=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT);try{gg.sync(Rg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:gg.sync(Rg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:gg.sync(Rg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Gt(new Error,Ro.GET_FUNCTIONS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,r)}return e}a(I7,"getCustomFunctions");function w7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("getting custom api endpoint file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return $e.readFileSync(o,{encoding:"utf8"})}catch(c){throw Gt(new Error,Ro.GET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(w7,"getCustomFunction");function C7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.setCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("setting custom function file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return $e.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Gt(new Error,Ro.SET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(C7,"setCustomFunction");function D7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function file");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return $e.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Gt(new Error,Ro.DROP_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,o)}}a(D7,"dropCustomFunction");function L7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.addComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("adding component");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return $e.mkdirSync(s,{recursive:!0}),$e.copySync(y7,s),`Successfully added project: ${n}`}catch(s){throw Gt(new Error,Ro.ADD_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,s)}}a(L7,"addComponent");function M7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.dropCustomFunctionProjectValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function project");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Ot.get(ze.CONFIG_PARAMS.APPS);if(!p7.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return sl.updateConfigValue(ze.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return $e.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Gt(new Error,Ro.DROP_FUNCTION_PROJECT,qt.INTERNAL_SERVER_ERROR,Ct.ERR,i)}}a(M7,"dropCustomFunctionProject");async function P7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.packageComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ct.trace("packaging component",n);let s;try{s=await $e.realpath(Te.join(r,n))}catch(u){if(u.code!==ze.NODE_ERROR_CODES.ENOENT)throw u;try{s=await $e.realpath(Te.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===ze.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await $e.ensureDir(Sv);let i=Te.join(Sv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),Tv.pack(s,o).pipe($e.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=$e.readFileSync(i,{encoding:"base64"});return await $e.remove(i),{project:n,payload:c}}a(P7,"packageComponent");async function U7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.deployComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ct.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await $e.emptyDir(o);let E=O7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Tv.extract(o,{finish:h})).on("error",p)});let f=await $e.readdir(o);f.length===1&&f[0]==="package"&&(await $e.copy(Te.join(o,"package"),o),await $e.remove(Te.join(o,"package")))}if(await sl.addConfig(n,{package:i}),!s){await R7();let E=gv.get(A7.CONFIG_PARAMS.ROOTPATH);o=Te.join(E,"node_modules",n)}if(b7)return;let c=new Map;c.isWorker=!0;let u=(xf(),ie(Hf)),_;u.setErrorReporter(E=>_=E);let l=g7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ct.info("Installed component"),`Successfully deployed: ${n}`}a(U7,"deployComponent");async function v7(){let e=sl.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 $e.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 E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await $e.stat(d),f={name:Te.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return Ct.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{name:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(xf(),ie(Hf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(v7,"getComponents");async function B7(e){let t=cs.getComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let n=sl.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(gv.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules"):Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await $e.stat(Te.join(n,e.project,e.file));return{message:await $e.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===ze.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(B7,"getComponentFile");async function H7(e){let t=cs.setComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await $e.ensureFile(n),await $e.outputFile(n,e.payload,r)):await $e.ensureDir(n),"Successfully set component: "+e.file}a(H7,"setComponentFile");async function x7(e){let t=cs.dropComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),r);return await $e.pathExists(n)&&await $e.remove(n),sl.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(x7,"dropComponent");Rv.exports={customFunctionsStatus:N7,getCustomFunctions:I7,getCustomFunction:w7,setCustomFunction:C7,dropCustomFunction:D7,addComponent:L7,dropCustomFunctionProject:M7,packageComponent:P7,deployComponent:U7,getComponents:v7,getComponentFile:B7,setComponentFile:H7,dropComponent:x7}});var Og=g((bme,Ov)=>{"use strict";var us=require("joi"),Av=Xe();Ov.exports={readTransactionLogValidator:G7,deleteTransactionLogsBeforeValidator:q7};function G7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),from:us.date().timestamp(),to:us.date().timestamp(),limit:us.number().min(1)});return Av.validateBySchema(e,t)}a(G7,"readTransactionLogValidator");function q7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),timestamp:us.date().timestamp().required()});return Av.validateBySchema(e,t)}a(q7,"deleteTransactionLogsBeforeValidator")});var Gf=g((Nme,wv)=>{"use strict";var bg=P(),il=ut(),bv=z(),yv=Z(),Nv=As(),{handleHDBError:Ua,hdb_errors:F7}=ne(),{HTTP_STATUS_CODES:va}=F7,{readTransactionLogValidator:k7,deleteTransactionLogsBeforeValidator:V7}=Og(),Iv="This operation relies on clustering and cannot run with it disable.",$7="Logs successfully deleted from transaction log.",Y7="All logs successfully deleted from transaction log.";wv.exports={readTransactionLog:K7,deleteTransactionLogsBefore:W7};async function*K7(e){let t=k7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!yv.get(bg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,Iv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=bv.checkSchemaTableExist(r,n);if(s)throw Ua(new Error,s,va.NOT_FOUND,void 0,void 0,!0);let i=Nv.createNatsTableStreamName(r,n),o=await il.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===bg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(K7,"readTransactionLog");async function W7(e){let t=V7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!yv.get(bg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,Iv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=bv.checkSchemaTableExist(r,n);if(i)throw Ua(new Error,i,va.NOT_FOUND,void 0,void 0,!0);let o=Nv.createNatsTableStreamName(r,n),{jsm:c}=await il.getNATSReferences(),u=await il.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=$7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=Y7):d=(await il.viewStream(o,parseInt(s),1))[0].nats_sequence,await il.purgeTableStream(r,n,{seq:d}),l}a(W7,"deleteTransactionLogsBefore")});var Dv=g((wme,Cv)=>{"use strict";var yg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};Cv.exports=yg});var Mv=g((Dme,Lv)=>{"use strict";var Ng=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Lv.exports=Ng});var wg=g((Mme,Uv)=>{"use strict";var Pv=Dv(),Q7=Mv(),{HDB_ERROR_MSGS:z7}=Ur(),Ig=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=z7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new Pv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new Q7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Pv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};Uv.exports=Ig});var Vf=g((Ume,Jv)=>{"use strict";var Cg=qr(),qf=Gr(),mn=Au(),cl=Os(),Dg=ai(),J7=FS(),j7=HL(),ul=ln(),Ff=JS(),Dt=$(),X7=ZS(),Z7=rf(),eee=MT(),tee=sf(),ree=UT(),nee=vT(),see=xT(),iee=qT(),Lg=VT(),Bs=z(),oee=vP(),Mg=QT(),Hv=zu(),hn=P(),xv=kU(),aee=ga(),Gv=wu(),qv=(Cf(),ie(Zu)),Fv=Er(),Jr=Ag(),cee=require("alasql"),kv=Gf(),Vv=Uf(),$v=wg(),{handleHDBError:wr,hdb_errors:Yv}=ne(),{HDB_ERROR_MSGS:Wt,HTTP_STATUS_CODES:ol}=Yv,V=new Map,Kv="delete",Ni="insert",Hs="read",Ao="update",al="describe",vv=cl.describeSchema.name,Bv=cl.describeTable.name,Wv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},uee="catchup",lee="handleGetJob",_ee="handleGetJobsByStartDate",kf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},dee=[mn.createTable.name,mn.createAttribute.name,mn.dropTable.name,mn.dropAttribute.name],Qv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(Cg.insert.name,new W(!1,[Ni]));V.set(Cg.update.name,new W(!1,[Ao]));V.set(Cg.upsert.name,new W(!1,[Ni,Ao]));V.set(qf.searchByConditions.name,new W(!1,[Hs]));V.set(qf.searchByHash.name,new W(!1,[Hs]));V.set(qf.searchByValue.name,new W(!1,[Hs]));V.set(qf.search.name,new W(!1,[Hs]));V.set(mn.createSchema.name,new W(!0,[]));V.set(mn.createTable.name,new W(!0,[]));V.set(mn.createAttribute.name,new W(!1,[Ni]));V.set(mn.dropSchema.name,new W(!0,[]));V.set(mn.dropTable.name,new W(!0,[]));V.set(mn.dropAttribute.name,new W(!0,[]));V.set(cl.describeSchema.name,new W(!1,[Hs]));V.set(cl.describeTable.name,new W(!1,[Hs]));V.set(Dg.deleteRecord.name,new W(!1,[Kv]));V.set(ul.addUser.name,new W(!0,[]));V.set(ul.alterUser.name,new W(!0,[]));V.set(ul.dropUser.name,new W(!0,[]));V.set(ul.listUsersExternal.name,new W(!0,[]));V.set(Ff.listRoles.name,new W(!0,[]));V.set(Ff.addRole.name,new W(!0,[]));V.set(Ff.alterRole.name,new W(!0,[]));V.set(Ff.dropRole.name,new W(!0,[]));V.set(X7.name,new W(!0,[]));V.set(Z7.name,new W(!0,[]));V.set(eee.name,new W(!0,[]));V.set(tee.name,new W(!0,[]));V.set(ree.name,new W(!0,[]));V.set(nee.name,new W(!0,[]));V.set(Lg.setRoutes.name,new W(!0,[]));V.set(Lg.getRoutes.name,new W(!0,[]));V.set(Lg.deleteRoutes.name,new W(!0,[]));V.set(Fv.setConfiguration.name,new W(!0,[]));V.set(see.clusterStatus.name,new W(!0,[]));V.set(iee.name,new W(!0,[]));V.set(Mg.getFingerprint.name,new W(!0,[]));V.set(Mg.setLicense.name,new W(!0,[]));V.set(Dg.deleteFilesBefore.name,new W(!0,[]));V.set(Dg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Hv.restart.name,new W(!0,[]));V.set(Hv.restartService.name,new W(!0,[]));V.set(J7.name,new W(!0,[]));V.set(j7.name,new W(!0,[Hs]));V.set(aee.systemInformation.name,new W(!0,[]));V.set(Fv.getConfiguration.name,new W(!0,[]));V.set(kv.readTransactionLog.name,new W(!0,[]));V.set(kv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Vv.installModules.name,new W(!0,[]));V.set(Vv.auditModules.name,new W(!0,[]));V.set(Gv.createTokens.name,new W(!1,[]));V.set(Gv.refreshOperationToken.name,new W(!1,[]));V.set(qv.login.name,new W(!1,[]));V.set(qv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Mg.getRegistrationInfo.name,new W(!1,[]));V.set(ul.userInfo.name,new W(!1,[]));V.set(cl.describeAll.name,new W(!1,[]));V.set(lee,new W(!1,[]));V.set(_ee,new W(!0,[]));V.set(uee,new W(!0,[]));V.set(kf.CSV_DATA_LOAD,new W(!1,[Ni,Ao]));V.set(kf.CSV_URL_LOAD,new W(!1,[Ni,Ao]));V.set(kf.CSV_FILE_LOAD,new W(!1,[Ni,Ao]));V.set(kf.IMPORT_FROM_S3,new W(!1,[Ni,Ao]));V.set(Qv.EXPORT_TO_S3,new W(!0,[]));V.set(Qv.EXPORT_LOCAL,new W(!0,[]));V.set(hn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Kv]));V.set(hn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Hs]));V.set(hn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ni]));V.set(hn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ao]));Jv.exports={verifyPerms:Eee,verifyPermsAst:fee,verifyBulkLoadAttributePerms:mee};function fee(e,t,r){if(Bs.isEmptyOrZeroLength(e))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(t))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(r))throw Dt.info("verify_perms_ast has a null operation parameter"),wr(new Error);try{let n=new $v,s=new oee(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Dt.info("No schemas defined in verifyPermsAst(), will not continue."),wr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Wv[r])throw wr(new Error,Wt.DROP_SYSTEM,ol.FORBIDDEN);if(c&&!u)return null;let _=xv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof cee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let l=zv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=Ug(t.role.permission,E,d[f]);Pg(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw wr(n)}}a(fee,"verifyPermsAst");function Eee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Dt.info("null required parameter in verifyPerms"),wr(new Error,Wt.DEFAULT_INVALID_REQUEST,ol.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new $v;if(Bs.isEmptyOrZeroLength(e.hdb_user.role)||Bs.isEmptyOrZeroLength(e.hdb_user.role.permission))return Dt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Wt.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(hn.SYSTEM_SCHEMA_NAME)||s===hn.SYSTEM_SCHEMA_NAME;if(l&&Wv[r])throw wr(new Error,Wt.DROP_SYSTEM,ol.FORBIDDEN);if(u&&!l||_===!0&&(r===mn.createSchema.name||r===mn.dropSchema.name))return null;if(dee.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=xv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===vv||r===Bv){if(s===hn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Wt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===vv&&(!d[s]||!d[s][al]))return c.handleInvalidItem(Wt.SCHEMA_NOT_FOUND(s));if(r===Bv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][al]))return c.handleInvalidItem(Wt.TABLE_NOT_FOUND(s,i))}}let E=zv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&hn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[hn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[hn.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=hee(e),h=Ug(e.hdb_user.role.permission,s,i);return Pg(f,h,r,i,s,c,n),c.getPermsResponse()}a(Eee,"verifyPerms");function zv(e,t,r,n,s){if(Bs.arrayHasEmptyValues([e,t,r]))throw Dt.info("hasPermissions has an invalid parameter"),wr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw Dt.info(`operation ${t} not found.`),wr(new Error,Wt.OP_NOT_FOUND(t),ol.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Dt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Wt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][al]===!1){n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[al]===!1)n.addInvalidItem(Wt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!Bs.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let p=f[h],S=d[p];(S==null||S===!1)&&(Dt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(u,l,E)}catch(E){let f=Wt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Dt.error(f),Dt.error(E),wr(Yv.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(zv,"hasPermissions");function Pg(e,t,r,n,s,i,o){if(!e||!t)throw Dt.info("no attributes specified in checkAttributePerms."),wr(new Error);let c=V.get(r).perms;if(!c||c==="")throw Dt.info(`no permissions found for ${r} in checkAttributePerms().`),wr(new Error);if(Bs.isEmptyOrZeroLength(t))return Dt.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[al]===!1){i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(hn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Hs)throw wr(new Error,Wt.SYSTEM_TIMESTAMP_PERMS_ERR,ol.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Pg,"checkAttributePerms");function hee(e){let t=new Set;try{if(e.action)return t;if(e.operation===hn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Dt.info(r)}return t}a(hee,"getRecordAttributes");function Ug(e,t,r){let n=new Map;if(Bs.isEmpty(e))return Dt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Dt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Ug,"getAttributePermissions");function mee(e,t,r,n,s,i,o){let c=new Set(i),u=Ug(e,n,s);Pg(c,u,t,s,n,o,r)}a(mee,"verifyBulkLoadAttributePerms")});var Yf=g((Bme,t0)=>{"use strict";t0.exports={evaluateSQL:Cee,processAST:e0,convertSQLToAST:Zv,checkASTPermissions:Xv};var pee=qr(),jv=require("util"),See=jv.callbackify(pee.insert),Tee=Gr().search,gee=AD().update,Ree=jv.callbackify(gee),Aee=bD().convertDelete,Ii=require("alasql"),Oee=Vf(),$f=$(),bee=gd(),yee=z(),ll=P(),{hdb_errors:Nee,handleHDBError:vg}=ne(),{HTTP_STATUS_CODES:Bg}=Nee;bee(Ii);var Iee=403,wee="There was a problem performing this insert. Please check the logs and try again.",Hg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Cee(e,t){let r=e.parsed_sql_object;if(!r){r=Zv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ii.yy.Insert?n=s.into.databaseid:s instanceof Ii.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ii.yy.Update||s instanceof Ii.yy.Delete?n=s.table.databaseid:$f.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ii.yy.Select)&&yee.isEmptyOrZeroLength(n))return t("No schema specified",null)}e0(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Cee,"evaluateSQL");function Xv(e,t){let r;try{r=Oee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Xv,"checkASTPermissions");function Zv(e){let t=new Hg;if(!e)throw vg(new Error,"The 'sql' parameter is missing from the request body",Bg.BAD_REQUEST);try{let r=e.trim(),n=Ii.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
19
+ `);throw n[1]?vg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Bg.BAD_REQUEST):vg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Bg.BAD_REQUEST)}return t}a(Zv,"convertSQLToAST");function e0(e,t,r){try{let n=Dee;if(!e.bypass_auth&&!t.permissions_checked){let i=Xv(e,t);if(i&&i.length>0)return r(Iee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ll.VALID_SQL_OPS_ENUM.SELECT:n=Tee,s=t.ast.statements[0];break;case ll.VALID_SQL_OPS_ENUM.INSERT:n=Lee;break;case ll.VALID_SQL_OPS_ENUM.UPDATE:n=Ree;break;case ll.VALID_SQL_OPS_ENUM.DELETE:n=Aee;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(e0,"processAST");function Dee(e,t){$f.info(e),t("unknown sql statement")}a(Dee,"nullFunction");function Lee({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=Mee(i,e.values)}catch(o){return r(o)}See(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){$f.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Lee,"convertInsert");function Mee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ii.compile(`SELECT ${s.toString()} AS [${ll.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw $f.error(r),new Error(wee)}}a(Mee,"createDataObjects")});var xg=g((xme,n0)=>{"use strict";var{S3:Pee,GetObjectCommand:Uee}=require("@aws-sdk/client-s3");n0.exports={getFileStreamFromS3:vee,getS3AuthObj:r0};async function vee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await r0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Uee(r))).Body}a(vee,"getFileStreamFromS3");function r0(e,t,r){return new Pee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(r0,"getS3AuthObj")});var Kf=g((qme,d0)=>{"use strict";var qg=Gr(),Bee=Yf(),Hee=xg(),{AsyncParser:xee,Transform:Gee}=require("json2csv"),dl=require("stream"),jr=z(),Gg=require("fs-extra"),qee=require("path"),pn=$(),{promisify:o0}=require("util"),_l=z(),{handleHDBError:bt,hdb_errors:Fee}=ne(),{HDB_ERROR_MSGS:Cr,HTTP_STATUS_CODES:yt}=Fee,{streamAsJSON:kee}=(nm(),ie(Pb)),{Upload:Vee}=require("@aws-sdk/lib-storage"),s0=["search_by_value","search_by_hash","sql","search_by_conditions"],i0=["json","csv"],a0="json",c0="csv",$ee="Successfully exported JSON locally.",Yee="Successfully exported CSV locally.",Kee=1e3,Wee=qg.searchByHash,Qee=qg.searchByValue,zee=o0(Bee.evaluateSQL),Jee=o0(dl.finished);d0.exports={export_to_s3:ete,export_local:jee,toCsvStream:u0};async function jee(e){pn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=l0(e);if(!jr.isEmpty(t))throw pn.error(t),bt(new Error,t,yt.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw pn.error(Cr.MISSING_VALUE("path")),bt(new Error,Cr.MISSING_VALUE("path"),yt.BAD_REQUEST,void 0,void 0,!0);let r=(jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(qee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jr.buildFolderPath(e.path,r);await Xee(e.path);let s=await _0(e);return await Zee(n,e.format,s)}a(jee,"export_local");async function Xee(e){if(pn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw bt(new Error,`Invalid path: ${e}`,yt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Gg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,pn.error(n),bt(new Error,n,yt.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 pn.error(r),bt(new Error,r,yt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Xee,"confirmPath");async function Zee(e,t,r){if(pn.trace("in saveToLocal"),_l.isEmptyOrZeroLength(e))throw bt(new Error,Cr.INVALID_VALUE("file_path"),yt.BAD_REQUEST,void 0,void 0,!0);if(_l.isEmptyOrZeroLength(t))throw bt(new Error,Cr.INVALID_VALUE("Source format"),yt.BAD_REQUEST,void 0,void 0,!0);if(_l.isEmpty(r))throw bt(new Error,Cr.NOT_FOUND("Data"),yt.BAD_REQUEST,void 0,void 0,!0);if(t===a0){let n=Gg.createWriteStream(e);return kee(r).pipe(n),await Jee(n),{message:$ee,path:e}}else if(t===c0){let n=Gg.createWriteStream(e),s=dl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new xee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Yee,path:e}}throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST)}a(Zee,"saveToLocal");async function ete(e){if(!e.s3||Object.keys(e.s3).length===0)throw bt(new Error,Cr.MISSING_VALUE("S3 object"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw bt(new Error,Cr.MISSING_VALUE("aws_access_key_id"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw bt(new Error,Cr.MISSING_VALUE("aws_secret_access_key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw bt(new Error,Cr.MISSING_VALUE("bucket"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw bt(new Error,Cr.MISSING_VALUE("key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw bt(new Error,Cr.MISSING_VALUE("region"),yt.BAD_REQUEST);let t=l0(e);if(!jr.isEmpty(t))throw bt(new Error,t,yt.BAD_REQUEST);pn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await _0(e)}catch(u){throw pn.error(u),u}let n,s=await Hee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new dl.PassThrough;if(e.format===c0){i=e.s3.key+".csv";let u=u0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===a0){i=e.s3.key+".json";let u=new dl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%Kee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST);return new Vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(ete,"export_to_s3");function u0(e,t){let r=dl.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new Gee(n,s);return r.pipe(i)}a(u0,"toCsvStream");function l0(e){if(pn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(i0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${i0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(s0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${s0.join(", ")}`}a(l0,"exportCoreValidation");async function _0(e){pn.trace("in getRecords");let t,r;if(_l.isEmpty(e.search_operation)||_l.isEmptyOrZeroLength(e.search_operation.operation))throw bt(new Error,Cr.INVALID_VALUE("Search operation"),yt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Qee;break;case"search_by_hash":t=Wee;break;case"search_by_conditions":t=qg.searchByConditions;break;case"sql":t=zee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,pn.error(r),bt(new Error,r,yt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(_0,"getRecords")});var R0={};Fe(R0,{contentTypes:()=>$g,findBestSerializer:()=>zf,getDeserializer:()=>bo,registerContentHandlers:()=>Yg,serialize:()=>Jf,serializeMessage:()=>go});function tte(e){try{return e?.[0]===123?Vg(e):e}catch{return e}}function Yg(e){e.register(nte,{serializers:[{regex:/^application\/json$/,serializer:Ic},{regex:/^application\/cbor$/,serializer:function(t){return new Oo.EncoderStream(El).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Qf.Readable.from((0,ls.encodeIter)(t,El)):(0,ls.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Wf.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,ls.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Oo.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function zf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,E={q:1};for(let h of l){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=Ft.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)throw new m0.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Ft.keys()).join(", "),406);n=Ft.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Jf(e,t,r){let n=E0&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=zf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,xs.createBrotliCompress)({params:{[xs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?xs.constants.BROTLI_MODE_TEXT:xs.constants.BROTLI_MODE_GENERIC,[xs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>E0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,xs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function go(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return fl(e);let r=t.serialize;if(r)return r(e);let n=zf(t);return r=t.serialize=n.serializer.serialize,r(e)}function ste(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function bo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Ft.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Ft.get(e)?.deserialize||h0(e,n);return o=>ste(o).then(i)}return e&&Ft.get(e)?.deserialize||h0(e,n)}function h0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Vg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function ite(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var Wf,ls,Oo,xs,m0,Qf,p0,Fg,kg,S0,T0,fl,Vg,El,Ft,$g,f0,g0,rte,nte,E0,Ca=Re(()=>{nm();Wf=B(Kf()),ls=require("msgpackr"),Oo=require("cbor-x"),xs=require("zlib"),m0=B(ne()),Qf=require("stream");lr();p0=require("../index"),Fg=B(Z()),kg=B(P()),S0=B(require("yaml")),T0=Fg.default.get(kg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,fl=T0?Gi:JSON.stringify,Vg=T0?rm:JSON.parse,El={useRecords:!1,useToJSON:!0},Ft=new Map,$g=Ft;at.contentTypes=$g;(0,p0._assignPackageExport)("contentTypes",$g);Ft.set("application/json",{serializeStream:Ic,serialize:fl,deserialize:Vg,q:.8});f0=new Oo.Encoder(El);Ft.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Oo.EncoderStream(El).end(e)},serialize:f0.encode,deserialize:f0.decode,q:1});Ft.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Qf.Readable.from((0,ls.encodeIter)(e,El)):(0,ls.pack)(e)},serialize:ls.pack,deserialize:ls.unpack,q:.9});Ft.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Wf.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,Wf.toCsvStream)(e,e?.getColumns?.())},q:.1});Ft.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Ft.set("text/yaml",{serialize(e){return S0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ft.set("text/event-stream",{serializeStream:function(e){return Qf.Readable.from(ite(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
20
+ `),e.data){let r=e.data;typeof r=="object"&&(r=fl(r)),t+="data: "+r+`
21
21
  `}return e.id&&(t+="id: "+e.id+`
22
22
  `),e.retry&&(t+="retry: "+e.retry+`
23
23
  `),t+`
24
- `}else return typeof e=="object"?`data: ${ul(e)}
24
+ `}else return typeof e=="object"?`data: ${fl(e)}
25
25
 
26
26
  `:`data: ${e}
27
27
 
28
- `},compressible:!1,q:.8});qt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});S0={type:"application/json",serializeStream:bc,serialize:ul,deserialize:Wee,q:.5};qt.set("*/*",S0);qt.set("",S0);a(Wee,"tryJSONParse");a(Vg,"registerContentHandlers");Qee=require("fastify-plugin"),zee=Qee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Kf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Kf,"findBestSerializer");f0=Gg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Wf,"serialize");a(To,"serializeMessage");a(Jee,"streamToBuffer");a(Oo,"getDeserializer");a(E0,"deserializerUnknownType");a(jee,"transformIterable")});function Kg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let f=1;f<e.length;f++){let h=e[f],p=_(h);d=d.concat(p)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Kg(d.conditions,d.operator,r,n,s,i,o,c):Ha(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",b=l(h.conditions,!R,f);return R?(C,H)=>b.some(v=>v(C,H)):(C,H)=>b.every(v=>v(C,H))}let S=(h.attribute||h[0])===r.primaryKey,T=Qg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=ote(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ha(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],b=Gs(n.attributes,R);if(b.relationship){if(o.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let C=b.definition?.tableClass||b.elements?.definition?.tableClass,H=new Map,v=Ha({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,C,s,H);if(b.relationship.to){i[o[0]]=H;let F=!!Gs(C.attributes,b.relationship.to)?.elements;v=rte(v,b,C.primaryStore,F,H)}if(b.relationship.from){let F=a(M=>Ha({attribute:b.relationship.from,value:M},t,r,n,s,H),"searchEntry");b.elements?(i[o[0]]=H,v=nte(v,b,C.primaryStore,H,F)):v=v.flatMap(F)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(Wg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,E=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=ls.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Xr.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!E,E=!d,d=R}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||f||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Xr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Xr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Xr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Xr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Qg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(T).map(S?function({key:b,value:C}){return this.isSync?C&&S(C)?b:Ii.SKIP:new Promise((H,v)=>setImmediate(()=>{try{H(C&&S(C)?b:Ii.SKIP)}catch(F){v(F)}}))}:b=>b.value==null?Ii.SKIP:b);return R.hasEntries=!0,R}else return p?p.getRange(T).map(S?function({key:R,value:b}){return this.isSync?S({[o]:R})?b:Ii.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(S({[o]:R})?b:Ii.SKIP)}catch(v){H(v)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:b}){return this.isSync?b&&S(b)?R:Ii.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(b&&S(b)?R:Ii.SKIP)}catch(v){H(v)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function rte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=xn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function nte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=xn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(xn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(xn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Qg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Gs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=Qg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((R,b)=>{let C,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let F of h.idFilter.idSet)e={attribute:p.from,value:F};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(R);return S.idFilter&&(T.idFilter=S.idFilter),v}H=p(R,r,b),C=H?.value}else C=R[l];return C?Array.isArray(C)?C.some(h):h(C,H):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Wg[o]||o){case $g.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,E=u.length;d<E;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,ls.compareKeys)(l,u[0])>=0&&(0,ls.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,ls.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,ls.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,ls.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,ls.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,ls.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&zf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(R){let b=R[l],C;if(typeof b!="object"||!b||f?C=d(b):Array.isArray(b)?C=b.some(d):b instanceof Date&&(C=d(b.getTime())),E&&(S++,!C&&!T.idFilter&&++p/S*(i-S)>h)){let H=Ha(e,r.transaction.getReadTxn(),!1,t).map(xn),v=new Set(H);T.idFilter=F=>v.has(xn(F)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function zf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Wg[n]||n,n===$g.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=zf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=ete*xs(e.primaryStore)+1:n==="between"?r.estimated_count=Zee*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Xee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jf(e){if(e)if(wi=e,va.lastIndex=0,ste.test(e))try{let t=_l(new Ba,"");if(Cr!==wi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${Cr} in '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function _l(e,t){let r=va,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){Cr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=g0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=dl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=tte[d],u=Yg[i]?g0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=dl(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&R0(h,l),Qf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(dl(l)),s=void 0;break;case"(":va.lastIndex=Cr;let f=_l(l?[]:new Ba,")");switch(l){case"":Qf(e,_),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=A0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[Cr]===","?r.lastIndex=++Cr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");va.lastIndex=Cr,E=_l([],"}"),E.name=l,e.push(E),wi[Cr]===","?r.lastIndex=++Cr:o=!0;break;case"[":va.lastIndex=Cr,l?(E=_l(new Ba,"]"),E.name=l):E=_l(e.conditions?new Ba:[],"]"),e.conditions?(Qf(e,_),e.conditions.push(E),s=null):e.push(E),wi[Cr]===","?r.lastIndex=++Cr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&R0(h,l),Qf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(dl(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?ite:va,r.lastIndex=Cr),Cr===wi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Qf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function dl(e){return e.indexOf(".")>-1?e.split(".").map(dl):decodeURIComponent(e)}function g0(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(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function R0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function A0(e){let t=O0(e[0]);return e.length>1&&(t.next=A0(e.slice(1))),t}function O0(e){if(Array.isArray(e)){let t=O0(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function xn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function ote(e,t,r){return t*r/xs(e)}var Xr,$g,ls,Ii,Xee,Zee,ete,tte,Yg,Wg,ste,va,ite,Cr,wi,Ba,jf=Re(()=>{Xr=B(ne()),$g=B(ft()),ls=require("ordered-binary"),Ii=require("lmdb"),Xee=.3,Zee=.1,ete=.05,tte={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Yg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Kg,"executeConditions");a(Ha,"searchByIndex");a(Gs,"findAttribute");a(rte,"joinTo");a(nte,"joinFrom");Wg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Qg,"filterByType");a(zf,"estimateCondition");ste=/[()[\]|!<>.]|(=\w*=)/,va=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,ite=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jf,"parseQuery");a(_l,"parseBlock");a(Qf,"assignOperator");a(dl,"decodeProperty");a(g0,"typedDecoding");a(R0,"wildcardDecoding");a(A0,"toSortObject");a(O0,"toSortEntry");Ba=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(xn,"flattenKey");a(xs,"estimatedEntryCount");a(ote,"intersectionEstimate")});function w0(e){let t={openapi:ate,info:{title:"HarperDB HTTP REST interface",version:(0,I0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:b,name:C,elements:H,relationship:v,definition:F}of o){if(v)b==="array"?_[C]={type:"array",items:{$ref:Ci+H.type}}:_[C]={$ref:Ci+b};else{let M=F??H?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(J=>{Q[J.name]=new Xg(zg[J.type],J.type)}),t.components.schemas[M.type]=new N0(Q)}b==="array"?_[C]={type:"array",items:{$ref:Ci+M.type}}:_[C]={$ref:Ci+M.type}}else b==="array"?H.type==="Any"||H.type=="ID"?_[C]={type:"array",items:{format:H.type}}:_[C]={type:"array",items:new Xg(zg[H.type],H.type)}:b==="Any"||b=="ID"?_[C]={format:b}:_[C]=new Xg(zg[b],b)}l.push(new Zg(C,"query",_[C]))}let d=Object.keys(_),E=new Zg(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new Zg("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new N0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",R="/"+s+"/";h&&(t.paths[R]={},t.paths[R].post=new cte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new Jg(l,r,{200:new jg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new y0(l,r,"delete all the records that match the provided query",{204:new b0})),R="/"+s+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new Jg([E],r,{200:new jg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new ute([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new y0([E],r,"delete a record with the given primary key",{204:new b0})),S&&f.schema.enum.length>0&&(R="/"+s+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new Jg([E,f],r,{200:new jg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function cte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:eR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Jg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function jg(e){this.description=eR,this.content={"application/json":{schema:e}}}function b0(){this.description="successfully processed request, no content returned to client"}function ute(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:eR}}}function y0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function N0(e){this.type="object",this.properties=e}function Xg(e,t){this.type=e,this.format=t}function Zg(e,t,r){this.name=e,this.in=t,this.schema=r}var I0,ate,zg,Ci,eR,C0=Re(()=>{I0=B(Kd()),ate="3.0.3",zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",eR="successful operation";a(w0,"generateJsonApi");a(cte,"Post");a(Jg,"Get");a(jg,"Response200");a(b0,"Response204");a(ute,"Put");a(y0,"Delete");a(N0,"ResourceSchema");a(Xg,"Type");a(Zg,"Parameter")});var Zf={};Fe(Zf,{start:()=>dte});async function _te(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Jf(e);let s=new bi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==D0){let h=Xf.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 Ze(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new xa.ClientError(h,400)}if(e.authorize=!0,i===D0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return w0(Xf);throw new xa.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new xa.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new xa.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,tR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){lte[0]=d;let h=String.fromCharCode(34,(Wt[0]&63)+62,(Wt[0]>>6)+(Wt[1]<<2&63)+62,(Wt[1]>>4)+(Wt[2]<<4&63)+62,(Wt[2]>>2)+62,(Wt[3]&63)+62,(Wt[3]>>6)+(Wt[4]<<2&63)+62,(Wt[4]>>4)+(Wt[5]<<4&63)+62,(Wt[5]>>2)+62,(Wt[6]&63)+62,(Wt[6]>>6)+(Wt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),tR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=Wf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?bo.warn(i):bo.info(i):bo.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Wf(i.contentType?i:i.toString(),e,o),o}}function dte(e){tR=e,!L0&&(L0=!0,Xf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return _te(t,r)},e),e.server.ws(async(t,r,n)=>{fl++;let s=new yn;M0||(M0=!0,_u(u=>{fl>0&&u.push({metric:"ws-connections",connections:fl,byThread:!0})}));let i;t.on("error",u=>{i=!0,bo.warn(u)});let o;t.on("message",a(function(_){o||(o=Oo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{fl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=Xf.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,pr(h=>({count:h.count,total:fl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=To(f.value,r);t.send(h),pr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(fte[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var bo,xa,Wt,lte,tR,D0,L0,Xf,M0,fl,fte,P0=Re(()=>{wa();ws();bo=B($()),xa=B(ne());jf();Ac();ro();Qu();C0();Wt=new Uint8Array(8),lte=new Float64Array(Wt.buffer,0,1),tR={},D0="openapi";a(_te,"http");fl=0;a(dte,"start");fte={401:3e3,403:3003}});var rR=g((Qme,U0)=>{var{recordAction:eE,recordActionBinary:Ete}=(ws(),ie(du)),hte=require("fastify-plugin"),mte=200;U0.exports=hte(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),eE(o,"duration",_,d,l),Ete(s.raw.statusCode<400,"success",_,d,l);let E=mte;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{eE(performance.now()-c,"transfer",_,d,l),eE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,eE(E,"bytes-sent",_,d,l));let f=o.toFixed(3);s.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var cR=g((jme,x0)=>{var sE=require("clone"),iE=Xe(),pte=z(),rE=P(),zme=$(),nR=require("fs"),iR=require("joi"),{string:nE}=iR.types(),{hdb_errors:Ste,handleHDBError:tE}=ne(),{HDB_ERROR_MSGS:Jme,HTTP_STATUS_CODES:sR}=Ste,{common_validators:Ga}=zn(),v0=" is required",Tte=["insert","update","upsert"],oR={database:{presence:!1,format:Ga.schema_format,length:Ga.schema_length},schema:{presence:!1,format:Ga.schema_format,length:Ga.schema_length},table:{presence:!0,format:Ga.schema_format,length:Ga.schema_length},action:{inclusion:{within:Tte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},gte={schema:nE.required(),table:nE.required(),action:nE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Rte,AWS_SECRET:Ate,AWS_BUCKET:Ote,AWS_FILE_KEY:bte,REGION:yte}=rE.S3_BUCKET_AUTH_KEYS,Nte={s3:{presence:!0},[`s3.${Rte}`]:{presence:!0,type:"String"},[`s3.${Ate}`]:{presence:!0,type:"String"},[`s3.${Ote}`]:{presence:!0,type:"String"},[`s3.${bte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${yte}`]:{presence:!0,type:"String"}},B0=sE(oR);B0.data.presence={message:v0};var H0=sE(oR);H0.file_path.presence={message:v0};var Ite=Object.assign(sE(oR),Nte),aR=sE(gte);aR.csv_url=nE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function wte(e){let t=iE.validateObject(e,B0);return oE(e,t)}a(wte,"dataObject");function Cte(e){let t=iE.validateBySchema(e,iR.object(aR));return oE(e,t)}a(Cte,"urlObject");function Dte(e){let t=iE.validateObject(e,H0);return oE(e,t)}a(Dte,"fileObject");function Lte(e){let t=iE.validateObject(e,Ite);return oE(e,t)}a(Lte,"s3FileObject");function oE(e,t){if(!t){let r=pte.checkGlobalSchemaTable(e.schema,e.table);if(r)return tE(new Error,r,sR.BAD_REQUEST);if(e.operation===rE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{nR.accessSync(e.file_path,nR.constants.R_OK|nR.constants.F_OK)}catch(n){return n.code===rE.NODE_ERROR_CODES.ENOENT?tE(n,`No such file or directory ${n.path}`,sR.BAD_REQUEST):n.code===rE.NODE_ERROR_CODES.EACCES?tE(n,`Permission denied ${n.path}`,sR.BAD_REQUEST):tE(n)}}return t}a(oE,"postValidateChecks");x0.exports={dataObject:wte,urlObject:Cte,fileObject:Dte,s3FileObject:Lte}});var uR=g((Zme,G0)=>{"use strict";var El=$(),aE=P();async function Mte(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===aE.OPERATIONS_ENUM.INSERT||t.operation===aE.OPERATIONS_ENUM.UPDATE||t.operation===aE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===aE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(El.info(i.message),i):i.http_resp_msg?(El.error(`Error calling operation: ${e.name}`),El.error(i.http_resp_msg),i):(El.error(`Error calling operation: ${e.name}`),El.error(i),i)}}a(Mte,"callOperationFunctionAsAwait");G0.exports={callOperationFunctionAsAwait:Mte}});var F0=g((tpe,q0)=>{"use strict";var lR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},_R=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};q0.exports={BulkLoadFileObject:lR,BulkLoadDataObject:_R}});var V0=g((npe,k0)=>{"use strict";var dR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};k0.exports=dR});var SR=g((upe,oB)=>{"use strict";var cE=qr(),lE=cR(),Pte=require("needle"),Gn=P(),ipe=Ve(),qa=z(),{handleHDBError:ct,hdb_errors:X0}=ne(),{HTTP_STATUS_CODES:Qt,HDB_ERROR_MSGS:Lt,CHECK_LOGS_WRAPPER:No}=X0,Fa=$(),fR=require("papaparse");qa.promisifyPapaParse();var qn=require("fs-extra"),Ute=require("path"),{chain:$0}=require("stream-chain"),Y0=require("stream-json/streamers/StreamArray"),K0=require("stream-json/utils/Batch"),W0=require("stream-chain/utils/comp"),{finished:Q0}=require("stream"),vte=Z(),Z0=uR(),Bte=Bg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Hte}=F0(),mR=Ng(),{verifyBulkLoadAttributePerms:eB}=qf(),ope=V0(),ape=at(),cpe=Rs(),{databases:xte}=(Ae(),ie(ke)),{coerceType:Gte}=(_E(),ie(TR)),z0="No records parsed from csv file.",yo=`${vte.get("HDB_ROOT")}/tmp`,{schema_regex:qte}=zn(),J0=1024*1024*2,j0=5e3,Fte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};oB.exports={csvDataLoad:kte,csvURLLoad:Vte,csvFileLoad:$te,importFromS3:Yte};async function kte(e,t){let r=lE.dataObject(e);if(r)throw ct(r,r.message,Qt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=nB(e.schema,e.table),i=fR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:ER.bind(null,s),dynamicTyping:!1}),o=new mR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&eB(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 ct(new Error,c,Qt.BAD_REQUEST,void 0,void 0,!0);let u=new Hte(e.action,e.schema,e.table,i.data);return n=await Z0.callOperationFunctionAsAwait(sB,u,null),n.message===z0?z0:iB(n.records,n.number_written)}catch(s){throw Io(s)}}a(kte,"csvDataLoad");async function Vte(e){let t=lE.urlObject(e);if(t)throw ct(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${yo}/${r}`;try{await Kte(e,r)}catch(s){throw Fa.error(Lt.DOWNLOAD_FILE_ERR(r)+" - "+s),ct(s,No(Lt.DOWNLOAD_FILE_ERR(r)))}try{let s=new hR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await pR(s);return await uE(n),i}catch(s){throw await uE(n),Io(s)}}a(Vte,"csvURLLoad");async function $te(e){let t=lE.fileObject(e);if(t)throw ct(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=new hR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await pR(r)}catch(n){throw Io(n)}}a($te,"csvFileLoad");async function Yte(e){let t=lE.s3FileObject(e);if(t)throw ct(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Ute.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${yo}/${s}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Wte(s,e);let o=await pR(i);return await uE(r),o}catch(n){throw await uE(r),Io(n)}}a(Yte,"importFromS3");async function Kte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Pte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw ct(n,s,n.statusCode,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}zte(r,e.csv_url),await Qte(t,r.raw)}a(Kte,"downloadCSVFile");async function Wte(e,t){try{let r=`${yo}/${e}`;await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await Bte.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Fa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fa.error(Lt.S3_DOWNLOAD_ERR+" - "+r),ct(r,No(Lt.S3_DOWNLOAD_ERR))}}a(Wte,"downloadFileFromS3");async function Qte(e,t){try{await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,t)}catch(r){throw Fa.error(Lt.WRITE_TEMP_FILE_ERR),ct(r,No(Lt.DEFAULT_BULK_LOAD_ERR))}}a(Qte,"writeFileToTempFolder");async function uE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{Fa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(uE,"deleteTempFile");function zte(e,t){if(e.statusCode!==X0.HTTP_STATUS_CODES.OK)throw ct(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Qt.BAD_REQUEST);if(!Fte[e.headers["content-type"]])throw ct(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Qt.BAD_REQUEST);if(!e.raw)throw ct(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Qt.BAD_REQUEST)}a(zte,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await Jte(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await jte(e);break;default:throw ct(new Error,Lt.DEFAULT_BULK_LOAD_ERR,Qt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_FILE_EXT_ERR(e))}return iB(t.records,t.number_written)}catch(t){throw Io(t)}}a(pR,"fileLoad");async function tB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await cE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&eB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=ct(c);r(u)}}a(tB,"validateChunk");async function rB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;qa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!qa.isEmpty(c)&&!qa.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 Z0.callOperationFunctionAsAwait(sB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=ct(c,No(Lt.INSERT_CSV_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_CSV_ERR+" - "+c);r(u)}}a(rB,"insertChunk");async function Jte(e){let t={records:0,number_written:0},r=nB(e.schema,e.table);try{let n=new mR,s=qn.createReadStream(e.file_path,{highWaterMark:J0});s.setEncoding("utf8"),await fR.parsePromise(s,tB.bind(null,e,n),ER.bind(null,r));let i=n.getPermsResponse();if(i)throw ct(new Error,i,Qt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:J0}),s.setEncoding("utf8"),await fR.parsePromise(s,rB.bind(null,e,t),ER.bind(null,r)),s.destroy(),t}catch(n){throw ct(n,No(Lt.PAPA_PARSE_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.PAPA_PARSE_ERR+n)}}a(Jte,"callPapaParse");function nB(e,t){let r=xte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Gte(i,s));return n}a(nB,"createTransformMap");function ER(e,t,r){let n=e.get(r);return n?n(t):qa.autoCast(t)}a(ER,"typeFunction");async function jte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new mR,s=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await tB(e,n,r,c)})]);await new Promise((c,u)=>{Q0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ct(new Error,i,Qt.BAD_REQUEST);let o=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await rB(e,t,r,c)})]);return await new Promise((c,u)=>{Q0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw ct(n,No(Lt.INSERT_JSON_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_JSON_ERR+n)}}a(jte,"insertJson");async function sB(e){let t={};try{e.data&&e.data.length>0&&Xte(e.data[0])?t=await Zte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fa.info(t.message))}catch(r){throw Io(r)}return t}a(sB,"callBulkFileLoad");function Xte(e){let t=Object.keys(e);for(let r of t)if(!qte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Xte,"validateColumnNames");async function Zte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=cE.insert;break;case"update":i=cE.update;break;case"upsert":i=cE.upsert;break;default:throw ct(new Error,Lt.INVALID_ACTION_PARAM_ERR(n),Qt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=qa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(Zte,"bulkFileLoad");function iB(e,t){return`successfully loaded ${t} of ${e} records`}a(iB,"buildResponseMsg");function Io(e){return ct(e,No(Lt.DEFAULT_BULK_LOAD_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var cB=g((_pe,aB)=>{"use strict";var gR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};aB.exports=gR});var _B=g((fpe,lB)=>{"use strict";var ere=P(),uB=require("moment"),tre=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=tre(),this.type=void 0,this.start_datetime=uB().valueOf(),this.created_datetime=uB().valueOf(),this.end_datetime=void 0,this.status=ere.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};lB.exports=RR});var AR=g((hpe,pB)=>{"use strict";var rre=require("uuid").v4,EB=qr(),hB=Gr(),nre=es(),sre=ia(),ire=cB(),ut=P(),ore=_B(),are=Gd(),Sn=$(),cre=xc(),ka=z(),{promisify:ure}=require("util"),wo=require("moment"),lre=kf(),dE=cR(),dB=Wm(),{deleteTransactionLogsBeforeValidator:_re}=Rg(),{handleHDBError:dre,hdb_errors:fre}=ne(),{HTTP_STATUS_CODES:Ere}=fre,fB=hB.searchByValue,hre=hB.searchByHash,mre=EB.insert,pre=ure(lre.evaluateSQL),Sre=EB.update;pB.exports={addJob:Rre,updateJob:Ore,handleGetJob:Tre,handleGetJobsByStartDate:gre,getJobById:mB};async function Tre(e){try{let t=await mB(e.id);return ka.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 Sn.error("There was an error getting job",t),new Error(r)}}a(Tre,"handleGetJob");async function gre(e){try{let t=await Are(e);if(Sn.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=wo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=wo(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw Sn.error(r),new Error(r)}}a(gre,"handleGetJobsByStartDate");async function Rre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||ka.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Sn.info(l),t.error=l,t}if(!ut.JOB_TYPE_ENUM[e.operation])return Sn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case ut.OPERATIONS_ENUM.CSV_FILE_LOAD:n=dE.fileObject(e);break;case ut.OPERATIONS_ENUM.CSV_URL_LOAD:n=dE.urlObject(e);break;case ut.OPERATIONS_ENUM.CSV_DATA_LOAD:n=dE.dataObject(e);break;case ut.OPERATIONS_ENUM.IMPORT_FROM_S3:n=dE.s3FileObject(e);break;case ut.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ut.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=dB(e,"date");break;case ut.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=dB(e,"timestamp");break;case ut.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=_re(e);break;default:break}if(n)throw dre(n,n.message,Ere.BAD_REQUEST,void 0,void 0,!0);let s=new ore;s.type=e.operation===ut.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ut.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new nre(ut.SYSTEM_SCHEMA_NAME,ut.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await fB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=rre();try{o=await fB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Sn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new cre(ut.SYSTEM_SCHEMA_NAME,ut.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await mre(u)}catch(l){return Sn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Sn.trace(l)}return t}a(Rre,"addJob");async function Are(e){let t=wo(e.from_date,wo.ISO_8601),r=wo(e.to_date,wo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new ire(n,e.hdb_user);try{return await pre(s)}catch(i){throw Sn.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(Are,"getJobsInDateRange");async function mB(e){if(ka.isEmptyOrZeroLength(e))return ka.errorizeMessage("Invalid job ID specified.");let t=new sre(ut.SYSTEM_SCHEMA_NAME,ut.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await hre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Sn.error(n),ka.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(mB,"getJobById");async function Ore(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(ka.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ut.JOB_STATUS_ENUM.COMPLETE||e.status===ut.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=wo().valueOf());let t=new are(ut.SYSTEM_SCHEMA_NAME,ut.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Sre(t),r}a(Ore,"updateJob")});var OB=g((ppe,AB)=>{"use strict";var SB=z(),Dr=P(),bre=require("moment"),fE=SR(),EE=$(),TB=AR(),gB=Vf(),RB=oi(),yre=je(),Nre=Bf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Ire(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(SB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(SB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Dr.JOB_TYPE_ENUM.csv_file_load:await qs(e,fE.csvFileLoad);break;case Dr.JOB_TYPE_ENUM.csv_url_load:await qs(e,fE.csvURLLoad);break;case Dr.JOB_TYPE_ENUM.csv_data_load:await qs(e,fE.csvDataLoad);break;case Dr.JOB_TYPE_ENUM.import_from_s3:await qs(e,fE.importFromS3);break;case Dr.JOB_TYPE_ENUM.empty_trash:break;case Dr.JOB_TYPE_ENUM.export_local:await qs(e,gB.export_local);break;case Dr.JOB_TYPE_ENUM.export_to_s3:await qs(e,gB.export_to_s3);break;case Dr.JOB_TYPE_ENUM.delete_files_before:case Dr.JOB_TYPE_ENUM.delete_records_before:await qs(e,RB.deleteFilesBefore);break;case Dr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,RB.deleteAuditLogsBefore);break;case Dr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qs(e,Nre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Ire,"parseMessage");async function qs(e,t){try{e.job.status=Dr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=bre().valueOf(),await TB.updateJob(e.job),await wre(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):EE.error(`There was an error running ${t.name} job with id ${e.job.id}`),EE.error(n),e.job.message=n,e.job.status=Dr.JOB_STATUS_ENUM.ERROR;try{await TB.updateJob(e.job)}catch(s){throw EE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(qs,"runJob");async function wre(e){EE.trace("launching job thread:",e),yre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Dr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(wre,"launchJobThread");AB.exports={parseMessage:Ire,RunnerMessage:OR}});var yB=g((Tpe,bB)=>{"use strict";var bR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};bB.exports=bR});var kB=g((Rpe,DR)=>{"use strict";var TE=Gr(),IR=kf(),hE=SR(),Fs=Tu(),mE=As(),ml=oi(),Cre=qS(),hl=ln(),pE=zS(),zt=gg(),SE=$(),Dre=XS(),Lre=Xd(),NB=LT(),Mre=ef(),Pre=PT(),Ure=UT(),vre=HT(),Bre=GT(),yR=kT(),IB=Vf(),Hre=qf(),wR=AR(),q=P(),{hdb_errors:Sl,handleHDBError:pl}=ne(),{HTTP_STATUS_CODES:wB}=Sl,NR=WT(),CB=Af(),xB=require("util"),Va=qr(),xre=Os(),Gre=Ta(),DB=OB(),LB=yu(),MB=(Nf(),ie(zu)),PB=fr(),UB=Bf(),vB=Lf(),{setServerUtilities:qre}=(_E(),ie(TR)),{CONTEXT:Fre}=(Nn(),ie(qp)),{_assignPackageExport:kre}=require("../index"),{transformReq:Vre}=z(),{server:$re}=(ur(),ie(Hi)),sr=SE.loggerWithTag("operation"),Yre=uR(),BB=TE.searchByHash,Kre=TE.searchByValue,Wre=xB.promisify(TE.search),Qre=xB.promisify(IR.evaluateSQL),zre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=yB();async function GB(e,t){try{if(e.body.operation!=="read_log"&&(SE.log_level===q.LOG_LEVELS.INFO||SE.log_level===q.LOG_LEVELS.DEBUG||SE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;sr.info(o)}}catch(n){sr.error(n)}let r=await Yre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return zre[e.body.operation]&&xre.setSchemaDataToGlobal(n=>{n&&sr.error(n)}),r}a(GB,"processLocalTransaction");var HB=jre();DR.exports={chooseOperation:qB,getOperationFunction:FB,operation:CR,processLocalTransaction:GB};qre(DR.exports);$re.operation=CR;function qB(e){let t;try{t=FB(e)}catch(s){throw sr.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=IR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=IR.checkASTPermissions(e,i);if(o)throw sr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),sr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Hre.verifyPerms(i,s);if(o)throw sr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),sr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw pl(s,"There was an error when trying to choose an operation path")}return r}a(qB,"chooseOperation");function FB(e){if(sr.trace(`getOperationFunction with operation: ${e.operation}`),HB.has(e.operation))return HB.get(e.operation);throw pl(new Error,Sl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Sl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(FB,"getOperationFunction");kre("operation",CR);function CR(e,t){e.hdb_user=this[Fre]?.user,e.bypass_auth=!t;let r=qB(e);return GB({body:e},r)}a(CR,"operation");async function Jre(e){sr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Va.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Va.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Va.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await ml.deleteRecord(i);break;default:sr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){sr.info("Invalid operation in transaction"),sr.error(o)}}a(Jre,"catchup");async function _s(e){Vre(e);let t,r;try{r=await wR.addJob(e),t=r.createdJob,sr.info("addJob result",r);let n=new DB.RunnerMessage(t,e);return await DB.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw sr.error(s),pl(n,s)}}a(_s,"executeJob");function jre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(Va.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(Va.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(Va.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(TE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Kre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Wre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Qre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(_s,hE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(_s,hE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(_s,hE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(_s,hE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(mE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(mE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(mE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(mE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(ml.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(hl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(hl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(hl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(hl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(pE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(pE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(pE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(pE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(hl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Dre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Lre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(NB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(NB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Mre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Pre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Ure)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(PB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(vre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Bre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(yR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(yR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(yR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(_s,IB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(_s,IB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(wR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(wR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(NR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(NR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(NR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(CB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(CB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(Jre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Gre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(_s,ml.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Cre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(LB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(LB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(MB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(MB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(PB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(zt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(zt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(zt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(zt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(zt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(zt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(zt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(zt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(zt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(zt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(zt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(zt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(zt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(zt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(zt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(zt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(UB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,UB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(vB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(vB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(jre,"initializeOperationFunctionMap")});var RE=g((Ope,YB)=>{"use strict";var LR=P(),Xre=z(),Tl=$(),{handleHDBError:MR,hdb_errors:gE}=ne(),{isMainThread:Zre}=require("worker_threads"),{Readable:ene}=require("stream"),VB=require("os"),tne=require("util"),rne=cT(),nne=tne.promisify(rne.authorize),$B=kB(),{createGzip:sne,constants:ine}=require("zlib");function one(e){let t=`Found an uncaught exception with message: ${e.message}. ${VB.EOL}Stack: ${e.stack} ${VB.EOL}Terminating ${Zre?"HDB":"thread"}.`;console.error(t),Tl.fatal(t),process.exit(1)}a(one,"handleServerUncaughtException");function ane(e,t,r){if(Tl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:gE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(ane,"serverErrorHandler");function cne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=MR(new Error,"Invalid JSON.",gE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Xre.isEmpty(e.body.operation)){let n=MR(new Error,"Request body must include an 'operation' property.",gE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(cne,"reqBodyValidationHandler");function une(e,t,r){let n;e.body.operation!==LR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==LR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==LR.OPERATIONS_ENUM.LOGOUT?nne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Tl.warn(s),Tl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(MR(s,i,gE.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(une,"authHandler");async function lne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=$B.chooseOperation(e.body);let s=await $B.processLocalTransaction(e,n);if(s instanceof ene&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(sne({level:ine.Z_BEST_SPEED})))}return s}catch(s){throw Tl.error(s),s}}a(lne,"handlePostRequest");YB.exports={authHandler:une,handlePostRequest:lne,handleServerUncaughtException:one,serverErrorHandler:ane,reqBodyValidationHandler:cne}});var zB=g((ype,QB)=>{"use strict";var _ne=require("fastify-plugin"),{handlePostRequest:KB,authHandler:dne,reqBodyValidationHandler:fne}=RE();async function Ene(e){e.decorate("hdbCore",{preValidation:[fne,dne],request:t=>WB(KB(t,response)),requestWithoutAuthentication:(t,r)=>WB(KB(t,r,!0))})}a(Ene,"hdbCore");async function WB(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(WB,"convertAsyncIterators");QB.exports=_ne(Ene)});var XB=g((wpe,jB)=>{"use strict";var Ipe=require("fs"),PR=Z();PR.initSync();var{CONFIG_PARAMS:JB}=P(),hne=1024*1024*1024;function mne(e){let t=PR.get(JB.HTTP_TIMEOUT),r=PR.get(JB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:hne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(mne,"getServerOptions");jB.exports=mne});var tH=g((Dpe,eH)=>{"use strict";var UR=Z();UR.initSync();var{CONFIG_PARAMS:ZB}=P();function pne(){let e=UR.get(ZB.HTTP_CORSACCESSLIST),t=UR.get(ZB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(pne,"getCORSOptions");eH.exports=pne});var sH=g((Mpe,nH)=>{"use strict";var rH=Z();rH.initSync();var Sne=P();function Tne(){return rH.get(Sne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Tne,"getHeaderTimeoutConfig");nH.exports=Tne});var BR={};Fe(BR,{customFunctionsServer:()=>Ane,ready:()=>TH,start:()=>Rne});function Rne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=SH(t),it.http((await ks).server));let o=await ks,c=(0,vR.dirname)(s),u=(0,vR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!iH.has(c)){iH.add(c);try{o.register(bne(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ye.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:TH}}async function Ane(){try{Ye.info("In Custom Functions Fastify server"+process.cwd()),Ye.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ye.debug(`Custom Functions server process ${process.pid} starting up.`),await One();let e=_H.get(dH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await SH(e)}catch(r){throw Ye.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ye.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ye.error(`Custom Functions ${process.pid} Error: ${e}`),Ye.error(e),process.exit(1)}}async function One(){try{Ye.info("Custom Functions starting configuration."),await fH.setUsersToGlobal(),Ye.info("Custom Functions completed configuration.")}catch(e){Ye.error(e)}}function bne(e,t){return async function(r){try{Ye.info("Custom Functions starting buildRoutes"),Ye.trace("Loading fastify routes folder "+e),(0,oH.existsSync)(e)&&r.register(lH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ye.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ye.error(s.message):s&&Ye.error(s),o()})}catch(n){Ye.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function SH(e){Ye.info("Custom Functions starting buildServer.");let t=(0,EH.default)(e),r=(0,aH.default)(t);r.server.headersTimeout=(0,mH.default)(),r.setErrorHandler(pH.serverErrorHandler);let n=(0,hH.default)();return n&&r.register(cH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(uH.default),await r.register(gne),await r.after(),Vg(r),Ye.info("Custom Functions completed buildServer."),r}function TH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var vR,oH,aH,cH,uH,lH,_H,dH,Ye,gne,fH,EH,hH,mH,pH,ks,iH,gH=Re(()=>{vR=require("path"),oH=require("fs"),aH=B(require("fastify")),cH=B(require("@fastify/cors")),uH=B(rR()),lH=B(require("@fastify/autoload")),_H=B(Z()),dH=B(P()),Ye=B($()),gne=B(zB()),fH=B(ln()),EH=B(XB()),hH=B(tH()),mH=B(sH()),pH=B(RE());wa();ur();iH=new Set;a(Rne,"start");a(Ane,"customFunctionsServer");a(One,"setUp");a(bne,"buildRouteFolder");a(SH,"buildServer");a(TH,"ready")});var HR={};Fe(HR,{start:()=>yne});function yne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,yH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){AH||(AH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=RH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,OH.default)(s,(0,bH.realpathSync)(o))}}return i(s)},{runFirst:!0})),RH.set(r,n)}}}var OH,bH,yH,RH,AH,NH=Re(()=>{OH=B(require("send")),bH=require("fs"),yH=B(require("serve-static")),RH=new Map;a(yne,"start")});function wne(e,t=1,r){if(xR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:bE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===bE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Ine.push(s),await s,$a.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=OE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=$a.indexOf(n);o>-1&&$a.splice(o,1)}if(a(i,"removeWorker"),Ya){let o=Ya;Ya=[];for(let c of o)DH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{GR?GR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),xR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function LH(e=0,t){if(typeof e=="string")try{(0,yE.existsSync)(e)&&(0,yE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Cne:r=Dne(t):r=FR;let n=(0,Ka.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=DH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),GR=!0,r(o,(c,u)=>{if(!c){if(IH){let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});IH.deliverSocket(l,e,u),l.resume()}else xR>0?(Ya.length===0&&setTimeout(()=>{Ya.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Ya.push(o)):(console.log("start up a dynamic thread to handle request"),wne(0));pr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Une(l,c,e)}pr(!0,"socket-routed")})};let s=au();qR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function FR(e,t){let r,n=0;for(let s of $a){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=AE)return AE=i,t(r);n=i}AE=0,t(r)}function Cne(e,t){let r={};e.getpeername(r);let n=r.address,s=Wa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);FR(e,o=>{Wa.set(n,{worker:o,lastUsed:i}),t(o)})}function Dne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ka.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Wa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);FR(n,d=>{Wa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Mne(){AE=0;for(let e of $a)e.expectedIdle=e.recentELU.idle+Lne,e.requests=1;$a.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Une(e,t,r){let n=Pne++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),OE.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),OE.delete(n)),s.event=="destroy"&&(e.destroy(),OE.delete(n))})}var Co,Ka,bE,qR,yE,CH,Nne,$a,Ya,DH,IH,xR,Ine,GR,AE,wH,Wa,Lne,OE,Pne,MH=Re(()=>{Co=B(je()),Ka=require("net"),bE=B(P()),qR=B($()),yE=require("fs");ws();CH=require("worker_threads"),Nne=B(Ji()),$a=[],Ya=[],DH=[],xR=0,Ine=[];CH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(wne,"startHTTPWorker");a(LH,"startSocketServer");AE=0;a(FR,"findMostIdleWorker");wH=36e5,Wa=new Map;a(Cne,"findByRemoteAddressAffinity");a(Dne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+wH<e&&Wa.delete(t)},wH).unref();Lne=1e3;a(Mne,"updateWorkerIdleness");(0,Co.setMonitorListener)(Mne);OE=new Map,Pne=1;a(Une,"proxySocket")});var YR={};Fe(YR,{Request:()=>kR,createReuseportFd:()=>NE});var PH,kR,VR,$R,NE,IE=Re(()=>{PH=require("os"),kR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new $R(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},VR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},$R=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,PH.platform)()!="win32"&&(NE=require("node-unix-socket").createReuseportFd)});var HH=g((Wpe,BH)=>{"use strict";var vne=require("cluster"),Do=Z();Do.initSync();var vH=P(),kpe=require("util"),Vs=$(),Vpe=require("fs"),Bne=require("fastify"),$pe=au(),Hne=require("@fastify/cors"),xne=require("@fastify/compress"),Gne=require("@fastify/static"),qne=rR(),Fne=require("path"),{PACKAGE_ROOT:kne}=P(),Vne=Os(),$ne=z(),Yne=ln(),Kne=Ji(),{server:Wne}=(ur(),ie(Hi)),{node_request_key:Ype}=(IE(),ie(YR)),{authHandler:Qne,handlePostRequest:zne,serverErrorHandler:Jne,reqBodyValidationHandler:jne}=RE(),Kpe=require("net"),{registerContentHandlers:Xne}=(wa(),ie(T0)),Zne=6e4,ese=1024*1024*1024,tse="TRUE",{CONFIG_PARAMS:gl}=vH,Qa;BH.exports={hdbServer:UH,start:UH};async function UH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=vne.isMaster,await rse();let t=e.securePort>0;Qa=nse(t),await Qa.ready(),e||(e={}),e.isOperationsServer=!0;try{Wne.http(Qa.server,e),Qa.server.closeIdleConnections||await Qa.listen({port:0,host:"::"})}catch(r){throw Qa.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(UH,"operationsServer");async function rse(){Vs.trace("Configuring HarperDB process."),Vne.setSchemaDataToGlobal(),await Yne.setUsersToGlobal(),await Kne.getLicense()}a(rse,"setUp");function nse(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=sse(e),r=Bne(t);r.server.headersTimeout=ose(),r.setErrorHandler(Jne);let n=ise();n&&r.register(Hne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(qne),r.register(xne),r.register(Gne,{root:Fne.join(kne,"studio/build-local")}),Xne(r);let s=Do.get(vH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!$ne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[jne,Qne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),zne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(nse,"buildServer");function sse(e){let t=Do.get(gl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(gl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:ese,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(sse,"getServerOptions");function ise(){let e=Do.get(gl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(gl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===tse)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(ise,"getCORSOpts");function ose(){return Do.get(gl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Zne}a(ose,"getHeaderTimeoutConfig")});var jR={};Fe(jR,{disableNATS:()=>cse,publishToStream:()=>DE,setNATSReplicator:()=>KR,setPublishToStream:()=>use,setSubscription:()=>JR,start:()=>ase});function ase(){Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&_se()}function cse(e=!0){kH=e}function use(e,t){DE=e,JR=t}function _se(){if(kH||process.env._DISABLE_NATS)return;let e=hr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];KR(s,r,i)}}XR((r,n)=>{KR(r.tableName,r.databaseName,r),n&&$H(r)}),!xH&&(xH=!0)}function KR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Vt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){$H(i)}static subscribe(){let i=new yn;return JR(t,e,i),i}static subscribeOnThisThread(i){return i<(Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??lse)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new wE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=VH;return i}a(n,"getNATSTransaction")}function $H(e){let t=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME);DE(`${QR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,zR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var GH,QR,zR,qH,FH,Rl,Al,CE,kH,DE,JR,lse,VH,xH,wE,WR,YH=Re(()=>{Ae();Nn();GH=B(at()),QR=B(Ve()),zR=B(Rs());Ac();qH=B(wS()),FH=B(vr()),Rl=B(Z()),Al=B(P()),CE=B($());a(ase,"start");a(cse,"disableNATS");DE=GH.publishToStream,JR=qH.setSubscription;a(use,"setPublishToStream");lse=2;a(_se,"assignReplicationSource");a(KR,"setNATSReplicator");a($H,"publishSchema");wE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,E=l.operation=="put"?"upsert":l.operation;u||(CE.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(DE(`${QR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,zR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw CE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},WR=class extends wE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,FH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};VH=new WR});var ix=g(Di=>{"use strict";var{isMainThread:tA,parentPort:bl,threadId:LE}=require("worker_threads"),{Socket:dse,createServer:fse}=require("net"),{createServer:Ese,IncomingMessage:hse}=require("http"),{createServer:mse}=require("https"),{readFileSync:pse,unlinkSync:KH,existsSync:Sse}=require("fs"),Mt=$(),xe=Z(),lt=P(),{server:UE}=(ur(),ie(Hi)),{WebSocketServer:Tse}=require("ws"),{createSecureContext:gse,createServer:Rse}=require("node:tls"),{getTicketKeys:JH,restartNumber:Ase,getWorkerIndex:yl}=je(),{Headers:jH,appendHeader:Ose}=(Qu(),ie(VU)),{recordAction:Ol,recordActionBinary:bse}=(ws(),ie(du)),{Request:XH,createReuseportFd:WH}=(IE(),ie(YR)),{checkMemoryLimit:yse}=Ji(),{X509Certificate:Nse}=require("crypto"),ZH=require("tls"),Ise=ZH.createSecureContext,za;ZH.createSecureContext=function(e){return za||Ise(e)};var ex=xe.get(lt.CONFIG_PARAMS.THREADS_DEBUG);if(ex){let e;if(tA)e=xe.get(lt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Mt.info("Could not close debugger",t)}});else{let t=xe.get(lt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&yl()>=0&&(e=t+yl())}if(e){let t=xe.get(lt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=xe.get(lt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Mt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&tA)try{require("inspector").open(9229)}catch(e){Ase<=1&&Mt.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:eSe,CONFIG_PARAMS:wse}=lt;xe.initSync();var Cse=xe.get(wse.HTTP_SESSIONAFFINITY),ds={};Di.registerServer=iA;Di.httpServer=oA;Di.deliverSocket=sA;Di.startServers=tx;Di.when_components_loaded=null;Di.createSNICallback=aA;UE.http=oA;UE.request=Pse;UE.socket=Use;UE.ws=vse;var ZR={},ME={},Dse,$s={},PE={},Lse=[],rA=[];function tx(){return Di.when_components_loaded=cA().loadRootComponents(!0).then(()=>{bl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)sA(n,r,s);else if(t.requestId)Mse(t);else if(t.type===lt.ITC_EVENT_TYPES.SHUTDOWN){Mt.trace("received shutdown request",LE);for(let i in ds){let o=ds[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===1?Mt.info(`Closing ${f.length} idle connections`):E&&Mt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,p=f.length;h<p;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
28
+ `},compressible:!1,q:.8});Ft.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});g0={type:"application/json",serializeStream:Ic,serialize:fl,deserialize:tte,q:.5};Ft.set("*/*",g0);Ft.set("",g0);a(tte,"tryJSONParse");a(Yg,"registerContentHandlers");rte=require("fastify-plugin"),nte=rte(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=zf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(zf,"findBestSerializer");E0=Fg.default.get(kg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Jf,"serialize");a(go,"serializeMessage");a(ste,"streamToBuffer");a(bo,"getDeserializer");a(h0,"deserializerUnknownType");a(ite,"transformIterable")});function Qg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let f=1;f<e.length;f++){let h=e[f],p=_(h);d=d.concat(p)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Qg(d.conditions,d.operator,r,n,s,i,o,c):xa(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",b=l(h.conditions,!R,f);return R?(C,H)=>b.some(v=>v(C,H)):(C,H)=>b.every(v=>v(C,H))}let S=(h.attribute||h[0])===r.primaryKey,T=Jg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=Ete(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function xa(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],b=qs(n.attributes,R);if(b.relationship){if(o.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let C=b.definition?.tableClass||b.elements?.definition?.tableClass,H=new Map,v=xa({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,C,s,H);if(b.relationship.to){i[o[0]]=H;let F=!!qs(C.attributes,b.relationship.to)?.elements;v=lte(v,b,C.primaryStore,F,H)}if(b.relationship.from){let F=a(M=>xa({attribute:b.relationship.from,value:M},t,r,n,s,H),"searchEntry");b.elements?(i[o[0]]=H,v=_te(v,b,C.primaryStore,H,F)):v=v.flatMap(F)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(zg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,E=!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]=_s.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,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Xr.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!E,E=!d,d=R}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||f||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Xr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Xr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Xr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Xr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Jg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(T).map(S?function({key:b,value:C}){return this.isSync?C&&S(C)?b:wi.SKIP:new Promise((H,v)=>setImmediate(()=>{try{H(C&&S(C)?b:wi.SKIP)}catch(F){v(F)}}))}:b=>b.value==null?wi.SKIP:b);return R.hasEntries=!0,R}else return p?p.getRange(T).map(S?function({key:R,value:b}){return this.isSync?S({[o]:R})?b:wi.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(S({[o]:R})?b:wi.SKIP)}catch(v){H(v)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:b}){return this.isSync?b&&S(b)?R:wi.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(b&&S(b)?R:wi.SKIP)}catch(v){H(v)}}))})}function qs(e,t){if(Array.isArray(t))if(t.length>1){let r=qs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?qs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function lte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=xn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function _te(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=xn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(xn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(xn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Jg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=qs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=Jg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((R,b)=>{let C,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let F of h.idFilter.idSet)e={attribute:p.from,value:F};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(R);return S.idFilter&&(T.idFilter=S.idFilter),v}H=p(R,r,b),C=H?.value}else C=R[l];return C?Array.isArray(C)?C.some(h):h(C,H):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),zg[o]||o){case Kg.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,E=u.length;d<E;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,_s.compareKeys)(l,u[0])>=0&&(0,_s.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,_s.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,_s.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,_s.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,_s.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,_s.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&Xf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(R){let b=R[l],C;if(typeof b!="object"||!b||f?C=d(b):Array.isArray(b)?C=b.some(d):b instanceof Date&&(C=d(b.getTime())),E&&(S++,!C&&!T.idFilter&&++p/S*(i-S)>h)){let H=xa(e,r.transaction.getReadTxn(),!1,t).map(xn),v=new Set(H);T.idFilter=F=>v.has(xn(F)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function Xf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Gs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=zg[n]||n,n===Kg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=qs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Xf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Gs(e.indices[i.relationship.from])/(Gs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Gs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=cte*Gs(e.primaryStore)+1:n==="between"?r.estimated_count=ate*Gs(e.primaryStore)+1:n==="sort"?r.estimated_count=Gs(e.primaryStore)+1:r.estimated_count=ote*Gs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Zf(e){if(e)if(Ci=e,Ba.lastIndex=0,dte.test(e))try{let t=hl(new Ha,"");if(Dr!==Ci.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 ${Dr} in '${Ci}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function hl(e,t){let r=Ba,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(Ci);){Dr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=A0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=ml(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=ute[d],u=Wg[i]?A0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=ml(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&O0(h,l),jf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(ml(l)),s=void 0;break;case"(":Ba.lastIndex=Dr;let f=hl(l?[]:new Ha,")");switch(l){case"":jf(e,_),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=b0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Ci[Dr]===","?r.lastIndex=++Dr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ba.lastIndex=Dr,E=hl([],"}"),E.name=l,e.push(E),Ci[Dr]===","?r.lastIndex=++Dr:o=!0;break;case"[":Ba.lastIndex=Dr,l?(E=hl(new Ha,"]"),E.name=l):E=hl(e.conditions?new Ha:[],"]"),e.conditions?(jf(e,_),e.conditions.push(E),s=null):e.push(E),Ci[Dr]===","?r.lastIndex=++Dr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&O0(h,l),jf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(ml(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?fte:Ba,r.lastIndex=Dr),Dr===Ci.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function ml(e){return e.indexOf(".")>-1?e.split(".").map(ml):decodeURIComponent(e)}function A0(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(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function O0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function b0(e){let t=y0(e[0]);return e.length>1&&(t.next=b0(e.slice(1))),t}function y0(e){if(Array.isArray(e)){let t=y0(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function xn(e){return Array.isArray(e)?e.join("\0"):e}function Gs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function Ete(e,t,r){return t*r/Gs(e)}var Xr,Kg,_s,wi,ote,ate,cte,ute,Wg,zg,dte,Ba,fte,Dr,Ci,Ha,eE=Re(()=>{Xr=B(ne()),Kg=B(ft()),_s=require("ordered-binary"),wi=require("lmdb"),ote=.3,ate=.1,cte=.05,ute={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Wg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Qg,"executeConditions");a(xa,"searchByIndex");a(qs,"findAttribute");a(lte,"joinTo");a(_te,"joinFrom");zg={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(Jg,"filterByType");a(Xf,"estimateCondition");dte=/[()[\]|!<>.]|(=\w*=)/,Ba=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,fte=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Zf,"parseQuery");a(hl,"parseBlock");a(jf,"assignOperator");a(ml,"decodeProperty");a(A0,"typedDecoding");a(O0,"wildcardDecoding");a(b0,"toSortObject");a(y0,"toSortEntry");Ha=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(xn,"flattenKey");a(Gs,"estimatedEntryCount");a(Ete,"intersectionEstimate")});function D0(e){let t={openapi:hte,info:{title:"HarperDB HTTP REST interface",version:(0,C0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:b,name:C,elements:H,relationship:v,definition:F}of o){if(v)b==="array"?_[C]={type:"array",items:{$ref:Di+H.type}}:_[C]={$ref:Di+b};else{let M=F??H?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(J=>{Q[J.name]=new eR(jg[J.type],J.type)}),t.components.schemas[M.type]=new w0(Q)}b==="array"?_[C]={type:"array",items:{$ref:Di+M.type}}:_[C]={$ref:Di+M.type}}else b==="array"?H.type==="Any"||H.type=="ID"?_[C]={type:"array",items:{format:H.type}}:_[C]={type:"array",items:new eR(jg[H.type],H.type)}:b==="Any"||b=="ID"?_[C]={format:b}:_[C]=new eR(jg[b],b)}l.push(new tR(C,"query",_[C]))}let d=Object.keys(_),E=new tR(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new tR("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new w0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",R="/"+s+"/";h&&(t.paths[R]={},t.paths[R].post=new mte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new Xg(l,r,{200:new Zg({$ref:Di+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new I0(l,r,"delete all the records that match the provided query",{204:new N0})),R="/"+s+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new Xg([E],r,{200:new Zg({$ref:Di+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new pte([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new I0([E],r,"delete a record with the given primary key",{204:new N0})),S&&f.schema.enum.length>0&&(R="/"+s+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new Xg([E,f],r,{200:new Zg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function mte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Di+e}}}},this.security=t,this.responses={200:{description:rR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Xg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Zg(e){this.description=rR,this.content={"application/json":{schema:e}}}function N0(){this.description="successfully processed request, no content returned to client"}function pte(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Di+r}}}},this.responses={200:{description:rR}}}function I0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function w0(e){this.type="object",this.properties=e}function eR(e,t){this.type=e,this.format=t}function tR(e,t,r){this.name=e,this.in=t,this.schema=r}var C0,hte,jg,Di,rR,L0=Re(()=>{C0=B(Jd()),hte="3.0.3",jg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Di="#/components/schemas/",rR="successful operation";a(D0,"generateJsonApi");a(mte,"Post");a(Xg,"Get");a(Zg,"Response200");a(N0,"Response204");a(pte,"Put");a(I0,"Delete");a(w0,"ResourceSchema");a(eR,"Type");a(tR,"Parameter")});var rE={};Fe(rE,{start:()=>gte});async function Tte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Zf(e);let s=new yi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==M0){let h=tE.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 Ze(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=bo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ga.ClientError(h,400)}if(e.authorize=!0,i===M0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return D0(tE);throw new Ga.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Ga.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ga.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,nR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){Ste[0]=d;let h=String.fromCharCode(34,(Qt[0]&63)+62,(Qt[0]>>6)+(Qt[1]<<2&63)+62,(Qt[1]>>4)+(Qt[2]<<4&63)+62,(Qt[2]>>2)+62,(Qt[3]&63)+62,(Qt[3]>>6)+(Qt[4]<<2&63)+62,(Qt[4]>>4)+(Qt[5]<<4&63)+62,(Qt[5]>>2)+62,(Qt[6]&63)+62,(Qt[6]>>6)+(Qt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),nR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=Jf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?yo.warn(i):yo.info(i):yo.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Jf(i.contentType?i:i.toString(),e,o),o}}function gte(e){nR=e,!P0&&(P0=!0,tE=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Tte(t,r)},e),e.server.ws(async(t,r,n)=>{pl++;let s=new yn;U0||(U0=!0,Eu(u=>{pl>0&&u.push({metric:"ws-connections",connections:pl,byThread:!0})}));let i;t.on("error",u=>{i=!0,yo.warn(u)});let o;t.on("message",a(function(_){o||(o=bo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{pl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=tE.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,Sr(h=>({count:h.count,total:pl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=go(f.value,r);t.send(h),Sr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(Rte[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var yo,Ga,Qt,Ste,nR,M0,P0,tE,U0,pl,Rte,v0=Re(()=>{Ca();Cs();yo=B($()),Ga=B(ne());eE();yc();no();Xu();L0();Qt=new Uint8Array(8),Ste=new Float64Array(Qt.buffer,0,1),nR={},M0="openapi";a(Tte,"http");pl=0;a(gte,"start");Rte={401:3e3,403:3003}});var sR=g((spe,B0)=>{var{recordAction:nE,recordActionBinary:Ate}=(Cs(),ie(hu)),Ote=require("fastify-plugin"),bte=200;B0.exports=Ote(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),nE(o,"duration",_,d,l),Ate(s.raw.statusCode<400,"success",_,d,l);let E=bte;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{nE(performance.now()-c,"transfer",_,d,l),nE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,nE(E,"bytes-sent",_,d,l));let f=o.toFixed(3),h=s.getHeader("Server-Timing"),p=`db;dur=${f}`;s.header("Server-Timing",h?`${h}, ${p}`:p)}),r()},{name:"hdb-request-time"})});var lR=g((ape,q0)=>{var aE=require("clone"),cE=Xe(),yte=z(),iE=P(),ipe=$(),iR=require("fs"),aR=require("joi"),{string:oE}=aR.types(),{hdb_errors:Nte,handleHDBError:sE}=ne(),{HDB_ERROR_MSGS:ope,HTTP_STATUS_CODES:oR}=Nte,{common_validators:qa}=Jn(),H0=" is required",Ite=["insert","update","upsert"],cR={database:{presence:!1,format:qa.schema_format,length:qa.schema_length},schema:{presence:!1,format:qa.schema_format,length:qa.schema_length},table:{presence:!0,format:qa.schema_format,length:qa.schema_length},action:{inclusion:{within:Ite,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},wte={schema:oE.required(),table:oE.required(),action:oE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Cte,AWS_SECRET:Dte,AWS_BUCKET:Lte,AWS_FILE_KEY:Mte,REGION:Pte}=iE.S3_BUCKET_AUTH_KEYS,Ute={s3:{presence:!0},[`s3.${Cte}`]:{presence:!0,type:"String"},[`s3.${Dte}`]:{presence:!0,type:"String"},[`s3.${Lte}`]:{presence:!0,type:"String"},[`s3.${Mte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Pte}`]:{presence:!0,type:"String"}},x0=aE(cR);x0.data.presence={message:H0};var G0=aE(cR);G0.file_path.presence={message:H0};var vte=Object.assign(aE(cR),Ute),uR=aE(wte);uR.csv_url=oE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();uR.passthrough_headers=aR.object();function Bte(e){let t=cE.validateObject(e,x0);return uE(e,t)}a(Bte,"dataObject");function Hte(e){let t=cE.validateBySchema(e,aR.object(uR));return uE(e,t)}a(Hte,"urlObject");function xte(e){let t=cE.validateObject(e,G0);return uE(e,t)}a(xte,"fileObject");function Gte(e){let t=cE.validateObject(e,vte);return uE(e,t)}a(Gte,"s3FileObject");function uE(e,t){if(!t){let r=yte.checkGlobalSchemaTable(e.schema,e.table);if(r)return sE(new Error,r,oR.BAD_REQUEST);if(e.operation===iE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{iR.accessSync(e.file_path,iR.constants.R_OK|iR.constants.F_OK)}catch(n){return n.code===iE.NODE_ERROR_CODES.ENOENT?sE(n,`No such file or directory ${n.path}`,oR.BAD_REQUEST):n.code===iE.NODE_ERROR_CODES.EACCES?sE(n,`Permission denied ${n.path}`,oR.BAD_REQUEST):sE(n)}}return t}a(uE,"postValidateChecks");q0.exports={dataObject:Bte,urlObject:Hte,fileObject:xte,s3FileObject:Gte}});var _R=g((upe,F0)=>{"use strict";var Sl=$(),lE=P();async function qte(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===lE.OPERATIONS_ENUM.INSERT||t.operation===lE.OPERATIONS_ENUM.UPDATE||t.operation===lE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===lE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}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(qte,"callOperationFunctionAsAwait");F0.exports={callOperationFunctionAsAwait:qte}});var V0=g((_pe,k0)=>{"use strict";var dR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},fR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};k0.exports={BulkLoadFileObject:dR,BulkLoadDataObject:fR}});var Y0=g((fpe,$0)=>{"use strict";var ER=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};$0.exports=ER});var gR=g((Tpe,cB)=>{"use strict";var _E=qr(),fE=lR(),Fte=require("needle"),Gn=P(),hpe=Ve(),Fa=z(),{handleHDBError:lt,hdb_errors:eB}=ne(),{HTTP_STATUS_CODES:zt,HDB_ERROR_MSGS:Lt,CHECK_LOGS_WRAPPER:Io}=eB,ka=$(),hR=require("papaparse");Fa.promisifyPapaParse();var qn=require("fs-extra"),kte=require("path"),{chain:K0}=require("stream-chain"),W0=require("stream-json/streamers/StreamArray"),Q0=require("stream-json/utils/Batch"),z0=require("stream-chain/utils/comp"),{finished:J0}=require("stream"),Vte=Z(),tB=_R(),$te=xg(),{BulkLoadFileObject:pR,BulkLoadDataObject:Yte}=V0(),SR=wg(),{verifyBulkLoadAttributePerms:rB}=Vf(),mpe=Y0(),ppe=ut(),Spe=As(),{databases:Kte}=(Ae(),ie(ke)),{coerceType:Wte}=(EE(),ie(RR)),j0="No records parsed from csv file.",No=`${Vte.get("HDB_ROOT")}/tmp`,{schema_regex:Qte}=Jn(),X0=1024*1024*2,Z0=5e3,zte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};cB.exports={csvDataLoad:Jte,csvURLLoad:jte,csvFileLoad:Xte,importFromS3:Zte};async function Jte(e,t){let r=fE.dataObject(e);if(r)throw lt(r,r.message,zt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=iB(e.schema,e.table),i=hR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:mR.bind(null,s),dynamicTyping:!1}),o=new SR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&rB(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 lt(new Error,c,zt.BAD_REQUEST,void 0,void 0,!0);let u=new Yte(e.action,e.schema,e.table,i.data);return n=await tB.callOperationFunctionAsAwait(oB,u,null),n.message===j0?j0:aB(n.records,n.number_written)}catch(s){throw wo(s)}}a(Jte,"csvDataLoad");async function jte(e){let t=fE.urlObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${No}/${r}`;try{await ere(e,r)}catch(s){throw ka.error(Lt.DOWNLOAD_FILE_ERR(r)+" - "+s),lt(s,Io(Lt.DOWNLOAD_FILE_ERR(r)))}try{let s=new pR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await TR(s);return await dE(n),i}catch(s){throw await dE(n),wo(s)}}a(jte,"csvURLLoad");async function Xte(e){let t=fE.fileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=new pR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await TR(r)}catch(n){throw wo(n)}}a(Xte,"csvFileLoad");async function Zte(e){let t=fE.s3FileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=kte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${No}/${s}`;let i=new pR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await tre(s,e);let o=await TR(i);return await dE(r),o}catch(n){throw await dE(r),wo(n)}}a(Zte,"importFromS3");async function ere(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Fte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw lt(n,s,n.statusCode,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}nre(r,e.csv_url),await rre(t,r.raw)}a(ere,"downloadCSVFile");async function tre(e,t){try{let r=`${No}/${e}`;await qn.mkdirp(No),await qn.writeFile(`${No}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await $te.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){ka.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw ka.error(Lt.S3_DOWNLOAD_ERR+" - "+r),lt(r,Io(Lt.S3_DOWNLOAD_ERR))}}a(tre,"downloadFileFromS3");async function rre(e,t){try{await qn.mkdirp(No),await qn.writeFile(`${No}/${e}`,t)}catch(r){throw ka.error(Lt.WRITE_TEMP_FILE_ERR),lt(r,Io(Lt.DEFAULT_BULK_LOAD_ERR))}}a(rre,"writeFileToTempFolder");async function dE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{ka.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(dE,"deleteTempFile");function nre(e,t){if(e.statusCode!==eB.HTTP_STATUS_CODES.OK)throw lt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,zt.BAD_REQUEST);if(!zte[e.headers["content-type"]])throw lt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,zt.BAD_REQUEST);if(!e.raw)throw lt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,zt.BAD_REQUEST)}a(nre,"validateURLResponse");async function TR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await sre(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await ire(e);break;default:throw lt(new Error,Lt.DEFAULT_BULK_LOAD_ERR,zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_FILE_EXT_ERR(e))}return aB(t.records,t.number_written)}catch(t){throw wo(t)}}a(TR,"fileLoad");async function nB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await _E.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&rB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=lt(c);r(u)}}a(nB,"validateChunk");async function sB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Fa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Fa.isEmpty(c)&&!Fa.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 tB.callOperationFunctionAsAwait(oB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=lt(c,Io(Lt.INSERT_CSV_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_CSV_ERR+" - "+c);r(u)}}a(sB,"insertChunk");async function sre(e){let t={records:0,number_written:0},r=iB(e.schema,e.table);try{let n=new SR,s=qn.createReadStream(e.file_path,{highWaterMark:X0});s.setEncoding("utf8"),await hR.parsePromise(s,nB.bind(null,e,n),mR.bind(null,r));let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:X0}),s.setEncoding("utf8"),await hR.parsePromise(s,sB.bind(null,e,t),mR.bind(null,r)),s.destroy(),t}catch(n){throw lt(n,Io(Lt.PAPA_PARSE_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.PAPA_PARSE_ERR+n)}}a(sre,"callPapaParse");function iB(e,t){let r=Kte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Wte(i,s));return n}a(iB,"createTransformMap");function mR(e,t,r){let n=e.get(r);return n?n(t):Fa.autoCast(t)}a(mR,"typeFunction");async function ire(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new SR,s=K0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),W0.withParser(),c=>c.value,new Q0({batchSize:Z0}),z0(async c=>{await nB(e,n,r,c)})]);await new Promise((c,u)=>{J0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);let o=K0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),W0.withParser(),c=>c.value,new Q0({batchSize:Z0}),z0(async c=>{await sB(e,t,r,c)})]);return await new Promise((c,u)=>{J0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw lt(n,Io(Lt.INSERT_JSON_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_JSON_ERR+n)}}a(ire,"insertJson");async function oB(e){let t={};try{e.data&&e.data.length>0&&ore(e.data[0])?t=await are(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",ka.info(t.message))}catch(r){throw wo(r)}return t}a(oB,"callBulkFileLoad");function ore(e){let t=Object.keys(e);for(let r of t)if(!Qte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(ore,"validateColumnNames");async function are(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=_E.insert;break;case"update":i=_E.update;break;case"upsert":i=_E.upsert;break;default:throw lt(new Error,Lt.INVALID_ACTION_PARAM_ERR(n),zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Fa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw wo(o)}}a(are,"bulkFileLoad");function aB(e,t){return`successfully loaded ${t} of ${e} records`}a(aB,"buildResponseMsg");function wo(e){return lt(e,Io(Lt.DEFAULT_BULK_LOAD_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(wo,"buildTopLevelErrMsg")});var lB=g((Rpe,uB)=>{"use strict";var AR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};uB.exports=AR});var fB=g((Ope,dB)=>{"use strict";var cre=P(),_B=require("moment"),ure=require("uuid").v4,OR=class{static{a(this,"JobObject")}constructor(){this.id=ure(),this.type=void 0,this.start_datetime=_B().valueOf(),this.created_datetime=_B().valueOf(),this.end_datetime=void 0,this.status=cre.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};dB.exports=OR});var bR=g((ype,RB)=>{"use strict";var lre=require("uuid").v4,SB=qr(),TB=Gr(),_re=ts(),dre=ia(),fre=lB(),et=P(),Ere=fB(),hre=Vd(),Sn=$(),mre=Fc(),Va=z(),{promisify:pre}=require("util"),Co=require("moment"),Sre=Yf(),hE=lR(),EB=Qm(),{deleteTransactionLogsBeforeValidator:Tre}=Og(),{handleHDBError:hB,hdb_errors:gre}=ne(),{HTTP_STATUS_CODES:mB}=gre,pB=TB.searchByValue,Rre=TB.searchByHash,Are=SB.insert,Ore=pre(Sre.evaluateSQL),bre=SB.update;RB.exports={addJob:Ire,updateJob:Cre,handleGetJob:yre,handleGetJobsByStartDate:Nre,getJobById:gB};async function yre(e){try{let t=await gB(e.id);return Va.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 Sn.error("There was an error getting job",t),new Error(r)}}a(yre,"handleGetJob");async function Nre(e){try{let t=await wre(e);if(Sn.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=Co(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Co(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 Sn.error(r),new Error(r)}}a(Nre,"handleGetJobsByStartDate");async function Ire(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Va.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Sn.info(l),t.error=l,t}if(!et.JOB_TYPE_ENUM[e.operation])return Sn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case et.OPERATIONS_ENUM.CSV_FILE_LOAD:n=hE.fileObject(e);break;case et.OPERATIONS_ENUM.CSV_URL_LOAD:n=hE.urlObject(e);break;case et.OPERATIONS_ENUM.CSV_DATA_LOAD:n=hE.dataObject(e);break;case et.OPERATIONS_ENUM.IMPORT_FROM_S3:n=hE.s3FileObject(e);break;case et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=EB(e,"date");break;case et.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=EB(e,"timestamp");break;case et.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Tre(e);break;case et.OPERATIONS_ENUM.RESTART_SERVICE:if(et.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw hB(new Error,"Invalid service",mB.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw hB(n,n.message,mB.BAD_REQUEST,void 0,void 0,!0);let s=new Ere;s.type=e.operation===et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new _re(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await pB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=lre();try{o=await pB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Sn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new mre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await Are(u)}catch(l){return Sn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Sn.trace(l)}return t}a(Ire,"addJob");async function wre(e){let t=Co(e.from_date,Co.ISO_8601),r=Co(e.to_date,Co.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new fre(n,e.hdb_user);try{return await Ore(s)}catch(i){throw Sn.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(wre,"getJobsInDateRange");async function gB(e){if(Va.isEmptyOrZeroLength(e))return Va.errorizeMessage("Invalid job ID specified.");let t=new dre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Rre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Sn.error(n),Va.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(gB,"getJobById");async function Cre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Va.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===et.JOB_STATUS_ENUM.COMPLETE||e.status===et.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Co().valueOf());let t=new hre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await bre(t),r}a(Cre,"updateJob")});var CB=g((Ipe,wB)=>{"use strict";var AB=z(),Mt=P(),Dre=require("moment"),mE=gR(),Tl=$(),OB=bR(),bB=Kf(),yB=ai(),NB=We(),Lre=Gf(),Mre=zu(),{parentPort:Pre,isMainThread:IB}=require("worker_threads"),{onMessageByType:Ure}=We(),yR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function vre(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(AB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(AB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Mt.JOB_TYPE_ENUM.csv_file_load:await ds(e,mE.csvFileLoad);break;case Mt.JOB_TYPE_ENUM.csv_url_load:await ds(e,mE.csvURLLoad);break;case Mt.JOB_TYPE_ENUM.csv_data_load:await ds(e,mE.csvDataLoad);break;case Mt.JOB_TYPE_ENUM.import_from_s3:await ds(e,mE.importFromS3);break;case Mt.JOB_TYPE_ENUM.empty_trash:break;case Mt.JOB_TYPE_ENUM.export_local:await ds(e,bB.export_local);break;case Mt.JOB_TYPE_ENUM.export_to_s3:await ds(e,bB.export_to_s3);break;case Mt.JOB_TYPE_ENUM.delete_files_before:case Mt.JOB_TYPE_ENUM.delete_records_before:await ds(e,yB.deleteFilesBefore);break;case Mt.JOB_TYPE_ENUM.delete_audit_logs_before:await ds(e,yB.deleteAuditLogsBefore);break;case Mt.JOB_TYPE_ENUM.delete_transaction_logs_before:await ds(e,Lre.deleteTransactionLogsBefore);break;case Mt.JOB_TYPE_ENUM.restart_service:return await ds(e,Mre.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(vre,"parseMessage");async function ds(e,t){try{e.job.status=Mt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Dre().valueOf(),await OB.updateJob(e.job),await Bre(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):Tl.error(`There was an error running ${t.name} job with id ${e.job.id}`),Tl.error(n),e.job.message=n,e.job.status=Mt.JOB_STATUS_ENUM.ERROR;try{await OB.updateJob(e.job)}catch(s){throw Tl.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(ds,"runJob");async function Bre(e){Tl.trace("launching job thread:",e),IB?NB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):Pre.postMessage({type:Mt.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(Bre,"launchJobThread");IB&&Ure(Mt.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{NB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){Tl.error(r)}});wB.exports={parseMessage:vre,RunnerMessage:yR}});var LB=g((Cpe,DB)=>{"use strict";var NR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};DB.exports=NR});var QB=g((Lpe,MR)=>{"use strict";var RE=Gr(),CR=Yf(),pE=gR(),Fs=Au(),SE=Os(),Rl=ai(),Hre=FS(),gl=ln(),TE=JS(),Jt=Ag(),gE=$(),xre=ZS(),Gre=rf(),MB=MT(),qre=sf(),Fre=UT(),kre=vT(),Vre=xT(),$re=qT(),IR=VT(),PB=Kf(),Yre=Vf(),DR=bR(),q=P(),{hdb_errors:Ol,handleHDBError:Al}=ne(),{HTTP_STATUS_CODES:UB}=Ol,wR=QT(),vB=zu(),$B=require("util"),$a=qr(),Kre=bs(),Wre=ga(),BB=CB(),HB=wu(),xB=(Cf(),ie(Zu)),GB=Er(),qB=Gf(),FB=Uf(),{setServerUtilities:Qre}=(EE(),ie(RR)),{CONTEXT:zre}=(Nn(),ie(Fp)),{_assignPackageExport:Jre}=require("../index"),{transformReq:jre}=z(),{server:Xre}=(lr(),ie(xi)),or=gE.loggerWithTag("operation"),Zre=_R(),kB=RE.searchByHash,ene=RE.searchByValue,tne=$B.promisify(RE.search),rne=$B.promisify(CR.evaluateSQL),nne={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=LB();async function YB(e,t){try{if(e.body.operation!=="read_log"&&(gE.log_level===q.LOG_LEVELS.INFO||gE.log_level===q.LOG_LEVELS.DEBUG||gE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;or.info(o)}}catch(n){or.error(n)}let r=await Zre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return nne[e.body.operation]&&Kre.setSchemaDataToGlobal(n=>{n&&or.error(n)}),r}a(YB,"processLocalTransaction");var VB=ine();MR.exports={chooseOperation:KB,getOperationFunction:WB,operation:LR,processLocalTransaction:YB};Qre(MR.exports);Xre.operation=LR;function KB(e){let t;try{t=WB(e)}catch(s){throw or.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=CR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=CR.checkASTPermissions(e,i);if(o)throw or.error(`${UB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Al(new Error,o,Ol.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Yre.verifyPerms(i,s);if(o)throw or.error(`${UB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Al(new Error,o,Ol.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw Al(s,"There was an error when trying to choose an operation path")}return r}a(KB,"chooseOperation");function WB(e){if(or.trace(`getOperationFunction with operation: ${e.operation}`),VB.has(e.operation))return VB.get(e.operation);throw Al(new Error,Ol.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Ol.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(WB,"getOperationFunction");Jre("operation",LR);function LR(e,t){e.hdb_user=this[zre]?.user,e.bypass_auth=!t;let r=KB(e);return YB({body:e},r)}a(LR,"operation");async function sne(e){or.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await $a.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await $a.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await $a.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await Rl.deleteRecord(i);break;default:or.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){or.info("Invalid operation in transaction"),or.error(o)}}a(sne,"catchup");async function Fn(e){jre(e);let t,r;try{r=await DR.addJob(e),t=r.createdJob,or.info("addJob result",r);let n=new BB.RunnerMessage(t,e);return{message:await BB.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw or.error(s),Al(n,s)}}a(Fn,"executeJob");function ine(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y($a.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y($a.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y($a.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(RE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(kB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(kB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(ene)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(tne)),e.set(q.OPERATIONS_ENUM.SQL,new Y(rne)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(Fn,pE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(Fn,pE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(Fn,pE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(Fn,pE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(SE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(SE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(SE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(SE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(Rl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(gl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(gl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(gl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(gl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(TE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(TE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(TE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(TE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(gl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(xre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Gre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(MB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(MB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(qre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Fre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(kre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(GB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Vre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y($re)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(IR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(IR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(IR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(Fn,PB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(Fn,Rl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(Fn,Rl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(Fn,PB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(DR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(DR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(wR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(wR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(wR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(vB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(Fn,vB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(sne)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Wre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(Fn,Rl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Hre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(HB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(HB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(xB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(xB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(GB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Jt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Jt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Jt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Jt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Jt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Jt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Jt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Jt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Jt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Jt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Jt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Jt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Jt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Jt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Jt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Jt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(qB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(Fn,qB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(FB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(FB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(ine,"initializeOperationFunctionMap")});var OE=g((Ppe,jB)=>{"use strict";var PR=P(),one=z(),bl=$(),{handleHDBError:UR,hdb_errors:AE}=ne(),{isMainThread:ane}=require("worker_threads"),{Readable:cne}=require("stream"),zB=require("os"),une=require("util"),lne=uT(),_ne=une.promisify(lne.authorize),JB=QB(),{createGzip:dne,constants:fne}=require("zlib");function Ene(e){let t=`Found an uncaught exception with message: ${e.message}. ${zB.EOL}Stack: ${e.stack} ${zB.EOL}Terminating ${ane?"HDB":"thread"}.`;console.error(t),bl.fatal(t),process.exit(1)}a(Ene,"handleServerUncaughtException");function hne(e,t,r){if(bl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:AE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(hne,"serverErrorHandler");function mne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=UR(new Error,"Invalid JSON.",AE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(one.isEmpty(e.body.operation)){let n=UR(new Error,"Request body must include an 'operation' property.",AE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(mne,"reqBodyValidationHandler");function pne(e,t,r){let n;e.body.operation!==PR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==PR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==PR.OPERATIONS_ENUM.LOGOUT?_ne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{bl.warn(s),bl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(UR(s,i,AE.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(pne,"authHandler");async function Sne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=JB.chooseOperation(e.body);let s=await JB.processLocalTransaction(e,n);if(s instanceof cne&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(dne({level:fne.Z_BEST_SPEED})))}return s}catch(s){throw bl.error(s),s}}a(Sne,"handlePostRequest");jB.exports={authHandler:pne,handlePostRequest:Sne,handleServerUncaughtException:Ene,serverErrorHandler:hne,reqBodyValidationHandler:mne}});var tH=g((vpe,eH)=>{"use strict";var Tne=require("fastify-plugin"),{handlePostRequest:XB,authHandler:gne,reqBodyValidationHandler:Rne}=OE();async function Ane(e){e.decorate("hdbCore",{preValidation:[Rne,gne],request:t=>ZB(XB(t,response)),requestWithoutAuthentication:(t,r)=>ZB(XB(t,r,!0))})}a(Ane,"hdbCore");async function ZB(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(ZB,"convertAsyncIterators");eH.exports=Tne(Ane)});var sH=g((xpe,nH)=>{"use strict";var Hpe=require("fs"),vR=Z();vR.initSync();var{CONFIG_PARAMS:rH}=P(),One=1024*1024*1024;function bne(e){let t=vR.get(rH.HTTP_TIMEOUT),r=vR.get(rH.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:One,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(bne,"getServerOptions");nH.exports=bne});var aH=g((qpe,oH)=>{"use strict";var BR=Z();BR.initSync();var{CONFIG_PARAMS:iH}=P();function yne(){let e=BR.get(iH.HTTP_CORSACCESSLIST),t=BR.get(iH.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(yne,"getCORSOptions");oH.exports=yne});var lH=g((kpe,uH)=>{"use strict";var cH=Z();cH.initSync();var Nne=P();function Ine(){return cH.get(Nne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Ine,"getHeaderTimeoutConfig");uH.exports=Ine});var xR={};Fe(xR,{customFunctionsServer:()=>Dne,ready:()=>yH,start:()=>Cne});function Cne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=bH(t),at.http((await ks).server));let o=await ks,c=(0,HR.dirname)(s),u=(0,HR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!_H.has(c)){_H.add(c);try{o.register(Mne(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ye.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:yH}}async function Dne(){try{Ye.info("In Custom Functions Fastify server"+process.cwd()),Ye.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ye.debug(`Custom Functions server process ${process.pid} starting up.`),await Lne();let e=pH.get(SH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await bH(e)}catch(r){throw Ye.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ye.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ye.error(`Custom Functions ${process.pid} Error: ${e}`),Ye.error(e),process.exit(1)}}async function Lne(){try{Ye.info("Custom Functions starting configuration."),await TH.setUsersToGlobal(),Ye.info("Custom Functions completed configuration.")}catch(e){Ye.error(e)}}function Mne(e,t){return async function(r){try{Ye.info("Custom Functions starting buildRoutes"),Ye.trace("Loading fastify routes folder "+e),(0,dH.existsSync)(e)&&r.register(mH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ye.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ye.error(s.message):s&&Ye.error(s),o()})}catch(n){Ye.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function bH(e){Ye.info("Custom Functions starting buildServer.");let t=(0,gH.default)(e),r=(0,fH.default)(t);r.server.headersTimeout=(0,AH.default)(),r.setErrorHandler(OH.serverErrorHandler);let n=(0,RH.default)();return n&&r.register(EH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(hH.default),await r.register(wne),await r.after(),Yg(r),Ye.info("Custom Functions completed buildServer."),r}function yH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var HR,dH,fH,EH,hH,mH,pH,SH,Ye,wne,TH,gH,RH,AH,OH,ks,_H,NH=Re(()=>{HR=require("path"),dH=require("fs"),fH=B(require("fastify")),EH=B(require("@fastify/cors")),hH=B(sR()),mH=B(require("@fastify/autoload")),pH=B(Z()),SH=B(P()),Ye=B($()),wne=B(tH()),TH=B(ln()),gH=B(sH()),RH=B(aH()),AH=B(lH()),OH=B(OE());Ca();lr();_H=new Set;a(Cne,"start");a(Dne,"customFunctionsServer");a(Lne,"setUp");a(Mne,"buildRouteFolder");a(bH,"buildServer");a(yH,"ready")});var GR={};Fe(GR,{start:()=>Pne});function Pne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,LH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){wH||(wH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=IH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,CH.default)(s,(0,DH.realpathSync)(o))}}return i(s)},{runFirst:!0})),IH.set(r,n)}}}var CH,DH,LH,IH,wH,MH=Re(()=>{CH=B(require("send")),DH=require("fs"),LH=B(require("serve-static")),IH=new Map;a(Pne,"start")});function Bne(){let e=(0,BH.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),FR=setInterval(()=>{NE.notify(e)},vne).unref())}function Hne(e,t=1,r){if(qR++,(0,Vs.startWorker)("server/threads/threadServer.js",{name:za.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===za.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Une.push(s),await s,Ya.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=yE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Ya.indexOf(n);o>-1&&Ya.splice(o,1)}if(a(i,"removeWorker"),Ka){let o=Ka;Ka=[];for(let c of o)HH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{kR?kR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Vs.shutdownWorkers)(),qR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function xH(e=0,t){if(typeof e=="string")try{(0,IE.existsSync)(e)&&(0,IE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=xne:r=Gne(t):r=VR;let n=(0,Wa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=HH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),kR=!0,r(o,(c,u)=>{if(!c){if(PH){let l=o._socket||new Wa.Socket({handle:o,writable:!0,readable:!0});PH.deliverSocket(l,e,u),l.resume()}else qR>0?(Ka.length===0&&setTimeout(()=>{Ka.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,Ka.push(o)):(console.log("start up a dynamic thread to handle request"),Hne(0));Sr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Wa.Socket({handle:o,writable:!0,readable:!0});Vne(l,c,e)}Sr(!0,"socket-routed")})};let s=lu();NE.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function VR(e,t){let r,n=0;for(let s of Ya){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=bE)return bE=i,t(r);n=i}bE=0,t(r)}function xne(e,t){let r={};e.getpeername(r);let n=r.address,s=Qa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);VR(e,o=>{Qa.set(n,{worker:o,lastUsed:i}),t(o)})}function Gne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Wa.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Qa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);VR(n,d=>{Qa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Fne(){bE=0;for(let e of Ya)e.expectedIdle=e.recentELU.idle+qne,e.requests=1;Ya.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Vne(e,t,r){let n=kne++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),yE.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),yE.delete(n)),s.event=="destroy"&&(e.destroy(),yE.delete(n))})}var Vs,Wa,za,NE,IE,vH,BH,Ya,Ka,HH,PH,qR,Une,FR,vne,kR,bE,UH,Qa,qne,yE,kne,GH=Re(()=>{Vs=B(We()),Wa=require("net"),za=B(P()),NE=B($()),IE=require("fs");Cs();vH=require("worker_threads"),BH=B(ji()),Ya=[],Ka=[],HH=[],qR=0,Une=[];vH.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Vs.onMessageFromWorkers)(e=>{e.type===za.ITC_EVENT_TYPES.RESTART&&FR&&(clearInterval(FR),Bne())}));vne=6e5;a(Bne,"licenseWarning");a(Hne,"startHTTPWorker");a(xH,"startSocketServer");bE=0;a(VR,"findMostIdleWorker");UH=36e5,Qa=new Map;a(xne,"findByRemoteAddressAffinity");a(Gne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Qa)r.lastUsed+UH<e&&Qa.delete(t)},UH).unref();qne=1e3;a(Fne,"updateWorkerIdleness");(0,Vs.setMonitorListener)(Fne);yE=new Map,kne=1;a(Vne,"proxySocket")});var WR={};Fe(WR,{Request:()=>$R,createReuseportFd:()=>wE});var qH,$R,YR,KR,wE,CE=Re(()=>{qH=require("os"),$R=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new KR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new YR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},YR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},KR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,qH.platform)()!="win32"&&(wE=require("node-unix-socket").createReuseportFd)});var $H=g((nSe,VH)=>{"use strict";var $ne=require("cluster"),Do=Z();Do.initSync();var kH=P(),Xpe=require("util"),$s=$(),Zpe=require("fs"),Yne=require("fastify"),eSe=lu(),Kne=require("@fastify/cors"),Wne=require("@fastify/compress"),Qne=require("@fastify/static"),zne=sR(),Jne=require("path"),{PACKAGE_ROOT:jne}=P(),Xne=bs(),Zne=z(),ese=ln(),tse=ji(),{server:rse}=(lr(),ie(xi)),{node_request_key:tSe}=(CE(),ie(WR)),{authHandler:nse,handlePostRequest:sse,serverErrorHandler:ise,reqBodyValidationHandler:ose}=OE(),rSe=require("net"),{registerContentHandlers:ase}=(Ca(),ie(R0)),cse=6e4,use=1024*1024*1024,lse="TRUE",{CONFIG_PARAMS:yl}=kH,Ja;VH.exports={hdbServer:FH,start:FH};async function FH(e){try{$s.info("In Fastify server"+process.cwd()),$s.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$s.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=$ne.isMaster,await _se();let t=e.securePort>0;Ja=dse(t),await Ja.ready(),e||(e={}),e.isOperationsServer=!0;try{rse.http(Ja.server,e),Ja.server.closeIdleConnections||await Ja.listen({port:0,host:"::"})}catch(r){throw Ja.close(),$s.error(r),$s.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),$s.fatal(t),process.exit(1)}}a(FH,"operationsServer");async function _se(){$s.trace("Configuring HarperDB process."),Xne.setSchemaDataToGlobal(),await ese.setUsersToGlobal(),await tse.getLicense()}a(_se,"setUp");function dse(e){$s.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=fse(e),r=Yne(t);r.server.headersTimeout=hse(),r.setErrorHandler(ise);let n=Ese();n&&r.register(Kne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(zne),r.register(Wne),r.register(Qne,{root:Jne.join(jne,"studio/build-local")}),ase(r);let s=Do.get(kH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Zne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[ose,nse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),sse(i,o)}),r.get("/health",()=>"HarperDB is running."),$s.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(dse,"buildServer");function fse(e){let t=Do.get(yl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(yl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:use,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(fse,"getServerOptions");function Ese(){let e=Do.get(yl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(yl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===lse)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Ese,"getCORSOpts");function hse(){return Do.get(yl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??cse}a(hse,"getHeaderTimeoutConfig")});var ZR={};Fe(ZR,{disableNATS:()=>pse,publishToStream:()=>ME,setNATSReplicator:()=>QR,setPublishToStream:()=>Sse,setSubscription:()=>XR,start:()=>mse});function mse(){Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&gse()}function pse(e=!0){zH=e}function Sse(e,t){ME=e,XR=t}function gse(){if(zH||process.env._DISABLE_NATS)return;let e=mr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];QR(s,r,i)}}eA((r,n)=>{QR(r.tableName,r.databaseName,r),n&&jH(r)}),!YH&&(YH=!0)}function QR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends $t{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){jH(i)}static subscribe(){let i=new yn;return XR(t,e,i),i}static subscribeOnThisThread(i){return i<(Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Tse)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new DE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=JH;return i}a(n,"getNATSTransaction")}function jH(e){let t=Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_NODENAME);ME(`${JR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,jR.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 KH,JR,jR,WH,QH,Nl,Il,LE,zH,ME,XR,Tse,JH,YH,DE,zR,XH=Re(()=>{Ae();Nn();KH=B(ut()),JR=B(Ve()),jR=B(As());yc();WH=B(CS()),QH=B(vr()),Nl=B(Z()),Il=B(P()),LE=B($());a(mse,"start");a(pse,"disableNATS");ME=KH.publishToStream,XR=WH.setSubscription;a(Sse,"setPublishToStream");Tse=2;a(gse,"assignReplicationSource");a(QR,"setNATSReplicator");a(jH,"publishSchema");DE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,E=l.operation=="put"?"upsert":l.operation;u||(LE.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(ME(`${JR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,jR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw LE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},zR=class extends DE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,QH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};JH=new zR});var dx=g(Li=>{"use strict";var{isMainThread:nA,parentPort:Cl,threadId:PE}=require("worker_threads"),{Socket:Rse,createServer:Ase}=require("net"),{createServer:Ose,IncomingMessage:bse}=require("http"),{createServer:yse}=require("https"),{readFileSync:Nse,unlinkSync:ZH,existsSync:Ise}=require("fs"),Pt=$(),xe=Z(),_t=P(),{server:BE}=(lr(),ie(xi)),{WebSocketServer:wse}=require("ws"),{createSecureContext:Cse,createServer:Dse}=require("node:tls"),{getTicketKeys:nx,restartNumber:Lse,getWorkerIndex:Dl}=We(),{Headers:sx,appendHeader:Mse}=(Xu(),ie($U)),{recordAction:wl,recordActionBinary:Pse}=(Cs(),ie(hu)),{Request:ix,createReuseportFd:ex}=(CE(),ie(WR)),{checkMemoryLimit:Use}=ji(),{X509Certificate:vse}=require("crypto"),ox=require("tls"),Bse=ox.createSecureContext,ja;ox.createSecureContext=function(e){return ja||Bse(e)};var ax=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG);if(ax){let e;if(nA)e=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Pt.info("Could not close debugger",t)}});else{let t=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&Dl()>=0&&(e=t+Dl())}if(e){let t=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Pt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&nA)try{require("inspector").open(9229)}catch(e){Lse<=1&&Pt.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:lSe,CONFIG_PARAMS:Hse}=_t;xe.initSync();var xse=xe.get(Hse.HTTP_SESSIONAFFINITY),Es={};Li.registerServer=aA;Li.httpServer=cA;Li.deliverSocket=oA;Li.startServers=cx;Li.when_components_loaded=null;Li.createSNICallback=uA;BE.http=cA;BE.request=kse;BE.socket=Vse;BE.ws=$se;var tA={},UE={},Gse,Ys={},vE={},qse=[],sA=[];function cx(){return Li.when_components_loaded=lA().loadRootComponents(!0).then(()=>{Cl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)oA(n,r,s);else if(t.requestId)Fse(t);else if(t.type===_t.ITC_EVENT_TYPES.SHUTDOWN){Pt.trace("received shutdown request",PE);for(let i in Es){let o=Es[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===1?Pt.info(`Closing ${f.length} idle connections`):E&&Pt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,p=f.length;h<p;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
29
29
  Connection: close\r
30
30
  \r
31
- `))}},25).unref()}o.close?.(()=>{if(xe.get(lt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&yl()==0)try{KH(xe.get(lt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,LE),o.cantCleanupProperly||Mt.warn("Had to forcefully exit the thread",LE),process.exit(0)},5e3).unref()})}if(ex||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Mt.info("Could not close debugger",i)}}}).ref();let e=[];if(WH&&!Cse)for(let t in ds){let r=ds[t];if(isNaN(t)&&yl()==0){Sse(t)&&KH(t),e.push(new Promise((i,o)=>{r.listen({path:t},()=>{i(),Mt.info("Domain socket listening on "+t)}).on("error",o)}));continue}let n=xe.get(lt.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=yl();if(o<i[0]||o>i[1])continue}let s;try{s=WH(+t,"::")}catch(i){console.error(`Unable to bind to port ${t}`,i);continue}e.push(new Promise((i,o)=>{r.listen({fd:s},()=>{i(),Mt.trace("Listening on port "+t,LE)}).on("error",o)}))}Promise.all(e).then(()=>{bl?.postMessage({type:lt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(tx,"startServers");tA||tx();function sA(e,t,r){let n=e?.read?e:new dse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ds[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=ds[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Mt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(sA,"deliverSocket");var QH=new Map;function Mse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=QH.get(s),r){case"connection":i=sA(void 0,t),QH.set(s,i),i.write=(c,u,_)=>(bl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(bl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),bl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(Mse,"proxyRequest");function iA(e,t,r=!0){!+t&&t!==xe.get(lt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(xe.get(lt.CONFIG_PARAMS.HTTP_PORT),10));let n=ds[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",zH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ds[t]=e;e.on("unhandled",zH)}a(iA,"registerServer");function rx(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=[],xe.get(lt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:xe.get(lt.CONFIG_PARAMS.HTTP_PORT),secure:xe.get(lt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),xe.get(lt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:xe.get(lt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&xe.get(lt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:xe.get(lt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(rx,"getPorts");function oA(e,t){for(let{port:r,secure:n}of rx(t))nx(r,n,t?.isOperationsServer),typeof e=="function"?rA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,iA(e,r,!1)),PE[r]=nA(rA,r),Dse=nA(Lse,r)}a(oA,"httpServer");function nx(e,t,r){if(!$s[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:xe.get(n+"_keepAliveTimeout"),headersTimeout:xe.get(n+"_headersTimeout"),requestTimeout:xe.get(n+"_timeout")},i=xe.get(n+"_mtls"),o=xe.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=xe.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:JH(),maxHeaderSize:xe.get(lt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:aA(u)})}let c=yse();$s[e]=(t?mse:Ese)(s,async(u,_)=>{try{let d=performance.now(),E=new XH(u,_);r&&(E.isOperationsServer=!0);let f=await PE[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=sx(E)}if(c?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 H of f.headers||[])_.setHeader(H[0],H[1]);return u.baseRequest=E,_.baseResponse=f,$s[e].emit("unhandled",u,_)}let h=f.status||200,p=performance.now(),S=p-d,T=f.body,R;if(!f.handlesHeaders){let H=f.headers||new jH;T?T.length>=0&&(typeof T=="string"?H.set("Content-Length",Buffer.byteLength(T)):H.set("Content-Length",T.length),R=!0):(H.set("Content-Length","0"),R=!0);let v=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(v+=", miss"),Ose(H,"Server-Timing",v,!0),_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),R&&_.end(T)}let b=E.handlerPath,C=E.method;if(Ol(S,"duration",b,C,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),bse(h<400,"success",b,C),!R)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let H=0;T.on("data",v=>{H+=v.length}),T.on("end",()=>{Ol(performance.now()-p,"transfer",b,C),Ol(H,"bytes-sent",b,C)})}else T?.then?T.then(H=>{_.end(H)},l):_.end(T)}catch(d){l(d)}function l(d){let E=d.headers;_.writeHead(d.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),_.end(d.toString()),d.statusCode?d.statusCode===500?Mt.warn(d):Mt.info(d):Mt.error(d)}a(l,"onError")}),i&&($s[e].mtlsConfig=i),t&&($s[e].on("secureConnection",u=>{u._parent.startTime&&Ol(performance.now()-u._parent.startTime,"tls-handshake",e),Ol(u.isSessionReused(),"tls-reused",e)}),$s[e].isSecure=!0,s.SNICallback(null,(u,_)=>{try{za=_,_&&$s[e].setSecureContext(_.options)}finally{za=null}})),iA($s[e],e)}return $s[e]}a(nx,"getHTTPServer");function nA(e,t){let r=sx;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(nA,"makeCallbackChain");function sx(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new jH}}a(sx,"unhandled");function Pse(e,t){oA(e,{requestOnly:!0,...t})}a(Pse,"onRequest");function Use(e,t){let r;if(t.securePort){let n=Object.assign({},xe.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:aA(n)};r=Rse(s,e),s.SNICallback(null,(i,o)=>{try{za=o,o&&r.setSecureContext(o.options)}finally{za=null}}),ds[t.securePort]=r}return t.port&&(r=fse(e),ds[t.port]=r),r}a(Use,"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 vse(e,t){let r;for(let{port:n,secure:s}of rx(t)){ME[n]||(ME[n]=new Tse({server:r=nx(n,s)}),ME[n].on("connection",async(c,u)=>{try{let _=new XH(u);_.isWebSocket=!0;let l=PE[n](_),d=u.headers["sec-websocket-protocol"]||"",E=ZR[n];if(d){let f;for(let h=0;h<E.length;h++){let p=E[h];p.protocol===d&&(f=!0,p.listener(c,_,l))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,l)}}catch(_){Mt.warn("Error handling WebSocket connection",_)}}),ME[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=ZR[n];o||(o=ZR[n]=[]),o.push({listener:e,protocol:i}),PE[n]=nA(rA,n)}return r}a(vse,"onWebSocket");function zH(e,t){t.writeHead(404),t.end(`Not found
32
- `)}a(zH,"defaultNotFound");function eA(e){return e.startsWith("-----BEGIN")?e:pse(e)}a(eA,"readPEM");function aA(e){let t=[];for(let i=0;e[i];i++)t.push(e[i]);t.length||t.push(e);let r=new Map,n,s=!1;for(let i of t){let o=eA(i.privateKey),c=eA(i.certificate),u=i.certificateAuthority&&eA(i.certificateAuthority);if(!o||!c)throw new Error("Missing private key or certificate for secure server");let _={ciphers:i.ciphers,ca:u,ticketKeys:JH()},l=gse(_);l.options=_,_.instantiatedContext=l,l.context.setCert(c),l.context.setKey(o,void 0),_.cert=c,_.key=o,l.certStart=c.slice(0,100).toString(),n||(n=l);let d=new Nse(c),E=i.hostname??i.host??i.hostnames??i.hosts??(d.subjectAltName?d.subjectAltName.split(",").map(f=>{let h=f.indexOf(":");return f.slice(h+1)}):[d.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(E)||(E=[E]);for(let f of E)f?(f[0]==="*"&&(s=!0,f=f.slice(1)),r.has(f)||r.set(f,l)):Mt.error("No hostname found for certificate at",i.certificate)}return(i,o)=>{let c=i;for(;;){let u=r.get(c);if(u)return Mt.debug("Found certificate for",i,u.certStart),o(null,u);if(s&&c){let _=c.indexOf(".",1);_<0?c="":c=c.slice(_)}else break}Mt.debug("No certificate found to match",i,"using the first certificate"),o(null,n)}}a(aA,"createSNICallback")});async function ux({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await uA.get(e,{returnNonexistent:!0});i=new dA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await uA.get(e);o&&o.delete()}i=new BE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Nl.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function lA(){return vE++,vE>65500&&(vE=1),vE}function _A(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Oi.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var ox,Li,ax,cx,uA,Nl,vE,BE,dA,lx=Re(()=>{Ae();Wu();ox=B(vr()),Li=B($());ro();ax=B(je()),cx=B(ix());ur();uA=Et({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),Nl=Et({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,ax.getWorkerIndex)()===0&&(async()=>{await cx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Nl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await it.getUser(r.user.username)),Ze(r,()=>{try{_A(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}Nl.delete(e.id,r)})}})();a(ux,"getSession");vE=1;a(lA,"getNextMessageId");BE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Li.trace)("Resuming subscription from",s,"from",o);let f=Oi.getMatch(_);if(!f){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let T=E.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,T.indexOf("+")===T.length-1)E.onlyChildren=!0,E.url="/"+T.slice(0,T.length-1);else{let R=T.split("/"),b;for(let v=0;v<R.length;v++)if(R[v].indexOf("+")>-1)if(R[v]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let C=!0;R[R.length-1]==="#"&&(R.length--,C=!1),b&&(n=a(v=>{let F=v.id;if(!Array.isArray(F)||C&&F.length!==R.length)return!1;for(let M=0;M<R.length;M++)if(R[M]!=="+"&&R[M]!==F[M])return!1;return!0},"filter"));let H=R.indexOf("+");E.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Ze(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let R=await p.subscribe(E,T);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let b of R)try{let C;if(b.type&&b.type!=="put"&&b.type!=="delete"&&b.type!=="message"&&b.type!=="patch"||n&&!n(b))continue;r?(b.topic=s,C=this.needsAcknowledge(b)):(b.acknowledge?.(),C=lA());let H=b.id;Array.isArray(H)&&(H=Na(H)),H==null&&(H=""),this.listener(h+"/"+H,b.value,C,t)}catch(C){(0,Li.warn)(C)}})(),R});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=lA();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return _A(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ze(r,async()=>{try{if(!t){let n=await Nl.get(this.sessionId);n?.doesExist()&&await _A(n,n.data,r)}}finally{await Nl.delete(this.sessionId)}}).catch(n=>{(0,Li.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(_A,"publish");dA=class extends BE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=lA(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Li.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,ox.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),uA.put(this.sessionRecord)}}});var EA={};Fe(EA,{bypassAuth:()=>Bse,start:()=>Hse});function Bse(){hx=!0}function Hse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Ex.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),ir.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=dx(_,(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",E),_.on("close",f),_.on("error",h=>{ir.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),ir.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&xE.notify({username:l?.username,status:Jt.AUTH_AUDIT_STATUS.SUCCESS,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&xE.error({username:f,status:Jt.AUTH_AUDIT_STATUS.FAILURE,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else ir.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),ir.error(f)}else if(u.required)return ir.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&hx&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,fx.getSuperUser)(),ir.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=dx(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{ir.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function dx(e,t,r,n,s){_x||(_x=!0,_u(d=>{HE>0&&d.push({metric:"mqtt-connections",connections:HE,byThread:!0})}));let i;HE++;let o,c={protocolVersion:4},u=(0,GE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){HE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),ir.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;pr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await it.getUser(d.username,d.password.toString(),r),(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&xE.notify({username:n?.username,status:Jt.AUTH_AUDIT_STATUS.SUCCESS,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&xE.error({username:d.username,status:Jt.AUTH_AUDIT_STATUS.FAILURE,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=ux({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return ir.error(M),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,J,j)=>{try{let ae=M.indexOf("/",1),ce=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:J||Math.floor(Math.random()*1e8),qos:j.qos},ce)}catch(ae){ir.error(ae),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let R=[];for(let M of d.subscriptions){let Q;try{Q=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(J){s.events.emit("error",J,e,M,o),ir.error(J),Q=c.protocolVersion<5?128:J.statusCode===403?135:J.statusCode===404?143:128}R.push(Q)}await o.committed,p({cmd:"suback",granted:R,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let Q of d.unsubscriptions)M.push(o.removeSubscription(Q)?0:17);p({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let b=d.qos===2?"pubrec":"puback",C=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,F;try{F=await o.publish(d,v)}catch(M){s.events.emit("error",M,e,d,o),ir.warn(M),d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:F===!1?144:0},d.topic);break;case"pubrec":p({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!0,"connection","mqtt","disconnect"),ir.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(R){s.events.emit("error",R,e,d,o),ir.error(R),p({cmd:"disconnect"})}function p(R,b){let C=(0,GE.generate)(R,c);t(C),pr(C.length,"bytes-sent",b,S(R),"mqtt")}a(p,"sendPacket");function S(R){return R.qos>0?R.cmd+",qos="+R.qos:R.cmd}a(S,"packetMethodName");function T(R){return To(R,r)}a(T,"serialize")}),{onMessage:_,onClose:l}}var GE,fx,Ja,Jt,fA,Ex,xE,ir,hx,_x,HE,mx=Re(()=>{GE=require("mqtt-packet");lx();fx=B(ln());wa();ws();ur();Ja=B(Z()),Jt=B(P()),fA=B($()),Ex=require("events"),xE=(0,fA.loggerWithTag)("auth-event"),ir=(0,fA.loggerWithTag)("mqtt"),hx=(0,Ja.get)(Jt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Bse,"bypassAuth");a(Hse,"start");HE=0;a(dx,"onSocket")});var Uf={};Fe(Uf,{component_errors:()=>Xa,loadComponent:()=>qE,loadComponentDirectories:()=>yx,setErrorReporter:()=>Fse});function yx(e,t){t&&(mA=t),e&&(pA=e);let r=[];if((0,_t.existsSync)(hA)){let s=(0,_t.readdirSync)(hA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,rt.join)(hA,o);r.push(qE(c,mA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(qE(n,mA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{bx=!0})}function Fse(e){Il=e}async function qE(e,t,r,n,s,i){let o=(0,_t.realpathSync)(e);if(!Sx.has(o)){Sx.set(o,!0),s&&(pA=s);try{let c;n&&(Xa=new Map);let u=(0,rt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,_t.existsSync)(u)?c=n?(0,Ox.getConfigObj)():(0,Tx.parseDocument)((0,_t.readFileSync)(u,"utf8"),{simpleKeys:!0}).toJSON():c=SA;let _=(0,rt.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&((0,_t.existsSync)(_)||n)&&((0,_t.rmSync)(_,{recursive:!0,force:!0}),(0,_t.existsSync)((0,rt.join)(e,"node_modules"))||(0,_t.mkdirSync)((0,rt.join)(e,"node_modules")),(0,_t.symlinkSync)(Cl.PACKAGE_ROOT,_,"dir"))}catch(E){ja.default.error("Error symlinking harperdb module",E)}let l=[],d=n;for(let E in c){let f=c[E];if(Xa.set(n?E:(0,rt.basename)(e),!1),!f)continue;let h,p=f.package;try{if(p){let C=e,H;for(;!(0,_t.existsSync)(H=(0,rt.join)(C,"node_modules",E));)if(C=(0,rt.dirname)(C),C.length<(0,Ax.getHdbBasePath)().length){H=null;break}if(H)h=await qE(H,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${p}`)}else h=qse[E];if(!h)continue;l.push(h);let S=a(C=>(C.origin=r,Et(C)),"ensureTable"),T=f.network||(f.port||f.securePort)&&f,R=T?.securePort||T?.https&&T.port,b=!T?.https&&T?.port;if(Lo.isMainThread&&(h=await h.startOnMainThread?.({server:it,ensureTable:S,port:b,securePort:R,resources:t,...f})||h,n&&T))for(let C of[b,R])try{if(+C&&!px.includes(C)){let H=TA.get(Cl.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);H&&ja.default.warn("Session affinity is not recommended and may cause memory leaks"),(H||!NE)&&(px.push(C),LH(C,H))}}catch(H){console.error("Error listening on socket",C,H,E)}if(t.isWorker&&(h=await h.start?.({server:it,ensureTable:S,port:b,securePort:R,resources:t,...f})||h),pA.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,Rx.handleHDBError)("Can not reference parent directories");let C=(0,rt.join)(e,f.files).replace(/\\/g,"/"),H=C.indexOf("/*");if(H>-1&&f.files!==SA[E]?.files&&!(0,_t.existsSync)(C.slice(0,H)))throw new Error(`The path '${C.slice(0,H)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let v=(0,rt.basename)(e),F=f.path||"/";F=F.startsWith("/")?F:F.startsWith("./")?"/"+v+F.slice(2):F==="."?"/"+v:"/"+v+"/"+F;let M,Q,J;if(f.root){let ae=f.root;ae.startsWith("/")&&(ae=ae.slice(1)),ae.endsWith("/")&&(ae=ae.slice(0,-1)),ae+="/",Q=(0,rt.join)(e,ae)}else(J=C.indexOf("/*"))>-1&&(Q=C.slice(0,J+1),M=(0,rt.relative)(e,Q));let j=!1;if(Lo.isMainThread&&h.setupDirectory&&(j=await h.setupDirectory?.(F,Q,t)),t.isWorker&&h.handleDirectory&&(j=await h.handleDirectory?.(F,Q,t)),j)continue;for(let ae of await(0,gx.default)(C,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:ge}=ae;d=!0;let Ge=(0,rt.relative)(e,ce).replace(/\\/g,"/");if(M)if(Ge.startsWith(M))Ge=Ge.slice(M.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${Ge}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Ne=F+(F.endsWith("/")?"":"/")+Ge;try{if(ge.isFile()){let ve=await Gse(ce);Lo.isMainThread&&await h.setupFile?.(ve,Ne,ce,t),t.isWorker&&await h.handleFile?.(ve,Ne,ce,t)}else Lo.isMainThread&&await h.setupDirectory?.(Ne,ce,t),t.isWorker&&await h.handleDirectory?.(Ne,ce,t)}catch(ve){ve.message=`Could not load ${ge.isFile()?"file":"directory"} '${ce}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${ve.message}`,Il?.(ve),((0,Za.getWorkerIndex)()===0?console:ja.default).error(ve),t.set(f.path||"/",new wl(ve)),Xa.set(n?E:(0,rt.basename)(e),ve.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,rt.basename)(e)}' due to: ${S.message}`,Il?.(S),((0,Za.getWorkerIndex)()===0?console:ja.default).error(S),t.set(f.path||"/",new wl(S),null,!0),Xa.set(n?E:(0,rt.basename)(e),S.message)}}if(Lo.isMainThread&&!bx&&i&&(0,Za.watchDir)(e,async()=>yx()),c.extensionModule)return await __((0,rt.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;Il?.(new Error(E)),((0,Za.getWorkerIndex)()===0?console:ja.default).error(E),Xa.set((0,rt.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Il?.(c),t.set("",new wl(c))}}}var _t,rt,Lo,Tx,TA,Cl,gx,Za,ja,Rx,Ax,xse,Ox,Gse,hA,pA,bx,mA,Xa,qse,SA,px,Sx,Il,wl,vf=Re(()=>{_t=require("fs"),rt=require("path"),Lo=require("worker_threads"),Tx=require("yaml"),TA=B(Z()),Cl=B(P());Tb();Ob();bb();P0();gH();NH();gx=B(require("fast-glob")),Za=B(je()),ja=B($());zh();ur();Rx=B(ne());Nn();Ae();MH();Ax=B(Z()),xse=B(HH());Nf();YH();mx();Ox=B(fr());IE();({readFile:Gse}=_t.promises),hA=TA.get(Cl.CONFIG_PARAMS.COMPONENTSROOT),pA=new Map,Xa=new Map;a(yx,"loadComponentDirectories");qse={REST:Zf,rest:Zf,graphqlSchema:Qh,jsResource:jh,fastifyRoutes:BR,login:Zh,static:HR,operationsApi:xse,customFunctions:{},http:{},clustering:jR,authentication:zu,mqtt:EA},SA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(SA,"static",{value:{files:"web/**"}});px=[],Sx=new Map;a(Fse,"setErrorReporter");a(qE,"loadComponent");wl=class extends Vt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var cA=g((OSe,Ix)=>{var{isMainThread:Nx}=require("worker_threads"),{getTables:kse}=(Ae(),ie(ke)),{loadComponentDirectories:Vse,loadComponent:$se}=(vf(),ie(Uf)),{resetResources:Yse}=(Wu(),ie(kU)),Kse=pg(),Wse=fr(),{dirname:Qse}=require("path"),{getConnection:zse}=at(),Jse=Z(),jse=P(),gA=new Map;async function Xse(e=!1){!Nx&&Jse.get(jse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&zse();try{Nx&&await Kse()}catch(n){console.error(n)}let t=Yse();kse(),t.isWorker=e,await $se(Qse(Wse.getConfigFilePath()),t,"hdb",!0,gA),await Vse(gA,t);let r=[];for(let[n]of gA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Xse,"loadRootComponents");Ix.exports.loadRootComponents=Xse});var je=g((ySe,Pi)=>{"use strict";var{Worker:Zse,MessageChannel:eie,parentPort:Es,isMainThread:yA,threadId:tie,workerData:Ys}=require("worker_threads"),{PACKAGE_ROOT:rie}=P(),{join:Lx,isAbsolute:nie,extname:sie}=require("path"),{server:Mx}=(ur(),ie(Hi)),{watch:iie,readdir:oie}=require("fs/promises"),{totalmem:wx}=require("os"),Dl=P(),Px=Z(),Ks=$(),{randomBytes:aie}=require("crypto"),{_assignPackageExport:cie}=require("../index"),uie=P(),Cx=1024*1024,Mi=[],Tn=[],lie=50,NA=1e4,_ie="restart",Ux="request_thread_info",vx="resource_report",Bx="thread_info",Hx="added-port",die="ack",RA;cie("threads",Tn);Pi.exports={startWorker:AA,restartWorkers:wA,shutdownWorkers:pie,workers:Mi,setMonitorListener:yie,onMessageFromWorkers:Sie,onMessageByType:$x,broadcast:gie,broadcastWithAcknowledgement:Aie,setChildListenerByType:mie,getWorkerIndex:xx,getWorkerCount:Gx,getTicketKeys:Fx,setMainIsWorker:Eie,setTerminateTimeout:fie,restartNumber:Ys?.restartNumber||1};Tn.onMessageByType=$x;Tn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Tn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var IA;function fie(e){NA=e}a(fie,"setTerminateTimeout");function xx(){return Ys?Ys.workerIndex:IA?0:void 0}a(xx,"getWorkerIndex");function Gx(){return Ys?Ys.workerCount:IA?1:void 0}a(Gx,"getWorkerCount");function Eie(e){IA=e}a(Eie,"setMainIsWorker");var qx=1,FE;function Fx(){return FE||(FE=yA?aie(48):Ys.ticketKeys,FE)}a(Fx,"getTicketKeys");Object.defineProperty(Mx,"workerIndex",{get(){return xx()}});Object.defineProperty(Mx,"workerCount",{get(){return Gx()}});var kx={[Ux](e,t){Oie(t)},[vx](e,t){bie(t,e)}};function AA(e,t={}){let r=process.constrainedMemory?.()||wx();r=Math.min(r,wx(),2e4*Cx);let n=Px.get(Dl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Cx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Tn){let _=new eie;_.existingPort=u,i.push(_),o.push(_.port2)}sie(e)||(e+=".js");let c=new Zse(nie(e)?e:Lx(rie,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:qx=t.threadCount,name:t.name,restartNumber:Pi.exports.restartNumber,ticketKeys:Fx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Hx,port:u,threadId:c.threadId},[u]);return VE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>AA(e,t),c.on("error",u=>{Ks.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<lie?(t.unexpectedRestarts=c.unexpectedRestarts+1,AA(e,t)):Ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{kx[u.type]?.(u,c)}),Mi.push(c),Iie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(AA,"startWorker");var hie=[Dl.THREAD_TYPES.HTTP];async function wA(e=null,t=Math.max(qx>3,1),r=!0){if(yA){if(r){let{loadRootComponents:o}=cA();await o()}Pi.exports.restartNumber++,t<1&&(t=t*Mi.length);let n=[],s=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Pi.exports.restartNumber,type:Dl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=hie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),NA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let E=a(f=>{f.type===uie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ks.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=Af();r&&(e==="http"||!e)&&Px.get(Dl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Es.postMessage({type:_ie,workerType:e})}a(wA,"restartWorkers");function mie(e,t){kx[e]=t}a(mie,"setChildListenerByType");function pie(e){return wA(e,1/0,!1)}a(pie,"shutdownWorkers");var Vx=[];function Sie(e){Vx.push(e)}a(Sie,"onMessageFromWorkers");var OA=new Map;function $x(e,t){let r=OA.get(e);r||OA.set(e,r=[]),r.push(t)}a($x,"onMessageByType");var Tie=10;async function gie(e){let t=0;for(let r of Tn)try{r.postMessage(e),t++>Tie&&(t=0,await new Promise(setImmediate))}catch(n){Ks.error("Unable to send message to worker",n)}}a(gie,"broadcast");var kE=new Map,Rie=1;function Aie(e){return new Promise(t=>{let r=0;for(let n of Tn)try{let s=Rie++,i=a(()=>{kE.delete(s),--r===0&&t(),n!==Es&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,kE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of kE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Aie,"broadcastWithAcknowledgement");function Oie(e){e.postMessage({type:Bx,workers:Yx()})}a(Oie,"sendThreadInfo");function Yx(){let e=Date.now();return Mi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(Yx,"getChildWorkerInfo");function bie(e,t){e.resources=t,e.resources.updated=Date.now()}a(bie,"recordResourceReport");var bA;function yie(e){bA=e}a(yie,"setMonitorListener");var Nie=1e3,Dx=!1;function Iie(){Dx||(Dx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}bA&&bA()},Nie).unref())}a(Iie,"startMonitoring");var wie=1e3;if(Es){VE(Es);for(let e=0,t=Ys.addPorts.length;e<t;e++){let r=Ys.addPorts[e];r.threadId=Ys.addThreadIds[e],VE(r)}setInterval(()=>{let e=process.memoryUsage();Es.postMessage({type:vx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},wie).unref(),RA=a(()=>new Promise((e,t)=>{Es.on("message",r),Es.postMessage({type:Ux});function r(n){n.type===Bx&&(Es.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else RA=Yx;Pi.exports.getThreadInfo=RA;function VE(e,t){Tn.push(e),e.on("message",r=>{if(r.type===Hx)r.port.threadId=r.threadId,VE(r.port);else if(r.type===die){let n=kE.get(r.id);n&&n()}else{for(let s of Vx)s(r,e);let n=OA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ks.error(i)}}}).on("close",()=>{Tn.splice(Tn.indexOf(e),1)}).on("exit",()=>{Tn.splice(Tn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(VE,"addPort");if(yA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await oie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Lx(s,o.name));try{for await(let{filename:o}of iie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await wA(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");Pi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Es.on("message",async e=>{let{type:t}=e;t===Dl.ITC_EVENT_TYPES.SHUTDOWN&&(Pi.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ks.warn("Thread did not voluntarily terminate",tie),process.exit(0)},NA).unref())})});var LC={};Fe(LC,{AUDIT_STORE_OPTIONS:()=>pf,createAuditEntry:()=>m_,openAuditStore:()=>WE,readAuditEntry:()=>Ut,setAuditRetention:()=>Die,transactionKeyEncoder:()=>eG});function WE(e){let t=e.auditStore=e.openDB(jx.AUDIT_STORE_NAME,pf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=$E){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-CA})){if((_[0]&15)===MA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Cie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,CA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,KE.getWorkerIndex)()===(0,KE.getWorkerCount)()-1&&s($E),t}function Die(e,t=$E){CA=e,$E=t}function m_(e,t,r,n,s,i,o){let c=tG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?ec.setFloat64(0,n):gn.set(hm),u=9),E(0),E(t),d(r),ec.setFloat64(u,e),u+=8,s?d(s):gn[u++]=0,gn[n?8:0]=c;let l=gn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,tc.writeKey)(f,gn,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",f),u=h+1,gn[h]=0):(gn.copyWithin(h+2,h+1,u),ec.setUint16(h,p|32768),u++):gn[h]=p}function E(f){f<128?gn[u++]=f:f<16384?(ec.setUint16(u,f|32768),u+=2):f<1056964608?(ec.setUint32(u,f|3221225472),u+=4):(gn[u]=255,ec.setUint32(u+1,f),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new PA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:tG[n&7],tableId:i,get recordId(){return Jx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Jx(e,l,d):void 0},getValue(E,f,h){if(n&DA||n&LA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&LA&&h)return vA(E.getEntry(this.recordId),h,E)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function Jx(e,t,r){let n=e.subarray(t,r);return(0,tc.readKey)(n,0,r-t)}var tc,YE,jx,Xx,KE,Zx,UA,gn,ec,eG,pf,CA,Cie,$E,DA,LA,Kx,MA,Wx,Qx,zx,tG,PA,ti=Re(()=>{tc=require("ordered-binary"),YE=B(Z()),jx=B(ft()),Xx=B(P()),KE=B(je()),Zx=B(z());Cc();UA=B($());QE();(0,YE.initSync)();gn=Buffer.alloc(1024),ec=new DataView(gn.buffer,gn.byteOffset,1024),eG={writeKey(e,t,r){return e===wc?(t.set(wc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,tc.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,tc.readKey)(e,t,r)}},pf={encoding:"binary",keyEncoder:eG},CA=(0,Zx.convertToMS)((0,YE.get)(Xx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Cie=1e3,$E=1e4;a(WE,"openAuditStore");a(Die,"setAuditRetention");DA=16,LA=32,Kx=1,MA=2,Wx=3,Qx=4,zx=5,tG={put:Kx|DA,[Kx]:"put",delete:MA,[MA]:"delete",message:Wx|DA,[Wx]:"message",invalidate:Qx,[Qx]:"invalidate",patch:zx|LA,[zx]:"patch"};a(m_,"createAuditEntry");a(Ut,"readAuditEntry");PA=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(Jx,"readKeySafely")});var BA={};Fe(BA,{add:()=>zE,applyReverse:()=>rG,getRecordAtTime:()=>vA,rebuildUpdateBefore:()=>JE});function zE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function JE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,zE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function rG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Lie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=nG}}function vA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":rG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===nG&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var Lie,nG,QE=Re(()=>{ti();a(zE,"add");zE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};Lie={add:zE};a(JE,"rebuildUpdateBefore");a(rG,"applyReverse");nG={};a(vA,"getRecordAtTime")});function Zr(e){return e[Nt]||(e[Nt]=Object.create(null))}function th(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(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 Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be a number, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Zr(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 Rn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[Nt];if(l&&c in l){let E=l[c];if(E?.__op__){let f=this[de]?.[c];return E.update(f)}return E}let d=this[de]?.[c];if(d&&typeof d=="object"){let E=iG(d,o);if(E)return l||(l=this[Nt]=Object.create(null)),l[c]=E}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Nt];return u?.[o]!==void 0?u[o]:this[de]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Rn.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[Nt],c;for(let _ in o){c||(c=Object.assign({},this[de]));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[de])),Object.assign(c,this)),c||this[de]}),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 iG(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=s}},th(r,t)),new r(e)):new jE(e);case Array:let n=new ZE(e.length);n[de]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=iG(o,t?.elements)),n[s]=o}return n;default:return e}}function fd(e){let t=e[Nt],r;for(let s in t){r||(r=Object.assign({},e[de]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=fd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Po(e,t=e[Nt]){let r;if(sG.call(e,de)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Po(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[de]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=BA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):sG.call(e,de)?e[de]:e}function XE(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[de]===s){if(XE(i))return!0}else return!0}}else{let r=e[Nt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[de]===i){if(XE(s))return!0}else return!0}else return!0}}return!1}var Rn,Nt,jE,sG,Mo,ZE,eh,Ed=Re(()=>{Nn();Rn=B(ne());QE();Nt=Symbol("own-data");a(Zr,"getChanges");a(th,"assignTrackedAccessors");a(iG,"trackObject");jE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=t}};th(jE,{});a(fd,"collapseData");sG=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(XE,"hasChanges");Mo=Symbol.for("has-array-changes"),ZE=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};ZE.prototype.constructor=Array;eh=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var qp={};Fe(qp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>Fn,RECORD_PROPERTY:()=>de,Resource:()=>Vt,snake_case:()=>Pie,transformForSelect:()=>nh});function Pie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function oG(e,t){if(Ll=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Ll=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new xA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Ll=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=s,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let f of s){if(typeof f=="object"&&f)break;c.push(f)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return Ze(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new rh(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new rh(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new uG.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function HA(e,t,r){let n=e[de];if(n){let s=e[Nt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function nh(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):HA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(HA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(HA(u,r,n)),d;for(let E of e){let f=l(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=nh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var aG,cG,uG,ye,Le,Fn,de,Mie,Vt,rh,Ll,xA,Nn=Re(()=>{aG=require("crypto");Ac();cG=require("../index"),uG=B(ne());Ed();ro();jf();ye=Symbol.for("context"),Le=Symbol.for("primary-key"),Fn=Symbol("is-collection"),de=Symbol("stored-record"),Mie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Vt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=en(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=nh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[Fn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,aG.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),n||(n={}),Ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=nh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[Fn])return this.constructor.create(this[Le],t,this[ye]);tn(this,"post")}static isCollection(t){return t?.[Fn]}static coerceId(t){return t}static parseQuery(t){return Jf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Mie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:oG(t,this),isCollection:Ll}}let i=oG(t,this);return Ll?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Le]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Fn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Le]}getContext(){return this[ye]}};Vt.prototype[ye]=null;(0,cG._assignPackageExport)("Resource",Vt);a(Pie,"snake_case");rh=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(oG,"pathToId");xA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(HA,"selectFromObject");a(nh,"transformForSelect")});function dG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=_G,Uie(e.primaryStore,e.auditStore)):(c=lG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{fG(lG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Na(t);let l=new qA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function fG(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Ut(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Na(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,GA.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,GA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Uie(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u=_G[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),fG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var GA,lG,_G,qA,EG=Re(()=>{GA=B($());Ac();Wu();ti();lG=Object.create(null),_G=Object.create(null);a(dG,"addSubscription");qA=class extends yn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(fG,"notifyFromTransactionData");a(Uie,"listenToCommits")});var TR={};Fe(TR,{coerceType:()=>sh,makeTable:()=>ah,setServerUtilities:()=>Vie,updateResource:()=>ih});function ah(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=Sm(i,n,u),R=0,b,C,H={},v=Promise.resolve(),F,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(F=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(H=K);let J,j=[],ae=[],ce=1,ge=2,Ge={},Ne={},ve=864e5,zl,Jl,zs,aO=!1,bh,yh,Sq=i.getRange({start:!1,end:!1}).constructor,Tq=10,gq=6;h&&lO();class ze extends Vt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=F;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),C=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(L=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[L]&&(!U[L].reliesOnPrototype||U.prototype[L])),N.length>0)if(N.length===1){let U=N[0];return(k,D,x)=>{if(k?.source!==U)return U[L](D,x,k)}}else return(U,k,D)=>{let x=[];for(let G of N){if(U?.source===G)break;x.push(G[L](k,D,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,U,k)=>{if(!N?.source)return y[L](U,k,N)}},"getApplyToCanonicalSource");return Ge={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ne={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let L=!1,N=a(async(U,k)=>{let D=U.value,x=U.table?ot[c][U.table]:ze;if(c===Vn.SYSTEM_SCHEMA_NAME&&(U.table===Vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!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 G=await x.getResource(U.id,k,rc);switch(U.type){case"put":return G._writeUpdate(D,!0,rc);case"patch":return G._writeUpdate(D,!1,rc);case"delete":return G._writeDelete(rc);case"publish":return G._writePublish(D,rc);case"invalidate":return G.invalidate(rc);default:nt.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let k=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,D=U&&k&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){nt.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{N(G,x);continue}if(G.type==="end_txn")continue;let me=Ze(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ue){throw ue.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ue}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ue of G.attributes)te.find(qe=>qe.name===ue.name)||(te.push(ue),Pe=!0);Pe&&(Et({table:s,database:c,attributes:te,origin:"cluster"}),xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(te=>{x.resolve=te})):N(G,G)});L&&(await me,xl.signalUserChange(new Gl.UserEventMsg(process.pid))),G.onCommit&&(me?.then?me.then(G.onCommit):G.onCommit())}catch(se){nt.error("error in subscription handler",se)}}}catch(U){nt.error(U)}})(),this}static getResource(m,A,w){let y=super.getResource(m,A,w);if(m!=null){ac(m);try{if(y.hasOwnProperty(de))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!w?.async||i.cache?.get(m),L=On(A),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Nh(m,A,{transaction:N},O,U=>{if(U?ih(y,U):y[de]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let k=Ih(m,U,A,y);if(k)return L?.disregardReadTxn(),y[FA]=!0,VA(k,D=>(ih(y,D),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=Ih(this[Le],this[Lr],this[ye]);if(m)return this[FA]=!0,VA(m,A=>{this[Lr]=A,this[de]=A.value,this[Bl]=A.version})}static setTTLExpiration(m){if(typeof m=="number")E=m*1e3,f||(f=0);else if(m&&typeof m=="object")E=m.expiration*1e3,f=(m.eviction||0)*1e3,ve=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");ve=ve||(E+f)/4,Ch()}static enableAuditing(m=!0){h=m,m&&lO(),ze.audit=m}static coerceId(m){return m===""?null:sh(m,H)}static async dropTable(){if(delete ot[c][s],c===o){for(let m of S)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Fn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let A=ze.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let w=Xl(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,O=A?.select;if(y?.length>0||aO&&O){if(A||(A={}),O){let L=y?.length>0&&kA(y,"read");A.select=O.map(N=>{let U=N.name||N;if(!L||L[U]){let k=zs[U]?.definition?.tableClass;if(k){if(N.name||(N={name:N}),!k.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(L=>L.read&&!zs[L.attribute_name]).map(L=>L.attribute_name);return A}else return!0}}allowUpdate(m,A){let w=Xl(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let O=kA(y,"update");for(let L in A)if(!O[L])return!1;for(let L of y){let N=L.attribute_name;!L.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[Fn]){let w=Xl(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let O=kA(y,"insert");for(let L in A)if(!O[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Xl(m)?.delete}update(m,A){if(!On(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[de]={},this[Nt]=m):(y=this[Nt],y&&(m=Object.assign(y,m)),this[Nt]=y=m)),this._writeUpdate(this[Nt],A),this}addTo(m,A){if(typeof A=="number"||typeof A=="bigint")this[Ml]===mG?this.set(m,(+this.getProperty(m)||0)+A):(this[Ml]||this.update(),this.set(m,new eh(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Lr]}invalidate(m){let A=this[ye],w=this[Le];ac(w),On(this[ye]).addWrite({key:w,store:i,invalidated:!0,entry:this[Lr],nodeName:this[ye]?.nodeName,before:Ge.invalidate?.bind(this,A,w),beforeIntermediate:Ne.invalidate?.bind(this,A,w),commit:(O,L)=>{if(L?.version>O)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(w,N,this[Lr],O,Pl,h,this[ye],0,"invalidate")}})}static evict(m,A,w){let y=this.Source,O;if(!((C||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==w))){if(C){if(i.hasLock(m,O.version))return;let L;for(let N in r)L||(L={}),L[N]=A[N];if(L)return T(m,L,O,w,Ul,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{jl(m,A,null)}),h?T(m,null,O,w,Ul,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,AG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,w){let y=this[ye],O=On(y),L=this[Le];ac(L);let N=this[Lr];this[Ml]=A?mG:qie;let U={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:k=>{m||(m=this[Nt]),A||m&&XE(this[Nt]===m?this:m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),M&&(m[M.name]=M.type==="Date"?new Date(k):M.type==="String"?new Date(k).toISOString():k),A&&(t&&m[t]!==L&&(m[t]=L),F&&(N?.value?m[F.name]=N?.value[F.name]:m[F.name]=F.type==="Date"?new Date(k):F.type==="String"?new Date(k).toISOString():k),m=Po(m))):O.removeWrite(U)},before:A?Ge.put?()=>Ge.put(y,L,m):null:Ge.patch?()=>Ge.patch(y,L,m):Ge.put?()=>Ge.put(y,L,Po(this)):null,beforeIntermediate:A?Ne.put?()=>Ne.put(y,L,m):null:Ne.patch?()=>Ne.patch(y,L,m):Ne.put?()=>Ne.put(y,L,Po(this)):null,commit:(k,D,x)=>{if(x){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Lr]=D,D?.value?.[de])throw new Error("Can not assign a record to a record, check for circular references");A||(this[de]=D?.value??null)}this[Nt]=void 0,this[Bl]=k;let G=D?.value,se=m;if(this[Ml]=0,D?.version>=k)if(h){let ue=D.localTime,qe=D.version;for(;se&&(ue>k||qe>=k&&ue>0);){let re=u.get(ue);if(!re)break;let X=Ut(re);if(qe=X.version,qe>k){if(X.type==="patch"){let pe=X.getValue(i);se=JE(se,pe)}else if(X.type==="put"||X.type==="delete")return}else if(qe===k)return;ue=X.previousLocalTime}}else{if(A)return;se=JE(se,G)}let me;if(A?me=se:(this[de]=G,me=A?se:Po(this,se)),this[de]=me,me?.[de])throw new Error("Can not assign a record to a record, check for circular references");let te;A||(te=m),jl(L,G,me);let Pe=A?"put":"patch";T(L,me,D,k,0,h,y,y.expiresAt||(E?E+Date.now():0),Pe,!1,te)}};O.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Fn]){for await(let A of this.search(m))(await ze.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let A=On(this[ye]),w=this[Le];ac(w);let y=this[ye];return A.addWrite({key:w,store:i,resource:this,nodeName:y?.nodeName,before:Ge.delete?.bind(this,y,w),beforeIntermediate:Ne.delete?.bind(this,y,w),commit:(O,L,N)=>{let U=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),ih(this,L)),!(L?.version>O)&&(jl(this[Le],U),nt.trace("Write delete entry",w,O),h||p?(T(w,null,this[Lr],O,0,h,this[ye],0,"delete"),h||Ch()):i.remove(this[Le]))}}),!0}search(m){let A=this[ye],w=On(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(y=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(y));let O,L={};function N(X,pe){let Be;switch(pe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}let $n=Be&&{},Js;for(let Ke of X){if(Ke.conditions){Ke.conditions=N(Ke.conditions,Ke.operator);continue}let Ft=Ke[0]??Ke.attribute,on=Ft==null?H:Gs(S,Ft);if(on){if(Be){let Yn=xn(Ft),kt=$n[Yn];kt?(kt.push(Ke),Js=!0):$n[Yn]=[Ke]}(on.type||Yg[Ke.comparator])&&(Ke[1]===void 0?Ke.value=k(Ke.value,on):Ke[1]=k(Ke[1],on))}else if(Ft!=null)throw(0,rn.handleHDBError)(new Error,`${Ft} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Js)for(let Ke in $n){let Ft=$n[Ke],on=Ft.length;if(on>1)for(let Yn=0;Yn<on;Yn++){let kt=Ft[Yn];if(kt.comparator==="ge"||kt.comparator==="greater_than_equal")for(let js=0;js<on;js++){let qo=Ft[js];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(kt.comparator="between",kt.value=[kt.value,qo.value],X.splice(X.indexOf(qo),1))}if(kt.comparator==="equals"||!kt.comparator){for(let js=0;js<on;js++)if(js!==Yn){let qo=Ft[js];X.splice(X.indexOf(qo),1)}break}}}return X}a(N,"prepareConditions");function U(X,pe){if(m.enforceExecutionOrder)return X;for(let Be of X)Be.conditions&&(Be.conditions=U(Be.conditions,Be.operator));return X.length>1&&pe!=="or"?(0,RG.sortBy)(X,zf(ze)):X}a(U,"orderConditions");function k(X,pe){return Array.isArray(X)?X.map(Be=>sh(Be,pe)):sh(X,pe)}a(k,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let x=typeof m.sort=="object"&&m.sort,G;if(x&&D!=="or"){let X=x.attribute;if(O=y.find(pe=>xn(pe.attribute)===xn(X)),!O){let pe=Gs(S,X);if(!pe)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(pe.indexed)O={attribute:X,comparator:"sort"},y.push(O);else if(y.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}O&&(O.descending=!!x.descending)}y=U(y,D),x&&(O&&y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:D,postOrdering:G,selectApplied:!!se};let me=w.useReadTxn(),te=Kg(y,D,ze,me,m,A,(X,pe)=>cO(X,se,A,me,pe),L),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ue=ze.transformEntryForSelect(se,A,me,L,Pe,!0),qe=ze.transformToOrderedSelect(te,se,G,me,A,ue);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(qe=re(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(se){let X=[];for(let pe of se)pe==="*"?X.push(...S.map(Be=>Be.name)):X.push(pe.name||pe);return X}return S.map(X=>X.name)},qe}static transformToOrderedSelect(m,A,w,y,O,L){let N=new Sq;if(w){m=cO(m,A,y,O,null);let U;N.iterate=function(){let D,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,me,te,Pe=!0;function ue(re){let X=re.next&&ue(re.next),pe=re.descending;return(Be,$n)=>{let Js=wh(Be,re.attribute,y),Ke=wh($n,re.attribute,y),Ft=pe?(0,Bo.compareKeys)(Ke,Js):(0,Bo.compareKeys)(Js,Ke);return Ft===0?X?.(Be,$n)||0:Ft}}a(ue,"createComparator");let qe=ue(w);return{async next(){let re;if(D)if(re=D.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await L.call(this,re.value)};U=[],me&&U.push(me);do if(re=await x.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let pe=wh(X,se,y);if(Pe)Pe=!1,te=pe;else if(pe!==te){te=pe,me=X;break}}U.push(X)}while(!0);return w.isGrouped,U.sort(qe),D=U[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let k=a(D=>{if(typeof A=="object"&&Array.isArray(D.attribute))for(let x=0;x<A.length;x++){let G=A[x],se;if(G.name===D.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=D.attribute.slice(1),se.descending=D.descending}else G===D.attribute[0]&&(A[x]=se={name:G,sort:{attribute:D.attribute.slice(1),descending:D.descending}})}D.next&&k(D.next)},"applySortingOnSelect");k(w)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(L);return N}static transformEntryForSelect(m,A,w,y,O,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let D=a(x=>(A?.transaction?.stale&&(A.transaction.stale=!1),x?.key??x),"transform");return m===t?D:m.asArray?x=>[D(x)]:x=>({[t]:D(x)})}let N;O&&C&&!m?.every(D=>{let x;return typeof D=="object"?x=D.name:x=D,r[x]||x===t})&&(N=!0);let U,k=a(function(D){let x;if(A?.transaction?.stale&&(A.transaction.stale=!1),D!=null){if(bh=D,x=D.value||D.deref?.(),!x&&(D.key===void 0||D.deref)){if(D=Nh(D.key??D,A,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(k.bind(this));x=D?.value}if(N&&(D.metadataFlags&(Pl|Ul)||D.expiresAt&&D.expiresAt<Date.now())){let G=Ih(D.key??D,D,A);if(G?.then)return G.then(k)}}if(x==null)return L?Uo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ue;typeof te=="object"?ue=te.name:ue=te;let qe=zs?.[ue],re;if(qe){let X=y?.[ue];if(X)if(X.hasMappings){let Be=qe.from?x[qe.from]:xn(D.key);re=X.get(Be),re||(re=[])}else re=X.fromRecord?.(x);else re=qe(x,A,D);let pe=a(Be=>{if(Be&&typeof Be=="object"){let $n=qe.definition?.tableClass||ze;U||(U={});let Js=U[ue]||(U[ue]=$n.transformEntryForSelect(ue===te?null:te.select||(Array.isArray(te)?te:null),A,w,X,O));if(Array.isArray(Be)){let Ke=[],Ft=$n.transformToOrderedSelect(Be,te.select,typeof te.sort=="object"&&te.sort,A,w,Js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(kt=>{for(;!kt.done;){if(kt?.then)return kt.then(on);Ke.push(kt.value),kt=Ft.next()}Pe(Ke,ue)},"nextValue"),Yn=on(Ft.next());Yn&&(G||(G=[]),G.push(Yn));return}else if(Be=Js.call(this,Be),Be?.then){G||(G=[]),G.push(Be.then(Ke=>Pe(Ke,ue)));return}}Pe(Be,ue)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(pe))):pe(re);return}else re=x[ue],re&&typeof re=="object"&&ue!==te&&(re=ze.transformEntryForSelect(te.select||te,A,w,null)({value:re}));Pe(re,ue)},"selectAttribute"),me;if(typeof m=="string")se(m,te=>{me=te});else if(Array.isArray(m))if(m.asArray)me=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=x:se(te,ue=>me[Pe]=ue)});else{me={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ue in x)me[ue]=x[ue];else se(Pe,(ue,qe)=>{ue===void 0&&te&&(ue=null),me[qe]=ue})}else throw new rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>me):me}return x},"transform");return k}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||Et({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,w=dG(ze,this[Le]??null,function(N,U,k,D){try{let x=U.getValue?.(i,A);if(!x&&U.type==="patch"&&A){let G=i.getEntry(N);G?.version===U.version?x=G.value:x=U.getValue?.(i,!0,k),U.type="put"}this.send({id:N,timestamp:k,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){nt.error(x)}},m.startTime||0,m);this[Fn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let y=this[Le],O=m.previousCount;O>1e3&&(O=1e3);let L=m.startTime;if(this[Fn]){if(L){if(O)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:L,exclusiveStart:!0})){let k=Ut(U);if(k.tableId!==n)continue;let D=k.recordId;if(y==null||TG(y,D)){let x=k.getValue(i,A,N);w.send({id:D,timestamp:N,value:x,version:k.version,type:k.type})}w.startTime=N}}else if(O){let N=[];for(let{key:U,value:k}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ut(k);if(D.tableId!==n)continue;let x=D.recordId;if(y==null||TG(y,x)){let G=D.getValue(i,A,U);if(N.push({id:x,timestamp:U,value:G,version:D.version,type:D.type}),--O<=0)break}}catch(D){nt.error("Error getting history entry",U,D)}for(let U=N.length;U>0;)w.send(N[--U]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:k,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&w.send({id:N,timestamp:D,value:U,version:k,type:"put"})}else{O&&!L&&(L=0);let N=this[Lr]?.localTime;if(N===pm&&(i.cache?.delete(y),this[Lr]=i.getEntry(y),nt.trace("re-retrieved record",N,this[Lr]?.localTime),N=this[Lr]?.localTime),nt.trace("Subscription from",L,"from",y,N),L<N){let U=[],k=N;do{let D=u.get(k);if(D){m.omitCurrent=!0;let x=Ut(D),G=x.getValue(i,A,k);A&&(x.type="put"),U.push({id:y,value:G,timestamp:k,...x}),k=x.previousLocalTime}else break;O&&O--}while(k>L&&O!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this[de],version:this[Bl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[Ml])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let w=On(this[ye]),y=this[Le]||null;ac(y);let O=this[ye];w.addWrite({key:y,store:i,entry:this[Lr],nodeName:O?.nodeName,validate:()=>{O?.source||(w.checkOverloaded(),this.validate(m))},before:Ge.publish?.bind(this,O,y,m),beforeIntermediate:Ne.publish?.bind(this,O,y,m),commit:(L,N,U)=>{N===void 0&&p&&!h&&Ch(),T(y,N?.value??null,N,N?.version||L,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let w,y=a((O,L,N)=>{if(L.type&&O!=null)if(A&&O.__op__&&(O=O.value),L.properties){typeof O!="object"&&(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let U=L.properties;for(let k=0,D=U.length;k<D;k++){let x=U[k],G=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(L.sealed&&O!=null&&typeof O=="object")for(let k in O)U.find(D=>D.name===k)||(w||(w=[])).push(`Property ${k} is not allowed within object in property ${N}`)}else switch(L.type){case"Int":(typeof O!="number"||O>>0!==O)&&(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(L.elements)for(let U=0,k=O.length;U<k;U++){let D=O[U],x=y(D,L.elements,N+"[*]");x&&(O[U]=x)}}else(w||(w=[])).push(`Value ${kn(O)} in property ${N} must be a Buffer or Uint8Array`);break}L.nullable===!1&&O==null&&(w||(w=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,L=S.length;O<L;O++){let N=S[O];if(!N.relationship&&(!A||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let O in m)S.find(L=>L.name===O)||(w||(w=[])).push(`Property ${O} is not allowed`);if(w)throw new rn.ClientError(w.join(". "))}getUpdatedTime(){return this[Bl]}wasLoadedFromSource(){return C?!!this[FA]:void 0}static async addAttributes(m){let A=S.slice(0);for(let w of m){if(!w.name)throw new rn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(w)}return Et({table:s,database:c,schemaDefined:_,attributes:A}),ze.indexingOperation}static async removeAttributes(m){let A=S.filter(w=>!m.includes(w.name));return Et({table:s,database:c,schemaDefined:_,attributes:A}),ze.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,w=5e3,y=1e3,O;A>w&&!m?.exactCount&&(O=y);let L=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&L++;if(O){let N=L;L=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&L++;let U=O*2,k=(L+N)/U,D=Math.pow((L-N+1)/O/2,2)+k*(1-k)/U,x=Math.max(Math.sqrt(D)*A,1),G=Math.round(k*A),se=Math.max(G-1.96*x,0),me=Math.min(G+1.96*x,A),te=Math.pow(10,Math.round(Math.log10(x)));return te>G&&(te=te/10),L=Math.round(G/te)*te,{recordCount:L,estimatedRange:[Math.round(se),Math.round(me)]}}return{recordCount:L}}static updatedAttributes(){zs=this.propertyResolvers={$id:(m,A,w)=>({value:w.key}),$updatedtime:(m,A,w)=>w.version,$record:(m,A,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),aO=!0,A.to)m.elements?.definition?(zs[m.name]=m.resolve=(w,y,O)=>{let L=w[A.from?A.from:t],N=m.elements.definition.tableClass;return O?Ha({attribute:A.to,value:L},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:L}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let w=m.definition||m.elements?.definition;w?(zs[m.name]=m.resolve=(y,O,L)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let U,k=N.map(D=>{let x=L?w.tableClass.primaryStore.getEntry(D,{transaction:On(O).getReadTxn()}):w.tableClass.get(D,O);return x?.then&&(U=!0),x});return A.filterMissing?U?Promise.all(k).then(D=>D.filter(gG)):k.filter(gG):U?Promise.all(k):k}return L?w.tableClass.primaryStore.getEntry(N,{transaction:On(O).getReadTxn()}):w.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let L=O.map(N=>N[Le]||N[w.tableClass.primaryKey]);y[A.from]=L}else{let L=O[Le]||O[w.tableClass.primaryKey];y[A.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}th(this,this)}static async deleteHistory(m=0){let A;for(let{key:w,value:y}of u.getRange({start:0,end:m}))await vl(),Ut(y).tableId===n&&(A=u.remove(w));await A}static async*getHistory(m=0,A=1/0){for(let{key:w,value:y}of u.getRange({start:m,end:A})){await vl();let O=Ut(y);O.tableId===n&&(yield{id:O.recordId,localTime:w,version:O.version,type:O.type,value:O.getValue(i,!0,w),user:O.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return A;let y=w.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await vl();let L=u.get(y);if(L){let N=Ut(L);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){J?.remove()}}ze.updatedAttributes();let Rq=ze.prototype;return Rq[Gie]=!0,E&&ze.setTTLExpiration(E/1e3),Q&&Aq(),ze;function jl(K,m,A){let w;for(let y in r){let O=r[y],L=O.isIndexing,N=A?.[y],U=m?.[y];if(N===U&&!L)continue;w=!0;let k=O.indexNulls,D=(0,Hl.getIndexedValues)(N,k),x=(0,Hl.getIndexedValues)(U,k);if(x?.length>0){let G=new Set(x);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||D.length>0)&&hG){let se=x.concat(D).map(me=>({key:me,value:K}));O.prefetch(se,SG)}for(let se=0,me=x.length;se<me;se++)O.remove(x[se],K)}else D?.length>0&&hG&&O.prefetch(D.map(G=>({key:G,value:K})),SG);if(D)for(let G=0,se=D.length;G<se;G++)O.put(D[G],K)}return w}a(jl,"updateIndices");function ac(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>pG)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Bo.writeKey)(K,Fie,0)>pG)throw new Error("Primary key size is too large: "+K.length);return!0}a(ac,"checkValidId");function Nh(K,m,A,w,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let L=i.getEntry(K,A);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,K)},"whenPrefetched");return w?O():ce>0?(ce--,O()):new Promise((L,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),k()})):(j.push(K),ae.push(k),j.length>gq&&(ce--,U()));function U(){if(j.length>0){let D=ae;i.prefetch(j,()=>{ce===-1?U():ce++;for(let x of D)x()}),j=[],ae=[],ge>2&&ge--}else ce=ge,ge<Tq&&ge++}a(U,"prefetch");function k(){try{L(O())}catch(D){N(D)}}a(k,"load")})}a(Nh,"loadLocalRecord");function Xl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return kie;let A=m[c],w,y=A?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(Xl,"getTablePermissions");function Ih(K,m,A,w){if(C){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Pl|Ul)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Wr(!y,"cache-hit",s)),y){let O=uO(K,m,A).then(L=>(L?.value?.[de]&&nt.error("Can not assign a record with a record property"),A&&(L?.version>(A.lastModified||0)&&(A.lastModified=L.version),A.lastRefreshed=Date.now()),L));if(A?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,K)){if(O.catch(L=>nt.warn(L)),A?.onlyIfCached&&!w.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return O}}}a(Ih,"ensureLoadedFromSource");function On(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new to,m.lmdbDb=i,m;m=A}while(!0)}else return new _d}a(On,"txnForContext");function wh(K,m,A){if(!K)return;bh=K;let w=K.value||K.deref?.()||(bh=i.getEntry(K.key))?.value;if(typeof m=="object"){let O=zs,L=w;for(let N=0,U=m.length;N<U;N++){let k=m[N],D=O?.[k];L=D&&L?D(L,A,!0)?.value:L?.[k],O=D?.definition?.tableClass?.propertyResolvers}return L}let y=zs[m];return y?y(w,A):w[m]}a(wh,"getAttributeValue");function cO(K,m,A,w,y){let O=y?.length,L={transaction:w,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(k,D){let x=k?.value;if(!x)return Uo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,k))return Uo.SKIP;return D!==void 0&&(k.key=D),k}if(a(U,"processEntry"),O>0||!K.hasEntries){let k=K.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return O>0?U(D):D;if(D==null)return Uo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(D))return Uo.SKIP;N||(N=[]),N.push(x)}}return Nh(D,A,L,!1,U)});return Array.isArray(K)&&(k=k.filter(D=>D!==Uo.SKIP)),k.hasEntries=!0,k}return K}a(cO,"transformToEntries");async function uO(K,m,A){let w=m?.metadataFlags,y=m?.version,O,L;if(!i.attemptLock(K,y,()=>{clearTimeout(L);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(Pl|Ul)?O(uO(K,i.getEntry(K),A)):O(D)}))return new Promise(D=>{O=D,L=setTimeout(()=>{i.unlock(K,y)},xie)});let N=m?.value,U={requestContext:A,replacingRecord:N,replacingVersion:y,source:null,resourceCache:A?.resourceCache},k=A?.responseHeaders;return new Promise((D,x)=>{let G;VA(Ze(U,async se=>{let me=performance.now(),te,Pe,ue;try{for(let pe of ze.sources)if(pe.get&&(!pe.get.reliesOnPrototype||pe.prototype.get)&&(U.source=pe,te=await pe.get(K,U),te))break;ue=w&Pl;let re=U.lastModified||ue&&y;Pe=ue||re>y||!N,re||(re=(0,Hl.getNextMonotonicTime)());let X=performance.now()-me;if(pr(X,"cache-resolution",s),k&&Eg(k,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,E&&!U.expiresAt&&(U.expiresAt=Date.now()+E),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}G=!0,D({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(D({version:y,value:N}),nt.trace(re.message,"(returned stale record)")):x(re),U.transaction.abort();return}if(A?.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let pe=jl(K,N,te);te?(Ne.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ue)):(Ne.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ue):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&nt.error("Error committing cache update",se)})})}a(uO,"getFromSource");function Ch(){if(ve!==zl&&(zl=ve,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(Jl&&clearTimeout(Jl),!ve)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/ve)*ve+K.getTime(),A=a(w=>{nt.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Jl=setTimeout(()=>v=v.then(async()=>{if(A(Math.max(w+ve,Date.now())),i.rootStore.status!=="open"){clearTimeout(Jl);return}let y=50,O=new Array(y),L=0;nt.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:k,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;k===null&&!h&&D+Hie<Date.now()?G=i.remove(U,D):x&&x+f<Date.now()&&(G=ze.evict(U,k,D),N++),G&&(await O[L],O[L]=G.catch(se=>{nt.error("Cleanup error",se)}),++L>=y&&(L=0)),await vl()}nt.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){nt.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Ch,"scheduleCleanup");function lO(){J=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(lO,"addDeleteRemoval");function Aq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!yh){yh=!0;try{let K=Q.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(A)){let y=i.getEntry(w);y?.value?y.value[K]<Date.now()&&ze.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(A,w))}await vl()}}catch(K){nt.error("Error in evicting old records",K)}finally{yh=!1}}},Bie).unref()}a(Aq,"runRecordExpirationEviction")}function kA(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function SG(){}function Vie(e){AG=e}function sh(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:($ie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,oh.autoCast)(e):e}function TG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function VA(e,t,r){return e?.then?e.then(t,r):t(e)}function ih(e,t){e[Lr]=t,e[de]=t?.value??null,e[Bl]=t?.version}function gG(e){return e!=null}function kn(e){try{return JSON.stringify(e)}catch{return e}}var Vn,Uo,Hl,RG,ql,rn,xl,Gl,nt,Bo,vo,oh,vie,AG,Bie,Hie,hG,xie,Bl,Gie,Lr,Ml,mG,qie,FA,rc,Pl,Ul,Fie,pG,kie,uTe,$ie,vl,_E=Re(()=>{Vn=B(P()),Uo=require("lmdb"),Hl=B(vr()),RG=require("lodash");Nn();aS();ql=B(Z());EG();rn=B(ne()),xl=B(bs()),Gl=B(Mn());Ae();jf();nt=B($());Ed();ro();Bo=require("ordered-binary"),vo=B(je());ti();oh=B(z());Cc();ws();QE();Qu();vie=new Uint8Array(9);vie[8]=192;Bie=6e4,Hie=864e5;ql.initSync();hG=ql.get(Vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),xie=1e4,Bl=Symbol.for("version"),Gie=Symbol.for("incremental-update"),Lr=Symbol("entry"),Ml=Symbol("is-saving"),mG=1,qie=2,FA=Symbol("loaded-from-source"),rc={isNotification:!0,ensureLoaded:!1},Pl=1,Ul=8,Fie=Buffer.allocUnsafeSlow(8192),pG=1978,kie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},uTe=(0,oh.convertToMS)(ql.get(Vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ah,"makeTable");a(kA,"attributesAsObject");a(SG,"noop");a(Vie,"setServerUtilities");$ie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(sh,"coerceType");a(TG,"isDescendantId");vl=a(()=>new Promise(setImmediate),"rest");a(VA,"when");a(ih,"updateResource");a(gG,"exists");a(kn,"stringify")});var ke={};Fe(ke,{database:()=>nu,databases:()=>ot,dropDatabase:()=>dS,dropTableMeta:()=>zie,getDatabases:()=>hr,getDefaultCompression:()=>Sf,getTables:()=>Yie,onUpdatedTable:()=>XR,readMetaDb:()=>Fl,resetDatabases:()=>Fu,table:()=>Et,tables:()=>Br});function Yie(){return dh||hr(),Br||{}}function hr(){if(dh)return ot;dh=!0,ic=new Map;let e=(0,St.getHdbBasePath)()&&(0,st.join)((0,St.getHdbBasePath)(),Pt.DATABASES_DIR_NAME),t=(0,St.get)(Pt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,St.get)(Pt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,st.join)((0,St.getHdbBasePath)(),Pt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,st.basename)(r.name,".mdb");r.isFile()&&(0,st.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Fl((0,st.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,sc.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,sc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,st.join)((0,sc.getBaseSchemaPath)(),r.name),s=(0,st.join)((0,sc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,st.extname)(i.name).toLowerCase()===".mdb"){let o=(0,st.join)(s,i.name);Fl((0,st.join)(n,i.name),(0,st.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,st.extname)(o.name).toLowerCase()===".mdb"&&Fl((0,st.join)(s,o.name),(0,st.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,st.join)(c.path,(0,st.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Fl(u,o,r,null,!0)}}for(let r in ot){let n=ic.get(r);if(n){let s=ot[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete ot[r],r==="data"){for(let s in Br)delete Br[s];delete Br[Eh]}}return ic=null,ot}}function Fu(){dh=!1;for(let[,e]of Ui)e.needsDeletion=!0;hr();for(let[e,t]of Ui)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ui.delete(e));return ot}function Fl(e,t,r=KA,n,s){let i=new $A.default(e,!1);try{let o=Ui.get(e);o?o.needsDeletion=!1:(o=(0,uh.open)(i),Ui.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(ch.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,uh.open)(i),_.isLegacy=!0):_=WE(o));let l=NG(r),d=l[Eh],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[p,S]=f.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let T=E.get(p);T||E.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let j of p)if(j.is_hash_attribute||j.isPrimaryKey){S=j;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],R={},b=[],C,H,v=typeof S.audit=="boolean"?S.audit:(0,St.get)(Pt.CONFIG_PARAMS.LOGGING_AUDITLOG),F=S.trackDeletes,M=S.expiration,Q=S.eviction,J=S.sealed;if(T)R=T.indices,b=T.attributes,T.schemaVersion++;else{C=S.tableId,C?C>=(u.get(nc)||0)&&u.putSync(nc,C+1):(S.tableId=C=u.get(nc),C||(C=1),u.putSync(nc,C+1),u.putSync(S.key,S));let j=new Ho.default(!S.is_hash_attribute,S.is_hash_attribute);if(j.compression=S.compression,j.compression){let ae=(0,St.get)(Pt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||yG;j.compression.threshold=ae}H=p_(o.openDB(S.key,j)),H.rootStore=o,H.tableId=C}for(let j of p){j.attribute=j.name;try{if(!j.is_hash_attribute&&(j.indexed||j.attribute&&!j.name)){if(!R[j.name]){let ce=new Ho.default(!j.is_hash_attribute,j.is_hash_attribute);R[j.name]=o.openDB(j.key,ce),R[j.name].indexNulls=j.indexNulls}let ae=b.find(ce=>ce.name===j.name);ae?b.splice(b.indexOf(ae),1,j):b.push(j)}}catch(ae){An.error("Error trying to update attribute",j,b,R,ae)}}if(!T){T=IG(l,f,ah({primaryStore:H,auditStore:_,audit:v,sealed:J,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:F,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let j of WA)j(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function NG(e){let t=ot[e];if(t||(e==="data"?t=ot[e]=Br:e==="system"?Object.defineProperty(ot,"system",{value:t=Object.create(null),configurable:!0}):t=ot[e]=Object.create(null)),ic&&!ic.has(e)){let r=new Set;t[Eh]=r,ic.set(e,r)}return t}function IG(e,t,r){return e[t]=r,r}function nu({database:e,table:t}){e||(e=KA),hr();let r=NG(e),n=(0,st.join)((0,St.getHdbBasePath)(),Pt.DATABASES_DIR_NAME),s=(0,St.get)(Pt.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,St.get)(Pt.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,st.join)((0,St.getHdbBasePath)(),Pt.LEGACY_DATABASES_DIR_NAME));let o=(0,st.join)(n,(i?t:e)+".mdb"),c=Ui.get(o);if(!c){let u=new $A.default(o,!1);c=(0,uh.open)(u),Ui.set(o,c)}return c}async function dS(e){if(!ot[e])throw new Error("Schema does not exist");let t=ot[e];for(let r in t){let s=t[r].primaryStore.rootStore;Ui.delete(s.path),s.status==="open"&&(await s.close(),await fh.remove(s.path))}if(e==="data"){for(let r in Br)delete Br[r];delete Br[Eh]}delete ot[e]}function Et({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=KA);let d=nu({database:t,table:e}),E=ot[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let R=new Ho.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let b,C;if(f){if(h=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=d.auditStore;M||(M=WE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Sf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,St.get)(Pt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let Q=new Ho.default(!1,!0);Q.compression=p.compression;let J=e+"/",j=p_(d.openDB(J,Q));j.rootStore=d,T=d.dbisDb=d.openDB(ch.INTERNAL_DBIS_NAME,R),j.tableId=T.get(nc),j.tableId||(j.tableId=1),T.putSync(nc,j.tableId+1),p.tableId=j.tableId,f=IG(E,e,ah({primaryStore:j,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:j.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,b=!0,F(),T.put(J,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(ch.INTERNAL_DBIS_NAME,R)),f.dbisDB=T;let H=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[J,j]=M.toString().split("/");if(j===""&&(j=Q.name),j){if(J!==e)continue}else j=J;if(!i.find(ce=>ce.name===j)?.indexed&&Q.indexed&&!Q.isPrimaryKey){F(),b=!0,T.remove(M);let ce=f.indices[J];ce&&H.push(ce)}}let v=[];try{for(let M of i||[]){if(M.relationship)continue;let Q=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:Q,configurable:!0});let J=T.get(Q);if(M.isPrimaryKey){if(J=J||T.get(Q=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+J.expiration||void 0)||(+n||void 0)!==(+J.eviction||void 0)){let ae=Object.assign({},J);typeof o=="boolean"&&(o&&f.enableAuditing(o),ae.audit=o),r&&(ae.expiration=+r),n&&(ae.eviction=+n),c!==void 0&&(ae.sealed=c),b=!0,F(),T.put(Q,ae)}continue}J?.attribute&&!J.name&&(J.indexed=!0);let j=!J||J.type!==M.type||J.indexed!==M.indexed||J.nullable!==M.nullable||JSON.stringify(J.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(J.elements)!==JSON.stringify(M.elements);if(M.indexed){let ae=new Ho.default(!0,!1),ce=d.openDB(Q,ae);(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<kl.workerData?.restartNumber)&&(b=!0,F(),J=T.get(Q),(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<kl.workerData?.restartNumber)&&(b=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=J?.lastIndexedKey||!1,M.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ce}),v.push(M))),T.put(Q,M)),J?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ce.indexNulls=M.indexNulls,S[M.name]=ce}else j&&(b=!0,F(),T.put(Q,M))}}finally{C&&C()}if(b&&(f.schemaVersion++,f.updatedAttributes()),An.trace(`${e} table loading, running index`),v.length>0||H.length>0?f.indexingOperation=Qie(f,v,H):b&&lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,b)for(let M of WA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),f;function F(){C||d.transactionSync(()=>({then(M){C=M}}))}a(F,"startTxn")}async function Qie(e,t,r){try{let n=e.schemaVersion;await lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,OG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,An.error(E)}),kl.workerData&&kl.workerData.restartNumber!==bG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>Kie?await s:u>Wie&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function zie({table:e,database:t}){let r=nu({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function XR(e){WA.push(e)}function Sf(){let e=(0,St.get)(Pt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,St.get)(Pt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,St.get)(Pt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||yG,n={startingOffset:32};return t&&(n.dictionary=fh.readFileSync(t)),r&&(n.threshold=r),e&&n}var St,ch,uh,st,nn,sc,Ho,$A,Pt,fh,YA,OG,lh,_h,kl,An,bG,KA,Eh,yG,Br,ot,nc,WA,dh,Ui,ic,Kie,Wie,Ae=Re(()=>{St=B(Z()),ch=B(ft()),uh=require("lmdb"),st=require("path"),nn=require("fs"),sc=B(Je());_E();Ho=B(Dc()),$A=B(Lc()),Pt=B(P()),fh=B(require("fs-extra")),YA=require("../index"),OG=B(vr()),lh=B(bs()),_h=B(Mn()),kl=require("worker_threads"),An=B($()),bG=B(je());ti();Cc();KA="data",Eh=Symbol("defined-tables"),yG=((0,St.get)(Pt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,St.initSync)();Br=Object.create(null),ot=Object.create(null);(0,YA._assignPackageExport)("databases",ot);(0,YA._assignPackageExport)("tables",Br);nc=Symbol.for("next-table-id"),WA=[],Ui=new Map;a(Yie,"getTables");a(hr,"getDatabases");a(Fu,"resetDatabases");a(Fl,"readMetaDb");a(NG,"ensureDB");a(IG,"setTable");a(nu,"database");a(dS,"dropDatabase");a(Et,"table");Kie=1e3,Wie=10;a(Qie,"runIndexing");a(zie,"dropTableMeta");a(XR,"onUpdatedTable");a(Sf,"getDefaultCompression")});var z=g((STe,FG)=>{"use strict";var vi=require("path"),MG=require("fs-extra"),Mr=$(),wG=require("fs-extra"),hh=require("os"),Jie=require("net"),jie=require("recursive-iterator"),dt=P(),Xie=VO(),CG=require("papaparse"),mh=require("moment"),{inspect:Zie}=require("util"),DG=require("is-number"),pTe=require("lodash"),eoe=require("minimist"),toe=require("https"),roe=require("http"),{hdb_errors:ph}=ne(),noe=/^((\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)))$/,PG=require("util").promisify(setTimeout),soe=100,ioe=5,ooe="",aoe=4,LG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};FG.exports={isEmpty:sn,isEmptyOrZeroLength:hs,arrayHasEmptyValues:loe,arrayHasEmptyOrZeroLengthValues:_oe,buildFolderPath:doe,isBoolean:UG,errorizeMessage:coe,stripFileExtension:Eoe,autoCast:hoe,autoCastJSON:vG,autoCastJSONDeep:zA,removeDir:moe,compareVersions:poe,isCompatibleDataVersion:Soe,escapeRawValue:Toe,unescapeValue:goe,stringifyProps:Roe,timeoutPromise:Ooe,isClusterOperation:yoe,getClusterUser:Ioe,checkGlobalSchemaTable:Noe,getHomeDir:HG,getPropsFilePath:Aoe,promisifyPapaParse:woe,removeBOM:xG,createEventPromise:Coe,checkProcessRunning:Doe,checkSchemaTableExist:Loe,checkSchemaExists:GG,checkTableExists:qG,getStartOfTomorrowInSeconds:Moe,getLimitKey:Poe,isObject:foe,isNotEmptyAndHasValue:uoe,autoCasterIsNumberCheck:BG,backtickASTSchemaItems:Uoe,isPortTaken:boe,createForkArgs:voe,autoCastBoolean:Boe,async_set_timeout:PG,getTableHashAttribute:Hoe,doesSchemaExist:xoe,doesTableExist:Goe,stringifyObj:qoe,ms_to_time:Foe,changeExtension:koe,getEnvCliRootPath:JA,noBootFile:Voe,httpRequest:$oe,transformReq:Yoe,convertToMS:Koe,PACKAGE_ROOT:dt.PACKAGE_ROOT};function coe(e){return e instanceof Error?e:new Error(e)}a(coe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function uoe(e){return!sn(e)&&(e||e===0||e===""||UG(e))}a(uoe,"isNotEmptyAndHasValue");function hs(e){return sn(e)||e.length===0||e.size===0}a(hs,"isEmptyOrZeroLength");function loe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(loe,"arrayHasEmptyValues");function _oe(e){if(hs(e))return!0;for(let t=0;t<e.length;t++)if(hs(e[t]))return!0;return!1}a(_oe,"arrayHasEmptyOrZeroLengthValues");function doe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(doe,"buildFolderPath");function UG(e){return sn(e)?!1:e===!0||e===!1}a(UG,"isBoolean");function foe(e){return sn(e)?!1:typeof e=="object"}a(foe,"isObject");function Eoe(e){return hs(e)?ooe:e.slice(0,-aoe)}a(Eoe,"stripFileExtension");function hoe(e){return sn(e)||e===""||typeof e!="string"?e:LG[e]!==void 0?LG[e]:BG(e)===!0?Number(e):noe.test(e)?new Date(e):e}a(hoe,"autoCast");function vG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(vG,"autoCastJSON");function zA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=zA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=zA(r);n!==r&&(e[t]=n)}return e}else return vG(e)}a(zA,"autoCastJSONDeep");function BG(e){if(e.startsWith("0.")&&DG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&DG(e))}a(BG,"autoCasterIsNumberCheck");async function moe(e){if(hs(e))throw new Error(`Directory path: ${e} does not exist`);try{await wG.emptyDir(e),await wG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(moe,"removeDir");function poe(e,t){if(hs(e)){Mr.info("Invalid current version sent as parameter.");return}if(hs(t)){Mr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(poe,"compareVersions");function Soe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Soe,"isCompatibleDataVersion");function Toe(e){if(sn(e))return e;let t=String(e);return t==="."?dt.UNICODE_PERIOD:t===".."?dt.UNICODE_PERIOD+dt.UNICODE_PERIOD:t.replace(dt.FORWARD_SLASH_REGEX,dt.UNICODE_FORWARD_SLASH)}a(Toe,"escapeRawValue");function goe(e){if(sn(e))return e;let t=String(e);return t===dt.UNICODE_PERIOD?".":t===dt.UNICODE_PERIOD+dt.UNICODE_PERIOD?"..":String(e).replace(dt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(goe,"unescapeValue");function Roe(e,t){if(sn(e))return Mr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+hh.EOL}!hs(n)&&n[0]===";"?r+=" "+n+s+hh.EOL:hs(n)||(r+=n+"="+s+hh.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Roe,"stringifyProps");function HG(){let e;try{e=hh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(HG,"getHomeDir");function Aoe(){let e=vi.join(HG(),dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return MG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Aoe,"getPropsFilePath");function Ooe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Ooe,"timeoutPromise");async function boe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Jie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(boe,"isPortTaken");function yoe(e){try{return dt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(yoe,"isClusterOperation");function Noe(e,t){let r=(Ae(),ie(ke)).getDatabases();if(!r[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Noe,"checkGlobalSchemaTable");function Ioe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||hs(e)){Mr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Ioe,"getClusterUser");function woe(){CG.parsePromise=function(e,t,r){return new Promise(function(n,s){CG.parse(e,{header:!0,transformHeader:xG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(woe,"promisifyPapaParse");function xG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(xG,"removeBOM");function Coe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${Zie(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(Coe,"createEventPromise");async function Doe(e){let t=!0,r=0;do await PG(soe*r++),(await Xie.findPs(e)).length>0&&(t=!1);while(t&&r<ioe);if(t)throw new Error(`process ${e} was not started`)}a(Doe,"checkProcessRunning");function Loe(e,t){let r=GG(e);if(r)return r;let n=qG(e,t);if(n)return n}a(Loe,"checkSchemaTableExist");function GG(e){let{getDatabases:t}=(Ae(),ie(ke));if(!t()[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(GG,"checkSchemaExists");function qG(e,t){let{getDatabases:r}=(Ae(),ie(ke));if(!r()[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(qG,"checkTableExists");function Moe(){let e=mh().utc().add(1,dt.MOMENT_DAYS_TAG).startOf(dt.MOMENT_DAYS_TAG).unix(),t=mh().utc().unix();return e-t}a(Moe,"getStartOfTomorrowInSeconds");function Poe(){return mh().utc().format("DD-MM-YYYY")}a(Poe,"getLimitKey");function Uoe(e){try{let t=new jie(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){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Uoe,"backtickASTSchemaItems");function voe(e){return[e]}a(voe,"createForkArgs");function Boe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Boe,"autoCastBoolean");function Hoe(e,t){let{getDatabases:r}=(Ae(),ie(ke)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Hoe,"getTableHashAttribute");function xoe(e){let{getDatabases:t}=(Ae(),ie(ke));return t()[e]!==void 0}a(xoe,"doesSchemaExist");function Goe(e,t){let{getDatabases:r}=(Ae(),ie(ke));return r()[e]?.[t]!==void 0}a(Goe,"doesTableExist");function qoe(e){try{return JSON.stringify(e)}catch{return e}}a(qoe,"stringifyObj");function Foe(e){let t=mh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(Foe,"ms_to_time");function koe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(koe,"changeExtension");function JA(){if(process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=eoe(process.argv);if(e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(JA,"getEnvCliRootPath");var QA;function Voe(){if(QA)return QA;let e=JA();if(JA()&&MG.pathExistsSync(vi.join(e,dt.HDB_CONFIG_FILE)))return QA=!0,!0}a(Voe,"noBootFile");function $oe(e,t){let r;return e.protocol==="http:"?r=roe:r=toe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a($oe,"httpRequest");function Yoe(e){if(!e.schema&&!e.database){e.schema=dt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Yoe,"transformReq");function Koe(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(Koe,"convertToMS")});var Z=g((gTe,KG)=>{"use strict";var jA=require("fs-extra"),xo=require("path"),kG=require("os"),Woe=require("properties-reader"),$l=$(),Vl=z(),le=P(),Sh=fr(),Qoe="Error initializing environment manager",Th="BOOT_PROPS_FILE_PATH",VG=!1,zoe={[le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ws={};KG.exports={BOOT_PROPS_FILE_PATH:Th,getHdbBasePath:Joe,setHdbBasePath:joe,get:$G,initSync:Zoe,setProperty:Me,initTestEnvironment:tae,setCloneVar:eae};function Joe(){return Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Joe,"getHdbBasePath");function joe(e){Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(joe,"setHdbBasePath");function $G(e){let t=Sh.getConfigValue(e);return t===void 0?Ws[e]:t}a($G,"get");function Me(e,t){zoe[e]&&(Ws[e]=t),Sh.updateConfigObject(e,t)}a(Me,"setProperty");function Xoe(){let e;try{e=Vl.getPropsFilePath(),jA.accessSync(e,jA.constants.F_OK|jA.constants.R_OK),VG=!0;let t=Woe(e);return Ws[le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(le.HDB_SETTINGS_NAMES.INSTALL_USER),Ws[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ws[Th]=e,!0}catch{return $l.trace(`Environment manager found no properties file at ${e}`),!1}}a(Xoe,"doesPropFileExist");function Zoe(e=!1){try{(VG||Xoe()||Vl.noBootFile())&&!YG&&(Sh.initConfig(e),Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Sh.getConfigValue(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){$l.error(Qoe),$l.error(t),console.error(t),process.exit(1)}}a(Zoe,"initSync");var YG=!1;function eae(e){YG=e}a(eae,"setCloneVar");function tae(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=xo.join(__dirname,"../../","unitTests");Ws[Th]=xo.join(u,"hdb_boot_properties.file"),Me(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Me(le.HDB_SETTINGS_NAMES.INSTALL_USER,kG.userInfo()?kG.userInfo().username:void 0),Me(le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Me(le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Me(le.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),s&&(Me(le.CONFIG_PARAMS.HTTP_SECUREPORT,$G(le.CONFIG_PARAMS.HTTP_PORT)),Me(le.CONFIG_PARAMS.HTTP_PORT,null)),Me(le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Vl.isEmpty(i)?!1:i),Me(le.CONFIG_PARAMS.HTTP_CORS,Vl.isEmpty(i)?!1:i),Me(le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Vl.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Th}. Please check your boot props and settings files`;$l.fatal(r),$l.error(t)}}a(tae,"initTestEnvironment")});var jG=g((ATe,JG)=>{"use strict";var zG=require("joi"),{string:Yl,boolean:WG,array:rae}=zG.types(),QG=P(),nae=Xe();JG.exports=sae;function sae(e){let t=zG.object({operation:Yl.valid(QG.OPERATIONS_ENUM.ADD_NODE,QG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Yl.required(),subscriptions:rae.items({schema:Yl.required(),table:Yl.optional(),hash_attribute:Yl.optional(),subscribe:WG.required(),publish:WG.required()}).min(1).required()});return nae.validateBySchema(e,t)}a(sae,"updateRemoteSourceValidator")});var Kl=g((bTe,XG)=>{"use strict";var XA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};XG.exports=XA});var rq=g((NTe,tq)=>{"use strict";var iae=jG(),Qs=$(),ZA=Ve(),oae=P(),eO=dn(),Go=at(),ZG=Tu(),aae=cd(),{Node:cae,NodeSubscription:eq}=pi(),tO=Kl(),rO=z(),uae=Z(),{cloneDeep:lae}=require("lodash"),{broadcast:_ae}=je();tq.exports=dae;async function dae(e){try{let t=iae(e);if(t)return Qs.error(`Validation error in updateRemoteSource: ${t.message}`),new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=lae(await eO.getNodeRecord(n)),c=!rO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Qs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!rO.doesSchemaExist(E)){Qs.trace(`updateRemoteSource creating schema: ${E}`);try{await ZG.createSchema({operation:"create_schema",schema:E})}catch(h){Qs.error(h)}}if(f&&!rO.doesTableExist(E,f)){let h=new aae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Qs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await ZG.createTable(h)}catch(p){Qs.error(p)}}if(Qs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new eq(E,f,d.publish,d.subscribe))}else i.push(new eq(E,f,d.publish,d.subscribe))}c||(o=new cae(n,i,void 0),Qs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await eO.upsertNodeRecord(u),_ae({type:"nats_update"}),new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${uae.get(oae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await eO.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(dae,"updateRemoteSource")});var oq=g((wTe,iq)=>{"use strict";var sq=require("joi"),{string:nq}=sq.types(),fae=P(),Eae=Xe();iq.exports=hae;function hae(e){let t=sq.object({operation:nq.valid(fae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:nq.required()});return Eae.validateBySchema(e,t)}a(hae,"removeRemoteSourceValidator")});var uq=g((DTe,cq)=>{"use strict";var mae=oq(),gh=$(),Rh=Ve(),nO=P(),pae=dn(),Sae=z(),aq=at(),Tae=Z(),Ah=Kl(),{NodeSubscription:gae}=pi(),Rae=oa(),Aae=oi(),{broadcast:Oae}=je(),bae=Tae.get(nO.CONFIG_PARAMS.CLUSTERING_NODENAME);cq.exports=yae;async function yae(e){try{let t=mae(e);if(t)return gh.error(`Validation error in removeRemoteSource: ${t.message}`),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await pae.getNodeRecord(r);if(Sae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return gh.error(i),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];gh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new gae(c.schema,c.table,!1,!1);await aq.updateConsumerIterator(c.schema,c.table,r,"stop"),await aq.updateRemoteConsumer(u,r)}let s=new Rae(nO.SYSTEM_SCHEMA_NAME,nO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Aae.deleteRecord(s),Oae({type:"nats_update"}),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${bae} successfully removed node '${r}'.`)}catch(t){gh.error(t);let r=t.message?t.message:t;return new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(yae,"removeRemoteSource")});var fq=g((MTe,dq)=>{"use strict";var Oh=$(),Wl=P(),lq=Ve(),sO=Z(),Nae=z(),_q=Kl(),Iae=dn(),wae=Gd(),Cae=qr();dq.exports=Dae;async function Dae(e){try{Oh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Nae.ms_to_time(t),n=new Lae(sO.get(Wl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),sO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??sO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Iae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new wae(Wl.SYSTEM_SCHEMA_NAME,Wl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Cae.update(i)}catch(s){Oh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return Oh.trace("getRemoteSourceConfig response:",n),new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Oh.error(t);let r=t.message?t.message:t;return new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Dae,"getRemoteSourceConfig");function Lae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(Lae,"ConfigResponseObject")});var pq=g((UTe,mq)=>{"use strict";var Eq=Z();Eq.initSync();var hq=at(),Ql=$(),oc=P(),iO=Ve(),Mae=rq(),Pae=uq(),Uae=fq(),vae=Kl(),{encode:Bae,decode:Hae}=require("msgpackr"),xae=Os(),Gae=As(),qae=require("util"),Fae=P(),{isMainThread:kae,parentPort:Vae}=require("worker_threads");je();var $ae=qae.promisify(xae.setSchemaDataToGlobal),oO=Eq.get(oc.CONFIG_PARAMS.CLUSTERING_NODENAME);mq.exports=Yae;async function Yae(){try{Ql.notify("Starting reply service."),await $ae();let e=await hq.getConnection(),t=`${oO}.__request__`,r=e.subscribe(t,{queue:oO});await Kae(r)}catch(e){Ql.error(e)}}a(Yae,"initialize");async function Kae(e){for await(let t of e){let r=Hae(t.data),n;switch(r.operation){case oc.OPERATIONS_ENUM.ADD_NODE:case oc.OPERATIONS_ENUM.UPDATE_NODE:n=await Mae(r);break;case oc.OPERATIONS_ENUM.REMOVE_NODE:n=await Pae(r);break;case oc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Uae(r);break;case oc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await Wae();break;default:let s=`node '${oO}' reply service received unrecognized request operation`;Ql.error(s),n=new vae(iO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Ql.trace(n),t.respond(Bae(n))}}a(Kae,"handleRequest");async function Wae(){try{return{status:iO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Gae.describeAll()}}catch(e){return Ql.error(e),{status:iO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Wae,"getRemoteDescribeAll");kae||Vae.on("message",async e=>{let{type:t}=e;t===Fae.ITC_EVENT_TYPES.SHUTDOWN&&hq.closeConnection()})});var Qae=pq();(async()=>{try{await Qae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
31
+ `))}},25).unref()}o.close?.(()=>{if(xe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&Dl()==0)try{ZH(xe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,PE),o.cantCleanupProperly||Pt.warn("Had to forcefully exit the thread",PE),process.exit(0)},5e3).unref()})}if(ax||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Pt.info("Could not close debugger",i)}}}).ref();let e=[];if(ex&&!xse)for(let t in Es){let r=Es[t];if(isNaN(t)&&Dl()==0){Ise(t)&&ZH(t),e.push(new Promise((i,o)=>{r.listen({path:t},()=>{i(),Pt.info("Domain socket listening on "+t)}).on("error",o)}));continue}let n=xe.get(_t.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=Dl();if(o<i[0]||o>i[1])continue}let s;try{s=ex(+t,"::")}catch(i){console.error(`Unable to bind to port ${t}`,i);continue}e.push(new Promise((i,o)=>{r.listen({fd:s},()=>{i(),Pt.trace("Listening on port "+t,PE)}).on("error",o)}))}Promise.all(e).then(()=>{Cl?.postMessage({type:_t.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(cx,"startServers");nA||cx();function oA(e,t,r){let n=e?.read?e:new Rse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Es[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=Es[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Pt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(oA,"deliverSocket");var tx=new Map;function Fse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=tx.get(s),r){case"connection":i=oA(void 0,t),tx.set(s,i),i.write=(c,u,_)=>(Cl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Cl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Cl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(Fse,"proxyRequest");function aA(e,t,r=!0){!+t&&t!==xe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(xe.get(_t.CONFIG_PARAMS.HTTP_PORT),10));let n=Es[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",rx),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else Es[t]=e;e.on("unhandled",rx)}a(aA,"registerServer");function ux(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=[],xe.get(_t.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:xe.get(_t.CONFIG_PARAMS.HTTP_PORT),secure:xe.get(_t.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),xe.get(_t.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:xe.get(_t.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&xe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:xe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(ux,"getPorts");function cA(e,t){for(let{port:r,secure:n}of ux(t))lx(r,n,t?.isOperationsServer),typeof e=="function"?sA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,aA(e,r,!1)),vE[r]=iA(sA,r),Gse=iA(qse,r)}a(cA,"httpServer");function lx(e,t,r){if(!Ys[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:xe.get(n+"_keepAliveTimeout"),headersTimeout:xe.get(n+"_headersTimeout"),requestTimeout:xe.get(n+"_timeout")},i=xe.get(n+"_mtls"),o=xe.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=xe.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:nx(),maxHeaderSize:xe.get(_t.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:uA(u)})}let c=Use();Ys[e]=(t?yse:Ose)(s,async(u,_)=>{try{let d=performance.now(),E=new ix(u,_);r&&(E.isOperationsServer=!0);let f=await vE[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=_x(E)}if(c?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 H of f.headers||[])_.setHeader(H[0],H[1]);return u.baseRequest=E,_.baseResponse=f,Ys[e].emit("unhandled",u,_)}let h=f.status||200,p=performance.now(),S=p-d,T=f.body,R;if(!f.handlesHeaders){let H=f.headers||new sx;T?T.length>=0&&(typeof T=="string"?H.set("Content-Length",Buffer.byteLength(T)):H.set("Content-Length",T.length),R=!0):(H.set("Content-Length","0"),R=!0);let v=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(v+=", miss"),Mse(H,"Server-Timing",v,!0),_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),R&&_.end(T)}let b=E.handlerPath,C=E.method;if(wl(S,"duration",b,C,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),Pse(h<400,"success",b,C),!R)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let H=0;T.on("data",v=>{H+=v.length}),T.on("end",()=>{wl(performance.now()-p,"transfer",b,C),wl(H,"bytes-sent",b,C)})}else T?.then?T.then(H=>{_.end(H)},l):_.end(T)}catch(d){l(d)}function l(d){let E=d.headers;_.writeHead(d.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),_.end(d.toString()),d.statusCode?d.statusCode===500?Pt.warn(d):Pt.info(d):Pt.error(d)}a(l,"onError")}),i&&(Ys[e].mtlsConfig=i),t&&(Ys[e].on("secureConnection",u=>{u._parent.startTime&&wl(performance.now()-u._parent.startTime,"tls-handshake",e),wl(u.isSessionReused(),"tls-reused",e)}),Ys[e].isSecure=!0,s.SNICallback(null,(u,_)=>{try{ja=_,_&&Ys[e].setSecureContext(_.options)}finally{ja=null}})),aA(Ys[e],e)}return Ys[e]}a(lx,"getHTTPServer");function iA(e,t){let r=_x;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(iA,"makeCallbackChain");function _x(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new sx}}a(_x,"unhandled");function kse(e,t){cA(e,{requestOnly:!0,...t})}a(kse,"onRequest");function Vse(e,t){let r;if(t.securePort){let n=Object.assign({},xe.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={noDelay:!0,rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:uA(n)};r=Dse(s,e),s.SNICallback(null,(i,o)=>{try{ja=o,o&&r.setSecureContext(o.options)}finally{ja=null}}),Es[t.securePort]=r}return t.port&&(r=Ase({noDelay:!0},e),Es[t.port]=r),r}a(Vse,"onSocket");Object.defineProperty(bse.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 $se(e,t){let r;for(let{port:n,secure:s}of ux(t)){UE[n]||(UE[n]=new wse({server:r=lx(n,s)}),UE[n].on("connection",async(c,u)=>{try{let _=new ix(u);_.isWebSocket=!0;let l=vE[n](_),d=u.headers["sec-websocket-protocol"]||"",E=tA[n];if(d){let f;for(let h=0;h<E.length;h++){let p=E[h];p.protocol===d&&(f=!0,p.listener(c,_,l))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,l)}}catch(_){Pt.warn("Error handling WebSocket connection",_)}}),UE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=tA[n];o||(o=tA[n]=[]),o.push({listener:e,protocol:i}),vE[n]=iA(sA,n)}return r}a($se,"onWebSocket");function rx(e,t){t.writeHead(404),t.end(`Not found
32
+ `)}a(rx,"defaultNotFound");function rA(e){return e.startsWith("-----BEGIN")?e:Nse(e)}a(rA,"readPEM");function uA(e){let t=[];for(let o=0;e[o];o++)t.push(e[o]);t.length||t.push(e);let r=new Map,n,s,i=!1;for(let o of t){let c=rA(o.privateKey),u=rA(o.certificate),_=o.certificateAuthority&&rA(o.certificateAuthority);if(!c||!u)throw new Error("Missing private key or certificate for secure server");let l={ciphers:o.ciphers,ca:_,ticketKeys:nx()},d=Cse(l);d.options=l,l.instantiatedContext=d,d.context.setCert(u),d.context.setKey(c,void 0),l.cert=u,l.key=c,d.certStart=u.slice(0,100).toString(),n||(n=d);let E=new vse(u);d.subject=E.subject;let f=o.hostname??o.host??o.hostnames??o.hosts??(E.subjectAltName?E.subjectAltName.split(",").map(h=>{let p=h.indexOf(":");return h.slice(p+1)}):[E.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(f)||(f=[f]);for(let h of f)h?(h[0]==="*"&&(i=!0,h=h.slice(1)),r.has(h)||r.set(h,d),!s&&h.match(/\d+\.\d+\.\d+\.\d+/)&&(s=d)):Pt.error("No hostname found for certificate at",o.certificate)}return(o,c)=>{let u=o;for(;;){let _=r.get(u);if(_)return Pt.debug("Found certificate for",o,_.certStart),c(null,_);if(i&&u){let l=u.indexOf(".",1);l<0?u="":u=u.slice(l)}else break}Pt.debug("No certificate found to match",o,"using the first certificate"),o?c(null,n):c(null,s)}}a(uA,"createSNICallback")});async function mx({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await _A.get(e,{returnNonexistent:!0});i=new EA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await _A.get(e);o&&o.delete()}i=new xE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Ll.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function dA(){return HE++,HE>65500&&(HE=1),HE}function fA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=bi.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var fx,Mi,Ex,hx,_A,Ll,HE,xE,EA,px=Re(()=>{Ae();ju();fx=B(vr()),Mi=B($());no();Ex=B(We()),hx=B(dx());lr();_A=Et({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),Ll=Et({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,Ex.getWorkerIndex)()===0&&(async()=>{await hx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ll.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await at.getUser(r.user.username)),Ze(r,()=>{try{fA(r,t,r)}catch{(0,Mi.warn)("Failed to publish will",t)}Ll.delete(e.id,r)})}})();a(mx,"getSession");HE=1;a(dA,"getNextMessageId");xE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Mi.trace)("Resuming subscription from",s,"from",o);let f=bi.getMatch(_);if(!f){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let T=E.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,T.indexOf("+")===T.length-1)E.onlyChildren=!0,E.url="/"+T.slice(0,T.length-1);else{let R=T.split("/"),b;for(let v=0;v<R.length;v++)if(R[v].indexOf("+")>-1)if(R[v]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let C=!0;R[R.length-1]==="#"&&(R.length--,C=!1),b&&(n=a(v=>{let F=v.id;if(!Array.isArray(F)||C&&F.length!==R.length)return!1;for(let M=0;M<R.length;M++)if(R[M]!=="+"&&R[M]!==F[M])return!1;return!0},"filter"));let H=R.indexOf("+");E.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Ze(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let R=await p.subscribe(E,T);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let b of R)try{let C;if(b.type&&b.type!=="put"&&b.type!=="delete"&&b.type!=="message"&&b.type!=="patch"||n&&!n(b))continue;r?(b.topic=s,C=this.needsAcknowledge(b)):(b.acknowledge?.(),C=dA());let H=b.id;Array.isArray(H)&&(H=Ia(H)),H==null&&(H=""),this.listener(h+"/"+H,b.value,C,t)}catch(C){(0,Mi.warn)(C)}})(),R});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=dA();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return fA(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ze(r,async()=>{try{if(!t){let n=await Ll.get(this.sessionId);n?.doesExist()&&await fA(n,n.data,r)}}finally{await Ll.delete(this.sessionId)}}).catch(n=>{(0,Mi.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(fA,"publish");EA=class extends xE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=dA(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Mi.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,fx.getNextMonotonicTime)()),(0,Mi.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),_A.put(this.sessionRecord)}}});var mA={};Fe(mA,{bypassAuth:()=>Yse,start:()=>Kse});function Yse(){Ax=!0}function Kse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Rx.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),jt.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=Tx(_,(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",E),_.on("close",f),_.on("error",h=>{jt.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),jt.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&qE.notify({username:l?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&qE.error({username:f,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else jt.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),jt.error(f)}else if(u.required)return jt.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&Ax&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,gx.getSuperUser)(),jt.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=Tx(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{jt.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function Tx(e,t,r,n,s){Sx||(Sx=!0,Eu(d=>{GE>0&&d.push({metric:"mqtt-connections",connections:GE,byThread:!0})}));let i;GE++;let o,c={protocolVersion:4},u=(0,FE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){GE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),jt.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;Sr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await at.getUser(d.username,d.password.toString(),r),(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&qE.notify({username:n?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&qE.error({username:d.username,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=bo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=mx({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return jt.error(M),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,J,j)=>{try{let ae=M.indexOf("/",1),ce=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:J||Math.floor(Math.random()*1e8),qos:j.qos},ce)}catch(ae){jt.error(ae),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let R=[];for(let M of d.subscriptions){let Q;try{Q=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(J){s.events.emit("error",J,e,M,o),jt.error(J),Q=c.protocolVersion<5?128:J.statusCode===403?135:J.statusCode===404?143:128}R.push(Q)}await o.committed,p({cmd:"suback",granted:R,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let Q of d.unsubscriptions)M.push(o.removeSubscription(Q)?0:17);p({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let b=d.qos===2?"pubrec":"puback",C=e.deserialize||(e.deserialize=bo(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,F;try{F=await o.publish(d,v)}catch(M){s.events.emit("error",M,e,d,o),jt.warn(M),d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:F===!1?144:0},d.topic);break;case"pubrec":p({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!0,"connection","mqtt","disconnect"),jt.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(R){s.events.emit("error",R,e,d,o),jt.error(R),p({cmd:"disconnect"})}function p(R,b){let C=(0,FE.generate)(R,c);t(C),Sr(C.length,"bytes-sent",b,S(R),"mqtt")}a(p,"sendPacket");function S(R){return R.qos>0?R.cmd+",qos="+R.qos:R.cmd}a(S,"packetMethodName");function T(R){return go(R,r)}a(T,"serialize")}),u.on("error",d=>{jt.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:_,onClose:l}}var FE,gx,Xa,Xt,hA,Rx,qE,jt,Ax,Sx,GE,Ox=Re(()=>{FE=require("mqtt-packet");px();gx=B(ln());Ca();Cs();lr();Xa=B(Z()),Xt=B(P()),hA=B($()),Rx=require("events"),qE=(0,hA.loggerWithTag)("auth-event"),jt=(0,hA.loggerWithTag)("mqtt"),Ax=(0,Xa.get)(Xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Yse,"bypassAuth");a(Kse,"start");GE=0;a(Tx,"onSocket")});var Hf={};Fe(Hf,{component_errors:()=>ec,loadComponent:()=>kE,loadComponentDirectories:()=>Mx,setErrorReporter:()=>Jse});function Mx(e,t){t&&(SA=t),e&&(TA=e);let r=[];if((0,tt.existsSync)(pA)){let s=(0,tt.readdirSync)(pA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,st.join)(pA,o);r.push(kE(c,SA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(kE(n,SA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Lx=!0})}function Jse(e){Ml=e}async function kE(e,t,r,n,s,i){let o=(0,tt.realpathSync)(e);if(!yx.has(o)){yx.set(o,!0),s&&(TA=s);try{let c;n&&(ec=new Map);let u=(0,st.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,tt.existsSync)(u)?c=n?(0,Dx.getConfigObj)():(0,Nx.parseDocument)((0,tt.readFileSync)(u,"utf8"),{simpleKeys:!0}).toJSON():c=gA;let _=(0,st.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&(n||(0,tt.existsSync)(_)&&(0,tt.realpathSync)(rc.PACKAGE_ROOT)!==(0,tt.realpathSync)(_))&&((0,tt.rmSync)(_,{recursive:!0,force:!0}),(0,tt.existsSync)((0,st.join)(e,"node_modules"))||(0,tt.mkdirSync)((0,st.join)(e,"node_modules")),(0,tt.symlinkSync)(rc.PACKAGE_ROOT,_,"dir"))}catch(E){Za.default.error("Error symlinking harperdb module",E)}let l=[],d=n;for(let E in c){let f=c[E];if(ec.set(n?E:(0,st.basename)(e),!1),!f)continue;let h,p=f.package;try{if(p){let C=e,H;for(;!(0,tt.existsSync)(H=(0,st.join)(C,"node_modules",E));)if(C=(0,st.dirname)(C),C.length<(0,Cx.getHdbBasePath)().length){H=null;break}if(H)h=await kE(H,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${p}`)}else h=zse[E];if(!h)continue;l.push(h);let S=a(C=>(C.origin=r,Et(C)),"ensureTable"),T=f.network||(f.port||f.securePort)&&f,R=T?.securePort||T?.https&&T.port,b=!T?.https&&T?.port;if(Lo.isMainThread&&(h=await h.startOnMainThread?.({server:at,ensureTable:S,port:b,securePort:R,resources:t,...f})||h,n&&T))for(let C of[b,R])try{if(+C&&!bx.includes(C)){let H=RA.get(rc.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);H&&Za.default.warn("Session affinity is not recommended and may cause memory leaks"),(H||!wE)&&(bx.push(C),xH(C,H))}}catch(H){console.error("Error listening on socket",C,H,E)}if(t.isWorker&&(h=await h.start?.({server:at,ensureTable:S,port:b,securePort:R,resources:t,...f})||h),TA.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,wx.handleHDBError)("Can not reference parent directories");let C=(0,st.join)(e,f.files).replace(/\\/g,"/"),H=C.indexOf("/*");if(H>-1&&f.files!==gA[E]?.files&&!(0,tt.existsSync)(C.slice(0,H)))throw new Error(`The path '${C.slice(0,H)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let v=(0,st.basename)(e),F=f.path||"/";F=F.startsWith("/")?F:F.startsWith("./")?"/"+v+F.slice(2):F==="."?"/"+v:"/"+v+"/"+F;let M,Q,J;if(f.root){let ae=f.root;ae.startsWith("/")&&(ae=ae.slice(1)),ae.endsWith("/")&&(ae=ae.slice(0,-1)),ae+="/",Q=(0,st.join)(e,ae)}else(J=C.indexOf("/*"))>-1&&(Q=C.slice(0,J+1),M=(0,st.relative)(e,Q));let j=!1;if(Lo.isMainThread&&h.setupDirectory&&(j=await h.setupDirectory?.(F,Q,t)),t.isWorker&&h.handleDirectory&&(j=await h.handleDirectory?.(F,Q,t)),j)continue;for(let ae of await(0,Ix.default)(C,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:ge}=ae;d=!0;let Ge=(0,st.relative)(e,ce).replace(/\\/g,"/");if(M)if(Ge.startsWith(M))Ge=Ge.slice(M.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${Ge}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Ne=F+(F.endsWith("/")?"":"/")+Ge;try{if(ge.isFile()){let ve=await Qse(ce);Lo.isMainThread&&await h.setupFile?.(ve,Ne,ce,t),t.isWorker&&await h.handleFile?.(ve,Ne,ce,t)}else Lo.isMainThread&&await h.setupDirectory?.(Ne,ce,t),t.isWorker&&await h.handleDirectory?.(Ne,ce,t)}catch(ve){ve.message=`Could not load ${ge.isFile()?"file":"directory"} '${ce}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${ve.message}`,Ml?.(ve),((0,tc.getWorkerIndex)()===0?console:Za.default).error(ve),t.set(f.path||"/",new Pl(ve)),ec.set(n?E:(0,st.basename)(e),ve.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,st.basename)(e)}' due to: ${S.message}`,Ml?.(S),((0,tc.getWorkerIndex)()===0?console:Za.default).error(S),t.set(f.path||"/",new Pl(S),null,!0),ec.set(n?E:(0,st.basename)(e),S.message)}}if(Lo.isMainThread&&!Lx&&i&&(0,tc.watchDir)(e,async()=>Mx()),c.extensionModule)return await m_((0,st.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;Ml?.(new Error(E)),((0,tc.getWorkerIndex)()===0?console:Za.default).error(E),ec.set((0,st.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Ml?.(c),t.set("",new Pl(c))}}}var tt,st,Lo,Nx,RA,rc,Ix,tc,Za,wx,Cx,Wse,Dx,Qse,pA,TA,Lx,SA,ec,zse,gA,bx,yx,Ml,Pl,xf=Re(()=>{tt=require("fs"),st=require("path"),Lo=require("worker_threads"),Nx=require("yaml"),RA=B(Z()),rc=B(P());Rb();yb();Nb();v0();NH();MH();Ix=B(require("fast-glob")),tc=B(We()),Za=B($());Jh();lr();wx=B(ne());Nn();Ae();GH();Cx=B(Z()),Wse=B($H());Cf();XH();Ox();Dx=B(Er());CE();({readFile:Qse}=tt.promises),pA=RA.get(rc.CONFIG_PARAMS.COMPONENTSROOT),TA=new Map,ec=new Map;a(Mx,"loadComponentDirectories");zse={REST:rE,rest:rE,graphqlSchema:zh,jsResource:Xh,fastifyRoutes:xR,login:em,static:GR,operationsApi:Wse,customFunctions:{},http:{},clustering:ZR,authentication:Zu,mqtt:mA},gA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(gA,"static",{value:{files:"web/**"}});bx=[],yx=new Map;a(Jse,"setErrorReporter");a(kE,"loadComponent");Pl=class extends $t{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 lA=g((PSe,Ux)=>{var{isMainThread:Px}=require("worker_threads"),{getTables:jse}=(Ae(),ie(ke)),{loadComponentDirectories:Xse,loadComponent:Zse}=(xf(),ie(Hf)),{resetResources:eie}=(ju(),ie(VU)),tie=Tg(),rie=Er(),{dirname:nie}=require("path"),{getConnection:sie}=ut(),iie=Z(),oie=P(),AA=new Map;async function aie(e=!1){!Px&&iie.get(oie.CONFIG_PARAMS.CLUSTERING_ENABLED)&&sie();try{Px&&await tie()}catch(n){console.error(n)}let t=eie();jse(),t.isWorker=e,await Zse(nie(rie.getConfigFilePath()),t,"hdb",!0,AA),await Xse(AA,t);let r=[];for(let[n]of AA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(aie,"loadRootComponents");Ux.exports.loadRootComponents=aie});var We=g((vSe,Ui)=>{"use strict";var{Worker:cie,MessageChannel:uie,parentPort:hs,isMainThread:IA,threadId:lie,workerData:Ks}=require("worker_threads"),{PACKAGE_ROOT:_ie}=P(),{join:xx,isAbsolute:die,extname:fie}=require("path"),{server:Gx}=(lr(),ie(xi)),{watch:Eie,readdir:hie}=require("fs/promises"),{totalmem:vx}=require("os"),Ul=P(),qx=Z(),Ws=$(),{randomBytes:mie}=require("crypto"),{_assignPackageExport:pie}=require("../index"),Sie=P(),Bx=1024*1024,Pi=[],Tn=[],Tie=50,wA=1e4,gie="restart",Fx="request_thread_info",kx="resource_report",Vx="thread_info",$x="added-port",Rie="ack",OA;pie("threads",Tn);Ui.exports={startWorker:bA,restartWorkers:DA,shutdownWorkers:Nie,workers:Pi,setMonitorListener:Uie,onMessageFromWorkers:Iie,onMessageByType:jx,broadcast:Cie,broadcastWithAcknowledgement:Lie,setChildListenerByType:yie,getWorkerIndex:Yx,getWorkerCount:Kx,getTicketKeys:Qx,setMainIsWorker:Oie,setTerminateTimeout:Aie,restartNumber:Ks?.restartNumber||1};Tn.onMessageByType=jx;Tn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Tn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var CA;function Aie(e){wA=e}a(Aie,"setTerminateTimeout");function Yx(){return Ks?Ks.workerIndex:CA?0:void 0}a(Yx,"getWorkerIndex");function Kx(){return Ks?Ks.workerCount:CA?1:void 0}a(Kx,"getWorkerCount");function Oie(e){CA=e}a(Oie,"setMainIsWorker");var Wx=1,VE;function Qx(){return VE||(VE=IA?mie(48):Ks.ticketKeys,VE)}a(Qx,"getTicketKeys");Object.defineProperty(Gx,"workerIndex",{get(){return Yx()}});Object.defineProperty(Gx,"workerCount",{get(){return Kx()}});var zx={[Fx](e,t){Mie(t)},[kx](e,t){Pie(t,e)}};function bA(e,t={}){let r=process.constrainedMemory?.()||vx();r=Math.min(r,vx(),2e4*Bx);let n=qx.get(Ul.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Bx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Tn){let _=new uie;_.existingPort=u,i.push(_),o.push(_.port2)}fie(e)||(e+=".js");let c=new cie(die(e)?e:xx(_ie,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Wx=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:Qx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:$x,port:u,threadId:c.threadId},[u]);return YE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>bA(e,t),c.on("error",u=>{Ws.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Pi.splice(Pi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Tie?(t.unexpectedRestarts=c.unexpectedRestarts+1,bA(e,t)):Ws.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{zx[u.type]?.(u,c)}),Pi.push(c),Bie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(bA,"startWorker");var bie=[Ul.THREAD_TYPES.HTTP];async function DA(e=null,t=Math.max(Wx>3,1),r=!0){if(IA){if(r){let{loadRootComponents:o}=lA();await o()}Ui.exports.restartNumber++,t<1&&(t=t*Pi.length);let n=[],s=[];for(let o of Pi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ws.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ui.exports.restartNumber,type:Ul.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=bie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),wA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let E=a(f=>{f.type===Sie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ws.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ws.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=zu();r&&(e==="http"||!e)&&qx.get(Ul.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else hs.postMessage({type:gie,workerType:e})}a(DA,"restartWorkers");function yie(e,t){zx[e]=t}a(yie,"setChildListenerByType");function Nie(e){return DA(e,1/0,!1)}a(Nie,"shutdownWorkers");var Jx=[];function Iie(e){Jx.push(e)}a(Iie,"onMessageFromWorkers");var yA=new Map;function jx(e,t){let r=yA.get(e);r||yA.set(e,r=[]),r.push(t)}a(jx,"onMessageByType");var wie=10;async function Cie(e){let t=0;for(let r of Tn)try{r.postMessage(e),t++>wie&&(t=0,await new Promise(setImmediate))}catch(n){Ws.error("Unable to send message to worker",n)}}a(Cie,"broadcast");var $E=new Map,Die=1;function Lie(e){return new Promise(t=>{let r=0;for(let n of Tn)try{let s=Die++,i=a(()=>{$E.delete(s),--r===0&&t(),n!==hs&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,$E.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of $E)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ws.error("Unable to send message to worker",s)}r===0&&t()})}a(Lie,"broadcastWithAcknowledgement");function Mie(e){e.postMessage({type:Vx,workers:Xx()})}a(Mie,"sendThreadInfo");function Xx(){let e=Date.now();return Pi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(Xx,"getChildWorkerInfo");function Pie(e,t){e.resources=t,e.resources.updated=Date.now()}a(Pie,"recordResourceReport");var NA;function Uie(e){NA=e}a(Uie,"setMonitorListener");var vie=1e3,Hx=!1;function Bie(){Hx||(Hx=!0,setInterval(()=>{for(let e of Pi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}NA&&NA()},vie).unref())}a(Bie,"startMonitoring");var Hie=1e3;if(hs){YE(hs);for(let e=0,t=Ks.addPorts.length;e<t;e++){let r=Ks.addPorts[e];r.threadId=Ks.addThreadIds[e],YE(r)}setInterval(()=>{let e=process.memoryUsage();hs.postMessage({type:kx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Hie).unref(),OA=a(()=>new Promise((e,t)=>{hs.on("message",r),hs.postMessage({type:Fx});function r(n){n.type===Vx&&(hs.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else OA=Xx;Ui.exports.getThreadInfo=OA;function YE(e,t){Tn.push(e),e.on("message",r=>{if(r.type===$x)r.port.threadId=r.threadId,YE(r.port);else if(r.type===Rie){let n=$E.get(r.id);n&&n()}else{for(let s of Jx)s(r,e);let n=yA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ws.error(i)}}}).on("close",()=>{Tn.splice(Tn.indexOf(e),1)}).on("exit",()=>{Tn.splice(Tn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(YE,"addPort");if(IA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await hie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(xx(s,o.name));try{for await(let{filename:o}of Eie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await DA(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");Ui.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else hs.on("message",async e=>{let{type:t}=e;t===Ul.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,hs.unref(),setTimeout(()=>{Ws.warn("Thread did not voluntarily terminate",lie),process.exit(0)},wA).unref())})});var PC={};Fe(PC,{AUDIT_STORE_OPTIONS:()=>Rf,createAuditEntry:()=>R_,openAuditStore:()=>zE,readAuditEntry:()=>vt,setAuditRetention:()=>Gie,transactionKeyEncoder:()=>aG});function zE(e){let t=e.auditStore=e.openDB(sG.AUDIT_STORE_NAME,Rf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=KE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-LA})){if((_[0]&15)===UA){let l=vt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=xie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,LA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,QE.getWorkerIndex)()===(0,QE.getWorkerCount)()-1&&s(KE),t}function Gie(e,t=KE){LA=e,KE=t}function R_(e,t,r,n,s,i,o){let c=cG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?nc.setFloat64(0,n):gn.set(mm),u=9),E(0),E(t),d(r),nc.setFloat64(u,e),u+=8,s?d(s):gn[u++]=0,gn[n?8:0]=c;let l=gn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,sc.writeKey)(f,gn,u);let p=u-h-1;p>127?p>16383?(BA.error("Key or username was too large for audit entry",f),u=h+1,gn[h]=0):(gn.copyWithin(h+2,h+1,u),nc.setUint16(h,p|32768),u++):gn[h]=p}function E(f){f<128?gn[u++]=f:f<16384?(nc.setUint16(u,f|32768),u+=2):f<1056964608?(nc.setUint32(u,f|3221225472),u+=4):(gn[u]=255,nc.setUint32(u+1,f),u+=5)}}function vt(e){try{let t=e.dataView||(e.dataView=new vA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:cG[n&7],tableId:i,get recordId(){return nG(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?nG(e,l,d):void 0},getValue(E,f,h){if(n&MA||n&PA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&PA&&h)return HA(E.getEntry(this.recordId),h,E)}}}catch(t){return BA.error("Reading audit entry error",t,e),{}}}function nG(e,t,r){let n=e.subarray(t,r);return(0,sc.readKey)(n,0,r-t)}var sc,WE,sG,iG,QE,oG,BA,gn,nc,aG,Rf,LA,xie,KE,MA,PA,Zx,UA,eG,tG,rG,cG,vA,ri=Re(()=>{sc=require("ordered-binary"),WE=B(Z()),sG=B(ft()),iG=B(P()),QE=B(We()),oG=B(z());Mc();BA=B($());JE();(0,WE.initSync)();gn=Buffer.alloc(1024),nc=new DataView(gn.buffer,gn.byteOffset,1024),aG={writeKey(e,t,r){return e===Lc?(t.set(Lc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,sc.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,sc.readKey)(e,t,r)}},Rf={encoding:"binary",keyEncoder:aG},LA=(0,oG.convertToMS)((0,WE.get)(iG.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,xie=1e3,KE=1e4;a(zE,"openAuditStore");a(Gie,"setAuditRetention");MA=16,PA=32,Zx=1,UA=2,eG=3,tG=4,rG=5,cG={put:Zx|MA,[Zx]:"put",delete:UA,[UA]:"delete",message:eG|MA,[eG]:"message",invalidate:tG,[tG]:"invalidate",patch:rG|PA,[rG]:"patch"};a(R_,"createAuditEntry");a(vt,"readAuditEntry");vA=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(nG,"readKeySafely")});var xA={};Fe(xA,{add:()=>jE,applyReverse:()=>uG,getRecordAtTime:()=>HA,rebuildUpdateBefore:()=>XE});function jE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function XE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,jE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function uG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=qie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=lG}}function HA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=vt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":uG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===lG&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=vt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var qie,lG,JE=Re(()=>{ri();a(jE,"add");jE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};qie={add:jE};a(XE,"rebuildUpdateBefore");a(uG,"applyReverse");lG={};a(HA,"getRecordAtTime")});function Zr(e){return e[Nt]||(e[Nt]=Object.create(null))}function nh(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(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 Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be a number, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Zr(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 Rn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[Nt];if(l&&c in l){let E=l[c];if(E?.__op__){let f=this[de]?.[c];return E.update(f)}return E}let d=this[de]?.[c];if(d&&typeof d=="object"){let E=dG(d,o);if(E)return l||(l=this[Nt]=Object.create(null)),l[c]=E}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Nt];return u?.[o]!==void 0?u[o]:this[de]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Rn.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[Nt],c;for(let _ in o){c||(c=Object.assign({},this[de]));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[de])),Object.assign(c,this)),c||this[de]}),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 dG(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=s}},nh(r,t)),new r(e)):new ZE(e);case Array:let n=new th(e.length);n[de]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=dG(o,t?.elements)),n[s]=o}return n;default:return e}}function pd(e){let t=e[Nt],r;for(let s in t){r||(r=Object.assign({},e[de]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=pd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Po(e,t=e[Nt]){let r;if(_G.call(e,de)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Po(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[de]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=xA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):_G.call(e,de)?e[de]:e}function eh(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[de]===s){if(eh(i))return!0}else return!0}}else{let r=e[Nt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[de]===i){if(eh(s))return!0}else return!0}else return!0}}return!1}var Rn,Nt,ZE,_G,Mo,th,rh,Sd=Re(()=>{Nn();Rn=B(ne());JE();Nt=Symbol("own-data");a(Zr,"getChanges");a(nh,"assignTrackedAccessors");a(dG,"trackObject");ZE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=t}};nh(ZE,{});a(pd,"collapseData");_G=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(eh,"hasChanges");Mo=Symbol.for("has-array-changes"),th=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};th.prototype.constructor=Array;rh=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Fp={};Fe(Fp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>kn,RECORD_PROPERTY:()=>de,Resource:()=>$t,snake_case:()=>kie,transformForSelect:()=>ih});function kie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function fG(e,t){if(vl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(vl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new qA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){vl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=s,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let f of s){if(typeof f=="object"&&f)break;c.push(f)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return Ze(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new sh(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new sh(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new mG.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function GA(e,t,r){let n=e[de];if(n){let s=e[Nt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ih(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):GA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(GA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(GA(u,r,n)),d;for(let E of e){let f=l(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=ih(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var EG,hG,mG,ye,Le,kn,de,Fie,$t,sh,vl,qA,Nn=Re(()=>{EG=require("crypto");yc();hG=require("../index"),mG=B(ne());Sd();no();eE();ye=Symbol.for("context"),Le=Symbol.for("primary-key"),kn=Symbol("is-collection"),de=Symbol("stored-record"),Fie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$t=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=en(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=ih(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[kn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,EG.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),n||(n={}),Ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ih(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[kn])return this.constructor.create(this[Le],t,this[ye]);tn(this,"post")}static isCollection(t){return t?.[kn]}static coerceId(t){return t}static parseQuery(t){return Zf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Fie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:fG(t,this),isCollection:vl}}let i=fG(t,this);return vl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Le]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[kn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Le]}getContext(){return this[ye]}};$t.prototype[ye]=null;(0,hG._assignPackageExport)("Resource",$t);a(kie,"snake_case");sh=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(fG,"pathToId");qA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(GA,"selectFromObject");a(ih,"transformForSelect")});function TG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=SG,Vie(e.primaryStore,e.auditStore)):(c=pG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{gG(pG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Ia(t);let l=new kA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function gG(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=vt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Ia(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,FA.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,FA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Vie(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u=SG[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),gG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var FA,pG,SG,kA,RG=Re(()=>{FA=B($());yc();ju();ri();pG=Object.create(null),SG=Object.create(null);a(TG,"addSubscription");kA=class extends yn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(gG,"notifyFromTransactionData");a(Vie,"listenToCommits")});var RR={};Fe(RR,{coerceType:()=>oh,makeTable:()=>uh,setServerUtilities:()=>Xie,updateResource:()=>ah});function uh(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=Tm(i,n,u),R=0,b,C,H={},v=Promise.resolve(),F,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(F=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(H=K);let J,j=[],ae=[],ce=1,ge=2,Ge={},Ne={},ve=864e5,e_,t_,Js,uO=!1,yh,Nh,yq=i.getRange({start:!1,end:!1}).constructor,Nq=10,Iq=6;h&&dO();class Je extends $t{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=F;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),C=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(L=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[L]&&(!U[L].reliesOnPrototype||U.prototype[L])),N.length>0)if(N.length===1){let U=N[0];return(k,D,x)=>{if(k?.source!==U)return U[L](D,x,k)}}else return(U,k,D)=>{let x=[];for(let G of N){if(U?.source===G)break;x.push(G[L](k,D,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,U,k)=>{if(!N?.source)return y[L](U,k,N)}},"getApplyToCanonicalSource");return Ge={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ne={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let L=!1,N=a(async(U,k)=>{let D=U.value,x=U.table?ct[c][U.table]:Je;if(c===$n.SYSTEM_SCHEMA_NAME&&(U.table===$n.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===$n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!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 G=await x.getResource(U.id,k,ic);switch(U.type){case"put":return G._writeUpdate(D,!0,ic);case"patch":return G._writeUpdate(D,!1,ic);case"delete":return G._writeDelete(ic);case"publish":return G._writePublish(D,ic);case"invalidate":return G.invalidate(ic);default:it.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let k=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,D=U&&k&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){it.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{N(G,x);continue}if(G.type==="end_txn")continue;let me=Ze(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ue){throw ue.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ue}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ue of G.attributes)te.find(qe=>qe.name===ue.name)||(te.push(ue),Pe=!0);Pe&&(Et({table:s,database:c,attributes:te,origin:"cluster"}),kl.signalSchemaChange(new Vl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(te=>{x.resolve=te})):N(G,G)});L&&(await me,kl.signalUserChange(new Vl.UserEventMsg(process.pid))),G.onCommit&&(me?.then?me.then(G.onCommit):G.onCommit())}catch(se){it.error("error in subscription handler",se)}}}catch(U){it.error(U)}})(),this}static getResource(m,A,w){let y=super.getResource(m,A,w);if(m!=null){lc(m);try{if(y.hasOwnProperty(de))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!w?.async||i.cache?.get(m),L=On(A),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ih(m,A,{transaction:N},O,U=>{if(U?ah(y,U):y[de]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let k=wh(m,U,A,y);if(k)return L?.disregardReadTxn(),y[VA]=!0,YA(k,D=>(ah(y,D),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=wh(this[Le],this[Lr],this[ye]);if(m)return this[VA]=!0,YA(m,A=>{this[Lr]=A,this[de]=A.value,this[ql]=A.version})}static setTTLExpiration(m){if(typeof m=="number")E=m*1e3,f||(f=0);else if(m&&typeof m=="object")E=m.expiration*1e3,f=(m.eviction||0)*1e3,ve=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");ve=ve||(E+f)/4,Dh()}static enableAuditing(m=!0){h=m,m&&dO(),Je.audit=m}static coerceId(m){return m===""?null:oh(m,H)}static async dropTable(){if(delete ct[c][s],c===o){for(let m of S)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));kl.signalSchemaChange(new Vl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[kn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let A=Je.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let w=n_(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,O=A?.select;if(y?.length>0||uO&&O){if(A||(A={}),O){let L=y?.length>0&&$A(y,"read");A.select=O.map(N=>{let U=N.name||N;if(!L||L[U]){let k=Js[U]?.definition?.tableClass;if(k){if(N.name||(N={name:N}),!k.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(L=>L.read&&!Js[L.attribute_name]).map(L=>L.attribute_name);return A}else return!0}}allowUpdate(m,A){let w=n_(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let O=$A(y,"update");for(let L in A)if(!O[L])return!1;for(let L of y){let N=L.attribute_name;!L.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[kn]){let w=n_(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let O=$A(y,"insert");for(let L in A)if(!O[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return n_(m)?.delete}update(m,A){if(!On(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[de]={},this[Nt]=m):(y=this[Nt],y&&(m=Object.assign(y,m)),this[Nt]=y=m)),this._writeUpdate(this[Nt],A),this}addTo(m,A){if(typeof A=="number"||typeof A=="bigint")this[Bl]===OG?this.set(m,(+this.getProperty(m)||0)+A):(this[Bl]||this.update(),this.set(m,new rh(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Lr]}invalidate(m){let A=this[ye],w=this[Le];lc(w),On(this[ye]).addWrite({key:w,store:i,invalidated:!0,entry:this[Lr],nodeName:this[ye]?.nodeName,before:Ge.invalidate?.bind(this,A,w),beforeIntermediate:Ne.invalidate?.bind(this,A,w),commit:(O,L)=>{if(L?.version>O)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(w,N,this[Lr],O,Hl,h,this[ye],0,"invalidate")}})}static evict(m,A,w){let y=this.Source,O;if(!((C||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==w))){if(C){if(i.hasLock(m,O.version))return;let L;for(let N in r)L||(L={}),L[N]=A[N];if(L)return T(m,L,O,w,xl,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{r_(m,A,null)}),h?T(m,null,O,w,xl,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,CG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,w){let y=this[ye],O=On(y),L=this[Le];lc(L);let N=this[Lr];this[Bl]=A?OG:zie;let U={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:k=>{m||(m=this[Nt]),A||m&&eh(this[Nt]===m?this:m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),M&&(m[M.name]=M.type==="Date"?new Date(k):M.type==="String"?new Date(k).toISOString():k),A&&(t&&m[t]!==L&&(m[t]=L),F&&(N?.value?m[F.name]=N?.value[F.name]:m[F.name]=F.type==="Date"?new Date(k):F.type==="String"?new Date(k).toISOString():k),m=Po(m))):O.removeWrite(U)},before:A?Ge.put?()=>Ge.put(y,L,m):null:Ge.patch?()=>Ge.patch(y,L,m):Ge.put?()=>Ge.put(y,L,Po(this)):null,beforeIntermediate:A?Ne.put?()=>Ne.put(y,L,m):null:Ne.patch?()=>Ne.patch(y,L,m):Ne.put?()=>Ne.put(y,L,Po(this)):null,commit:(k,D,x)=>{if(x){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Lr]=D,D?.value?.[de])throw new Error("Can not assign a record to a record, check for circular references");A||(this[de]=D?.value??null)}this[Nt]=void 0,this[ql]=k;let G=D?.value,se=m;if(this[Bl]=0,D?.version>=k)if(h){let ue=D.localTime,qe=D.version;for(;se&&(ue>k||qe>=k&&ue>0);){let re=u.get(ue);if(!re)break;let X=vt(re);if(qe=X.version,qe>k){if(X.type==="patch"){let pe=X.getValue(i);se=XE(se,pe)}else if(X.type==="put"||X.type==="delete")return}else if(qe===k)return;ue=X.previousLocalTime}}else{if(A)return;se=XE(se,G)}let me;if(A?me=se:(this[de]=G,me=A?se:Po(this,se)),this[de]=me,me?.[de])throw new Error("Can not assign a record to a record, check for circular references");let te;A||(te=m),r_(L,G,me);let Pe=A?"put":"patch";T(L,me,D,k,0,h,y,y.expiresAt||(E?E+Date.now():0),Pe,!1,te)}};O.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[kn]){for await(let A of this.search(m))(await Je.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let A=On(this[ye]),w=this[Le];lc(w);let y=this[ye];return A.addWrite({key:w,store:i,resource:this,nodeName:y?.nodeName,before:Ge.delete?.bind(this,y,w),beforeIntermediate:Ne.delete?.bind(this,y,w),commit:(O,L,N)=>{let U=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),ah(this,L)),!(L?.version>O)&&(r_(this[Le],U),it.trace("Write delete entry",w,O),h||p?(T(w,null,this[Lr],O,0,h,this[ye],0,"delete"),h||Dh()):i.remove(this[Le]))}}),!0}search(m){let A=this[ye],w=On(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(y=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(y));let O,L={};function N(X,pe){let Be;switch(pe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}let Yn=Be&&{},js;for(let Ke of X){if(Ke.conditions){Ke.conditions=N(Ke.conditions,Ke.operator);continue}let kt=Ke[0]??Ke.attribute,on=kt==null?H:qs(S,kt);if(on){if(Be){let Kn=xn(kt),Vt=Yn[Kn];Vt?(Vt.push(Ke),js=!0):Yn[Kn]=[Ke]}(on.type||Wg[Ke.comparator])&&(Ke[1]===void 0?Ke.value=k(Ke.value,on):Ke[1]=k(Ke[1],on))}else if(kt!=null)throw(0,rn.handleHDBError)(new Error,`${kt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(js)for(let Ke in Yn){let kt=Yn[Ke],on=kt.length;if(on>1)for(let Kn=0;Kn<on;Kn++){let Vt=kt[Kn];if(Vt.comparator==="ge"||Vt.comparator==="greater_than_equal")for(let Xs=0;Xs<on;Xs++){let qo=kt[Xs];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(Vt.comparator="between",Vt.value=[Vt.value,qo.value],X.splice(X.indexOf(qo),1))}if(Vt.comparator==="equals"||!Vt.comparator){for(let Xs=0;Xs<on;Xs++)if(Xs!==Kn){let qo=kt[Xs];X.splice(X.indexOf(qo),1)}break}}}return X}a(N,"prepareConditions");function U(X,pe){if(m.enforceExecutionOrder)return X;for(let Be of X)Be.conditions&&(Be.conditions=U(Be.conditions,Be.operator));return X.length>1&&pe!=="or"?(0,wG.sortBy)(X,Xf(Je)):X}a(U,"orderConditions");function k(X,pe){return Array.isArray(X)?X.map(Be=>oh(Be,pe)):oh(X,pe)}a(k,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let x=typeof m.sort=="object"&&m.sort,G;if(x&&D!=="or"){let X=x.attribute;if(O=y.find(pe=>xn(pe.attribute)===xn(X)),!O){let pe=qs(S,X);if(!pe)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(pe.indexed)O={attribute:X,comparator:"sort"},y.push(O);else if(y.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}O&&(O.descending=!!x.descending)}y=U(y,D),x&&(O&&y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:D,postOrdering:G,selectApplied:!!se};let me=w.useReadTxn(),te=Qg(y,D,Je,me,m,A,(X,pe)=>lO(X,se,A,me,pe),L),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ue=Je.transformEntryForSelect(se,A,me,L,Pe,!0),qe=Je.transformToOrderedSelect(te,se,G,me,A,ue);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(qe=re(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(se){let X=[];for(let pe of se)pe==="*"?X.push(...S.map(Be=>Be.name)):X.push(pe.name||pe);return X}return S.map(X=>X.name)},qe}static transformToOrderedSelect(m,A,w,y,O,L){let N=new yq;if(w){m=lO(m,A,y,O,null);let U;N.iterate=function(){let D,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,me,te,Pe=!0;function ue(re){let X=re.next&&ue(re.next),pe=re.descending;return(Be,Yn)=>{let js=Ch(Be,re.attribute,y),Ke=Ch(Yn,re.attribute,y),kt=pe?(0,Bo.compareKeys)(Ke,js):(0,Bo.compareKeys)(js,Ke);return kt===0?X?.(Be,Yn)||0:kt}}a(ue,"createComparator");let qe=ue(w);return{async next(){let re;if(D)if(re=D.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await L.call(this,re.value)};U=[],me&&U.push(me);do if(re=await x.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let pe=Ch(X,se,y);if(Pe)Pe=!1,te=pe;else if(pe!==te){te=pe,me=X;break}}U.push(X)}while(!0);return w.isGrouped,U.sort(qe),D=U[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let k=a(D=>{if(typeof A=="object"&&Array.isArray(D.attribute))for(let x=0;x<A.length;x++){let G=A[x],se;if(G.name===D.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=D.attribute.slice(1),se.descending=D.descending}else G===D.attribute[0]&&(A[x]=se={name:G,sort:{attribute:D.attribute.slice(1),descending:D.descending}})}D.next&&k(D.next)},"applySortingOnSelect");k(w)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(L);return N}static transformEntryForSelect(m,A,w,y,O,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let D=a(x=>(A?.transaction?.stale&&(A.transaction.stale=!1),x?.key??x),"transform");return m===t?D:m.asArray?x=>[D(x)]:x=>({[t]:D(x)})}let N;O&&C&&!m?.every(D=>{let x;return typeof D=="object"?x=D.name:x=D,r[x]||x===t})&&(N=!0);let U,k=a(function(D){let x;if(A?.transaction?.stale&&(A.transaction.stale=!1),D!=null){if(yh=D,x=D.value||D.deref?.(),!x&&(D.key===void 0||D.deref)){if(D=Ih(D.key??D,A,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(k.bind(this));x=D?.value}if(N&&(D.metadataFlags&(Hl|xl)||D.expiresAt&&D.expiresAt<Date.now())){let G=wh(D.key??D,D,A);if(G?.then)return G.then(k)}}if(x==null)return L?Uo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ue;typeof te=="object"?ue=te.name:ue=te;let qe=Js?.[ue],re;if(qe){let X=y?.[ue];if(X)if(X.hasMappings){let Be=qe.from?x[qe.from]:xn(D.key);re=X.get(Be),re||(re=[])}else re=X.fromRecord?.(x);else re=qe(x,A,D);let pe=a(Be=>{if(Be&&typeof Be=="object"){let Yn=qe.definition?.tableClass||Je;U||(U={});let js=U[ue]||(U[ue]=Yn.transformEntryForSelect(ue===te?null:te.select||(Array.isArray(te)?te:null),A,w,X,O));if(Array.isArray(Be)){let Ke=[],kt=Yn.transformToOrderedSelect(Be,te.select,typeof te.sort=="object"&&te.sort,A,w,js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(Vt=>{for(;!Vt.done;){if(Vt?.then)return Vt.then(on);Ke.push(Vt.value),Vt=kt.next()}Pe(Ke,ue)},"nextValue"),Kn=on(kt.next());Kn&&(G||(G=[]),G.push(Kn));return}else if(Be=js.call(this,Be),Be?.then){G||(G=[]),G.push(Be.then(Ke=>Pe(Ke,ue)));return}}Pe(Be,ue)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(pe))):pe(re);return}else re=x[ue],re&&typeof re=="object"&&ue!==te&&(re=Je.transformEntryForSelect(te.select||te,A,w,null)({value:re}));Pe(re,ue)},"selectAttribute"),me;if(typeof m=="string")se(m,te=>{me=te});else if(Array.isArray(m))if(m.asArray)me=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=x:se(te,ue=>me[Pe]=ue)});else{me={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ue in x)me[ue]=x[ue];else se(Pe,(ue,qe)=>{ue===void 0&&te&&(ue=null),me[qe]=ue})}else throw new rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>me):me}return x},"transform");return k}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||Et({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,w=TG(Je,this[Le]??null,function(N,U,k,D){try{let x=U.getValue?.(i,A);if(!x&&U.type==="patch"&&A){let G=i.getEntry(N);G?.version===U.version?x=G.value:x=U.getValue?.(i,!0,k),U.type="put"}this.send({id:N,timestamp:k,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){it.error(x)}},m.startTime||0,m);this[kn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let y=this[Le],O=m.previousCount;O>1e3&&(O=1e3);let L=m.startTime;if(this[kn]){if(L){if(O)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:L,exclusiveStart:!0})){let k=vt(U);if(k.tableId!==n)continue;let D=k.recordId;if(y==null||NG(y,D)){let x=k.getValue(i,A,N);w.send({id:D,timestamp:N,value:x,version:k.version,type:k.type})}w.startTime=N}}else if(O){let N=[];for(let{key:U,value:k}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=vt(k);if(D.tableId!==n)continue;let x=D.recordId;if(y==null||NG(y,x)){let G=D.getValue(i,A,U);if(N.push({id:x,timestamp:U,value:G,version:D.version,type:D.type}),--O<=0)break}}catch(D){it.error("Error getting history entry",U,D)}for(let U=N.length;U>0;)w.send(N[--U]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:k,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&w.send({id:N,timestamp:D,value:U,version:k,type:"put"})}else{O&&!L&&(L=0);let N=this[Lr]?.localTime;if(N===Sm&&(i.cache?.delete(y),this[Lr]=i.getEntry(y),it.trace("re-retrieved record",N,this[Lr]?.localTime),N=this[Lr]?.localTime),it.trace("Subscription from",L,"from",y,N),L<N){let U=[],k=N;do{let D=u.get(k);if(D){m.omitCurrent=!0;let x=vt(D),G=x.getValue(i,A,k);A&&(x.type="put"),U.push({id:y,value:G,timestamp:k,...x}),k=x.previousLocalTime}else break;O&&O--}while(k>L&&O!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this[de],version:this[ql],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[Bl])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let w=On(this[ye]),y=this[Le]||null;lc(y);let O=this[ye];w.addWrite({key:y,store:i,entry:this[Lr],nodeName:O?.nodeName,validate:()=>{O?.source||(w.checkOverloaded(),this.validate(m))},before:Ge.publish?.bind(this,O,y,m),beforeIntermediate:Ne.publish?.bind(this,O,y,m),commit:(L,N,U)=>{N===void 0&&p&&!h&&Dh(),T(y,N?.value??null,N,N?.version||L,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let w,y=a((O,L,N)=>{if(L.type&&O!=null)if(A&&O.__op__&&(O=O.value),L.properties){typeof O!="object"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let U=L.properties;for(let k=0,D=U.length;k<D;k++){let x=U[k],G=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(L.sealed&&O!=null&&typeof O=="object")for(let k in O)U.find(D=>D.name===k)||(w||(w=[])).push(`Property ${k} is not allowed within object in property ${N}`)}else switch(L.type){case"Int":(typeof O!="number"||O>>0!==O)&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(L.elements)for(let U=0,k=O.length;U<k;U++){let D=O[U],x=y(D,L.elements,N+"[*]");x&&(O[U]=x)}}else(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Buffer or Uint8Array`);break}L.nullable===!1&&O==null&&(w||(w=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,L=S.length;O<L;O++){let N=S[O];if(!N.relationship&&(!A||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let O in m)S.find(L=>L.name===O)||(w||(w=[])).push(`Property ${O} is not allowed`);if(w)throw new rn.ClientError(w.join(". "))}getUpdatedTime(){return this[ql]}wasLoadedFromSource(){return C?!!this[VA]:void 0}static async addAttributes(m){let A=S.slice(0);for(let w of m){if(!w.name)throw new rn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(w)}return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static async removeAttributes(m){let A=S.filter(w=>!m.includes(w.name));return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,w=5e3,y=1e3,O;A>w&&!m?.exactCount&&(O=y);let L=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&L++;if(O){let N=L;L=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&L++;let U=O*2,k=(L+N)/U,D=Math.pow((L-N+1)/O/2,2)+k*(1-k)/U,x=Math.max(Math.sqrt(D)*A,1),G=Math.round(k*A),se=Math.max(G-1.96*x,0),me=Math.min(G+1.96*x,A),te=Math.pow(10,Math.round(Math.log10(x)));return te>G&&(te=te/10),L=Math.round(G/te)*te,{recordCount:L,estimatedRange:[Math.round(se),Math.round(me)]}}return{recordCount:L}}static updatedAttributes(){Js=this.propertyResolvers={$id:(m,A,w)=>({value:w.key}),$updatedtime:(m,A,w)=>w.version,$record:(m,A,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),uO=!0,A.to)m.elements?.definition?(Js[m.name]=m.resolve=(w,y,O)=>{let L=w[A.from?A.from:t],N=m.elements.definition.tableClass;return O?xa({attribute:A.to,value:L},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:L}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let w=m.definition||m.elements?.definition;w?(Js[m.name]=m.resolve=(y,O,L)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let U,k=N.map(D=>{let x=L?w.tableClass.primaryStore.getEntry(D,{transaction:On(O).getReadTxn()}):w.tableClass.get(D,O);return x?.then&&(U=!0),x});return A.filterMissing?U?Promise.all(k).then(D=>D.filter(IG)):k.filter(IG):U?Promise.all(k):k}return L?w.tableClass.primaryStore.getEntry(N,{transaction:On(O).getReadTxn()}):w.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let L=O.map(N=>N[Le]||N[w.tableClass.primaryKey]);y[A.from]=L}else{let L=O[Le]||O[w.tableClass.primaryKey];y[A.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}nh(this,this)}static async deleteHistory(m=0){let A;for(let{key:w,value:y}of u.getRange({start:0,end:m}))await Gl(),vt(y).tableId===n&&(A=u.remove(w));await A}static async*getHistory(m=0,A=1/0){for(let{key:w,value:y}of u.getRange({start:m,end:A})){await Gl();let O=vt(y);O.tableId===n&&(yield{id:O.recordId,localTime:w,version:O.version,type:O.type,value:O.getValue(i,!0,w),user:O.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return A;let y=w.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await Gl();let L=u.get(y);if(L){let N=vt(L);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){J?.remove()}}Je.updatedAttributes();let wq=Je.prototype;return wq[Qie]=!0,E&&Je.setTTLExpiration(E/1e3),Q&&Cq(),Je;function r_(K,m,A){let w;for(let y in r){let O=r[y],L=O.isIndexing,N=A?.[y],U=m?.[y];if(N===U&&!L)continue;w=!0;let k=O.indexNulls,D=(0,Fl.getIndexedValues)(N,k),x=(0,Fl.getIndexedValues)(U,k);if(x?.length>0){let G=new Set(x);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||D.length>0)&&AG){let se=x.concat(D).map(me=>({key:me,value:K}));O.prefetch(se,yG)}for(let se=0,me=x.length;se<me;se++)O.remove(x[se],K)}else D?.length>0&&AG&&O.prefetch(D.map(G=>({key:G,value:K})),yG);if(D)for(let G=0,se=D.length;G<se;G++)O.put(D[G],K)}return w}a(r_,"updateIndices");function lc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>bG)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Bo.writeKey)(K,Jie,0)>bG)throw new Error("Primary key size is too large: "+K.length);return!0}a(lc,"checkValidId");function Ih(K,m,A,w,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let L=i.getEntry(K,A);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,K)},"whenPrefetched");return w?O():ce>0?(ce--,O()):new Promise((L,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),k()})):(j.push(K),ae.push(k),j.length>Iq&&(ce--,U()));function U(){if(j.length>0){let D=ae;i.prefetch(j,()=>{ce===-1?U():ce++;for(let x of D)x()}),j=[],ae=[],ge>2&&ge--}else ce=ge,ge<Nq&&ge++}a(U,"prefetch");function k(){try{L(O())}catch(D){N(D)}}a(k,"load")})}a(Ih,"loadLocalRecord");function n_(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return jie;let A=m[c],w,y=A?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(n_,"getTablePermissions");function wh(K,m,A,w){if(C){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Hl|xl)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Wr(!y,"cache-hit",s)),y){let O=_O(K,m,A).then(L=>(L?.value?.[de]&&it.error("Can not assign a record with a record property"),A&&(L?.version>(A.lastModified||0)&&(A.lastModified=L.version),A.lastRefreshed=Date.now()),L));if(A?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,K)){if(O.catch(L=>it.warn(L)),A?.onlyIfCached&&!w.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return O}}}a(wh,"ensureLoadedFromSource");function On(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new ro,m.lmdbDb=i,m;m=A}while(!0)}else return new hd}a(On,"txnForContext");function Ch(K,m,A){if(!K)return;yh=K;let w=K.value||K.deref?.()||(yh=i.getEntry(K.key))?.value;if(typeof m=="object"){let O=Js,L=w;for(let N=0,U=m.length;N<U;N++){let k=m[N],D=O?.[k];L=D&&L?D(L,A,!0)?.value:L?.[k],O=D?.definition?.tableClass?.propertyResolvers}return L}let y=Js[m];return y?y(w,A):w[m]}a(Ch,"getAttributeValue");function lO(K,m,A,w,y){let O=y?.length,L={transaction:w,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(k,D){let x=k?.value;if(!x)return Uo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,k))return Uo.SKIP;return D!==void 0&&(k.key=D),k}if(a(U,"processEntry"),O>0||!K.hasEntries){let k=K.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return O>0?U(D):D;if(D==null)return Uo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(D))return Uo.SKIP;N||(N=[]),N.push(x)}}return Ih(D,A,L,!1,U)});return Array.isArray(K)&&(k=k.filter(D=>D!==Uo.SKIP)),k.hasEntries=!0,k}return K}a(lO,"transformToEntries");async function _O(K,m,A){let w=m?.metadataFlags,y=m?.version,O,L;if(!i.attemptLock(K,y,()=>{clearTimeout(L);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(Hl|xl)?O(_O(K,i.getEntry(K),A)):O(D)}))return new Promise(D=>{O=D,L=setTimeout(()=>{i.unlock(K,y)},Wie)});let N=m?.value,U={requestContext:A,replacingRecord:N,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:A?.resourceCache},k=A?.responseHeaders;return new Promise((D,x)=>{let G;YA(Ze(U,async se=>{let me=performance.now(),te,Pe,ue;try{for(let pe of Je.sources)if(pe.get&&(!pe.get.reliesOnPrototype||pe.prototype.get)&&(U.source=pe,te=await pe.get(K,U),te))break;ue=w&Hl;let re=U.lastModified||ue&&y;Pe=ue||re>y||!N,re||(re=(0,Fl.getNextMonotonicTime)());let X=performance.now()-me;if(Sr(X,"cache-resolution",s),k&&mg(k,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,E&&!U.expiresAt&&(U.expiresAt=Date.now()+E),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}G=!0,D({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(D({version:y,value:N}),it.trace(re.message,"(returned stale record)")):x(re),U.transaction.abort();return}if(A?.noCacheStore||U.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let pe=r_(K,N,te);te?(Ne.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ue)):(Ne.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ue):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&it.error("Error committing cache update",se)})})}a(_O,"getFromSource");function Dh(){if(ve!==e_&&(e_=ve,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(t_&&clearTimeout(t_),!ve)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/ve)*ve+K.getTime(),A=a(w=>{it.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),t_=setTimeout(()=>v=v.then(async()=>{if(A(Math.max(w+ve,Date.now())),i.rootStore.status!=="open"){clearTimeout(t_);return}let y=50,O=new Array(y),L=0;it.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:k,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;k===null&&!h&&D+Kie<Date.now()?G=i.remove(U,D):x&&x+f<Date.now()&&(G=Je.evict(U,k,D),N++),G&&(await O[L],O[L]=G.catch(se=>{it.error("Cleanup error",se)}),++L>=y&&(L=0)),await Gl()}it.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){it.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Dh,"scheduleCleanup");function dO(){J=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(dO,"addDeleteRemoval");function Cq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!Nh){Nh=!0;try{let K=Q.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(A)){let y=i.getEntry(w);y?.value?y.value[K]<Date.now()&&Je.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(A,w))}await Gl()}}catch(K){it.error("Error in evicting old records",K)}finally{Nh=!1}}},Yie).unref()}a(Cq,"runRecordExpirationEviction")}function $A(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function yG(){}function Xie(e){CG=e}function oh(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:(Zie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,ch.autoCast)(e):e}function NG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function YA(e,t,r){return e?.then?e.then(t,r):t(e)}function ah(e,t){e[Lr]=t,e[de]=t?.value??null,e[ql]=t?.version}function IG(e){return e!=null}function Vn(e){try{return JSON.stringify(e)}catch{return e}}var $n,Uo,Fl,wG,$l,rn,kl,Vl,it,Bo,vo,ch,$ie,CG,Yie,Kie,AG,Wie,ql,Qie,Lr,Bl,OG,zie,VA,ic,Hl,xl,Jie,bG,jie,TTe,Zie,Gl,EE=Re(()=>{$n=B(P()),Uo=require("lmdb"),Fl=B(vr()),wG=require("lodash");Nn();cS();$l=B(Z());RG();rn=B(ne()),kl=B(ys()),Vl=B(Mn());Ae();eE();it=B($());Sd();no();Bo=require("ordered-binary"),vo=B(We());ri();ch=B(z());Mc();Cs();JE();Xu();$ie=new Uint8Array(9);$ie[8]=192;Yie=6e4,Kie=864e5;$l.initSync();AG=$l.get($n.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Wie=1e4,ql=Symbol.for("version"),Qie=Symbol.for("incremental-update"),Lr=Symbol("entry"),Bl=Symbol("is-saving"),OG=1,zie=2,VA=Symbol("loaded-from-source"),ic={isNotification:!0,ensureLoaded:!1},Hl=1,xl=8,Jie=Buffer.allocUnsafeSlow(8192),bG=1978,jie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},TTe=(0,ch.convertToMS)($l.get($n.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(uh,"makeTable");a($A,"attributesAsObject");a(yG,"noop");a(Xie,"setServerUtilities");Zie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(oh,"coerceType");a(NG,"isDescendantId");Gl=a(()=>new Promise(setImmediate),"rest");a(YA,"when");a(ah,"updateResource");a(IG,"exists");a(Vn,"stringify")});var ke={};Fe(ke,{database:()=>ca,databases:()=>ct,dropDatabase:()=>fS,dropTableMeta:()=>soe,getDatabases:()=>mr,getDefaultCompression:()=>Af,getTables:()=>eoe,onUpdatedTable:()=>eA,readMetaDb:()=>Yl,resetDatabases:()=>$u,table:()=>Et,tables:()=>Br});function eoe(){return Eh||mr(),Br||{}}function mr(){if(Eh)return ct;Eh=!0,cc=new Map;let e=(0,St.getHdbBasePath)()&&(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),t=(0,St.get)(Ut.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,ot.basename)(r.name,".mdb");r.isFile()&&(0,ot.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Yl((0,ot.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,ac.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,ac.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,ot.join)((0,ac.getBaseSchemaPath)(),r.name),s=(0,ot.join)((0,ac.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,ot.extname)(i.name).toLowerCase()===".mdb"){let o=(0,ot.join)(s,i.name);Yl((0,ot.join)(n,i.name),(0,ot.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,ot.extname)(o.name).toLowerCase()===".mdb"&&Yl((0,ot.join)(s,o.name),(0,ot.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,ot.join)(c.path,(0,ot.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Yl(u,o,r,null,!0)}}for(let r in ct){let n=cc.get(r);if(n){let s=ct[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete ct[r],r==="data"){for(let s in Br)delete Br[s];delete Br[hh]}}return cc=null,ct}}function $u(){Eh=!1;for(let[,e]of vi)e.needsDeletion=!0;mr();for(let[e,t]of vi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),vi.delete(e));return ct}function Yl(e,t,r=QA,n,s){let i=new KA.default(e,!1);try{let o=vi.get(e);o?o.needsDeletion=!1:(o=(0,_h.open)(i),vi.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(lh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,_h.open)(i),_.isLegacy=!0):_=zE(o));let l=PG(r),d=l[hh],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[p,S]=f.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let T=E.get(p);T||E.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let j of p)if(j.is_hash_attribute||j.isPrimaryKey){S=j;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],R={},b=[],C,H,v=typeof S.audit=="boolean"?S.audit:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),F=S.trackDeletes,M=S.expiration,Q=S.eviction,J=S.sealed;if(T)R=T.indices,b=T.attributes,T.schemaVersion++;else{C=S.tableId,C?C>=(u.get(oc)||0)&&u.putSync(oc,C+1):(S.tableId=C=u.get(oc),C||(C=1),u.putSync(oc,C+1),u.putSync(S.key,S));let j=new Ho.default(!S.is_hash_attribute,S.is_hash_attribute);if(j.compression=S.compression,j.compression){let ae=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||MG;j.compression.threshold=ae}H=A_(o.openDB(S.key,j)),H.rootStore=o,H.tableId=C}for(let j of p){j.attribute=j.name;try{if(!j.is_hash_attribute&&(j.indexed||j.attribute&&!j.name)){if(!R[j.name]){let ce=new Ho.default(!j.is_hash_attribute,j.is_hash_attribute);R[j.name]=o.openDB(j.key,ce),R[j.name].indexNulls=j.indexNulls}let ae=b.find(ce=>ce.name===j.name);ae?b.splice(b.indexOf(ae),1,j):b.push(j)}}catch(ae){An.error("Error trying to update attribute",j,b,R,ae)}}if(!T){T=UG(l,f,uh({primaryStore:H,auditStore:_,audit:v,sealed:J,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:F,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let j of zA)j(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function PG(e){let t=ct[e];if(t||(e==="data"?t=ct[e]=Br:e==="system"?Object.defineProperty(ct,"system",{value:t=Object.create(null),configurable:!0}):t=ct[e]=Object.create(null)),cc&&!cc.has(e)){let r=new Set;t[hh]=r,cc.set(e,r)}return t}function UG(e,t,r){return e[t]=r,r}function ca({database:e,table:t}){e||(e=QA),mr();let r=PG(e),n=(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),s=(0,St.get)(Ut.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME));let o=(0,ot.join)(n,(i?t:e)+".mdb"),c=vi.get(o);if(!c){let u=new KA.default(o,!1);c=(0,_h.open)(u),vi.set(o,c)}return c}async function fS(e){if(!ct[e])throw new Error("Schema does not exist");let t=ct[e],r;for(let n in t)r=t[n].primaryStore.rootStore,vi.delete(r.path),r.status==="open"&&(await r.close(),await Kl.remove(r.path));if(r||(r=ca({database:e,table:null}),r.status==="open"&&(await r.close(),await Kl.remove(r.path))),e==="data"){for(let n in Br)delete Br[n];delete Br[hh]}delete ct[e]}function Et({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=QA);let d=ca({database:t,table:e}),E=ct[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let R=new Ho.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let b,C;if(f){if(h=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=d.auditStore;M||(M=zE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Af(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let Q=new Ho.default(!1,!0);Q.compression=p.compression;let J=e+"/",j=A_(d.openDB(J,Q));j.rootStore=d,T=d.dbisDb=d.openDB(lh.INTERNAL_DBIS_NAME,R),j.tableId=T.get(oc),j.tableId||(j.tableId=1),T.putSync(oc,j.tableId+1),p.tableId=j.tableId,f=UG(E,e,uh({primaryStore:j,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:j.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,b=!0,F(),T.put(J,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(lh.INTERNAL_DBIS_NAME,R)),f.dbisDB=T;let H=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[J,j]=M.toString().split("/");if(j===""&&(j=Q.name),j){if(J!==e)continue}else j=J;if(!i.find(ce=>ce.name===j)?.indexed&&Q.indexed&&!Q.isPrimaryKey){F(),b=!0,T.remove(M);let ce=f.indices[J];ce&&H.push(ce)}}let v=[];try{for(let M of i||[]){if(M.relationship)continue;let Q=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:Q,configurable:!0});let J=T.get(Q);if(M.isPrimaryKey){if(J=J||T.get(Q=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+J.expiration||void 0)||(+n||void 0)!==(+J.eviction||void 0)){let ae=Object.assign({},J);typeof o=="boolean"&&(o&&f.enableAuditing(o),ae.audit=o),r&&(ae.expiration=+r),n&&(ae.eviction=+n),c!==void 0&&(ae.sealed=c),b=!0,F(),T.put(Q,ae)}continue}J?.attribute&&!J.name&&(J.indexed=!0);let j=!J||J.type!==M.type||J.indexed!==M.indexed||J.nullable!==M.nullable||JSON.stringify(J.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(J.elements)!==JSON.stringify(M.elements);if(M.indexed){let ae=new Ho.default(!0,!1),ce=d.openDB(Q,ae);(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Wl.workerData?.restartNumber)&&(b=!0,F(),J=T.get(Q),(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Wl.workerData?.restartNumber)&&(b=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=J?.lastIndexedKey||!1,M.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ce}),v.push(M))),T.put(Q,M)),J?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ce.indexNulls=M.indexNulls,S[M.name]=ce}else j&&(b=!0,F(),T.put(Q,M))}}finally{C&&C()}if(b&&(f.schemaVersion++,f.updatedAttributes()),An.trace(`${e} table loading, running index`),v.length>0||H.length>0?f.indexingOperation=noe(f,v,H):b&&dh.signalSchemaChange(new fh.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,b)for(let M of zA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),f;function F(){C||d.transactionSync(()=>({then(M){C=M}}))}a(F,"startTxn")}async function noe(e,t,r){try{let n=e.schemaVersion;await dh.signalSchemaChange(new fh.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,DG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,An.error(E)}),Wl.workerData&&Wl.workerData.restartNumber!==LG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>toe?await s:u>roe&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await dh.signalSchemaChange(new fh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function soe({table:e,database:t}){let r=ca({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function eA(e){zA.push(e)}function Af(){let e=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||MG,n={startingOffset:32};return t&&(n.dictionary=Kl.readFileSync(t)),r&&(n.threshold=r),e&&n}var St,lh,_h,ot,nn,ac,Ho,KA,Ut,Kl,WA,DG,dh,fh,Wl,An,LG,QA,hh,MG,Br,ct,oc,zA,Eh,vi,cc,toe,roe,Ae=Re(()=>{St=B(Z()),lh=B(ft()),_h=require("lmdb"),ot=require("path"),nn=require("fs"),ac=B(je());EE();Ho=B(Pc()),KA=B(Uc()),Ut=B(P()),Kl=B(require("fs-extra")),WA=require("../index"),DG=B(vr()),dh=B(ys()),fh=B(Mn()),Wl=require("worker_threads"),An=B($()),LG=B(We());ri();Mc();QA="data",hh=Symbol("defined-tables"),MG=((0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,St.initSync)();Br=Object.create(null),ct=Object.create(null);(0,WA._assignPackageExport)("databases",ct);(0,WA._assignPackageExport)("tables",Br);oc=Symbol.for("next-table-id"),zA=[],vi=new Map;a(eoe,"getTables");a(mr,"getDatabases");a($u,"resetDatabases");a(Yl,"readMetaDb");a(PG,"ensureDB");a(UG,"setTable");a(ca,"database");a(fS,"dropDatabase");a(Et,"table");toe=1e3,roe=10;a(noe,"runIndexing");a(soe,"dropTableMeta");a(eA,"onUpdatedTable");a(Af,"getDefaultCompression")});var z=g((wTe,QG)=>{"use strict";var Bi=require("path"),GG=require("fs-extra"),Mr=$(),vG=require("fs-extra"),mh=require("os"),ioe=require("net"),ooe=require("recursive-iterator"),dt=P(),aoe=YO(),BG=require("papaparse"),ph=require("moment"),{inspect:coe}=require("util"),HG=require("is-number"),ITe=require("lodash"),uoe=require("minimist"),loe=require("https"),_oe=require("http"),{hdb_errors:Sh}=ne(),doe=/^((\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)))$/,qG=require("util").promisify(setTimeout),foe=100,Eoe=5,hoe="",moe=4,xG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};QG.exports={isEmpty:sn,isEmptyOrZeroLength:ms,arrayHasEmptyValues:Toe,arrayHasEmptyOrZeroLengthValues:goe,buildFolderPath:Roe,isBoolean:FG,errorizeMessage:poe,stripFileExtension:Ooe,autoCast:boe,autoCastJSON:kG,autoCastJSONDeep:jA,removeDir:yoe,compareVersions:Noe,isCompatibleDataVersion:Ioe,escapeRawValue:woe,unescapeValue:Coe,stringifyProps:Doe,timeoutPromise:Moe,isClusterOperation:Uoe,getClusterUser:Boe,checkGlobalSchemaTable:voe,getHomeDir:$G,getPropsFilePath:Loe,promisifyPapaParse:Hoe,removeBOM:YG,createEventPromise:xoe,checkProcessRunning:Goe,checkSchemaTableExist:qoe,checkSchemaExists:KG,checkTableExists:WG,getStartOfTomorrowInSeconds:Foe,getLimitKey:koe,isObject:Aoe,isNotEmptyAndHasValue:Soe,autoCasterIsNumberCheck:VG,backtickASTSchemaItems:Voe,isPortTaken:Poe,createForkArgs:$oe,autoCastBoolean:Yoe,async_set_timeout:qG,getTableHashAttribute:Koe,doesSchemaExist:Woe,doesTableExist:Qoe,stringifyObj:zoe,ms_to_time:Joe,changeExtension:joe,getEnvCliRootPath:XA,noBootFile:Xoe,httpRequest:Zoe,transformReq:eae,convertToMS:tae,PACKAGE_ROOT:dt.PACKAGE_ROOT};function poe(e){return e instanceof Error?e:new Error(e)}a(poe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function Soe(e){return!sn(e)&&(e||e===0||e===""||FG(e))}a(Soe,"isNotEmptyAndHasValue");function ms(e){return sn(e)||e.length===0||e.size===0}a(ms,"isEmptyOrZeroLength");function Toe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(Toe,"arrayHasEmptyValues");function goe(e){if(ms(e))return!0;for(let t=0;t<e.length;t++)if(ms(e[t]))return!0;return!1}a(goe,"arrayHasEmptyOrZeroLengthValues");function Roe(...e){try{return e.join(Bi.sep)}catch{console.error(e)}}a(Roe,"buildFolderPath");function FG(e){return sn(e)?!1:e===!0||e===!1}a(FG,"isBoolean");function Aoe(e){return sn(e)?!1:typeof e=="object"}a(Aoe,"isObject");function Ooe(e){return ms(e)?hoe:e.slice(0,-moe)}a(Ooe,"stripFileExtension");function boe(e){return sn(e)||e===""||typeof e!="string"?e:xG[e]!==void 0?xG[e]:VG(e)===!0?Number(e):doe.test(e)?new Date(e):e}a(boe,"autoCast");function kG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(kG,"autoCastJSON");function jA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=jA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=jA(r);n!==r&&(e[t]=n)}return e}else return kG(e)}a(jA,"autoCastJSONDeep");function VG(e){if(e.startsWith("0.")&&HG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&HG(e))}a(VG,"autoCasterIsNumberCheck");async function yoe(e){if(ms(e))throw new Error(`Directory path: ${e} does not exist`);try{await vG.emptyDir(e),await vG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(yoe,"removeDir");function Noe(e,t){if(ms(e)){Mr.info("Invalid current version sent as parameter.");return}if(ms(t)){Mr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(Noe,"compareVersions");function Ioe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Ioe,"isCompatibleDataVersion");function woe(e){if(sn(e))return e;let t=String(e);return t==="."?dt.UNICODE_PERIOD:t===".."?dt.UNICODE_PERIOD+dt.UNICODE_PERIOD:t.replace(dt.FORWARD_SLASH_REGEX,dt.UNICODE_FORWARD_SLASH)}a(woe,"escapeRawValue");function Coe(e){if(sn(e))return e;let t=String(e);return t===dt.UNICODE_PERIOD?".":t===dt.UNICODE_PERIOD+dt.UNICODE_PERIOD?"..":String(e).replace(dt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Coe,"unescapeValue");function Doe(e,t){if(sn(e))return Mr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+mh.EOL}!ms(n)&&n[0]===";"?r+=" "+n+s+mh.EOL:ms(n)||(r+=n+"="+s+mh.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Doe,"stringifyProps");function $G(){let e;try{e=mh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a($G,"getHomeDir");function Loe(){let e=Bi.join($G(),dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return GG.existsSync(e)||(e=Bi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Loe,"getPropsFilePath");function Moe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Moe,"timeoutPromise");async function Poe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=ioe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Poe,"isPortTaken");function Uoe(e){try{return dt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Uoe,"isClusterOperation");function voe(e,t){let r=(Ae(),ie(ke)).getDatabases();if(!r[e])return Sh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Sh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(voe,"checkGlobalSchemaTable");function Boe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||ms(e)){Mr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Boe,"getClusterUser");function Hoe(){BG.parsePromise=function(e,t,r){return new Promise(function(n,s){BG.parse(e,{header:!0,transformHeader:YG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Hoe,"promisifyPapaParse");function YG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(YG,"removeBOM");function xoe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${coe(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(xoe,"createEventPromise");async function Goe(e){let t=!0,r=0;do await qG(foe*r++),(await aoe.findPs(e)).length>0&&(t=!1);while(t&&r<Eoe);if(t)throw new Error(`process ${e} was not started`)}a(Goe,"checkProcessRunning");function qoe(e,t){let r=KG(e);if(r)return r;let n=WG(e,t);if(n)return n}a(qoe,"checkSchemaTableExist");function KG(e){let{getDatabases:t}=(Ae(),ie(ke));if(!t()[e])return Sh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(KG,"checkSchemaExists");function WG(e,t){let{getDatabases:r}=(Ae(),ie(ke));if(!r()[e][t])return Sh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(WG,"checkTableExists");function Foe(){let e=ph().utc().add(1,dt.MOMENT_DAYS_TAG).startOf(dt.MOMENT_DAYS_TAG).unix(),t=ph().utc().unix();return e-t}a(Foe,"getStartOfTomorrowInSeconds");function koe(){return ph().utc().format("DD-MM-YYYY")}a(koe,"getLimitKey");function Voe(e){try{let t=new ooe(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){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Voe,"backtickASTSchemaItems");function $oe(e){return[e]}a($oe,"createForkArgs");function Yoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Yoe,"autoCastBoolean");function Koe(e,t){let{getDatabases:r}=(Ae(),ie(ke)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Koe,"getTableHashAttribute");function Woe(e){let{getDatabases:t}=(Ae(),ie(ke));return t()[e]!==void 0}a(Woe,"doesSchemaExist");function Qoe(e,t){let{getDatabases:r}=(Ae(),ie(ke));return r()[e]?.[t]!==void 0}a(Qoe,"doesTableExist");function zoe(e){try{return JSON.stringify(e)}catch{return e}}a(zoe,"stringifyObj");function Joe(e){let t=ph.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(Joe,"ms_to_time");function joe(e,t){let r=Bi.basename(e,Bi.extname(e));return Bi.join(Bi.dirname(e),r+t)}a(joe,"changeExtension");function XA(){if(process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=uoe(process.argv);if(e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(XA,"getEnvCliRootPath");var JA;function Xoe(){if(JA)return JA;let e=XA();if(XA()&&GG.pathExistsSync(Bi.join(e,dt.HDB_CONFIG_FILE)))return JA=!0,!0}a(Xoe,"noBootFile");function Zoe(e,t){let r;return e.protocol==="http:"?r=_oe:r=loe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(Zoe,"httpRequest");function eae(e){if(!e.schema&&!e.database){e.schema=dt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(eae,"transformReq");function tae(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(tae,"convertToMS")});var Z=g((DTe,ZG)=>{"use strict";var ZA=require("fs-extra"),xo=require("path"),zG=require("os"),rae=require("properties-reader"),zl=$(),Ql=z(),le=P(),Th=Er(),nae="Error initializing environment manager",gh="BOOT_PROPS_FILE_PATH",JG=!1,sae={[le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Qs={};ZG.exports={BOOT_PROPS_FILE_PATH:gh,getHdbBasePath:iae,setHdbBasePath:oae,get:jG,initSync:cae,setProperty:Me,initTestEnvironment:lae,setCloneVar:uae};function iae(){return Qs[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(iae,"getHdbBasePath");function oae(e){Qs[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(oae,"setHdbBasePath");function jG(e){let t=Th.getConfigValue(e);return t===void 0?Qs[e]:t}a(jG,"get");function Me(e,t){sae[e]&&(Qs[e]=t),Th.updateConfigObject(e,t)}a(Me,"setProperty");function aae(){let e;try{e=Ql.getPropsFilePath(),ZA.accessSync(e,ZA.constants.F_OK|ZA.constants.R_OK),JG=!0;let t=rae(e);return Qs[le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(le.HDB_SETTINGS_NAMES.INSTALL_USER),Qs[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Qs[gh]=e,!0}catch{return zl.trace(`Environment manager found no properties file at ${e}`),!1}}a(aae,"doesPropFileExist");function cae(e=!1){try{(JG||aae()||Ql.noBootFile())&&!XG&&(Th.initConfig(e),Qs[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Th.getConfigValue(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){zl.error(nae),zl.error(t),console.error(t),process.exit(1)}}a(cae,"initSync");var XG=!1;function uae(e){XG=e}a(uae,"setCloneVar");function lae(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=xo.join(__dirname,"../../","unitTests");Qs[gh]=xo.join(u,"hdb_boot_properties.file"),Me(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Me(le.HDB_SETTINGS_NAMES.INSTALL_USER,zG.userInfo()?zG.userInfo().username:void 0),Me(le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Me(le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Me(le.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),s&&(Me(le.CONFIG_PARAMS.HTTP_SECUREPORT,jG(le.CONFIG_PARAMS.HTTP_PORT)),Me(le.CONFIG_PARAMS.HTTP_PORT,null)),Me(le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ql.isEmpty(i)?!1:i),Me(le.CONFIG_PARAMS.HTTP_CORS,Ql.isEmpty(i)?!1:i),Me(le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ql.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${gh}. Please check your boot props and settings files`;zl.fatal(r),zl.error(t)}}a(lae,"initTestEnvironment")});var sq=g((MTe,nq)=>{"use strict";var rq=require("joi"),{string:Jl,boolean:eq,array:_ae}=rq.types(),tq=P(),dae=Xe();nq.exports=fae;function fae(e){let t=rq.object({operation:Jl.valid(tq.OPERATIONS_ENUM.ADD_NODE,tq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Jl.required(),subscriptions:_ae.items({schema:Jl.required(),table:Jl.optional(),hash_attribute:Jl.optional(),subscribe:eq.required(),publish:eq.required()}).min(1).required()});return dae.validateBySchema(e,t)}a(fae,"updateRemoteSourceValidator")});var jl=g((UTe,iq)=>{"use strict";var eO=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};iq.exports=eO});var uq=g((BTe,cq)=>{"use strict";var Eae=sq(),zs=$(),tO=Ve(),hae=P(),rO=dn(),Go=ut(),oq=Au(),mae=dd(),{Node:pae,NodeSubscription:aq}=Si(),nO=jl(),sO=z(),Sae=Z(),{cloneDeep:Tae}=require("lodash"),{broadcast:gae}=We();cq.exports=Rae;async function Rae(e){try{let t=Eae(e);if(t)return zs.error(`Validation error in updateRemoteSource: ${t.message}`),new nO(tO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=Tae(await rO.getNodeRecord(n)),c=!sO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&zs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!sO.doesSchemaExist(E)){zs.trace(`updateRemoteSource creating schema: ${E}`);try{await oq.createSchema({operation:"create_schema",schema:E})}catch(h){zs.error(h)}}if(f&&!sO.doesTableExist(E,f)){let h=new mae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),zs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await oq.createTable(h)}catch(p){zs.error(p)}}if(zs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new aq(E,f,d.publish,d.subscribe))}else i.push(new aq(E,f,d.publish,d.subscribe))}c||(o=new pae(n,i,void 0),zs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await rO.upsertNodeRecord(u),gae({type:"nats_update"}),new nO(tO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Sae.get(hae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await rO.getSystemInfo())}catch(t){zs.error(t);let r=t.message?t.message:t;return new nO(tO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Rae,"updateRemoteSource")});var fq=g((xTe,dq)=>{"use strict";var _q=require("joi"),{string:lq}=_q.types(),Aae=P(),Oae=Xe();dq.exports=bae;function bae(e){let t=_q.object({operation:lq.valid(Aae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:lq.required()});return Oae.validateBySchema(e,t)}a(bae,"removeRemoteSourceValidator")});var mq=g((qTe,hq)=>{"use strict";var yae=fq(),Rh=$(),Ah=Ve(),iO=P(),Nae=dn(),Iae=z(),Eq=ut(),wae=Z(),Oh=jl(),{NodeSubscription:Cae}=Si(),Dae=oa(),Lae=ai(),{broadcast:Mae}=We(),Pae=wae.get(iO.CONFIG_PARAMS.CLUSTERING_NODENAME);hq.exports=Uae;async function Uae(e){try{let t=yae(e);if(t)return Rh.error(`Validation error in removeRemoteSource: ${t.message}`),new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await Nae.getNodeRecord(r);if(Iae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return Rh.error(i),new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];Rh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Cae(c.schema,c.table,!1,!1);await Eq.updateConsumerIterator(c.schema,c.table,r,"stop"),await Eq.updateRemoteConsumer(u,r)}let s=new Dae(iO.SYSTEM_SCHEMA_NAME,iO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Lae.deleteRecord(s),Mae({type:"nats_update"}),new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Pae} successfully removed node '${r}'.`)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Uae,"removeRemoteSource")});var gq=g((kTe,Tq)=>{"use strict";var bh=$(),Xl=P(),pq=Ve(),oO=Z(),vae=z(),Sq=jl(),Bae=dn(),Hae=Vd(),xae=qr();Tq.exports=Gae;async function Gae(e){try{bh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=vae.ms_to_time(t),n=new qae(oO.get(Xl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),oO.get(Xl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??oO.get(Xl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Bae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new Hae(Xl.SYSTEM_SCHEMA_NAME,Xl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await xae.update(i)}catch(s){bh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return bh.trace("getRemoteSourceConfig response:",n),new Sq(pq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){bh.error(t);let r=t.message?t.message:t;return new Sq(pq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Gae,"getRemoteSourceConfig");function qae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(qae,"ConfigResponseObject")});var bq=g(($Te,Oq)=>{"use strict";var Rq=Z();Rq.initSync();var Aq=ut(),Zl=$(),uc=P(),aO=Ve(),Fae=uq(),kae=mq(),Vae=gq(),$ae=jl(),{encode:Yae,decode:Kae}=require("msgpackr"),Wae=bs(),Qae=Os(),zae=require("util"),Jae=P(),{isMainThread:jae,parentPort:Xae}=require("worker_threads");We();var Zae=zae.promisify(Wae.setSchemaDataToGlobal),cO=Rq.get(uc.CONFIG_PARAMS.CLUSTERING_NODENAME);Oq.exports=ece;async function ece(){try{Zl.notify("Starting reply service."),await Zae();let e=await Aq.getConnection(),t=`${cO}.__request__`,r=e.subscribe(t,{queue:cO});await tce(r)}catch(e){Zl.error(e)}}a(ece,"initialize");async function tce(e){for await(let t of e){let r=Kae(t.data),n;switch(r.operation){case uc.OPERATIONS_ENUM.ADD_NODE:case uc.OPERATIONS_ENUM.UPDATE_NODE:n=await Fae(r);break;case uc.OPERATIONS_ENUM.REMOVE_NODE:n=await kae(r);break;case uc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Vae(r);break;case uc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await rce();break;default:let s=`node '${cO}' reply service received unrecognized request operation`;Zl.error(s),n=new $ae(aO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Zl.trace(n),t.respond(Yae(n))}}a(tce,"handleRequest");async function rce(){try{return{status:aO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Qae.describeAll()}}catch(e){return Zl.error(e),{status:aO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(rce,"getRemoteDescribeAll");jae||Xae.on("message",async e=>{let{type:t}=e;t===Jae.ITC_EVENT_TYPES.SHUTDOWN&&Aq.closeConnection()})});var nce=bq();(async()=>{try{await nce()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();