harperdb 4.5.12 → 4.5.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +2 -2
- package/bin/lite.js +23 -23
- package/launchServiceScripts/launchNatsIngestService.js +23 -23
- package/launchServiceScripts/launchNatsReplyService.js +2 -2
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +24 -24
- package/npm-shrinkwrap.json +38 -31
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +2 -2
- package/server/threads/threadServer.js +24 -24
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.f785c076.js → main.0bd2b3d8.js} +2 -2
- package/utility/scripts/restartHdb.js +25 -25
- /package/studio/build-local/static/js/{main.f785c076.js.LICENSE.txt → main.0bd2b3d8.js.LICENSE.txt} +0 -0
package/bin/harperdb.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
`+JSON.stringify(u)),u.cause&&(t[c--]=u.cause,u&&(n+=`
|
|
6
6
|
Caused by:`));else if(typeof u=="object")try{n+=JSON.stringify(u)}catch{n+="Object ["+Object.keys(u)+"]"}else n+=u;c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
7
7
|
`}a(Js,"createLogRecord");function If(e){if(Ri){if(DD(e),gs){_a=!1;try{process.stdout.write(e)}finally{_a=!0}}}else gs&&process.stdout.write(e)}a(If,"logStdOut");function _m(e){if(Ri){if(DD(e),gs){_a=!1;try{process.stderr.write(e)}finally{_a=!0}}}else gs&&process.stderr.write(e)}a(_m,"logStdErr");function DD(e){aR(),fa?oo.appendFileSync(fa,e):oR||console.log(e)}a(DD,"logToFile");function lR(){try{oo.closeSync(fa)}catch{}fa=null}a(lR,"closeLogFile");function aR(){if(!fa){try{fa=oo.openSync(dm,"a")}catch(e){oR||(oR=!0,console.error(e))}setTimeout(()=>{lR()},$Q).unref()}}a(aR,"openLogFile");function LD(...e){Er[Dr]<=Er.info&&If(Js("info",e))}a(LD,"info");function MD(...e){Er[Dr]<=Er.trace&&If(Js("trace",e))}a(MD,"trace");function fm(...e){Er[Dr]<=Er.error&&_m(Js("error",e))}a(fm,"error");function vD(...e){Er[Dr]<=Er.debug&&If(Js("debug",e))}a(vD,"debug");function UD(...e){Er[Dr]<=Er.notify&&If(Js("notify",e))}a(UD,"notify");function xD(...e){Er[Dr]<=Er.fatal&&_m(Js("fatal",e))}a(xD,"fatal");function BD(...e){Er[Dr]<=Er.warn&&_m(Js("warn",e))}a(BD,"warn");function jQ(e,t,...r){t===CD.STDERR?_m(Js(e,r)):If(Js(e,r))}a(jQ,"logCustomLevel");function JQ(){let e;try{e=kQ.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=yi.join(e,Vt.HDB_HOME_DIR_NAME,Vt.BOOT_PROPS_FILE_NAME);return oo.existsSync(t)||(t=yi.join(cR,"utility/hdb_boot_properties.file")),t}a(JQ,"getPropsFilePath");function QQ(e){Dr=e}a(QQ,"setLogLevel");function ND(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(ND,"autoCastBoolean");function XQ(e){try{if(e.includes("config/settings.js")){let o=ID(e);return{level:o.get(Vt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:yi.dirname(o.get(Vt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Vt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Vt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=wD.parseDocument(oo.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===Vt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(XQ,"getLogConfig");function ZQ(){try{let e=wD.parseDocument(oo.readFileSync(qQ,"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(ZQ,"getDefaultConfig");function e4(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(e4,"AuthAuditLog")});var uR=P((zye,FD)=>{"use strict";var t4=require("util"),r4=require("path"),n4=require("child_process"),s4=t4.promisify(n4.execFile),i4=1e3*1e3*10;FD.exports={findPs:o4};async function o4(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await s4("ps",["wwxo",`pid,${r}`],{maxBuffer:i4});for(let s of n.trim().split(`
|
|
8
|
-
`).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:r4.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(o4,"findPs")});var Ut=P((Jye,qD)=>{"use strict";var a4="__dbis__",c4="__txns__",l4="__environment_name__",u4="__dbi_defintion__",d4={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"},f4=["__createdtime__","__updatedtime__"],_4="\uFFFF",GD={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},p4=Object.values(GD);qD.exports={AUDIT_STORE_NAME:c4,INTERNAL_DBIS_NAME:a4,DBI_DEFINITION_NAME:u4,SEARCH_TYPES:d4,TIMESTAMP_NAMES:f4,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:l4,TRANSACTIONS_DBI_NAMES_ENUM:GD,TRANSACTIONS_DBIS:p4,OVERFLOW_MARKER:_4}});var kn=P((Qye,QD)=>{"use strict";var $D=(k(),D(q)),VD=Ut(),KD={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},YD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),WD={500:YD("There was an error processing your request."),400:"Invalid request"},h4=WD[KD.INTERNAL_SERVER_ERROR],m4={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},E4={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},g4={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),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:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},S4={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 ${VD.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${VD.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"},T4={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${$D.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),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 ${$D.INSERT_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"},zD={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"},A4={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:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_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:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},R4={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_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:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),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:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},y4={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},b4={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},O4={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},jD={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},JD={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:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},N4={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.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},w4={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},I4={...zD,...g4,...m4,...A4,...R4,...y4,...b4,...O4,...T4,...jD,...JD,...N4,...w4,...E4};QD.exports={CHECK_LOGS_WRAPPER:YD,HDB_ERROR_MSGS:I4,DEFAULT_ERROR_MSGS:WD,DEFAULT_ERROR_RESP:h4,HTTP_STATUS_CODES:KD,LMDB_ERRORS_ENUM:S4,AUTHENTICATION_ERROR_MSGS:zD,VALIDATION_ERROR_MSGS:jD,ITC_ERRORS:JD}});var he=P((Zye,eL)=>{"use strict";var _u=kn(),C4=z(),P4=(k(),D(q)),pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,XD),this.statusCode=n||_u.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(_u.DEFAULT_ERROR_MSGS[n]?_u.DEFAULT_ERROR_MSGS[n]:_u.DEFAULT_ERROR_MSGS[_u.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&&C4[s](i)}},dR=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}},fR=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function XD(e,t,r,n=P4.LOG_LEVELS.ERROR,s=null,i=!1){if(ZD(e))return e;let o=new pm(e,t,r,n,s);return i&&delete o.stack,o}a(XD,"handleHDBError");function ZD(e){return e.__proto__.constructor.name===pm.name}a(ZD,"isHDBError");eL.exports={isHDBError:ZD,handleHDBError:XD,ClientError:dR,ServerError:fR,hdb_errors:_u}});var mt=P((tbe,aL)=>{"use strict";var Mf=(k(),D(q)),D4=oe(),_n=le(),vf=require("path"),L4=require("minimist"),tL=require("fs-extra"),rL=require("lodash");_n.initSync();var{CONFIG_PARAMS:pa,DATABASES_PARAM_CONFIG:Cf,SYSTEM_SCHEMA_NAME:hm}=Mf,Pf,Df,Lf;function nL(){if(Pf!==void 0)return Pf;if(_n.getHdbBasePath()!==void 0)return Pf=_n.get(pa.STORAGE_PATH)||vf.join(_n.getHdbBasePath(),Mf.DATABASES_DIR_NAME),Pf}a(nL,"getBaseSchemaPath");function sL(){if(Df!==void 0)return Df;if(_n.getHdbBasePath()!==void 0)return Df=oL(hm),Df}a(sL,"getSystemSchemaPath");function iL(){if(Lf!==void 0)return Lf;if(_n.getHdbBasePath()!==void 0)return Lf=_n.get(Mf.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||vf.join(_n.getHdbBasePath(),Mf.TRANSACTIONS_DIR_NAME),Lf}a(iL,"getTransactionAuditStoreBasePath");function M4(e,t){let r=_n.get(pa.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||vf.join(iL(),e.toString())}a(M4,"getTransactionAuditStorePath");function oL(e,t){e=e.toString(),t=t&&t.toString();let r=_n.get(Mf.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||vf.join(nL(),e)}a(oL,"getSchemaPath");function v4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,L4(process.argv));let n=r[pa.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!D4.isObject(n))throw o;i=n}for(let o of i){let c=o[hm];if(!c)continue;let l=_n.get(pa.DATABASES);l=l??{};let u=c?.tables?.[t]?.[Cf.PATH];if(u)return rL.set(l,[hm,Cf.TABLES,t,Cf.PATH],u),_n.setProperty(pa.DATABASES,l),u;let f=c?.[Cf.PATH];if(f)return rL.set(l,[hm,Cf.PATH],f),_n.setProperty(pa.DATABASES,l),f}}let s=r[pa.STORAGE_PATH.toUpperCase()];if(s){if(!tL.pathExistsSync(s))throw new Error(s+" does not exist");let i=vf.join(s,e);return tL.mkdirsSync(i),_n.setProperty(pa.STORAGE_PATH,s),i}return sL()}a(v4,"initSystemSchemaPaths");function U4(){Pf=void 0,Df=void 0,Lf=void 0}a(U4,"resetPaths");aL.exports={getBaseSchemaPath:nL,getSystemSchemaPath:sL,getTransactionAuditStorePath:M4,getTransactionAuditStoreBasePath:iL,getSchemaPath:oL,initSystemSchemaPaths:v4,resetPaths:U4}});var pn=P((ibe,fL)=>{"use strict";var x4=kn().LMDB_ERRORS_ENUM,nbe=require("lmdb"),B4=Ut(),sbe=require("buffer").Buffer,{OVERFLOW_MARKER:cL,MAX_SEARCH_KEY_LENGTH:mm}=B4,lL=["number","string","symbol","boolean","bigint"];function H4(e){if(e=e?.primaryStore||e,!e)throw new Error(x4.ENV_REQUIRED)}a(H4,"validateEnv");function k4(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(k4,"stringifyData");function F4(e){return e instanceof Date?e.valueOf():e}a(F4,"convertKeyValueToWrite");function G4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(lL.includes(typeof e))return e.length>mm?[e.slice(0,mm)+cL]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(lL.includes(typeof i))i.length>mm?r.push(i.slice(0,mm)+cL):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(G4,"getIndexedValues");var Em=0,uL=0;function dL(){uL=Date.now()-performance.now()}a(dL,"adjustStartTime");dL();var q4=6e4;setInterval(dL,q4).unref();function $4(){let e=performance.now()+uL;return e>Em?(Em=e,e):(Em+=488e-6,Em)}a($4,"getNextMonotonicTime");fL.exports={validateEnv:H4,stringifyData:k4,convertKeyValueToWrite:F4,getNextMonotonicTime:$4,getIndexedValues:G4}});var Uf=P((abe,_L)=>{"use strict";var V4=(k(),D(q)).OPERATIONS_ENUM,_R=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=V4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};_L.exports=_R});var xf=P((ube,EL)=>{"use strict";var lbe=Uf(),gm=(k(),D(q)),pR=oe(),pL=z(),K4=require("uuid"),{handleHDBError:Sm,hdb_errors:Y4}=he(),{HDB_ERROR_MSGS:Tm,HTTP_STATUS_CODES:Am}=Y4;EL.exports=hL;function hL(e,t,r){for(let s=0;s<t.length;s++)mL(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];W4(i,r,e.operation)}}a(hL,"processRows");hL.validateAttribute=mL;function mL(e){if(Buffer.byteLength(String(e))>gm.INSERT_MAX_CHARACTER_SIZE)throw Sm(new Error,Tm.ATTR_NAME_LENGTH_ERR(e),Am.BAD_REQUEST,void 0,void 0,!0);if(pR.isEmptyOrZeroLength(e)||pR.isEmpty(e.trim()))throw Sm(new Error,Tm.ATTR_NAME_NULLISH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(mL,"validateAttribute");function W4(e,t,r){if(!e.hasOwnProperty(t)||pR.isEmptyOrZeroLength(e[t])){if(r===gm.OPERATIONS_ENUM.INSERT||r===gm.OPERATIONS_ENUM.UPSERT){e[t]=K4.v4();return}throw pL.error("Update transaction aborted due to record with no hash value:",e),Sm(new Error,Tm.RECORD_MISSING_HASH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>gm.INSERT_MAX_CHARACTER_SIZE)throw pL.error(e),Sm(new Error,Tm.HASH_VAL_LENGTH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(W4,"validateHash")});var gL,Fn,hR,pu=be(()=>{gL=require("events"),Fn=class extends gL.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new hR;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(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}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)}},hR=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function OL(e){ER=e}function Q4(){J4=setInterval(function(){for(let e of mR)if(e.stale){let t=e.getContext()?.url;RL.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},j4).unref()}var gR,AL,RL,yL,bL,SL,mR,z4,Bf,TL,ER,Nc,Rm,j4,J4,ym=be(()=>{gR=M(pn()),AL=M(he()),RL=M(z()),yL=M(le());k();bL=M(oe()),SL=100,mR=new Set,z4=(0,bL.convertToMS)(yL.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(OL,"replicationConfirmation");Nc=class e{static{a(this,"DatabaseTransaction")}#e;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.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),mR.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(mR.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Bf&&!this.overloadChecked&&performance.now()-TL>z4)throw new AL.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||(0,gR.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let p=d;p<this.validated;p++)this.writes[p]?.validate?.(this.timestamp);let _;for(let p=d;p<this.validated;p++){let h=this.writes[p];h&&(h.before||h.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let p=0;p<2;p++){let h;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let R=g[p===0?"before":"beforeIntermediate"];if(R){let E=R();h?h.push?h.push(E):h=[h,E]:h=E}}h&&await(h.push?Promise.all(h):h)}}catch(p){throw this.abort(),p}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<SL>>n?l():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 Bf||(Bf=s,TL=performance.now(),Bf.then(()=>{Bf=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,p=this.writes[this.writes.length-1];ER&&p&&i.push(ER(_,p.store.getEntry(p.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+SL/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Rm=class extends Nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,gR.getNextMonotonicTime)())}getReadTxn(){}},j4=3e4;a(Q4,"startMonitoringTxns");Q4()});function Ot(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 Nc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(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 l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var NL,wc=be(()=>{NL=M(Ai());ym();a(Ot,"transaction");(0,NL._assignPackageExport)("transaction",Ot);Ot.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ot.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function TR(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let p=1;p<e.length;p++){let h=e[p],S=u(h);d=d.concat(S)}let _=new Set;return d.filter(p=>{let h=p.key??p;return _.has(h)?!1:(_.add(h),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?TR(d.conditions,d.operator,r,n,s,i,o,c):Eu(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,p){return d.map((h,S)=>{if(h.conditions){let E=h.operator==="or",T=f(h.conditions,!E,p);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(h.attribute||h[0])===r.primaryKey,R=Ff(h,r,i,c,g,p);return _&&S<d.length-1&&p&&(p=o3(r.primaryStore,h.estimated_count,p)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Eu(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new mn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=Oi(n.attributes,E);if(T.relationship){if(o.length<2)throw new mn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=T.definition?.tableClass||T.elements?.definition?.tableClass,v=new Map,H=Eu({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let $=!!Oi(w.attributes,T.relationship.to)?.elements;H=r3(H,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Eu({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=n3(H,T,w.primaryStore,v,$)):H=H.flatMap($)}return H}else if(o.length===1)o=o[0];else throw new mn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let p;switch(AR[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=bi.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,p=!0;break;default:throw new mn.ClientError(`Unknown query comparator "${l}"`)}let h,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>Ss.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,Ss.MAX_SEARCH_KEY_LENGTH)+Ss.OVERFLOW_MARKER,_=!1,h=Ff(e,n,null,i,S)),typeof f=="string"&&f.length>Ss.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,Ss.MAX_SEARCH_KEY_LENGTH)+Ss.OVERFLOW_MARKER,d=!0,h=h??Ff(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||p||c===null&&!g.indexNulls){if(s===!1&&!g)throw new mn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&p)throw new mn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(g?.isIndexing)throw new mn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new mn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(h=h??Ff(e,n,null,i,S),!h)throw new mn.ClientError(`Unknown search operator ${e.comparator}`)}let R={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(R).map(h?function({key:T,value:w}){return this?.isSync?w&&h(w)?T:ha.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&h(w)?T:ha.SKIP)}catch($){H($)}}))}:T=>T.value==null&&!(T.metadataFlags&(En|Ea))?ha.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(h?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>Ss.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?h(w)?T:ha.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(h(w)?T:ha.SKIP)}catch($){H($)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&h(T)?E:ha.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&h(T)?E:ha.SKIP)}catch(H){v(H)}}))})}function Oi(e,t){if(Array.isArray(t))if(t.length>1){let r=Oi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Oi(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 r3(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=a((u,f)=>{let d=s.get(u);d?d.push(f):s.set(u,d=[f])},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),d=f?.[c];if(d!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<d.length;_++)l(d[_],u);else l(d,u)}return i=s.keys()[Symbol.iterator](),this.next()}let o=i.next();return o.done?o:{value:o.value}},return(){if(i?.return)return i.return()}}}})}function n3(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Ff(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=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 f=c[0],d=Oi(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,p=n?.[f],h=Ff({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,p?.[f]?.joined,c[1]===_.primaryKey,i);if(!h)return;if(p){p.filters||(p.filters=[]),p.filters.push(h);return}let S=t.propertyResolvers?.[f],g,R=a((E,T)=>{let w,v;if(S){if(S.from&&h.idFilter){if(!g)if(h.idFilter.idSet?.size===1){for(let $ of h.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,h.idFilter,!0,!0)}else g=u(S.from,h.idFilter,!1,!0);let H=g(E);return g.idFilter&&(R.idFilter=g.idFilter),H}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(h):h(w,v):!1},"recordFilter");return R}}switch(l instanceof Date&&(l=l.getTime()),AR[o]||o){case Ss.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,bi.compareKeys)(f,l[0])>=0&&(0,bi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,bi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,bi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,bi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,bi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,bi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new mn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,p){let h;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Om(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(_=!1));let S=0,g=3;function R(E){let T=E[f],w;if(typeof T!="object"||!T||p?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!R.idFilter&&++S/g*(i-g)>h)){let v=Eu(e,r.transaction.getReadTxn(),!1,t).map(gu),H=new Set(v);R.idFilter=$=>H.has(gu($)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Om(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/ao(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=AR[n]||n,n===Ss.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=Oi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Om(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*ao(e.indices[i.relationship.from])/(ao(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=ao(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=e3*ao(e.primaryStore)+1:n==="between"?r.estimated_count=Z4*ao(e.primaryStore)+1:n==="sort"?r.estimated_count=ao(e.primaryStore)+1:r.estimated_count=X4*ao(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Nm(e){if(e)if(ma=e,hu.lastIndex=0,s3.test(e))try{let t=Hf(new mu,"");if(hn!==ma.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 ${hn} in '${ma}'`,t}else return new URLSearchParams(e)}function Hf(e,t){let r=hu,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(ma);){hn=r.lastIndex;let[,f,d]=n;if(o){if(f)throw new SyntaxError(`expected operator, but encountered '${f}'`);o=!1,c=!1}else c=!0;let _;switch(d){case"=":if(s!=null){if(f.length<=2)i=f;else throw new SyntaxError(`invalid FIQL operator ${f}`);l=wL}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=kf(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=t3[d],l=SR[i]?wL:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=kf(f);break;case"&=":case"|=":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||null,value:l(f)};if(i==="eq"&&IL(h,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(h),S.operator=u}else bm(e,u),e.conditions.push(h)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(kf(f)),s=void 0;break;case"(":hu.lastIndex=hn;let p=Hf(f?[]:new mu,")");switch(f){case"":bm(e,u),e.conditions.push(p);break;case"limit":switch(p.length){case 1:e.limit=+p[0];break;case 2:e.offset=+p[0],e.limit=p[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(p[0])&&p.length===1&&!p[0].name?(e.select=p[0],e.select.asArray=!0):p.length===1?e.select=p[0]:p.length===2&&p[1]===""?e.select=p.slice(0,1):e.select=p;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=CL(p);break;default:throw new SyntaxError(`unknown query function call ${f}`)}ma[hn]===","?r.lastIndex=++hn:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");hu.lastIndex=hn,_=Hf([],"}"),_.name=f,e.push(_),ma[hn]===","?r.lastIndex=++hn:o=!0;break;case"[":hu.lastIndex=hn,f?(_=Hf(new mu,"]"),_.name=f):_=Hf(e.conditions?new mu:[],"]"),e.conditions?(bm(e,u),e.conditions.push(_),s=null):e.push(_),ma[hn]===","?r.lastIndex=++hn:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&IL(h,f),bm(e,u),e.conditions.push(h)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(kf(f));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?i3:hu,r.lastIndex=hn),hn===ma.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function bm(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 kf(e){return e.indexOf(".")>-1?e.split(".").map(kf):decodeURIComponent(e)}function wL(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+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 mn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function IL(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new mn.ClientError("wildcard can only be used at the end of a string")}function CL(e){let t=PL(e[0]);return e.length>1&&(t.next=CL(e.slice(1))),t}function PL(e){if(Array.isArray(e)){let t=PL(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 gu(e){return Array.isArray(e)?e.join("\0"):e}function ao(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function o3(e,t,r){return t*r/ao(e)}var mn,Ss,bi,ha,X4,Z4,e3,t3,SR,AR,s3,hu,i3,hn,ma,mu,Ic,Gf=be(()=>{mn=M(he()),Ss=M(Ut()),bi=require("ordered-binary"),ha=require("lmdb");qf();X4=.3,Z4=.1,e3=.05,t3={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},SR={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(TR,"executeConditions");a(Eu,"searchByIndex");a(Oi,"findAttribute");a(r3,"joinTo");a(n3,"joinFrom");AR={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(Ff,"filterByType");a(Om,"estimateCondition");s3=/[()[\]|!<>.]|(=\w*=)/,hu=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,i3=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Nm,"parseQuery");a(Hf,"parseBlock");a(bm,"assignOperator");a(kf,"decodeProperty");a(wL,"typedDecoding");a(IL,"wildcardDecoding");a(CL,"toSortObject");a(PL,"toSortEntry");mu=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(gu,"flattenKey");a(ao,"estimatedEntryCount");a(o3,"intersectionEstimate");Ic=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var yR={};Ue(yR,{MultiPartId:()=>Im,Resource:()=>Yr,snake_case:()=>c3,transformForSelect:()=>Cm});function c3(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function DL(e,t){if(Cc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Cc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Im;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Cc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Cc=!0,null;e[e.length-1]==="/"&&(Cc=!0)}return t.coerceId(decodeURIComponent(e))}function Gn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let p=c.indexOf("?");if(p>-1){let S=this.parseQuery(c.slice(p+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,p)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),u=h.isCollection,c=h.id):c=h}else if(s[Symbol.iterator]){c=[],u=!0;for(let p of s){if(typeof p=="object"&&p)break;c.push(p)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new Ic(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let p=this.getResource(c,o,d);return p.then?p.then(_):_(p)}else return Ot(o,()=>{let p=this.getResource(c,o,d);return p.then?p.then(_):_(p)},d);function _(p){if(o.authorize){o.authorize=!1;let h=t.type==="read"?p.allowRead(o.user,l,o):t.type==="update"?p.doesExist?.()===!1?p.allowCreate(o.user,f,o):p.allowUpdate(o.user,f,o):t.type==="create"?p.allowCreate(o.user,f,o):p.allowDelete(o.user,l,o);if(h?.then)return h.then(S=>{if(!S)throw new wm(o.user);return typeof f?.then=="function"?f.then(g=>e(p,l,o,g)):e(p,l,o,f)});if(!h)throw new wm(o.user)}return typeof f?.then=="function"?f.then(h=>e(p,l,o,h)):e(p,l,o,f)}a(_,"authorizeActionOnResource")}}function qn(e,t){let r=new vL.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 RR(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();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 Cm(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):RR(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],f=i(RR(l,r,n));for(let d of e)u.push(f(d));return u},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(_=>_&&typeof _=="object"?c(_):_);let u={},f=i(RR(l,r,n)),d;for(let _ of e){let p=f(_);p===void 0&&o&&(p=null),p?.then?(d||(d=[]),d.push(p.then(h=>u[_.name||_]=h))):u[_.name||_]=p}return d?Promise.all(d).then(()=>u):u},"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 l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=Cm(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var LL,ML,vL,a3,Yr,wm,Cc,Im,ga=be(()=>{LL=require("crypto");pu();ML=M(Ai()),vL=M(he());wc();Gf();a3={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Yr=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Gn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=Cm(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Gn(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):qn(t,"put")},{hasContent:!0,type:"update"});static patch=Gn(function(t,r,n,s){return t.patch?t.patch(s,r):qn(t,"patch")},{hasContent:!0,type:"update"});static delete=Gn(function(t,r,n,s){return t.delete?t.delete(r):qn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,LL.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),Ot(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):qn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Gn(function(t,r,n,s){return t.invalidate?t.invalidate(r):qn(t,"delete")},{hasContent:!1,type:"update"});static post=Gn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Gn(function(t,r,n,s){return t.connect?t.connect(s,r):qn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Gn(function(t,r,n,s){return t.subscribe?t.subscribe(r):qn(t,"subscribe")},{type:"read"});static publish=Gn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):qn(t,"publish")},{hasContent:!0,type:"create"});static search=Gn(function(t,r,n,s){let i=t.search?t.search(r):qn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Cm(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Gn(function(t,r,n,s){return t.search?t.search(s,r):qn(t,"search")},{hasContent:!0,type:"read"});static copy=Gn(function(t,r,n,s){return t.copy?t.copy(s,r):qn(t,"copy")},{hasContent:!0,type:"create"});static move=Gn(function(t,r,n,s){return t.move?t.move(s,r):qn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;qn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Nm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&a3[o];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===o))if(t=t.slice(0,s),n)n.property=o;else return{query:{property:o},id:DL(t,this),isCollection:Cc}}let i=DL(t,this);return Cc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),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 l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Fn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Fn}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.#e}getContext(){return this.#t}};(0,ML._assignPackageExport)("Resource",Yr);a(c3,"snake_case");wm=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(DL,"pathToId");Im=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Gn,"transactional");a(qn,"missingMethod");a(RR,"selectFromObject");a(Cm,"transformForSelect")});var Sa,bR=be(()=>{Sa=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}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 Su={};Ue(Su,{server:()=>Ke});var UL,Ke,Lr=be(()=>{UL=M(Ai()),Ke={};(0,UL._assignPackageExport)("server",Ke)});var HL={};Ue(HL,{Resources:()=>Pm,keyArrayToString:()=>Tu,resetResources:()=>l3,resources:()=>Ts});function l3(){return Ts=new Pm,Ke.resources=Ts,Ts}function Tu(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var xL,BL,Pm,Ts,Au=be(()=>{wc();bR();xL=M(z()),BL=M(he());Lr();Pm=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,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new BL.ServerError(`Conflicting paths for ${t}`);xL.default.error(c),i.Resource=new Sa(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}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 Ot(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(l3,"resetResources");a(Tu,"keyArrayToString")});var wR={};Ue(wR,{loadGQLSchema:()=>f3,start:()=>NR,startOnMainThread:()=>d3});function NR({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,p=[],h;for(let R of d.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(W){if(W.kind==="NonNullType"){let Y=H(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:H(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(H,"getProperty");let E=R.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of R.directives){if(W.name.value==="table"){for(let se of W.arguments)w[se.name.value]=se.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=E),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,p.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,$={};for(let W of R.fields){let te=H(W.type);te.name=W.name.value,T.push(te),$[te.name]=void 0;for(let se of W.directives){let Y=se.name.value;if(Y==="primaryKey")v?console.warn("Can not define two attributes as a primary key at",se.loc):(te.isPrimaryKey=!0,v=!0);else if(Y==="indexed")te.indexed=!0;else if(Y==="computed"){for(let ne of se.arguments||[])if(ne.name.value==="from"){let ue=ne.value.value;te.computed={from:g(ue,ne,$)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(h=w)}function S(R){let E=_.get(R.type);E?(Object.defineProperty(R,"properties",{value:E.properties}),Object.defineProperty(R,"definition",{value:E})):R.type==="array"?S(R.elements):u3.includes(R.type)||(0,FL.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let R of _.values())for(let E of R.properties)S(E);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,OR.dirname)(n),R.tableClass):i.set((0,OR.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new kL.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var OR,kL,FL,u3,d3,f3,GL=be(()=>{OR=require("path"),kL=require("node:vm");Le();FL=M(tt()),u3=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(NR,"start");d3=NR,f3=NR({ensureTable:dt}).handleFile});var zL={};Ue(zL,{parse:()=>CR,streamAsJSON:()=>$f,stringify:()=>Pc});function $f(e){return new IR({value:e})}function qL(e){return console.error(e),JSON.stringify(e.toString())}function $L(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===YL)return WL(e);if(t.resolution)return t.resolution.then(()=>Pc(e));throw t}}function WL(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+=WL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Pc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function CR(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),h3.test(e)?_3.parse(e):JSON.parse(e)):null}var VL,KL,_3,p3,YL,IR,h3,PR=be(()=>{VL=require("stream"),KL=M(require("json-bigint-fixes")),_3=(0,KL.default)({useNativeBigInt:!0}),p3=1e4,YL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw YL};a($f,"streamAsJSON");IR=class extends VL.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(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")}}if(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),qL)}catch(s){yield qL(s)}else yield Pc(t)}else yield Pc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);$L(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>p3?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 $L(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(qL,"handleError");a($L,"when");a(Pc,"stringify");a(WL,"jsStringify");h3=/[[,:]\s*-?\d{16,}/;a(CR,"parse")});var Ni=P(Lm=>{var Dm=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])Dm.logsAtLevel(e)&&(Lm[e]=Dm[e]);Lm.loggerWithTag=e=>Dm.loggerWithTag(e,!0);Lm.setLogLevel=Dm.setLogLevel});var $m={};Ue($m,{Blob:()=>wi,blobsWereEncoded:()=>Lc,databasePaths:()=>LR,decodeBlobsWithWrites:()=>Gm,decodeFromDatabase:()=>Mc,decodeWithBlobCallback:()=>qm,deleteBlob:()=>Hm,deleteBlobsInObject:()=>Ta,deleteRootBlobPathsForDB:()=>vR,encodeBlobsAsBuffers:()=>O3,encodeBlobsWithFilePath:()=>Fm,findBlobsInObject:()=>yu,getFileId:()=>km,getFilePathForBlob:()=>sM,getRootBlobPathsForDB:()=>Wf,setDeletionDelay:()=>S3});function tM(){}function Hm(e){let t=sM(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&co.default.debug?.("Error trying to remove blob file",r)})},rM)}function S3(e){rM=e}function nM(e){let t=gn.get(e);if(!t)t={storageIndex:0,fileId:null,store:Sn},gn.set(e,t);else{if(t.saving)return t;t.store=Sn}return A3(t),t.source?DR(e,t.source,t):t.contentBuffer?T3(e,t):DR(e,Kf.Readable.from(e.stream()),t),t}function DR(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,je.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([h(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(h(e.size)),_=!0);let p;o?(_||d.write(E3),p=(0,xm.createDeflate)(),t.pipe(p).pipe(d)):(_||d.write(m3),t.pipe(d)),t.on("error",S);function h(g){let R=BigInt(g),E=new Uint8Array(gr),T=new DataView(E.buffer);return R|=BigInt(o?MR:eM)<<48n,T.setBigInt64(0,R),E}a(h,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,je.close)(R),u(g)):c?(0,je.fdatasync)(R,E=>{E&&u(E),l(),(0,je.close)(R)}):(l(),(0,je.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=p?p.bytesWritten:d.bytesWritten-gr;e.size=g,(0,je.write)(d.fd,h(g),0,gr,0,S)}})}),e}function km(e){return gn.get(e)?.fileId}function sM(e){let t=gn.get(e);return t?.fileId&&Yf(t)}function Wf(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=LR.get(e);if(!t){if(!e.databaseName)return co.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,Bm.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,uo.join)(n,e.databaseName)):t=[(0,uo.join)((0,Bm.getHdbBasePath)(),"blobs",e.databaseName)],LR.set(e,t)}return t}async function vR(e){let t=Wf(e);t&&await Promise.all(t.map(r=>iM(r)))}async function iM(e){if((0,je.existsSync)(e)){for(let t of await(0,Qs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await iM((0,uo.join)(e,t.name));else try{await(0,Qs.unlink)((0,uo.join)(e,t.name))}catch(r){co.default.warn?.("Error deleting file",r)}try{await(0,Qs.rmdir)(e)}catch(t){co.default.warn?.("Error deleting directory",t)}}}function Yf({storageIndex:e,fileId:t,store:r}){let n=Wf(r);return(0,uo.join)(n[e],t.slice(-9,-6)||"0",t.slice(-6,-3)||"0",t.length<=9?t.slice(-3):t.slice(0,-9)+t.slice(-3))}function T3(e,t){let r=t.contentBuffer,n=r.length;if(!(n<ZL))return e.size=n,DR(e,Kf.Readable.from([r]),t)}function A3(e){let t=Wf(e.store),r=R3(),n=t?.length>1?y3(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Yf(e),o=(0,uo.dirname)(i);(0,je.existsSync)(o)||(0,XL.ensureDirSync)(o),e.filePath=i}function R3(){let e=QL.get(Sn);if(!e){let t=0,r=Wf(Sn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,uo.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(Sn.getUserSharedBuffer("blob-file-id",e.buffer)),QL.set(Sn,e)}return Number(Atomics.add(e,0,1n))}function y3(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(Um);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,b3(e)),e.frequencyTable[t%Um]}async function b3(e){if(!Qs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Qs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(Um),n=t.map(s=>1/s);for(let s=0;s<Um;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function Fm(e,t,r){Ru=t,Sn=r,Lc=!1;try{return e()}finally{Ru=void 0,Sn=void 0}}function O3(e){Mr=[];let t;try{t=e()}catch(n){throw Mr=void 0,n}let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r?r.then(()=>e()):t}function Gm(e,t){try{Mr=[],Dc=t,e()}catch(n){throw Dc=void 0,Mr=void 0,n}Dc=void 0;let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r}function qm(e,t,r){Sn=r;try{return Dc=t,e()}finally{Dc=void 0}}function Mc(e,t){return Sn=t,e()}function Ta(e){yu(e,t=>{Hm(t)})}function yu(e,t){if(e instanceof wi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&yu(r,t);else if(e.constructor===Object)for(let r in e){let n=e[r];typeof n=="object"&&n&&yu(e[r],t)}}function N3(){return class{static{a(this,"Blob")}content;constructor(t){this.content=t[0]}stream(){return new ReadableStream({start(t){t.enqueue(this.content),t.close()}})}text(){return Promise.resolve(this.content.toString())}arrayBuffer(){return Promise.resolve(this.content.buffer)}get size(){return this.content.length}slice(){throw new Error("Not implemented")}bytes(){return Promise.resolve(this.content)}get type(){return""}}}var lo,Qs,je,xm,Kf,XL,Bm,uo,co,ZL,gr,eM,MR,jL,m3,E3,JL,gn,Dc,wi,Ru,Mr,Sn,Lc,Vf,Mm,g3,vm,rM,LR,QL,Um,As=be(()=>{lo=require("msgpackr"),Qs=require("node:fs/promises"),je=require("node:fs"),xm=require("node:zlib"),Kf=require("node:stream"),XL=require("fs-extra"),Bm=M(le());k();uo=require("path"),co=M(Ni());fo();ZL=8192,gr=8,eM=0,MR=1,jL=255,m3=new Uint8Array([0,eM,255,255,255,255,255,255]),E3=new Uint8Array([0,MR,255,255,255,255,255,255]),JL=0xffffffffffff,gn=new WeakMap,wi=global.Blob||N3(),Lc=!1,Vf=new Uint8Array(8),Mm=new DataView(Vf.buffer),g3=6e4;a(tM,"InstanceOfBlobWithNoConstructor");tM.prototype=wi.prototype;vm=class e extends tM{static{a(this,"FileBackedBlob")}type="";size;#e;#t;constructor(t){super(),t?.type&&(this.type=t.type),t?.size!=null&&(this.size=t.size)}on(t,r){if(t==="error")this.#e??=[],this.#e.push(r);else if(t==="size")this.#t??=[],this.#t.push(r);else throw new Error("Only 'error' and 'size' events are supported")}toJSON(){if(this.type?.startsWith("text")){let t=gn.get(this),{start:r,end:n,contentBuffer:s,asString:i}=t;return i||(s&&(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),s?(t.asString=s.toString(),t.asString):(xR()&&UR(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=gn.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Yf(t),o,c=a(async()=>{let l,u=gr;try{if(l=await(0,Qs.readFile)(i),l.length>=gr){l.copy(Vf,0,0,gr);let d=Mm.getBigUint64(0);if(Number(d>>48n)===jL)throw new Error("Error in blob: "+buffer.subarray(gr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<JL&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,p=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((h,S)=>{if(_.attemptLock(p,0,()=>(o=!0,_.unlock(p,0),h(c()))))return o=!0,_.unlock(p,0),h(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===MR?new Promise((d,_)=>{(0,xm.deflate)(l.subarray(gr),(p,h)=>{p?_(p):d(f(h))})}):f(l.subarray(gr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=gn.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Yf(t),o,c=0,l=0,u,f,d,_=!1,p=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(co.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{h(),g(R,E)},20).unref();E(T),p.#e?.forEach(v=>v(T))}else o=w,R(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,R=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),p.#e?.forEach(W=>W($))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,je.read)(o,H,0,H.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<gr){R-- >0&&d!==!1?(h(),co.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(co.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(Vf,0,0,gr);let se=Mm.getBigUint64(0);if(Number(se>>48n)===jL)return v(new Error("Error in blob: "+te.subarray(gr)));if(g=Number(se&0xffffffffffffn),g<JL&&p.size!==g&&(p.size=g,p.#t))for(let Y of p.#t)Y(g);te=te.subarray(gr,W),l-=gr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,gr,0,Y=>{if(Y)return v(Y);if(Vf.set(se),g=Number(Mm.getBigUint64(0)&0xffffffffffffn),g>l){h()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},g3).unref():(u=(0,je.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,je.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return co.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.close)(o),clearTimeout(f),u&&u.close()}});function h(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=gn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};gn.set(i,o),this.size!=null&&(i.size=(r==null?this.size:Math.min(r,this.size))-(t??0))}else if(s?.contentBuffer&&!s.storageBuffer){let o={...s,contentBuffer:s.contentBuffer.subarray(t,r)};gn.set(i,o),i.size=(r??this.size)-t}else throw new Error("Can not slice a streaming blob that is not backed by a file");return i}save(t){if(Sn=t?.primaryStore?.rootStore,!Sn)throw new Error("No target table specified");return nM(this).saving??Promise.resolve()}},rM=500;a(Hm,"deleteBlob");a(S3,"setDeletionDelay");global.createBlob=function(e,t){let r=new vm(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(gn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Kf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Kf.Readable.from(e);else throw new Error("Invalid source type");return r};a(nM,"saveBlob");a(DR,"writeBlobWithStream");a(km,"getFileId");a(sM,"getFilePathForBlob");LR=new Map;a(Wf,"getRootBlobPathsForDB");a(vR,"deleteRootBlobPathsForDB");a(iM,"rimrafSteadily");a(Yf,"getFilePath");a(T3,"writeBlobWithBuffer");a(A3,"generateFilePath");QL=new Map;a(R3,"getNextFileId");Um=128;a(y3,"getNextStorageIndex");a(b3,"createFrequencyTableForStoragePaths");a(Fm,"encodeBlobsWithFilePath");a(O3,"encodeBlobsAsBuffers");a(Gm,"decodeBlobsWithWrites");a(qm,"decodeWithBlobCallback");a(Mc,"decodeFromDatabase");a(Ta,"deleteBlobsInObject");a(yu,"findBlobsInObject");(0,lo.addExtension)({Class:wi,type:11,unpack:a(function(e){let t=(0,lo.unpack)(e),r=new vm;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(gn.set(r,{storageIndex:t[1],fileId:t[2],store:Sn}),Dc)return Dc(r)??r;if(!Sn)throw new Error("No store specified, cannot load blob from storage")}else gn.set(r,{storageIndex:0,fileId:null,storageBuffer:e,contentBuffer:t[1]}),r.size=t[1]?.length;return r},"unpack"),pack:a(function(e){let t=gn.get(e);if(Ru!==void 0&&(Lc=!0,t?.recordId!==void 0&&t.recordId!==Ru))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<ZL)return r.size=t.contentBuffer.length,(0,lo.pack)([r,t.contentBuffer])}if(Ru!==void 0){if(t=nM(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Ru,(0,lo.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Yf(t));if(n.length>=gr&&(n.copy(Vf,0,0,gr),Number(Mm.getBigUint64(0)&0xffffffffffffn)===n.length-gr))return Buffer.concat([(0,lo.pack)([r]),n]);if(Mr)Mr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Mr)return Mr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,lo.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(N3,"polyfillBlob")});var _M={};Ue(_M,{asyncSerialization:()=>UR,contentTypes:()=>FR,findBestSerializer:()=>Km,getDeserializer:()=>ho,hasAsyncSerialization:()=>xR,registerContentHandlers:()=>Jf,serialize:()=>Qf,serializeMessage:()=>Aa,toCsvStream:()=>Vm});function I3(e){try{return e?.[0]===123?kR(e):e}catch{return e}}function Jf(e){e.register(P3,{serializers:[{regex:/^application\/json$/,serializer:$f},{regex:/^application\/cbor$/,serializer:a(function(t){return new vc.EncoderStream(jf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Uc.Readable.from((0,Ii.encodeIter)(t,jf)):(0,Ii.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),Vm(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ii.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,vc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Km(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let h of f){let S=h.indexOf("=");_[h.substring(0,S)]=h.substring(S+1)}d=+_.q;let p=Wr.get(u);if(p){let h=(p.q||1)*d;h>s&&(n=p,i=p.type||u,s=h,o=_)}}if(!n){if(r)throw new cM.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Wr.keys()).join(", "),406);n=Wr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Qf(e,t,r){let n=aM&&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||e instanceof wi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Km(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&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),HR.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,po.createBrotliCompress)({params:{[po.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?po.constants.BROTLI_MODE_TEXT:po.constants.BROTLI_MODE_GENERIC,[po.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>aM?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,po.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function Aa(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;_o=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=Km(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=zf(e);return _o?.length>0?(_o.length===1?_o[0]:Promise.all(_o)).then(()=>Aa(e,t,!0)):n}finally{_o=void 0}}function UR(e){if(_o)_o.push(e);else throw new Error("Unable to serialize asynchronously")}function xR(){return!!_o}function D3(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 M3(e){return L3.includes(e)}function v3(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function ho(e="",t=!1){let r=v3(e),n=r.type&&Wr.get(r.type)?.deserialize||U3(r);return t?s=>D3(s).then(n):n}function U3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!M3(e.parameters.charset)&&HR.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return kR(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function x3(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)}}}}}function Vm(e,t){let r=Uc.default.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 w3(n,s);return r.pipe(i)}var Ii,vc,po,cM,Uc,lM,BR,uM,HR,w3,dM,zf,kR,jf,Wr,FR,oM,fM,C3,P3,aM,_o,L3,fo=be(()=>{PR();Ii=require("msgpackr"),vc=require("cbor-x"),po=require("zlib"),cM=M(he()),Uc=M(require("stream"));Lr();lM=M(Ai()),BR=M(le());k();uM=M(require("yaml")),HR=M(Ni());As();({Transform:w3}=require("json2csv")),dM=BR.default.get(U.SERIALIZATION_BIGINT)!==!1,zf=dM?Pc:JSON.stringify,kR=dM?CR:JSON.parse,jf={useRecords:!1,useToJSON:!0},Wr=new Map,FR=Wr;Ke.contentTypes=FR;(0,lM._assignPackageExport)("contentTypes",FR);Wr.set("application/json",{serializeStream:$f,serialize:zf,deserialize(e){return kR(e)},q:.8});oM=new vc.Encoder(jf);Wr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new vc.EncoderStream(jf).end(e)},serialize:oM.encode,deserialize:oM.decode,q:1});Wr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Uc.Readable.from((0,Ii.encodeIter)(e,jf)):(0,Ii.pack)(e)},serialize:Ii.pack,deserialize:Ii.unpack,q:.9});Wr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),Vm(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]),Vm(e,e?.getColumns?.())},q:.1});Wr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return Uc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Wr.set("text/yaml",{serialize(e){return uM.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Wr.set("text/event-stream",{serializeStream:a(function(e){return Uc.Readable.from(x3(e,this.serialize))},"serializeStream"),serialize:a(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+`
|
|
8
|
+
`).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:r4.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(o4,"findPs")});var Ut=P((Jye,qD)=>{"use strict";var a4="__dbis__",c4="__txns__",l4="__environment_name__",u4="__dbi_defintion__",d4={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"},f4=["__createdtime__","__updatedtime__"],_4="\uFFFF",GD={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},p4=Object.values(GD);qD.exports={AUDIT_STORE_NAME:c4,INTERNAL_DBIS_NAME:a4,DBI_DEFINITION_NAME:u4,SEARCH_TYPES:d4,TIMESTAMP_NAMES:f4,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:l4,TRANSACTIONS_DBI_NAMES_ENUM:GD,TRANSACTIONS_DBIS:p4,OVERFLOW_MARKER:_4}});var kn=P((Qye,QD)=>{"use strict";var $D=(k(),D(q)),VD=Ut(),KD={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},YD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),WD={500:YD("There was an error processing your request."),400:"Invalid request"},h4=WD[KD.INTERNAL_SERVER_ERROR],m4={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},E4={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},g4={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),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:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},S4={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 ${VD.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${VD.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"},T4={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${$D.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),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 ${$D.INSERT_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"},zD={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"},A4={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:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_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:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},R4={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_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:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),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:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},y4={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},b4={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},O4={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},jD={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},JD={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:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},N4={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.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},w4={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},I4={...zD,...g4,...m4,...A4,...R4,...y4,...b4,...O4,...T4,...jD,...JD,...N4,...w4,...E4};QD.exports={CHECK_LOGS_WRAPPER:YD,HDB_ERROR_MSGS:I4,DEFAULT_ERROR_MSGS:WD,DEFAULT_ERROR_RESP:h4,HTTP_STATUS_CODES:KD,LMDB_ERRORS_ENUM:S4,AUTHENTICATION_ERROR_MSGS:zD,VALIDATION_ERROR_MSGS:jD,ITC_ERRORS:JD}});var he=P((Zye,eL)=>{"use strict";var _u=kn(),C4=z(),P4=(k(),D(q)),pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,XD),this.statusCode=n||_u.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(_u.DEFAULT_ERROR_MSGS[n]?_u.DEFAULT_ERROR_MSGS[n]:_u.DEFAULT_ERROR_MSGS[_u.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&&C4[s](i)}},dR=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}},fR=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function XD(e,t,r,n=P4.LOG_LEVELS.ERROR,s=null,i=!1){if(ZD(e))return e;let o=new pm(e,t,r,n,s);return i&&delete o.stack,o}a(XD,"handleHDBError");function ZD(e){return e.__proto__.constructor.name===pm.name}a(ZD,"isHDBError");eL.exports={isHDBError:ZD,handleHDBError:XD,ClientError:dR,ServerError:fR,hdb_errors:_u}});var mt=P((tbe,aL)=>{"use strict";var Mf=(k(),D(q)),D4=oe(),_n=le(),vf=require("path"),L4=require("minimist"),tL=require("fs-extra"),rL=require("lodash");_n.initSync();var{CONFIG_PARAMS:pa,DATABASES_PARAM_CONFIG:Cf,SYSTEM_SCHEMA_NAME:hm}=Mf,Pf,Df,Lf;function nL(){if(Pf!==void 0)return Pf;if(_n.getHdbBasePath()!==void 0)return Pf=_n.get(pa.STORAGE_PATH)||vf.join(_n.getHdbBasePath(),Mf.DATABASES_DIR_NAME),Pf}a(nL,"getBaseSchemaPath");function sL(){if(Df!==void 0)return Df;if(_n.getHdbBasePath()!==void 0)return Df=oL(hm),Df}a(sL,"getSystemSchemaPath");function iL(){if(Lf!==void 0)return Lf;if(_n.getHdbBasePath()!==void 0)return Lf=_n.get(Mf.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||vf.join(_n.getHdbBasePath(),Mf.TRANSACTIONS_DIR_NAME),Lf}a(iL,"getTransactionAuditStoreBasePath");function M4(e,t){let r=_n.get(pa.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||vf.join(iL(),e.toString())}a(M4,"getTransactionAuditStorePath");function oL(e,t){e=e.toString(),t=t&&t.toString();let r=_n.get(Mf.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||vf.join(nL(),e)}a(oL,"getSchemaPath");function v4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,L4(process.argv));let n=r[pa.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!D4.isObject(n))throw o;i=n}for(let o of i){let c=o[hm];if(!c)continue;let l=_n.get(pa.DATABASES);l=l??{};let u=c?.tables?.[t]?.[Cf.PATH];if(u)return rL.set(l,[hm,Cf.TABLES,t,Cf.PATH],u),_n.setProperty(pa.DATABASES,l),u;let f=c?.[Cf.PATH];if(f)return rL.set(l,[hm,Cf.PATH],f),_n.setProperty(pa.DATABASES,l),f}}let s=r[pa.STORAGE_PATH.toUpperCase()];if(s){if(!tL.pathExistsSync(s))throw new Error(s+" does not exist");let i=vf.join(s,e);return tL.mkdirsSync(i),_n.setProperty(pa.STORAGE_PATH,s),i}return sL()}a(v4,"initSystemSchemaPaths");function U4(){Pf=void 0,Df=void 0,Lf=void 0}a(U4,"resetPaths");aL.exports={getBaseSchemaPath:nL,getSystemSchemaPath:sL,getTransactionAuditStorePath:M4,getTransactionAuditStoreBasePath:iL,getSchemaPath:oL,initSystemSchemaPaths:v4,resetPaths:U4}});var pn=P((ibe,fL)=>{"use strict";var x4=kn().LMDB_ERRORS_ENUM,nbe=require("lmdb"),B4=Ut(),sbe=require("buffer").Buffer,{OVERFLOW_MARKER:cL,MAX_SEARCH_KEY_LENGTH:mm}=B4,lL=["number","string","symbol","boolean","bigint"];function H4(e){if(e=e?.primaryStore||e,!e)throw new Error(x4.ENV_REQUIRED)}a(H4,"validateEnv");function k4(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(k4,"stringifyData");function F4(e){return e instanceof Date?e.valueOf():e}a(F4,"convertKeyValueToWrite");function G4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(lL.includes(typeof e))return e.length>mm?[e.slice(0,mm)+cL]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(lL.includes(typeof i))i.length>mm?r.push(i.slice(0,mm)+cL):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(G4,"getIndexedValues");var Em=0,uL=0;function dL(){uL=Date.now()-performance.now()}a(dL,"adjustStartTime");dL();var q4=6e4;setInterval(dL,q4).unref();function $4(){let e=performance.now()+uL;return e>Em?(Em=e,e):(Em+=488e-6,Em)}a($4,"getNextMonotonicTime");fL.exports={validateEnv:H4,stringifyData:k4,convertKeyValueToWrite:F4,getNextMonotonicTime:$4,getIndexedValues:G4}});var Uf=P((abe,_L)=>{"use strict";var V4=(k(),D(q)).OPERATIONS_ENUM,_R=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=V4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};_L.exports=_R});var xf=P((ube,EL)=>{"use strict";var lbe=Uf(),gm=(k(),D(q)),pR=oe(),pL=z(),K4=require("uuid"),{handleHDBError:Sm,hdb_errors:Y4}=he(),{HDB_ERROR_MSGS:Tm,HTTP_STATUS_CODES:Am}=Y4;EL.exports=hL;function hL(e,t,r){for(let s=0;s<t.length;s++)mL(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];W4(i,r,e.operation)}}a(hL,"processRows");hL.validateAttribute=mL;function mL(e){if(Buffer.byteLength(String(e))>gm.INSERT_MAX_CHARACTER_SIZE)throw Sm(new Error,Tm.ATTR_NAME_LENGTH_ERR(e),Am.BAD_REQUEST,void 0,void 0,!0);if(pR.isEmptyOrZeroLength(e)||pR.isEmpty(e.trim()))throw Sm(new Error,Tm.ATTR_NAME_NULLISH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(mL,"validateAttribute");function W4(e,t,r){if(!e.hasOwnProperty(t)||pR.isEmptyOrZeroLength(e[t])){if(r===gm.OPERATIONS_ENUM.INSERT||r===gm.OPERATIONS_ENUM.UPSERT){e[t]=K4.v4();return}throw pL.error("Update transaction aborted due to record with no hash value:",e),Sm(new Error,Tm.RECORD_MISSING_HASH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>gm.INSERT_MAX_CHARACTER_SIZE)throw pL.error(e),Sm(new Error,Tm.HASH_VAL_LENGTH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(W4,"validateHash")});var gL,Fn,hR,pu=be(()=>{gL=require("events"),Fn=class extends gL.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new hR;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(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}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)}},hR=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function OL(e){ER=e}function Q4(){J4=setInterval(function(){for(let e of mR)if(e.stale){let t=e.getContext()?.url;RL.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},j4).unref()}var gR,AL,RL,yL,bL,SL,mR,z4,Bf,TL,ER,Nc,Rm,j4,J4,ym=be(()=>{gR=M(pn()),AL=M(he()),RL=M(z()),yL=M(le());k();bL=M(oe()),SL=100,mR=new Set,z4=(0,bL.convertToMS)(yL.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(OL,"replicationConfirmation");Nc=class e{static{a(this,"DatabaseTransaction")}#e;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.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),mR.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(mR.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Bf&&!this.overloadChecked&&performance.now()-TL>z4)throw new AL.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||(0,gR.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let p=d;p<this.validated;p++)this.writes[p]?.validate?.(this.timestamp);let _;for(let p=d;p<this.validated;p++){let h=this.writes[p];h&&(h.before||h.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let p=0;p<2;p++){let h;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let R=g[p===0?"before":"beforeIntermediate"];if(R){let E=R();h?h.push?h.push(E):h=[h,E]:h=E}}h&&await(h.push?Promise.all(h):h)}}catch(p){throw this.abort(),p}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<SL>>n?l():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 Bf||(Bf=s,TL=performance.now(),Bf.then(()=>{Bf=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,p=this.writes[this.writes.length-1];ER&&p&&i.push(ER(_,p.store.getEntry(p.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+SL/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Rm=class extends Nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,gR.getNextMonotonicTime)())}getReadTxn(){}},j4=3e4;a(Q4,"startMonitoringTxns");Q4()});function Ot(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 Nc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(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 l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var NL,wc=be(()=>{NL=M(Ai());ym();a(Ot,"transaction");(0,NL._assignPackageExport)("transaction",Ot);Ot.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ot.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function TR(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let p=1;p<e.length;p++){let h=e[p],S=u(h);d=d.concat(S)}let _=new Set;return d.filter(p=>{let h=p.key??p;return _.has(h)?!1:(_.add(h),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?TR(d.conditions,d.operator,r,n,s,i,o,c):Eu(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,p){return d.map((h,S)=>{if(h.conditions){let E=h.operator==="or",T=f(h.conditions,!E,p);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(h.attribute||h[0])===r.primaryKey,R=Ff(h,r,i,c,g,p);return _&&S<d.length-1&&p&&(p=o3(r.primaryStore,h.estimated_count,p)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Eu(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new mn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=Oi(n.attributes,E);if(T.relationship){if(o.length<2)throw new mn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=T.definition?.tableClass||T.elements?.definition?.tableClass,v=new Map,H=Eu({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let $=!!Oi(w.attributes,T.relationship.to)?.elements;H=r3(H,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Eu({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=n3(H,T,w.primaryStore,v,$)):H=H.flatMap($)}return H}else if(o.length===1)o=o[0];else throw new mn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let p;switch(AR[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=bi.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,p=!0;break;default:throw new mn.ClientError(`Unknown query comparator "${l}"`)}let h,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>Ss.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,Ss.MAX_SEARCH_KEY_LENGTH)+Ss.OVERFLOW_MARKER,_=!1,h=Ff(e,n,null,i,S)),typeof f=="string"&&f.length>Ss.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,Ss.MAX_SEARCH_KEY_LENGTH)+Ss.OVERFLOW_MARKER,d=!0,h=h??Ff(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||p||c===null&&!g.indexNulls){if(s===!1&&!g)throw new mn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&p)throw new mn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(g?.isIndexing)throw new mn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new mn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(h=h??Ff(e,n,null,i,S),!h)throw new mn.ClientError(`Unknown search operator ${e.comparator}`)}let R={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(R).map(h?function({key:T,value:w}){return this?.isSync?w&&h(w)?T:ha.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&h(w)?T:ha.SKIP)}catch($){H($)}}))}:T=>T.value==null&&!(T.metadataFlags&(En|Ea))?ha.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(h?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>Ss.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?h(w)?T:ha.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(h(w)?T:ha.SKIP)}catch($){H($)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&h(T)?E:ha.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&h(T)?E:ha.SKIP)}catch(H){v(H)}}))})}function Oi(e,t){if(Array.isArray(t))if(t.length>1){let r=Oi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Oi(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 r3(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=a((u,f)=>{let d=s.get(u);d?d.push(f):s.set(u,d=[f])},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),d=f?.[c];if(d!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<d.length;_++)l(d[_],u);else l(d,u)}return i=s.keys()[Symbol.iterator](),this.next()}let o=i.next();return o.done?o:{value:o.value}},return(){if(i?.return)return i.return()}}}})}function n3(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Ff(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=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 f=c[0],d=Oi(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,p=n?.[f],h=Ff({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,p?.[f]?.joined,c[1]===_.primaryKey,i);if(!h)return;if(p){p.filters||(p.filters=[]),p.filters.push(h);return}let S=t.propertyResolvers?.[f],g,R=a((E,T)=>{let w,v;if(S){if(S.from&&h.idFilter){if(!g)if(h.idFilter.idSet?.size===1){for(let $ of h.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,h.idFilter,!0,!0)}else g=u(S.from,h.idFilter,!1,!0);let H=g(E);return g.idFilter&&(R.idFilter=g.idFilter),H}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(h):h(w,v):!1},"recordFilter");return R}}switch(l instanceof Date&&(l=l.getTime()),AR[o]||o){case Ss.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,bi.compareKeys)(f,l[0])>=0&&(0,bi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,bi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,bi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,bi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,bi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,bi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new mn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,p){let h;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Om(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(_=!1));let S=0,g=3;function R(E){let T=E[f],w;if(typeof T!="object"||!T||p?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!R.idFilter&&++S/g*(i-g)>h)){let v=Eu(e,r.transaction.getReadTxn(),!1,t).map(gu),H=new Set(v);R.idFilter=$=>H.has(gu($)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Om(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/ao(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=AR[n]||n,n===Ss.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=Oi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Om(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*ao(e.indices[i.relationship.from])/(ao(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=ao(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=e3*ao(e.primaryStore)+1:n==="between"?r.estimated_count=Z4*ao(e.primaryStore)+1:n==="sort"?r.estimated_count=ao(e.primaryStore)+1:r.estimated_count=X4*ao(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Nm(e){if(e)if(ma=e,hu.lastIndex=0,s3.test(e))try{let t=Hf(new mu,"");if(hn!==ma.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 ${hn} in '${ma}'`,t}else return new URLSearchParams(e)}function Hf(e,t){let r=hu,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(ma);){hn=r.lastIndex;let[,f,d]=n;if(o){if(f)throw new SyntaxError(`expected operator, but encountered '${f}'`);o=!1,c=!1}else c=!0;let _;switch(d){case"=":if(s!=null){if(f.length<=2)i=f;else throw new SyntaxError(`invalid FIQL operator ${f}`);l=wL}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=kf(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=t3[d],l=SR[i]?wL:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=kf(f);break;case"&=":case"|=":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||null,value:l(f)};if(i==="eq"&&IL(h,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(h),S.operator=u}else bm(e,u),e.conditions.push(h)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(kf(f)),s=void 0;break;case"(":hu.lastIndex=hn;let p=Hf(f?[]:new mu,")");switch(f){case"":bm(e,u),e.conditions.push(p);break;case"limit":switch(p.length){case 1:e.limit=+p[0];break;case 2:e.offset=+p[0],e.limit=p[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(p[0])&&p.length===1&&!p[0].name?(e.select=p[0],e.select.asArray=!0):p.length===1?e.select=p[0]:p.length===2&&p[1]===""?e.select=p.slice(0,1):e.select=p;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=CL(p);break;default:throw new SyntaxError(`unknown query function call ${f}`)}ma[hn]===","?r.lastIndex=++hn:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");hu.lastIndex=hn,_=Hf([],"}"),_.name=f,e.push(_),ma[hn]===","?r.lastIndex=++hn:o=!0;break;case"[":hu.lastIndex=hn,f?(_=Hf(new mu,"]"),_.name=f):_=Hf(e.conditions?new mu:[],"]"),e.conditions?(bm(e,u),e.conditions.push(_),s=null):e.push(_),ma[hn]===","?r.lastIndex=++hn:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&IL(h,f),bm(e,u),e.conditions.push(h)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(kf(f));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?i3:hu,r.lastIndex=hn),hn===ma.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function bm(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 kf(e){return e.indexOf(".")>-1?e.split(".").map(kf):decodeURIComponent(e)}function wL(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+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 mn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function IL(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new mn.ClientError("wildcard can only be used at the end of a string")}function CL(e){let t=PL(e[0]);return e.length>1&&(t.next=CL(e.slice(1))),t}function PL(e){if(Array.isArray(e)){let t=PL(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 gu(e){return Array.isArray(e)?e.join("\0"):e}function ao(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function o3(e,t,r){return t*r/ao(e)}var mn,Ss,bi,ha,X4,Z4,e3,t3,SR,AR,s3,hu,i3,hn,ma,mu,Ic,Gf=be(()=>{mn=M(he()),Ss=M(Ut()),bi=require("ordered-binary"),ha=require("lmdb");qf();X4=.3,Z4=.1,e3=.05,t3={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},SR={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(TR,"executeConditions");a(Eu,"searchByIndex");a(Oi,"findAttribute");a(r3,"joinTo");a(n3,"joinFrom");AR={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(Ff,"filterByType");a(Om,"estimateCondition");s3=/[()[\]|!<>.]|(=\w*=)/,hu=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,i3=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Nm,"parseQuery");a(Hf,"parseBlock");a(bm,"assignOperator");a(kf,"decodeProperty");a(wL,"typedDecoding");a(IL,"wildcardDecoding");a(CL,"toSortObject");a(PL,"toSortEntry");mu=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(gu,"flattenKey");a(ao,"estimatedEntryCount");a(o3,"intersectionEstimate");Ic=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var yR={};Ue(yR,{MultiPartId:()=>Im,Resource:()=>Yr,snake_case:()=>c3,transformForSelect:()=>Cm});function c3(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function DL(e,t){if(Cc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Cc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Im;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Cc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Cc=!0,null;e[e.length-1]==="/"&&(Cc=!0)}return t.coerceId(decodeURIComponent(e))}function Gn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let p=c.indexOf("?");if(p>-1){let S=this.parseQuery(c.slice(p+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,p)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),u=h.isCollection,c=h.id):c=h}else if(s[Symbol.iterator]){c=[],u=!0;for(let p of s){if(typeof p=="object"&&p)break;c.push(p)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new Ic(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let p=this.getResource(c,o,d);return p.then?p.then(_):_(p)}else return Ot(o,()=>{let p=this.getResource(c,o,d);return p.then?p.then(_):_(p)},d);function _(p){if(o.authorize){o.authorize=!1;let h=t.type==="read"?p.allowRead(o.user,l,o):t.type==="update"?p.doesExist?.()===!1?p.allowCreate(o.user,f,o):p.allowUpdate(o.user,f,o):t.type==="create"?p.allowCreate(o.user,f,o):p.allowDelete(o.user,l,o);if(h?.then)return h.then(S=>{if(!S)throw new wm(o.user);return typeof f?.then=="function"?f.then(g=>e(p,l,o,g)):e(p,l,o,f)});if(!h)throw new wm(o.user)}return typeof f?.then=="function"?f.then(h=>e(p,l,o,h)):e(p,l,o,f)}a(_,"authorizeActionOnResource")}}function qn(e,t){let r=new vL.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 RR(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();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 Cm(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):RR(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],f=i(RR(l,r,n));for(let d of e)u.push(f(d));return u},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(_=>_&&typeof _=="object"?c(_):_);let u={},f=i(RR(l,r,n)),d;for(let _ of e){let p=f(_);p===void 0&&o&&(p=null),p?.then?(d||(d=[]),d.push(p.then(h=>u[_.name||_]=h))):u[_.name||_]=p}return d?Promise.all(d).then(()=>u):u},"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 l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=Cm(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var LL,ML,vL,a3,Yr,wm,Cc,Im,ga=be(()=>{LL=require("crypto");pu();ML=M(Ai()),vL=M(he());wc();Gf();a3={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Yr=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Gn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=Cm(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Gn(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):qn(t,"put")},{hasContent:!0,type:"update"});static patch=Gn(function(t,r,n,s){return t.patch?t.patch(s,r):qn(t,"patch")},{hasContent:!0,type:"update"});static delete=Gn(function(t,r,n,s){return t.delete?t.delete(r):qn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,LL.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),Ot(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):qn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Gn(function(t,r,n,s){return t.invalidate?t.invalidate(r):qn(t,"delete")},{hasContent:!1,type:"update"});static post=Gn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Gn(function(t,r,n,s){return t.connect?t.connect(s,r):qn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Gn(function(t,r,n,s){return t.subscribe?t.subscribe(r):qn(t,"subscribe")},{type:"read"});static publish=Gn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):qn(t,"publish")},{hasContent:!0,type:"create"});static search=Gn(function(t,r,n,s){let i=t.search?t.search(r):qn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Cm(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Gn(function(t,r,n,s){return t.search?t.search(s,r):qn(t,"search")},{hasContent:!0,type:"read"});static copy=Gn(function(t,r,n,s){return t.copy?t.copy(s,r):qn(t,"copy")},{hasContent:!0,type:"create"});static move=Gn(function(t,r,n,s){return t.move?t.move(s,r):qn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;qn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Nm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&a3[o];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===o))if(t=t.slice(0,s),n)n.property=o;else return{query:{property:o},id:DL(t,this),isCollection:Cc}}let i=DL(t,this);return Cc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),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 l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Fn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Fn}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.#e}getContext(){return this.#t}};(0,ML._assignPackageExport)("Resource",Yr);a(c3,"snake_case");wm=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(DL,"pathToId");Im=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Gn,"transactional");a(qn,"missingMethod");a(RR,"selectFromObject");a(Cm,"transformForSelect")});var Sa,bR=be(()=>{Sa=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}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 Su={};Ue(Su,{server:()=>Ke});var UL,Ke,Lr=be(()=>{UL=M(Ai()),Ke={};(0,UL._assignPackageExport)("server",Ke)});var HL={};Ue(HL,{Resources:()=>Pm,keyArrayToString:()=>Tu,resetResources:()=>l3,resources:()=>Ts});function l3(){return Ts=new Pm,Ke.resources=Ts,Ts}function Tu(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var xL,BL,Pm,Ts,Au=be(()=>{wc();bR();xL=M(z()),BL=M(he());Lr();Pm=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,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new BL.ServerError(`Conflicting paths for ${t}`);xL.default.error(c),i.Resource=new Sa(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}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 Ot(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(l3,"resetResources");a(Tu,"keyArrayToString")});var wR={};Ue(wR,{loadGQLSchema:()=>f3,start:()=>NR,startOnMainThread:()=>d3});function NR({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,p=[],h;for(let R of d.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(W){if(W.kind==="NonNullType"){let Y=H(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:H(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(H,"getProperty");let E=R.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of R.directives){if(W.name.value==="table"){for(let se of W.arguments)w[se.name.value]=se.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=E),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,p.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,$={};for(let W of R.fields){let te=H(W.type);te.name=W.name.value,T.push(te),$[te.name]=void 0;for(let se of W.directives){let Y=se.name.value;if(Y==="primaryKey")v?console.warn("Can not define two attributes as a primary key at",se.loc):(te.isPrimaryKey=!0,v=!0);else if(Y==="indexed")te.indexed=!0;else if(Y==="computed"){for(let ne of se.arguments||[])if(ne.name.value==="from"){let ue=ne.value.value;te.computed={from:g(ue,ne,$)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(h=w)}function S(R){let E=_.get(R.type);E?(Object.defineProperty(R,"properties",{value:E.properties}),Object.defineProperty(R,"definition",{value:E})):R.type==="array"?S(R.elements):u3.includes(R.type)||(0,FL.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let R of _.values())for(let E of R.properties)S(E);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,OR.dirname)(n),R.tableClass):i.set((0,OR.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new kL.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var OR,kL,FL,u3,d3,f3,GL=be(()=>{OR=require("path"),kL=require("node:vm");Le();FL=M(tt()),u3=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(NR,"start");d3=NR,f3=NR({ensureTable:dt}).handleFile});var zL={};Ue(zL,{parse:()=>CR,streamAsJSON:()=>$f,stringify:()=>Pc});function $f(e){return new IR({value:e})}function qL(e){return console.error(e),JSON.stringify(e.toString())}function $L(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===YL)return WL(e);if(t.resolution)return t.resolution.then(()=>Pc(e));throw t}}function WL(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+=WL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Pc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function CR(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),h3.test(e)?_3.parse(e):JSON.parse(e)):null}var VL,KL,_3,p3,YL,IR,h3,PR=be(()=>{VL=require("stream"),KL=M(require("json-bigint-fixes")),_3=(0,KL.default)({useNativeBigInt:!0}),p3=1e4,YL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw YL};a($f,"streamAsJSON");IR=class extends VL.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(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")}}if(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),qL)}catch(s){yield qL(s)}else yield Pc(t)}else yield Pc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);$L(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>p3?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 $L(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(qL,"handleError");a($L,"when");a(Pc,"stringify");a(WL,"jsStringify");h3=/[[,:]\s*-?\d{16,}/;a(CR,"parse")});var Ni=P(Lm=>{var Dm=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])Dm.logsAtLevel(e)&&(Lm[e]=Dm[e]);Lm.loggerWithTag=e=>Dm.loggerWithTag(e,!0);Lm.setLogLevel=Dm.setLogLevel});var $m={};Ue($m,{Blob:()=>wi,blobsWereEncoded:()=>Lc,databasePaths:()=>LR,decodeBlobsWithWrites:()=>Gm,decodeFromDatabase:()=>Mc,decodeWithBlobCallback:()=>qm,deleteBlob:()=>Hm,deleteBlobsInObject:()=>Ta,deleteRootBlobPathsForDB:()=>vR,encodeBlobsAsBuffers:()=>O3,encodeBlobsWithFilePath:()=>Fm,findBlobsInObject:()=>yu,getFileId:()=>km,getFilePathForBlob:()=>sM,getRootBlobPathsForDB:()=>Wf,setDeletionDelay:()=>S3});function tM(){}function Hm(e){let t=sM(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&co.default.debug?.("Error trying to remove blob file",r)})},rM)}function S3(e){rM=e}function nM(e){let t=gn.get(e);if(!t)t={storageIndex:0,fileId:null,store:Sn},gn.set(e,t);else{if(t.saving)return t;t.store=Sn}return A3(t),t.source?DR(e,t.source,t):t.contentBuffer?T3(e,t):DR(e,Kf.Readable.from(e.stream()),t),t}function DR(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,je.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([h(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(h(e.size)),_=!0);let p;o?(_||d.write(E3),p=(0,xm.createDeflate)(),t.pipe(p).pipe(d)):(_||d.write(m3),t.pipe(d)),t.on("error",S);function h(g){let R=BigInt(g),E=new Uint8Array(gr),T=new DataView(E.buffer);return R|=BigInt(o?MR:eM)<<48n,T.setBigInt64(0,R),E}a(h,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,je.close)(R),u(g)):c?(0,je.fdatasync)(R,E=>{E&&u(E),l(),(0,je.close)(R)}):(l(),(0,je.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=p?p.bytesWritten:d.bytesWritten-gr;e.size=g,(0,je.write)(d.fd,h(g),0,gr,0,S)}})}),e}function km(e){return gn.get(e)?.fileId}function sM(e){let t=gn.get(e);return t?.fileId&&Yf(t)}function Wf(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=LR.get(e);if(!t){if(!e.databaseName)return co.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,Bm.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,uo.join)(n,e.databaseName)):t=[(0,uo.join)((0,Bm.getHdbBasePath)(),"blobs",e.databaseName)],LR.set(e,t)}return t}async function vR(e){let t=Wf(e);t&&await Promise.all(t.map(r=>iM(r)))}async function iM(e){if((0,je.existsSync)(e)){for(let t of await(0,Qs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await iM((0,uo.join)(e,t.name));else try{await(0,Qs.unlink)((0,uo.join)(e,t.name))}catch(r){co.default.warn?.("Error deleting file",r)}try{await(0,Qs.rmdir)(e)}catch(t){co.default.warn?.("Error deleting directory",t)}}}function Yf({storageIndex:e,fileId:t,store:r}){let n=Wf(r);return(0,uo.join)(n[e],t.slice(-9,-6)||"0",t.slice(-6,-3)||"0",t.length<=9?t.slice(-3):t.slice(0,-9)+t.slice(-3))}function T3(e,t){let r=t.contentBuffer,n=r.length;if(!(n<ZL))return e.size=n,DR(e,Kf.Readable.from([r]),t)}function A3(e){let t=Wf(e.store),r=R3(),n=t?.length>1?y3(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Yf(e),o=(0,uo.dirname)(i);(0,je.existsSync)(o)||(0,XL.ensureDirSync)(o),e.filePath=i}function R3(){let e=QL.get(Sn);if(!e){let t=0,r=Wf(Sn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,uo.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(Sn.getUserSharedBuffer("blob-file-id",e.buffer)),QL.set(Sn,e)}return Number(Atomics.add(e,0,1n))}function y3(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(Um);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,b3(e)),e.frequencyTable[t%Um]}async function b3(e){if(!Qs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Qs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(Um),n=t.map(s=>1/s);for(let s=0;s<Um;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function Fm(e,t,r){Ru=t,Sn=r,Lc=!1;try{return e()}finally{Ru=void 0,Sn=void 0}}function O3(e){Mr=[];let t;try{t=e()}catch(n){throw Mr=void 0,n}let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r?r.then(()=>e()):t}function Gm(e,t){try{Mr=[],Dc=t,e()}catch(n){throw Dc=void 0,Mr=void 0,n}Dc=void 0;let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r}function qm(e,t,r){Sn=r;try{return Dc=t,e()}finally{Dc=void 0}}function Mc(e,t){return Sn=t,e()}function Ta(e){yu(e,t=>{Hm(t)})}function yu(e,t){if(e instanceof wi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&yu(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&yu(e[r],t)}}function N3(){return class{static{a(this,"Blob")}content;constructor(t){this.content=t[0]}stream(){return new ReadableStream({start(t){t.enqueue(this.content),t.close()}})}text(){return Promise.resolve(this.content.toString())}arrayBuffer(){return Promise.resolve(this.content.buffer)}get size(){return this.content.length}slice(){throw new Error("Not implemented")}bytes(){return Promise.resolve(this.content)}get type(){return""}}}var lo,Qs,je,xm,Kf,XL,Bm,uo,co,ZL,gr,eM,MR,jL,m3,E3,JL,gn,Dc,wi,Ru,Mr,Sn,Lc,Vf,Mm,g3,vm,rM,LR,QL,Um,As=be(()=>{lo=require("msgpackr"),Qs=require("node:fs/promises"),je=require("node:fs"),xm=require("node:zlib"),Kf=require("node:stream"),XL=require("fs-extra"),Bm=M(le());k();uo=require("path"),co=M(Ni());fo();ZL=8192,gr=8,eM=0,MR=1,jL=255,m3=new Uint8Array([0,eM,255,255,255,255,255,255]),E3=new Uint8Array([0,MR,255,255,255,255,255,255]),JL=0xffffffffffff,gn=new WeakMap,wi=global.Blob||N3(),Lc=!1,Vf=new Uint8Array(8),Mm=new DataView(Vf.buffer),g3=6e4;a(tM,"InstanceOfBlobWithNoConstructor");tM.prototype=wi.prototype;vm=class e extends tM{static{a(this,"FileBackedBlob")}type="";size;#e;#t;constructor(t){super(),t?.type&&(this.type=t.type),t?.size!=null&&(this.size=t.size)}on(t,r){if(t==="error")this.#e??=[],this.#e.push(r);else if(t==="size")this.#t??=[],this.#t.push(r);else throw new Error("Only 'error' and 'size' events are supported")}toJSON(){if(this.type?.startsWith("text")){let t=gn.get(this),{start:r,end:n,contentBuffer:s,asString:i}=t;return i||(s&&(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),s?(t.asString=s.toString(),t.asString):(xR()&&UR(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=gn.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Yf(t),o,c=a(async()=>{let l,u=gr;try{if(l=await(0,Qs.readFile)(i),l.length>=gr){l.copy(Vf,0,0,gr);let d=Mm.getBigUint64(0);if(Number(d>>48n)===jL)throw new Error("Error in blob: "+buffer.subarray(gr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<JL&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,p=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((h,S)=>{if(_.attemptLock(p,0,()=>(o=!0,_.unlock(p,0),h(c()))))return o=!0,_.unlock(p,0),h(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===MR?new Promise((d,_)=>{(0,xm.deflate)(l.subarray(gr),(p,h)=>{p?_(p):d(f(h))})}):f(l.subarray(gr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=gn.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Yf(t),o,c=0,l=0,u,f,d,_=!1,p=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(co.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{h(),g(R,E)},20).unref();E(T),p.#e?.forEach(v=>v(T))}else o=w,R(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,R=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),p.#e?.forEach(W=>W($))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,je.read)(o,H,0,H.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<gr){R-- >0&&d!==!1?(h(),co.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(co.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(Vf,0,0,gr);let se=Mm.getBigUint64(0);if(Number(se>>48n)===jL)return v(new Error("Error in blob: "+te.subarray(gr)));if(g=Number(se&0xffffffffffffn),g<JL&&p.size!==g&&(p.size=g,p.#t))for(let Y of p.#t)Y(g);te=te.subarray(gr,W),l-=gr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,gr,0,Y=>{if(Y)return v(Y);if(Vf.set(se),g=Number(Mm.getBigUint64(0)&0xffffffffffffn),g>l){h()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},g3).unref():(u=(0,je.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,je.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return co.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.close)(o),clearTimeout(f),u&&u.close()}});function h(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=gn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};gn.set(i,o),this.size!=null&&(i.size=(r==null?this.size:Math.min(r,this.size))-(t??0))}else if(s?.contentBuffer&&!s.storageBuffer){let o={...s,contentBuffer:s.contentBuffer.subarray(t,r)};gn.set(i,o),i.size=(r??this.size)-t}else throw new Error("Can not slice a streaming blob that is not backed by a file");return i}save(t){if(Sn=t?.primaryStore?.rootStore,!Sn)throw new Error("No target table specified");return nM(this).saving??Promise.resolve()}},rM=500;a(Hm,"deleteBlob");a(S3,"setDeletionDelay");global.createBlob=function(e,t){let r=new vm(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(gn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Kf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Kf.Readable.from(e);else throw new Error("Invalid source type");return r};a(nM,"saveBlob");a(DR,"writeBlobWithStream");a(km,"getFileId");a(sM,"getFilePathForBlob");LR=new Map;a(Wf,"getRootBlobPathsForDB");a(vR,"deleteRootBlobPathsForDB");a(iM,"rimrafSteadily");a(Yf,"getFilePath");a(T3,"writeBlobWithBuffer");a(A3,"generateFilePath");QL=new Map;a(R3,"getNextFileId");Um=128;a(y3,"getNextStorageIndex");a(b3,"createFrequencyTableForStoragePaths");a(Fm,"encodeBlobsWithFilePath");a(O3,"encodeBlobsAsBuffers");a(Gm,"decodeBlobsWithWrites");a(qm,"decodeWithBlobCallback");a(Mc,"decodeFromDatabase");a(Ta,"deleteBlobsInObject");a(yu,"findBlobsInObject");(0,lo.addExtension)({Class:wi,type:11,unpack:a(function(e){let t=(0,lo.unpack)(e),r=new vm;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(gn.set(r,{storageIndex:t[1],fileId:t[2],store:Sn}),Dc)return Dc(r)??r;if(!Sn)throw new Error("No store specified, cannot load blob from storage")}else gn.set(r,{storageIndex:0,fileId:null,storageBuffer:e,contentBuffer:t[1]}),r.size=t[1]?.length;return r},"unpack"),pack:a(function(e){let t=gn.get(e);if(Ru!==void 0&&(Lc=!0,t?.recordId!==void 0&&t.recordId!==Ru))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<ZL)return r.size=t.contentBuffer.length,(0,lo.pack)([r,t.contentBuffer])}if(Ru!==void 0){if(t=nM(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Ru,(0,lo.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Yf(t));if(n.length>=gr&&(n.copy(Vf,0,0,gr),Number(Mm.getBigUint64(0)&0xffffffffffffn)===n.length-gr))return Buffer.concat([(0,lo.pack)([r]),n]);if(Mr)Mr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Mr)return Mr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,lo.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(N3,"polyfillBlob")});var _M={};Ue(_M,{asyncSerialization:()=>UR,contentTypes:()=>FR,findBestSerializer:()=>Km,getDeserializer:()=>ho,hasAsyncSerialization:()=>xR,registerContentHandlers:()=>Jf,serialize:()=>Qf,serializeMessage:()=>Aa,toCsvStream:()=>Vm});function I3(e){try{return e?.[0]===123?kR(e):e}catch{return e}}function Jf(e){e.register(P3,{serializers:[{regex:/^application\/json$/,serializer:$f},{regex:/^application\/cbor$/,serializer:a(function(t){return new vc.EncoderStream(jf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Uc.Readable.from((0,Ii.encodeIter)(t,jf)):(0,Ii.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),Vm(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ii.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,vc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Km(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let h of f){let S=h.indexOf("=");_[h.substring(0,S)]=h.substring(S+1)}d=+_.q;let p=Wr.get(u);if(p){let h=(p.q||1)*d;h>s&&(n=p,i=p.type||u,s=h,o=_)}}if(!n){if(r)throw new cM.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Wr.keys()).join(", "),406);n=Wr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Qf(e,t,r){let n=aM&&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||e instanceof wi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Km(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&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),HR.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,po.createBrotliCompress)({params:{[po.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?po.constants.BROTLI_MODE_TEXT:po.constants.BROTLI_MODE_GENERIC,[po.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>aM?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,po.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function Aa(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;_o=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=Km(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=zf(e);return _o?.length>0?(_o.length===1?_o[0]:Promise.all(_o)).then(()=>Aa(e,t,!0)):n}finally{_o=void 0}}function UR(e){if(_o)_o.push(e);else throw new Error("Unable to serialize asynchronously")}function xR(){return!!_o}function D3(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 M3(e){return L3.includes(e)}function v3(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function ho(e="",t=!1){let r=v3(e),n=r.type&&Wr.get(r.type)?.deserialize||U3(r);return t?s=>D3(s).then(n):n}function U3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!M3(e.parameters.charset)&&HR.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return kR(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function x3(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)}}}}}function Vm(e,t){let r=Uc.default.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 w3(n,s);return r.pipe(i)}var Ii,vc,po,cM,Uc,lM,BR,uM,HR,w3,dM,zf,kR,jf,Wr,FR,oM,fM,C3,P3,aM,_o,L3,fo=be(()=>{PR();Ii=require("msgpackr"),vc=require("cbor-x"),po=require("zlib"),cM=M(he()),Uc=M(require("stream"));Lr();lM=M(Ai()),BR=M(le());k();uM=M(require("yaml")),HR=M(Ni());As();({Transform:w3}=require("json2csv")),dM=BR.default.get(U.SERIALIZATION_BIGINT)!==!1,zf=dM?Pc:JSON.stringify,kR=dM?CR:JSON.parse,jf={useRecords:!1,useToJSON:!0},Wr=new Map,FR=Wr;Ke.contentTypes=FR;(0,lM._assignPackageExport)("contentTypes",FR);Wr.set("application/json",{serializeStream:$f,serialize:zf,deserialize(e){return kR(e)},q:.8});oM=new vc.Encoder(jf);Wr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new vc.EncoderStream(jf).end(e)},serialize:oM.encode,deserialize:oM.decode,q:1});Wr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Uc.Readable.from((0,Ii.encodeIter)(e,jf)):(0,Ii.pack)(e)},serialize:Ii.pack,deserialize:Ii.unpack,q:.9});Wr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),Vm(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]),Vm(e,e?.getColumns?.())},q:.1});Wr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return Uc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Wr.set("text/yaml",{serialize(e){return uM.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Wr.set("text/event-stream",{serializeStream:a(function(e){return Uc.Readable.from(x3(e,this.serialize))},"serializeStream"),serialize:a(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+`
|
|
9
9
|
`),e.data){let r=e.data;typeof r=="object"&&(r=zf(r)),t+="data: "+r+`
|
|
10
10
|
`}return e.id&&(t+="id: "+e.id+`
|
|
11
11
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
@@ -130,7 +130,7 @@ Connection: close\r
|
|
|
130
130
|
\r
|
|
131
131
|
`))}},25).unref()}o.close?.(()=>{if(ot.get(jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&Qd()==0)try{az(uz(ot.get(jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,GT),o.cantCleanupProperly||Un.warn("Had to forcefully exit the thread",GT),process.exit(0)},5e3).unref()})}if(dz||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Un.info("Could not close debugger",i)}}}).ref();let e;Oh&&!xSe&&(e=_z()),Promise.resolve(e).then(()=>{if(Qd()===0)try{MSe(qC)}catch(t){console.error("Error displaying start-up log",t)}Nh?.postMessage({type:jt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(fz,"startServers");function _z(){let e=[];for(let t in Qi){let r=Qi[t];if(t.includes?.("/")&&Qd()==0){NSe(t)&&az(t),e.push(new Promise((o,c)=>{r.listen({path:t},()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),Un.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=ot.get(jt.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let o=typeof s=="string"?s.split("-"):s,c=Qd();if(c<o[0]||c>o[1])continue}let i;try{let o=t.lastIndexOf(":");o>0?Oh?n={fd:Oh(+t.slice(o+1).replace(/[\[\]]/g,""),t.slice(0,o))}:n={host:+t.slice(o+1).replace(/[\[\]]/g,""),port:t.slice(0,o)}:Oh?n={fd:Oh(+t,"::")}:n={port:t}}catch(o){console.error(`Unable to bind to port ${t}`,o);continue}e.push(new Promise((o,c)=>{r.listen(n,()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),Un.trace("Listening on port "+t,GT)}).on("error",c)}))}return Promise.all(e)}a(_z,"listenOnPorts");!FC&&!gSe?.noServerStart&&fz();function KC(e,t,r){let n=e?.read?e:new SSe({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Qi[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=Qi[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Un.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(KC,"deliverSocket");var rz=new Map;function BSe(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=rz.get(s),r){case"connection":i=KC(void 0,t),rz.set(s,i),i.write=(c,l,u)=>(Nh.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(Nh.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Nh.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(BSe,"proxyRequest");var{getComponentName:$T}=(Jp(),D(jp));function YC(e,t,r=!0){t||(t=ot.get(jt.CONFIG_PARAMS.HTTP_PORT));let n=Qi[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",oz),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else Qi[t]=e;e.on("unhandled",oz)}a(YC,"registerServer");function WC(e){let t=[],r=e?.securePort;return r&&t.push({port:r,secure:!0}),r=e?.port,r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],ot.get(jt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:ot.get(jt.CONFIG_PARAMS.HTTP_PORT),secure:ot.get(jt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),ot.get(jt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:ot.get(jt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&ot.get(jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:uz(ot.get(jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}a(WC,"getPorts");function zC(e,t){let r=[];for(let{port:n,secure:s}of WC(t))r.push(pz(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?$C[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,YC(e,n,!1)),qT[n]=KT($C,n);return r}a(zC,"httpServer");function VT(e,t){let r=qC.get(e)??[];qC.set(e,[...r,t])}a(VT,"setPortServerMap");function pz(e,t,r,n){if(VT(e,{protocol_name:t?"HTTPS":"HTTP",name:$T()}),!FT[e]){let s=r?"operationsApi_network":"http",i=ot.get(s+"_keepAliveTimeout"),o=ot.get(s+"_timeout"),c=ot.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:o,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:ot.get(jt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)},u=ot.get(s+"_mtls"),f=ot.get(s+"_mtls_required"),d;if(t){let h=ot.get("tls");d=ot.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!f,requestCert:!!(u||n),ticketKeys:CSe(),SNICallback:lz(r?"operations-api":"server",u),ciphers:h.ciphers??h[0]?.ciphers})}let _=LSe(),p=FT[e]=(t?d?bSe:ySe:ASe)(l,async(h,S)=>{try{let R=performance.now(),E=new cz(h,S);r&&(E.isOperationsServer=!0);let T=await qT[e](E);if(!T){if(E._nodeResponse.statusCode)return;T=hz(E)}if(T.headers?.set||(T.headers=new GC(T.headers)),_?T.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):T.headers?.set?.("Server","HarperDB"),T.status===-1){for(let ne of T.headers||[])S.setHeader(ne[0],ne[1]);return h.baseRequest=E,S.baseResponse=T,FT[e].emit("unhandled",h,S)}let w=T.status||200,v=performance.now(),H=v-R,$=T.body,W,te=!1;if(!T.handlesHeaders){let ne=T.headers||new GC;$?$.length>=0?(typeof $=="string"?ne.set("Content-Length",Buffer.byteLength($)):ne.set("Content-Length",$.length),W=!0):$ instanceof OSe&&($.size?ne.set("Content-Length",$.size):$.on&&(te=!0,$.on("size",ae=>{S.headersSent||S.setHeader("Content-Length",ae)})),$=$.stream()):(ne.set("Content-Length","0"),W=!0);let ue=`hdb;dur=${H.toFixed(2)}`;if(T.wasCacheMiss&&(ue+=", miss"),DSe(ne,"Server-Timing",ue,!0),!S.headersSent)if(te){if(S.statusCode=w,ne)if(ne[Symbol.iterator])for(let[ae,me]of ne)S.setHeader(ae,me);else for(let ae in ne)S.setHeader(ae,ne[ae])}else S.writeHead(w,ne&&(ne[Symbol.iterator]?Array.from(ne):ne));W&&S.end($)}let se=E.handlerPath,Y=E.method;if(yh(H,"duration",se,Y,T.wasCacheMiss==null?void 0:T.wasCacheMiss?"cache-miss":"cache-hit"),ez(w<400,"success",se,Y),ez(1,"response_"+w,se,Y),!W)if($ instanceof ReadableStream&&($=tz.fromWeb($)),($[Symbol.iterator]||$[Symbol.asyncIterator])&&($=tz.from($)),$?.pipe){$.pipe(S),$.destroy&&S.on("close",()=>{$.destroy()});let ne=0;$.on("data",ue=>{ne+=ue.length}),$.on("end",()=>{yh(performance.now()-v,"transfer",se,Y),yh(ne,"bytes-sent",se,Y)})}else $?.then?$.then(ne=>{S.end(ne)},g):S.end($)}catch(R){g(R)}function g(R){let E=R.headers;S.writeHead(R.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),S.end(R.toString()),R.statusCode?R.statusCode===500?Un.warn(R):Un.info(R):Un.error(R)}a(g,"onError")});i>=0&&(p.keepAliveTimeout=i),c>=0&&(p.headersTimeout=c),t&&(p.ports||(p.ports=[]),p.ports.push(e),l.SNICallback.initialize(p),u&&(p.mtlsConfig=u),p.on("secureConnection",h=>{h._parent.startTime&&yh(performance.now()-h._parent.startTime,"tls-handshake",e),yh(h.isSessionReused(),"tls-reused",e)}),p.isSecure=!0),YC(p,e)}return FT[e]}a(pz,"getHTTPServer");function KT(e,t){let r=hz;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(KT,"makeCallbackChain");function hz(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new GC}}a(hz,"unhandled");function HSe(e,t){zC(e,{requestOnly:!0,...t})}a(HSe,"onRequest");function kSe(e,t){let r;if(t.securePort){VT(t.securePort,{protocol_name:"TLS",name:$T()});let n=lz("server",t.mtls),s=ot.get("tls");r=ISe({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,ciphers:s.ciphers??s[0]?.ciphers,SNICallback:n},e),n.initialize(r),Qi[t.securePort]=r}return t.port&&(VT(t.port,{protocol_name:"TCP",name:$T()}),r=TSe(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),Qi[t.port]=r),r}a(kSe,"onSocket");Object.defineProperty(RSe.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.toLowerCase().includes("upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});var nz=[],VC={};function mz(e,t){for(let{port:r}of WC(t))nz[t?.runFirst?"unshift":"push"]({listener:e,port:r}),VC[r]=KT(nz,r)}a(mz,"onUpgrade");var sz=[],iz={};function FSe(e,t){let r=[];for(let{port:n,secure:s}of WC(t)){VT(n,{protocol_name:s?"WSS":"WS",name:$T()});let i=pz(n,s,t?.isOperationsServer,t?.mtls);bh[n]||(bh[n]=new wSe({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),bh[n].on("connection",(o,c)=>{let l=new cz(c);l.isWebSocket=!0;let u=qT[n](l);iz[n](o,l,u)}),mz((o,c,l,u)=>o.__harperdb_request_upgraded?u(o,c,l):bh[n].handleUpgrade(o,c,l,f=>{o.__harperdb_request_upgraded=!0,u(o,c,l),bh[n].emit("connection",f,o)}),{port:n}),i.on("upgrade",(o,c,l)=>{VC[n]&&VC[n](o,c,l)})),r.push(i),sz[t?.runFirst?"unshift":"push"]({listener:e,port:n}),iz[n]=KT(sz,n),qT[n]=KT($C,n)}return r}a(FSe,"onWebSocket");function oz(e,t){t.writeHead(404),t.end(`Not found
|
|
132
132
|
`)}a(oz,"defaultNotFound")});var ZW={};Ue(ZW,{startHTTPThreads:()=>qSe,startSocketServer:()=>eP,updateWorkerIdleness:()=>Oz});async function qSe(e=2,t){try{if(t)XC(0,1,!0);else{let{loadRootComponents:r}=YT();if(e===0)return(0,ks.setMainIsWorker)(!0),await jC().startServers(),Promise.resolve([]);await r()}bz();for(let r=0;r<e;r++)XC(r,e);return Promise.all(yz)}finally{(0,ks.threadsHaveStarted)()}}function bz(){let e=(0,Tz.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),QC=setInterval(()=>{jT.notify(e)},GSe).unref())}function XC(e,t=1,r){if(JC++,(0,ks.startWorker)("server/threads/threadServer.js",{name:sR.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(u){u.type===tR.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});yz.push(s),await s,Xd.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=zT.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Xd.indexOf(n);o>-1&&Xd.splice(o,1)}if(a(i,"removeWorker"),Zd){let o=Zd;Zd=[];for(let c of o)Rz[c.localPort](null,c)}}}),r){let n=setInterval(()=>{ZC?ZC=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ks.shutdownWorkers)(),JC=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function eP(e=0,t){if(typeof e=="string")try{(0,JT.existsSync)(e)&&(0,JT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=$Se:r=VSe(t):r=tP;let n=(0,ef.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=Rz[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),ZC=!0,r(i,(o,c)=>{if(!o){if(Ez){let u=i._socket||new ef.Socket({handle:i,writable:!0,readable:!0});Ez.deliverSocket(u,e,c),u.resume()}else JC>0?(Zd.length===0&&setTimeout(()=>{Zd.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(),i.localPort=e,Zd.push(i)):(console.log("start up a dynamic thread to handle request"),XC(0));nr(!1,"socket-routed");return}o.requests++;let l=i.fd;if(l>=0)o.postMessage({port:e,fd:l,data:c});else{let u=i._socket||new ef.Socket({handle:i,writable:!0,readable:!0});WSe(u,o,e)}nr(!0,"socket-routed")})},jT.info(`HarperDB ${Az.packageJson.version} Server running on port ${e}`)),n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function tP(e,t){let r,n=0;for(let s of Xd){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=WT)return WT=i,t(r);n=i}WT=0,t(r)}function $Se(e,t){let r={};e.getpeername(r);let n=r.address,s=tf.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);tP(e,o=>{tf.set(n,{worker:o,lastUsed:i}),t(o)})}function VSe(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new ef.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],u=tf.get(l),f=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=f,s(u.worker);tP(n,d=>{tf.set(l,{worker:d,lastUsed:f}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Oz(){WT=0;for(let e of Xd)e.expectedIdle=e.recentELU.idle+KSe,e.requests=1;Xd.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function WSe(e,t,r){let n=YSe++;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(),zT.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")),zT.delete(n)),s.event=="destroy"&&(e.destroy(),zT.delete(n))})}var ks,ef,jT,JT,Sz,Tz,Az,Xd,Zd,Rz,Ez,JC,yz,QC,GSe,ZC,WT,gz,tf,KSe,zT,YSe,kC=be(()=>{ks=M(tt()),ef=require("net");k();jT=M(z()),JT=require("fs");ki();Sz=require("worker_threads"),Tz=M(bd()),Az=M(nt()),Xd=[],Zd=[],Rz=[],JC=0,yz=[];Sz.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ks.onMessageFromWorkers)(e=>{e.type===nR.RESTART&&QC&&(clearInterval(QC),bz())}));GSe=6e5;a(qSe,"startHTTPThreads");a(bz,"licenseWarning");a(XC,"startHTTPWorker");a(eP,"startSocketServer");WT=0;a(tP,"findMostIdleWorker");gz=36e5,tf=new Map;a($Se,"findByRemoteAddressAffinity");a(VSe,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of tf)r.lastUsed+gz<e&&tf.delete(t)},gz).unref();KSe=1e3;a(Oz,"updateWorkerIdleness");(0,ks.setMonitorListener)(Oz);zT=new Map,YSe=1;a(WSe,"proxySocket")});var Fz=P((t0e,kz)=>{var wz=M(require("cluster")),dc=M(le());k();var Xi=M(z()),Iz=M(require("fastify")),Cz=M(require("@fastify/cors")),Pz=M(require("@fastify/compress")),Dz=M(require("@fastify/static")),Lz=M(IO()),Mz=M(require("path")),vz=M(nt()),Uz=M(bs()),xz=M(oe()),Bz=M(On()),Hz=M(bd());Lr();var fc=M(ST());fo();dc.default.initSync();var zSe=6e4,jSe=1024*1024*1024,JSe="TRUE",{CONFIG_PARAMS:Ih}=q,rf;kz.exports={hdbServer:Nz,start:Nz};async function Nz(e){try{Xi.default.debug("In Fastify server"+process.cwd()),Xi.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Xi.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=wz.default.isMaster,await QSe();let t=e.securePort>0;rf=XSe(t),await rf.ready(),e||(e={}),e.isOperationsServer=!0;try{Ke.http(rf.server,e),rf.server.closeIdleConnections||await rf.listen({port:0,host:"::"})}catch(r){throw rf.close(),Xi.default.error(r),Xi.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Xi.default.fatal(t),process.exit(1)}}a(Nz,"operationsServer");async function QSe(){Xi.default.trace("Configuring HarperDB process."),Uz.default.setSchemaDataToGlobal(),await Bz.default.setUsersWithRolesCache(),await Hz.default.getLicense()}a(QSe,"setUp");function XSe(e){Xi.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=ZSe(e),r=(0,Iz.default)(t);r.server.headersTimeout=tTe(),r.setErrorHandler(fc.serverErrorHandler);let n=eTe();n&&r.register(Cz.default,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(Lz.default),r.register(Pz.default),r.register(Dz.default,{root:Mz.default.join(vz.PACKAGE_ROOT,"studio/build-local")}),Jf(r);let s=dc.default.get(eR.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!xz.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[fc.reqBodyValidationHandler,fc.authHandler],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),(0,fc.handlePostRequest)(i,o)}),r.get("/health",()=>"HarperDB is running."),Xi.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(XSe,"buildServer");function ZSe(e){let t=dc.default.get(Ih.OPERATIONSAPI_NETWORK_TIMEOUT),r=dc.default.get(Ih.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:jSe,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(ZSe,"getServerOptions");function eTe(){let e=dc.default.get(Ih.OPERATIONSAPI_NETWORK_CORS),t=dc.default.get(Ih.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===JSe)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(eTe,"getCORSOpts");function tTe(){return dc.default.get(Ih.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??zSe}a(tTe,"getHeaderTimeoutConfig")});var aP={};Ue(aP,{disableNATS:()=>nTe,publishToStream:()=>ZT,setNATSReplicator:()=>rP,setPublishToStream:()=>sTe,setSubscription:()=>oP,start:()=>rTe});function rTe(){Ch.default.get(U.CLUSTERING_ENABLED)&&oTe()}function nTe(e=!0){Kz=e}function sTe(e,t){ZT=e,oP=t}function oTe(){if(Kz||process.env._DISABLE_NATS)return;let e=Qe(),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];rP(s,r,i)}}Tl((r,n)=>{rP(r.tableName,r.databaseName,r),n&&Wz(r)}),!Gz&&(Gz=!0)}function rP(e,t,r){if(t==="system"&&aTe.includes(e))return;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 Yr{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this.getId(),record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this.getId()})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this.getId(),record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this.getId(),record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this.getId()})}static defineSchema(i){Wz(i)}static subscribe(){let i=new Fn;return oP(t,e,i),i}static subscribeOnThisThread(i){return i<(Ch.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??iTe)}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 QT(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=Yz;return i}a(n,"getNATSTransaction")}function Wz(e){let t=Ch.default.get(U.CLUSTERING_NODENAME);ZT(`${sP.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,iP.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 qz,sP,iP,$z,Vz,Ch,XT,Kz,ZT,oP,iTe,Yz,Gz,aTe,QT,nP,zz=be(()=>{Le();ga();qz=M(sr()),sP=M(St()),iP=M(Ao());pu();$z=M(qO()),Vz=M(pn()),Ch=M(le());k();XT=M(z());a(rTe,"start");a(nTe,"disableNATS");ZT=qz.publishToStream,oP=$z.setSubscription;a(sTe,"setPublishToStream");iTe=2;a(oTe,"assignReplicationSource");aTe=["hdb_job","hdb_analytics","hdb_raw_analytics","hdb_info","hdb_license"];a(rP,"setNATSReplicator");a(Wz,"publishSchema");QT=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=Ch.default.get(U.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,u;for(let f of i){let d=f.table,_=f.operation=="put"?"upsert":f.operation;l||(XT.trace(`Sending transaction event ${_}`),u=l={operation:_,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,_!=="delete"&&_!=="invalidate"&&(l.records=o)),l.table===d&&l.operation===_?(o.push(f.record),c.push(f.id)):u=u.next={operation:_,table:d,id:f.id,record:f.record},f.expiresAt&&(u.expiresAt=f.expiresAt)}l&&n.push(ZT(`${sP.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,iP.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(f=>{throw XT.error("An error has occurred trying to replicate transaction",l,f),f.statusCode=504,f}))}return Promise.all(n)}},nP=class extends QT{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,Vz.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};Yz=new nP});async function Zz({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await cP.get(e,{returnNonexistent:!0});i=new dP(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await cP.get(e);o&&o.delete()}i=new tA(e,t)}return n&&(n.id=e,n.user={username:t?.username},Ph.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function lP(){return eA++,eA>65500&&(eA=1),eA}function uP(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Ts.getMatch(n,"mqtt");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 Ot(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var Jz,_c,Qz,Xz,jz,cP,Ph,eA,tA,dP,ej=be(()=>{Le();Au();Jz=M(pn()),_c=M(z());wc();Qz=M(tt()),Xz=M(jC());Lr();jz=100,cP=dt({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),Ph=dt({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,Qz.getWorkerIndex)()===0&&(async()=>{await Xz.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ph.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Ke.getUser(r.user.username));try{await uP(r,t,r)}catch{(0,_c.warn)("Failed to publish will",t)}Ph.delete(e.id)}})();a(Zz,"getSession");eA=1;a(lP,"getNextMessageId");tA=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("?"),l,u;if(c>-1?(l=s.slice(c),u=s.slice(0,c)):u=s,!u)throw new Error("No topic provided");if(u.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let f=this.subscriptions.find(R=>R.topic===s),d;f?(d=i>0,f.end(),this.subscriptions.splice(this.subscriptions.indexOf(f),1)):d=i===2;let _={search:l,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,_c.trace)("Resuming subscription from",s,"from",o);let p=Ts.getMatch(u,"mqtt");if(!p){let R=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw R.statusCode=404,R}if(_.url=p.relativeURL,_.url.indexOf("+")>-1||_.url.indexOf("#")>-1){let R=_.url.slice(1);if(R.indexOf("#")>-1&&R.indexOf("#")!==R.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(_.isCollection=!0,R.indexOf("+")===R.length-1)_.onlyChildren=!0,_.url="/"+R.slice(0,R.length-1);else{let E=R.split("/"),T;for(let H=0;H<E.length;H++)if(E[H].indexOf("+")>-1)if(E[H]==="+")T=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&T)throw new Error("Filters can not be combined");let w=!0;E[E.length-1]==="#"&&(E.length--,w=!1),T&&(n=a(H=>{let $=H.id;if(!Array.isArray($))if($?.indexOf?.("/")>-1)$=$.split("/");else return!1;if(w&&$.length!==E.length)return!1;for(let W=0;W<E.length;W++)if(E[W]!=="+"&&E[W]!==$[W])return!1;return!0},"filter"));let v=E.indexOf("+");_.url="/"+(v>-1?E.slice(0,v):E).concat("").join("/")}}else _.isCollection=!1;let h=p.path,S=p.Resource,g=await Ot(_,async()=>{let R=this.createContext();R.topic=s,R.retainHandling=i,R.isCollection=_.isCollection;let E=await S.subscribe(_,R);if(!E)return;if(!E[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let T=(async()=>{for await(let w of E)try{let v;if(w.type&&w.type!=="put"&&w.type!=="delete"&&w.type!=="message"&&w.type!=="patch"||n&&!n(w))continue;r?(w.topic=s,v=this.needsAcknowledge(w)):(w.acknowledge?.(),v=lP());let H=w.id;if(Array.isArray(H)&&(H=Tu(H)),H==null&&(H=""),await this.listener(h+"/"+H,w.value,v,t)===!1)break;this.awaitingAcks?.size>jz?await new Promise(W=>setTimeout(W,this.awaitingAcks.size-jz)):await new Promise(setImmediate)}catch(v){(0,_c.warn)(v)}})();return E});if(g)return g.topic=s,g.qos=t.qos,this.subscriptions.push(g),g}resume(){}needsAcknowledge(t){let r=lP();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,{acknowledge:t.acknowledge})),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r.acknowledge())}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 uP(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();Ot(r,async()=>{try{if(!t){let n=await Ph.get(this.sessionId);n?.doesExist()&&await uP(n,n.data,r)}}finally{await Ph.delete(this.sessionId)}}).catch(n=>{(0,_c.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(uP,"publish");dP=class extends tA{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.localTime):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=lP(),n={topic:t.topic,timestamp:t.localTime};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks?.get(t);if(!r)return;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,_c.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,Jz.getNextMonotonicTime)()),(0,_c.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),cP.put(this.sessionRecord)}}});var _P={};Ue(_P,{bypassAuth:()=>cTe,start:()=>lTe});function cTe(){ij=!0}function lTe({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new sj.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((u,f,d,_)=>{if(f.headers.get("sec-websocket-protocol")!=="mqtt")return _(u,f,d);o.events.emit("connection",u),pr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:p,onClose:h}=rj(u,S=>{u.send(S)},f,Promise.resolve(d).then(()=>f?.user),o);u.on("message",p),u.on("close",h),u.on("error",S=>{pr.info?.("WebSocket error",S)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let f;if(o.events.emit("connection",u),pr.debug?.(`Received ${u.getCertificate?"SSL":"TCP"} connection for MQTT from ${u.remoteAddress}`),l){if(u.authorized)try{let p=l.user;if(p!==null){(p===void 0||p==="Common Name"||p==="CN")&&(p=u.getPeerCertificate().subject.CN);try{f=await e.getUser(p,null,null),(0,nf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&nA.notify?.({username:f?.username,status:zs.SUCCESS,type:ua.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:u.remoteAddress})}catch(h){throw(0,nf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&nA.error?.({username:p,status:zs.FAILURE,type:ua.AUTHENTICATION,auth_strategy:"mqtt",remote_address:u.remoteAddress}),h}}else pr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(p){o.events.emit("error",p,u),pr.error?.(p)}else if(l.required)return pr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!f&&ij&&u.remoteAddress.includes("127.0.0.1")&&(f=await(0,nj.getSuperUser)(),pr.debug?.("Auto-authorizing local connection",f?.username));let{onMessage:d,onClose:_}=rj(u,p=>u.write(p),null,f,o);u.on("data",d),u.on("close",_),u.on("error",p=>{pr.info?.("Socket error",p)})},{port:t,securePort:s,mtls:l})),c}function rj(e,t,r,n,s){tj||(tj=!0,Y_(d=>{rA>0&&d.push({metric:"mqtt-connections",connections:rA,byThread:!0})}));let i;rA++;let o,c={protocolVersion:4},l=(0,sA.parser)({protocolVersion:5});function u(d){l.parse(d)}a(u,"onMessage");function f(){rA--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Zn(!1,"connection","mqtt","disconnect"),pr.debug?.("MQTT connection was closed",e.remoteAddress))}return a(f,"onClose"),l.on("packet",async d=>{n?.then&&(n=await n);let _=d.cmd;if(o)o.then&&await o;else if(_!=="connect"){pr.info?.("Received packet before connection was established, closing connection"),e?.destroy?e.destroy():e?.terminate();return}let p=d.topic,h=p?.indexOf("/",1),S=h>0?p.slice(0,h):p;nr(d.length,"bytes-received",S,R(d),"mqtt");try{switch(o?.receivedPacket?.(),_){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await Ke.getUser(d.username,d.password.toString(),r),(0,nf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&nA.notify?.({username:n?.username,status:zs.SUCCESS,type:ua.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(se){return(0,nf.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&nA.error?.({username:d.username,status:zs.FAILURE,type:ua.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,se),Zn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Zn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let se=e.deserialize||(e.deserialize=ho(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?se(d.will.payload):void 0,delete d.will.payload}o=Zz({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(se){return pr.error?.(se),s.events.emit("auth-failed",d,e,se),Zn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:se.code||5,returnCode:se.code||128})}s.events.emit("connected",o,e),Zn(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0});let T=a(async(se,Y,ne,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",se);let ae=se.indexOf("/",1),me=ae>0?se.slice(0,ae):se;g({cmd:"publish",topic:se,payload:await E(Y),messageId:ne||Math.floor(Math.random()*1e8),qos:ue.qos},me);let Te=e._socket??e;return Te.writableNeedDrain?new Promise(ye=>Te.once("drain",ye)):!Te.closed}catch(ae){return pr.error?.(ae),o?.disconnect(),s.sessions.delete(o),!1}},"listener");o.setListener(T),o.sessionWasPresent&&await o.resume();break;case"subscribe":let w=[];for(let se of d.subscriptions){let Y;try{let ne=await o.addSubscription(se,se.qos>=1);Y=ne?ne.qos||0:c.protocolVersion<5?128:143}catch(ne){s.events.emit("error",ne,e,se,o),ne.statusCode?ne.statusCode===500?pr.warn?.(ne):pr.info?.(ne):pr.error?.(ne),Y=c.protocolVersion<5?128:ne.statusCode===403?135:ne.statusCode===404?143:128}w.push(Y)}await o.committed,g({cmd:"suback",granted:w,messageId:d.messageId});break;case"unsubscribe":{let se=[];for(let Y of d.unsubscriptions)se.push(o.removeSubscription(Y)?0:17);g({cmd:"unsuback",granted:se,messageId:d.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let v=d.qos===2?"pubrec":"puback",H=e.deserialize||(e.deserialize=ho(r?.headers.get?.("content-type"))),W=(d.payload?.length||0)>0?H(d.payload):void 0,te;try{te=await o.publish(d,W)}catch(se){s.events.emit("error",se,e,d,o),pr.warn?.(se),d.qos>0&&g({cmd:v,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&g({cmd:v,messageId:d.messageId,reasonCode:te===!1?144:0},d.topic);break;case"pubrec":g({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":g({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Zn(!0,"connection","mqtt","disconnect"),pr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(T){s.events.emit("error",T,e,d,o),pr.error?.(T),g({cmd:"disconnect"})}function g(T,w){let v=(0,sA.generate)(T,c);t(v),nr(v.length,"bytes-sent",w,R(T),"mqtt")}a(g,"sendPacket");function R(T){return T.qos>0?T.cmd+",qos="+T.qos:T.cmd}a(R,"packetMethodName");function E(T){return Aa(T,r)}a(E,"serialize")}),l.on("error",d=>{pr.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:f}}var sA,nj,nf,fP,sj,nA,pr,ij,tj,rA,oj=be(()=>{sA=require("mqtt-packet");ej();nj=M(On());fo();ki();Lr();nf=M(le());k();fP=M(Ni()),sj=require("events"),nA=(0,fP.loggerWithTag)("auth-event"),pr=(0,fP.loggerWithTag)("mqtt"),ij=(0,nf.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(cTe,"bypassAuth");a(lTe,"start");rA=0;a(rj,"onSocket")});var jp={};Ue(jp,{component_errors:()=>of,getComponentName:()=>pTe,loadComponent:()=>aA,loadComponentDirectories:()=>dj,setErrorReporter:()=>_Te});function dj(e,t){t&&(hP=t),e&&(gP=e);let r=[];if((0,lt.existsSync)(pP)){let s=(0,lt.readdirSync)(pP,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,gt.join)(pP,o);r.push(aA(c,hP,JA,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(aA(n,hP,n,!1,null,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{uj=!0})}function _Te(e){Dh=e}function hTe(e,t){return new Promise((r,n)=>{let s=Qe().system.hdb_info;if(!s)return r();let i=setTimeout(()=>{s.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(s.primaryStore.attemptLock(e,0,()=>{clearTimeout(i),r()}))try{(0,lt.rmSync)(t,{recursive:!0,force:!0}),(0,lt.existsSync)((0,gt.join)(e,"node_modules"))||(0,lt.mkdirSync)((0,gt.join)(e,"node_modules")),(0,lt.symlinkSync)(AP.PACKAGE_ROOT,t,"dir"),r()}finally{s.primaryStore.unlock(e,0)}})}async function aA(e,t,r,n,s,i){let o=(0,lt.realpathSync)(e);if(iA.has(o))return iA.get(o);iA.set(o,!0),s&&(gP=s);try{let c;n&&(of=new Map);let l=(0,gt.join)(e,"harperdb-config.yaml");(0,lt.existsSync)(l)?c=n?(0,cA.getConfigObj)():(0,mP.parseDocument)((0,lt.readFileSync)(l,"utf8")).toJSON():!n&&(0,lt.existsSync)(l=(0,gt.join)(e,"config.yaml"))?c=(0,mP.parseDocument)((0,lt.readFileSync)(l,"utf8")).toJSON():c=SP;try{let d=(0,gt.join)(e,"node_modules","harperdb");(n||((0,lt.existsSync)(d)||!e.startsWith((0,EP.getHdbBasePath)()))&&(!(0,lt.existsSync)(d)||(0,lt.realpathSync)(AP.PACKAGE_ROOT)!==(0,lt.realpathSync)(d)))&&await hTe(e,d)}catch(d){jl.default.error("Error symlinking harperdb module",d),d.code=="EPERM"&&process.platform==="win32"&&jl.default.error('You may need to enable developer mode in "Settings" / "System" (or "Update & Security") / "For developers", in order to enable symlinks so components can use `import from "harperdb"`')}let u=oA,f=n;for(let d in c){oA=d;let _=c[d];if(of.set(n?d:(0,gt.basename)(e),!1),!_)continue;let p,h=_.package;try{if(h){let T=e,w;for(;!(0,lt.existsSync)(w=(0,gt.join)(T,"node_modules",d));)if(T=(0,gt.dirname)(T),T.length<(0,EP.getHdbBasePath)().length){w=null;break}if(w)p=await aA(w,t,r,!1),f=!0;else throw new Error(`Unable to find package ${d}:${h}`)}else p=fTe[d];if(!p)continue;let S=a(T=>(T.origin=r,dt(T)),"ensureTable"),g=_.network||(_.port||_.securePort)&&_,R=g?.securePort||g?.https&&g.port,E=!g?.https&&g?.port;if(sf.isMainThread&&(p=await p.startOnMainThread?.({server:Ke,ensureTable:S,port:E,securePort:R,resources:t,..._})||p,n&&g))for(let T of[E,R])try{if(+T&&!aj.includes(T)){let w=TP.get(U.HTTP_SESSIONAFFINITY);w&&jl.default.warn("Session affinity is not recommended and may cause memory leaks"),(w||!rg)&&(aj.push(T),eP(T,w))}}catch(w){console.error("Error listening on socket",T,w,d)}if(t.isWorker&&(p=await p.start?.({server:Ke,ensureTable:S,port:E,securePort:R,resources:t,..._})||p),gP.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&_.files!=null){if(_.files.includes(".."))throw(0,lj.handleHDBError)("Can not reference parent directories");let T=(0,gt.join)(e,_.files).replace(/\\/g,"/"),w=T.indexOf("/*");if(w>-1&&_.files!==SP[d]?.files&&!(0,lt.existsSync)(T.slice(0,w)))throw new Error(`The path '${T.slice(0,w)}' does not exist and cannot be used as the base of the resolved 'files' path value '${_.files}'`);let v=(0,gt.basename)(e),H=_.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+v+H.slice(2):H==="."?"/"+v:"/"+v+"/"+H;let $,W,te;if(_.root){let Y=_.root;Y.startsWith("/")&&(Y=Y.slice(1)),Y.endsWith("/")&&(Y=Y.slice(0,-1)),Y+="/",W=(0,gt.join)(e,Y)}else(te=T.indexOf("/*"))>-1?(W=T.slice(0,te+1),$=(0,gt.relative)(e,W)):_.files.indexOf("/")>-1&&(W=T.slice(0,T.lastIndexOf("/")+1),$=(0,gt.relative)(e,W));let se=!1;if(sf.isMainThread&&p.setupDirectory&&(se=await p.setupDirectory?.(H,W,t)),t.isWorker&&p.handleDirectory&&(se=await p.handleDirectory?.(H,W,t)),se){f=!0;continue}for(let Y of await(0,cj.default)(T,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:ue}=Y;f=!0;let ae=(0,gt.relative)(e,ne).replace(/\\/g,"/");if($)if(ae.startsWith($))ae=ae.slice($.length+1);else throw new Error(`The root path '${_.root}' does not reference a valid part of the file path '${ae}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let me=H+(H.endsWith("/")?"":"/")+ae;try{if(ue.isFile()){let Te=await dTe(ne);sf.isMainThread&&await p.setupFile?.(Te,me,ne,t),t.isWorker&&await p.handleFile?.(Te,me,ne,t)}else sf.isMainThread&&await p.setupDirectory?.(me,ne,t),t.isWorker&&await p.handleDirectory?.(me,ne,t)}catch(Te){let ye=`Could not load ${ue.isFile()?"file":"directory"} '${ne}'${_.module?` using '${_.module}'`:""} for application '${e}' due to:
|
|
133
|
-
`;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,Dh?.(Te),jl.default.error(Te),t.set(_.path||"/",new Sa(Te)),of.set(n?d:(0,gt.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,gt.basename)(e)}' due to: ${S.message}`,Dh?.(S),((0,Lh.getWorkerIndex)()===0?console:jl.default).error(S),t.set(_.path||"/",new Sa(S),null,!0),of.set(n?d:(0,gt.basename)(e),S.message)}}if(oA=u,sf.isMainThread&&!uj&&i&&(0,Lh.watchDir)(e,async()=>dj()),c.extensionModule){let d=await QE((0,gt.join)(e,c.extensionModule));return iA.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;Dh?.(new Error(d)),((0,Lh.getWorkerIndex)()===0?console:jl.default).error(d),of.set((0,gt.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Dh?.(c),t.set("",new Sa(c))}}var lt,gt,sf,mP,TP,AP,cj,Lh,jl,lj,EP,uTe,cA,dTe,pP,gP,uj,hP,of,fTe,SP,aj,iA,Dh,oA,pTe,Jp=be(()=>{lt=require("fs"),gt=require("path"),sf=require("worker_threads"),mP=require("yaml"),TP=M(le()),AP=M(nt());k();GL();yM();XB();rH();nH();GH();TY();NY();IY();cj=M(require("fast-glob")),Lh=M(tt()),jl=M(z());uO();Lr();lj=M(he());Le();kC();EP=M(le()),uTe=M(Fz());HS();zz();es();oj();cA=M(At());ng();bR();({readFile:dTe}=lt.promises),pP=(0,cA.resolvePath)(TP.get(U.COMPONENTSROOT)),gP=new Map,of=new Map;a(dj,"loadComponentDirectories");fTe={REST:ig,rest:ig,graphql:qR,graphqlSchema:wR,roles:lO,jsResource:fO,fastifyRoutes:ZI,login:pO,static:eC,operationsApi:uTe,customFunctions:{},http:{},clustering:aP,replication:Do,authentication:qp,mqtt:_P,loadEnv:tC},SP={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(SP,"static",{value:{files:"web/**"}});aj=[],iA=new Map;a(_Te,"setErrorReporter");pTe=a(()=>oA,"getComponentName");a(hTe,"symlinkHarperModule");a(aA,"loadComponent")});var YT=P((D0e,_j)=>{var{isMainThread:fj}=require("worker_threads"),{getTables:mTe,getDatabases:C0e,table:P0e}=(Le(),D(rt)),{loadComponentDirectories:ETe,loadComponent:gTe}=(Jp(),D(jp)),{resetResources:STe}=(Au(),D(HL)),TTe=jw(),ATe=At(),{dirname:RTe}=require("path"),{getConnection:yTe}=sr(),bTe=le(),{CONFIG_PARAMS:OTe}=(k(),D(q)),{loadCertificates:NTe}=rs(),RP=new Map;async function wTe(e=!1){!fj&&bTe.get(OTe.CLUSTERING_ENABLED)&&yTe();try{fj&&await TTe()}catch(n){console.error(n)}let t=STe();mTe(),t.isWorker=e,await NTe(),await gTe(RTe(ATe.getConfigFilePath()),t,"hdb",!0,RP),await ETe(RP,t);let r=[];for(let[n]of RP)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(wTe,"loadRootComponents");_j.exports.loadRootComponents=wTe});var tt=P((M0e,Ti)=>{"use strict";sm();var{Worker:ITe,MessageChannel:CTe,parentPort:Zi,isMainThread:wP,threadId:PTe,workerData:eo}=require("worker_threads"),{PACKAGE_ROOT:DTe}=nt(),{join:Ej,isAbsolute:LTe,extname:MTe}=require("path"),{server:gj}=(Lr(),D(Su)),{watch:vTe,readdir:UTe}=require("fs/promises"),{totalmem:pj}=require("os"),af=(k(),D(q)),Sj=le(),Si=z(),{randomBytes:xTe}=require("crypto"),{_assignPackageExport:BTe}=Ai(),hj=1024*1024,pc=[],Fs=[],HTe=50,IP=1e4,kTe="restart",Tj="request_thread_info",Aj="resource_report",Rj="thread_info",yj="added-port",FTe="ack",yP;BTe("threads",Fs);Ti.exports={startWorker:bP,restartWorkers:PP,shutdownWorkers:KTe,workers:pc,setMonitorListener:ZTe,onMessageFromWorkers:YTe,onMessageByType:Pj,broadcast:zTe,broadcastWithAcknowledgement:JTe,setChildListenerByType:VTe,getWorkerIndex:bj,getWorkerCount:Oj,getTicketKeys:wj,setMainIsWorker:qTe,setTerminateTimeout:GTe,restartNumber:eo?.restartNumber||1};Fs.onMessageByType=Pj;Fs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Fs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Ti.exports.whenThreadsStarted=new Promise(e=>{Ti.exports.threadsHaveStarted=e});var CP;function GTe(e){IP=e}a(GTe,"setTerminateTimeout");function bj(){return eo?eo.workerIndex:CP?0:void 0}a(bj,"getWorkerIndex");function Oj(){return eo?eo.workerCount:CP?1:void 0}a(Oj,"getWorkerCount");function qTe(e){CP=e,Ti.exports.threadsHaveStarted()}a(qTe,"setMainIsWorker");var Nj=1,lA;function wj(){return lA||(lA=wP?xTe(48):eo.ticketKeys,lA)}a(wj,"getTicketKeys");Object.defineProperty(gj,"workerIndex",{get(){return bj()}});Object.defineProperty(gj,"workerCount",{get(){return Oj()}});var Ij={[Tj](e,t){QTe(t)},[Aj](e,t){XTe(t,e)}};function bP(e,t={}){let r=process.constrainedMemory?.()||pj();r=Math.min(r,pj(),2e4*hj);let n=Sj.get(af.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/hj/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Fs){let u=new CTe;u.existingPort=l,i.push(u),o.push(u.port2)}MTe(e)||(e+=".js");let c=new ITe(LTe(e)?e:Ej(DTe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Nj=t.threadCount,name:t.name,restartNumber:Ti.exports.restartNumber,ticketKeys:wj()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:yj,port:l,threadId:c.threadId},[l]);return dA(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>bP(e,t),c.on("error",l=>{Si.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{pc.splice(pc.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<HTe?(t.unexpectedRestarts=c.unexpectedRestarts+1,bP(e,t)):Si.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{Ij[l.type]?.(l,c)}),pc.push(c),tAe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(bP,"startWorker");var $Te=[af.THREAD_TYPES.HTTP];async function PP(e=null,t=Math.max(Nj>3,1),r=!0){if(wP){try{process.chdir(process.cwd())}catch(o){Si.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=YT();await o()}Ti.exports.restartNumber++,t<1&&(t=t*pc.length);let n=[],s=[];for(let o of pc.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Si.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ti.exports.restartNumber,type:af.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=$Te.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{Si.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},IP*2).unref();o.on("exit",()=>{clearTimeout(f),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),u()})});if(n.push(l),c&&r){let u=o.startCopy(),f=new Promise(d=>{let _=a(p=>{p.type===af.ITC_EVENT_TYPES.CHILD_STARTED&&(Si.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");Si.trace("Waiting for worker to start",u.threadId),u.on("message",_)});s.push(f),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}=ja();r&&(e==="http"||!e)&&Sj.get(af.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Zi.postMessage({type:kTe,workerType:e})}a(PP,"restartWorkers");function VTe(e,t){Ij[e]=t}a(VTe,"setChildListenerByType");function KTe(e){return PP(e,1/0,!1)}a(KTe,"shutdownWorkers");var Cj=[];function YTe(e){Cj.push(e)}a(YTe,"onMessageFromWorkers");var OP=new Map;function Pj(e,t){let r=OP.get(e);r||OP.set(e,r=[]),r.push(t)}a(Pj,"onMessageByType");var WTe=10;async function zTe(e,t){let r=0;for(let n of Fs)try{n.postMessage(e),r++>WTe&&(r=0,await new Promise(setImmediate))}catch(s){Si.error("Unable to send message to worker",s)}t&&Lj(e,null)}a(zTe,"broadcast");var uA=new Map,jTe=1;function JTe(e){return new Promise(t=>{let r=0;for(let n of Fs)try{let s=jTe++,i=a(()=>{uA.delete(s),--r===0&&t(),n!==Zi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,uA.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of uA)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Si.error("Unable to send message to worker",s)}r===0&&t()})}a(JTe,"broadcastWithAcknowledgement");function QTe(e){e.postMessage({type:Rj,workers:Dj()})}a(QTe,"sendThreadInfo");function Dj(){let e=Date.now();return pc.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(Dj,"getChildWorkerInfo");function XTe(e,t){e.resources=t,e.resources.updated=Date.now()}a(XTe,"recordResourceReport");var NP;function ZTe(e){NP=e}a(ZTe,"setMonitorListener");var eAe=1e3,mj=!1;function tAe(){mj||(mj=!0,setInterval(()=>{for(let e of pc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}NP&&NP()},eAe).unref())}a(tAe,"startMonitoring");var rAe=1e3;if(Zi&&eo?.addPorts){dA(Zi);for(let e=0,t=eo.addPorts.length;e<t;e++){let r=eo.addPorts[e];r.threadId=eo.addThreadIds[e],dA(r)}setInterval(()=>{let e=process.memoryUsage();Zi.postMessage({type:Aj,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},rAe).unref(),yP=a(()=>new Promise((e,t)=>{Zi.on("message",r),Zi.postMessage({type:Tj});function r(n){n.type===Rj&&(Zi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else yP=Dj;Ti.exports.getThreadInfo=yP;function dA(e,t){Fs.push(e),e.on("message",r=>{if(r.type===yj)r.port.threadId=r.threadId,dA(r.port);else if(r.type===FTe){let n=uA.get(r.id);n&&n()}else Lj(r,e)}).on("close",()=>{Fs.splice(Fs.indexOf(e),1)}).on("exit",()=>{Fs.splice(Fs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(dA,"addPort");function Lj(e,t){for(let n of Cj)n(e,t);let r=OP.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){Si.error(s)}}a(Lj,"notifyMessageListeners");if(wP){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await UTe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Ej(s,o.name));try{for await(let{filename:o}of vTe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await PP(),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");Ti.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Zi.on("message",async e=>{let{type:t}=e;t===af.ITC_EVENT_TYPES.SHUTDOWN&&(Ti.exports.restartNumber=e.restartNumber,Zi.unref(),setTimeout(()=>{Si.warn("Thread did not voluntarily terminate",PTe),process.exit(0)},IP).unref())})});var EB={};Ue(EB,{ACTION_32_BIT:()=>Jm,ACTION_64_BIT:()=>iAe,AUDIT_STORE_OPTIONS:()=>Bp,Decoder:()=>Sl,HAS_BLOBS:()=>An,HAS_CURRENT_RESIDENCY_ID:()=>kc,HAS_EXPIRATION_EXTENDED_TYPE:()=>n_,HAS_ORIGINATING_OPERATION:()=>r_,HAS_PREVIOUS_RESIDENCY_ID:()=>Fc,REMOTE_SEQUENCE_UPDATE:()=>Hg,createAuditEntry:()=>Nu,getLastRemoved:()=>ON,openAuditStore:()=>pA,readAuditEntry:()=>Nt,removeAuditEntry:()=>hA,setAuditRetention:()=>sAe,transactionKeyEncoder:()=>Gj});function pA(e){let t=e.auditStore=e.openDB(DP.AUDIT_STORE_NAME,{create:!1,...Bp});t||(t=e.auditStore=e.openDB(DP.AUDIT_STORE_NAME,Bp),vj(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,f){return r[l]=f,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,o=MP;Rh(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(o=l),clearTimeout(n);let u=new Promise(f=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let d=0,_,p;try{for(let{key:h,value:S}of t.getRange({start:1,snapshot:!1,end:Date.now()-LP/(1+i*i)})){try{_=hA(t,h,S)}catch(g){cf.warn("Error removing audit entry",g)}if(p=h,await new Promise(setImmediate),++d>=nAe){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,LP/10):(vj(t,p),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,vh.getWorkerIndex)()===(0,vh.getWorkerCount)()-1&&c(),(0,vh.getWorkerIndex)()===0&&!Mj)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(Mj=!0,cf.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function hA(e,t,r){let n=oAe(r),s;if(n&An){s=Nt(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&Mc(()=>Ta(s.getValue(i)),i.rootStore)}if((n&15)===vP){s=s||Nt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId).version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function vj(e,t){UP[0]=t,e.put(Symbol.for("last-removed"),qj)}function ON(e){let t=e.get(Symbol.for("last-removed"));if(t)return qj.set(t),UP[0]}function sAe(e,t=MP){LP=e,MP=t}function Nu(e,t,r,n,s,i,o,c,l,u,f,d,_){let p=$j[o];if(!p)throw new Error(`Invalid audit entry type ${o}`);let h=1;if(n&&(n>1?hc.setFloat64(0,n):Gs.set(XR),h=9),l){if(l&255)throw new Error("Illegal extended type");h+=3}R(s),R(t),g(r),hc.setFloat64(h,e),h+=8,l&kc&&R(u),l&Fc&&R(f),l&n_&&(hc.setFloat64(h,d),h+=8),l&r_&&R(Vj[_]),i?g(i):Gs[h++]=0,l?hc.setUint32(n?8:0,p|l|3221225472):Gs[n?8:0]=p;let S=Gs.subarray(0,h);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=h;h+=1,h=(0,Jl.writeKey)(E,Gs,h);let w=h-T-1;w>127?w>16383?(cf.error("Key or username was too large for audit entry",E),h=T+1,Gs[T]=0):(Gs.copyWithin(T+2,T+1,h),hc.setUint16(T,w|32768),h++):Gs[T]=w}function R(E){E<128?Gs[h++]=E:E<16384?(hc.setUint16(h,E|32768),h+=2):E<1056964608?(hc.setUint32(h,E|3221225472),h+=4):(Gs[h]=255,hc.setUint32(h+1,E),h+=5)}}function oAe(e){let t=0;e[0]==66&&(t=8);let r=e[t];if(r<128)return r;let n=e.dataView||(e.dataView=new Sl(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Sl(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),o=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,f=n.position+=l,d=n.readFloat64(),_,p,h,S;if(i&kc&&(_=n.readInt()),i&Fc&&(p=n.readInt()),i&n_&&(h=n.readFloat64()),i&r_){let T=n.readInt();S=Vj[T]}l=n.readInt();let g=n.position,R=n.position+=l,E;return{type:$j[i&7],tableId:c,nodeId:o,get recordId(){return(0,Jl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return R>g?(0,Jl.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&fA||i&Mh&&!w)return E||(E=Mc(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&Mh&&v)return zb(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(fA|Mh)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:p,expiresAt:h,originatingOperation:S}}catch(n){return cf.error("Reading audit entry error",n,e),{}}}var Jl,_A,DP,vh,Fj,cf,Gs,hc,Gj,Bp,LP,nAe,UP,qj,MP,Mj,fA,Mh,Uj,vP,xj,Bj,Hj,kj,Jm,iAe,Hg,kc,Fc,r_,n_,An,$j,Vj,Sl,mo=be(()=>{Jl=require("ordered-binary"),_A=M(le()),DP=M(Ut());k();vh=M(tt()),Fj=M(oe());wu();cf=M(z());HE();As();HT();(0,_A.initSync)();Gs=Buffer.alloc(2816),hc=new DataView(Gs.buffer,Gs.byteOffset,2816),Gj={writeKey(e,t,r){return e===t_?(t.set(t_,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Jl.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,Jl.readKey)(e,t,r)}},Bp={encoding:"binary",keyEncoder:Gj},LP=(0,Fj.convertToMS)((0,_A.get)(U.LOGGING_AUDITRETENTION))||86400*3,nAe=1e3,UP=new Float64Array(1),qj=new Uint8Array(UP.buffer),MP=1e4,Mj=!1;a(pA,"openAuditStore");a(hA,"removeAuditEntry");a(vj,"updateLastRemoved");a(ON,"getLastRemoved");a(sAe,"setAuditRetention");fA=16,Mh=32,Uj=1,vP=2,xj=3,Bj=4,Hj=5,kj=6,Jm=14,iAe=15,Hg=11,kc=512,Fc=1024,r_=2048,n_=4096,An=8192,$j={put:Uj|fA,[Uj]:"put",delete:vP,[vP]:"delete",message:xj|fA,[xj]:"message",invalidate:Bj|Mh,[Bj]:"invalidate",patch:Hj|Mh,[Hj]:"patch",relocate:kj,[kj]:"relocate"},Vj={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(Nu,"createAuditEntry");a(oAe,"readAction");a(Nt,"readAuditEntry");Sl=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t;return t=this.getUint8(this.position++),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(t){throw t.message=`Error reading float64: ${t.message} at position ${this.position}`,t}}}});function HP(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=Yj,aAe(e.primaryStore,e.auditStore)):(c=Kj,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{Wj(Kj[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let u=l[o];u||(u=l[o]=new Map,u.envs=l,u.tableId=o,u.store=e.primaryStore),t=Tu(t);let f=new BP(r);f.startTime=n;let d=u.get(t);return d?d.push(f):(u.set(t,d=[f]),d.tables=u,d.key=t),f.subscriptions=d,f}function Wj(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),zj(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Nt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Tu(c),u=0;do{let f=o.get(l);if(f){for(let _ of f)if(!(u>0&&!(_.includeDescendants&&!(_.onlyChildren&&u>1)))){if(_.startTime>=n){(0,xP.info)("omitting",c,_.startTime,n);continue}try{let p;_.supportsTransactions&&_.txnInProgress!==i.version&&(p=!0,_.txnInProgress||(r?r.push(_):r=[_]),_.txnInProgress=i.version),_.listener(c,i,n,p)}catch(p){console.error(p),(0,xP.info)(p)}}}if(l==null)break;let d=l.lastIndexOf?.("/",l.length-2);d!==l.length-1&&u++,d>-1?l=l.slice(0,d+1):l=null}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function aAe(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 l=Yj[s];if(!l)return;let u=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{Wj(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function zj(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function qF(e){return e.nextTransaction||(HP({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),zj(e)),e.nextTransaction}var xP,Kj,Yj,BP,NN=be(()=>{xP=M(z());pu();Au();mo();Kj=Object.create(null),Yj=Object.create(null);a(HP,"addSubscription");BP=class extends Fn{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;if(t){let 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(Wj,"notifyFromTransactionData");a(aAe,"listenToCommits");a(zj,"nextTransaction");a(qF,"whenNextTransaction")});var vI={};Ue(vI,{EVICTED:()=>Ea,INVALIDATED:()=>En,coerceType:()=>gA,makeTable:()=>TA,setServerUtilities:()=>hAe});function TA(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:f,sealed:d,splitSegments:_,replicate:p}=e,{expirationMS:h,evictionMS:S,audit:g,trackDeletes:R}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=ty(i,n,l),w,v,H={},$=Promise.resolve(),W,te,se;for(let K of E)(K.assignCreatedTime||K.name==="__createdtime__")&&(W=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(te=K),K.expiresAt&&(se=K),K.isPrimaryKey&&(H=K);let Y,ne=[],ue=[],ae=1,me=2,Te={},ye={},Qt=864e5,ut=0,br,Es,Hn,ou=!1,au,GA=new Map,qA=new Map,Mt,mf,Qh=Xl.get(U.REPLICATION_DATABASES);if(Array.isArray(Qh)){for(let K of Qh)if(K.name===c&&K.replicateTo>=0){mf=K.replicateTo;break}}let Xh=i.getRange({start:!1,end:!1}).constructor,Ef=10,Zh=6;g&&Af(),Rh(i.env.path,K=>{if(v)return so(K)});class Ce extends Yr{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=E;static replicate=p;static sealed=d;static splitSegments=_??!0;static createdTimeProperty=W;static updatedTimeProperty=te;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=f;static schemaDefined=u;static sourcedFrom(m,O){if(O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource)m.intermediateSource=!0,this.sources.unshift(m);else{if(this.sources.some(I=>!I.intermediateSource)){if(this.sources.some(I=>I.name===m.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(m)}v=v||m.get&&(!m.get.reliesOnPrototype||m.prototype.get),w=w||m.load;let A=a(I=>{let L=this.sources;if(L=L.filter(B=>B.intermediateSource&&B[I]&&(!B[I].reliesOnPrototype||B.prototype[I])),L.length>0)if(L.length===1){let B=L[0];return(N,x,G)=>{if(N?.source!==B)return B[I](x,G,N)}}else return(B,N,x)=>{let G=[];for(let j of L){if(B?.source===j)break;G.push(j[I](N,x,B))}return Promise.all(G)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1];y.intermediateSource&&(y={});let b=a(I=>{if(y[I]&&(!y[I].reliesOnPrototype||y.prototype[I]))return(L,B,N)=>{if(!L?.source)return y[I](B,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,B=a(async(N,x)=>{let G=N.value,j=N.table?Ve[c][N.table]:Ce;if(c===bf&&(N.table===fu.ROLE_TABLE_NAME||N.table===fu.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[j.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=m;let ie={residencyId:Rc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await j.getResource(N.id,x,ie);switch(N.finished&&await N.finished,N.type){case"put":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!0,ie);case"patch":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!1,ie);case"delete":return F._writeDelete(ie);case"publish":case"message":return F._writePublish(G,ie);case"invalidate":return F._writeInvalidate(G,ie);case"relocate":return F._writeRelocate(ie);default:xe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=m.subscribe;N&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Ql.getWorkerIndex)(),x):(0,Ql.getWorkerIndex)()===0,j=N&&G&&await m.subscribe?.(x);if(j){let ie;for await(let F of j)try{if(!(F.type==="transaction"?F.writes[0]:F)){xe.default.error?.("Bad subscription event",F);continue}if(F.source=m,F.type==="end_txn"){if(ie?.resolve(),F.localTime&&L!==F.localTime){if(F.remoteNodeIds?.length>0){let ce=[Symbol.for("seq"),F.remoteNodeIds[0]],ee=f.get(ce),J=ee?.nodes;J||(J=[]);for(let fe of F.remoteNodeIds.slice(1)){let Ae=J.find(De=>De.id===fe);J=J.filter(De=>De.id!==fe||De===Ae),Ae||(Ae={id:fe,seqId:0},J.push(Ae)),Ae.seqId=Math.max(ee?.seqId??1,F.localTime),fe===ie?.nodeId&&(Ae.lastTxnTime=F.timestamp)}let _e=Math.max(ee?.seqId??1,F.localTime);xe.default.trace?.("Received txn",c,new Date(_e),new Date(F.localTime),F.remoteNodeIds),f.put(ce,{seqId:_e,nodes:J})}L=F.localTime}F.onCommit&&ie?.committed.then(F.onCommit);continue}if(ie)if(F.beginTxn)ie.resolve();else{ie.write_promises.push(B(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=Ot(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(B(ee,F))}catch(J){throw J.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(F),J}return Promise.all(ce)}else if(F.type==="define_schema"){let ce=this.attributes.slice(0),ee;for(let J of F.attributes)ce.find(_e=>_e.name===J.name)||(ce.push(J),ee=!0);ee&&(dt({table:s,database:c,attributes:ce,origin:"cluster"}),xh.signalSchemaChange(new Bh.SchemaEventMsg(process.pid,$t.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[B(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):B(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>xh.signalUserChange(new Bh.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(qe){xe.default.error?.("error in subscription handler",qe)}}}catch(N){xe.default.error?.(N)}})(),this}static get isCaching(){return v}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(m,O,A){let y=super.getResource(m,O,A);if(m!=null){Cr(m);try{if(y.getRecord?.())return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!A?.async||i.cache?.get?.(m),C=Vr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return cu(m,O,{transaction:I,ensureLoaded:A?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Ir.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let B=lu(m,L,O,y);if(B)return C?.disregardReadTxn(),y.#i=!0,FP(B,N=>(Ce._updateResource(y,N),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return y}static _updateResource(m,O){m.#r=O,m.#e=O?.value??null,m.#n=O?.version}ensureLoaded(){let m=lu(this.getId(),this.#r,this.getContext());if(m)return this.#i=!0,FP(m,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let m=H?.type;if(m==="String"||m==="ID")return super.getNewId();if(!Mt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!EAe(i)||C.pid===process.pid)){let L=C.start,B=C.end;I=L;for(let N of i.getKeys({start:B,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;Mt=new BigInt64Array([BigInt(I)+1n]),Mt=new BigInt64Array(i.getUserSharedBuffer("id",Mt.buffer)),Mt.maxSafeId=C.end}let O=Number(Atomics.add(Mt,0,1n)),A=m==="Int"?512:1048576;if(O+A>=Mt.maxSafeId){let b=a(C=>{Mt.maxSafeId=O+(m==="Int"?1023:4194303);let I=(m==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=C?void 0:i.useReadTransaction(),B=Number(Mt[0]);for(let G of i.getKeys({start:B+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Mt.maxSafeId<I){if(N.end>Mt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,Mt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:Mt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Mt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(Mt,0,BigInt(G.start+1)),Mt.maxSafeId=G.end}},"updateEnd");O+A===Mt.maxSafeId?setImmediate(b):O+100>=Mt.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${m=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return O;function y(b){let C=(m==="Int"?Math.pow(2,31):Math.pow(2,49))-1,I=C/4,L,B,N=!1,x,G;do{x=Math.floor(Math.random()*C),G={start:x,end:x+(m==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let j of i.getKeys({start:x,limit:1,reverse:!0}))L=j;B=C;for(let j of i.getKeys({start:x+1,end:C,limit:1}))B=j;I*=.875,I<1e3&&!N&&(N=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${m==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,B,I))}while(!(I<B-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let j=i.getEntry(Symbol.for("id_allocation"));return(j?.version??null)==b?(xe.default.info?.("Allocated new id range",G),i.put(Symbol.for("id_allocation"),G,Date.now()),G):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...j.value})})}}static setTTLExpiration(m){if(typeof m=="number")h=m*1e3,S||(S=0);else if(m&&typeof m=="object")h=m.expiration*1e3,S=(m.eviction||0)*1e3,Qt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");Qt=Qt||(h+S)/4,so()}static getResidencyRecord(m){return f.get([Symbol.for("residency_by_id"),m])}static setResidency(m){Ce.getResidency=m&&((O,A)=>{try{return m(O,A)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(m){Ce.getResidencyById=m&&(O=>{try{return m(O)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(m,O){if(Ce.getResidencyById)return Ce.getResidencyById(m[t]);let A=mf;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(A=O.replicateTo)}if(A>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,A));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+A));let I=C+A-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(m=!0){g=m,m&&Af(),Ce.audit=m}static coerceId(m){return m===""?null:gA(m,H)}static async dropTable(){delete Ve[c][s];for(let m of i.getRange({versions:!0,snapshot:!1,lazy:!0}))m.metadataFlags&An&&m.value&&Ta(m.value);if(c===o){for(let m of E)f.remove(Ce.tableName+"/"+m.name),r[m.name]?.drop();f.remove(Ce.tableName+"/"),i.drop(),await f.committed}else console.log("legacy dropTable"),await i.close(),await EA.default.remove(data_path),await EA.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));xh.signalSchemaChange(new Bh.SchemaEventMsg(process.pid,$t.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this.isCollection)return this.search(m);if(this.getId()===null){if(m?.conditions||m?.size>0)return this.search(m);let O={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:E};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(A=>(O.recordCount=A.recordCount,O.estimatedRecordRange=A.estimatedRange,O)):O}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(m,O){let A=$r(m);if(A?.read){if(A.isSuperUser)return!0;let y=A.attribute_permissions,b=O?.select;if(y?.length>0||ou&&b){if(O||(O={}),b){let C=y?.length>0&&kP(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let B=Hn[L]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,m,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else O.select=y.filter(C=>C.read&&!Hn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(m,O){let A=$r(m);if(A?.update){let y=A.attribute_permissions;if(y?.length>0){let b=kP(y,"update");for(let C in O)if(!b[C])return!1;for(let C of y){let I=C.attribute_name;!C.update&&!(I in O)&&(O[I]=this.getProperty(I))}}return du(this.getContext())}}allowCreate(m,O){if(this.isCollection){let A=$r(m);if(A?.insert){let y=A.attribute_permissions;if(y?.length>0){let b=kP(y,"insert");for(let C in O)if(!b[C])return!1;return du(this.getContext())}else return du(this.getContext())}}else return this.allowUpdate(m,{})}allowDelete(m){return $r(m)?.delete&&du(this.getContext())}update(m,O){if(!Vr(this.getContext()))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m={...m}),this.#e={},this.#t=m):(y=this.#t,y&&(m=Object.assign(y,m)),this.#t=m)),this._writeUpdate(this.#t,O),this}addTo(m,O){if(typeof O=="number"||typeof O=="bigint")this.#s===Jj?this.set(m,(+this.getProperty(m)||0)+O):(this.#s||this.update(),this.set(m,new GE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(m){this.#t=m}setRecord(m){this.#e=m}invalidate(){this._writeInvalidate()}_writeInvalidate(m,O){let A=this.getContext(),y=this.getId();Cr(y),Vr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,A,y),beforeIntermediate:ye.invalidate?.bind(this,A,y),commit:a((C,I)=>{if(!(no(C,I,O?.nodeId)<=0)){m??=null;for(let L in r)m||(m={}),m[L]===void 0&&(m[L]=this.getProperty(L));xe.default.trace?.(`Invalidating entry id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,m,this.#r,C,En,g,{user:A?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(m){let O=this.getContext(),A=this.getId();Cr(A),Vr(this.getContext()).addWrite({key:A,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,A),beforeIntermediate:ye.relocate?.bind(this,O,A),commit:a((b,C)=>{if(no(b,C,m?.nodeId)<=0)return;let I=Ce.getResidencyRecord(m.residencyId),L=0,B=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)B||(B={}),B[x]=N(x);L=En}else B=N;xe.default.trace?.(`Relocating entry id: ${A}, timestamp: ${new Date(b).toISOString()}`),T(A,B,this.#r,b,L,g,{user:O.user,residencyId:m.residencyId,nodeId:m.nodeId,expiresAt:m.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(m,O){let A={previousResidency:this.getResidencyRecord(m.residencyId),isRelocation:!0},y=io(this.getResidency(O.value,A)),b;if(y){if(!y.includes(server.hostname))return!1;b=Rc(y)}let I=T(m.key,O.value,m,m.version,0,!0,{residencyId:b,expiresAt:O.expiresAt},"relocate",!1,null);return!0}static evict(m,O,A){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==A))){if(v){if(i.hasLock(m,b.version))return;let C;for(let I in r)C||(C={}),C[I]=O[I];if(C)return T(m,C,b,A,Ea,null,null,null,!0)}if(i.ifVersion(m,A,()=>{fn(m,O,null)}),g)return T(m,null,b,A,Ea,null,null,null,!0);Hc(i,b??i.getEntry(m),A)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,sJ.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,A){let y=this.getContext(),b=Vr(y),C=this.getId();Cr(C);let I=this.#r;this.#s=O?Jj:fAe;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(B=>{m||(m=this.#t),O||m&&kE(this.#t===m?this:m)?y?.source||(b.checkOverloaded(),this.validate(m,!O),te&&(m[te.name]=te.type==="Date"?new Date(B):te.type==="String"?new Date(B).toISOString():B),O&&(t&&m[t]!==C&&(m[t]=C),W&&(I?.value?m[W.name]=I?.value[W.name]:m[W.name]=W.type==="Date"?new Date(B):W.type==="String"?new Date(B).toISOString():B),m=nl(m))):b.removeWrite(L)},"validate"),before:O?Te.put?()=>Te.put(y,C,m):null:Te.patch?()=>Te.patch(y,C,m):Te.put?()=>Te.put(y,C,nl(this)):null,beforeIntermediate:O?ye.put?()=>ye.put(y,C,m):null:ye.patch?()=>ye.patch(y,C,m):ye.put?()=>ye.put(y,C,nl(this)):null,commit:a((B,N,x)=>{if(x){if(y&&N?.version>(y.lastModified||0)&&(y.lastModified=N.version),this.#r=N,N?.value&&N.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");O||(this.#e=N?.value??null)}this.#t=void 0,this.#n=B;let G=N?.value,j=m;this.#s=0;let ie=!1,F=no(B,N,A?.nodeId),qe;if(F<=0)if(g){let _e=N.localTime,fe=N.version;xe.default.trace?.("Applying CRDT update to record with id: ",C,"applying later update:",fe);let Ae=[];for(;_e>B||fe>=B&&_e>0;){let De=l.get(_e);if(!De)break;let we=Nt(De);if(fe=we.version,fe>=B){if(fe===B){if(F=no(B,{version:fe,localTime:_e},A?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),qe=m;else if(we.type==="put"||we.type==="delete")return}_e=we.previousLocalTime}Ae.sort((De,we)=>De.version-we.version);for(let De of Ae){let we=De.getValue(i);if(j=BE(j,we,O),xe.default.debug?.("Rebuilding update with future patch:",j),!j)return}}else{if(O)return;j=BE(j,G,O),xe.default.debug?.("Rebuilding update without audit:",j)}let Z;if(O?Z=j:(this.#e=G,Z=nl(this,j)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(A?.residencyId!=null)ce=A.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=io(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(qe??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=qe[fe]}ce=Rc(_e)}O||(qe=m);let ee=y?.expiresAt??(h?h+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(B).toISOString()}${ee?", expires at: "+new Date(ee).toISOString():""}${N?", replaces entry from: "+new Date(N.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(Z).slice(0,100)}catch{return""}})()),fn(C,G,Z);let J=O?"put":"patch";T(C,Z,N,B,ie?En:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:A?.nodeId,originatingOperation:y?.originatingOperation},J,!1,qe),y.expiresAt&&so()},"commit")};b.addWrite(L)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this.isCollection){for await(let O of this.search(m))(await Ce.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this.#e?this._writeDelete(m):!1}_writeDelete(m){let O=Vr(this.getContext()),A=this.getId();Cr(A);let y=this.getContext();return O.addWrite({key:A,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,A),beforeIntermediate:ye.delete?.bind(this,y,A),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!(no(b,C,m?.nodeId)<=0)&&(fn(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${A}, txn timestamp: ${new Date(b).toISOString()}`),g||R?(T(A,null,this.#r,b,0,g,{user:y?.user,nodeId:m?.nodeId},"delete"),g||so()):Hc(i,C))},"commit")}),!0}search(m){let O=this.getContext(),A=Vr(O);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this.getId()&&(y=[{attribute:null,comparator:Array.isArray(this.getId())?"prefix":"starts_with",value:this.getId()}].concat(y));let b,C={};function I(J,_e){let fe;switch(_e){case"and":case void 0:if(J.length<1)throw new Error('An "and" operator requires at least one condition');fe=!0;break;case"or":if(J.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+_e)}for(let Ae of J){if(Ae.conditions){Ae.conditions=I(Ae.conditions,Ae.operator);continue}let De=Ae[0]??Ae.attribute,we=De==null?H:Oi(E,De);if(we)(we.type||SR[Ae.comparator])&&(Ae[1]===void 0?Ae.value=B(Ae.value,we):Ae[1]=B(Ae[1],we));else if(De!=null)throw(0,Ir.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let hr=Ae.chainedConditions[0],Pr,Ws;if(hr.comparator==="gt"||hr.comparator==="greater_than"||hr.comparator==="ge"||hr.comparator==="greater_than_equal"?(Pr=Ae,Ws=hr):(Pr=hr,Ws=Ae),Pr.comparator!=="lt"&&Pr.comparator!=="less_than"&&Pr.comparator!=="le"&&Pr.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ws.comparator==="ge"||Ws.comparator==="greater_than_equal",bt=Pr.comparator==="le"||Pr.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(bt?"le":"lt"),Ae.value=[Ws.value,Pr.value]}else throw new Error("Multiple chained conditions are not currently supported")}return J}a(I,"prepareConditions");function L(J,_e){if(m.enforceExecutionOrder)return J;for(let fe of J)fe.conditions&&(fe.conditions=L(fe.conditions,fe.operator));return J.length>1&&_e!=="or"?(0,rJ.sortBy)(J,Om(Ce)):J}a(L,"orderConditions");function B(J,_e){return Array.isArray(J)?J.map(fe=>gA(fe,_e)):gA(J,_e)}a(B,"coerceTypedValues");let N=m.operator;(y.length>0||N)&&(y=I(y,N));let x=typeof m.sort=="object"&&m.sort,G;if(x&&N!=="or"){let J=x.attribute;if(J==null)throw new Ir.ClientError("Sort requires an attribute");if(b=y.find(_e=>gu(_e.attribute)===gu(J)),!b){let _e=Oi(E,J);if(!_e)throw(0,Ir.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not a defined attribute`,404);if(_e.indexed)b={attribute:J,comparator:"sort"},y.push(b);else if(y.length===0&&!m.allowFullScan)throw(0,Ir.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}y=L(y,N),x&&(b&&y[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&y.splice(y.indexOf(b),1),G=x));let j=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!j};let ie=A.useReadTxn(),F=TR(y,N,Ce,ie,m,O,(J,_e)=>Sf(J,j,O,ie,_e),C),qe=m.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(j,O,ie,C,qe,!0),ce=Ce.transformToOrderedSelect(F,j,G,ie,O,Z);function ee(J){return m.offset||m.limit!==void 0?J.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):J}return a(ee,"applyOffset"),G&&(ce=ee(ce)),ce.onDone=()=>{ce.onDone=null,A.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(j){let J=[];for(let _e of j)_e==="*"?J.push(...E.map(fe=>fe.name)):J.push(_e.name||_e);return J}return E.filter(J=>!J.computed&&!J.relationship).map(J=>J.name)},ce}static transformToOrderedSelect(m,O,A,y,b,C){let I=new Xh;if(A){m=Sf(m,O,y,b,null);let L;I.iterate=function(){let N,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,j=A.dbOrderedAttribute,ie,F,qe=!0;function Z(ee){let J=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=uu(fe,ee.attribute,y),we=uu(Ae,ee.attribute,y),hr=_e?(0,Zl.compareKeys)(we,De):(0,Zl.compareKeys)(De,we);return hr===0?J?.(fe,Ae)||0:hr}}a(Z,"createComparator");let ce=Z(A);return{async next(){let ee;if(N)if(ee=N.next(),ee.done){if(G)return I.onDone&&I.onDone(),ee}else return{value:await C.call(this,ee.value)};L=[],ie&&L.push(ie);do if(ee=await x.next(),ee.done){if(G=!0,L.length)break;return I.onDone&&I.onDone(),ee}else{let J=ee.value;if(J?.then&&(J=await J),j){let _e=uu(J,j,y);if(qe)qe=!1,F=_e;else if(_e!==F){F=_e,ie=J;break}}L.push(J)}while(!0);return A.isGrouped,L.sort(ce),N=L[Symbol.iterator](),ee=N.next(),ee.done?(I.onDone&&I.onDone(),ee):{value:await C.call(this,ee.value)}},return(){I.onDone&&I.onDone(),x.return()},throw(){I.onDone&&I.onDone(),x.throw()}}};let B=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],j;if(G.name===N.attribute[0]){for(j=G.sort||(G.sort={});j.next;)j=j.next;j.attribute=N.attribute.slice(1),j.descending=N.descending}else G===N.attribute[0]&&(O[x]=j={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&B(N.next)},"applySortingOnSelect");B(A)}else I.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),I=I.map(function(L){try{let B=C.call(this,L);return typeof B?.catch=="function"?B.catch(N=>{throw N.partialObject={[t]:L.key},N}):B}catch(B){throw B.partialObject={[t]:L.key},B}});return I}static transformEntryForSelect(m,O,A,y,b,C){if(m&&(m===t||m?.length===1&&m[0]===t&&Array.isArray(m))){let N=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return m===t?N:m.asArray?x=>[N(x)]:x=>({[t]:N(x)})}let I;b&&v&&!(typeof m=="string"?[m]:m)?.every(N=>{let x;return typeof N=="object"?x=N.name:x=N,r[x]||x===t})&&(I=!0);let L,B=a(function(N){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),N!=null){if(x=N.value||N.deref?.()?.value,!x&&(N.key===void 0||N.deref)||N.metadataFlags&En){if(N.metadataFlags&En&&O.replicateFrom===!1&&C&&N.residencyId)return Ec.SKIP;if(N=cu(N.key??N,O,{transaction:A,lazy:m?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(B.bind(this));x=N?.value}if(I&&N?.metadataFlags&(En|Ea)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=lu(N.key??N,N,O);if(G?.then)return G.then(B)}}if(x==null)return C?Ec.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,j=a((F,qe)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Hn?.[Z],ee;if(ce){let J=y?.[Z];if(J)if(J.hasMappings){let fe=ce.from?x[ce.from]:gu(N.key);ee=J.get(fe),ee||(ee=[])}else ee=J.fromRecord?.(x);else ee=ce(x,O,N);let _e=a(fe=>{if(fe&&typeof fe=="object"){let Ae=ce.definition?.tableClass||Ce;L||(L={});let De=L[Z]||(L[Z]=Ae.transformEntryForSelect(Z===F?null:F.select||(Array.isArray(F)?F:null),O,A,J,b));if(Array.isArray(fe)){let we=[],hr=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,A,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Pr=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Pr);we.push(Re.value),Re=hr.next()}qe(we,Z)},"nextValue"),Ws=Pr(hr.next());Ws&&(G||(G=[]),G.push(Ws));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>qe(we,Z)));return}}qe(fe,Z)},"handleResolvedValue");ee?.then?(G||(G=[]),G.push(ee.then(_e))):_e(ee);return}else ee=x[Z],ee&&typeof ee=="object"&&Z!==F&&(ee=Ce.transformEntryForSelect(F.select||F,O,A,null)({value:ee}));qe(ee,Z)},"selectAttribute"),ie;if(typeof m=="string")j(m,F=>{ie=F});else if(Array.isArray(m))if(m.asArray)ie=[],m.forEach((F,qe)=>{F==="*"?m[qe]=x:j(F,Z=>ie[qe]=Z)});else{ie={};let F=m.forceNulls;for(let qe of m)if(qe==="*")for(let Z in x)ie[Z]=x[Z];else j(qe,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new Ir.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return B}async subscribe(m){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||dt({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),m||(m={});let O=!m.rawEvents,A=[],y=this,b=HP(Ce,this.getId()??null,function(I,L,B,N){try{let x=L.getValue?.(i,O),G=L.type;if(!x&&G==="patch"&&O){let ie=i.getEntry(I);ie?.version===L.version?x=ie.value:x=L.getValue?.(i,!0,B),G="put"}let j={id:I,localTime:B,value:x,version:L.version,type:G,beginTxn:N};A?A.push(j):this.send(j)}catch(x){xe.default.error?.(x)}},m.startTime||0,m),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,m.onlyChildren&&(b.onlyChildren=!0)),m.supportsTransactions&&(b.supportsTransactions=!0);let I=this.getId(),L=m.previousCount;L>1e3&&(L=1e3);let B=m.startTime;if(this.isCollection){if(B){if(L)throw new Ir.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let G=Nt(x);if(G.tableId!==n)continue;let j=G.recordId;if(I==null||eJ(I,j)){let ie=G.getValue(i,O,N);if(b.send({id:j,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>Xj&&await b.waitForDrain()===!1)return}b.startTime=N}}else if(L){let N=[];for(let{key:x,value:G}of l.getRange({start:"z",end:!1,reverse:!0}))try{let j=Nt(G);if(j.tableId!==n)continue;let ie=j.recordId;if(I==null||eJ(I,ie)){let F=j.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:j.version,type:j.type}),--L<=0)break}}catch(j){xe.default.error("Error getting history entry",x,j)}for(let x=N.length;x>0;)b.send(N[--x]);N[0]&&(b.startTime=N[0].localTime)}else if(!m.omitCurrent){for(let{key:N,value:x,version:G,localTime:j}of i.getRange({start:I??!1,end:I==null?void 0:[I,Zl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:j,value:x,version:G,type:"put"}),b.queue?.length>Xj&&await b.waitForDrain()===!1))return}}else{L&&!B&&(B=0);let N=this.#r?.localTime;if(N===ey&&(i.cache?.delete(I),this.#r=i.getEntry(I),xe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),xe.default.trace?.("Subscription from",B,"from",I,N),B<N){let x=[],G=N;do{let j=l.get(G);if(j){m.omitCurrent=!0;let ie=Nt(j),F=ie.getValue(i,O,G);O&&(ie.type="put"),x.push({id:I,value:F,localTime:G,...ie}),G=ie.previousLocalTime}else break;L&&L--}while(G>B&&L!==0);for(let j=x.length;j>0;)b.send(x[--j]);b.startTime=N}!m.omitCurrent&&this.doesExist()&&b.send({id:I,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of A)b.send(N);A=null})();return m.listener&&b.on("data",m.listener),b}static subscribeOnThisThread(m,O){return m===0||O?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let A=Vr(this.getContext()),y=this.getId()||null;y!=null&&Cr(y);let b=this.getContext();A.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(A.checkOverloaded(),this.validate(m))},"validate"),before:Te.publish?.bind(this,b,y,m),beforeIntermediate:ye.publish?.bind(this,b,y,m),commit:a((C,I,L)=>{I===void 0&&R&&!g&&so(),xe.default.trace?.(`Publishing message to id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,I?.value??null,I,I?.version||C,0,!0,{user:b?.user,residencyId:O?.residencyId,expiresAt:b?.expiresAt,nodeId:O?.nodeId},"message",!1,m)},"commit")})}validate(m,O){let A,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let B=0,N=L.length;B<N;B++){let x=L[B],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let B in b)L.find(N=>N.name===B)||(A||(A=[])).push(`Property ${B} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof wi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,B=b.length;L<B;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=E.length;b<C;b++){let I=E[b];if(!(I.relationship||I.computed)&&(!O||I.name in m)){let L=y(m[I.name],I,I.name);L&&(m[I.name]=L)}}if(d)for(let b in m)E.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new Ir.ClientError(A.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(m){let O=E.slice(0);for(let A of m){if(!A.name)throw new Ir.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new Ir.ClientError("Attribute names cannot include backticks or forward slashes");(0,nJ.validateAttribute)(A.name),O.push(A)}return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(m){let O=E.filter(A=>!m.includes(A.name));return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static getSize(){let m=i.getStats();return(m.treeBranchPageCount+m.treeLeafPageCount+m.overflowPages)*m.pageSize}static getAuditSize(){let m=l?.getStats();return m&&(m.treeBranchPageCount+m.treeLeafPageCount+m.overflowPages)*m.pageSize}static getStorageStats(){let m=i.env.path,O=EA.default.statfsSync?.(m)??{};return{available:O.bavail*O.bsize,free:O.bfree*O.bsize,size:O.blocks*O.bsize}}static async getRecordCount(m){let O=i.getStats().entryCount,A=1e3/2,y=performance.now(),b=Math.floor(O/2),C=m?.exactCount,I=0,L=0,B;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await mc(),!C&&L<b&&performance.now()-y>A){B=L;break}if(B){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:B,snapshot:!1}))ee!=null&&I++,await mc();let x=B*2,G=(I+N)/x,j=Math.pow((I-N+1)/B/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(j)*O,1),F=Math.round(G*O),qe=Math.max(F-1.96*ie,I+N),Z=Math.min(F+1.96*ie,O),ce=Math.pow(10,Math.round(Math.log10(ie)));return ce>F&&(ce=ce/10),I=Math.round(F/ce)*ce,{recordCount:I,estimatedRange:[Math.round(qe),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Hn=this.propertyResolvers={$id:a((m,O,A)=>({value:A.key}),"$id"),$updatedtime:a((m,O,A)=>A.version,"$updatedtime"),$record:a((m,O,A)=>A?{value:m}:m,"$record")};for(let m of this.attributes){m.isPrimaryKey&&(H=m),m.resolve=null;let O=m.relationship,A=m.computed;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),ou=!0,O.to)m.elements?.definition?(Hn[m.name]=m.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=m.elements.definition.tableClass;return C?Eu({attribute:O.to,value:I},Vr(b).getReadTxn(),!1,L,!1).asArray:L.search([{attribute:O.to,value:I}],b).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let y=m.definition||m.elements?.definition;y?(Hn[m.name]=m.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(m.elements){let B,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:Vr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(B=!0),G});return O.filterMissing?B?Promise.all(N).then(x=>x.filter(tJ)):N.filter(tJ):B?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:Vr(C).getReadTxn()}):y.tableClass.get(L,C)}},m.set=(b,C)=>{if(Array.isArray(C)){let I=C.map(L=>L.getId?.()||L[y.tableClass.primaryKey]);b[O.from]=I}else{let I=C.getId?.()||C[y.tableClass.primaryKey];b[O.from]=I}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.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`);else A&&(typeof A.from=="function"&&this.setComputedAttribute(m.name,A.from),Hn[m.name]=m.resolve=(y,b,C)=>{let I=typeof A.from=="string"?y[A.from]:y,L=this.userResolvers[m.name];if(L)return L(I,b,C);xe.default.warn(`Computed attribute "${m.name}" does not have a function assigned to it. Please use setComputedAttribute('${m.name}', resolver) to assign a resolver function.`),this.userResolvers[m.name]=()=>{}})}qE(this,this)}static setComputedAttribute(m,O){let A=Oi(E,m);if(!A){console.error(`The attribute "${m}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${m}" is not defined as computed in the table "${s}"`);return}this.userResolvers[m]=O}static async deleteHistory(m=0,O=!1){let A;for(let{key:y,value:b}of l.getRange({start:0,end:m}))await mc(),Nt(b).tableId===n&&(A=hA(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await mc(),C===null&&I<m&&(A=Hc(i,y))}await A}static async*getHistory(m=0,O=1/0){for(let{key:A,value:y}of l.getRange({start:m||1,end:O})){await mc();let b=Nt(y);b.tableId===n&&(yield{id:b.recordId,localTime:A,version:b.version,type:b.type,value:b.getValue(i,!0,A),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let A=i.getEntry(m);if(!A)return O;let y=A.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await mc();let C=l.get(y);if(C){let I=Nt(C);O.push({id:I.recordId,localTime:y,version:I.version,type:I.type,value:I.getValue(i,!0,y),user:I.user}),y=I.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){Y?.remove()}}Ce.updatedAttributes();let gf=Ce.prototype;return h&&Ce.setTTLExpiration(h/1e3),se&&em(),Ce;function fn(K,m,O){let A;for(let y in r){let b=r[y],C=b.isIndexing,I=Hn[y],L=O&&(I?I(O):O[y]),B=m&&(I?I(m):m[y]);if(L===B&&!C)continue;A=!0;let N=b.indexNulls,x=(0,Uh.getIndexedValues)(L,N),G=(0,Uh.getIndexedValues)(B,N);if(G?.length>0){let j=new Set(G);if(x=x?x.filter(ie=>{if(j.has(ie))j.delete(ie);else return!0}):[],G=Array.from(j),(G.length>0||x.length>0)&&jj){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,Zj)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&jj&&b.prefetch(x.map(j=>({key:j,value:K})),Zj);if(x)for(let j=0,ie=x.length;j<ie;j++)b.put(x[j],K)}return A}a(fn,"updateIndices");function Cr(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>Qj)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");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,Zl.writeKey)(K,_Ae,0)>Qj)throw new Error("Primary key size is too large: "+K.length);return!0}a(Cr,"checkValidId");function cu(K,m,O,A,y){if(Ce.getResidencyById&&O.ensureLoaded&&m?.replicateFrom!==!1){let C=io(Ce.getResidencyById(K));if(C&&!C.includes(server.hostname)&&w)return w({key:K,residency:C}).then(y)}let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let C=i.getEntry(K,O);return C?.residencyId&&C.metadataFlags&En&&w&&O.ensureLoaded&&m?.replicateFrom!==!1?w(C).then(I=>y(I,K),I=>(xe.default.error?.("Error loading remote record",K,C,O,I),y(null,K))):(C&&m&&(C?.version>(m.lastModified||0)&&(m.lastModified=C.version),C?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=C.localTime)),y(C,K))},"whenPrefetched");return A?b():ae>0?(ae--,b()):new Promise((C,I)=>{ae===0?(ae--,i.prefetch([K],()=>{L(),B()})):(ne.push(K),ue.push(B),ne.length>Zh&&(ae--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{ae===-1?L():ae++;for(let x of N)x()}),ne=[],ue=[],me>2&&me--}else ae=me,me<Ef&&me++}a(L,"prefetch");function B(){try{C(b())}catch(N){I(N)}}a(B,"load")})}a(cu,"loadLocalRecord");function $r(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return pAe;let O=m[c],A,y=O?.tables;if(y)return y[s];if(c==="data"&&(A=m[s])&&!A.tables)return A}a($r,"getTablePermissions");function lu(K,m,O,A){if(v){let y=!1;if(O.noCache?y=!0:(m?(!m.value||m.metadataFlags&(En|Ea)||m.expiresAt!=null&&m.expiresAt<Date.now())&&(y=!0):y=!0,Zn(!y,"cache-hit",s)),y){let b=Tf(K,m,O).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),O&&(C?.version>(O.lastModified||0)&&(O.lastModified=C.version),O.lastRefreshed=Date.now()),C));if(O?.onlyIfCached||m?.value&&A?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!A.doesExist())throw new Ir.ServerError("Entry is not cached",504);return}else return b}}else if(m?.value&&m.expiresAt!=null&&m.expiresAt<Date.now())return Ce.evict(m.key,m.value,m.version),m.value=null,{then(y){return y(m)}}}a(lu,"ensureLoadedFromSource");function Vr(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new Nc,m.lmdbDb=i,m;m=O}while(!0)}else return new Rm}a(Vr,"txnForContext");function uu(K,m,O){if(!K)return;let A=K.value||i.getEntry(K.key)?.value;if(typeof m=="object"){let b=Hn,C=A;for(let I=0,L=m.length;I<L;I++){let B=m[I],N=b?.[B];C=N&&C?N(C,O,!0)?.value:C?.[B],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Hn[m];return y?y(A,O):A[m]}a(uu,"getAttributeValue");function Sf(K,m,O,A,y){let b=y?.length,C={transaction:A,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},I;function L(B,N){let x=B?.value;if(!x)return Ec.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,B))return Ec.SKIP;return N!==void 0&&(B.key=N),B}if(a(L,"processEntry"),b>0||!K.hasEntries){let B=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Ec.SKIP;for(let x=0;x<b;x++){let j=y[x].idFilter;if(j){if(!j(N))return Ec.SKIP;I||(I=[]),I.push(x)}}return cu(N,O,C,!1,L)});return Array.isArray(K)&&(B=B.filter(N=>N!==Ec.SKIP)),B.hasEntries=!0,B}return K}a(Sf,"transformToEntries");function no(K,m,O=server.replication?.getThisNodeId(l)){if(K<=m?.version){if(m?.version===K&&O!==void 0){let A=server.replication?.exportIdMapping(l),y=m.localTime,b=y&&l.get(y);if(b){let C,I,L=Nt(b);for(let B in A)A[B]===O&&(C=B),A[B]===L.nodeId&&(I=B);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a(no,"precedesExistingVersion");async function Tf(K,m,O){let A=m?.metadataFlags,y=m?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(En|Ea)?b(Tf(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},dAe)});let I=m?.value,L={requestContext:O,replacingRecord:I,replacingEntry:m,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},B=O?.responseHeaders;return new Promise((N,x)=>{let G;FP(Ot(L,async j=>{let ie=performance.now(),F,qe,Z;try{for(let _e of Ce.sources)if(_e.get&&(!_e.get.reliesOnPrototype||_e.prototype.get)){if(_e.available?.(m)===!1)continue;if(L.source=_e,F=await _e.get(K,L),F)break}Z=A&En;let ee=L.lastModified||Z&&y;qe=Z||ee>y||!I,ee||(ee=(0,Uh.getNextMonotonicTime)());let J=performance.now()-ie;if(nr(J,"cache-resolution",s,null,"success"),B&&tg(B,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),j.timestamp=ee,h&&L.expiresAt==null&&(L.expiresAt=Date.now()+h),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=I,ee=y;else throw new Ir.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}G=!0,N({key:K,version:ee,value:F})}catch(ee){ee.message+=` while resolving record ${K} for ${s}`,I&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(N({key:K,version:y,value:I}),xe.default.trace?.(ee.message,"(returned stale record)")):x(ee);let J=performance.now()-ie;nr(J,"cache-resolution",s,null,"fail"),B&&tg(B,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Vr(L).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:a((ee,J)=>{if(J?.version!==y)return;let _e=fn(K,I,F);if(F){ye.put?.(L,K,F),J&&(O.previousResidency=Ce.getResidencyRecord(J.residencyId));let fe,Ae=!1,De,we=io(Ce.getResidency(F,O));if(we){if(!we.includes(server.hostname))if(fe=F,Ae=!0,Ce.getResidencyById)F=void 0;else{F=null;for(let hr in r)F||(F={}),F[hr]=fe[hr]}De=Rc(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,J,ee,Ae?En:0,g&&(qe||Ae)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:De},"put",!!Z,fe)}else J&&(ye.delete?.(L,K),xe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),g||R?T(K,null,J,ee,0,g&&qe||null,{user:L?.user},"delete",!!Z):Hc(i,J,y))},"commit")})}),()=>{i.unlock(K,y)},j=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",j)})})}a(Tf,"getFromSource");function du(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new Ir.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new Ir.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(du,"checkContextPermissions");function so(K){let m=!1;if(K&&(K-ut>1&&(m=!0),ut=K),!(Qt===br&&!m)&&(br=Qt,(0,Ql.getWorkerIndex)()===(0,Ql.getWorkerCount)()-1))return Es&&clearTimeout(Es),Qt?new Promise(O=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let y=Qt/(1+ut),b=m?Date.now():Math.ceil((Date.now()-A.getTime())/y)*y+A.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),Es=setTimeout(()=>$=$.then(async()=>{if(C(Math.max(I+Qt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Es);return}let L=50,B=new Array(L),N=0,x=Math.pow(ut,8)*(Xl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(ut,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function j(ie,F,qe,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(ut){let ee=i.lastSize;return qe&An&&yu(Z,J=>{J.size&&(ee+=J.size)}),xe.default.trace?.(`shouldEvict adjusted ${ce} ${ee}, ${ce*(ie-F)/ee} < ${x}`),ce*(ie-F)/ee<x}return!1}a(j,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:qe,value:Z,version:ce,expiresAt:ee,metadataFlags:J}=F,_e;Z===null&&!g&&ce+uAe<Date.now()?_e=Hc(i,F,ce):ee!=null&&j(ee,ce,J,Z)&&(_e=Ce.evict(qe,Z,ce),ie++),_e&&(await B[N],B[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await mc()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${ie} entries`)}catch(ie){xe.default.warn?.(`Error in cleanup scan for ${s}:`,ie)}O(void 0),ut=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a(so,"scheduleCleanup");function Af(){Y=l?.addDeleteRemovalCallback(n,i,(K,m)=>{i.remove(K,m)})}a(Af,"addDeleteRemoval");function em(){(0,Ql.getWorkerIndex)()===0&&setInterval(async()=>{if(!au){au=!0;try{let K=se.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${se} must be indexed`);for(let O of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of m.getValues(O)){let y=i.getEntry(A);y?.value?y.value[K]<Date.now()&&Ce.evict(A,y.value,y.version):i.ifVersion(A,y?.version,()=>m.remove(O,A))}await mc()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{au=!1}}},lAe).unref()}a(em,"runRecordExpirationEviction");function io(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let m=server.shards?.get?.(K);if(m)return xe.default.trace?.(`Shard ${K} mapped to ${m.map(O=>O.name).join(", ")}`),m.map(O=>O.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(io,"residencyFromFunction");function Rc(K){if(K){let m=K.join(","),O=f.get([Symbol.for("residency_by_set"),m]);return O||(f.put([Symbol.for("residency_by_set"),m],O=Math.floor(Math.random()*2147418112)+65535),f.put([Symbol.for("residency_by_id"),O],K),O)}}a(Rc,"getResidencyId")}function kP(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 Zj(){}function hAe(e){sJ=e}function gA(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return mA(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return mA(+e);case"Float":return e==="null"?null:mA(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;mAe.test(e)||(e+="Z");let n=new Date(e);return mA(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,SA.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function mA(e){if(isNaN(e))throw new SyntaxError;return e}function eJ(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);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 FP(e,t,r){return e?.then?e.then(t,r):t(e)}function tJ(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function EAe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Ec,Uh,rJ,nJ,Xl,Ir,xh,Bh,xe,Zl,Ql,SA,EA,cAe,sJ,lAe,uAe,jj,dAe,Jj,fAe,En,Ea,_Ae,Qj,Xj,pAe,uxe,mAe,mc,qf=be(()=>{k();Ec=require("lmdb"),Uh=M(pn()),rJ=require("lodash"),nJ=M(xf());ga();ym();Xl=M(le());NN();Ir=M(he()),xh=M(bo()),Bh=M(ni());Le();Gf();xe=M(Ni());Qb();wc();Zl=require("ordered-binary"),Ql=M(tt());mo();SA=M(oe());wu();ki();HE();z_();EA=M(require("node:fs"));As();HT();cAe=new Uint8Array(9);cAe[8]=192;lAe=6e4,uAe=864e5;Xl.initSync();jj=Xl.get(U.STORAGE_PREFETCHWRITES),dAe=1e4,Jj=1,fAe=2,En=1,Ea=8,_Ae=Buffer.allocUnsafeSlow(8192),Qj=1978,Xj=100,pAe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},uxe=(0,SA.convertToMS)(Xl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(TA,"makeTable");a(kP,"attributesAsObject");a(Zj,"noop");a(hAe,"setServerUtilities");mAe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(gA,"coerceType");a(mA,"rejectNaN");a(eJ,"isDescendantId");mc=a(()=>new Promise(setImmediate),"rest");a(FP,"when");a(tJ,"exists");a(qs,"stringify");a(EAe,"hasOtherProcesses")});var rt={};Ue(rt,{database:()=>qu,database_envs:()=>sa,databases:()=>Ve,dropDatabase:()=>rO,dropTableMeta:()=>RAe,getDatabases:()=>Qe,getDefaultCompression:()=>MS,getTables:()=>gAe,onRemovedDB:()=>hp,onUpdatedTable:()=>Tl,readMetaDb:()=>Hh,resetDatabases:()=>Pd,table:()=>dt,tables:()=>Xn});function gAe(){return bA||Qe(),Xn||{}}function Qe(){if(bA)return Ve;bA=!0,df=new Map;let e=(0,Jt.getHdbBasePath)()&&(0,Pt.join)((0,Jt.getHdbBasePath)(),Oc),t=(0,Jt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Jt.get)(U.STORAGE_PATH)||e&&((0,fs.existsSync)(e)?e:(0,Pt.join)((0,Jt.getHdbBasePath)(),am)),!e)return;if((0,fs.existsSync)(e))for(let n of(0,fs.readdirSync)(e,{withFileTypes:!0})){let s=(0,Pt.basename)(n.name,".mdb");n.isFile()&&(0,Pt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&Hh((0,Pt.join)(e,n.name),null,s)}if((0,fs.existsSync)((0,uf.getBaseSchemaPath)())){for(let n of(0,fs.readdirSync)((0,uf.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Pt.join)((0,uf.getBaseSchemaPath)(),n.name),i=(0,Pt.join)((0,uf.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,fs.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Pt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Pt.join)(i,o.name);Hh((0,Pt.join)(s,o.name),(0,Pt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,fs.existsSync)(i))for(let c of(0,fs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Pt.extname)(c.name).toLowerCase()===".mdb"&&Hh((0,Pt.join)(i,c.name),(0,Pt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Pt.join)(l.path,(0,Pt.basename)(c+".mdb"));(0,fs.existsSync)(u)&&Hh(u,c,n,null,!0)}}for(let n in Ve){let s=df.get(n);if(s){let i=Ve[n];n.includes("delete")&&Dt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Dt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Xn)delete Xn[i];delete Xn[OA]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return df=null,Ve}function Pd(){bA=!1;for(let[,e]of sa)e.needsDeletion=!0;Qe();for(let[e,t]of sa)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),sa.delete(e),delete Ve[t.databaseName],Fh.forEach(r=>r(t.databaseName)));return Ve}function Hh(e,t,r=$P,n,s){let i=new GP.default(e,!1);try{let o=sa.get(e);o?o.needsDeletion=!1:(o=(0,ff.open)(i),sa.set(e,o));let c=new eu.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(AA.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,fs.existsSync)(n)&&(i.path=n,u=(0,ff.open)(i),u.isLegacy=!0):u=pA(o));let f=cJ(r),d=f[OA],_=new Map;for(let{key:p,value:h}of l.getRange({start:!1})){let[S,g]=p.toString().split("/");g===""?g=h.name:g||(g=S,S=t,h.name||(h.name=g,h.indexed=!h.is_hash_attribute)),d?.add(S);let R=_.get(S);R||_.set(S,R={attributes:[]}),(g==null||h.is_hash_attribute)&&(R.primary=h),g!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:p,configurable:!0})}for(let[p,h]of _){let{attributes:S,primary:g}=h;if(!g){for(let ae of S)if(ae.is_hash_attribute||ae.isPrimaryKey){g=ae;break}if(!g){Dt.warn(`Unable to find a primary key attribute on table ${p}, with attributes: ${JSON.stringify(S)}`);continue}}let R=f[p],E={},T=[],w,v,H=typeof g.audit=="boolean"?g.audit:(0,Jt.get)(U.LOGGING_AUDITLOG),$=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(R)E=R.indices,T=R.attributes,R.schemaVersion++;else{w=g.tableId,w?w>=(l.get(lf)||0)&&(l.putSync(lf,w+1),Dt.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(g.tableId=w=l.get(lf),w||(w=1),Dt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(lf,w+1),l.putSync(g.key,g));let ae=new eu.default(!g.is_hash_attribute,g.is_hash_attribute);if(ae.compression=g.compression,ae.compression){let me=(0,Jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||aJ;ae.compression.threshold=me}v=Xm(o.openDB(g.key,ae),o),o.databaseName=r,v.tableId=w}let ue;for(let ae of S){ae.attribute=ae.name;try{if(!ae.is_hash_attribute&&(ae.indexed||ae.attribute&&!ae.name)){if(!E[ae.name]){let Te=new eu.default(!ae.is_hash_attribute,ae.is_hash_attribute);E[ae.name]=o.openDB(ae.key,Te),E[ae.name].indexNulls=ae.indexNulls}let me=T.find(Te=>Te.name===ae.name);me?T.splice(T.indexOf(me),1,ae):T.push(ae),ue=!0}}catch(me){Dt.error("Error trying to update attribute",ae,T,E,me)}}for(let ae of T)if(!S.find(Te=>Te.name===ae.name)){if(ae.is_hash_attribute){Dt.error("Unable to remove existing primary key attribute",ae);continue}ae.indexed&&(T.splice(T.indexOf(ae),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=lJ(f,p,TA({primaryStore:v,auditStore:u,audit:H,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:$,tableName:p,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let ae of kh)ae(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function cJ(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Xn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),df&&!df.has(e)){let r=new Set;t[OA]=r,df.set(e,r)}return t}function lJ(e,t,r){return e[t]=r,r}function qu({database:e,table:t}){e||(e=$P),Qe();let r=cJ(e),n=(0,Pt.join)((0,Jt.getHdbBasePath)(),Oc),s=(0,Jt.get)(U.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Jt.get)(U.STORAGE_PATH)||((0,fs.existsSync)(n)?n:(0,Pt.join)((0,Jt.getHdbBasePath)(),am));let o=(0,Pt.join)(n,(i?t:e)+".mdb"),c=sa.get(o);if(!c||c.status==="closed"){let l=new GP.default(o,!1);c=(0,ff.open)(l),sa.set(o,c)}return c.auditStore||(c.auditStore=pA(c)),c}async function rO(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,sa.delete(r.path),r.status==="open"&&(await r.close(),await Gh.remove(r.path));if(r||(r=qu({database:e,table:null}),r.status==="open"&&(await r.close(),await Gh.remove(r.path))),e==="data"){for(let n in Xn)delete Xn[n];delete Xn[OA]}delete Ve[e],Fh.forEach(n=>n(e)),await vR(r)}function dt(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,schemaDefined:_,origin:p}=e;r||(r=$P);let h=qu({database:r,table:t}),S=Ve[r];Dt.trace(`Defining ${t} in ${r}`);let g=S?.[t];if(h.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,E,T;_==null&&(_=!0);let w=new eu.default(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let v,H;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...o)}else{let Y=h.auditStore;E=o.find(me=>me.isPrimaryKey)||{},R=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=MS(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,Jt.get)(U.LOGGING_AUDITLOG),n&&(E.expiration=n),s&&(E.eviction=s),u??=!1,E.splitSegments=u,typeof l=="boolean"&&(E.sealed=l),typeof f=="boolean"&&(E.replicate=f),p&&(E.origins?E.origins.includes(p)||E.origins.push(p):E.origins=[p]),Dt.trace(`${t} table loading, opening primary store`);let ne=new eu.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=h.dbisDb=h.openDB(AA.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return H&&H(),Pd(),dt(e);let ae=Xm(h.openDB(ue,ne),h);h.databaseName=r,ae.tableId=T.get(lf),Dt.trace(`Assigning new table id ${ae.tableId} for ${t}`),ae.tableId||(ae.tableId=1),T.put(lf,ae.tableId+1),E.tableId=ae.tableId,g=lJ(S,t,TA({primaryStore:ae,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:ae.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let $=g.indices;T=T||(h.dbisDb=h.openDB(AA.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,ae]=Y.toString().split("/");if(ae===""&&(ae=ne.name),ae){if(ue!==t)continue}else continue;let me=o.find(ye=>ye.name===ae),Te=!me?.indexed&&ne.indexed&&!ne.isPrimaryKey;if((!me||Te)&&(se(),v=!0,me||T.remove(Y),Te)){let ye=g.indices[ue];ye&&W.push(ye)}}let te=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(v=!0,Y.relationship))continue;let ne=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ne,configurable:!0});let ue=T.get(ne);if(Y.isPrimaryKey){if(ue=ue||T.get(ne=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||f!==void 0&&f!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||Y.type!==ue.type){let me={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),me.audit=c),n&&(me.expiration=+n),s&&(me.eviction=+s),l!==void 0&&(me.sealed=l),f!==void 0&&(me.replicate=f),Y.type&&(me.type=Y.type),v=!0,se(),T.put(ne,me)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let ae=!ue||ue.type!==Y.type||ue.indexed!==Y.indexed||ue.nullable!==Y.nullable||ue.version!==Y.version||JSON.stringify(ue.properties)!==JSON.stringify(Y.properties)||JSON.stringify(ue.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let me=new eu.default(!0,!1),Te=h.openDB(ne,me);(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<qh.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<qh.workerData?.restartNumber)&&(v=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=ue?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Te}),te.push(Y))),T.put(ne,Y)),ue?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Te.indexNulls=Y.indexNulls,$[Y.name]=Te}else ae&&(v=!0,se(),T.put(ne,Y))}}finally{H&&H()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Dt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=AAe(g,te,W):v&&RA.signalSchemaChange(new yA.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=p,v)for(let Y of kh)Y(g,p!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Dt.trace(`${t} table loaded`),g;function se(){H||h.transactionSync(()=>({then(Y){H=Y}}))}a(se,"startTxn")}async function AAe(e,t,r){try{Dt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await RA.signalSchemaChange(new yA.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let d of t)(0,ff.compareKeys)(d.lastIndexedKey,u)<0&&(u=d.lastIndexedKey),d.lastIndexedKey==null&&d.dbi.clearAsync();let f=0;for(let{key:d,value:_,version:p}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(_){if(f++,s=e.primaryStore.ifVersion(d,p,()=>{for(let h=0;h<l;h++){let S=t[h],g=S.name;try{let R=S.resolve,E=_&&(R?R(_):_[g]),T=(0,iJ.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(R){o[g]||(o[g]=!0,Dt.error(`Error indexing attribute ${g}`,R))}}}),s.then(()=>f--,h=>{f--,Dt.error(h)}),qh.workerData&&qh.workerData.restartNumber!==oJ.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=d,e.dbisDB.put(h.key,h);if(i)return}f>SAe?await s:f>TAe&&await new Promise(h=>setImmediate(h))}for(let d of t)delete d.lastIndexedKey,delete d.indexingPID,d.dbi.isIndexing=!1,s=e.dbisDB.put(d.key,d)}await s,await RA.signalSchemaChange(new yA.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Dt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Dt.error("Error in indexing",n)}}function RAe({table:e,database:t}){let r=qu({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 Tl(e){return kh.push(e),{remove(){let t=kh.indexOf(e);t>-1&&kh.splice(t,1)}}}function hp(e){return Fh.push(e),{remove(){let t=Fh.indexOf(e);t>-1&&Fh.splice(t,1)}}}function MS(){let e=(0,Jt.get)(U.STORAGE_COMPRESSION),t=(0,Jt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||aJ,n={startingOffset:32};return t&&(n.dictionary=Gh.readFileSync(t)),r&&(n.threshold=r),e&&n}var Jt,AA,ff,Pt,fs,uf,eu,GP,Gh,qP,iJ,RA,yA,qh,Dt,oJ,$P,OA,aJ,Xn,Ve,lf,kh,Fh,bA,sa,df,SAe,TAe,Le=be(()=>{Jt=M(le()),AA=M(Ut()),ff=require("lmdb"),Pt=require("path"),fs=require("fs"),uf=M(mt());qf();eu=M(s_()),GP=M(i_());k();Gh=M(require("fs-extra")),qP=M(Ai()),iJ=M(pn()),RA=M(bo()),yA=M(ni()),qh=require("worker_threads"),Dt=M(z()),oJ=M(tt());mo();wu();As();$P="data",OA=Symbol("defined-tables"),aJ=((0,Jt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Jt.initSync)();Xn=Object.create(null),Ve=Object.create(null);(0,qP._assignPackageExport)("databases",Ve);(0,qP._assignPackageExport)("tables",Xn);lf=Symbol.for("next-table-id"),kh=[],Fh=[],sa=new Map;a(gAe,"getTables");a(Qe,"getDatabases");a(Pd,"resetDatabases");a(Hh,"readMetaDb");a(cJ,"ensureDB");a(lJ,"setTable");a(qu,"database");a(rO,"dropDatabase");a(dt,"table");SAe=1e3,TAe=10;a(AAe,"runIndexing");a(RAe,"dropTableMeta");a(Tl,"onUpdatedTable");a(hp,"onRemovedDB");a(MS,"getDefaultCompression")});var oe=P((Axe,yJ)=>{"use strict";var gc=require("path"),pJ=require("fs-extra"),xn=z(),uJ=require("fs-extra"),NA=require("os"),yAe=require("net"),bAe=require("recursive-iterator"),yr=(k(),D(q)),{PACKAGE_ROOT:OAe}=nt(),NAe=uR(),dJ=require("papaparse"),wA=require("moment"),{inspect:wAe}=require("util"),fJ=require("is-number"),Txe=require("lodash"),IAe=require("minimist"),CAe=require("https"),PAe=require("http"),{hdb_errors:IA}=he(),DAe=/^((\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)))$/,hJ=require("util").promisify(setTimeout),LAe=100,MAe=5,vAe="",UAe=4,_J={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};yJ.exports={isEmpty:_s,isEmptyOrZeroLength:to,arrayHasEmptyValues:HAe,arrayHasEmptyOrZeroLengthValues:kAe,buildFolderPath:FAe,isBoolean:mJ,errorizeMessage:xAe,stripFileExtension:qAe,autoCast:$Ae,autoCastJSON:EJ,autoCastJSONDeep:KP,removeDir:VAe,compareVersions:KAe,isCompatibleDataVersion:YAe,escapeRawValue:WAe,unescapeValue:zAe,stringifyProps:jAe,timeoutPromise:QAe,isClusterOperation:ZAe,getClusterUser:tRe,checkGlobalSchemaTable:eRe,getHomeDir:SJ,getPropsFilePath:JAe,promisifyPapaParse:rRe,removeBOM:TJ,createEventPromise:nRe,checkProcessRunning:sRe,checkSchemaTableExist:iRe,checkSchemaExists:AJ,checkTableExists:RJ,getStartOfTomorrowInSeconds:oRe,getLimitKey:aRe,isObject:GAe,isNotEmptyAndHasValue:BAe,autoCasterIsNumberCheck:gJ,backtickASTSchemaItems:cRe,isPortTaken:XAe,createForkArgs:lRe,autoCastBoolean:uRe,async_set_timeout:hJ,getTableHashAttribute:dRe,doesSchemaExist:fRe,doesTableExist:_Re,stringifyObj:pRe,ms_to_time:hRe,changeExtension:mRe,getEnvCliRootPath:YP,noBootFile:ERe,httpRequest:gRe,transformReq:SRe,convertToMS:TRe,PACKAGE_ROOT:OAe};function xAe(e){return e instanceof Error?e:new Error(e)}a(xAe,"errorizeMessage");function _s(e){return e==null}a(_s,"isEmpty");function BAe(e){return!_s(e)&&(e||e===0||e===""||mJ(e))}a(BAe,"isNotEmptyAndHasValue");function to(e){return _s(e)||e.length===0||e.size===0}a(to,"isEmptyOrZeroLength");function HAe(e){if(_s(e))return!0;for(let t=0;t<e.length;t++)if(_s(e[t]))return!0;return!1}a(HAe,"arrayHasEmptyValues");function kAe(e){if(to(e))return!0;for(let t=0;t<e.length;t++)if(to(e[t]))return!0;return!1}a(kAe,"arrayHasEmptyOrZeroLengthValues");function FAe(...e){try{return e.join(gc.sep)}catch{console.error(e)}}a(FAe,"buildFolderPath");function mJ(e){return _s(e)?!1:e===!0||e===!1}a(mJ,"isBoolean");function GAe(e){return _s(e)?!1:typeof e=="object"}a(GAe,"isObject");function qAe(e){return to(e)?vAe:e.slice(0,-UAe)}a(qAe,"stripFileExtension");function $Ae(e){return _s(e)||e===""||typeof e!="string"?e:_J[e]!==void 0?_J[e]:gJ(e)===!0?Number(e):DAe.test(e)?new Date(e):e}a($Ae,"autoCast");function EJ(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(EJ,"autoCastJSON");function KP(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=KP(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=KP(r);n!==r&&(e[t]=n)}return e}else return EJ(e)}a(KP,"autoCastJSONDeep");function gJ(e){if(e.startsWith("0.")&&fJ(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&fJ(e))}a(gJ,"autoCasterIsNumberCheck");async function VAe(e){if(to(e))throw new Error(`Directory path: ${e} does not exist`);try{await uJ.emptyDir(e),await uJ.remove(e)}catch(t){throw xn.error(`Error removing files in ${e} -- ${t}`),t}}a(VAe,"removeDir");function KAe(e,t){if(to(e)){xn.info("Invalid current version sent as parameter.");return}if(to(t)){xn.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("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(KAe,"compareVersions");function YAe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(YAe,"isCompatibleDataVersion");function WAe(e){if(_s(e))return e;let t=String(e);return t==="."?yr.UNICODE_PERIOD:t===".."?yr.UNICODE_PERIOD+yr.UNICODE_PERIOD:t.replace(yr.FORWARD_SLASH_REGEX,yr.UNICODE_FORWARD_SLASH)}a(WAe,"escapeRawValue");function zAe(e){if(_s(e))return e;let t=String(e);return t===yr.UNICODE_PERIOD?".":t===yr.UNICODE_PERIOD+yr.UNICODE_PERIOD?"..":String(e).replace(yr.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(zAe,"unescapeValue");function jAe(e,t){if(_s(e))return xn.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+NA.EOL}!to(n)&&n[0]===";"?r+=" "+n+s+NA.EOL:to(n)||(r+=n+"="+s+NA.EOL)}catch{xn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(jAe,"stringifyProps");function SJ(){let e;try{e=NA.homedir()}catch{e=process.env.HOME}return e}a(SJ,"getHomeDir");function JAe(){let e=gc.join(SJ(),yr.HDB_HOME_DIR_NAME,yr.BOOT_PROPS_FILE_NAME);return pJ.existsSync(e)||(e=gc.join(__dirname,"../","hdb_boot_properties.file")),e}a(JAe,"getPropsFilePath");function QAe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(QAe,"timeoutPromise");async function XAe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=yAe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(XAe,"isPortTaken");function ZAe(e){try{return yr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){xn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(ZAe,"isClusterOperation");function eRe(e,t){let r=(Le(),D(rt)).getDatabases();if(!r[e])return IA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return IA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(eRe,"checkGlobalSchemaTable");function tRe(e,t){if(_s(t)){xn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(_s(e)||to(e)){xn.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){xn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){xn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(tRe,"getClusterUser");function rRe(){dJ.parsePromise=function(e,t,r){return new Promise(function(n,s){dJ.parse(e,{header:!0,transformHeader:TJ,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(rRe,"promisifyPapaParse");function TJ(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(TJ,"removeBOM");function nRe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;xn.info(`Got cluster status event response: ${wAe(s)}`);try{i.cancel()}catch{xn.error("Error trying to cancel timeout.")}n(s)})})}a(nRe,"createEventPromise");async function sRe(e){let t=!0,r=0;do await hJ(LAe*r++),(await NAe.findPs(e)).length>0&&(t=!1);while(t&&r<MAe);if(t)throw new Error(`process ${e} was not started`)}a(sRe,"checkProcessRunning");function iRe(e,t){let r=AJ(e);if(r)return r;let n=RJ(e,t);if(n)return n}a(iRe,"checkSchemaTableExist");function AJ(e){let{getDatabases:t}=(Le(),D(rt));if(!t()[e])return IA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(AJ,"checkSchemaExists");function RJ(e,t){let{getDatabases:r}=(Le(),D(rt));if(!r()[e][t])return IA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(RJ,"checkTableExists");function oRe(){let e=wA().utc().add(1,"d").startOf("d").unix(),t=wA().utc().unix();return e-t}a(oRe,"getStartOfTomorrowInSeconds");function aRe(){return wA().utc().format("DD-MM-YYYY")}a(aRe,"getLimitKey");function cRe(e){try{let t=new bAe(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){xn.error("Got an error back ticking items."),xn.error(t)}}a(cRe,"backtickASTSchemaItems");function lRe(e){return[e]}a(lRe,"createForkArgs");function uRe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(uRe,"autoCastBoolean");function dRe(e,t){let{getDatabases:r}=(Le(),D(rt)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(dRe,"getTableHashAttribute");function fRe(e){let{getDatabases:t}=(Le(),D(rt));return t()[e]!==void 0}a(fRe,"doesSchemaExist");function _Re(e,t){let{getDatabases:r}=(Le(),D(rt));return r()[e]?.[t]!==void 0}a(_Re,"doesTableExist");function pRe(e){try{return JSON.stringify(e)}catch{return e}}a(pRe,"stringifyObj");function hRe(e){let t=wA.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(hRe,"ms_to_time");function mRe(e,t){let r=gc.basename(e,gc.extname(e));return gc.join(gc.dirname(e),r+t)}a(mRe,"changeExtension");function YP(){if(process.env[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=IAe(process.argv);if(e[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(YP,"getEnvCliRootPath");var VP;function ERe(){if(VP)return VP;let e=YP();if(YP()&&pJ.pathExistsSync(gc.join(e,yr.HDB_CONFIG_FILE)))return VP=!0,!0}a(ERe,"noBootFile");function gRe(e,t){let r;return e.protocol==="http:"?r=PAe:r=CAe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(gRe,"httpRequest");function SRe(e){if(!e.schema&&!e.database){e.schema=yr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(SRe,"transformReq");function TRe(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(TRe,"convertToMS")});var le=P((IJ,CJ)=>{"use strict";var WP=require("fs-extra"),tu=require("path"),bJ=require("os"),ARe=require("properties-reader"),Vh=z(),$h=oe(),ve=(k(),D(q)),CA=At(),RRe="Error initializing environment manager",PA="BOOT_PROPS_FILE_PATH",OJ=!1,yRe={[ve.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},ia={};Object.assign(IJ,CJ.exports={BOOT_PROPS_FILE_PATH:PA,getHdbBasePath:bRe,setHdbBasePath:ORe,get:NJ,initSync:wRe,setProperty:ze,initTestEnvironment:CRe,setCloneVar:IRe});function bRe(){return ia[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(bRe,"getHdbBasePath");function ORe(e){ia[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(ORe,"setHdbBasePath");function NJ(e){let t=CA.getConfigValue(e);return t===void 0?ia[e]:t}a(NJ,"get");function ze(e,t){yRe[e]&&(ia[e]=t),CA.updateConfigObject(e,t)}a(ze,"setProperty");function NRe(){let e;try{e=$h.getPropsFilePath(),WP.accessSync(e,WP.constants.F_OK|WP.constants.R_OK),OJ=!0;let t=ARe(e);return ia[ve.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ve.HDB_SETTINGS_NAMES.INSTALL_USER),ia[ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),ia[PA]=e,!0}catch{return Vh.trace(`Environment manager found no properties file at ${e}`),!1}}a(NRe,"doesPropFileExist");function wRe(e=!1){try{((OJ||NRe()||$h.noBootFile())&&!wJ||e)&&(CA.initConfig(e),ia[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=CA.getConfigValue(ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Vh.error(RRe),Vh.error(t),console.error(t),process.exit(1)}}a(wRe,"initSync");var wJ=!1;function IRe(e){wJ=e}a(IRe,"setCloneVar");function CRe(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,l=tu.join(__dirname,"../../","unitTests");ia[PA]=tu.join(l,"hdb_boot_properties.file"),ze(ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,tu.join(l,"settings.test")),ze(ve.HDB_SETTINGS_NAMES.INSTALL_USER,bJ.userInfo()?bJ.userInfo().username:void 0),ze(ve.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ze(ve.HDB_SETTINGS_NAMES.LOG_PATH_KEY,tu.join(l,"envDir","log")),ze(ve.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),ze(ve.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),ze(ve.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),ze(ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,tu.join(l,"envDir")),ze(ve.CONFIG_PARAMS.STORAGE_PATH,tu.join(l,"envDir")),s&&(ze(ve.CONFIG_PARAMS.HTTP_SECUREPORT,NJ(ve.CONFIG_PARAMS.HTTP_PORT)),ze(ve.CONFIG_PARAMS.HTTP_PORT,null)),ze(ve.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),ze(ve.CONFIG_PARAMS.HTTP_PORT,9926),ze(ve.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),ze(ve.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),ze(ve.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,$h.isEmpty(i)?!1:i),ze(ve.CONFIG_PARAMS.HTTP_CORS,$h.isEmpty(i)?!1:i),ze(ve.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),ze(ve.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),ze(ve.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),ze(ve.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),ze(ve.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,tu.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ze(ve.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,$h.isEmpty(c)?!1:c),o&&(ze("CORS_ACCESSLIST",o),ze(ve.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(ze(ve.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),ze(ve.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(ze(ve.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),ze(ve.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(ze(ve.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),ze(ve.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${PA}. Please check your boot props and settings files`;Vh.fatal(r),Vh.error(t)}}a(CRe,"initTestEnvironment")});var vJ=P((bxe,MJ)=>{"use strict";var LA=le();LA.initSync();var DA=(k(),D(q)),{httpRequest:PRe}=oe(),LJ=require("path"),PJ=require("fs-extra"),DRe=require("yaml"),{packageDirectory:LRe}=(Qw(),D(Jw)),{encode:MRe}=require("cbor-x"),vRe=["describe_table","describe_all","describe_database","list_users","list_roles","drop_role","add_user","alter_user","drop_user","restart_service","restart","create_database","drop_database","create_table","drop_table","create_attribute","drop_attribute","search_by_id","insert","update","upsert","delete","search_by_value","csv_file_load","csv_url_load","cluster_get_routes","cluster_network","cluster_status","remove_node","add_component","deploy_component","package_component","drop_component","get_components","get_component_file","set_component_file","registration_info","get_fingerprint","set_license","get_job","search_jobs_by_start_date","read_log","read_transaction_log","read_audit_log","delete_transaction_logs_before","purge_stream","delete_records_before","install_node_modules","set_configuration","get_configuration","create_authentication_tokens","refresh_operation_token","system_information","sql","create_csr","sign_certificate","list_certificates","add_certificate","remove_certificate","add_ssh_key","update_ssh_key","delete_ssh_key","list_ssh_keys","set_ssh_known_hosts","get_ssh_known_hosts"],DJ={deploy:"deploy_component",package:"package_component"};MJ.exports={cliOperations:BRe,buildRequest:xRe};var URe={deploy_component:a(async e=>{if(e.package)return;let t=process.cwd();e.payload=await LRe(t,{skip_node_modules:!0,...e}),e.cborEncode=!0,e.project||(e.project=LJ.basename(t))},"deploy_component")};function xRe(){let e={};for(let t of process.argv.slice(2))if(vRe.includes(t))e.operation=t;else if(DJ.hasOwnProperty(t))e.operation=DJ[t];else if(t.includes("=")){let[r,...n]=t.split("=");n=n.join("=");try{n=JSON.parse(n)}catch{}e[r]=n}return e}a(xRe,"buildRequest");async function BRe(e){e.target||(e.target=process.env.CLI_TARGET);let t;if(e.target){try{t=new URL(e.target)}catch(r){try{t=new URL(`https://${e.target}:9925`)}catch{throw r}}t={protocol:t.protocol,hostname:t.hostname,port:t.port,username:e.username||t.username||process.env.CLI_TARGET_USERNAME,password:e.password||t.password||process.env.CLI_TARGET_PASSWORD,rejectUnauthorized:e.rejectUnauthorized}}else PJ.existsSync(LJ.join(LA.get(DA.CONFIG_PARAMS.ROOTPATH),DA.HDB_PID_FILE))||(console.error("HarperDB must be running to perform this operation"),process.exit()),PJ.existsSync(LA.get(DA.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))||(console.error("No domain socket found, unable to perform this operation"),process.exit());await URe[e.operation]?.(e);try{let r=t??{protocol:"http:",socketPath:LA.get(DA.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)};r.method="POST",r.headers={"Content-Type":"application/json"},t?.username&&(r.headers.Authorization=`Basic ${Buffer.from(`${t.username}:${t.password}`).toString("base64")}`),e.cborEncode&&(r.headers["Content-Type"]="application/cbor",e=MRe(e));let n=await PRe(r,e),s;try{s=JSON.parse(n.body)}catch{s={status:n.statusCode+" "+(n.statusMessage||"Unknown"),body:n.body}}e.json?console.log(JSON.stringify(s,null,2)):console.log(DRe.stringify(s).trim())}catch(r){let n="Error: ";if(r?.response?.data?.error)n+=r.response.data.error;else if(r?.response?.data)n+=r?.response?.data;else return console.error(r);console.error(n)}}a(BRe,"cliOperations")});var BJ=P((Nxe,xJ)=>{"use strict";var UJ=require("semver/functions/major"),{packageJson:HRe}=nt(),zP=process.versions&&process.versions.node?process.versions.node:void 0;xJ.exports=kRe;function kRe(){let e=HRe.engines["minimum-node"];if(zP&&UJ(zP)<UJ(e))return{error:`The minimum version of Node.js HarperDB supports is: ${e}, the currently installed Node.js version is: ${zP}. Please install a version of Node.js that is withing the defined range.`}}a(kRe,"checkNodeVersion")});var tD=P((Cxe,s2)=>{"use strict";var HJ=require("os"),MA=require("https"),kJ=require("http"),Gt=require("fs-extra"),FJ=require("yaml"),{pipeline:GJ}=require("stream/promises"),{createWriteStream:vA,ensureDir:Kh,writeFileSync:qJ}=require("fs-extra"),{join:Ks}=require("path"),YJ=require("lodash"),FRe=require("minimist"),oa=require("path"),GRe=require("node:crypto"),qRe=require("properties-reader"),Vs=le(),$Re=vo(),XP=z(),UA=At(),{restart:VRe}=ja(),xA=oe(),KRe=da(),YRe=bs(),{main:BA,launch:WRe}=Jd(),{install:WJ,updateConfigEnv:zRe,setIgnoreExisting:kA}=MT(),zJ=AC(),un=(k(),D(q)),{packageJson:jRe}=nt(),JRe=Eh(),{sendOperationToNode:QP}=(es(),D(Do)),{updateConfigCert:QRe}=rs(),{restartWorkers:XRe}=tt(),{databases:ZRe}=(Le(),D(rt)),{SYSTEM_TABLE_NAMES:jP,SYSTEM_SCHEMA_NAME:Ixe,CONFIG_PARAMS:Yh,OPERATIONS_ENUM:ms}=un,eye=1e4,tye="clone-node-config.yaml",jJ=[jP.ROLE_TABLE_NAME,jP.USER_TABLE_NAME,jP.NODE_TABLE_NAME],rye={clustering_nodename:!0,clustering_leafserver_streams_path:!0,clustering_tls_certificate:!0,clustering_tls_privatekey:!0,clustering_tls_certificateauthority:!0,logging_file:!0,logging_root:!0,logging_rotation_path:!0,operationsapi_network_domainsocket:!0,operationsapi_tls_certificate:!0,operationsapi_tls_privatekey:!0,operationsapi_tls_certificateauthority:!0,rootpath:!0,storage_path:!0,storage_audit_path:!0,databases:!0,mqtt_network_mtls_certificateauthority:!0,componentsroot:!0,tls_certificate:!0,tls_privatekey:!0,tls_certificateauthority:!0,replication_hostname:!0,replication_url:!0,cloned:!0},qr={HDB_LEADER_USERNAME:"HDB_LEADER_USERNAME",HDB_LEADER_PASSWORD:"HDB_LEADER_PASSWORD",HDB_LEADER_URL:"HDB_LEADER_URL",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",HDB_CLONE_OVERTOP:"HDB_CLONE_OVERTOP",CLONE_KEYS:"CLONE_KEYS",CLONE_USING_WS:"CLONE_USING_WS",NO_START:"NO_START"},ca=FRe(process.argv),_f=ca[qr.HDB_LEADER_USERNAME]??process.env[qr.HDB_LEADER_USERNAME],pf=ca[qr.HDB_LEADER_PASSWORD]??process.env[qr.HDB_LEADER_PASSWORD],nu=ca[qr.HDB_LEADER_URL]??process.env[qr.HDB_LEADER_URL],aa=ca[qr.REPLICATION_HOSTNAME]??process.env[qr.REPLICATION_HOSTNAME],JJ,QJ;aa&&([JJ,QJ]=aa.split(":"));var ZP=(ca[qr.HDB_CLONE_OVERTOP]??process.env[qr.HDB_CLONE_OVERTOP])==="true",XJ=ca[Yh.CLONED.toUpperCase()]??process.env[Yh.CLONED.toUpperCase()],nye=ca[qr.CLONE_KEYS]!=="false"&&process.env[qr.CLONE_KEYS]!=="false",ZJ=(ca[qr.CLONE_USING_WS]??process.env[qr.CLONE_USING_WS])==="true",e2=(ca[qr.NO_START]??process.env[qr.NO_START])==="true",hs,Sc={},$J,VJ,ru={},ln,Lt,$s,ro,su=!1,eD=!1,ps,hf;s2.exports=a(async function(t=!1,r=!1){if(console.info(`Starting clone node from leader node: ${nu}`),delete process.env.HDB_LEADER_URL,Lt=xA.getEnvCliRootPath(),!Lt)try{let i=Ks(HJ.homedir(),un.HDB_HOME_DIR_NAME,un.BOOT_PROPS_FILE_NAME);if(await Gt.pathExists(i)){let o=qRe(i);Lt=oa.parse(o.get(un.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)).dir}}catch{throw new Error("There was an error setting the clone default root path. Please set ROOTPATH using an environment or CLI variable.")}Lt?await Gt.pathExists(Lt)?console.log(`Existing HarperDB install found at ${Lt}. Clone node will only clone items that do not already exist on clone.`):(console.log(`No HarperDB install found at ${Lt} starting fresh clone`),su=!0):(console.log("No HarperDB install found, starting fresh clone"),su=!0),Lt||(Lt=Ks(HJ.homedir(),un.HDB_ROOT_DIR_NAME),console.log("Using default root path",Lt));let n;try{n=Ks(Lt,tye),hs=FJ.parseDocument(await Gt.readFile(n,"utf8"),{simpleKeys:!0}).toJSON(),console.log("Clone config file found")}catch{}let s=Ks(Lt,un.HDB_CONFIG_FILE);if(await Gt.pathExists(s))try{$J=FJ.parseDocument(await Gt.readFile(s,"utf8"),{simpleKeys:!0}).toJSON(),Sc=UA.flattenConfig($J)}catch(i){console.error("Error reading existing harperdb-config.yaml on clone",i)}if(aa){let i=new URL(nu);hf=`${i.protocol==="https:"?"wss://":"ws://"}${i.hostname}:${QJ||9933}`}if(ZJ){await sye();return}if(Sc?.cloned&&XJ!=="false")return console.log("Instance marked as cloned, clone will not run"),Vs.setCloneVar(!1),Vs.initSync(),BA();ln=await HA({operation:ms.DESCRIBE_ALL}),await r2(),Vs.setCloneVar(!1),Vs.setHdbBasePath(Lt),Gt.ensureDir(Vs.get(un.CONFIG_PARAMS.LOGGING_ROOT)),XP.initLogSettings(),await oye(),eD||await aye(),await uye(t,r),aa&&(await fye(),await t2()),console.info(`
|
|
133
|
+
`;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,Dh?.(Te),jl.default.error(Te),t.set(_.path||"/",new Sa(Te)),of.set(n?d:(0,gt.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,gt.basename)(e)}' due to: ${S.message}`,Dh?.(S),((0,Lh.getWorkerIndex)()===0?console:jl.default).error(S),t.set(_.path||"/",new Sa(S),null,!0),of.set(n?d:(0,gt.basename)(e),S.message)}}if(oA=u,sf.isMainThread&&!uj&&i&&(0,Lh.watchDir)(e,async()=>dj()),c.extensionModule){let d=await QE((0,gt.join)(e,c.extensionModule));return iA.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;Dh?.(new Error(d)),((0,Lh.getWorkerIndex)()===0?console:jl.default).error(d),of.set((0,gt.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Dh?.(c),t.set("",new Sa(c))}}var lt,gt,sf,mP,TP,AP,cj,Lh,jl,lj,EP,uTe,cA,dTe,pP,gP,uj,hP,of,fTe,SP,aj,iA,Dh,oA,pTe,Jp=be(()=>{lt=require("fs"),gt=require("path"),sf=require("worker_threads"),mP=require("yaml"),TP=M(le()),AP=M(nt());k();GL();yM();XB();rH();nH();GH();TY();NY();IY();cj=M(require("fast-glob")),Lh=M(tt()),jl=M(z());uO();Lr();lj=M(he());Le();kC();EP=M(le()),uTe=M(Fz());HS();zz();es();oj();cA=M(At());ng();bR();({readFile:dTe}=lt.promises),pP=(0,cA.resolvePath)(TP.get(U.COMPONENTSROOT)),gP=new Map,of=new Map;a(dj,"loadComponentDirectories");fTe={REST:ig,rest:ig,graphql:qR,graphqlSchema:wR,roles:lO,jsResource:fO,fastifyRoutes:ZI,login:pO,static:eC,operationsApi:uTe,customFunctions:{},http:{},clustering:aP,replication:Do,authentication:qp,mqtt:_P,loadEnv:tC},SP={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(SP,"static",{value:{files:"web/**"}});aj=[],iA=new Map;a(_Te,"setErrorReporter");pTe=a(()=>oA,"getComponentName");a(hTe,"symlinkHarperModule");a(aA,"loadComponent")});var YT=P((D0e,_j)=>{var{isMainThread:fj}=require("worker_threads"),{getTables:mTe,getDatabases:C0e,table:P0e}=(Le(),D(rt)),{loadComponentDirectories:ETe,loadComponent:gTe}=(Jp(),D(jp)),{resetResources:STe}=(Au(),D(HL)),TTe=jw(),ATe=At(),{dirname:RTe}=require("path"),{getConnection:yTe}=sr(),bTe=le(),{CONFIG_PARAMS:OTe}=(k(),D(q)),{loadCertificates:NTe}=rs(),RP=new Map;async function wTe(e=!1){!fj&&bTe.get(OTe.CLUSTERING_ENABLED)&&yTe();try{fj&&await TTe()}catch(n){console.error(n)}let t=STe();mTe(),t.isWorker=e,await NTe(),await gTe(RTe(ATe.getConfigFilePath()),t,"hdb",!0,RP),await ETe(RP,t);let r=[];for(let[n]of RP)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(wTe,"loadRootComponents");_j.exports.loadRootComponents=wTe});var tt=P((M0e,Ti)=>{"use strict";sm();var{Worker:ITe,MessageChannel:CTe,parentPort:Zi,isMainThread:wP,threadId:PTe,workerData:eo}=require("worker_threads"),{PACKAGE_ROOT:DTe}=nt(),{join:Ej,isAbsolute:LTe,extname:MTe}=require("path"),{server:gj}=(Lr(),D(Su)),{watch:vTe,readdir:UTe}=require("fs/promises"),{totalmem:pj}=require("os"),af=(k(),D(q)),Sj=le(),Si=z(),{randomBytes:xTe}=require("crypto"),{_assignPackageExport:BTe}=Ai(),hj=1024*1024,pc=[],Fs=[],HTe=50,IP=1e4,kTe="restart",Tj="request_thread_info",Aj="resource_report",Rj="thread_info",yj="added-port",FTe="ack",yP;BTe("threads",Fs);Ti.exports={startWorker:bP,restartWorkers:PP,shutdownWorkers:KTe,workers:pc,setMonitorListener:ZTe,onMessageFromWorkers:YTe,onMessageByType:Pj,broadcast:zTe,broadcastWithAcknowledgement:JTe,setChildListenerByType:VTe,getWorkerIndex:bj,getWorkerCount:Oj,getTicketKeys:wj,setMainIsWorker:qTe,setTerminateTimeout:GTe,restartNumber:eo?.restartNumber||1};Fs.onMessageByType=Pj;Fs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Fs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Ti.exports.whenThreadsStarted=new Promise(e=>{Ti.exports.threadsHaveStarted=e});var CP;function GTe(e){IP=e}a(GTe,"setTerminateTimeout");function bj(){return eo?eo.workerIndex:CP?0:void 0}a(bj,"getWorkerIndex");function Oj(){return eo?eo.workerCount:CP?1:void 0}a(Oj,"getWorkerCount");function qTe(e){CP=e,Ti.exports.threadsHaveStarted()}a(qTe,"setMainIsWorker");var Nj=1,lA;function wj(){return lA||(lA=wP?xTe(48):eo.ticketKeys,lA)}a(wj,"getTicketKeys");Object.defineProperty(gj,"workerIndex",{get(){return bj()}});Object.defineProperty(gj,"workerCount",{get(){return Oj()}});var Ij={[Tj](e,t){QTe(t)},[Aj](e,t){XTe(t,e)}};function bP(e,t={}){let r=process.constrainedMemory?.()||pj();r=Math.min(r,pj(),2e4*hj);let n=Sj.get(af.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/hj/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Fs){let u=new CTe;u.existingPort=l,i.push(u),o.push(u.port2)}MTe(e)||(e+=".js");let c=new ITe(LTe(e)?e:Ej(DTe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Nj=t.threadCount,name:t.name,restartNumber:Ti.exports.restartNumber,ticketKeys:wj()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:yj,port:l,threadId:c.threadId},[l]);return dA(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>bP(e,t),c.on("error",l=>{Si.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{pc.splice(pc.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<HTe?(t.unexpectedRestarts=c.unexpectedRestarts+1,bP(e,t)):Si.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{Ij[l.type]?.(l,c)}),pc.push(c),tAe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(bP,"startWorker");var $Te=[af.THREAD_TYPES.HTTP];async function PP(e=null,t=Math.max(Nj>3,1),r=!0){if(wP){try{process.chdir(process.cwd())}catch(o){Si.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=YT();await o()}Ti.exports.restartNumber++,t<1&&(t=t*pc.length);let n=[],s=[];for(let o of pc.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Si.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ti.exports.restartNumber,type:af.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=$Te.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{Si.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},IP*2).unref();o.on("exit",()=>{clearTimeout(f),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),u()})});if(n.push(l),c&&r){let u=o.startCopy(),f=new Promise(d=>{let _=a(p=>{p.type===af.ITC_EVENT_TYPES.CHILD_STARTED&&(Si.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");Si.trace("Waiting for worker to start",u.threadId),u.on("message",_)});s.push(f),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}=ja();r&&(e==="http"||!e)&&Sj.get(af.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Zi.postMessage({type:kTe,workerType:e})}a(PP,"restartWorkers");function VTe(e,t){Ij[e]=t}a(VTe,"setChildListenerByType");function KTe(e){return PP(e,1/0,!1)}a(KTe,"shutdownWorkers");var Cj=[];function YTe(e){Cj.push(e)}a(YTe,"onMessageFromWorkers");var OP=new Map;function Pj(e,t){let r=OP.get(e);r||OP.set(e,r=[]),r.push(t)}a(Pj,"onMessageByType");var WTe=10;async function zTe(e,t){let r=0;for(let n of Fs)try{n.postMessage(e),r++>WTe&&(r=0,await new Promise(setImmediate))}catch(s){Si.error("Unable to send message to worker",s)}t&&Lj(e,null)}a(zTe,"broadcast");var uA=new Map,jTe=1;function JTe(e){return new Promise(t=>{let r=0;for(let n of Fs)try{let s=jTe++,i=a(()=>{uA.delete(s),--r===0&&t(),n!==Zi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,uA.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of uA)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Si.error("Unable to send message to worker",s)}r===0&&t()})}a(JTe,"broadcastWithAcknowledgement");function QTe(e){e.postMessage({type:Rj,workers:Dj()})}a(QTe,"sendThreadInfo");function Dj(){let e=Date.now();return pc.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(Dj,"getChildWorkerInfo");function XTe(e,t){e.resources=t,e.resources.updated=Date.now()}a(XTe,"recordResourceReport");var NP;function ZTe(e){NP=e}a(ZTe,"setMonitorListener");var eAe=1e3,mj=!1;function tAe(){mj||(mj=!0,setInterval(()=>{for(let e of pc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}NP&&NP()},eAe).unref())}a(tAe,"startMonitoring");var rAe=1e3;if(Zi&&eo?.addPorts){dA(Zi);for(let e=0,t=eo.addPorts.length;e<t;e++){let r=eo.addPorts[e];r.threadId=eo.addThreadIds[e],dA(r)}setInterval(()=>{let e=process.memoryUsage();Zi.postMessage({type:Aj,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},rAe).unref(),yP=a(()=>new Promise((e,t)=>{Zi.on("message",r),Zi.postMessage({type:Tj});function r(n){n.type===Rj&&(Zi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else yP=Dj;Ti.exports.getThreadInfo=yP;function dA(e,t){Fs.push(e),e.on("message",r=>{if(r.type===yj)r.port.threadId=r.threadId,dA(r.port);else if(r.type===FTe){let n=uA.get(r.id);n&&n()}else Lj(r,e)}).on("close",()=>{Fs.splice(Fs.indexOf(e),1)}).on("exit",()=>{Fs.splice(Fs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(dA,"addPort");function Lj(e,t){for(let n of Cj)n(e,t);let r=OP.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){Si.error(s)}}a(Lj,"notifyMessageListeners");if(wP){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await UTe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Ej(s,o.name));try{for await(let{filename:o}of vTe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await PP(),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");Ti.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Zi.on("message",async e=>{let{type:t}=e;t===af.ITC_EVENT_TYPES.SHUTDOWN&&(Ti.exports.restartNumber=e.restartNumber,Zi.unref(),setTimeout(()=>{Si.warn("Thread did not voluntarily terminate",PTe),process.exit(0)},IP).unref())})});var EB={};Ue(EB,{ACTION_32_BIT:()=>Jm,ACTION_64_BIT:()=>iAe,AUDIT_STORE_OPTIONS:()=>Bp,Decoder:()=>Sl,HAS_BLOBS:()=>An,HAS_CURRENT_RESIDENCY_ID:()=>kc,HAS_EXPIRATION_EXTENDED_TYPE:()=>n_,HAS_ORIGINATING_OPERATION:()=>r_,HAS_PREVIOUS_RESIDENCY_ID:()=>Fc,REMOTE_SEQUENCE_UPDATE:()=>Hg,createAuditEntry:()=>Nu,getLastRemoved:()=>ON,openAuditStore:()=>pA,readAuditEntry:()=>Nt,removeAuditEntry:()=>hA,setAuditRetention:()=>sAe,transactionKeyEncoder:()=>Gj});function pA(e){let t=e.auditStore=e.openDB(DP.AUDIT_STORE_NAME,{create:!1,...Bp});t||(t=e.auditStore=e.openDB(DP.AUDIT_STORE_NAME,Bp),vj(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,f){return r[l]=f,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,o=MP;Rh(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(o=l),clearTimeout(n);let u=new Promise(f=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let d=0,_,p;try{for(let{key:h,value:S}of t.getRange({start:1,snapshot:!1,end:Date.now()-LP/(1+i*i)})){try{_=hA(t,h,S)}catch(g){cf.warn("Error removing audit entry",g)}if(p=h,await new Promise(setImmediate),++d>=nAe){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,LP/10):(vj(t,p),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,vh.getWorkerIndex)()===(0,vh.getWorkerCount)()-1&&c(),(0,vh.getWorkerIndex)()===0&&!Mj)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(Mj=!0,cf.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function hA(e,t,r){let n=oAe(r),s;if(n&An){s=Nt(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&Mc(()=>Ta(s.getValue(i)),i.rootStore)}if((n&15)===vP){s=s||Nt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId)?.version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function vj(e,t){UP[0]=t,e.put(Symbol.for("last-removed"),qj)}function ON(e){let t=e.get(Symbol.for("last-removed"));if(t)return qj.set(t),UP[0]}function sAe(e,t=MP){LP=e,MP=t}function Nu(e,t,r,n,s,i,o,c,l,u,f,d,_){let p=$j[o];if(!p)throw new Error(`Invalid audit entry type ${o}`);let h=1;if(n&&(n>1?hc.setFloat64(0,n):Gs.set(XR),h=9),l){if(l&255)throw new Error("Illegal extended type");h+=3}R(s),R(t),g(r),hc.setFloat64(h,e),h+=8,l&kc&&R(u),l&Fc&&R(f),l&n_&&(hc.setFloat64(h,d),h+=8),l&r_&&R(Vj[_]),i?g(i):Gs[h++]=0,l?hc.setUint32(n?8:0,p|l|3221225472):Gs[n?8:0]=p;let S=Gs.subarray(0,h);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=h;h+=1,h=(0,Jl.writeKey)(E,Gs,h);let w=h-T-1;w>127?w>16383?(cf.error("Key or username was too large for audit entry",E),h=T+1,Gs[T]=0):(Gs.copyWithin(T+2,T+1,h),hc.setUint16(T,w|32768),h++):Gs[T]=w}function R(E){E<128?Gs[h++]=E:E<16384?(hc.setUint16(h,E|32768),h+=2):E<1056964608?(hc.setUint32(h,E|3221225472),h+=4):(Gs[h]=255,hc.setUint32(h+1,E),h+=5)}}function oAe(e){let t=0;e[0]==66&&(t=8);let r=e[t];if(r<128)return r;let n=e.dataView||(e.dataView=new Sl(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Sl(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),o=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,f=n.position+=l,d=n.readFloat64(),_,p,h,S;if(i&kc&&(_=n.readInt()),i&Fc&&(p=n.readInt()),i&n_&&(h=n.readFloat64()),i&r_){let T=n.readInt();S=Vj[T]}l=n.readInt();let g=n.position,R=n.position+=l,E;return{type:$j[i&7],tableId:c,nodeId:o,get recordId(){return(0,Jl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return R>g?(0,Jl.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&fA||i&Mh&&!w)return E||(E=Mc(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&Mh&&v)return zb(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(fA|Mh)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:p,expiresAt:h,originatingOperation:S}}catch(n){return cf.error("Reading audit entry error",n,e),{}}}var Jl,_A,DP,vh,Fj,cf,Gs,hc,Gj,Bp,LP,nAe,UP,qj,MP,Mj,fA,Mh,Uj,vP,xj,Bj,Hj,kj,Jm,iAe,Hg,kc,Fc,r_,n_,An,$j,Vj,Sl,mo=be(()=>{Jl=require("ordered-binary"),_A=M(le()),DP=M(Ut());k();vh=M(tt()),Fj=M(oe());wu();cf=M(z());HE();As();HT();(0,_A.initSync)();Gs=Buffer.alloc(2816),hc=new DataView(Gs.buffer,Gs.byteOffset,2816),Gj={writeKey(e,t,r){return e===t_?(t.set(t_,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Jl.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,Jl.readKey)(e,t,r)}},Bp={encoding:"binary",keyEncoder:Gj},LP=(0,Fj.convertToMS)((0,_A.get)(U.LOGGING_AUDITRETENTION))||86400*3,nAe=1e3,UP=new Float64Array(1),qj=new Uint8Array(UP.buffer),MP=1e4,Mj=!1;a(pA,"openAuditStore");a(hA,"removeAuditEntry");a(vj,"updateLastRemoved");a(ON,"getLastRemoved");a(sAe,"setAuditRetention");fA=16,Mh=32,Uj=1,vP=2,xj=3,Bj=4,Hj=5,kj=6,Jm=14,iAe=15,Hg=11,kc=512,Fc=1024,r_=2048,n_=4096,An=8192,$j={put:Uj|fA,[Uj]:"put",delete:vP,[vP]:"delete",message:xj|fA,[xj]:"message",invalidate:Bj|Mh,[Bj]:"invalidate",patch:Hj|Mh,[Hj]:"patch",relocate:kj,[kj]:"relocate"},Vj={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(Nu,"createAuditEntry");a(oAe,"readAction");a(Nt,"readAuditEntry");Sl=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t;return t=this.getUint8(this.position++),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(t){throw t.message=`Error reading float64: ${t.message} at position ${this.position}`,t}}}});function HP(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=Yj,aAe(e.primaryStore,e.auditStore)):(c=Kj,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{Wj(Kj[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let u=l[o];u||(u=l[o]=new Map,u.envs=l,u.tableId=o,u.store=e.primaryStore),t=Tu(t);let f=new BP(r);f.startTime=n;let d=u.get(t);return d?d.push(f):(u.set(t,d=[f]),d.tables=u,d.key=t),f.subscriptions=d,f}function Wj(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),zj(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Nt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Tu(c),u=0;do{let f=o.get(l);if(f){for(let _ of f)if(!(u>0&&!(_.includeDescendants&&!(_.onlyChildren&&u>1)))){if(_.startTime>=n){(0,xP.info)("omitting",c,_.startTime,n);continue}try{let p;_.supportsTransactions&&_.txnInProgress!==i.version&&(p=!0,_.txnInProgress||(r?r.push(_):r=[_]),_.txnInProgress=i.version),_.listener(c,i,n,p)}catch(p){console.error(p),(0,xP.info)(p)}}}if(l==null)break;let d=l.lastIndexOf?.("/",l.length-2);d!==l.length-1&&u++,d>-1?l=l.slice(0,d+1):l=null}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function aAe(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 l=Yj[s];if(!l)return;let u=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{Wj(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function zj(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function qF(e){return e.nextTransaction||(HP({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),zj(e)),e.nextTransaction}var xP,Kj,Yj,BP,NN=be(()=>{xP=M(z());pu();Au();mo();Kj=Object.create(null),Yj=Object.create(null);a(HP,"addSubscription");BP=class extends Fn{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;if(t){let 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(Wj,"notifyFromTransactionData");a(aAe,"listenToCommits");a(zj,"nextTransaction");a(qF,"whenNextTransaction")});var vI={};Ue(vI,{EVICTED:()=>Ea,INVALIDATED:()=>En,coerceType:()=>gA,makeTable:()=>TA,setServerUtilities:()=>hAe});function TA(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:f,sealed:d,splitSegments:_,replicate:p}=e,{expirationMS:h,evictionMS:S,audit:g,trackDeletes:R}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=ty(i,n,l),w,v,H={},$=Promise.resolve(),W,te,se;for(let K of E)(K.assignCreatedTime||K.name==="__createdtime__")&&(W=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(te=K),K.expiresAt&&(se=K),K.isPrimaryKey&&(H=K);let Y,ne=[],ue=[],ae=1,me=2,Te={},ye={},Qt=864e5,ut=0,br,Es,Hn,ou=!1,au,GA=new Map,qA=new Map,Mt,mf,Qh=Xl.get(U.REPLICATION_DATABASES);if(Array.isArray(Qh)){for(let K of Qh)if(K.name===c&&K.replicateTo>=0){mf=K.replicateTo;break}}let Xh=i.getRange({start:!1,end:!1}).constructor,Ef=10,Zh=6;g&&Af(),Rh(i.env.path,K=>{if(v)return so(K)});class Ce extends Yr{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=E;static replicate=p;static sealed=d;static splitSegments=_??!0;static createdTimeProperty=W;static updatedTimeProperty=te;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=f;static schemaDefined=u;static sourcedFrom(m,O){if(O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource)m.intermediateSource=!0,this.sources.unshift(m);else{if(this.sources.some(I=>!I.intermediateSource)){if(this.sources.some(I=>I.name===m.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(m)}v=v||m.get&&(!m.get.reliesOnPrototype||m.prototype.get),w=w||m.load;let A=a(I=>{let L=this.sources;if(L=L.filter(B=>B.intermediateSource&&B[I]&&(!B[I].reliesOnPrototype||B.prototype[I])),L.length>0)if(L.length===1){let B=L[0];return(N,x,G)=>{if(N?.source!==B)return B[I](x,G,N)}}else return(B,N,x)=>{let G=[];for(let j of L){if(B?.source===j)break;G.push(j[I](N,x,B))}return Promise.all(G)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1];y.intermediateSource&&(y={});let b=a(I=>{if(y[I]&&(!y[I].reliesOnPrototype||y.prototype[I]))return(L,B,N)=>{if(!L?.source)return y[I](B,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,B=a(async(N,x)=>{let G=N.value,j=N.table?Ve[c][N.table]:Ce;if(c===bf&&(N.table===fu.ROLE_TABLE_NAME||N.table===fu.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[j.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=m;let ie={residencyId:Rc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await j.getResource(N.id,x,ie);switch(N.finished&&await N.finished,N.type){case"put":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!0,ie);case"patch":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!1,ie);case"delete":return F._writeDelete(ie);case"publish":case"message":return F._writePublish(G,ie);case"invalidate":return F._writeInvalidate(G,ie);case"relocate":return F._writeRelocate(ie);default:xe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=m.subscribe;N&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Ql.getWorkerIndex)(),x):(0,Ql.getWorkerIndex)()===0,j=N&&G&&await m.subscribe?.(x);if(j){let ie;for await(let F of j)try{if(!(F.type==="transaction"?F.writes[0]:F)){xe.default.error?.("Bad subscription event",F);continue}if(F.source=m,F.type==="end_txn"){if(ie?.resolve(),F.localTime&&L!==F.localTime){if(F.remoteNodeIds?.length>0){let ce=[Symbol.for("seq"),F.remoteNodeIds[0]],ee=f.get(ce),J=ee?.nodes;J||(J=[]);for(let fe of F.remoteNodeIds.slice(1)){let Ae=J.find(De=>De.id===fe);J=J.filter(De=>De.id!==fe||De===Ae),Ae||(Ae={id:fe,seqId:0},J.push(Ae)),Ae.seqId=Math.max(ee?.seqId??1,F.localTime),fe===ie?.nodeId&&(Ae.lastTxnTime=F.timestamp)}let _e=Math.max(ee?.seqId??1,F.localTime);xe.default.trace?.("Received txn",c,new Date(_e),new Date(F.localTime),F.remoteNodeIds),f.put(ce,{seqId:_e,nodes:J})}L=F.localTime}F.onCommit&&ie?.committed.then(F.onCommit);continue}if(ie)if(F.beginTxn)ie.resolve();else{ie.write_promises.push(B(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=Ot(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(B(ee,F))}catch(J){throw J.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(F),J}return Promise.all(ce)}else if(F.type==="define_schema"){let ce=this.attributes.slice(0),ee;for(let J of F.attributes)ce.find(_e=>_e.name===J.name)||(ce.push(J),ee=!0);ee&&(dt({table:s,database:c,attributes:ce,origin:"cluster"}),xh.signalSchemaChange(new Bh.SchemaEventMsg(process.pid,$t.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[B(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):B(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>xh.signalUserChange(new Bh.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(qe){xe.default.error?.("error in subscription handler",qe)}}}catch(N){xe.default.error?.(N)}})(),this}static get isCaching(){return v}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(m,O,A){let y=super.getResource(m,O,A);if(m!=null){Cr(m);try{if(y.getRecord?.())return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!A?.async||i.cache?.get?.(m),C=Vr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return cu(m,O,{transaction:I,ensureLoaded:A?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Ir.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let B=lu(m,L,O,y);if(B)return C?.disregardReadTxn(),y.#i=!0,FP(B,N=>(Ce._updateResource(y,N),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return y}static _updateResource(m,O){m.#r=O,m.#e=O?.value??null,m.#n=O?.version}ensureLoaded(){let m=lu(this.getId(),this.#r,this.getContext());if(m)return this.#i=!0,FP(m,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let m=H?.type;if(m==="String"||m==="ID")return super.getNewId();if(!Mt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!EAe(i)||C.pid===process.pid)){let L=C.start,B=C.end;I=L;for(let N of i.getKeys({start:B,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;Mt=new BigInt64Array([BigInt(I)+1n]),Mt=new BigInt64Array(i.getUserSharedBuffer("id",Mt.buffer)),Mt.maxSafeId=C.end}let O=Number(Atomics.add(Mt,0,1n)),A=m==="Int"?512:1048576;if(O+A>=Mt.maxSafeId){let b=a(C=>{Mt.maxSafeId=O+(m==="Int"?1023:4194303);let I=(m==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=C?void 0:i.useReadTransaction(),B=Number(Mt[0]);for(let G of i.getKeys({start:B+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Mt.maxSafeId<I){if(N.end>Mt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,Mt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:Mt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Mt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(Mt,0,BigInt(G.start+1)),Mt.maxSafeId=G.end}},"updateEnd");O+A===Mt.maxSafeId?setImmediate(b):O+100>=Mt.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${m=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return O;function y(b){let C=(m==="Int"?Math.pow(2,31):Math.pow(2,49))-1,I=C/4,L,B,N=!1,x,G;do{x=Math.floor(Math.random()*C),G={start:x,end:x+(m==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let j of i.getKeys({start:x,limit:1,reverse:!0}))L=j;B=C;for(let j of i.getKeys({start:x+1,end:C,limit:1}))B=j;I*=.875,I<1e3&&!N&&(N=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${m==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,B,I))}while(!(I<B-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let j=i.getEntry(Symbol.for("id_allocation"));return(j?.version??null)==b?(xe.default.info?.("Allocated new id range",G),i.put(Symbol.for("id_allocation"),G,Date.now()),G):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...j.value})})}}static setTTLExpiration(m){if(typeof m=="number")h=m*1e3,S||(S=0);else if(m&&typeof m=="object")h=m.expiration*1e3,S=(m.eviction||0)*1e3,Qt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");Qt=Qt||(h+S)/4,so()}static getResidencyRecord(m){return f.get([Symbol.for("residency_by_id"),m])}static setResidency(m){Ce.getResidency=m&&((O,A)=>{try{return m(O,A)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(m){Ce.getResidencyById=m&&(O=>{try{return m(O)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(m,O){if(Ce.getResidencyById)return Ce.getResidencyById(m[t]);let A=mf;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(A=O.replicateTo)}if(A>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,A));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+A));let I=C+A-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(m=!0){g=m,m&&Af(),Ce.audit=m}static coerceId(m){return m===""?null:gA(m,H)}static async dropTable(){delete Ve[c][s];for(let m of i.getRange({versions:!0,snapshot:!1,lazy:!0}))m.metadataFlags&An&&m.value&&Ta(m.value);if(c===o){for(let m of E)f.remove(Ce.tableName+"/"+m.name),r[m.name]?.drop();f.remove(Ce.tableName+"/"),i.drop(),await f.committed}else console.log("legacy dropTable"),await i.close(),await EA.default.remove(data_path),await EA.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));xh.signalSchemaChange(new Bh.SchemaEventMsg(process.pid,$t.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this.isCollection)return this.search(m);if(this.getId()===null){if(m?.conditions||m?.size>0)return this.search(m);let O={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:E};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(A=>(O.recordCount=A.recordCount,O.estimatedRecordRange=A.estimatedRange,O)):O}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(m,O){let A=$r(m);if(A?.read){if(A.isSuperUser)return!0;let y=A.attribute_permissions,b=O?.select;if(y?.length>0||ou&&b){if(O||(O={}),b){let C=y?.length>0&&kP(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let B=Hn[L]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,m,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else O.select=y.filter(C=>C.read&&!Hn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(m,O){let A=$r(m);if(A?.update){let y=A.attribute_permissions;if(y?.length>0){let b=kP(y,"update");for(let C in O)if(!b[C])return!1;for(let C of y){let I=C.attribute_name;!C.update&&!(I in O)&&(O[I]=this.getProperty(I))}}return du(this.getContext())}}allowCreate(m,O){if(this.isCollection){let A=$r(m);if(A?.insert){let y=A.attribute_permissions;if(y?.length>0){let b=kP(y,"insert");for(let C in O)if(!b[C])return!1;return du(this.getContext())}else return du(this.getContext())}}else return this.allowUpdate(m,{})}allowDelete(m){return $r(m)?.delete&&du(this.getContext())}update(m,O){if(!Vr(this.getContext()))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m={...m}),this.#e={},this.#t=m):(y=this.#t,y&&(m=Object.assign(y,m)),this.#t=m)),this._writeUpdate(this.#t,O),this}addTo(m,O){if(typeof O=="number"||typeof O=="bigint")this.#s===Jj?this.set(m,(+this.getProperty(m)||0)+O):(this.#s||this.update(),this.set(m,new GE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(m){this.#t=m}setRecord(m){this.#e=m}invalidate(){this._writeInvalidate()}_writeInvalidate(m,O){let A=this.getContext(),y=this.getId();Cr(y),Vr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,A,y),beforeIntermediate:ye.invalidate?.bind(this,A,y),commit:a((C,I)=>{if(!(no(C,I,O?.nodeId)<=0)){m??=null;for(let L in r)m||(m={}),m[L]===void 0&&(m[L]=this.getProperty(L));xe.default.trace?.(`Invalidating entry id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,m,this.#r,C,En,g,{user:A?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(m){let O=this.getContext(),A=this.getId();Cr(A),Vr(this.getContext()).addWrite({key:A,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,A),beforeIntermediate:ye.relocate?.bind(this,O,A),commit:a((b,C)=>{if(no(b,C,m?.nodeId)<=0)return;let I=Ce.getResidencyRecord(m.residencyId),L=0,B=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)B||(B={}),B[x]=N(x);L=En}else B=N;xe.default.trace?.(`Relocating entry id: ${A}, timestamp: ${new Date(b).toISOString()}`),T(A,B,this.#r,b,L,g,{user:O.user,residencyId:m.residencyId,nodeId:m.nodeId,expiresAt:m.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(m,O){let A={previousResidency:this.getResidencyRecord(m.residencyId),isRelocation:!0},y=io(this.getResidency(O.value,A)),b;if(y){if(!y.includes(server.hostname))return!1;b=Rc(y)}let I=T(m.key,O.value,m,m.version,0,!0,{residencyId:b,expiresAt:O.expiresAt},"relocate",!1,null);return!0}static evict(m,O,A){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==A))){if(v){if(i.hasLock(m,b.version))return;let C;for(let I in r)C||(C={}),C[I]=O[I];if(C)return T(m,C,b,A,Ea,null,null,null,!0)}if(i.ifVersion(m,A,()=>{fn(m,O,null)}),g)return T(m,null,b,A,Ea,null,null,null,!0);Hc(i,b??i.getEntry(m),A)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,sJ.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,A){let y=this.getContext(),b=Vr(y),C=this.getId();Cr(C);let I=this.#r;this.#s=O?Jj:fAe;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(B=>{m||(m=this.#t),O||m&&kE(this.#t===m?this:m)?y?.source||(b.checkOverloaded(),this.validate(m,!O),te&&(m[te.name]=te.type==="Date"?new Date(B):te.type==="String"?new Date(B).toISOString():B),O&&(t&&m[t]!==C&&(m[t]=C),W&&(I?.value?m[W.name]=I?.value[W.name]:m[W.name]=W.type==="Date"?new Date(B):W.type==="String"?new Date(B).toISOString():B),m=nl(m))):b.removeWrite(L)},"validate"),before:O?Te.put?()=>Te.put(y,C,m):null:Te.patch?()=>Te.patch(y,C,m):Te.put?()=>Te.put(y,C,nl(this)):null,beforeIntermediate:O?ye.put?()=>ye.put(y,C,m):null:ye.patch?()=>ye.patch(y,C,m):ye.put?()=>ye.put(y,C,nl(this)):null,commit:a((B,N,x)=>{if(x){if(y&&N?.version>(y.lastModified||0)&&(y.lastModified=N.version),this.#r=N,N?.value&&N.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");O||(this.#e=N?.value??null)}this.#t=void 0,this.#n=B;let G=N?.value,j=m;this.#s=0;let ie=!1,F=no(B,N,A?.nodeId),qe;if(F<=0)if(g){let _e=N.localTime,fe=N.version;xe.default.trace?.("Applying CRDT update to record with id: ",C,"applying later update:",fe);let Ae=[];for(;_e>B||fe>=B&&_e>0;){let De=l.get(_e);if(!De)break;let we=Nt(De);if(fe=we.version,fe>=B){if(fe===B){if(F=no(B,{version:fe,localTime:_e},A?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),qe=m;else if(we.type==="put"||we.type==="delete")return}_e=we.previousLocalTime}Ae.sort((De,we)=>De.version-we.version);for(let De of Ae){let we=De.getValue(i);if(j=BE(j,we,O),xe.default.debug?.("Rebuilding update with future patch:",j),!j)return}}else{if(O)return;j=BE(j,G,O),xe.default.debug?.("Rebuilding update without audit:",j)}let Z;if(O?Z=j:(this.#e=G,Z=nl(this,j)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(A?.residencyId!=null)ce=A.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=io(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(qe??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=qe[fe]}ce=Rc(_e)}O||(qe=m);let ee=y?.expiresAt??(h?h+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(B).toISOString()}${ee?", expires at: "+new Date(ee).toISOString():""}${N?", replaces entry from: "+new Date(N.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(Z).slice(0,100)}catch{return""}})()),fn(C,G,Z);let J=O?"put":"patch";T(C,Z,N,B,ie?En:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:A?.nodeId,originatingOperation:y?.originatingOperation},J,!1,qe),y.expiresAt&&so()},"commit")};b.addWrite(L)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this.isCollection){for await(let O of this.search(m))(await Ce.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this.#e?this._writeDelete(m):!1}_writeDelete(m){let O=Vr(this.getContext()),A=this.getId();Cr(A);let y=this.getContext();return O.addWrite({key:A,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,A),beforeIntermediate:ye.delete?.bind(this,y,A),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!(no(b,C,m?.nodeId)<=0)&&(fn(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${A}, txn timestamp: ${new Date(b).toISOString()}`),g||R?(T(A,null,this.#r,b,0,g,{user:y?.user,nodeId:m?.nodeId},"delete"),g||so()):Hc(i,C))},"commit")}),!0}search(m){let O=this.getContext(),A=Vr(O);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this.getId()&&(y=[{attribute:null,comparator:Array.isArray(this.getId())?"prefix":"starts_with",value:this.getId()}].concat(y));let b,C={};function I(J,_e){let fe;switch(_e){case"and":case void 0:if(J.length<1)throw new Error('An "and" operator requires at least one condition');fe=!0;break;case"or":if(J.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+_e)}for(let Ae of J){if(Ae.conditions){Ae.conditions=I(Ae.conditions,Ae.operator);continue}let De=Ae[0]??Ae.attribute,we=De==null?H:Oi(E,De);if(we)(we.type||SR[Ae.comparator])&&(Ae[1]===void 0?Ae.value=B(Ae.value,we):Ae[1]=B(Ae[1],we));else if(De!=null)throw(0,Ir.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let hr=Ae.chainedConditions[0],Pr,Ws;if(hr.comparator==="gt"||hr.comparator==="greater_than"||hr.comparator==="ge"||hr.comparator==="greater_than_equal"?(Pr=Ae,Ws=hr):(Pr=hr,Ws=Ae),Pr.comparator!=="lt"&&Pr.comparator!=="less_than"&&Pr.comparator!=="le"&&Pr.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ws.comparator==="ge"||Ws.comparator==="greater_than_equal",bt=Pr.comparator==="le"||Pr.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(bt?"le":"lt"),Ae.value=[Ws.value,Pr.value]}else throw new Error("Multiple chained conditions are not currently supported")}return J}a(I,"prepareConditions");function L(J,_e){if(m.enforceExecutionOrder)return J;for(let fe of J)fe.conditions&&(fe.conditions=L(fe.conditions,fe.operator));return J.length>1&&_e!=="or"?(0,rJ.sortBy)(J,Om(Ce)):J}a(L,"orderConditions");function B(J,_e){return Array.isArray(J)?J.map(fe=>gA(fe,_e)):gA(J,_e)}a(B,"coerceTypedValues");let N=m.operator;(y.length>0||N)&&(y=I(y,N));let x=typeof m.sort=="object"&&m.sort,G;if(x&&N!=="or"){let J=x.attribute;if(J==null)throw new Ir.ClientError("Sort requires an attribute");if(b=y.find(_e=>gu(_e.attribute)===gu(J)),!b){let _e=Oi(E,J);if(!_e)throw(0,Ir.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not a defined attribute`,404);if(_e.indexed)b={attribute:J,comparator:"sort"},y.push(b);else if(y.length===0&&!m.allowFullScan)throw(0,Ir.handleHDBError)(new Error,`${Array.isArray(J)?J.join("."):J} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}y=L(y,N),x&&(b&&y[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&y.splice(y.indexOf(b),1),G=x));let j=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!j};let ie=A.useReadTxn(),F=TR(y,N,Ce,ie,m,O,(J,_e)=>Sf(J,j,O,ie,_e),C),qe=m.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(j,O,ie,C,qe,!0),ce=Ce.transformToOrderedSelect(F,j,G,ie,O,Z);function ee(J){return m.offset||m.limit!==void 0?J.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):J}return a(ee,"applyOffset"),G&&(ce=ee(ce)),ce.onDone=()=>{ce.onDone=null,A.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(j){let J=[];for(let _e of j)_e==="*"?J.push(...E.map(fe=>fe.name)):J.push(_e.name||_e);return J}return E.filter(J=>!J.computed&&!J.relationship).map(J=>J.name)},ce}static transformToOrderedSelect(m,O,A,y,b,C){let I=new Xh;if(A){m=Sf(m,O,y,b,null);let L;I.iterate=function(){let N,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,j=A.dbOrderedAttribute,ie,F,qe=!0;function Z(ee){let J=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=uu(fe,ee.attribute,y),we=uu(Ae,ee.attribute,y),hr=_e?(0,Zl.compareKeys)(we,De):(0,Zl.compareKeys)(De,we);return hr===0?J?.(fe,Ae)||0:hr}}a(Z,"createComparator");let ce=Z(A);return{async next(){let ee;if(N)if(ee=N.next(),ee.done){if(G)return I.onDone&&I.onDone(),ee}else return{value:await C.call(this,ee.value)};L=[],ie&&L.push(ie);do if(ee=await x.next(),ee.done){if(G=!0,L.length)break;return I.onDone&&I.onDone(),ee}else{let J=ee.value;if(J?.then&&(J=await J),j){let _e=uu(J,j,y);if(qe)qe=!1,F=_e;else if(_e!==F){F=_e,ie=J;break}}L.push(J)}while(!0);return A.isGrouped,L.sort(ce),N=L[Symbol.iterator](),ee=N.next(),ee.done?(I.onDone&&I.onDone(),ee):{value:await C.call(this,ee.value)}},return(){I.onDone&&I.onDone(),x.return()},throw(){I.onDone&&I.onDone(),x.throw()}}};let B=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],j;if(G.name===N.attribute[0]){for(j=G.sort||(G.sort={});j.next;)j=j.next;j.attribute=N.attribute.slice(1),j.descending=N.descending}else G===N.attribute[0]&&(O[x]=j={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&B(N.next)},"applySortingOnSelect");B(A)}else I.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),I=I.map(function(L){try{let B=C.call(this,L);return typeof B?.catch=="function"?B.catch(N=>{throw N.partialObject={[t]:L.key},N}):B}catch(B){throw B.partialObject={[t]:L.key},B}});return I}static transformEntryForSelect(m,O,A,y,b,C){if(m&&(m===t||m?.length===1&&m[0]===t&&Array.isArray(m))){let N=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return m===t?N:m.asArray?x=>[N(x)]:x=>({[t]:N(x)})}let I;b&&v&&!(typeof m=="string"?[m]:m)?.every(N=>{let x;return typeof N=="object"?x=N.name:x=N,r[x]||x===t})&&(I=!0);let L,B=a(function(N){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),N!=null){if(x=N.value||N.deref?.()?.value,!x&&(N.key===void 0||N.deref)||N.metadataFlags&En){if(N.metadataFlags&En&&O.replicateFrom===!1&&C&&N.residencyId)return Ec.SKIP;if(N=cu(N.key??N,O,{transaction:A,lazy:m?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(B.bind(this));x=N?.value}if(I&&N?.metadataFlags&(En|Ea)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=lu(N.key??N,N,O);if(G?.then)return G.then(B)}}if(x==null)return C?Ec.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,j=a((F,qe)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Hn?.[Z],ee;if(ce){let J=y?.[Z];if(J)if(J.hasMappings){let fe=ce.from?x[ce.from]:gu(N.key);ee=J.get(fe),ee||(ee=[])}else ee=J.fromRecord?.(x);else ee=ce(x,O,N);let _e=a(fe=>{if(fe&&typeof fe=="object"){let Ae=ce.definition?.tableClass||Ce;L||(L={});let De=L[Z]||(L[Z]=Ae.transformEntryForSelect(Z===F?null:F.select||(Array.isArray(F)?F:null),O,A,J,b));if(Array.isArray(fe)){let we=[],hr=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,A,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Pr=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Pr);we.push(Re.value),Re=hr.next()}qe(we,Z)},"nextValue"),Ws=Pr(hr.next());Ws&&(G||(G=[]),G.push(Ws));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>qe(we,Z)));return}}qe(fe,Z)},"handleResolvedValue");ee?.then?(G||(G=[]),G.push(ee.then(_e))):_e(ee);return}else ee=x[Z],ee&&typeof ee=="object"&&Z!==F&&(ee=Ce.transformEntryForSelect(F.select||F,O,A,null)({value:ee}));qe(ee,Z)},"selectAttribute"),ie;if(typeof m=="string")j(m,F=>{ie=F});else if(Array.isArray(m))if(m.asArray)ie=[],m.forEach((F,qe)=>{F==="*"?m[qe]=x:j(F,Z=>ie[qe]=Z)});else{ie={};let F=m.forceNulls;for(let qe of m)if(qe==="*")for(let Z in x)ie[Z]=x[Z];else j(qe,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new Ir.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return B}async subscribe(m){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||dt({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),m||(m={});let O=!m.rawEvents,A=[],y=this,b=HP(Ce,this.getId()??null,function(I,L,B,N){try{let x=L.getValue?.(i,O),G=L.type;if(!x&&G==="patch"&&O){let ie=i.getEntry(I);ie?.version===L.version?x=ie.value:x=L.getValue?.(i,!0,B),G="put"}let j={id:I,localTime:B,value:x,version:L.version,type:G,beginTxn:N};A?A.push(j):this.send(j)}catch(x){xe.default.error?.(x)}},m.startTime||0,m),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,m.onlyChildren&&(b.onlyChildren=!0)),m.supportsTransactions&&(b.supportsTransactions=!0);let I=this.getId(),L=m.previousCount;L>1e3&&(L=1e3);let B=m.startTime;if(this.isCollection){if(B){if(L)throw new Ir.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let G=Nt(x);if(G.tableId!==n)continue;let j=G.recordId;if(I==null||eJ(I,j)){let ie=G.getValue(i,O,N);if(b.send({id:j,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>Xj&&await b.waitForDrain()===!1)return}b.startTime=N}}else if(L){let N=[];for(let{key:x,value:G}of l.getRange({start:"z",end:!1,reverse:!0}))try{let j=Nt(G);if(j.tableId!==n)continue;let ie=j.recordId;if(I==null||eJ(I,ie)){let F=j.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:j.version,type:j.type}),--L<=0)break}}catch(j){xe.default.error("Error getting history entry",x,j)}for(let x=N.length;x>0;)b.send(N[--x]);N[0]&&(b.startTime=N[0].localTime)}else if(!m.omitCurrent){for(let{key:N,value:x,version:G,localTime:j}of i.getRange({start:I??!1,end:I==null?void 0:[I,Zl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:j,value:x,version:G,type:"put"}),b.queue?.length>Xj&&await b.waitForDrain()===!1))return}}else{L&&!B&&(B=0);let N=this.#r?.localTime;if(N===ey&&(i.cache?.delete(I),this.#r=i.getEntry(I),xe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),xe.default.trace?.("Subscription from",B,"from",I,N),B<N){let x=[],G=N;do{let j=l.get(G);if(j){m.omitCurrent=!0;let ie=Nt(j),F=ie.getValue(i,O,G);O&&(ie.type="put"),x.push({id:I,value:F,localTime:G,...ie}),G=ie.previousLocalTime}else break;L&&L--}while(G>B&&L!==0);for(let j=x.length;j>0;)b.send(x[--j]);b.startTime=N}!m.omitCurrent&&this.doesExist()&&b.send({id:I,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of A)b.send(N);A=null})();return m.listener&&b.on("data",m.listener),b}static subscribeOnThisThread(m,O){return m===0||O?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let A=Vr(this.getContext()),y=this.getId()||null;y!=null&&Cr(y);let b=this.getContext();A.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(A.checkOverloaded(),this.validate(m))},"validate"),before:Te.publish?.bind(this,b,y,m),beforeIntermediate:ye.publish?.bind(this,b,y,m),commit:a((C,I,L)=>{I===void 0&&R&&!g&&so(),xe.default.trace?.(`Publishing message to id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,I?.value??null,I,I?.version||C,0,!0,{user:b?.user,residencyId:O?.residencyId,expiresAt:b?.expiresAt,nodeId:O?.nodeId},"message",!1,m)},"commit")})}validate(m,O){let A,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let B=0,N=L.length;B<N;B++){let x=L[B],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let B in b)L.find(N=>N.name===B)||(A||(A=[])).push(`Property ${B} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof wi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,B=b.length;L<B;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(A||(A=[])).push(`Value ${qs(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=E.length;b<C;b++){let I=E[b];if(!(I.relationship||I.computed)&&(!O||I.name in m)){let L=y(m[I.name],I,I.name);L&&(m[I.name]=L)}}if(d)for(let b in m)E.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new Ir.ClientError(A.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(m){let O=E.slice(0);for(let A of m){if(!A.name)throw new Ir.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new Ir.ClientError("Attribute names cannot include backticks or forward slashes");(0,nJ.validateAttribute)(A.name),O.push(A)}return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(m){let O=E.filter(A=>!m.includes(A.name));return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static getSize(){let m=i.getStats();return(m.treeBranchPageCount+m.treeLeafPageCount+m.overflowPages)*m.pageSize}static getAuditSize(){let m=l?.getStats();return m&&(m.treeBranchPageCount+m.treeLeafPageCount+m.overflowPages)*m.pageSize}static getStorageStats(){let m=i.env.path,O=EA.default.statfsSync?.(m)??{};return{available:O.bavail*O.bsize,free:O.bfree*O.bsize,size:O.blocks*O.bsize}}static async getRecordCount(m){let O=i.getStats().entryCount,A=1e3/2,y=performance.now(),b=Math.floor(O/2),C=m?.exactCount,I=0,L=0,B;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await mc(),!C&&L<b&&performance.now()-y>A){B=L;break}if(B){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:B,snapshot:!1}))ee!=null&&I++,await mc();let x=B*2,G=(I+N)/x,j=Math.pow((I-N+1)/B/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(j)*O,1),F=Math.round(G*O),qe=Math.max(F-1.96*ie,I+N),Z=Math.min(F+1.96*ie,O),ce=Math.pow(10,Math.round(Math.log10(ie)));return ce>F&&(ce=ce/10),I=Math.round(F/ce)*ce,{recordCount:I,estimatedRange:[Math.round(qe),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Hn=this.propertyResolvers={$id:a((m,O,A)=>({value:A.key}),"$id"),$updatedtime:a((m,O,A)=>A.version,"$updatedtime"),$record:a((m,O,A)=>A?{value:m}:m,"$record")};for(let m of this.attributes){m.isPrimaryKey&&(H=m),m.resolve=null;let O=m.relationship,A=m.computed;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),ou=!0,O.to)m.elements?.definition?(Hn[m.name]=m.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=m.elements.definition.tableClass;return C?Eu({attribute:O.to,value:I},Vr(b).getReadTxn(),!1,L,!1).asArray:L.search([{attribute:O.to,value:I}],b).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let y=m.definition||m.elements?.definition;y?(Hn[m.name]=m.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(m.elements){let B,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:Vr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(B=!0),G});return O.filterMissing?B?Promise.all(N).then(x=>x.filter(tJ)):N.filter(tJ):B?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:Vr(C).getReadTxn()}):y.tableClass.get(L,C)}},m.set=(b,C)=>{if(Array.isArray(C)){let I=C.map(L=>L.getId?.()||L[y.tableClass.primaryKey]);b[O.from]=I}else{let I=C.getId?.()||C[y.tableClass.primaryKey];b[O.from]=I}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.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`);else A&&(typeof A.from=="function"&&this.setComputedAttribute(m.name,A.from),Hn[m.name]=m.resolve=(y,b,C)=>{let I=typeof A.from=="string"?y[A.from]:y,L=this.userResolvers[m.name];if(L)return L(I,b,C);xe.default.warn(`Computed attribute "${m.name}" does not have a function assigned to it. Please use setComputedAttribute('${m.name}', resolver) to assign a resolver function.`),this.userResolvers[m.name]=()=>{}})}qE(this,this)}static setComputedAttribute(m,O){let A=Oi(E,m);if(!A){console.error(`The attribute "${m}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${m}" is not defined as computed in the table "${s}"`);return}this.userResolvers[m]=O}static async deleteHistory(m=0,O=!1){let A;for(let{key:y,value:b}of l.getRange({start:0,end:m}))await mc(),Nt(b).tableId===n&&(A=hA(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await mc(),C===null&&I<m&&(A=Hc(i,y))}await A}static async*getHistory(m=0,O=1/0){for(let{key:A,value:y}of l.getRange({start:m||1,end:O})){await mc();let b=Nt(y);b.tableId===n&&(yield{id:b.recordId,localTime:A,version:b.version,type:b.type,value:b.getValue(i,!0,A),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let A=i.getEntry(m);if(!A)return O;let y=A.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await mc();let C=l.get(y);if(C){let I=Nt(C);O.push({id:I.recordId,localTime:y,version:I.version,type:I.type,value:I.getValue(i,!0,y),user:I.user}),y=I.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){Y?.remove()}}Ce.updatedAttributes();let gf=Ce.prototype;return h&&Ce.setTTLExpiration(h/1e3),se&&em(),Ce;function fn(K,m,O){let A;for(let y in r){let b=r[y],C=b.isIndexing,I=Hn[y],L=O&&(I?I(O):O[y]),B=m&&(I?I(m):m[y]);if(L===B&&!C)continue;A=!0;let N=b.indexNulls,x=(0,Uh.getIndexedValues)(L,N),G=(0,Uh.getIndexedValues)(B,N);if(G?.length>0){let j=new Set(G);if(x=x?x.filter(ie=>{if(j.has(ie))j.delete(ie);else return!0}):[],G=Array.from(j),(G.length>0||x.length>0)&&jj){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,Zj)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&jj&&b.prefetch(x.map(j=>({key:j,value:K})),Zj);if(x)for(let j=0,ie=x.length;j<ie;j++)b.put(x[j],K)}return A}a(fn,"updateIndices");function Cr(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>Qj)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");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,Zl.writeKey)(K,_Ae,0)>Qj)throw new Error("Primary key size is too large: "+K.length);return!0}a(Cr,"checkValidId");function cu(K,m,O,A,y){if(Ce.getResidencyById&&O.ensureLoaded&&m?.replicateFrom!==!1){let C=io(Ce.getResidencyById(K));if(C&&!C.includes(server.hostname)&&w)return w({key:K,residency:C}).then(y)}let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let C=i.getEntry(K,O);return C?.residencyId&&C.metadataFlags&En&&w&&O.ensureLoaded&&m?.replicateFrom!==!1?w(C).then(I=>y(I,K),I=>(xe.default.error?.("Error loading remote record",K,C,O,I),y(null,K))):(C&&m&&(C?.version>(m.lastModified||0)&&(m.lastModified=C.version),C?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=C.localTime)),y(C,K))},"whenPrefetched");return A?b():ae>0?(ae--,b()):new Promise((C,I)=>{ae===0?(ae--,i.prefetch([K],()=>{L(),B()})):(ne.push(K),ue.push(B),ne.length>Zh&&(ae--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{ae===-1?L():ae++;for(let x of N)x()}),ne=[],ue=[],me>2&&me--}else ae=me,me<Ef&&me++}a(L,"prefetch");function B(){try{C(b())}catch(N){I(N)}}a(B,"load")})}a(cu,"loadLocalRecord");function $r(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return pAe;let O=m[c],A,y=O?.tables;if(y)return y[s];if(c==="data"&&(A=m[s])&&!A.tables)return A}a($r,"getTablePermissions");function lu(K,m,O,A){if(v){let y=!1;if(O.noCache?y=!0:(m?(!m.value||m.metadataFlags&(En|Ea)||m.expiresAt!=null&&m.expiresAt<Date.now())&&(y=!0):y=!0,Zn(!y,"cache-hit",s)),y){let b=Tf(K,m,O).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),O&&(C?.version>(O.lastModified||0)&&(O.lastModified=C.version),O.lastRefreshed=Date.now()),C));if(O?.onlyIfCached||m?.value&&A?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!A.doesExist())throw new Ir.ServerError("Entry is not cached",504);return}else return b}}else if(m?.value&&m.expiresAt!=null&&m.expiresAt<Date.now())return Ce.evict(m.key,m.value,m.version),m.value=null,{then(y){return y(m)}}}a(lu,"ensureLoadedFromSource");function Vr(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new Nc,m.lmdbDb=i,m;m=O}while(!0)}else return new Rm}a(Vr,"txnForContext");function uu(K,m,O){if(!K)return;let A=K.value||i.getEntry(K.key)?.value;if(typeof m=="object"){let b=Hn,C=A;for(let I=0,L=m.length;I<L;I++){let B=m[I],N=b?.[B];C=N&&C?N(C,O,!0)?.value:C?.[B],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Hn[m];return y?y(A,O):A[m]}a(uu,"getAttributeValue");function Sf(K,m,O,A,y){let b=y?.length,C={transaction:A,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},I;function L(B,N){let x=B?.value;if(!x)return Ec.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,B))return Ec.SKIP;return N!==void 0&&(B.key=N),B}if(a(L,"processEntry"),b>0||!K.hasEntries){let B=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Ec.SKIP;for(let x=0;x<b;x++){let j=y[x].idFilter;if(j){if(!j(N))return Ec.SKIP;I||(I=[]),I.push(x)}}return cu(N,O,C,!1,L)});return Array.isArray(K)&&(B=B.filter(N=>N!==Ec.SKIP)),B.hasEntries=!0,B}return K}a(Sf,"transformToEntries");function no(K,m,O=server.replication?.getThisNodeId(l)){if(K<=m?.version){if(m?.version===K&&O!==void 0){let A=server.replication?.exportIdMapping(l),y=m.localTime,b=y&&l.get(y);if(b){let C,I,L=Nt(b);for(let B in A)A[B]===O&&(C=B),A[B]===L.nodeId&&(I=B);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a(no,"precedesExistingVersion");async function Tf(K,m,O){let A=m?.metadataFlags,y=m?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(En|Ea)?b(Tf(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},dAe)});let I=m?.value,L={requestContext:O,replacingRecord:I,replacingEntry:m,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},B=O?.responseHeaders;return new Promise((N,x)=>{let G;FP(Ot(L,async j=>{let ie=performance.now(),F,qe,Z;try{for(let _e of Ce.sources)if(_e.get&&(!_e.get.reliesOnPrototype||_e.prototype.get)){if(_e.available?.(m)===!1)continue;if(L.source=_e,F=await _e.get(K,L),F)break}Z=A&En;let ee=L.lastModified||Z&&y;qe=Z||ee>y||!I,ee||(ee=(0,Uh.getNextMonotonicTime)());let J=performance.now()-ie;if(nr(J,"cache-resolution",s,null,"success"),B&&tg(B,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),j.timestamp=ee,h&&L.expiresAt==null&&(L.expiresAt=Date.now()+h),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=I,ee=y;else throw new Ir.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}G=!0,N({key:K,version:ee,value:F})}catch(ee){ee.message+=` while resolving record ${K} for ${s}`,I&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(N({key:K,version:y,value:I}),xe.default.trace?.(ee.message,"(returned stale record)")):x(ee);let J=performance.now()-ie;nr(J,"cache-resolution",s,null,"fail"),B&&tg(B,"Server-Timing",`cache-resolve;dur=${J.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Vr(L).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:a((ee,J)=>{if(J?.version!==y)return;let _e=fn(K,I,F);if(F){ye.put?.(L,K,F),J&&(O.previousResidency=Ce.getResidencyRecord(J.residencyId));let fe,Ae=!1,De,we=io(Ce.getResidency(F,O));if(we){if(!we.includes(server.hostname))if(fe=F,Ae=!0,Ce.getResidencyById)F=void 0;else{F=null;for(let hr in r)F||(F={}),F[hr]=fe[hr]}De=Rc(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,J,ee,Ae?En:0,g&&(qe||Ae)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:De},"put",!!Z,fe)}else J&&(ye.delete?.(L,K),xe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),g||R?T(K,null,J,ee,0,g&&qe||null,{user:L?.user},"delete",!!Z):Hc(i,J,y))},"commit")})}),()=>{i.unlock(K,y)},j=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",j)})})}a(Tf,"getFromSource");function du(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new Ir.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new Ir.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(du,"checkContextPermissions");function so(K){let m=!1;if(K&&(K-ut>1&&(m=!0),ut=K),!(Qt===br&&!m)&&(br=Qt,(0,Ql.getWorkerIndex)()===(0,Ql.getWorkerCount)()-1))return Es&&clearTimeout(Es),Qt?new Promise(O=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let y=Qt/(1+ut),b=m?Date.now():Math.ceil((Date.now()-A.getTime())/y)*y+A.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),Es=setTimeout(()=>$=$.then(async()=>{if(C(Math.max(I+Qt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Es);return}let L=50,B=new Array(L),N=0,x=Math.pow(ut,8)*(Xl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(ut,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function j(ie,F,qe,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(ut){let ee=i.lastSize;return qe&An&&yu(Z,J=>{J.size&&(ee+=J.size)}),xe.default.trace?.(`shouldEvict adjusted ${ce} ${ee}, ${ce*(ie-F)/ee} < ${x}`),ce*(ie-F)/ee<x}return!1}a(j,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:qe,value:Z,version:ce,expiresAt:ee,metadataFlags:J}=F,_e;Z===null&&!g&&ce+uAe<Date.now()?_e=Hc(i,F,ce):ee!=null&&j(ee,ce,J,Z)&&(_e=Ce.evict(qe,Z,ce),ie++),_e&&(await B[N],B[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await mc()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${ie} entries`)}catch(ie){xe.default.warn?.(`Error in cleanup scan for ${s}:`,ie)}O(void 0),ut=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a(so,"scheduleCleanup");function Af(){Y=l?.addDeleteRemovalCallback(n,i,(K,m)=>{i.remove(K,m)})}a(Af,"addDeleteRemoval");function em(){(0,Ql.getWorkerIndex)()===0&&setInterval(async()=>{if(!au){au=!0;try{let K=se.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${se} must be indexed`);for(let O of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of m.getValues(O)){let y=i.getEntry(A);y?.value?y.value[K]<Date.now()&&Ce.evict(A,y.value,y.version):i.ifVersion(A,y?.version,()=>m.remove(O,A))}await mc()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{au=!1}}},lAe).unref()}a(em,"runRecordExpirationEviction");function io(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let m=server.shards?.get?.(K);if(m)return xe.default.trace?.(`Shard ${K} mapped to ${m.map(O=>O.name).join(", ")}`),m.map(O=>O.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(io,"residencyFromFunction");function Rc(K){if(K){let m=K.join(","),O=f.get([Symbol.for("residency_by_set"),m]);return O||(f.put([Symbol.for("residency_by_set"),m],O=Math.floor(Math.random()*2147418112)+65535),f.put([Symbol.for("residency_by_id"),O],K),O)}}a(Rc,"getResidencyId")}function kP(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 Zj(){}function hAe(e){sJ=e}function gA(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return mA(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return mA(+e);case"Float":return e==="null"?null:mA(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;mAe.test(e)||(e+="Z");let n=new Date(e);return mA(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,SA.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function mA(e){if(isNaN(e))throw new SyntaxError;return e}function eJ(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);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 FP(e,t,r){return e?.then?e.then(t,r):t(e)}function tJ(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function EAe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Ec,Uh,rJ,nJ,Xl,Ir,xh,Bh,xe,Zl,Ql,SA,EA,cAe,sJ,lAe,uAe,jj,dAe,Jj,fAe,En,Ea,_Ae,Qj,Xj,pAe,uxe,mAe,mc,qf=be(()=>{k();Ec=require("lmdb"),Uh=M(pn()),rJ=require("lodash"),nJ=M(xf());ga();ym();Xl=M(le());NN();Ir=M(he()),xh=M(bo()),Bh=M(ni());Le();Gf();xe=M(Ni());Qb();wc();Zl=require("ordered-binary"),Ql=M(tt());mo();SA=M(oe());wu();ki();HE();z_();EA=M(require("node:fs"));As();HT();cAe=new Uint8Array(9);cAe[8]=192;lAe=6e4,uAe=864e5;Xl.initSync();jj=Xl.get(U.STORAGE_PREFETCHWRITES),dAe=1e4,Jj=1,fAe=2,En=1,Ea=8,_Ae=Buffer.allocUnsafeSlow(8192),Qj=1978,Xj=100,pAe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},uxe=(0,SA.convertToMS)(Xl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(TA,"makeTable");a(kP,"attributesAsObject");a(Zj,"noop");a(hAe,"setServerUtilities");mAe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(gA,"coerceType");a(mA,"rejectNaN");a(eJ,"isDescendantId");mc=a(()=>new Promise(setImmediate),"rest");a(FP,"when");a(tJ,"exists");a(qs,"stringify");a(EAe,"hasOtherProcesses")});var rt={};Ue(rt,{database:()=>qu,database_envs:()=>sa,databases:()=>Ve,dropDatabase:()=>rO,dropTableMeta:()=>RAe,getDatabases:()=>Qe,getDefaultCompression:()=>MS,getTables:()=>gAe,onRemovedDB:()=>hp,onUpdatedTable:()=>Tl,readMetaDb:()=>Hh,resetDatabases:()=>Pd,table:()=>dt,tables:()=>Xn});function gAe(){return bA||Qe(),Xn||{}}function Qe(){if(bA)return Ve;bA=!0,df=new Map;let e=(0,Jt.getHdbBasePath)()&&(0,Pt.join)((0,Jt.getHdbBasePath)(),Oc),t=(0,Jt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Jt.get)(U.STORAGE_PATH)||e&&((0,fs.existsSync)(e)?e:(0,Pt.join)((0,Jt.getHdbBasePath)(),am)),!e)return;if((0,fs.existsSync)(e))for(let n of(0,fs.readdirSync)(e,{withFileTypes:!0})){let s=(0,Pt.basename)(n.name,".mdb");n.isFile()&&(0,Pt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&Hh((0,Pt.join)(e,n.name),null,s)}if((0,fs.existsSync)((0,uf.getBaseSchemaPath)())){for(let n of(0,fs.readdirSync)((0,uf.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Pt.join)((0,uf.getBaseSchemaPath)(),n.name),i=(0,Pt.join)((0,uf.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,fs.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Pt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Pt.join)(i,o.name);Hh((0,Pt.join)(s,o.name),(0,Pt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,fs.existsSync)(i))for(let c of(0,fs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Pt.extname)(c.name).toLowerCase()===".mdb"&&Hh((0,Pt.join)(i,c.name),(0,Pt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Pt.join)(l.path,(0,Pt.basename)(c+".mdb"));(0,fs.existsSync)(u)&&Hh(u,c,n,null,!0)}}for(let n in Ve){let s=df.get(n);if(s){let i=Ve[n];n.includes("delete")&&Dt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Dt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Xn)delete Xn[i];delete Xn[OA]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return df=null,Ve}function Pd(){bA=!1;for(let[,e]of sa)e.needsDeletion=!0;Qe();for(let[e,t]of sa)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),sa.delete(e),delete Ve[t.databaseName],Fh.forEach(r=>r(t.databaseName)));return Ve}function Hh(e,t,r=$P,n,s){let i=new GP.default(e,!1);try{let o=sa.get(e);o?o.needsDeletion=!1:(o=(0,ff.open)(i),sa.set(e,o));let c=new eu.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(AA.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,fs.existsSync)(n)&&(i.path=n,u=(0,ff.open)(i),u.isLegacy=!0):u=pA(o));let f=cJ(r),d=f[OA],_=new Map;for(let{key:p,value:h}of l.getRange({start:!1})){let[S,g]=p.toString().split("/");g===""?g=h.name:g||(g=S,S=t,h.name||(h.name=g,h.indexed=!h.is_hash_attribute)),d?.add(S);let R=_.get(S);R||_.set(S,R={attributes:[]}),(g==null||h.is_hash_attribute)&&(R.primary=h),g!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:p,configurable:!0})}for(let[p,h]of _){let{attributes:S,primary:g}=h;if(!g){for(let ae of S)if(ae.is_hash_attribute||ae.isPrimaryKey){g=ae;break}if(!g){Dt.warn(`Unable to find a primary key attribute on table ${p}, with attributes: ${JSON.stringify(S)}`);continue}}let R=f[p],E={},T=[],w,v,H=typeof g.audit=="boolean"?g.audit:(0,Jt.get)(U.LOGGING_AUDITLOG),$=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(R)E=R.indices,T=R.attributes,R.schemaVersion++;else{w=g.tableId,w?w>=(l.get(lf)||0)&&(l.putSync(lf,w+1),Dt.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(g.tableId=w=l.get(lf),w||(w=1),Dt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(lf,w+1),l.putSync(g.key,g));let ae=new eu.default(!g.is_hash_attribute,g.is_hash_attribute);if(ae.compression=g.compression,ae.compression){let me=(0,Jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||aJ;ae.compression.threshold=me}v=Xm(o.openDB(g.key,ae),o),o.databaseName=r,v.tableId=w}let ue;for(let ae of S){ae.attribute=ae.name;try{if(!ae.is_hash_attribute&&(ae.indexed||ae.attribute&&!ae.name)){if(!E[ae.name]){let Te=new eu.default(!ae.is_hash_attribute,ae.is_hash_attribute);E[ae.name]=o.openDB(ae.key,Te),E[ae.name].indexNulls=ae.indexNulls}let me=T.find(Te=>Te.name===ae.name);me?T.splice(T.indexOf(me),1,ae):T.push(ae),ue=!0}}catch(me){Dt.error("Error trying to update attribute",ae,T,E,me)}}for(let ae of T)if(!S.find(Te=>Te.name===ae.name)){if(ae.is_hash_attribute){Dt.error("Unable to remove existing primary key attribute",ae);continue}ae.indexed&&(T.splice(T.indexOf(ae),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=lJ(f,p,TA({primaryStore:v,auditStore:u,audit:H,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:$,tableName:p,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let ae of kh)ae(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function cJ(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Xn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),df&&!df.has(e)){let r=new Set;t[OA]=r,df.set(e,r)}return t}function lJ(e,t,r){return e[t]=r,r}function qu({database:e,table:t}){e||(e=$P),Qe();let r=cJ(e),n=(0,Pt.join)((0,Jt.getHdbBasePath)(),Oc),s=(0,Jt.get)(U.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Jt.get)(U.STORAGE_PATH)||((0,fs.existsSync)(n)?n:(0,Pt.join)((0,Jt.getHdbBasePath)(),am));let o=(0,Pt.join)(n,(i?t:e)+".mdb"),c=sa.get(o);if(!c||c.status==="closed"){let l=new GP.default(o,!1);c=(0,ff.open)(l),sa.set(o,c)}return c.auditStore||(c.auditStore=pA(c)),c}async function rO(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,sa.delete(r.path),r.status==="open"&&(await r.close(),await Gh.remove(r.path));if(r||(r=qu({database:e,table:null}),r.status==="open"&&(await r.close(),await Gh.remove(r.path))),e==="data"){for(let n in Xn)delete Xn[n];delete Xn[OA]}delete Ve[e],Fh.forEach(n=>n(e)),await vR(r)}function dt(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,schemaDefined:_,origin:p}=e;r||(r=$P);let h=qu({database:r,table:t}),S=Ve[r];Dt.trace(`Defining ${t} in ${r}`);let g=S?.[t];if(h.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,E,T;_==null&&(_=!0);let w=new eu.default(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let v,H;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...o)}else{let Y=h.auditStore;E=o.find(me=>me.isPrimaryKey)||{},R=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=MS(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,Jt.get)(U.LOGGING_AUDITLOG),n&&(E.expiration=n),s&&(E.eviction=s),u??=!1,E.splitSegments=u,typeof l=="boolean"&&(E.sealed=l),typeof f=="boolean"&&(E.replicate=f),p&&(E.origins?E.origins.includes(p)||E.origins.push(p):E.origins=[p]),Dt.trace(`${t} table loading, opening primary store`);let ne=new eu.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=h.dbisDb=h.openDB(AA.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return H&&H(),Pd(),dt(e);let ae=Xm(h.openDB(ue,ne),h);h.databaseName=r,ae.tableId=T.get(lf),Dt.trace(`Assigning new table id ${ae.tableId} for ${t}`),ae.tableId||(ae.tableId=1),T.put(lf,ae.tableId+1),E.tableId=ae.tableId,g=lJ(S,t,TA({primaryStore:ae,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:ae.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let $=g.indices;T=T||(h.dbisDb=h.openDB(AA.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,ae]=Y.toString().split("/");if(ae===""&&(ae=ne.name),ae){if(ue!==t)continue}else continue;let me=o.find(ye=>ye.name===ae),Te=!me?.indexed&&ne.indexed&&!ne.isPrimaryKey;if((!me||Te)&&(se(),v=!0,me||T.remove(Y),Te)){let ye=g.indices[ue];ye&&W.push(ye)}}let te=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(v=!0,Y.relationship))continue;let ne=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ne,configurable:!0});let ue=T.get(ne);if(Y.isPrimaryKey){if(ue=ue||T.get(ne=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||f!==void 0&&f!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||Y.type!==ue.type){let me={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),me.audit=c),n&&(me.expiration=+n),s&&(me.eviction=+s),l!==void 0&&(me.sealed=l),f!==void 0&&(me.replicate=f),Y.type&&(me.type=Y.type),v=!0,se(),T.put(ne,me)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let ae=!ue||ue.type!==Y.type||ue.indexed!==Y.indexed||ue.nullable!==Y.nullable||ue.version!==Y.version||JSON.stringify(ue.properties)!==JSON.stringify(Y.properties)||JSON.stringify(ue.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let me=new eu.default(!0,!1),Te=h.openDB(ne,me);(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<qh.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(ae||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<qh.workerData?.restartNumber)&&(v=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=ue?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Te}),te.push(Y))),T.put(ne,Y)),ue?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Te.indexNulls=Y.indexNulls,$[Y.name]=Te}else ae&&(v=!0,se(),T.put(ne,Y))}}finally{H&&H()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Dt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=AAe(g,te,W):v&&RA.signalSchemaChange(new yA.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=p,v)for(let Y of kh)Y(g,p!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Dt.trace(`${t} table loaded`),g;function se(){H||h.transactionSync(()=>({then(Y){H=Y}}))}a(se,"startTxn")}async function AAe(e,t,r){try{Dt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await RA.signalSchemaChange(new yA.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let d of t)(0,ff.compareKeys)(d.lastIndexedKey,u)<0&&(u=d.lastIndexedKey),d.lastIndexedKey==null&&d.dbi.clearAsync();let f=0;for(let{key:d,value:_,version:p}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(_){if(f++,s=e.primaryStore.ifVersion(d,p,()=>{for(let h=0;h<l;h++){let S=t[h],g=S.name;try{let R=S.resolve,E=_&&(R?R(_):_[g]),T=(0,iJ.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(R){o[g]||(o[g]=!0,Dt.error(`Error indexing attribute ${g}`,R))}}}),s.then(()=>f--,h=>{f--,Dt.error(h)}),qh.workerData&&qh.workerData.restartNumber!==oJ.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=d,e.dbisDB.put(h.key,h);if(i)return}f>SAe?await s:f>TAe&&await new Promise(h=>setImmediate(h))}for(let d of t)delete d.lastIndexedKey,delete d.indexingPID,d.dbi.isIndexing=!1,s=e.dbisDB.put(d.key,d)}await s,await RA.signalSchemaChange(new yA.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Dt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Dt.error("Error in indexing",n)}}function RAe({table:e,database:t}){let r=qu({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 Tl(e){return kh.push(e),{remove(){let t=kh.indexOf(e);t>-1&&kh.splice(t,1)}}}function hp(e){return Fh.push(e),{remove(){let t=Fh.indexOf(e);t>-1&&Fh.splice(t,1)}}}function MS(){let e=(0,Jt.get)(U.STORAGE_COMPRESSION),t=(0,Jt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Jt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||aJ,n={startingOffset:32};return t&&(n.dictionary=Gh.readFileSync(t)),r&&(n.threshold=r),e&&n}var Jt,AA,ff,Pt,fs,uf,eu,GP,Gh,qP,iJ,RA,yA,qh,Dt,oJ,$P,OA,aJ,Xn,Ve,lf,kh,Fh,bA,sa,df,SAe,TAe,Le=be(()=>{Jt=M(le()),AA=M(Ut()),ff=require("lmdb"),Pt=require("path"),fs=require("fs"),uf=M(mt());qf();eu=M(s_()),GP=M(i_());k();Gh=M(require("fs-extra")),qP=M(Ai()),iJ=M(pn()),RA=M(bo()),yA=M(ni()),qh=require("worker_threads"),Dt=M(z()),oJ=M(tt());mo();wu();As();$P="data",OA=Symbol("defined-tables"),aJ=((0,Jt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Jt.initSync)();Xn=Object.create(null),Ve=Object.create(null);(0,qP._assignPackageExport)("databases",Ve);(0,qP._assignPackageExport)("tables",Xn);lf=Symbol.for("next-table-id"),kh=[],Fh=[],sa=new Map;a(gAe,"getTables");a(Qe,"getDatabases");a(Pd,"resetDatabases");a(Hh,"readMetaDb");a(cJ,"ensureDB");a(lJ,"setTable");a(qu,"database");a(rO,"dropDatabase");a(dt,"table");SAe=1e3,TAe=10;a(AAe,"runIndexing");a(RAe,"dropTableMeta");a(Tl,"onUpdatedTable");a(hp,"onRemovedDB");a(MS,"getDefaultCompression")});var oe=P((Axe,yJ)=>{"use strict";var gc=require("path"),pJ=require("fs-extra"),xn=z(),uJ=require("fs-extra"),NA=require("os"),yAe=require("net"),bAe=require("recursive-iterator"),yr=(k(),D(q)),{PACKAGE_ROOT:OAe}=nt(),NAe=uR(),dJ=require("papaparse"),wA=require("moment"),{inspect:wAe}=require("util"),fJ=require("is-number"),Txe=require("lodash"),IAe=require("minimist"),CAe=require("https"),PAe=require("http"),{hdb_errors:IA}=he(),DAe=/^((\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)))$/,hJ=require("util").promisify(setTimeout),LAe=100,MAe=5,vAe="",UAe=4,_J={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};yJ.exports={isEmpty:_s,isEmptyOrZeroLength:to,arrayHasEmptyValues:HAe,arrayHasEmptyOrZeroLengthValues:kAe,buildFolderPath:FAe,isBoolean:mJ,errorizeMessage:xAe,stripFileExtension:qAe,autoCast:$Ae,autoCastJSON:EJ,autoCastJSONDeep:KP,removeDir:VAe,compareVersions:KAe,isCompatibleDataVersion:YAe,escapeRawValue:WAe,unescapeValue:zAe,stringifyProps:jAe,timeoutPromise:QAe,isClusterOperation:ZAe,getClusterUser:tRe,checkGlobalSchemaTable:eRe,getHomeDir:SJ,getPropsFilePath:JAe,promisifyPapaParse:rRe,removeBOM:TJ,createEventPromise:nRe,checkProcessRunning:sRe,checkSchemaTableExist:iRe,checkSchemaExists:AJ,checkTableExists:RJ,getStartOfTomorrowInSeconds:oRe,getLimitKey:aRe,isObject:GAe,isNotEmptyAndHasValue:BAe,autoCasterIsNumberCheck:gJ,backtickASTSchemaItems:cRe,isPortTaken:XAe,createForkArgs:lRe,autoCastBoolean:uRe,async_set_timeout:hJ,getTableHashAttribute:dRe,doesSchemaExist:fRe,doesTableExist:_Re,stringifyObj:pRe,ms_to_time:hRe,changeExtension:mRe,getEnvCliRootPath:YP,noBootFile:ERe,httpRequest:gRe,transformReq:SRe,convertToMS:TRe,PACKAGE_ROOT:OAe};function xAe(e){return e instanceof Error?e:new Error(e)}a(xAe,"errorizeMessage");function _s(e){return e==null}a(_s,"isEmpty");function BAe(e){return!_s(e)&&(e||e===0||e===""||mJ(e))}a(BAe,"isNotEmptyAndHasValue");function to(e){return _s(e)||e.length===0||e.size===0}a(to,"isEmptyOrZeroLength");function HAe(e){if(_s(e))return!0;for(let t=0;t<e.length;t++)if(_s(e[t]))return!0;return!1}a(HAe,"arrayHasEmptyValues");function kAe(e){if(to(e))return!0;for(let t=0;t<e.length;t++)if(to(e[t]))return!0;return!1}a(kAe,"arrayHasEmptyOrZeroLengthValues");function FAe(...e){try{return e.join(gc.sep)}catch{console.error(e)}}a(FAe,"buildFolderPath");function mJ(e){return _s(e)?!1:e===!0||e===!1}a(mJ,"isBoolean");function GAe(e){return _s(e)?!1:typeof e=="object"}a(GAe,"isObject");function qAe(e){return to(e)?vAe:e.slice(0,-UAe)}a(qAe,"stripFileExtension");function $Ae(e){return _s(e)||e===""||typeof e!="string"?e:_J[e]!==void 0?_J[e]:gJ(e)===!0?Number(e):DAe.test(e)?new Date(e):e}a($Ae,"autoCast");function EJ(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(EJ,"autoCastJSON");function KP(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=KP(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=KP(r);n!==r&&(e[t]=n)}return e}else return EJ(e)}a(KP,"autoCastJSONDeep");function gJ(e){if(e.startsWith("0.")&&fJ(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&fJ(e))}a(gJ,"autoCasterIsNumberCheck");async function VAe(e){if(to(e))throw new Error(`Directory path: ${e} does not exist`);try{await uJ.emptyDir(e),await uJ.remove(e)}catch(t){throw xn.error(`Error removing files in ${e} -- ${t}`),t}}a(VAe,"removeDir");function KAe(e,t){if(to(e)){xn.info("Invalid current version sent as parameter.");return}if(to(t)){xn.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("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(KAe,"compareVersions");function YAe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(YAe,"isCompatibleDataVersion");function WAe(e){if(_s(e))return e;let t=String(e);return t==="."?yr.UNICODE_PERIOD:t===".."?yr.UNICODE_PERIOD+yr.UNICODE_PERIOD:t.replace(yr.FORWARD_SLASH_REGEX,yr.UNICODE_FORWARD_SLASH)}a(WAe,"escapeRawValue");function zAe(e){if(_s(e))return e;let t=String(e);return t===yr.UNICODE_PERIOD?".":t===yr.UNICODE_PERIOD+yr.UNICODE_PERIOD?"..":String(e).replace(yr.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(zAe,"unescapeValue");function jAe(e,t){if(_s(e))return xn.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+NA.EOL}!to(n)&&n[0]===";"?r+=" "+n+s+NA.EOL:to(n)||(r+=n+"="+s+NA.EOL)}catch{xn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(jAe,"stringifyProps");function SJ(){let e;try{e=NA.homedir()}catch{e=process.env.HOME}return e}a(SJ,"getHomeDir");function JAe(){let e=gc.join(SJ(),yr.HDB_HOME_DIR_NAME,yr.BOOT_PROPS_FILE_NAME);return pJ.existsSync(e)||(e=gc.join(__dirname,"../","hdb_boot_properties.file")),e}a(JAe,"getPropsFilePath");function QAe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(QAe,"timeoutPromise");async function XAe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=yAe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(XAe,"isPortTaken");function ZAe(e){try{return yr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){xn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(ZAe,"isClusterOperation");function eRe(e,t){let r=(Le(),D(rt)).getDatabases();if(!r[e])return IA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return IA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(eRe,"checkGlobalSchemaTable");function tRe(e,t){if(_s(t)){xn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(_s(e)||to(e)){xn.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){xn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){xn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(tRe,"getClusterUser");function rRe(){dJ.parsePromise=function(e,t,r){return new Promise(function(n,s){dJ.parse(e,{header:!0,transformHeader:TJ,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(rRe,"promisifyPapaParse");function TJ(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(TJ,"removeBOM");function nRe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;xn.info(`Got cluster status event response: ${wAe(s)}`);try{i.cancel()}catch{xn.error("Error trying to cancel timeout.")}n(s)})})}a(nRe,"createEventPromise");async function sRe(e){let t=!0,r=0;do await hJ(LAe*r++),(await NAe.findPs(e)).length>0&&(t=!1);while(t&&r<MAe);if(t)throw new Error(`process ${e} was not started`)}a(sRe,"checkProcessRunning");function iRe(e,t){let r=AJ(e);if(r)return r;let n=RJ(e,t);if(n)return n}a(iRe,"checkSchemaTableExist");function AJ(e){let{getDatabases:t}=(Le(),D(rt));if(!t()[e])return IA.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(AJ,"checkSchemaExists");function RJ(e,t){let{getDatabases:r}=(Le(),D(rt));if(!r()[e][t])return IA.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(RJ,"checkTableExists");function oRe(){let e=wA().utc().add(1,"d").startOf("d").unix(),t=wA().utc().unix();return e-t}a(oRe,"getStartOfTomorrowInSeconds");function aRe(){return wA().utc().format("DD-MM-YYYY")}a(aRe,"getLimitKey");function cRe(e){try{let t=new bAe(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){xn.error("Got an error back ticking items."),xn.error(t)}}a(cRe,"backtickASTSchemaItems");function lRe(e){return[e]}a(lRe,"createForkArgs");function uRe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(uRe,"autoCastBoolean");function dRe(e,t){let{getDatabases:r}=(Le(),D(rt)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(dRe,"getTableHashAttribute");function fRe(e){let{getDatabases:t}=(Le(),D(rt));return t()[e]!==void 0}a(fRe,"doesSchemaExist");function _Re(e,t){let{getDatabases:r}=(Le(),D(rt));return r()[e]?.[t]!==void 0}a(_Re,"doesTableExist");function pRe(e){try{return JSON.stringify(e)}catch{return e}}a(pRe,"stringifyObj");function hRe(e){let t=wA.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(hRe,"ms_to_time");function mRe(e,t){let r=gc.basename(e,gc.extname(e));return gc.join(gc.dirname(e),r+t)}a(mRe,"changeExtension");function YP(){if(process.env[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=IAe(process.argv);if(e[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[yr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(YP,"getEnvCliRootPath");var VP;function ERe(){if(VP)return VP;let e=YP();if(YP()&&pJ.pathExistsSync(gc.join(e,yr.HDB_CONFIG_FILE)))return VP=!0,!0}a(ERe,"noBootFile");function gRe(e,t){let r;return e.protocol==="http:"?r=PAe:r=CAe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(gRe,"httpRequest");function SRe(e){if(!e.schema&&!e.database){e.schema=yr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(SRe,"transformReq");function TRe(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(TRe,"convertToMS")});var le=P((IJ,CJ)=>{"use strict";var WP=require("fs-extra"),tu=require("path"),bJ=require("os"),ARe=require("properties-reader"),Vh=z(),$h=oe(),ve=(k(),D(q)),CA=At(),RRe="Error initializing environment manager",PA="BOOT_PROPS_FILE_PATH",OJ=!1,yRe={[ve.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},ia={};Object.assign(IJ,CJ.exports={BOOT_PROPS_FILE_PATH:PA,getHdbBasePath:bRe,setHdbBasePath:ORe,get:NJ,initSync:wRe,setProperty:ze,initTestEnvironment:CRe,setCloneVar:IRe});function bRe(){return ia[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(bRe,"getHdbBasePath");function ORe(e){ia[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(ORe,"setHdbBasePath");function NJ(e){let t=CA.getConfigValue(e);return t===void 0?ia[e]:t}a(NJ,"get");function ze(e,t){yRe[e]&&(ia[e]=t),CA.updateConfigObject(e,t)}a(ze,"setProperty");function NRe(){let e;try{e=$h.getPropsFilePath(),WP.accessSync(e,WP.constants.F_OK|WP.constants.R_OK),OJ=!0;let t=ARe(e);return ia[ve.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ve.HDB_SETTINGS_NAMES.INSTALL_USER),ia[ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),ia[PA]=e,!0}catch{return Vh.trace(`Environment manager found no properties file at ${e}`),!1}}a(NRe,"doesPropFileExist");function wRe(e=!1){try{((OJ||NRe()||$h.noBootFile())&&!wJ||e)&&(CA.initConfig(e),ia[ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=CA.getConfigValue(ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Vh.error(RRe),Vh.error(t),console.error(t),process.exit(1)}}a(wRe,"initSync");var wJ=!1;function IRe(e){wJ=e}a(IRe,"setCloneVar");function CRe(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,l=tu.join(__dirname,"../../","unitTests");ia[PA]=tu.join(l,"hdb_boot_properties.file"),ze(ve.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,tu.join(l,"settings.test")),ze(ve.HDB_SETTINGS_NAMES.INSTALL_USER,bJ.userInfo()?bJ.userInfo().username:void 0),ze(ve.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ze(ve.HDB_SETTINGS_NAMES.LOG_PATH_KEY,tu.join(l,"envDir","log")),ze(ve.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),ze(ve.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),ze(ve.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),ze(ve.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,tu.join(l,"envDir")),ze(ve.CONFIG_PARAMS.STORAGE_PATH,tu.join(l,"envDir")),s&&(ze(ve.CONFIG_PARAMS.HTTP_SECUREPORT,NJ(ve.CONFIG_PARAMS.HTTP_PORT)),ze(ve.CONFIG_PARAMS.HTTP_PORT,null)),ze(ve.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),ze(ve.CONFIG_PARAMS.HTTP_PORT,9926),ze(ve.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),ze(ve.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),ze(ve.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,$h.isEmpty(i)?!1:i),ze(ve.CONFIG_PARAMS.HTTP_CORS,$h.isEmpty(i)?!1:i),ze(ve.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),ze(ve.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),ze(ve.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),ze(ve.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),ze(ve.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,tu.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ze(ve.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,$h.isEmpty(c)?!1:c),o&&(ze("CORS_ACCESSLIST",o),ze(ve.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(ze(ve.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),ze(ve.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(ze(ve.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),ze(ve.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(ze(ve.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),ze(ve.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${PA}. Please check your boot props and settings files`;Vh.fatal(r),Vh.error(t)}}a(CRe,"initTestEnvironment")});var vJ=P((bxe,MJ)=>{"use strict";var LA=le();LA.initSync();var DA=(k(),D(q)),{httpRequest:PRe}=oe(),LJ=require("path"),PJ=require("fs-extra"),DRe=require("yaml"),{packageDirectory:LRe}=(Qw(),D(Jw)),{encode:MRe}=require("cbor-x"),vRe=["describe_table","describe_all","describe_database","list_users","list_roles","drop_role","add_user","alter_user","drop_user","restart_service","restart","create_database","drop_database","create_table","drop_table","create_attribute","drop_attribute","search_by_id","insert","update","upsert","delete","search_by_value","csv_file_load","csv_url_load","cluster_get_routes","cluster_network","cluster_status","remove_node","add_component","deploy_component","package_component","drop_component","get_components","get_component_file","set_component_file","registration_info","get_fingerprint","set_license","get_job","search_jobs_by_start_date","read_log","read_transaction_log","read_audit_log","delete_transaction_logs_before","purge_stream","delete_records_before","install_node_modules","set_configuration","get_configuration","create_authentication_tokens","refresh_operation_token","system_information","sql","create_csr","sign_certificate","list_certificates","add_certificate","remove_certificate","add_ssh_key","update_ssh_key","delete_ssh_key","list_ssh_keys","set_ssh_known_hosts","get_ssh_known_hosts"],DJ={deploy:"deploy_component",package:"package_component"};MJ.exports={cliOperations:BRe,buildRequest:xRe};var URe={deploy_component:a(async e=>{if(e.package)return;let t=process.cwd();e.payload=await LRe(t,{skip_node_modules:!0,...e}),e.cborEncode=!0,e.project||(e.project=LJ.basename(t))},"deploy_component")};function xRe(){let e={};for(let t of process.argv.slice(2))if(vRe.includes(t))e.operation=t;else if(DJ.hasOwnProperty(t))e.operation=DJ[t];else if(t.includes("=")){let[r,...n]=t.split("=");n=n.join("=");try{n=JSON.parse(n)}catch{}e[r]=n}return e}a(xRe,"buildRequest");async function BRe(e){e.target||(e.target=process.env.CLI_TARGET);let t;if(e.target){try{t=new URL(e.target)}catch(r){try{t=new URL(`https://${e.target}:9925`)}catch{throw r}}t={protocol:t.protocol,hostname:t.hostname,port:t.port,username:e.username||t.username||process.env.CLI_TARGET_USERNAME,password:e.password||t.password||process.env.CLI_TARGET_PASSWORD,rejectUnauthorized:e.rejectUnauthorized}}else PJ.existsSync(LJ.join(LA.get(DA.CONFIG_PARAMS.ROOTPATH),DA.HDB_PID_FILE))||(console.error("HarperDB must be running to perform this operation"),process.exit()),PJ.existsSync(LA.get(DA.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))||(console.error("No domain socket found, unable to perform this operation"),process.exit());await URe[e.operation]?.(e);try{let r=t??{protocol:"http:",socketPath:LA.get(DA.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)};r.method="POST",r.headers={"Content-Type":"application/json"},t?.username&&(r.headers.Authorization=`Basic ${Buffer.from(`${t.username}:${t.password}`).toString("base64")}`),e.cborEncode&&(r.headers["Content-Type"]="application/cbor",e=MRe(e));let n=await PRe(r,e),s;try{s=JSON.parse(n.body)}catch{s={status:n.statusCode+" "+(n.statusMessage||"Unknown"),body:n.body}}e.json?console.log(JSON.stringify(s,null,2)):console.log(DRe.stringify(s).trim())}catch(r){let n="Error: ";if(r?.response?.data?.error)n+=r.response.data.error;else if(r?.response?.data)n+=r?.response?.data;else return console.error(r);console.error(n)}}a(BRe,"cliOperations")});var BJ=P((Nxe,xJ)=>{"use strict";var UJ=require("semver/functions/major"),{packageJson:HRe}=nt(),zP=process.versions&&process.versions.node?process.versions.node:void 0;xJ.exports=kRe;function kRe(){let e=HRe.engines["minimum-node"];if(zP&&UJ(zP)<UJ(e))return{error:`The minimum version of Node.js HarperDB supports is: ${e}, the currently installed Node.js version is: ${zP}. Please install a version of Node.js that is withing the defined range.`}}a(kRe,"checkNodeVersion")});var tD=P((Cxe,s2)=>{"use strict";var HJ=require("os"),MA=require("https"),kJ=require("http"),Gt=require("fs-extra"),FJ=require("yaml"),{pipeline:GJ}=require("stream/promises"),{createWriteStream:vA,ensureDir:Kh,writeFileSync:qJ}=require("fs-extra"),{join:Ks}=require("path"),YJ=require("lodash"),FRe=require("minimist"),oa=require("path"),GRe=require("node:crypto"),qRe=require("properties-reader"),Vs=le(),$Re=vo(),XP=z(),UA=At(),{restart:VRe}=ja(),xA=oe(),KRe=da(),YRe=bs(),{main:BA,launch:WRe}=Jd(),{install:WJ,updateConfigEnv:zRe,setIgnoreExisting:kA}=MT(),zJ=AC(),un=(k(),D(q)),{packageJson:jRe}=nt(),JRe=Eh(),{sendOperationToNode:QP}=(es(),D(Do)),{updateConfigCert:QRe}=rs(),{restartWorkers:XRe}=tt(),{databases:ZRe}=(Le(),D(rt)),{SYSTEM_TABLE_NAMES:jP,SYSTEM_SCHEMA_NAME:Ixe,CONFIG_PARAMS:Yh,OPERATIONS_ENUM:ms}=un,eye=1e4,tye="clone-node-config.yaml",jJ=[jP.ROLE_TABLE_NAME,jP.USER_TABLE_NAME,jP.NODE_TABLE_NAME],rye={clustering_nodename:!0,clustering_leafserver_streams_path:!0,clustering_tls_certificate:!0,clustering_tls_privatekey:!0,clustering_tls_certificateauthority:!0,logging_file:!0,logging_root:!0,logging_rotation_path:!0,operationsapi_network_domainsocket:!0,operationsapi_tls_certificate:!0,operationsapi_tls_privatekey:!0,operationsapi_tls_certificateauthority:!0,rootpath:!0,storage_path:!0,storage_audit_path:!0,databases:!0,mqtt_network_mtls_certificateauthority:!0,componentsroot:!0,tls_certificate:!0,tls_privatekey:!0,tls_certificateauthority:!0,replication_hostname:!0,replication_url:!0,cloned:!0},qr={HDB_LEADER_USERNAME:"HDB_LEADER_USERNAME",HDB_LEADER_PASSWORD:"HDB_LEADER_PASSWORD",HDB_LEADER_URL:"HDB_LEADER_URL",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",HDB_CLONE_OVERTOP:"HDB_CLONE_OVERTOP",CLONE_KEYS:"CLONE_KEYS",CLONE_USING_WS:"CLONE_USING_WS",NO_START:"NO_START"},ca=FRe(process.argv),_f=ca[qr.HDB_LEADER_USERNAME]??process.env[qr.HDB_LEADER_USERNAME],pf=ca[qr.HDB_LEADER_PASSWORD]??process.env[qr.HDB_LEADER_PASSWORD],nu=ca[qr.HDB_LEADER_URL]??process.env[qr.HDB_LEADER_URL],aa=ca[qr.REPLICATION_HOSTNAME]??process.env[qr.REPLICATION_HOSTNAME],JJ,QJ;aa&&([JJ,QJ]=aa.split(":"));var ZP=(ca[qr.HDB_CLONE_OVERTOP]??process.env[qr.HDB_CLONE_OVERTOP])==="true",XJ=ca[Yh.CLONED.toUpperCase()]??process.env[Yh.CLONED.toUpperCase()],nye=ca[qr.CLONE_KEYS]!=="false"&&process.env[qr.CLONE_KEYS]!=="false",ZJ=(ca[qr.CLONE_USING_WS]??process.env[qr.CLONE_USING_WS])==="true",e2=(ca[qr.NO_START]??process.env[qr.NO_START])==="true",hs,Sc={},$J,VJ,ru={},ln,Lt,$s,ro,su=!1,eD=!1,ps,hf;s2.exports=a(async function(t=!1,r=!1){if(console.info(`Starting clone node from leader node: ${nu}`),delete process.env.HDB_LEADER_URL,Lt=xA.getEnvCliRootPath(),!Lt)try{let i=Ks(HJ.homedir(),un.HDB_HOME_DIR_NAME,un.BOOT_PROPS_FILE_NAME);if(await Gt.pathExists(i)){let o=qRe(i);Lt=oa.parse(o.get(un.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)).dir}}catch{throw new Error("There was an error setting the clone default root path. Please set ROOTPATH using an environment or CLI variable.")}Lt?await Gt.pathExists(Lt)?console.log(`Existing HarperDB install found at ${Lt}. Clone node will only clone items that do not already exist on clone.`):(console.log(`No HarperDB install found at ${Lt} starting fresh clone`),su=!0):(console.log("No HarperDB install found, starting fresh clone"),su=!0),Lt||(Lt=Ks(HJ.homedir(),un.HDB_ROOT_DIR_NAME),console.log("Using default root path",Lt));let n;try{n=Ks(Lt,tye),hs=FJ.parseDocument(await Gt.readFile(n,"utf8"),{simpleKeys:!0}).toJSON(),console.log("Clone config file found")}catch{}let s=Ks(Lt,un.HDB_CONFIG_FILE);if(await Gt.pathExists(s))try{$J=FJ.parseDocument(await Gt.readFile(s,"utf8"),{simpleKeys:!0}).toJSON(),Sc=UA.flattenConfig($J)}catch(i){console.error("Error reading existing harperdb-config.yaml on clone",i)}if(aa){let i=new URL(nu);hf=`${i.protocol==="https:"?"wss://":"ws://"}${i.hostname}:${QJ||9933}`}if(ZJ){await sye();return}if(Sc?.cloned&&XJ!=="false")return console.log("Instance marked as cloned, clone will not run"),Vs.setCloneVar(!1),Vs.initSync(),BA();ln=await HA({operation:ms.DESCRIBE_ALL}),await r2(),Vs.setCloneVar(!1),Vs.setHdbBasePath(Lt),Gt.ensureDir(Vs.get(un.CONFIG_PARAMS.LOGGING_ROOT)),XP.initLogSettings(),await oye(),eD||await aye(),await uye(t,r),aa&&(await fye(),await t2()),console.info(`
|
|
134
134
|
Successfully cloned node: `+nu),(t||e2)&&process.exit()},"cloneNode");async function sye(){if(Sc?.cloned&&XJ!=="false")return console.log("Instance marked as cloned, clone will not run"),Vs.setCloneVar(!1),Vs.initSync(),BA();console.log("Cloning using WebSockets");let e=Tc("system"),t=Ks(e,"system.mdb"),r=Gt.existsSync(t);su||!r||ZP?(console.info("Clone node installing HarperDB"),process.env.TC_AGREEMENT="yes",process.env.ROOTPATH=Lt,process.env.HDB_ADMIN_USERNAME="clone-temp-admin",process.env.HDB_ADMIN_PASSWORD=GRe.randomBytes(10).toString("base64").slice(0,10),kA(!0),await WJ()):(Vs.setCloneVar(!1),Vs.initSync()),await BA(),await r2(!0),await QRe(),r||await ZRe.system.hdb_user.delete({username:"clone-temp-admin"}),await XRe(),await iye(),console.log("Adding node to the cluster");let s=await gd()({operation:ms.ADD_NODE,url:hf});console.log("Add node response: ",s),await t2(),console.log(`Successfully cloned node: ${nu} using WebSockets`),UA.updateConfigValue(Yh.CLONED,!0),e2&&process.exit()}a(sye,"cloneUsingWS");async function iye(){let e=a(i=>{let o=0;for(let c in i){let l=i[c];typeof l=="object"&&l.last_updated_record>o&&(o=l.last_updated_record)}return o},"findMostRecentTimestamp");console.log("Getting last updated record timestamp for all database");let t={},r=await HA({operation:"describe_database",database:"system"});t.system=e(r);let n=await HA({operation:"describe_all"});for(let i in n)typeof n[i]=="object"&&(t[i]=e(n[i]));let s=Ks(Lt,"tmp","lastUpdated.json");console.log("Writing last updated database timestamps to:",s),await Gt.outputJson(s,t)}a(iye,"getLastUpdatedRecord");async function HA(e){return ZJ?QP({url:hf},e,{rejectUnauthorized:!1}):JSON.parse((await _ye(e)).body)}a(HA,"leaderReq");async function t2(){try{if(nye!==!1){console.log("Cloning JWT keys");let e=oa.join(Lt,un.LICENSE_KEY_DIR_NAME),t=await QP({url:hf},{operation:ms.GET_KEY,name:".jwtPublic"},{rejectUnauthorized:!1});qJ(oa.join(e,un.JWT_ENUM.JWT_PUBLIC_KEY_NAME),t.message);let r=await QP({url:hf},{operation:ms.GET_KEY,name:".jwtPrivate"},{rejectUnauthorized:!1});qJ(oa.join(e,un.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r.message)}}catch(e){console.error("Error cloning JWT keys",e)}}a(t2,"cloneKeys");async function r2(e=!1){console.info("Cloning configuration"),VJ=await HA({operation:ms.GET_CONFIGURATION}),ru=UA.flattenConfig(VJ);let t=hs?.componentConfig?.exclude,r={rootpath:Lt};aa&&(r.replication_hostname=JJ);for(let i in ru)if(!(ru[i]!==null&&typeof ru[i]=="object"&&!(ru[i]instanceof Array)||rye[i])){if(i.includes("_package")||i.includes("_port")){if(ru[i]?.includes?.("hdb/components"))continue;if(t){let o=!1;for(let c of t)if(i.includes(c.name)){o=!0;break}if(o)continue}}Sc[i]||(r[i]=ru[i])}for(let i in Sc)i!=="databases"&&typeof Sc[i]=="object"&&!(Sc[i]instanceof Array)||(r[i]=Sc[i]);let n={};if(hs?.databaseConfig?.excludeDatabases&&hs.databaseConfig.excludeDatabases.forEach(i=>{n[i.database]=!0}),hs?.clusteringConfig?.excludeDatabases&&hs.clusteringConfig.excludeDatabases.forEach(i=>{n[i.database]=!0}),Object.keys(n).length>0){r.replication_databases=[],n.system||r.replication_databases.push("system");for(let i in ln)n[i]||r.replication_databases.push(i)}let s=KRe(Object.keys(un.CONFIG_PARAM_MAP),!0);Object.assign(r,s),e||(r.cloned=!0),UA.createConfigFile(r,!0)}a(r2,"cloneConfig");async function oye(){process.env.HDB_FETCH==="true"?(await lye(),process.env.NODE_TLS_REJECT_UNAUTHORIZED&&delete process.env.NODE_TLS_REJECT_UNAUTHORIZED):await cye()}a(oye,"cloneDatabases");async function aye(){if(console.info("Clone node installing HarperDB."),process.env.TC_AGREEMENT="yes",process.env.ROOTPATH=Lt,!_f)throw new Error("HDB_LEADER_USERNAME is undefined.");if(process.env.HDB_ADMIN_USERNAME=_f,!pf)throw new Error("HDB_LEADER_PASSWORD is undefined.");process.env.HDB_ADMIN_PASSWORD=pf,process.env.OPERATIONSAPI_NETWORK_PORT=Vs.get(Yh.OPERATIONSAPI_NETWORK_PORT),zRe(oa.join(Lt,un.HDB_CONFIG_FILE)),kA(!0),await WJ()}a(aye,"installHDB");function Tc(e){return Vs.get(un.CONFIG_PARAMS.DATABASES)?.[e]?.path||Vs.get(Yh.STORAGE_PATH)||oa.join(Lt,un.DATABASES_DIR_NAME)}a(Tc,"getDBPath");async function cye(){let e=Tc("system"),t=Ks(e,"system.mdb");if(await Kh(e),su||!await Gt.exists(t)||ZP){if(!aa){console.info("Cloning system database"),await Kh(e);let r=vA(t,{overwrite:!0}),n={operation:ms.GET_BACKUP,database:"system",tables:jJ},s=await KJ(n,r),i=new Date(s.date);(!ps||i<ps)&&(ps=i),await Gt.utimes(t,Date.now(),i)}su||(await zJ(Lt),await n2(),kA(!0))}else eD=!0,console.log("Not cloning system database due to it already existing on clone");$s=hs?.databaseConfig?.excludeDatabases,$s=$s?$s.reduce((r,n)=>({...r,[n.database]:!0}),{}):{};for(let r in ln)await Gt.exists(oa.join(Tc(r),r+".mdb"))&&(console.log(`Not cloning database ${r} due to it already existing on clone`),$s[r]=!0);ro=hs?.databaseConfig?.excludeTables,ro=ro?ro.reduce((r,n)=>({...r,[n.database==null?null:n.database+n.table]:!0}),{}):{};for(let r in ln){if($s[r]){ln[r]="excluded";continue}if(YJ.isEmpty(ln[r]))continue;let n=[],s=!1;for(let d in ln[r])ro[r+d]?(s=!0,ln[r][d]="excluded"):n.push(ln[r][d]);if(n.length===0)continue;if(aa){XP.debug("Setting up tables for #{db}");let d=(Le(),D(rt)).table;for(let _ of n){for(let p of _.attributes)(p.is_hash_attribute||p.is_primary_key)&&(p.isPrimaryKey=!0);d({database:r,table:_.name,attributes:_.attributes})}continue}n=n.map(d=>d.name);let i;s?(console.info(`Cloning database: ${r} tables: ${n}`),i={operation:ms.GET_BACKUP,database:r,tables:n}):(console.info(`Cloning database: ${r}`),i={operation:ms.GET_BACKUP,database:r});let o=Tc(r);await Kh(o);let c=Ks(o,r+".mdb"),l=vA(c,{overwrite:!0}),u=await KJ(i,l),f=new Date(u.date);(!ps||f<ps)&&(ps=f),await Gt.utimes(c,Date.now(),f)}}a(cye,"cloneTablesHttp");async function lye(){let e=Tc("system"),t=Ks(e,"system.mdb");if(su||!await Gt.exists(t)||ZP){if(!aa){console.info("Cloning system database using fetch");let r={operation:ms.GET_BACKUP,database:"system",tables:jJ},n=await JP(r,!0),s=Tc("system");await Kh(s);let i=Ks(s,"system.mdb");await GJ(n.body,vA(i,{overwrite:!0}));let o=new Date(n.headers.get("date"));(!ps||o<ps)&&(ps=o),await Gt.utimes(i,Date.now(),new Date(n.headers.get("date")))}su||(await zJ(Lt),await n2(),kA(!0))}else eD=!0,console.log("Not cloning system database due to it already existing on clone");if(aa){XP.info("Replication hostname set, not using backup to clone databases, replication will clone");return}$s=hs?.databaseConfig?.excludeDatabases,$s=$s?$s.reduce((r,n)=>({...r,[n.database]:!0}),{}):{};for(let r in ln)await Gt.exists(oa.join(Tc(r),r+".mdb"))&&(console.log(`Not cloning database ${r} due to it already existing on clone`),$s[r]=!0);ro=hs?.databaseConfig?.excludeTables,ro=ro?ro.reduce((r,n)=>({...r,[n.database==null?null:n.database+n.table]:!0}),{}):{};for(let r in ln){if($s[r]){ln[r]="excluded";continue}if(YJ.isEmpty(ln[r]))continue;let n=[],s=!1;for(let f in ln[r])ro[r+f]?(s=!0,ln[r][f]="excluded"):n.push(f);if(n.length===0)return;let i;s?(console.info(`Cloning database: ${r} tables: ${n}`),i=await JP({operation:ms.GET_BACKUP,database:r,tables:n},!0)):(console.info(`Cloning database: ${r}`),i=await JP({operation:ms.GET_BACKUP,database:r},!0));let o=Tc(r);await Kh(o);let c=new Date(i.headers.get("date")),l=Ks(o,`${c.getTime()}-${r}.mdb`);await GJ(i.body,vA(l,{overwrite:!0}));let u=Ks(o,r+".mdb");await Gt.rename(l,u),(!ps||c<ps)&&(ps=c),await Gt.utimes(u,Date.now(),c)}}a(lye,"cloneTablesFetch");async function JP(e,t=!1){let r=hs?.httpsRejectUnauthorized??!1,n=new MA.Agent({rejectUnauthorized:r});r||(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let i={Authorization:"Basic "+Buffer.from(_f+":"+pf).toString("base64"),"Content-Type":"application/json"};t&&(i["Accept-Encoding"]="gzip");let o=await fetch(nu,{method:"POST",headers:i,body:JSON.stringify(e),agent:n,compress:!0});if(o.ok)return o;throw console.error(`HTTP Error Response: ${o.status} ${o.statusText}`),new Error(await o.text())}a(JP,"leaderHttpReqFetch");async function uye(e,t=!1){let r=await $Re.getHDBProcessInfo();r.clustering.length===0||r.core.length===0?e?await WRe(!1):(t&&await dye(),await BA()):(console.info(await VRe({operation:ms.RESTART})),await xA.async_set_timeout(eye)),e&&await xA.async_set_timeout(2e3)}a(uye,"startHDB");async function dye(){let e=process.argv[3];e&&e[0]!=="-"&&(await Gt.exists(e)||console.error(`The folder ${e} does not exist`),Gt.statSync(e).isDirectory()||console.error(`The path ${e} is not a folder`),e=await Gt.realpath(e),await Gt.exists(oa.join(e,un.HDB_CONFIG_FILE))?process.env.ROOTPATH=e:process.env.RUN_HDB_APP=e)}a(dye,"setAppPath");async function fye(){console.info("Setting up replication"),await YRe.setSchemaDataToGlobalAsync();let t=await gd()({operation:ms.ADD_NODE,verify_tls:!1,url:hf,start_time:ps,authorization:{username:_f,password:pf}},!0);console.log("Add node response: ",t)}a(fye,"setupReplication");async function _ye(e){let t=new MA.Agent({rejectUnauthorized:hs?.httpsRejectUnauthorized??!1}),n={Authorization:"Basic "+Buffer.from(_f+":"+pf).toString("base64"),"Content-Type":"application/json"},s=new URL(nu),i={protocol:s.protocol,host:s.hostname,method:"POST",headers:n};return s.protocol==="https:"&&(i.agent=t),s.port&&(i.port=s.port),await xA.httpRequest(i,e)}a(_ye,"leaderHttpReq");async function KJ(e,t){let r=new MA.Agent({rejectUnauthorized:hs?.httpsRejectUnauthorized??!1}),s={Authorization:"Basic "+Buffer.from(_f+":"+pf).toString("base64"),"Content-Type":"application/json"},i=new URL(nu),o={protocol:i.protocol,host:i.hostname,method:"POST",headers:s};return i.protocol==="https:"&&(o.agent=r,kJ=MA),i.port&&(o.port=i.port),new Promise((c,l)=>{let u=kJ.request(o,f=>{f.statusCode!==200&&l("Request to leader node failed with code: "+f.statusCode),f.pipe(t),f.on("end",()=>{t.close(),c(f.headers)})});u.on("error",f=>{l(f)}),u.write(JSON.stringify(e)),u.end()})}a(KJ,"leaderHttpStream");async function n2(){let e=jRe.version;if(e)await JRe.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a(n2,"insertHdbVersionInfo")});var o2=P((Dxe,i2)=>{var pye=MT(),hye=z();i2.exports=mye;async function mye(){try{await pye.install()}catch(e){console.error("There was an error during the install."),console.error(e),hye.error(e),process.exit(1)}}a(mye,"install")});var l2=P((Mxe,c2)=>{"use strict";var Eye=TS(),gye=z(),a2="Registration failed.";async function Sye(){let e;try{e=await Eye.register()}catch(t){return gye.error(`Registration error ${t}`),a2}return e||a2}a(Sye,"register");c2.exports={register:Sye}});var _2=P((Uxe,f2)=>{"use strict";var Tye=z(),Aye=(k(),D(q)),Rye=require("util"),yye=require("child_process"),u2=Rye.promisify(yye.exec),bye=vo(),Wh=Cd(),d2="Stopping HarperDB.";f2.exports=Oye;async function Oye(){if(console.log(d2),Tye.notify(d2),await Wh.isServiceRegistered(Aye.PROCESS_DESCRIPTORS.HDB)){Wh.enterPM2Mode();let r=await Wh.getUniqueServicesList();for(let n in r)await Wh.stop(n)}await Wh.kill();let t=await bye.getHDBProcessInfo();t.clustering.forEach(r=>{u2(`kill ${r.pid}`)}),t.core.forEach(r=>{u2(`kill ${r.pid}`)})}a(Oye,"stop")});var m2=P((Bxe,h2)=>{"use strict";var nD=require("fs-extra"),sD=require("path"),rD=require("yaml"),zh=sr(),Ac=(k(),D(q)),p2=St(),iD=z(),Nye=On(),wye=pS(),Iye=fS(),Cye=vo(),jh=le(),Pye=Jd(),Dye=oe();jh.initSync();var Ys={RUNNING:"running",STOPPED:"stopped",ERRORED:"errored",NOT_INSTALLED:"not installed"},Bn={LEAF:"leaf server",HUB:"hub server"},FA;h2.exports=Lye;async function Lye(){let e={harperdb:{status:Ys.STOPPED}};if(!await Pye.isHdbInstalled()){e.harperdb.status=Ys.NOT_INSTALLED,console.log(rD.stringify(e));return}FA=jh.get(Ac.CONFIG_PARAMS.ROOTPATH);let t;try{t=Number.parseInt(await nD.readFile(sD.join(FA,Ac.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Ac.NODE_ERROR_CODES.ENOENT){iD.info("`harperdb status` did not find a hdb.pid file"),e.harperdb.status=Ys.STOPPED,console.log(rD.stringify(e));return}throw n}let r=await Cye.getHDBProcessInfo();for(let n of r.core)if(n.pid===t){e.harperdb.status=Ys.RUNNING,e.harperdb.pid=t;break}if((jh.get(Ac.CONFIG_PARAMS.REPLICATION_URL)||jh.get(Ac.CONFIG_PARAMS.REPLICATION_HOSTNAME))&&(e.replication=await vye()),e.clustering=await Mye(r),e.clustering[Bn.HUB].status===Ys.RUNNING&&e.clustering[Bn.LEAF].status===Ys.RUNNING){let n=[],s=await wye({});for(let o of s.nodes){let c={};for(let l in o)c[l.replace("_"," ")]=o[l];n.push(c)}e.clustering.network=n;let i=await Iye.clusterStatus();e.clustering.replication={"node name":i.node_name,"is enabled":i.is_enabled,connections:[]};for(let o of i.connections){let c={};c["node name"]=o?.node_name,c.status=o?.status,c.ports={clustering:o?.ports?.clustering,"operations api":o?.ports?.operations_api},c["latency ms"]=o?.latency_ms,c.uptime=o?.uptime,c.subscriptions=o?.subscriptions,c["system info"]={"hdb version":o?.system_info?.hdb_version,"node version":o?.system_info?.node_version,platform:o?.system_info?.platform},e.clustering.replication.connections.push(c)}await zh.closeConnection()}console.log(rD.stringify(e)),process.exit()}a(Lye,"status");async function Mye(e){let t={[Bn.HUB]:{},[Bn.LEAF]:{}};if(e.clustering.length===0)return t[Bn.HUB].status=Ys.STOPPED,t[Bn.LEAF].status=Ys.STOPPED,t;let{port:r}=zh.getServerConfig(Ac.PROCESS_DESCRIPTORS.CLUSTERING_HUB),{username:n,decrypt_hash:s}=await Nye.getClusterUser();try{(await zh.createConnection(r,n,s,!1)).close(),t[Bn.HUB].status=Ys.RUNNING}catch{t[Bn.HUB].status=Ys.ERRORED}let{port:i}=zh.getServerConfig(Ac.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);try{(await zh.createConnection(i,n,s,!1)).close(),t[Bn.LEAF].status=Ys.RUNNING}catch{t[Bn.LEAF].status=Ys.ERRORED}try{t[Bn.HUB].pid=Number.parseInt(await nD.readFile(sD.join(FA,"clustering",p2.PID_FILES.HUB),"utf8"))}catch(o){iD.error(o),t[Bn.HUB].pid=void 0}try{t[Bn.LEAF].pid=Number.parseInt(await nD.readFile(sD.join(FA,"clustering",p2.PID_FILES.LEAF),"utf8"))}catch(o){iD.error(o),t[Bn.LEAF].pid=void 0}return t}a(Mye,"getHubLeafStatus");async function vye(){let e=await Dye.httpRequest({method:"POST",protocol:"http:",socketPath:jh.get(Ac.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),headers:{"Content-Type":"application/json"}},{operation:"cluster_status"});e=JSON.parse(e.body);let t={"node name":e.node_name,"is enabled":e.is_enabled,connections:[]};for(let r of e.connections)t.connections.push({"node name":r.name,url:r.url,subscriptions:r.subscriptions,replicates:r.replicates,"database sockets":r.database_sockets.map(n=>({database:n.database,connected:n.connected,latency:n.latency,"catching up from":n.catching_up_from,"thread id":n.thread_id,nodes:n.nodes}))});return t}a(vye,"getReplicationStatus")});sm();var oD=process.env.HDB_LEADER_URL||process.argv.includes("--HDB_LEADER_URL");oD&&le().setCloneVar(!0);var Jh=require("node:fs"),E2=require("node:path"),iu=z(),g2=vJ(),{packageJson:Uye,PACKAGE_ROOT:S2}=nt(),xye=BJ(),aD=(k(),D(q)),{SERVICE_ACTIONS_ENUM:dn}=aD,Bye=`
|
|
135
135
|
Usage: harperdb [command]
|
|
136
136
|
|