harperdb 4.6.1 → 4.6.2

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.
@@ -31,7 +31,7 @@ Host ${s}
31
31
  `+u):await Ie.outputFile(l,u);let d="";if(await Ie.pathExists(Go)||(await Ie.writeFile(Go,""),await Ie.chmod(Go,"0600")),i=="github.com"&&!(await Ie.readFile(Go,"utf8")).includes("github.com"))try{let _=(await(await fetch("https://api.github.com/meta")).json()).ssh_keys;for(let g of _)Ie.appendFile(Go,"github.com "+g+`
32
32
  `)}catch{d=". Unable to get known hosts from github.com. Set your known hosts manually using set_ssh_known_hosts."}a&&await Ie.appendFile(Go,a);let f=await mi(e);return f.message=`Added ssh key: ${r}${d}`,f}o(uhe,"addSSHKey");async function dhe(e){let t=Un.updateSSHKeyValidator(e);if(t)throw Vt(t,t.message,Kt.BAD_REQUEST);let{name:r,key:n}=e;$t.trace("updating ssh key",r);let s=Pe.join(Qa,r+".key");if(!await Ie.pathExists(s))throw new Error("Key does not exist. Use add_ssh_key");await Ie.outputFile(s,n);let i=await mi(e);return i.message=`Updated ssh key: ${r}`,i}o(dhe,"updateSSHKey");async function fhe(e){let t=Un.deleteSSHKeyValidator(e);if(t)throw Vt(t,t.message,Kt.BAD_REQUEST);let{name:r}=e;$t.trace("deleting ssh key",r);let n=Pe.join(Qa,r+".key"),s=Pe.join(Qa,"config");if(!await Ie.pathExists(n))throw new Error("Key does not exist");let i=await Ie.readFile(s,"utf8"),a=new RegExp(`#${r}[\\S\\s]*?IdentitiesOnly yes`,"g");i=i.replace(a,""),await Ie.outputFile(s,i),Ie.removeSync(n);let c=await mi(e);return c.message=`Deleted ssh key: ${r}`,c}o(fhe,"deleteSSHKey");async function mhe(e){let t=[];return await Ie.pathExists(Qa)&&(await Ie.readdir(Qa)).forEach(r=>{r!="known_hosts"&&r!="config"&&t.push({name:r.split(".")[0]})}),t}o(mhe,"listSSHKeys");async function hhe(e){let t=Un.setSSHKnownHostsValidator(e);if(t)throw Vt(t,t.message,Kt.BAD_REQUEST);let{known_hosts:r}=e;await Ie.outputFile(Go,r);let n=await mi(e);return n.message="Known hosts successfully set",n}o(hhe,"setSSHKnownHosts");async function phe(e){return await Ie.pathExists(Go)?{known_hosts:await Ie.readFile(Go,"utf8")}:{known_hosts:null}}o(phe,"getSSHKnownHosts");tr.customFunctionsStatus=Qme;tr.getCustomFunctions=Jme;tr.getCustomFunction=Xme;tr.setCustomFunction=Zme;tr.dropCustomFunction=ehe;tr.addComponent=the;tr.dropCustomFunctionProject=rhe;tr.packageComponent=nhe;tr.deployComponent=she;tr.getComponents=ohe;tr.getComponentFile=ahe;tr.setComponentFile=che;tr.dropComponent=lhe;tr.addSSHKey=uhe;tr.updateSSHKey=dhe;tr.deleteSSHKey=fhe;tr.listSSHKeys=mhe;tr.setSSHKnownHosts=hhe;tr.getSSHKnownHosts=phe});var FO=M((Kve,X1)=>{"use strict";var Ls=require("joi"),J1=at();X1.exports={readTransactionLogValidator:Ehe,deleteTransactionLogsBeforeValidator:_he};function Ehe(e){let t=Ls.object({schema:Ls.string(),database:Ls.string(),table:Ls.string().required(),from:Ls.date().timestamp(),to:Ls.date().timestamp(),limit:Ls.number().min(1)});return J1.validateBySchema(e,t)}o(Ehe,"readTransactionLogValidator");function _he(e){let t=Ls.object({schema:Ls.string(),database:Ls.string(),table:Ls.string().required(),timestamp:Ls.date().timestamp().required()});return J1.validateBySchema(e,t)}o(_he,"deleteTransactionLogsBeforeValidator")});var KS=M((Wve,sK)=>{"use strict";var HO=(k(),v(K)),Wh=lr(),Z1=ie(),eK=ce(),tK=Di(),rK=z(),{handleHDBError:$S,hdbErrors:ghe}=Ee(),{HTTP_STATUS_CODES:VS}=ghe,{readTransactionLogValidator:She,deleteTransactionLogsBeforeValidator:The}=FO(),nK=Kn(),Rhe="Logs successfully deleted from transaction log.",yhe="All logs successfully deleted from transaction log.";sK.exports={readTransactionLog:Ahe,deleteTransactionLogsBefore:Ihe};async function Ahe(e){let t=She(e);if(t)throw $S(t,t.message,VS.BAD_REQUEST,void 0,void 0,!0);e.database=e.database??e.schema??"data";let r=Z1.checkSchemaTableExist(e.database,e.table);if(r)throw $S(new Error,r,VS.NOT_FOUND,void 0,void 0,!0);return eK.get(HO.CONFIG_PARAMS.CLUSTERING_ENABLED)?await bhe(e):(rK.info("Reading HarperDB logs used by Plexus"),(e.from||e.to)&&(e.search_type="timestamp",e.search_values=[e.from??0],e.to&&(e.search_values[1]=e.to)),nK.readAuditLog(e))}o(Ahe,"readTransactionLog");async function*bhe(e){let t=tK.createNatsTableStreamName(e.database,e.table),r=await Wh.viewStreamIterator(t,parseInt(e.from),e.limit);for await(let n of r){let s=Math.floor(n?.nats_timestamp/1e6);if(e.to&&s>e.to)break;let i={operation:n?.entry?.operation,user:n?.entry?.__origin?.user,timestamp:s,records:n?.entry?.records,attributes:n?.entry?.attributes};n?.entry?.operation===HO.OPERATIONS_ENUM.DELETE&&(i.hash_values=n?.entry?.hash_values),yield i}}o(bhe,"readTransactionLogNats");async function Ihe(e){let t=The(e);if(t)throw $S(t,t.message,VS.BAD_REQUEST,void 0,void 0,!0);if(e.database=e.database??e.schema??"data",!eK.get(HO.CONFIG_PARAMS.CLUSTERING_ENABLED))return rK.info("Delete transaction logs called for Plexus"),nK.deleteAuditLogsBefore(e);let{database:r,table:n,timestamp:s}=e,i=Z1.checkSchemaTableExist(r,n);if(i)throw $S(new Error,i,VS.NOT_FOUND,void 0,void 0,!0);let a=tK.createNatsTableStreamName(r,n),{jsm:c}=await Wh.getNATSReferences(),l=await Wh.getStreamInfo(a),u=new Date(l.state.first_ts).getTime();if(s<=u)return`No transactions exist before: ${s}`;let d=Rhe,f,m=new Date(l.state.last_ts).getTime();return s>m?(f=l.state.last_seq+1,d=yhe):f=(await Wh.viewStream(a,parseInt(s),1))[0].nats_sequence,await Wh.purgeTableStream(r,n,{seq:f}),d}o(Ihe,"deleteTransactionLogsBefore")});var $O={};Ce($O,{describeMetric:()=>uK,describeMetricOp:()=>qO,get:()=>cK,getOp:()=>kO,listMetrics:()=>lK,listMetricsOp:()=>GO});async function Nhe(e){return(await z_().get(e)).hostname}function iK(e,t){return e.length===0||e.includes(t)}function kO(e){return zh.trace?.("get_analytics request:",e),cK(e.metric,e.get_attributes,e.start_time,e.end_time,e.conditions)}function aK(e){return"conditions"in e?{...e,conditions:e.conditions.map(aK)}:{attribute:e.search_attribute??e.attribute,comparator:e.search_type??e.comparator,value:e.search_value??e.value}}async function cK(e,t,r,n,s){let i=[{attribute:"metric",comparator:"equals",value:e}];s&&i.push(...s.map(aK));let a=t??[];iK(a,"id")||a.push("id"),r&&i.push({attribute:"id",comparator:"greater_than_equal",value:r}),n&&i.push({attribute:"id",comparator:"less_than",value:n});let c={conditions:i};return a.length>0&&(c.select=a),zh.trace?.("get_analytics hdb_analytics.search request:",JSON.stringify(c)),(await databases.system.hdb_analytics.search(c)).map(async u=>{let d=u.id[1];return u.id=u.id[0],iK(a,"node")&&(zh.trace?.(`get_analytics lookup hostname for nodeId: ${d}`),u.node=await Nhe(d)),zh.trace?.("get_analytics result:",JSON.stringify(u)),u})}function GO(e){return lK(e.metric_types)}async function lK(e=["builtin"]){let t=[],r=Object.values(No);if(e.includes("builtin")&&(t=r),e.includes("custom")){let n=r.map(c=>({attribute:"metric",comparator:"not_equal",value:c})),s={select:["metric"],conditions:n},i=new Set,a=await databases.system.hdb_analytics.search(s);for await(let c of a)i.add(c.metric);t.push(...Array.from(i.values()))}return t}function qO(e){return uK(e.metric)}async function uK(e){let t={conditions:[{attribute:"metric",comparator:"equals",value:e}],sort:{attribute:"id",descending:!0},limit:1},r=databases.system.hdb_analytics.search(t),n=[{name:"node",type:"string"}];for await(let s of r){for(let a in s)n.push({name:a,type:typeof s[a]});let i={attributes:n};return zh.trace?.("describe_metric result:",JSON.stringify(i)),i}return{}}var oK,zh,VO=fe(()=>{oK=w(z());UI();xI();zh=(0,oK.forComponent)("analytics").conditional;o(Nhe,"lookupHostname");o(iK,"isSelected");o(kO,"getOp");o(aK,"conformCondition");o(cK,"get");o(GO,"listMetricsOp");o(lK,"listMetrics");o(qO,"describeMetricOp");o(uK,"describeMetric")});var YS,WS,jh,zS=fe(()=>{YS={primary:{allowedValues:null},maintenance:{allowedValues:null},availability:{allowedValues:["Available","Unavailable"]}},WS=Object.keys(YS),jh="primary"});function fK(e){return dK.validateBySchema(e,Phe)}var Qh,dK,whe,Ohe,Che,Phe,mK=fe(()=>{Qh=w(require("joi")),dK=w(at());zS();whe=WS,Ohe=Object.entries(YS).reduce((e,[t,r])=>(r.allowedValues&&(e[t]=`Status "${t}" only accepts these values: ${r.allowedValues.join(", ")}`),e),{}),Che=o(()=>{let e=Qh.default.string().min(1).max(512);return Object.entries(YS).forEach(([t,r])=>{r.allowedValues&&(e=e.when("id",{is:t,then:Qh.default.string().valid(...r.allowedValues).messages({"any.only":Ohe[t]})}))}),e.required()},"createStatusValidationSchema"),Phe=Qh.default.object({id:Qh.default.string().valid(...whe).required(),status:Che()});o(fK,"validateStatus")});var jO={};Ce(jO,{DEFAULT_STATUS_ID:()=>jh,STATUS_IDS:()=>WS,Status:()=>qo,clear:()=>YO,get:()=>WO,set:()=>zO});function Xh(){return KO||(KO=Ze({database:"system",table:"hdb_status",replicate:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"status"},{name:"__createdtime__"},{name:"__updatedtime__"}]})),KO}function YO({id:e}){return Jh.debug?.("clearStatus",e),Xh().delete(e)}function Dhe(){return Jh.debug?.("getAllStatus"),Xh().get({})}function WO({id:e}){return e?(Jh.debug?.("getStatus",e),Xh().get(e)):(Jh.debug?.("getStatus","all"),Dhe())}function zO({status:e,id:t=jh}){let r=fK({status:e,id:t});if(r)throw(0,jS.handleHDBError)(r,r.message,Lhe.BAD_REQUEST);return Jh.debug?.("setStatus",t,e),Xh().put(t,{status:e})}var jS,hK,Lhe,KO,qo,Jh,Zh=fe(()=>{Le();jS=w(Ee()),hK=w(Ii());mK();zS();zS();({HTTP_STATUS_CODES:Lhe}=jS.hdbErrors);o(Xh,"getStatusTable");qo={get primaryStore(){return Xh().primaryStore}},Jh=(0,hK.loggerWithTag)("status");o(YO,"clearStatus");o(Dhe,"getAllStatus");o(WO,"getStatus");o(zO,"setStatus")});var EK=M((dUe,pK)=>{"use strict";var QO=class{static{o(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};pK.exports=QO});var gK=M((mUe,_K)=>{"use strict";var JO=class{static{o(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};_K.exports=JO});var ZO=M((pUe,TK)=>{"use strict";var SK=EK(),Mhe=gK(),{HDB_ERROR_MSGS:vhe}=en(),XO=class{static{o(this,"PermissionResponseObject")}constructor(){this.error=vhe.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new SK(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Mhe(c,s[c]);i.push(l)});let a=`${r}_${n}`;if(this.unauthorized_access[a])this.unauthorized_access[a].required_attribute_permissions=i;else{let c=new SK(r,n,[],i);this.unauthorized_access[a]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};TK.exports=XO});var ZS=M((_Ue,BK)=>{"use strict";var eC=On(),QS=rn(),Ds=Jg(),rp=Ta(),tC=zc(),Uhe=sw(),xhe=bq(),np=zn(),JS=Fm(),yr=z(),Bhe=lw(),Fhe=lS(),Hhe=xw(),khe=dS(),Ghe=Hw(),qhe=kw(),$he=$w(),Vhe=Kw(),rC=ES(),$o=ie(),Khe=rV(),nC=sO(),AK=Pd(),En=(k(),v(K)),bK=E1(),Yhe=pd(),IK=($u(),v(jm)),NK=(BS(),v(Hh)),wK=At(),fr=UO(),Whe=require("alasql"),OK=KS(),CK=$h(),Ud=es(),PK=(_d(),v(Ed)),sC=(VO(),v($O)),iC=(Zh(),v(jO)),LK=ZO(),{handleHDBError:xn,hdbErrors:DK}=Ee(),{HDB_ERROR_MSGS:zr,HTTP_STATUS_CODES:ep}=DK,J=new Map,MK="delete",Ja="insert",Ms="read",Ul="update",tp="describe",RK=rp.describeSchema.name,yK=rp.describeTable.name,vK={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},zhe={insert:!0,delete:!0,deleteRecord:!0,update:!0,updateData:!0,upsert:!0,upsertData:!0},jhe="catchup",Qhe="handleGetJob",Jhe="handleGetJobsByStartDate",XS={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},Xhe=[Ds.createTable.name,Ds.createAttribute.name,Ds.dropTable.name,Ds.dropAttribute.name],UK={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},Z=class{static{o(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};J.set(eC.insert.name,new Z(!1,[Ja]));J.set(eC.update.name,new Z(!1,[Ul]));J.set(eC.upsert.name,new Z(!1,[Ja,Ul]));J.set(QS.searchByConditions.name,new Z(!1,[Ms]));J.set(QS.searchByHash.name,new Z(!1,[Ms]));J.set(QS.searchByValue.name,new Z(!1,[Ms]));J.set(QS.search.name,new Z(!1,[Ms]));J.set(Ds.createSchema.name,new Z(!0,[]));J.set(Ds.createTable.name,new Z(!0,[]));J.set(Ds.createAttribute.name,new Z(!1,[Ja]));J.set(Ds.dropSchema.name,new Z(!0,[]));J.set(Ds.dropTable.name,new Z(!0,[]));J.set(Ds.dropAttribute.name,new Z(!0,[]));J.set(rp.describeSchema.name,new Z(!1,[Ms]));J.set(rp.describeTable.name,new Z(!1,[Ms]));J.set(tC.deleteRecord.name,new Z(!1,[MK]));J.set(np.addUser.name,new Z(!0,[]));J.set(np.alterUser.name,new Z(!0,[]));J.set(np.dropUser.name,new Z(!0,[]));J.set(np.listUsersExternal.name,new Z(!0,[]));J.set(JS.listRoles.name,new Z(!0,[]));J.set(JS.addRole.name,new Z(!0,[]));J.set(JS.alterRole.name,new Z(!0,[]));J.set(JS.dropRole.name,new Z(!0,[]));J.set(Bhe.name,new Z(!0,[]));J.set(Fhe.name,new Z(!0,[]));J.set(Hhe.name,new Z(!0,[]));J.set(khe.name,new Z(!0,[]));J.set(Ghe.name,new Z(!0,[]));J.set(qhe.name,new Z(!0,[]));J.set(rC.setRoutes.name,new Z(!0,[]));J.set(rC.getRoutes.name,new Z(!0,[]));J.set(rC.deleteRoutes.name,new Z(!0,[]));J.set(wK.setConfiguration.name,new Z(!0,[]));J.set($he.clusterStatus.name,new Z(!0,[]));J.set(Vhe.name,new Z(!0,[]));J.set(nC.getFingerprint.name,new Z(!0,[]));J.set(nC.setLicense.name,new Z(!0,[]));J.set(tC.deleteFilesBefore.name,new Z(!0,[]));J.set(tC.deleteAuditLogsBefore.name,new Z(!0,[]));J.set(AK.restart.name,new Z(!0,[]));J.set(AK.restartService.name,new Z(!0,[]));J.set(Uhe.name,new Z(!0,[]));J.set(xhe.name,new Z(!0,[Ms]));J.set(Yhe.systemInformation.name,new Z(!0,[]));J.set(wK.getConfiguration.name,new Z(!0,[]));J.set(OK.readTransactionLog.name,new Z(!0,[]));J.set(OK.deleteTransactionLogsBefore.name,new Z(!0,[]));J.set(CK.installModules.name,new Z(!0,[]));J.set(CK.auditModules.name,new Z(!0,[]));J.set(Ud.createCsr.name,new Z(!0,[]));J.set(Ud.signCertificate.name,new Z(!0,[]));J.set(Ud.listCertificates.name,new Z(!0,[]));J.set(Ud.addCertificate.name,new Z(!0,[]));J.set(Ud.removeCertificate.name,new Z(!0,[]));J.set(Ud.getKey.name,new Z(!0,[]));J.set(PK.addNodeBack.name,new Z(!0,[]));J.set(PK.removeNodeBack.name,new Z(!0,[]));J.set(sC.getOp.name,new Z(!1,[Ms]));J.set(sC.listMetricsOp.name,new Z(!1,[Ms]));J.set(sC.describeMetricOp.name,new Z(!1,[Ms]));J.set(iC.clear.name,new Z(!0,[]));J.set(iC.get.name,new Z(!0,[]));J.set(iC.set.name,new Z(!0,[]));J.set(IK.createTokens.name,new Z(!1,[]));J.set(IK.refreshOperationToken.name,new Z(!1,[]));J.set(NK.login.name,new Z(!1,[]));J.set(NK.logout.name,new Z(!1,[]));J.set(fr.customFunctionsStatus.name,new Z(!0,[]));J.set(fr.getCustomFunctions.name,new Z(!0,[]));J.set(fr.getComponents.name,new Z(!0,[]));J.set(fr.getComponentFile.name,new Z(!0,[]));J.set(fr.setComponentFile.name,new Z(!0,[]));J.set(fr.dropComponent.name,new Z(!0,[]));J.set(fr.getCustomFunction.name,new Z(!0,[]));J.set(fr.setCustomFunction.name,new Z(!0,[]));J.set(fr.dropCustomFunction.name,new Z(!0,[]));J.set(fr.addComponent.name,new Z(!0,[]));J.set(fr.dropCustomFunctionProject.name,new Z(!0,[]));J.set(fr.packageComponent.name,new Z(!0,[]));J.set(fr.deployComponent.name,new Z(!0,[]));J.set(fr.addSSHKey.name,new Z(!0,[]));J.set(fr.updateSSHKey.name,new Z(!0,[]));J.set(fr.deleteSSHKey.name,new Z(!0,[]));J.set(fr.listSSHKeys.name,new Z(!0,[]));J.set(fr.setSSHKnownHosts.name,new Z(!0,[]));J.set(fr.getSSHKnownHosts.name,new Z(!0,[]));J.set(nC.getRegistrationInfo.name,new Z(!1,[]));J.set(np.userInfo.name,new Z(!1,[]));J.set(rp.describeAll.name,new Z(!1,[]));J.set(Qhe,new Z(!1,[]));J.set(Jhe,new Z(!0,[]));J.set(jhe,new Z(!0,[]));J.set(XS.CSV_DATA_LOAD,new Z(!1,[Ja,Ul]));J.set(XS.CSV_URL_LOAD,new Z(!1,[Ja,Ul]));J.set(XS.CSV_FILE_LOAD,new Z(!1,[Ja,Ul]));J.set(XS.IMPORT_FROM_S3,new Z(!1,[Ja,Ul]));J.set(UK.EXPORT_TO_S3,new Z(!0,[]));J.set(UK.EXPORT_LOCAL,new Z(!0,[]));J.set(En.VALID_SQL_OPS_ENUM.DELETE,new Z(!1,[MK]));J.set(En.VALID_SQL_OPS_ENUM.SELECT,new Z(!1,[Ms]));J.set(En.VALID_SQL_OPS_ENUM.INSERT,new Z(!1,[Ja]));J.set(En.VALID_SQL_OPS_ENUM.UPDATE,new Z(!1,[Ul]));BK.exports={verifyPerms:epe,verifyPermsAst:Zhe,verifyBulkLoadAttributePerms:rpe};function Zhe(e,t,r){if($o.isEmptyOrZeroLength(e))throw yr.info("verify_perms_ast has an empty user parameter"),xn(new Error);if($o.isEmptyOrZeroLength(t))throw yr.info("verify_perms_ast has an empty user parameter"),xn(new Error);if($o.isEmptyOrZeroLength(r))throw yr.info("verify_perms_ast has a null operation parameter"),xn(new Error);try{let n=new LK,s=new Khe(e),i=s.getSchemas(),a=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw yr.info("No schemas defined in verifyPermsAst(), will not continue."),xn(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&vK[r])throw xn(new Error,zr.DROP_SYSTEM,ep.FORBIDDEN);if(c&&!l)return null;let u=bK.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof Whe.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(u));for(let f=0;f<i.length;f++){let m=s.getTablesBySchemaName(i[f]);m&&a.set(i[f],m)}let d=xK(t,r,a,n);return d||(a.forEach((f,m)=>{for(let h=0;h<f.length;h++){let p=s.getAttributesBySchemaTableName(m,f[h]),_=aC(t.role.permission,m,f[h]);oC(p,_,r,f[h],m,n)}}),n.getPermsResponse())}catch(n){throw xn(n)}}o(Zhe,"verifyPermsAst");function epe(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw yr.info("null required parameter in verifyPerms"),xn(new Error,zr.DEFAULT_INVALID_REQUEST,ep.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,a=new Map;s&&i&&a.set(s,[i]);let c=new LK;if($o.isEmptyOrZeroLength(e.hdb_user?.role)||$o.isEmptyOrZeroLength(e.hdb_user?.role?.permission))return yr.info(`User ${e.hdb_user?.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(zr.USER_HAS_NO_PERMS(e.hdb_user?.username));let l=!!e.hdb_user?.role?.permission?.super_user,u=e.hdb_user?.role?.permission?.structure_user,d=a.has(En.SYSTEM_SCHEMA_NAME)||s===En.SYSTEM_SCHEMA_NAME;if(l&&d&&zhe[e.operation]&&(i===En.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME||i===En.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||i===En.SYSTEM_TABLE_NAMES.USER_TABLE_NAME))return null;if(d&&vK[r])throw xn(new Error,zr.DROP_SYSTEM,ep.FORBIDDEN);if(l&&!d||u===!0&&(r===Ds.createSchema.name||r===Ds.dropSchema.name))return null;if(Xhe.indexOf(r)>=0&&(u===!0||Array.isArray(u)))return u===!0||u.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let f=bK.getRolePermissions(e.hdb_user?.role);if(e.hdb_user?.role&&(e.hdb_user.role.permission=f),(r===RK||r===yK)&&!f.super_user){if(s===En.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(zr.SCHEMA_PERM_ERROR(s));if(r===RK&&(!f[s]||!f[s][tp]))return c.handleInvalidItem(zr.SCHEMA_NOT_FOUND(s));if(r===yK&&(!f[s]||!f[s].tables[i]||!f[s].tables[i][tp]))return c.handleInvalidItem(zr.TABLE_NOT_FOUND(s,i))}let m=xK(e.hdb_user,r,a,c,n);if(m)return m;if(J.get(r)&&J.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&En.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let _=[],g=f[s].tables[i];g[En.PERMS_CRUD_ENUM.READ]&&(g.attribute_permissions.length>0?g.attribute_permissions.filter(T=>T[En.PERMS_CRUD_ENUM.READ]).forEach(T=>{_.push(T.attribute_name)}):_=global.hdb_schema[s][i].attributes.map(y=>y.attribute),e.get_attributes=_)}let h=tpe(e),p=aC(e.hdb_user?.role?.permission,s,i);return oC(h,p,r,i,s,c,n),c.getPermsResponse()}o(epe,"verifyPerms");function xK(e,t,r,n,s){if($o.arrayHasEmptyValues([e,t,r]))throw yr.info("hasPermissions has an invalid parameter"),xn(new Error);let i=r.has("system"),a=e.role.permission;if(a.super_user&&(!i||J.get(t).requires_su))return null;if(!J.get(t))throw yr.info(`operation ${t} not found.`),xn(new Error,zr.OP_NOT_FOUND(t),ep.BAD_REQUEST);if(J.get(t)&&J.get(t).requires_su)return yr.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(zr.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!a[l]||a[l][tp]===!1){n.addInvalidItem(zr.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(zr.SCHEMA_NOT_FOUND(l));continue}let u=r.get(l);for(let d of u){let f=a[l].tables[d];if(!f||f[tp]===!1)n.addInvalidItem(zr.TABLE_NOT_FOUND(l,d));else try{let m=[],h=J.get(t).perms;!$o.isEmpty(s)&&h.includes(s)&&(h=[s]);for(let p=0;p<h.length;p++){let _=h[p],g=f[_];(g==null||g===!1)&&(yr.info(`Required ${_} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),m.push(_))}m.length>0&&n.addUnauthorizedTable(l,d,m)}catch(m){let h=zr.UNKNOWN_OP_AUTH_ERROR(t,l,d);throw yr.error(h),yr.error(m),xn(DK.CHECK_LOGS_WRAPPER(h))}}}return r.size<2?n.getPermsResponse():null}o(xK,"hasPermissions");function oC(e,t,r,n,s,i,a){if(!e||!t)throw yr.info("no attributes specified in checkAttributePerms."),xn(new Error);let c=J.get(r).perms;if(!c||c==="")throw yr.info(`no permissions found for ${r} in checkAttributePerms().`),xn(new Error);if($o.isEmptyOrZeroLength(t))return yr.info("No role permissions set (this is OK)."),null;a&&c.includes(a)&&(c=[a]);let l={};for(let d of e){let f=t.get(d);if(f){if(f[tp]===!1){i.addInvalidItem(zr.ATTR_NOT_FOUND(s,n,d),s,n);continue}if(c)for(let m of c){if(En.TIME_STAMP_NAMES.includes(f.attribute_name)&&m!==Ms)throw xn(new Error,zr.SYSTEM_TIMESTAMP_PERMS_ERR,ep.FORBIDDEN);f[m]===!1&&(l[f.attribute_name]?l[f.attribute_name].push(m):l[f.attribute_name]=[m])}}else i.addInvalidItem(zr.ATTR_NOT_FOUND(s,n,d),s,n)}let u=Object.keys(l);u.length>0&&i.addUnauthorizedAttributes(u,s,n,l)}o(oC,"checkAttributePerms");function tpe(e){let t=new Set;try{if(e.action)return t;if(e.operation===En.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){yr.info(r)}return t}o(tpe,"getRecordAttributes");function aC(e,t,r){let n=new Map;if($o.isEmpty(e))return yr.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{yr.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}o(aC,"getAttributePermissions");function rpe(e,t,r,n,s,i,a){let c=new Set(i),l=aC(e,n,s);oC(c,l,t,s,n,a,r)}o(rpe,"verifyBulkLoadAttributePerms")});var tT=M((SUe,qK)=>{"use strict";qK.exports={evaluateSQL:ppe,processAST:GK,convertSQLToAST:kK,checkASTPermissions:HK};var npe=On(),FK=require("util"),spe=FK.callbackify(npe.insert),ipe=rn().search,ope=uk().update,ape=FK.callbackify(ope),cpe=fk().convertDelete,Xa=require("alasql"),lpe=ZS(),eT=z(),upe=o_(),dpe=ie(),sp=(k(),v(K)),{hdbErrors:fpe,handleHDBError:cC}=Ee(),{HTTP_STATUS_CODES:lC}=fpe;upe(Xa);var mpe=403,hpe="There was a problem performing this insert. Please check the logs and try again.",uC=class{static{o(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function ppe(e,t){let r=e.parsed_sql_object;if(!r){r=kK(e.sql);let n,s=r.ast.statements[0];if(s instanceof Xa.yy.Insert?n=s.into.databaseid:s instanceof Xa.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Xa.yy.Update||s instanceof Xa.yy.Delete?n=s.table.databaseid:eT.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Xa.yy.Select)&&dpe.isEmptyOrZeroLength(n))return t("No schema specified",null)}GK(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}o(ppe,"evaluateSQL");function HK(e,t){let r;try{r=lpe.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}o(HK,"checkASTPermissions");function kK(e){let t=new uC;if(!e)throw cC(new Error,"The 'sql' parameter is missing from the request body",lC.BAD_REQUEST);try{let r=e.trim(),n=Xa.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
33
33
  `);throw n[1]?cC(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,lC.BAD_REQUEST):cC(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",lC.BAD_REQUEST)}return t}o(kK,"convertSQLToAST");function GK(e,t,r){try{let n=Epe;if(!e.bypass_auth&&!t.permissions_checked){let i=HK(e,t);if(i&&i.length>0)return r(mpe,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case sp.VALID_SQL_OPS_ENUM.SELECT:n=ipe,s=t.ast.statements[0];break;case sp.VALID_SQL_OPS_ENUM.INSERT:n=_pe;break;case sp.VALID_SQL_OPS_ENUM.UPDATE:n=ape;break;case sp.VALID_SQL_OPS_ENUM.DELETE:n=cpe;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,a)=>{if(i){r(i);return}r(null,a)})}catch(n){return r(n)}}o(GK,"processAST");function Epe(e,t){eT.info(e),t("unknown sql statement")}o(Epe,"nullFunction");function _pe({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(a=>a.columnid);try{s.records=gpe(i,e.values)}catch(a){return r(a)}spe(s,(a,c)=>{if(a)return r(a);try{delete c.new_attributes,delete c.txn_time}catch(l){eT.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}o(_pe,"convertInsert");function gpe(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Xa.compile(`SELECT ${s.toString()} AS [${sp.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw eT.error(r),new Error(hpe)}}o(gpe,"createDataObjects")});var EC=M((AUe,YK)=>{var iT=require("clone"),oT=at(),Spe=ie(),nT=(k(),v(K)),RUe=z(),dC=require("fs"),mC=require("joi"),{string:sT}=mC.types(),{hdbErrors:Tpe,handleHDBError:rT}=Ee(),{HDB_ERROR_MSGS:yUe,HTTP_STATUS_CODES:fC}=Tpe,{commonValidators:xd}=Ci(),$K=" is required",Rpe=["insert","update","upsert"],hC={database:{presence:!1,format:xd.schema_format,length:xd.schema_length},schema:{presence:!1,format:xd.schema_format,length:xd.schema_length},table:{presence:!0,format:xd.schema_format,length:xd.schema_length},action:{inclusion:{within:Rpe,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},ype={schema:sT.required(),table:sT.required(),action:sT.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Ape,AWS_SECRET:bpe,AWS_BUCKET:Ipe,AWS_FILE_KEY:Npe,REGION:wpe}=nT.S3_BUCKET_AUTH_KEYS,Ope={s3:{presence:!0},[`s3.${Ape}`]:{presence:!0,type:"String"},[`s3.${bpe}`]:{presence:!0,type:"String"},[`s3.${Ipe}`]:{presence:!0,type:"String"},[`s3.${Npe}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${wpe}`]:{presence:!0,type:"String"}},VK=iT(hC);VK.data.presence={message:$K};var KK=iT(hC);KK.file_path.presence={message:$K};var Cpe=Object.assign(iT(hC),Ope),pC=iT(ype);pC.csv_url=sT.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();pC.passthrough_headers=mC.object();function Ppe(e){let t=oT.validateObject(e,VK);return aT(e,t)}o(Ppe,"dataObject");function Lpe(e){let t=oT.validateBySchema(e,mC.object(pC));return aT(e,t)}o(Lpe,"urlObject");function Dpe(e){let t=oT.validateObject(e,KK);return aT(e,t)}o(Dpe,"fileObject");function Mpe(e){let t=oT.validateObject(e,Cpe);return aT(e,t)}o(Mpe,"s3FileObject");function aT(e,t){if(!t){let r=Spe.checkGlobalSchemaTable(e.schema,e.table);if(r)return rT(new Error,r,fC.BAD_REQUEST);if(e.operation===nT.OPERATIONS_ENUM.CSV_FILE_LOAD)try{dC.accessSync(e.file_path,dC.constants.R_OK|dC.constants.F_OK)}catch(n){return n.code===nT.NODE_ERROR_CODES.ENOENT?rT(n,`No such file or directory ${n.path}`,fC.BAD_REQUEST):n.code===nT.NODE_ERROR_CODES.EACCES?rT(n,`Permission denied ${n.path}`,fC.BAD_REQUEST):rT(n)}}return t}o(aT,"postValidateChecks");YK.exports={dataObject:Ppe,urlObject:Lpe,fileObject:Dpe,s3FileObject:Mpe}});var _C=M((IUe,WK)=>{"use strict";var ip=z(),cT=(k(),v(K));async function vpe(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===cT.OPERATIONS_ENUM.INSERT||t.operation===cT.OPERATIONS_ENUM.UPDATE||t.operation===cT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===cT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ip.info(i.message),i):i.http_resp_msg?(ip.error(`Error calling operation: ${e.name}`),ip.error(i.http_resp_msg),i):(ip.error(`Error calling operation: ${e.name}`),ip.error(i),i)}}o(vpe,"callOperationFunctionAsAwait");WK.exports={callOperationFunctionAsAwait:vpe}});var gC=M((wUe,jK)=>{"use strict";var{S3:Upe,GetObjectCommand:xpe}=require("@aws-sdk/client-s3");jK.exports={getFileStreamFromS3:Bpe,getS3AuthObj:zK};async function Bpe(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await zK(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new xpe(r))).Body}o(Bpe,"getFileStreamFromS3");function zK(e,t,r){return new Upe({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}o(zK,"getS3AuthObj")});var JK=M((CUe,QK)=>{"use strict";var SC=class{static{o(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,a,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=a,this.role_perms=c}},TC=class{static{o(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};QK.exports={BulkLoadFileObject:SC,BulkLoadDataObject:TC}});var yC=M((LUe,XK)=>{"use strict";var RC=class{static{o(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};XK.exports=RC});var OC=M((BUe,pY)=>{"use strict";var lT=On(),dT=EC(),Fpe=require("needle"),hi=(k(),v(K)),MUe=bt(),Bd=ie(),{handleHDBError:Yt,hdbErrors:aY}=Ee(),{HTTP_STATUS_CODES:jr,HDB_ERROR_MSGS:Ar,CHECK_LOGS_WRAPPER:Bl}=aY,Fd=z(),AC=require("papaparse");Bd.promisifyPapaParse();var pi=require("fs-extra"),Hpe=require("path"),{chain:ZK}=require("stream-chain"),eY=require("stream-json/streamers/StreamArray"),tY=require("stream-json/utils/Batch"),rY=require("stream-chain/utils/comp"),{finished:nY}=require("stream"),kpe=ce(),cY=_C(),Gpe=gC(),{BulkLoadFileObject:IC,BulkLoadDataObject:qpe}=JK(),NC=ZO(),{verifyBulkLoadAttributePerms:lY}=ZS(),vUe=yC(),UUe=lr(),xUe=Di(),{databases:$pe}=(Le(),v(ft)),{coerceType:Vpe}=(op(),v(EY)),sY="No records parsed from csv file.",xl=`${kpe.get("HDB_ROOT")}/tmp`,{schemaRegex:Kpe}=Ci(),iY=1024*1024*2,oY=5e3,Ype={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};pY.exports={csvDataLoad:Wpe,csvURLLoad:zpe,csvFileLoad:jpe,importFromS3:Qpe};async function Wpe(e,t){let r=dT.dataObject(e);if(r)throw Yt(r,r.message,jr.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=fY(e.schema,e.table),i=AC.parse(e.data,{header:!0,skipEmptyLines:!0,transform:bC.bind(null,s),dynamicTyping:!1}),a=new NC;e.hdb_user&&e.hdb_user?.role&&e.hdb_user?.role?.permission&&e.hdb_user?.role?.permission?.super_user!==!0&&lY(e.hdb_user?.role?.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,a);let c=a.getPermsResponse();if(c)throw Yt(new Error,c,jr.BAD_REQUEST,void 0,void 0,!0);let l=new qpe(e.action,e.schema,e.table,i.data);return n=await cY.callOperationFunctionAsAwait(mY,l,null),n.message===sY?sY:hY(n.records,n.number_written)}catch(s){throw Fl(s)}}o(Wpe,"csvDataLoad");async function zpe(e){let t=dT.urlObject(e);if(t)throw Yt(t,t.message,jr.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${xl}/${r}`;try{await Jpe(e,r)}catch(s){throw Fd.error(Ar.DOWNLOAD_FILE_ERR(r)+" - "+s),Yt(s,Bl(Ar.DOWNLOAD_FILE_ERR(r)))}try{let s=new IC(this.job_operation_function.name,e.action,e.schema,e.table,n,hi.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission),i=await wC(s);return await uT(n),i}catch(s){throw await uT(n),Fl(s)}}o(zpe,"csvURLLoad");async function jpe(e){let t=dT.fileObject(e);if(t)throw Yt(t,t.message,jr.BAD_REQUEST,void 0,void 0,!0);let r=new IC(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,hi.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission);try{return await wC(r)}catch(n){throw Fl(n)}}o(jpe,"csvFileLoad");async function Qpe(e){let t=dT.s3FileObject(e);if(t)throw Yt(t,t.message,jr.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Hpe.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${xl}/${s}`;let i=new IC(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user?.role?.permission);await Xpe(s,e);let a=await wC(i);return await uT(r),a}catch(n){throw await uT(r),Fl(n)}}o(Qpe,"importFromS3");async function Jpe(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Fpe("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw Yt(n,s,n.statusCode,hi.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}eEe(r,e.csv_url),await Zpe(t,r.raw)}o(Jpe,"downloadCSVFile");async function Xpe(e,t){try{let r=`${xl}/${e}`;await pi.mkdirp(xl),await pi.writeFile(`${xl}/${e}`,"",{flag:"a+"});let n=await pi.createWriteStream(r),s=await Gpe.getFileStreamFromS3(t);await new Promise((i,a)=>{s.on("error",function(c){a(c)}),s.pipe(n).on("error",function(c){a(c)}).on("close",function(){Fd.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fd.error(Ar.S3_DOWNLOAD_ERR+" - "+r),Yt(r,Bl(Ar.S3_DOWNLOAD_ERR))}}o(Xpe,"downloadFileFromS3");async function Zpe(e,t){try{await pi.mkdirp(xl),await pi.writeFile(`${xl}/${e}`,t)}catch(r){throw Fd.error(Ar.WRITE_TEMP_FILE_ERR),Yt(r,Bl(Ar.DEFAULT_BULK_LOAD_ERR))}}o(Zpe,"writeFileToTempFolder");async function uT(e){if(e)try{await pi.access(e),await pi.unlink(e)}catch{Fd.warn(`could not delete temp csv file at ${e}, file does not exist`)}}o(uT,"deleteTempFile");function eEe(e,t){if(e.statusCode!==aY.HTTP_STATUS_CODES.OK)throw Yt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,jr.BAD_REQUEST);if(!Ype[e.headers["content-type"]])throw Yt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,jr.BAD_REQUEST);if(!e.raw)throw Yt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,jr.BAD_REQUEST)}o(eEe,"validateURLResponse");async function wC(e){try{let t;switch(e.file_type){case hi.VALID_S3_FILE_TYPES.CSV:t=await tEe(e);break;case hi.VALID_S3_FILE_TYPES.JSON:t=await rEe(e);break;default:throw Yt(new Error,Ar.DEFAULT_BULK_LOAD_ERR,jr.BAD_REQUEST,hi.LOG_LEVELS.ERROR,Ar.INVALID_FILE_EXT_ERR(e))}return hY(t.records,t.number_written)}catch(t){throw Fl(t)}}o(wC,"fileLoad");async function uY(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let a={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await lT.validation(a);e.role_perms&&e.role_perms.super_user!==!0&&lY(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=Yt(c);r(l)}}o(uY,"validateChunk");async function dY(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Bd.autoCastJSONDeep(i),s&&s.pause();let a=n.meta?n.meta.fields:null;if(a)i.forEach(c=>{!Bd.isEmpty(c)&&!Bd.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(u=>c.add(u))}),a=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await cY.callOperationFunctionAsAwait(mY,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=Yt(c,Bl(Ar.INSERT_CSV_ERR),jr.INTERNAL_SERVER_ERROR,hi.LOG_LEVELS.ERROR,Ar.INSERT_CSV_ERR+" - "+c);r(l)}}o(dY,"insertChunk");async function tEe(e){let t={records:0,number_written:0},r=fY(e.schema,e.table);try{let n=new NC,s=pi.createReadStream(e.file_path,{highWaterMark:iY});s.setEncoding("utf8"),await AC.parsePromise(s,uY.bind(null,e,n),bC.bind(null,r));let i=n.getPermsResponse();if(i)throw Yt(new Error,i,jr.BAD_REQUEST);return s=pi.createReadStream(e.file_path,{highWaterMark:iY}),s.setEncoding("utf8"),await AC.parsePromise(s,dY.bind(null,e,t),bC.bind(null,r)),s.destroy(),t}catch(n){throw Yt(n,Bl(Ar.PAPA_PARSE_ERR),jr.INTERNAL_SERVER_ERROR,hi.LOG_LEVELS.ERROR,Ar.PAPA_PARSE_ERR+n)}}o(tEe,"callPapaParse");function fY(e,t){let r=$pe[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>Vpe(i,s));return n}o(fY,"createTransformMap");function bC(e,t,r){let n=e.get(r);return n?n(t):Bd.autoCast(t)}o(bC,"typeFunction");async function rEe(e){let t={records:0,number_written:0},r=o(n=>{throw n},"throwErr");try{let n=new NC,s=ZK([pi.createReadStream(e.file_path,{encoding:"utf-8"}),eY.withParser(),c=>c.value,new tY({batchSize:oY}),rY(async c=>{await uY(e,n,r,c)})]);await new Promise((c,l)=>{nY(s,u=>{u?l(u):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw Yt(new Error,i,jr.BAD_REQUEST);let a=ZK([pi.createReadStream(e.file_path,{encoding:"utf-8"}),eY.withParser(),c=>c.value,new tY({batchSize:oY}),rY(async c=>{await dY(e,t,r,c)})]);return await new Promise((c,l)=>{nY(a,u=>{u?l(u):c()}),a.resume()}),t}catch(n){throw Yt(n,Bl(Ar.INSERT_JSON_ERR),jr.INTERNAL_SERVER_ERROR,hi.LOG_LEVELS.ERROR,Ar.INSERT_JSON_ERR+n)}}o(rEe,"insertJson");async function mY(e){let t={};try{e.data&&e.data.length>0&&nEe(e.data[0])?t=await sEe(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fd.info(t.message))}catch(r){throw Fl(r)}return t}o(mY,"callBulkFileLoad");function nEe(e){let t=Object.keys(e);for(let r of t)if(!Kpe.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}o(nEe,"validateColumnNames");async function sEe(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=lT.insert;break;case"update":i=lT.update;break;case"upsert":i=lT.upsert;break;default:throw Yt(new Error,Ar.INVALID_ACTION_PARAM_ERR(n),jr.BAD_REQUEST,hi.LOG_LEVELS.ERROR,Ar.INVALID_ACTION_PARAM_ERR(n))}try{let a=await i(s),c;switch(n){case"insert":c=a.inserted_hashes;break;case"update":c=a.update_hashes;break;case"upsert":c=a.upserted_hashes;break;default:break}if(Array.isArray(a.skipped_hashes)&&a.skipped_hashes.length>0){let d=global.hdb_schema[t][r].hash_attribute,f=e.length;for(;f--;)a.skipped_hashes.indexOf(e[f][d])>=0&&e.splice(f,1)}let l=Bd.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:a.new_attributes}}catch(a){throw Fl(a)}}o(sEe,"bulkFileLoad");function hY(e,t){return`successfully loaded ${t} of ${e} records`}o(hY,"buildResponseMsg");function Fl(e){return Yt(e,Bl(Ar.DEFAULT_BULK_LOAD_ERR),jr.INTERNAL_SERVER_ERROR,hi.LOG_LEVELS.ERROR,Ar.DEFAULT_BULK_LOAD_ERR+" - "+e)}o(Fl,"buildTopLevelErrMsg")});var LC=M((HUe,bY)=>{"use strict";var PC=rn(),iEe=gC(),{AsyncParser:oEe}=require("json2csv"),fT=require("stream"),is=ie(),CC=require("fs-extra"),aEe=require("path"),vs=z(),{promisify:SY}=require("util"),ap=ie(),{handleHDBError:mr,hdbErrors:cEe}=Ee(),{HDB_ERROR_MSGS:Bn,HTTP_STATUS_CODES:hr}=cEe,{streamAsJSON:lEe}=(tA(),v(jM)),{Upload:uEe}=require("@aws-sdk/lib-storage"),{toCsvStream:dEe}=(mo(),v(Ev)),_Y=["search_by_value","search_by_hash","sql","search_by_conditions"],gY=["json","csv"],TY="json",RY="csv",fEe="Successfully exported JSON locally.",mEe="Successfully exported CSV locally.",hEe=1e3,pEe=PC.searchByHash,EEe=PC.searchByValue,_Ee=SY(fT.finished);bY.exports={export_to_s3:REe,export_local:gEe};async function gEe(e){vs.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=yY(e);if(!is.isEmpty(t))throw vs.error(t),mr(new Error,t,hr.BAD_REQUEST,void 0,void 0,!0);if(is.isEmpty(e.path))throw vs.error(Bn.MISSING_VALUE("path")),mr(new Error,Bn.MISSING_VALUE("path"),hr.BAD_REQUEST,void 0,void 0,!0);let r=(is.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(aEe.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=is.buildFolderPath(e.path,r);await SEe(e.path);let s=await AY(e);return await TEe(n,e.format,s)}o(gEe,"export_local");async function SEe(e){if(vs.trace("in confirmPath"),is.isEmptyOrZeroLength(e))throw mr(new Error,`Invalid path: ${e}`,hr.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await CC.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${directory_path}' does not exist`:r.code==="EACCES"?n=`access to path '${directory_path}' is denied`:n=r.message,vs.error(n),mr(new Error,n,hr.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${directory_path}' is not a directory, please supply a valid folder path`;throw vs.error(r),mr(new Error,r,hr.BAD_REQUEST,void 0,void 0,!0)}return!0}o(SEe,"confirmPath");async function TEe(e,t,r){if(vs.trace("in saveToLocal"),ap.isEmptyOrZeroLength(e))throw mr(new Error,Bn.INVALID_VALUE("file_path"),hr.BAD_REQUEST,void 0,void 0,!0);if(ap.isEmptyOrZeroLength(t))throw mr(new Error,Bn.INVALID_VALUE("Source format"),hr.BAD_REQUEST,void 0,void 0,!0);if(ap.isEmpty(r))throw mr(new Error,Bn.NOT_FOUND("Data"),hr.BAD_REQUEST,void 0,void 0,!0);if(t===TY){let n=CC.createWriteStream(e);return lEe(r).pipe(n),await _Ee(n),{message:fEe,path:e}}else if(t===RY){let n=CC.createWriteStream(e),s=fT.Readable.from(r),i={},a=r.getColumns?.();a&&(i.fields=a.map(d=>({label:d,value:d})));let c={objectMode:!0};return await new oEe(i,c).fromInput(s).toOutput(n).promise(!1),{message:mEe,path:e}}throw mr(new Error,Bn.INVALID_VALUE("format"),hr.BAD_REQUEST)}o(TEe,"saveToLocal");async function REe(e){if(!e.s3||Object.keys(e.s3).length===0)throw mr(new Error,Bn.MISSING_VALUE("S3 object"),hr.BAD_REQUEST);if(is.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw mr(new Error,Bn.MISSING_VALUE("aws_access_key_id"),hr.BAD_REQUEST);if(is.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw mr(new Error,Bn.MISSING_VALUE("aws_secret_access_key"),hr.BAD_REQUEST);if(is.isEmptyOrZeroLength(e.s3.bucket))throw mr(new Error,Bn.MISSING_VALUE("bucket"),hr.BAD_REQUEST);if(is.isEmptyOrZeroLength(e.s3.key))throw mr(new Error,Bn.MISSING_VALUE("key"),hr.BAD_REQUEST);if(is.isEmptyOrZeroLength(e.s3.region))throw mr(new Error,Bn.MISSING_VALUE("region"),hr.BAD_REQUEST);let t=yY(e);if(!is.isEmpty(t))throw mr(new Error,t,hr.BAD_REQUEST);vs.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await AY(e)}catch(l){throw vs.error(l),l}let n,s=await iEe.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,a=new fT.PassThrough;if(e.format===RY){i=e.s3.key+".csv";let l=dEe(r,r.getColumns?.());l.on("error",u=>{throw u}),l.pipe(a)}else if(e.format===TY){i=e.s3.key+".json";let l=new fT.Readable;l.pipe(a),l.on("error",f=>{throw f}),l.push("[");let u=r.length,d="";for(let[f,m]of r.entries()){let h=f===u-1?JSON.stringify(m):JSON.stringify(m)+",";d+=h,f!==0&&f%hEe===0&&(l.push(d),d="")}d.length!==0&&l.push(d),l.push("]"),l.push(null)}else throw mr(new Error,Bn.INVALID_VALUE("format"),hr.BAD_REQUEST);return new uEe({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:a}}).done()}o(REe,"export_to_s3");function yY(e){if(vs.trace("in exportCoreValidation"),is.isEmpty(e.format))return"format missing";if(gY.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${gY.join(", ")}`;let t=e.search_operation.operation;if(is.isEmpty(t))return"search_operation.operation missing";if(_Y.indexOf(t)<0)return`searchOperation.operation must be one of the following values: ${_Y.join(", ")}`}o(yY,"exportCoreValidation");async function AY(e){vs.trace("in getRecords");let t,r;if(ap.isEmpty(e.search_operation)||ap.isEmptyOrZeroLength(e.search_operation.operation))throw mr(new Error,Bn.INVALID_VALUE("Search operation"),hr.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=EEe;break;case"search_by_hash":t=pEe;break;case"search_by_conditions":t=PC.searchByConditions;break;case"sql":{let n=tT();t=SY(n.evaluateSQL);break}default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,vs.error(r),mr(new Error,r,hr.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}o(AY,"getRecords")});var NY=M((GUe,IY)=>{"use strict";var DC=class{static{o(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};IY.exports=DC});var CY=M(($Ue,OY)=>{"use strict";var yEe=(k(),v(K)),wY=require("moment"),AEe=require("uuid").v4,MC=class{static{o(this,"JobObject")}constructor(){this.id=AEe(),this.type=void 0,this.start_datetime=wY().valueOf(),this.created_datetime=wY().valueOf(),this.end_datetime=void 0,this.status=yEe.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};OY.exports=MC});var vC=M((KUe,BY)=>{"use strict";var bEe=require("uuid").v4,vY=On(),UY=rn(),IEe=ri(),NEe=Lu(),wEe=NY(),Ot=(k(),v(K)),OEe=CY(),CEe=ag(),Ei=z(),PEe=Gf(),Hd=ie(),{promisify:LEe}=require("util"),Hl=require("moment"),DEe=tT(),mT=EC(),PY=XA(),{deleteTransactionLogsBeforeValidator:MEe}=FO(),{handleHDBError:LY,hdbErrors:vEe,ClientError:UEe}=Ee(),{HTTP_STATUS_CODES:DY}=vEe,MY=UY.searchByValue,xEe=UY.searchByHash,BEe=vY.insert,FEe=LEe(DEe.evaluateSQL),HEe=vY.update;BY.exports={addJob:qEe,updateJob:VEe,handleGetJob:kEe,handleGetJobsByStartDate:GEe,getJobById:xY};async function kEe(e){if(e.id===void 0)throw new UEe("'id' is required");let t=await xY(e.id);return Hd.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}o(kEe,"handleGetJob");async function GEe(e){try{let t=await $Ee(e);if(Ei.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Hl(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Hl(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw Ei.error(r),new Error(r)}}o(GEe,"handleGetJobsByStartDate");async function qEe(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Hd.isEmptyOrZeroLength(e.operation)){let d="job parameter is invalid";return Ei.info(d),t.error=d,t}if(!Ot.JOB_TYPE_ENUM[e.operation])return Ei.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Ot.OPERATIONS_ENUM.CSV_FILE_LOAD:n=mT.fileObject(e);break;case Ot.OPERATIONS_ENUM.CSV_URL_LOAD:n=mT.urlObject(e);break;case Ot.OPERATIONS_ENUM.CSV_DATA_LOAD:n=mT.dataObject(e);break;case Ot.OPERATIONS_ENUM.IMPORT_FROM_S3:n=mT.s3FileObject(e);break;case Ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=PY(e,"date");break;case Ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=PY(e,"timestamp");break;case Ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=MEe(e);break;case Ot.OPERATIONS_ENUM.RESTART_SERVICE:if(Ot.HDB_PROCESS_SERVICES[e.service]===void 0)throw LY(new Error,"Invalid service",DY.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw LY(n,n.message,DY.BAD_REQUEST,void 0,void 0,!0);let s=new OEe;s.type=e.operation===Ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user?.username;let i=new IEe(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),a;try{a=Array.from(await MY(i))}catch(d){let f=`There was an error inserting a new job: ${d}`;return Ei.error(f),t}let c=Array.isArray(a)?a:Object.keys(a);if(c&&c.length>0){s.id=bEe();try{a=await MY(i)}catch(d){let f=`There was an error inserting a new job: ${d}`;return Ei.error(f),t}if(c=Array.isArray(a)?a:Object.keys(a),c&&c.length>0)return Ei.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new PEe(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),u;try{u=await BEe(l)}catch(d){return Ei.error(`There was an error inserting a job for job type: ${e.operation} -- ${d}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let d=`Created a job with type ${s.type} and id ${s.id}`;t.message=d,t.createdJob=s,t.success=!0,Ei.trace(d)}return t}o(qEe,"addJob");async function $Ee(e){let t=Hl(e.from_date,Hl.ISO_8601),r=Hl(e.to_date,Hl.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new wEe(n,e.hdb_user);try{return await FEe(s)}catch(i){throw Ei.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}o($Ee,"getJobsInDateRange");async function xY(e){if(Hd.isEmptyOrZeroLength(e))return Hd.errorizeMessage("Invalid job ID specified.");let t=new NEe(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await xEe(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Ei.error(n),Hd.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}o(xY,"getJobById");async function VEe(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Hd.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Ot.JOB_STATUS_ENUM.COMPLETE||e.status===Ot.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Hl().valueOf());let t=new CEe(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await HEe(t),r}o(VEe,"updateJob")});var KY=M((WUe,VY)=>{"use strict";var FY=ie(),br=(k(),v(K)),KEe=require("moment"),hT=OC(),cp=z(),HY=vC(),kY=LC(),GY=zc(),qY=st(),YEe=KS(),WEe=Pd(),{parentPort:zEe,isMainThread:$Y}=require("worker_threads"),{onMessageByType:jEe}=st(),UC=class{static{o(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function QEe(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(FY.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(FY.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case br.JOB_TYPE_ENUM.csv_file_load:await Vi(e,hT.csvFileLoad);break;case br.JOB_TYPE_ENUM.csv_url_load:await Vi(e,hT.csvURLLoad);break;case br.JOB_TYPE_ENUM.csv_data_load:await Vi(e,hT.csvDataLoad);break;case br.JOB_TYPE_ENUM.import_from_s3:await Vi(e,hT.importFromS3);break;case br.JOB_TYPE_ENUM.empty_trash:break;case br.JOB_TYPE_ENUM.export_local:await Vi(e,kY.export_local);break;case br.JOB_TYPE_ENUM.export_to_s3:await Vi(e,kY.export_to_s3);break;case br.JOB_TYPE_ENUM.delete_files_before:case br.JOB_TYPE_ENUM.delete_records_before:await Vi(e,GY.deleteFilesBefore);break;case br.JOB_TYPE_ENUM.delete_audit_logs_before:await Vi(e,GY.deleteAuditLogsBefore);break;case br.JOB_TYPE_ENUM.delete_transaction_logs_before:await Vi(e,YEe.deleteTransactionLogsBefore);break;case br.JOB_TYPE_ENUM.restart_service:return await Vi(e,WEe.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}o(QEe,"parseMessage");async function Vi(e,t){try{e.job.status=br.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=KEe().valueOf(),await HY.updateJob(e.job),await JEe(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):cp.error(`There was an error running ${t.name} job with id ${e.job.id}`),cp.error(n),e.job.message=n,e.job.status=br.JOB_STATUS_ENUM.ERROR;try{await HY.updateJob(e.job)}catch(s){throw cp.error(`Unable to update job with id ${e.job.id}`),s}throw r}}o(Vi,"runJob");async function JEe(e){cp.trace("launching job thread:",e),$Y?qY.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[br.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):zEe.postMessage({type:br.ITC_EVENT_TYPES.START_JOB,jobId:e})}o(JEe,"launchJobThread");$Y&&jEe(br.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{qY.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[br.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){cp.error(r)}});VY.exports={parseMessage:QEe,RunnerMessage:UC}});var WY=M((jUe,YY)=>{"use strict";var XEe=ie(),xC=ce(),Za=(k(),v(K)),ZEe=bt(),e_e=lr(),Ki=z(),t_e=yC(),r_e=Di();xC.initSync();YY.exports={postOperationHandler:s_e,sendOperationTransaction:lp};async function lp(e,t,r,n){if(e.schema===Za.SYSTEM_SCHEMA_NAME)return;let s=n_e(e,t,r);s&&(Ki.trace(`sendOperationTransaction publishing to schema ${e.schema} following transaction:`,s),await e_e.publishToStream(`${ZEe.SUBJECT_PREFIXES.TXN}.${e.schema}`,r_e.createNatsTableStreamName(e.schema,e.table),n,s))}o(lp,"sendOperationTransaction");function n_e(e,t,r){if(XEe.isEmptyOrZeroLength(t))return null;let n={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===Za.OPERATIONS_ENUM.DELETE?n.hash_values=t:n.records=e.records,n}o(n_e,"convertCRUDOperationToTransaction");async function s_e(e,t,r){if(!xC.get(Za.CONFIG_PARAMS.CLUSTERING_ENABLED))return;Ki.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let n=e.hdb_user?.username,s=xC.get(Za.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new t_e(t.txn_time,n,s);switch(e.operation){case Za.OPERATIONS_ENUM.INSERT:try{await lp(e,t.inserted_hashes,i,r)}catch(a){Ki.error("There was an error calling clustering postOperationHandler for insert."),Ki.error(a)}break;case Za.OPERATIONS_ENUM.DELETE:try{await lp(e,t.deleted_hashes,i,r)}catch(a){Ki.error("There was an error calling clustering postOperationHandler for delete."),Ki.error(a)}break;case Za.OPERATIONS_ENUM.UPDATE:try{await lp(e,t.update_hashes,i,r)}catch(a){Ki.error("There was an error calling clustering postOperationHandler for update."),Ki.error(a)}break;case Za.OPERATIONS_ENUM.UPSERT:try{await lp(e,t.upserted_hashes,i,r)}catch(a){Ki.error("There was an error calling clustering postOperationHandler for upsert."),Ki.error(a)}break;default:break}return t}o(s_e,"postOperationHandler")});var Q,zY=fe(()=>{Q=class{static{o(this,"OperationFunctionObject")}operation_function;job_operation_function;constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}}});var xO={};Ce(xO,{chooseOperation:()=>mW,executeJob:()=>Us,getOperationFunction:()=>hW,operation:()=>KC,processLocalTransaction:()=>fW});async function fW(e,t){try{if(e.body.operation!=="read_log"&&(mp.default.log_level===Df.INFO||mp.default.log_level===Df.DEBUG||mp.default.log_level===Df.TRACE)){let{hdb_user:n,hdbAuthHeader:s,password:i,payload:a,...c}=e.body;_n.info(c)}}catch(n){_n.error(n)}let r=await uW.default.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return a_e[e.body.operation]&&oW.default.setSchemaDataToGlobal(n=>{n&&_n.error(n)}),r}function mW(e){let t;try{t=hW(e)}catch(s){throw _n.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=_T.default.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let a=_T.default.checkASTPermissions(e,i);if(a)throw _n.error(`${jY.FORBIDDEN} from operation ${e.operation}`),_n.warn(`User '${e.hdb_user?.username}' is not permitted to ${e.operation}`),(0,xs.handleHDBError)(new Error,a,xs.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==G.CREATE_AUTHENTICATION_TOKENS&&e.operation!==G.LOGIN&&e.operation!==G.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let a=iW.default.verifyPerms(i,s);if(a)throw _n.error(`${jY.FORBIDDEN} from operation ${e.operation}`),_n.warn(`User '${i.hdb_user?.username}' is not permitted to ${i.operation}`),(0,xs.handleHDBError)(new Error,a,xs.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw(0,xs.handleHDBError)(s,"There was an error when trying to choose an operation path")}return r}function hW(e){if(_n.trace(`getOperationFunction with operation: ${e.operation}`),QY.has(e.operation))return QY.get(e.operation);throw(0,xs.handleHDBError)(new Error,xs.hdbErrors.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),xs.hdbErrors.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}function KC(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=mW(e);return fW({body:e},n)}async function c_e(e){_n.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[Uy]=!0;let a;switch(i.operation){case G.INSERT:a=await Gl.default.insert(i);break;case G.UPDATE:a=await Gl.default.update(i);break;case G.UPSERT:a=await Gl.default.upsert(i);break;case G.DELETE:a=await qd.default.deleteRecord(i);break;default:_n.warn("invalid operation in catchup");break}await dW.transactToClusteringUtils.postOperationHandler(i,a,e)}catch(a){_n.info("Invalid operation in transaction"),_n.error(a)}}async function Us(e){(0,lW.transformReq)(e);let t,r;try{if(r=await gT.default.addJob(e),r){t=r.createdJob,_n.info("addJob result",r);let n=new kC.default.RunnerMessage(t,e);return{message:await kC.default.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}}catch(n){let s=n instanceof Error?n:null,i=`There was an error executing job: ${s&&"http_resp_msg"in s?s.http_resp_msg:n}`;throw _n.error(i),(0,xs.handleHDBError)(n,i)}}function l_e(){let e=new Map;return e.set(G.INSERT,new Q(Gl.default.insert)),e.set(G.UPDATE,new Q(Gl.default.update)),e.set(G.UPSERT,new Q(Gl.default.upsert)),e.set(G.SEARCH_BY_CONDITIONS,new Q(Gd.default.searchByConditions)),e.set(G.SEARCH_BY_HASH,new Q(Gd.default.searchByHash)),e.set(G.SEARCH_BY_ID,new Q(Gd.default.searchByHash)),e.set(G.SEARCH_BY_VALUE,new Q(Gd.default.searchByValue)),e.set(G.SEARCH,new Q(i_e)),e.set(G.SQL,new Q(o_e)),e.set(G.CSV_DATA_LOAD,new Q(Us,up.default.csvDataLoad)),e.set(G.CSV_FILE_LOAD,new Q(Us,up.default.csvFileLoad)),e.set(G.CSV_URL_LOAD,new Q(Us,up.default.csvURLLoad)),e.set(G.IMPORT_FROM_S3,new Q(Us,up.default.importFromS3)),e.set(G.CREATE_SCHEMA,new Q(Yi.default.createSchema)),e.set(G.CREATE_DATABASE,new Q(Yi.default.createSchema)),e.set(G.CREATE_TABLE,new Q(Yi.default.createTable)),e.set(G.CREATE_ATTRIBUTE,new Q(Yi.default.createAttribute)),e.set(G.DROP_SCHEMA,new Q(Yi.default.dropSchema)),e.set(G.DROP_DATABASE,new Q(Yi.default.dropSchema)),e.set(G.DROP_TABLE,new Q(Yi.default.dropTable)),e.set(G.DROP_ATTRIBUTE,new Q(Yi.default.dropAttribute)),e.set(G.DESCRIBE_SCHEMA,new Q(dp.default.describeSchema)),e.set(G.DESCRIBE_DATABASE,new Q(dp.default.describeSchema)),e.set(G.DESCRIBE_TABLE,new Q(dp.default.describeTable)),e.set(G.DESCRIBE_ALL,new Q(dp.default.describeAll)),e.set(G.DELETE,new Q(qd.default.deleteRecord)),e.set(G.ADD_USER,new Q(kd.default.addUser)),e.set(G.ALTER_USER,new Q(kd.default.alterUser)),e.set(G.DROP_USER,new Q(kd.default.dropUser)),e.set(G.LIST_USERS,new Q(kd.default.listUsersExternal)),e.set(G.LIST_ROLES,new Q(fp.default.listRoles)),e.set(G.ADD_ROLE,new Q(fp.default.addRole)),e.set(G.ALTER_ROLE,new Q(fp.default.alterRole)),e.set(G.DROP_ROLE,new Q(fp.default.dropRole)),e.set(G.USER_INFO,new Q(kd.default.userInfo)),e.set(G.READ_LOG,new Q(XY.default)),e.set(G.ADD_NODE,new Q(ZY.default)),e.set(G.UPDATE_NODE,new Q(BC.default)),e.set(G.SET_NODE_REPLICATION,new Q(BC.default)),e.set(G.REMOVE_NODE,new Q(eW.default)),e.set(G.CONFIGURE_CLUSTER,new Q(tW.default)),e.set(G.PURGE_STREAM,new Q(rW.default)),e.set(G.SET_CONFIGURATION,new Q(GC.default.setConfiguration)),e.set(G.CLUSTER_STATUS,new Q(nW.default.clusterStatus)),e.set(G.CLUSTER_NETWORK,new Q(sW.default)),e.set(G.CLUSTER_SET_ROUTES,new Q(pT.default.setRoutes)),e.set(G.CLUSTER_GET_ROUTES,new Q(pT.default.getRoutes)),e.set(G.CLUSTER_DELETE_ROUTES,new Q(pT.default.deleteRoutes)),e.set(G.EXPORT_TO_S3,new Q(Us,FC.default.export_to_s3)),e.set(G.CREATE_CSR,new Q(kl.default.createCsr)),e.set(G.SIGN_CERTIFICATE,new Q(kl.default.signCertificate)),e.set(G.LIST_CERTIFICATES,new Q(kl.default.listCertificates)),e.set(G.ADD_CERTIFICATES,new Q(kl.default.addCertificate)),e.set(G.REMOVE_CERTIFICATE,new Q(kl.default.removeCertificate)),e.set(G.GET_KEY,new Q(kl.default.getKey)),e.set(G.ADD_NODE_BACK,new Q(Pw)),e.set(G.REMOVE_NODE_BACK,new Q(Lw)),e.set(G.DELETE_FILES_BEFORE,new Q(Us,qd.default.deleteFilesBefore)),e.set(G.DELETE_RECORDS_BEFORE,new Q(Us,qd.default.deleteFilesBefore)),e.set(G.EXPORT_LOCAL,new Q(Us,FC.default.export_local)),e.set(G.SEARCH_JOBS_BY_START_DATE,new Q(gT.default.handleGetJobsByStartDate)),e.set(G.GET_JOB,new Q(gT.default.handleGetJob)),e.set(G.GET_FINGERPRINT,new Q(ET.default.getFingerprint)),e.set(G.SET_LICENSE,new Q(ET.default.setLicense)),e.set(G.GET_REGISTRATION_INFO,new Q(ET.default.getRegistrationInfo)),e.set(G.RESTART,new Q(HC.default.restart)),e.set(G.RESTART_SERVICE,new Q(Us,HC.default.restartService)),e.set(G.CATCHUP,new Q(c_e)),e.set(G.SYSTEM_INFORMATION,new Q(aW.default.systemInformation)),e.set(G.DELETE_AUDIT_LOGS_BEFORE,new Q(Us,qd.default.deleteAuditLogsBefore)),e.set(G.READ_AUDIT_LOG,new Q(JY.default)),e.set(G.CREATE_AUTHENTICATION_TOKENS,new Q(tN)),e.set(G.REFRESH_OPERATION_TOKEN,new Q(rN)),e.set(G.LOGIN,new Q(OO)),e.set(G.LOGOUT,new Q(CO)),e.set(G.GET_CONFIGURATION,new Q(GC.default.getConfiguration)),e.set(G.CUSTOM_FUNCTIONS_STATUS,new Q(Ct.default.customFunctionsStatus)),e.set(G.GET_CUSTOM_FUNCTIONS,new Q(Ct.default.getCustomFunctions)),e.set(G.GET_COMPONENT_FILE,new Q(Ct.default.getComponentFile)),e.set(G.GET_COMPONENTS,new Q(Ct.default.getComponents)),e.set(G.SET_COMPONENT_FILE,new Q(Ct.default.setComponentFile)),e.set(G.DROP_COMPONENT,new Q(Ct.default.dropComponent)),e.set(G.GET_CUSTOM_FUNCTION,new Q(Ct.default.getCustomFunction)),e.set(G.SET_CUSTOM_FUNCTION,new Q(Ct.default.setCustomFunction)),e.set(G.DROP_CUSTOM_FUNCTION,new Q(Ct.default.dropCustomFunction)),e.set(G.ADD_CUSTOM_FUNCTION_PROJECT,new Q(Ct.default.addComponent)),e.set(G.ADD_COMPONENT,new Q(Ct.default.addComponent)),e.set(G.DROP_CUSTOM_FUNCTION_PROJECT,new Q(Ct.default.dropCustomFunctionProject)),e.set(G.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Q(Ct.default.packageComponent)),e.set(G.PACKAGE_COMPONENT,new Q(Ct.default.packageComponent)),e.set(G.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Q(Ct.default.deployComponent)),e.set(G.DEPLOY_COMPONENT,new Q(Ct.default.deployComponent)),e.set(G.READ_TRANSACTION_LOG,new Q(qC.default.readTransactionLog)),e.set(G.DELETE_TRANSACTION_LOGS_BEFORE,new Q(Us,qC.default.deleteTransactionLogsBefore)),e.set(G.INSTALL_NODE_MODULES,new Q($C.default.installModules)),e.set(G.AUDIT_NODE_MODULES,new Q($C.default.auditModules)),e.set(G.GET_BACKUP,new Q(Yi.default.getBackup)),e.set(G.ADD_SSH_KEY,new Q(Ct.default.addSSHKey)),e.set(G.UPDATE_SSH_KEY,new Q(Ct.default.updateSSHKey)),e.set(G.DELETE_SSH_KEY,new Q(Ct.default.deleteSSHKey)),e.set(G.LIST_SSH_KEYS,new Q(Ct.default.listSSHKeys)),e.set(G.SET_SSH_KNOWN_HOSTS,new Q(Ct.default.setSSHKnownHosts)),e.set(G.GET_SSH_KNOWN_HOSTS,new Q(Ct.default.getSSHKnownHosts)),e.set(G.GET_ANALYTICS,new Q(kO)),e.set(G.LIST_METRICS,new Q(GO)),e.set(G.DESCRIBE_METRIC,new Q(qO)),e.set(G.GET_STATUS,new Q(WO)),e.set(G.SET_STATUS,new Q(zO)),e.set(G.CLEAR_STATUS,new Q(YO)),e}var Gd,_T,up,Yi,dp,qd,JY,kd,fp,Ct,mp,XY,ZY,BC,eW,tW,rW,nW,sW,pT,FC,iW,gT,xs,ET,HC,VC,Gl,oW,aW,kC,GC,qC,$C,cW,lW,kl,uW,dW,jY,_n,i_e,o_e,a_e,QY,BO=fe(()=>{Gd=w(rn()),_T=w(tT()),up=w(OC()),Yi=w(Jg()),dp=w(Ta()),qd=w(zc()),JY=w(sw()),kd=w(zn()),fp=w(Fm()),Ct=w(UO()),mp=w(z()),XY=w(lw()),ZY=w(lS()),BC=w(xw()),eW=w(dS()),tW=w(Hw()),rW=w(kw()),nW=w($w()),sW=w(Kw()),pT=w(ES()),FC=w(LC()),iW=w(ZS()),gT=w(vC());k();xs=w(Ee()),ET=w(sO()),HC=w(Pd()),VC=w(require("util")),Gl=w(On()),oW=w(Js()),aW=w(pd()),kC=w(KY());$u();BS();GC=w(At()),qC=w(KS()),$C=w($h());op();cW=w(Ws()),lW=w(ie());Pr();kl=w(es());_d();VO();uW=w(_C()),dW=w(WY());Zh();zY();({HTTP_STATUS_CODES:jY}=xs.hdbErrors),_n=mp.default.loggerWithTag("operation"),i_e=VC.promisify(Gd.default.search),o_e=VC.promisify(_T.default.evaluateSQL),a_e={[G.CREATE_ATTRIBUTE]:!0,[G.CREATE_TABLE]:!0,[G.CREATE_SCHEMA]:!0,[G.DROP_ATTRIBUTE]:!0,[G.DROP_TABLE]:!0,[G.DROP_SCHEMA]:!0};o(fW,"processLocalTransaction");QY=l_e();YC(exports);ve.operation=KC;o(mW,"chooseOperation");o(hW,"getOperationFunction");(0,cW._assignPackageExport)("operation",KC);o(KC,"operation");o(c_e,"catchup");o(Us,"executeJob");o(l_e,"initializeOperationFunctionMap")});var RT=M((nxe,_W)=>{"use strict";var ST=(k(),v(K)),u_e=ie(),hp=z(),{handleHDBError:WC,hdbErrors:TT}=Ee(),{isMainThread:d_e}=require("worker_threads"),{Readable:f_e}=require("stream"),pW=require("os"),m_e=require("util"),h_e=sN(),p_e=m_e.promisify(h_e.authorize),EW=(BO(),v(xO)),{createGzip:E_e,constants:__e}=require("zlib"),g_e=[ST.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,ST.OPERATIONS_ENUM.LOGIN,ST.OPERATIONS_ENUM.LOGOUT];function S_e(e){let t=`Found an uncaught exception with message: ${e.message}. ${pW.EOL}Stack: ${e.stack} ${pW.EOL}Terminating ${d_e?"HDB":"thread"}.`;console.error(t),hp.fatal(t),process.exit(1)}o(S_e,"handleServerUncaughtException");function T_e(e,t,r){if(hp[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:TT.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}o(T_e,"serverErrorHandler");function R_e(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=WC(new Error,"Invalid JSON.",TT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(u_e.isEmpty(e.body.operation)){let n=WC(new Error,"Request body must include an 'operation' property.",TT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}o(R_e,"reqBodyValidationHandler");function y_e(e,t,r){let n;!g_e.includes(e.body.operation)||e.body.operation===ST.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&!e.body.username&&!e.body.password?p_e(e,t).then(i=>{n=i,e.body.hdb_user=n,r()}).catch(i=>{hp.warn(i),hp.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${i.stack}"`);let a=typeof i=="string"?{error:i}:{error:i.message};r(WC(i,a,TT.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}o(y_e,"authHandler");async function A_e(e,t,r=!1){let n;try{e.body.bypass_auth&&delete e.body.bypass_auth,n=EW.chooseOperation(e.body);let s=await EW.processLocalTransaction(e,n);if(s instanceof f_e&&s.headers){for(let[i,a]of s.headers)t.header(i,a);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(E_e({level:__e.Z_BEST_SPEED})))}return s}catch(s){throw hp.error(s),s}}o(A_e,"handlePostRequest");_W.exports={authHandler:y_e,handlePostRequest:A_e,handleServerUncaughtException:S_e,serverErrorHandler:T_e,reqBodyValidationHandler:R_e}});var RW=M((ixe,TW)=>{"use strict";var b_e=require("fastify-plugin"),{handlePostRequest:gW,authHandler:I_e,reqBodyValidationHandler:N_e}=RT();async function w_e(e){e.decorate("hdbCore",{preValidation:[N_e,I_e],request:o(t=>SW(gW(t,response)),"request"),requestWithoutAuthentication:o((t,r)=>SW(gW(t,r,!0)),"requestWithoutAuthentication")})}o(w_e,"hdbCore");async function SW(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}o(SW,"convertAsyncIterators");TW.exports=b_e(w_e)});var AW=M((cxe,yW)=>{"use strict";var axe=require("fs"),yT=ce();yT.initSync();var{CONFIG_PARAMS:zC}=(k(),v(K)),O_e=1024*1024*1024;function C_e(e){let t=yT.get(zC.HTTP_TIMEOUT),r=yT.get(zC.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:O_e,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,maxParamLength:yT.get(zC.HTTP_MAXPARAMLENGTH)??1e3,https:e}}o(C_e,"getServerOptions");yW.exports=C_e});var NW=M((uxe,IW)=>{"use strict";var jC=ce();jC.initSync();var{CONFIG_PARAMS:bW}=(k(),v(K));function P_e(){let e=jC.get(bW.HTTP_CORSACCESSLIST),t=jC.get(bW.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}o(P_e,"getCORSOptions");IW.exports=P_e});var CW=M((fxe,OW)=>{"use strict";var wW=ce();wW.initSync();var L_e=(k(),v(K));function D_e(){return wW.get(L_e.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}o(D_e,"getHeaderTimeoutConfig");OW.exports=D_e});var JC={};Ce(JC,{customFunctionsServer:()=>U_e,ready:()=>$W,start:()=>v_e});function v_e(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Vo||(Vo=qW(t),ve.http((await Vo).server));let a=await Vo,c=(0,QC.dirname)(s),l=(0,QC.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!PW.has(c)){PW.add(c);try{a.register(B_e(c,l))}catch(u){if(u.message==="Root plugin has already booted")St.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw u}}},ready:$W}}async function U_e(){try{St.info("In Custom Functions Fastify server"+process.cwd()),St.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),St.debug(`Custom Functions server process ${process.pid} starting up.`),await x_e();let e=xW.get(U.HTTP_SECUREPORT)>0,t;try{t=Vo=await qW(e)}catch(r){throw St.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw St.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){St.error(`Custom Functions ${process.pid} Error: ${e}`),St.error(e),process.exit(1)}}async function x_e(){try{St.info("Custom Functions starting configuration."),await BW.setUsersWithRolesCache(),St.info("Custom Functions completed configuration.")}catch(e){St.error(e)}}function B_e(e,t){return async function(r){try{St.info("Custom Functions starting buildRoutes"),St.trace("Loading fastify routes folder "+e),(0,LW.existsSync)(e)&&r.register(UW.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:St.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,a)=>{s?.message?St.error(s.message):s&&St.error(s),a()})}catch(n){St.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function qW(e){St.info("Custom Functions starting buildServer.");let t=(0,FW.default)(e),r=(0,DW.default)(t);r.server.headersTimeout=(0,kW.default)(),r.setErrorHandler(GW.serverErrorHandler);let n=(0,HW.default)();return n&&r.register(MW.default,n),r.register(function(s,i,a){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),a()}),r.register(vW.default),await r.register(M_e),await r.after(),em(r),St.info("Custom Functions completed buildServer."),r}function $W(){if(Vo)return Vo.then?Vo.then(e=>e.ready()):Vo.ready()}var QC,LW,DW,MW,vW,UW,xW,St,M_e,BW,FW,HW,kW,GW,Vo,PW,VW=fe(()=>{QC=require("path"),LW=require("fs"),DW=w(require("fastify")),MW=w(require("@fastify/cors")),vW=w(JI()),UW=w(require("@fastify/autoload")),xW=w(ce());k();St=w(z()),M_e=w(RW()),BW=w(zn()),FW=w(AW()),HW=w(NW()),kW=w(CW()),GW=w(RT());mo();Pr();PW=new Set;o(v_e,"start");o(U_e,"customFunctionsServer");o(x_e,"setUp");o(B_e,"buildRouteFolder");o(qW,"buildServer");o($W,"ready")});var XC={};Ce(XC,{start:()=>F_e});function F_e(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,jW.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(a=>n(s._nodeRequest,s._nodeResponse,()=>{a(i(s))}))}),!0}},handleFile(t,r,n){YW||(YW=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let a=KW.get(s.pathname);if(a)return{handlesHeaders:!0,body:(0,WW.default)(s,(0,zW.realpathSync)(a))}}return i(s)},{runFirst:!0})),KW.set(r,n)}}}var WW,zW,jW,KW,YW,QW=fe(()=>{WW=w(require("send")),zW=require("fs"),jW=w(require("serve-static")),KW=new Map;o(F_e,"start")});var ZC={};Ce(ZC,{start:()=>H_e});function H_e({override:e}){return{handleFile:o((t,r,n)=>{AT.default.debug(`Loading env file: ${n}`);for(let[s,i]of Object.entries((0,JW.parse)(t))){if(process.env[s]!==void 0)if(AT.default.warn(`Environment variable conflict: ${s} from ${n} is already set on process.env`),e)AT.default.debug(`override option enabled. overriding environment variable: ${s}`);else continue;process.env[s]=i}},"handleFile")}}var JW,AT,XW=fe(()=>{JW=require("dotenv"),AT=w(z());o(H_e,"start")});var eP={};Ce(eP,{DataLoaderError:()=>os,DataLoaderResult:()=>$d,EmptyFileError:()=>NT,FileParseError:()=>IT,InvalidPropertyTypeError:()=>wT,MissingRequiredPropertyError:()=>pp,RecordProcessingError:()=>Ep,SystemDatabaseError:()=>OT,UnsupportedFileExtensionError:()=>bT,handleApplication:()=>G_e,loadDataFile:()=>nz,suppressHandleApplicationWarning:()=>k_e});function G_e(e){if((0,ez.getWorkerIndex)()!==0){Wi.debug?.("Skipping data loader initialization on non-primary worker");return}e.handleEntry(t=>{t.entryType!=="file"||t.eventType==="unlink"||nz(t,cn,Ge).then(r=>{Wi.debug?.("Data loader processed file: %s: %s",(0,Ko.basename)(t.absolutePath),r.message)})})}async function nz({contents:e,absolutePath:t,stats:r},n,s){let i=(0,Ko.extname)(t)||"unknown",a;try{if(i===".yaml"||i===".yml")a=(0,ZW.parseDocument)(e.toString()).toJSON();else if(i===".json")a=JSON.parse(e.toString());else throw new bT(t,i);a.mtime=r.mtimeMs}catch(f){throw f instanceof os?f:new IT(t,f)}if(!a)throw new NT(t);let{database:c,table:l,records:u}=a;if(!l)throw new pp(t,"table");if(!u)throw new pp(t,"records");if(!Array.isArray(u))throw new wT(t,"records","array");let d=c?`${c}.${l}`:l;if(c?.toLowerCase()==="system")throw new OT(c,l);try{let f;if(c&&s[c]&&s[c][l])Wi.debug?.(`Using existing table ${d} from database tables`),f=s[c][l];else if(n&&n[l])Wi.debug?.(`Using existing table ${d} from global tables`),f=n[l];else{Wi.debug?.(`Table ${d} not found, creating new table`);let y=[];if(u.length>0){let T=u[0];Object.keys(T).map(R=>{let I={name:R,type:typeof T[R]};return R==="id"&&(I.isPrimaryKey=!0),I}).forEach(R=>{y.push(R)})}f=await Ze({database:c,table:l,attributes:y})}let m=u.length,h=0,p=0,_=0,g=100;for(let y=0;y<u.length;y+=g){let T=u.slice(y,y+g),R=[];for(let I of T)R.push(async()=>{try{let P=null,Y=I.id;if(Y!==void 0&&(P=await f.get(Y)),!P)return h++,f.put(I);let te=P.getUpdatedTime();return a.mtime>te?(p++,f.put(I)):(_++,Promise.resolve({inserted:0,updated:0}))}catch(P){if(P instanceof os)Wi.error?.(`Record processing error: ${P.message}`);else{let Y=new Ep(d,P);Wi.error?.(`Record processing error: ${Y.message}`)}return Promise.resolve({inserted:0,updated:0,error:P.message})}});await Promise.all(R.map(I=>I()))}if(h>0||p>0){let y=`Loaded ${h} new and updated ${p} records in ${d}`;return _>0&&(y+=` (${_} records skipped)`),Wi.info?.(y),new $d(t,c,l,"success",h+p,y)}else if(_>0){let y=`All ${_} records in ${d} already up-to-date`;return Wi.info?.(y),new $d(t,c,l,"skipped",m,y)}else{let y=`No records to process in ${d}`;return Wi.info?.(y),new $d(t,c,l,"success",0,y)}}catch(f){throw f instanceof os?f:new Ep(d,f)}}var Ko,ZW,ez,Yo,tz,rz,Wi,k_e,os,bT,IT,NT,pp,wT,OT,Ep,$d,sz=fe(()=>{Ko=require("node:path"),ZW=require("yaml");Le();ez=w(st()),Yo=w(en()),tz=w(Ee()),rz=w(z()),Wi=rz.default.forComponent("dataLoader"),k_e=!0;o(G_e,"handleApplication");o(nz,"loadDataFile");os=class extends tz.ClientError{static{o(this,"DataLoaderError")}constructor(t,r=Yo.HTTP_STATUS_CODES.BAD_REQUEST){super(t,r),this.name="DataLoaderError"}},bT=class extends os{static{o(this,"UnsupportedFileExtensionError")}constructor(t,r){super(`Unsupported file extension in ${(0,Ko.basename)(t)}: ${r}. Only YAML and JSON files are supported.`,Yo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="UnsupportedFileExtensionError"}},IT=class extends os{static{o(this,"FileParseError")}constructor(t,r){super(`Failed to parse data file ${(0,Ko.basename)(t)}: ${r.message}`,Yo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="FileParseError"}},NT=class extends os{static{o(this,"EmptyFileError")}constructor(t){super(`Data file ${(0,Ko.basename)(t)} is empty or invalid`,Yo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="EmptyFileError"}},pp=class extends os{static{o(this,"MissingRequiredPropertyError")}constructor(t,r){super(`Data file ${(0,Ko.basename)(t)} is missing required "${r}" property`,Yo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="MissingRequiredPropertyError"}},wT=class extends os{static{o(this,"InvalidPropertyTypeError")}constructor(t,r,n){super(`Data file ${(0,Ko.basename)(t)} has invalid "${r}" property, expected ${n}`,Yo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="InvalidPropertyTypeError"}},OT=class extends os{static{o(this,"SystemDatabaseError")}constructor(t,r){super(`Cannot load data into system database: ${t}.${r}`,Yo.HTTP_STATUS_CODES.FORBIDDEN),this.name="SystemDatabaseError"}},Ep=class extends os{static{o(this,"RecordProcessingError")}constructor(t,r){super(`Failed to process record in ${t}: ${r.message}`,Yo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="RecordProcessingError"}},$d=class{static{o(this,"DataLoaderResult")}#e;#t;#r;#n;#s;#i;constructor(t,r,n,s,i,a){this.#e=t,this.#t=r||"unknown",this.#r=n||"unknown",this.#n=s,this.#s=i,this.#i=a}get filePath(){return this.#e}get database(){return this.#t}get table(){return this.#r}get status(){return this.#n}get count(){return this.#s}get message(){return this.#i}toJSON(){return{filePath:this.#e,database:this.#t,table:this.#r,status:this.#n,count:this.#s,message:this.#i}}}});var hz={};Ce(hz,{startHTTPThreads:()=>$_e,startSocketServer:()=>iP,updateWorkerIdleness:()=>mz});async function $_e(e=2,t){HI().catch(r=>zd.error?.("Error recording hostname for analytics:",r));try{if(t)nP(0,1,!0);else{let{loadRootComponents:r}=DT();if(e===0)return(0,Bs.setMainIsWorker)(!0),await cP().startServers(),Promise.resolve([]);await r()}fz();for(let r=0;r<e;r++)nP(r,e);return Promise.all(dz)}finally{(0,Bs.threadsHaveStarted)()}}function fz(){let e=(0,cz.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),rP=setInterval(()=>{zd.notify(e)},q_e).unref())}function nP(e,t=1,r){if(tP++,(0,Bs.startWorker)("server/threads/threadServer.js",{name:Fy.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((a,c)=>{function l(u){u.type===vy.CHILD_STARTED&&(n.removeListener("message",l),a(n))}o(l,"onMessage"),n.on("message",l),n.on("error",c)});dz.push(s),await s,Vd.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",a=>{if(a.requestId){let c=PT.get(a.requestId);c&&c(a)}}),n.on("exit",i),n.on("shutdown",i);function i(){let a=Vd.indexOf(n);a>-1&&Vd.splice(a,1)}if(o(i,"removeWorker"),Kd){let a=Kd;Kd=[];for(let c of a)uz[c.localPort](null,c)}}}),r){let n=setInterval(()=>{sP?sP=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Bs.shutdownWorkers)(),tP=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function iP(e=0,t){if(typeof e=="string")try{(0,LT.existsSync)(e)&&(0,LT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=V_e:r=K_e(t):r=oP;let n=(0,Yd.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=uz[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),sP=!0,r(i,(a,c)=>{if(!a){if(iz){let u=i._socket||new Yd.Socket({handle:i,writable:!0,readable:!0});iz.deliverSocket(u,e,c),u.resume()}else tP>0?(Kd.length===0&&setTimeout(()=>{Kd.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,Kd.push(i)):(console.log("start up a dynamic thread to handle request"),nP(0));gt(!1,"socket-routed");return}a.requests++;let l=i.fd;if(l>=0)a.postMessage({port:e,fd:l,data:c});else{let u=i._socket||new Yd.Socket({handle:i,writable:!0,readable:!0});z_e(u,a,e)}gt(!0,"socket-routed")})},zd.info(`HarperDB ${lz.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 oP(e,t){let r,n=0;for(let s of Vd){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=CT)return CT=i,t(r);n=i}CT=0,t(r)}function V_e(e,t){let r={};e.getpeername(r);let n=r.address,s=Wd.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);oP(e,a=>{Wd.set(n,{worker:a,lastUsed:i}),t(a)})}function K_e(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Yd.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",a=>{n.readStop();let l=a.toString("latin1").match(t)?.[1],u=Wd.get(l),d=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=d,s(u.worker);oP(n,f=>{Wd.set(l,{worker:f,lastUsed:d}),s(f,a)})})}o(r,"findByHeaderAffinity")}function mz(){CT=0;for(let e of Vd)e.expectedIdle=e.recentELU.idle+Y_e,e.requests=1;Vd.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function z_e(e,t,r){let n=W_e++;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(),PT.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")),PT.delete(n)),s.event=="destroy"&&(e.destroy(),PT.delete(n))})}var Bs,Yd,zd,LT,az,cz,lz,Vd,Kd,uz,iz,tP,dz,rP,q_e,sP,CT,oz,Wd,Y_e,PT,W_e,aP=fe(()=>{Bs=w(st()),Yd=require("net");k();zd=w(z()),LT=require("fs");Fi();az=require("worker_threads"),cz=w(Ad()),lz=w(Rt()),Vd=[],Kd=[],uz=[],tP=0,dz=[];az.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Bs.onMessageFromWorkers)(e=>{e.type===By.RESTART&&rP&&(clearInterval(rP),fz())}));q_e=6e5;o($_e,"startHTTPThreads");o(fz,"licenseWarning");o(nP,"startHTTPWorker");o(iP,"startSocketServer");CT=0;o(oP,"findMostIdleWorker");oz=36e5,Wd=new Map;o(V_e,"findByRemoteAddressAffinity");o(K_e,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wd)r.lastUsed+oz<e&&Wd.delete(t)},oz).unref();Y_e=1e3;o(mz,"updateWorkerIdleness");(0,Bs.setMonitorListener)(mz);PT=new Map,W_e=1;o(z_e,"proxySocket")});var lP={};Ce(lP,{hdbServer:()=>X_e,start:()=>X_e});async function X_e(e){try{zi.default.debug("In Fastify server"+process.cwd()),zi.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),zi.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=pz.default.isMaster,await Z_e();let t=e.securePort>0;jd=ege(t),await jd.ready(),e||(e={}),e.isOperationsServer=!0;try{ve.http(jd.server,e),jd.server.closeIdleConnections||await jd.listen({port:0,host:"::"})}catch(r){throw jd.close(),zi.default.error(r),zi.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),zi.default.fatal(t),process.exit(1)}}async function Z_e(){zi.default.trace("Configuring HarperDB process."),Az.default.setSchemaDataToGlobal(),await Iz.default.setUsersWithRolesCache(),await Nz.default.getLicense()}function ege(e){zi.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=tge(e),r=(0,Ez.default)(t);r.server.headersTimeout=nge(),r.setErrorHandler(tc.serverErrorHandler);let n=rge();n&&r.register(_z.default,n),r.register(function(i,a,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(Tz.default),r.register(gz.default),r.register(Sz.default,{root:Rz.default.join(yz.PACKAGE_ROOT,"studio/build-local")}),em(r);let s=ec.default.get(My.LOCAL_STUDIO_ON);return r.get("/",function(i,a){return!bz.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?a.sendFile("index.html"):a.sendFile("running.html")}),r.post("/",{preValidation:[tc.reqBodyValidationHandler,tc.authHandler],config:{isOperation:!0}},async function(i,a){return i.body?.operation?.startsWith("restart")&&a.header("Connection","close"),(0,tc.handlePostRequest)(i,a)}),r.get("/health",()=>"HarperDB is running."),zi.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}function tge(e){let t=ec.default.get(_p.OPERATIONSAPI_NETWORK_TIMEOUT),r=ec.default.get(_p.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Q_e,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}function rge(){let e=ec.default.get(_p.OPERATIONSAPI_NETWORK_CORS),t=ec.default.get(_p.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===J_e)&&(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}function nge(){return ec.default.get(_p.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??j_e}var pz,ec,zi,Ez,_z,gz,Sz,Tz,Rz,yz,Az,bz,Iz,Nz,tc,j_e,Q_e,J_e,_p,jd,wz=fe(()=>{pz=w(require("cluster")),ec=w(ce());k();zi=w(z()),Ez=w(require("fastify")),_z=w(require("@fastify/cors")),gz=w(require("@fastify/compress")),Sz=w(require("@fastify/static")),Tz=w(JI()),Rz=w(require("path")),yz=w(Rt()),Az=w(Js()),bz=w(ie()),Iz=w(zn()),Nz=w(Ad());Pr();tc=w(RT());mo();ec.default.initSync();j_e=6e4,Q_e=1024*1024*1024,J_e="TRUE",{CONFIG_PARAMS:_p}=K;o(X_e,"operationsServer");o(Z_e,"setUp");o(ege,"buildServer");o(tge,"getServerOptions");o(rge,"getCORSOpts");o(nge,"getHeaderTimeoutConfig")});var pP={};Ce(pP,{disableNATS:()=>ige,publishToStream:()=>UT,setNATSReplicator:()=>uP,setPublishToStream:()=>oge,setSubscription:()=>hP,start:()=>sge});function sge(){gp.default.get(U.CLUSTERING_ENABLED)&&cge()}function ige(e=!0){Dz=e}function oge(e,t){UT=e,hP=t}function cge(){if(Dz||process.env._DISABLE_NATS)return;let e=it(),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];uP(s,r,i)}}Rl((r,n)=>{uP(r.tableName,r.databaseName,r),n&&vz(r)}),!Oz&&(Oz=!0)}function uP(e,t,r){if(t==="system"&&lge.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 vr{static{o(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){vz(i)}static subscribe(){let i=new Gn;return hP(t,e,i),i}static subscribeOnThisThread(i){return i<(gp.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??age)}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 MT(s.transaction,s);let a=s.transaction;for(;a.next;)a=a.next;a.next=s.transaction.nats,i.user=s.user,i.context=s}else i=Mz;return i}o(n,"getNATSTransaction")}function vz(e){let t=gp.default.get(U.CLUSTERING_NODENAME);UT(`${fP.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,mP.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 Cz,fP,mP,Pz,Lz,gp,vT,Dz,UT,hP,age,Mz,Oz,lge,MT,dP,Uz=fe(()=>{Le();wa();Cz=w(lr()),fP=w(bt()),mP=w(Di());mu();Pz=w(mN()),Lz=w(Rn()),gp=w(ce());k();vT=w(z());o(sge,"start");o(ige,"disableNATS");UT=Cz.publishToStream,hP=Pz.setSubscription;o(oge,"setPublishToStream");age=2;o(cge,"assignReplicationSource");lge=["hdb_job","hdb_raw_analytics","hdb_info","hdb_license"];o(uP,"setNATSReplicator");o(vz,"publishSchema");MT=class{constructor(t,r){this.transaction=t;this.options=r}static{o(this,"NATSTransaction")}user;writesByDb=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writesByDb.get(t);n||this.writesByDb.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=gp.default.get(U.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writesByDb){let a=[],c=[],l,u;for(let d of i){let f=d.table,m=d.operation=="put"?"upsert":d.operation;l||(vT.trace(`Sending transaction event ${m}`),u=l={operation:m,schema:s,table:f,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,m!=="delete"&&m!=="invalidate"&&(l.records=a)),l.table===f&&l.operation===m?(a.push(d.record),c.push(d.id)):u=u.next={operation:m,table:f,id:d.id,record:d.record},d.expiresAt&&(u.expiresAt=d.expiresAt)}l&&n.push(UT(`${fP.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,mP.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(d=>{throw vT.error("An error has occurred trying to replicate transaction",l,d),d.statusCode=504,d}))}return Promise.all(n)}},dP=class extends MT{static{o(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,Lz.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};Mz=new dP});async function kz({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let a=await EP.get(e,{returnNonexistent:!0});i=new SP(e,t,a),a&&(i.sessionWasPresent=!0)}else{if(e){let a=await EP.get(e);a&&a.delete()}i=new BT(e,t)}return n&&(n.id=e,n.user={username:t?.username},Sp.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function _P(){return xT++,xT>65500&&(xT=1),xT}function gP(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 a=new si(i.relativeURL);a.checkPermission=r.user?.role?.permission??{};let c=i.Resource;return Mt(r,()=>s?t===void 0?c.delete(a,r):c.put(a,e.data,r):c.publish(a,e.data,r))}var Bz,rc,Fz,Hz,xz,EP,Sp,xT,BT,SP,Gz=fe(()=>{Le();_u();Bz=w(Rn()),rc=w(z());Dc();Fz=w(st()),Hz=w(cP());Pr();tg();xz=100,EP=Ze({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"}]}}]}),Sp=Ze({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,Fz.getWorkerIndex)()===0&&(async()=>{await Hz.whenComponentsLoaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Sp.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await ve.getUser(r.user.username));try{await gP(r,t,r)}catch{(0,rc.warn)("Failed to publish will",t)}Sp.delete(e.id)}})();o(kz,"getSession");xT=1;o(_P,"getNextMessageId");BT=class{static{o(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:a}=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 d=this.subscriptions.find(T=>T.topic===s),f;d?(f=i>0,d.end(),this.subscriptions.splice(this.subscriptions.indexOf(d),1)):f=i===2;let m={search:l,async:!0,user:this.user,startTime:a,omitCurrent:f,target:"",checkPermission:this.user?.role?.permission??{}};a&&(0,rc.trace)("Resuming subscription from",s,"from",a);let h=Ts.getMatch(u,"mqtt");if(!h){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}m.url=h.relativeURL;let p;if(m.url.indexOf("+")>-1||(p=m.url.indexOf("#"))>-1){let T=m.url.slice(1);if(p--,p>-1&&p!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(m.isCollection=!0,T.indexOf("+")===T.length-1)m.onlyChildren=!0,m.url="/"+T.slice(0,T.length-1);else{let R=T.split("/"),I;for(let te=0;te<R.length;te++)if(R[te].indexOf("+")>-1)if(R[te]==="+")I=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&I)throw new Error("Filters can not be combined");let P=!0;R[R.length-1]==="#"&&(R.length--,P=!1),I&&(n=o(te=>{let x=te.id;if(!Array.isArray(x))if(x?.indexOf?.("/")>-1)x=x.split("/");else return!1;if(P&&x.length!==R.length)return!1;for(let $=0;$<R.length;$++)if(R[$]!=="+"&&R[$]!==x[$])return!1;return!0},"filter"));let Y=R.indexOf("+");m.url="/"+(Y>-1?R.slice(0,Y):R).concat("").join("/")}}else m.isCollection=!1;let _=h.path,g=h.Resource,y=await Mt(m,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i,T.isCollection=m.isCollection;let R=await g.subscribe(m,T);if(!R)return;if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let I=(async()=>{for await(let P of R)try{let Y;if(P.type&&P.type!=="put"&&P.type!=="delete"&&P.type!=="message"&&P.type!=="patch"||n&&!n(P))continue;r?(P.topic=s,Y=this.needsAcknowledge(P)):(P.acknowledge?.(),Y=_P());let te=P.id;if(Array.isArray(te)&&(te=Eu(te)),te==null&&(te=""),await this.listener(_+"/"+te,P.value,Y,t)===!1)break;this.awaitingAcks?.size>xz?await new Promise($=>setTimeout($,this.awaitingAcks.size-xz)):await new Promise(setImmediate)}catch(Y){(0,rc.warn)(Y)}})();return R});if(y)return y.topic=s,y.qos=t.qos,this.subscriptions.push(y),y}resume(){}needsAcknowledge(t){let r=_P();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 gP(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();Mt(r,async()=>{try{if(!t){let n=await Sp.get(this.sessionId);n?.doesExist()&&await gP(n,n.data,r)}}finally{await Sp.delete(this.sessionId)}}).catch(n=>{(0,rc.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))}};o(gP,"publish");SP=class extends BT{static{o(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=_P(),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,rc.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,Bz.getNextMonotonicTime)()),(0,rc.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),EP.put(this.sessionRecord)}}});var TP={};Ce(TP,{bypassAuth:()=>uge,start:()=>fge});function uge(){zz=!0}function fge({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Wz.EventEmitter},e.mqtt.events.on("error",()=>{}));let a=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((u,d,f,m)=>{if(d.headers.get("sec-websocket-protocol")!=="mqtt")return m(u,d,f);a.events.emit("connection",u),rr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:p}=$z(u,_=>{u.send(_)},d,Promise.resolve(f).then(()=>d?.user),a);u.on("message",h),u.on("close",p),u.on("error",_=>{rr.info?.("WebSocket error",_)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let d;if(a.events.emit("connection",u),rr.debug?.(`Received ${u.getCertificate?"SSL":"TCP"} connection for MQTT from ${u.remoteAddress}`),l){if(u.authorized)try{let h=l.user;if(h!==null){(h===void 0||h==="Common Name"||h==="CN")&&(h=u.getPeerCertificate().subject.CN);try{d=await e.getUser(h,null,null),(0,Qd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&HT.notify?.({username:d?.username,status:Ys.SUCCESS,type:ha.AUTHENTICATION,authStrategy:"MQTT mTLS",remoteAddress:u.remoteAddress})}catch(p){throw(0,Qd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&HT.error?.({username:h,status:Ys.FAILURE,type:ha.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:u.remoteAddress}),p}}else rr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){a.events.emit("error",h,u),rr.error?.(h)}else if(l.required)return rr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!d&&dge(u.remoteAddress)&&(d=await(0,Vz.getSuperUser)(),rr.debug?.("Auto-authorizing local connection",d?.username));let{onMessage:f,onClose:m}=$z(u,h=>u.write(h),null,d,a);u.on("data",f),u.on("close",m),u.on("error",h=>{rr.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function $z(e,t,r,n,s){qz||(qz=!0,qm(f=>{FT>0&&f.push({metric:"mqtt-connections",connections:FT,byThread:!0})}));let i;FT++;let a,c={protocolVersion:4},l=(0,kT.parser)({protocolVersion:5});function u(f){l.parse(f)}o(u,"onMessage");function d(){FT--,i||(i=!0,a?.disconnect?.(),s.events.emit("disconnected",a,e),s.sessions.delete(a),Vr(!1,"connection","mqtt","disconnect"),rr.debug?.("MQTT connection was closed",e.remoteAddress))}return o(d,"onClose"),l.on("packet",async f=>{try{n?.then&&(n=await n)}catch(R){e.close?.(1008,"Unauthorized"),rr.info?.(R);return}let m=f.cmd;if(a)a.then&&await a;else if(m!=="connect"){rr.info?.("Received packet before connection was established, closing connection"),e?.destroy?e.destroy():e?.terminate();return}let h=f.topic,p=h?.indexOf("/",1),_=p>0?h.slice(0,p):h;gt(f.length,"bytes-received",_,y(f),"mqtt");try{switch(a?.receivedPacket?.(),m){case"connect":if(c.protocolVersion=f.protocolVersion,f.username)try{n=await ve.getUser(f.username,f.password.toString(),r),(0,Qd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&HT.notify?.({username:n?.username,status:Ys.SUCCESS,type:ha.AUTHENTICATION,authStrategy:"MQTT",remoteAddress:e.remoteAddress})}catch(j){return(0,Qd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&HT.error?.({username:f.username,status:Ys.FAILURE,type:ha.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:e.remoteAddress}),s.events.emit("auth-failed",f,e,j),Vr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",f,e),Vr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(f,n),f.will){let j=e.deserialize||(e.deserialize=Eo(r?.headers.get?.("content-type")));f.will.data=f.will.payload?.length>0?j(f.will.payload):void 0,delete f.will.payload}a=kz({user:n,...f}),a=await a,a.socket=e,r&&(a.request=r),s.sessions.add(a)}catch(j){return rr.error?.(j),s.events.emit("auth-failed",f,e,j),Vr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:j.code||5,returnCode:j.code||128})}s.events.emit("connected",a,e),Vr(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:a.sessionWasPresent,reasonCode:0,returnCode:0});let R=o(async(j,V,le,re)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",j);let se=j.indexOf("/",1),_e=se>0?j.slice(0,se):j;g({cmd:"publish",topic:j,payload:await T(V),messageId:le||Math.floor(Math.random()*1e8),qos:re.qos},_e);let Ne=e._socket??e;return Ne.writableNeedDrain?new Promise(Fe=>Ne.once("drain",Fe)):!Ne.closed}catch(se){return rr.error?.(se),a?.disconnect(),s.sessions.delete(a),!1}},"listener");a.setListener(R),a.sessionWasPresent&&await a.resume();break;case"subscribe":let I=[];for(let j of f.subscriptions){let V;try{let le=await a.addSubscription(j,j.qos>=1);V=le?le.qos||0:c.protocolVersion<5?128:143}catch(le){s.events.emit("error",le,e,j,a),le.statusCode?le.statusCode===500?rr.warn?.(le):rr.info?.(le):rr.error?.(le),V=c.protocolVersion<5?128:le.statusCode===403?135:le.statusCode===404?143:128}I.push(V)}await a.committed,g({cmd:"suback",granted:I,messageId:f.messageId});break;case"unsubscribe":{let j=[];for(let V of f.unsubscriptions)j.push(a.removeSubscription(V)?0:17);g({cmd:"unsuback",granted:j,messageId:f.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:f.messageId,reasonCode:0});return;case"publish":let P=f.qos===2?"pubrec":"puback",Y=e.deserialize||(e.deserialize=Eo(r?.headers.get?.("content-type"))),x=(f.payload?.length||0)>0?Y(f.payload):void 0,$;try{$=await a.publish(f,x)}catch(j){s.events.emit("error",j,e,f,a),rr.warn?.(j),f.qos>0&&g({cmd:P,messageId:f.messageId,reasonCode:128},f.topic);break}f.qos>0&&g({cmd:P,messageId:f.messageId,reasonCode:$===!1?144:0},f.topic);break;case"pubrec":g({cmd:"pubrel",messageId:f.messageId,reasonCode:0});break;case"pubcomp":case"puback":a.acknowledge(f.messageId);break;case"pingreq":g({cmd:"pingresp"});break;case"disconnect":i=!0,a?.disconnect(!0),s.events.emit("disconnected",a,e),s.sessions.delete(a),Vr(!0,"connection","mqtt","disconnect"),rr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(R){s.events.emit("error",R,e,f,a),rr.error?.(R),g({cmd:"disconnect"})}function g(R,I){let P=(0,kT.generate)(R,c);t(P),gt(P.length,"bytes-sent",I,y(R),"mqtt")}o(g,"sendPacket");function y(R){return R.qos>0?R.cmd+",qos="+R.qos:R.cmd}o(y,"packetMethodName");function T(R){return _a(R,r)}o(T,"serialize")}),l.on("error",f=>{rr.warn("MQTT parsing error, closing connection:",f.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:d}}var kT,Vz,Qd,Kz,Yz,Wz,HT,rr,zz,dge,qz,FT,jz=fe(()=>{kT=require("mqtt-packet");Gz();Vz=w(zn());mo();Fi();Pr();Qd=w(ce());k();Kz=w(Ii()),Yz=w(z()),Wz=require("events"),HT=(0,Kz.loggerWithTag)("auth-event"),rr=(0,Yz.forComponent)("mqtt"),zz=(0,Qd.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;o(uge,"bypassAuth");dge=o(e=>zz&&(e.includes("127.0.0.")||e==="::1"),"authorizeLocal");o(fge,"start");FT=0;o($z,"onSocket")});function GT(e,t){if(t?.includes(".."))throw new RP(t);let r=t||"/";return(r==="."||r.startsWith("./"))&&(r=`/${e}${r.slice(1)}`),r.startsWith("/")||(r=`/${r}`),r.endsWith("/")||(r=`${r}/`),r}var RP,yP=fe(()=>{RP=class extends Error{static{o(this,"InvalidBaseURLPathError")}constructor(t){super(`urlPath must not contain '..'. Received: '${t}'`)}};o(GT,"resolveBaseURLPath")});function Qz(e){if(e.length===0)return".";if(e.length===1)return e[0];let t=e.map(s=>s.split("/")),r=Math.min(...t.map(s=>s.length)),n=[];for(let s=0;s<r;s++){let i=t[0][s];if(t.every(a=>a[s]===i))n.push(i);else break}return n.length===0?".":n.join("/")}var Jz=fe(()=>{o(Qz,"deriveCommonPatternBase")});function qT(e){let t={source:[],onlyFiles:!1,onlyDirectories:!1,ignore:[]},r=o((n,s)=>{typeof s=="string"?n.push(s):Array.isArray(s)&&n.push(...s)},"addToArray");return typeof e=="string"||Array.isArray(e)?r(t.source,e):(r(t.source,e.source),r(t.ignore,e.ignore),t.onlyFiles=e.only==="files",t.onlyDirectories=e.only==="directories"),t}var AP=fe(()=>{o(qT,"deriveGlobOptions")});var Xz,bP,Tp,Zz=fe(()=>{yP();Jz();AP();Xz=require("micromatch"),bP=class extends Error{static{o(this,"ComponentInvalidPatternError")}constructor(t){super(`Config 'files' option glob pattern must not contain '..' or start with '/'. Received: '${t}'`),this.name="ComponentInvalidPatternError"}},Tp=class{static{o(this,"Component")}globOptions;baseURLPath;patternBases;directory;name;config;commonPatternBase;constructor(t,r,n){this.name=t,this.directory=r,this.config=n,this.baseURLPath=GT(this.name,this.config.urlPath),this.globOptions=qT(this.config.files),this.globOptions.source=this.globOptions.source.map(s=>{if(s.includes("..")||s.startsWith("/"))throw new bP(s);return s==="."||s==="./"?"**/*":s}),this.patternBases=this.globOptions.source.map(s=>(0,Xz.scan)(s).base),this.commonPatternBase=Qz(this.patternBases)}}});function ej(e,t){return new RegExp(`^${e}(/|$)`).test(t)}function ql(e,t,r){t.startsWith("./")&&(t=t.slice(2));for(let n of e.patternBases)if(n.startsWith("./")&&(n=n.slice(2)),n!==""){if(r==="file"){if(t===n){let s=t.split("/");t=s[s.length-1];break}else if(ej(n,t)){t=t.slice(n.length+1);break}}if(r==="directory"){if(t===n){t="";break}else if(ej(n,t)){t=t.slice(n.length+1);break}}}return(0,tj.join)(e.baseURLPath,t)}var tj,IP=fe(()=>{tj=require("node:path");o(ej,"pathStartsWithBase");o(ql,"deriveURLPath")});function rj(e){return typeof e=="string"||Array.isArray(e)||!("files"in e)?{files:e}:e}var VT,nj,sj,NP,ij,oj,$T,aj=fe(()=>{VT=require("node:events");Zz();nj=w(z()),sj=w(require("chokidar")),NP=require("node:path"),ij=require("node:fs/promises");IP();oj=require("micromatch"),$T=class extends VT.EventEmitter{static{o(this,"EntryHandler")}#e;#t;#r;ready;constructor(t,r,n,s){super(),this.#e=new Tp(t,r,rj(n)),this.#r=s||nj.default.loggerWithTag(t),this.ready=(0,VT.once)(this,"ready"),this.#a()}get name(){return this.#e.name}get directory(){return this.#e.directory}#n(...[t,r,n]){if(r===""&&(r="/"),!(0,oj.isMatch)(r,this.#e.globOptions.source,{ignore:this.#e.globOptions.ignore}))return;let s=(0,NP.join)(this.directory,r);switch(t){case"add":case"change":{let i=ql(this.#e,r,"file");(0,ij.readFile)(s).then(a=>{let c={eventType:t,entryType:"file",contents:a,stats:n,absolutePath:s,urlPath:i};this.emit("all",c),this.emit(t,c)});break}case"unlink":{let i=ql(this.#e,r,"file"),a={eventType:t,entryType:"file",stats:n,absolutePath:s,urlPath:i};this.emit("all",a),this.emit(t,a);break}case"addDir":case"unlinkDir":{let i=ql(this.#e,r,"directory"),a={eventType:t,entryType:"directory",stats:n,absolutePath:s,urlPath:i};this.emit("all",a),this.emit(t,a);break}}}#s(t){this.emit("error",t)}#i(){this.emit("ready")}async#a(){await this.#t?.close(),this.#t=void 0;let t=this.#e.patternBases.map(r=>(0,NP.join)(this.#e.directory,r));return this.#t=sj.default.watch(this.#e.commonPatternBase,{cwd:this.#e.directory,persistent:!1,ignored:o(r=>r!==this.#e.directory&&t.every(n=>!r.startsWith(n)),"ignored")}).on("all",this.#n.bind(this)).on("error",this.#s.bind(this)).on("ready",this.#i.bind(this)),this.ready}close(){return this.#t?.close(),this.#t=void 0,this.emit("close"),this.removeAllListeners(),this}update(t){return this.#e=new Tp(this.name,this.directory,rj(t)),this.#a()}};o(rj,"castConfig")});var KT,wP=fe(()=>{KT={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js"},static:{files:"web/**"}}});var WT,cj,lj,uj,dj,fj,OP,CP,PP,LP,DP,YT,mj=fe(()=>{WT=require("events"),cj=w(require("yaml")),lj=w(require("chokidar")),uj=require("node:fs/promises"),dj=require("util"),fj=w(z());wP();OP=class extends Error{static{o(this,"OptionsWatcherConfigFileError")}constructor(t,r){super(`Error watching config file ${t}: ${typeof r=="object"&&r!==null&&"message"in r?r.message:r}`),this.name="OptionsWatcherConfigFileError"}},CP=class extends Error{static{o(this,"InvariantUninitializedOptionsWatcherError")}constructor(){super("Invariant: OptionsWatcher has not been initialized yet. This should never happen."),this.name="InvariantUninitializedOptionsWatcherError"}},PP=class extends Error{static{o(this,"InvalidValueTypeError")}constructor(t,r){super(`Invalid value type for key ${t.join(".")}. Expected object, string, array, number, boolean, or undefined. Received ${typeof r}.`),this.name="InvalidValueTypeError"}},LP=class extends Error{static{o(this,"KeyDoesNotExistError")}constructor(t,r){super(`Cannot set property ${t.join(".")} as ${r} does not exist.`),this.name="KeyDoesNotExistError"}},DP=class extends Error{static{o(this,"CannotSetPropertyError")}constructor(t){super(`Cannot set property ${t.join(".")} as parent is not an object.`),this.name="CannotSetPropertyError"}},YT=class extends WT.EventEmitter{static{o(this,"OptionsWatcher")}#e;#t;#r;#n;#s;#i;ready;constructor(t,r,n){super(),this.#s=t,this.#e=r,this.#i=n||fj.default.loggerWithTag(t),this.ready=(0,WT.once)(this,"ready"),this.#t=lj.default.watch(r,{persistent:!1}).on("add",this.#a.bind(this)).on("change",this.#a.bind(this)).on("error",this.#d.bind(this)).on("unlink",this.#c.bind(this)).on("ready",this.#a.bind(this))}#a(){(0,uj.readFile)(this.#e,"utf-8").then(t=>{this.#n=cj.default.parse(t),this.#n&&this.#s in this.#n?this.#r?this.#f(this.#n[this.#s],this.#r):(this.#r=this.#n[this.#s],this.emit("ready",this.#r)):this.#r&&(this.#r=void 0,this.emit("remove"))}).catch(t=>{if(t instanceof Error&&"code"in t&&t.code==="ENOENT"){this.#n?(this.#o(),this.emit("remove")):(this.#o(),this.emit("ready"));return}this.emit("error",t)})}#d(t){this.emit("error",new OP(this.#e,t))}#c(t){this.#i.warn(`Configuration file ${t} was deleted. Reverting to default configuration. Recreate it to restore the options watcher.`),this.#o(),this.emit("remove")}#o(){this.#n=KT,this.#r=this.#n[this.#s]}#f(t,r,n=[]){if(!this.#l(r)||!this.#l(t)){this.#u(n,t);return}for(let s of Object.keys(r))s in t||this.#u(n.concat(s),void 0);for(let[s,i]of Object.entries(t)){let a=n.concat(s),c=this.#m(a);if(typeof i!=typeof c||Array.isArray(i)&&!Array.isArray(c)||!Array.isArray(i)&&Array.isArray(c)){this.#u(a,i);continue}if(!Array.isArray(i)&&typeof i=="object"&&i!==null){this.#l(c)?this.#f(i,c,a):this.#u(a,i);continue}(0,dj.isDeepStrictEqual)(i,c)||this.#u(a,i)}}#l(t){return typeof t=="object"&&t!==null&&t!==void 0&&!Array.isArray(t)}#m(t){let r=this.#r;for(let n of t){if(r==null||typeof r!="object"||!(n in r))return;r=r[n]}return structuredClone(r)}#u(t,r){if(!this.#r)throw new CP;if(!["object","string","array","number","boolean","undefined"].includes(typeof r))throw new PP(t,r);let n=this.#r;for(let s of t.slice(0,-1)){if(n==null||typeof n!="object"||!(s in n))throw new LP(t,s);n=n[s]}if(n==null||typeof n!="object")throw new DP(t);n[t[t.length-1]]=r,this.emit("change",t,r,this.#r)}close(){return this.#t.close(),this.emit("close"),this.removeAllListeners(),this}get(t){return this.#r?this.#m(t):void 0}getAll(){return structuredClone(this.#r)}getRoot(){return this.#n}}});function hj(){hge[0]=1}var mge,hge,pj=fe(()=>{Zh();mge=qo.primaryStore.getUserSharedBuffer("restart-needed",new ArrayBuffer(1)),hge=new Uint8Array(mge);o(hj,"requestRestart")});var QT,Ej,zT,jT,_j=fe(()=>{QT=require("node:events");aj();mj();Ej=w(z());pj();zT=class extends Error{static{o(this,"MissingDefaultFilesOptionError")}constructor(){super("No default files option exists. Ensure `files` is specified in config.yaml"),this.name="MissingDefaultFilesOptionError"}},jT=class extends QT.EventEmitter{static{o(this,"Scope")}#e;#t;#r;#n;#s;#i;options;resources;server;ready;constructor(t,r,n,s,i){super(),this.#r=t,this.#t=r,this.#e=n,this.#i=Ej.default.forComponent(this.#r),this.resources=s,this.server=i,this.#s=[],this.ready=(0,QT.once)(this,"ready"),this.options=new YT(t,n,this.#i).on("error",this.#d.bind(this)).on("change",this.#f.bind(this)()).on("ready",this.#a.bind(this))}get logger(){return this.#i}get name(){return this.#r}get directory(){return this.#t}#a(){this.emit("ready")}#d(t){this.emit("error",t)}close(){for(let t of this.#s)t.close();return this.options.close(),this.emit("close"),this.removeAllListeners(),this}#c(t){let r=new $T(this.#r,this.#t,t,this.#i).on("error",this.#d.bind(this)).on("add",this.#o("add")).on("change",this.#o("change")).on("unlink",this.#o("unlink")).on("addDir",this.#o("addDir")).on("unlinkDir",this.#o("unlinkDir"));return this.#s.push(r),r}#o(t){let r=this;return function(){this.listenerCount("all")>0||this.listenerCount(t)>1||r.requestRestart()}}#f(){let t=this;return o(function(...[n,s,i]){if(n[0]==="files"||n[0]==="urlPath"){if(!t.#n){t.#n=t.#c(i);return}t.#n.update(i);return}this.listenerCount("change")>1||(t.#i.debug(`Options changed: ${n.join(".")}, requesting restart`),t.requestRestart())},"handleOptionsWatcherChange")}#l(){let t=this.options.getAll();if(t&&typeof t=="object"&&t!==null&&!Array.isArray(t)&&"files"in t)return t.files}handleEntry(t,r){if(t===void 0){if(this.#n)return this.#n;let s=this.#l();if(s)return this.#n=this.#c(s),this.#n;this.emit("error",new zT);return}if(typeof t=="function"){if(this.#n)return this.#n.on("all",t);let s=this.#l();if(s)return this.#n=this.#c(s),this.#n.on("all",t);this.emit("error",new zT);return}let n=this.#c(t);return r?n.on("all",r):n}requestRestart(){this.#i.debug(`Restart requested from ${this.name} scope for ${this.directory}`),hj()}}});function $l(e){return typeof e=="string"&&e.trim()!==""}function MP(e){return Array.isArray(e)&&e.length!==0&&e.every(t=>$l(t))}function Rj(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function pge(e){e.config.root&&Rp.default.warn("Resource extension 'root' option is deprecated. Due to backwards compatibility reasons it does not act as assumed. The glob pattern will always be evaluated from the component directory root. The option is only used for the initial root directory handling. Please remove and modify the 'files' glob pattern instead.");let t=[];if(e.config.root&&typeof e.config.files!="string")throw new kP(e);let r=e.config.root;r&&(r.startsWith("/")&&(r=r.slice(1)),r.endsWith("/")||(r+="/"));let n=e.config.files;if(typeof n=="string"&&!n.includes("**/*")&&(n.indexOf("/*")>-1?r=n.slice(0,n.indexOf("/*")+1):n.indexOf("/")>-1&&(r=n.slice(0,n.lastIndexOf("/")+1))),r&&t.push(r),t.length===0){if(Rj(e.config.files)&&e.config.files.only==="files")return!1;t=e.patternBases}let s=!1;for(let i of t){let a=(0,yp.join)(e.directory,i);JT.isMainThread&&e.module.setupDirectory&&(s=await e.module.setupDirectory(e.baseURLPath,a,e.resources)),e.resources.isWorker&&e.module.handleDirectory&&(s=await e.module.handleDirectory(e.baseURLPath,a,e.resources))}return s}async function yj(e){let t=!1;if(t=await pge(e),t)return t;let r=await(0,gj.default)(e.globOptions.source,{cwd:e.directory,objectMode:!0,onlyFiles:e.globOptions.onlyFiles,onlyDirectories:e.globOptions.onlyDirectories,ignore:e.globOptions.ignore});for(let n of r){let s=(0,yp.join)(e.directory,n.path);if(n.dirent.isDirectory()){let i=ql(e,n.path,"directory");JT.isMainThread&&e.module.setupDirectory&&(await e.module.setupDirectory(i,s,e.resources),t=!0),e.resources.isWorker&&e.module.handleDirectory&&(await e.module.handleDirectory(i,s,e.resources),t=!0)}else if(n.dirent.isFile()){let i=ql(e,n.path,"file"),a=await(0,Sj.readFile)(s);JT.isMainThread&&e.module.setupFile?(await e.module.setupFile(a,i,s,e.resources),t=!0):e.resources.isWorker&&e.module.handleFile&&(await e.module.handleFile(a,i,s,e.resources),t=!0)}else Rp.default.error(`Entry received from glob pattern match for component ${e.name} is neither a file nor a directory:`,n)}return t}var JT,gj,Rp,yp,Sj,Tj,XT,_i,vP,UP,xP,BP,FP,HP,kP,GP,qP,Aj=fe(()=>{JT=require("node:worker_threads"),gj=w(require("fast-glob")),Rp=w(z());yP();AP();yp=require("node:path"),Sj=require("node:fs/promises");IP();Tj=require("micromatch"),XT=class{static{o(this,"ComponentV1")}config;name;directory;module;resources;globOptions;patternBases;baseURLPath;constructor(t){if(this.config=t.config,this.name=t.name,this.directory=t.directory,this.module=t.module,this.resources=t.resources,!$l(this.config.files)&&!MP(this.config.files)&&!Rj(this.config.files))throw new vP(this);if(typeof this.config.files=="object"&&!Array.isArray(this.config.files)){if(this.config.files.source===void 0||!MP(this.config.files.source)&&!$l(this.config.files.source))throw new UP(this);if(this.config.files.only!==void 0&&(typeof this.config.files.only!="string"||!["all","files","directories"].includes(this.config.files.only)))throw new xP(this);if(this.config.files.ignore!==void 0&&!MP(this.config.files.ignore)&&!$l(this.config.files.ignore))throw new BP(this)}if(this.config.root!==void 0&&!$l(this.config.root))throw new HP(this);if(this.config.path!==void 0&&!$l(this.config.path))throw new GP(this);if(this.config.path&&(Rp.default.warn("Resource extension 'path' option is deprecated. Please replace with 'urlPath'."),this.config.urlPath=this.config.path),this.config.urlPath!==void 0&&(!$l(this.config.urlPath)||typeof this.config.urlPath=="string"&&this.config.urlPath.includes("..")))throw new qP(this);this.globOptions=qT(this.config.files),this.globOptions.source=this.globOptions.source.map(r=>{if(r.includes(".."))throw new FP(this,r);return r.startsWith("/")&&(Rp.default.warn("Leading '/' in 'files' glob pattern is deprecated. For backwards compatibility purposes, it is currently transformed to the relative path of the component, but in the future will result in an error. Paths are automatically derived from the root of the component directory. Please remove (e.g. '/web/*' -> 'web/*')."),r=r==="/"?".":r.slice(1)),r}),this.patternBases=this.globOptions.source.map(r=>(0,Tj.scan)(r).base),this.baseURLPath=GT(this.name,this.config.urlPath)}},_i=class extends Error{static{o(this,"ComponentV1ProcessingError")}constructor(t,r){super(`Component ${r.name} (from ${(0,yp.basename)(r.directory)}) ${t}`)}},vP=class extends _i{static{o(this,"InvalidFilesOptionError")}constructor(t){super("'files' option must be a non-empty string, an array of non-empty strings, or an object.",t)}},UP=class extends _i{static{o(this,"InvalidFilesSourceOptionError")}constructor(t){super("'files' object must have a non-empty 'source' property.",t)}},xP=class extends _i{static{o(this,"InvalidFilesOnlyOptionError")}constructor(t){super("'files.only' option must be one of 'all', 'files', or 'directories'.",t)}},BP=class extends _i{static{o(this,"InvalidFileIgnoreOptionError")}constructor(t){super("'files.ignore' option must be a non-empty string or an array of non-empty strings.",t)}},FP=class extends _i{static{o(this,"InvalidGlobPattern")}constructor(t,r){super(`'files' glob pattern must not contain '..'. Received: '${r}'`,t)}},HP=class extends _i{static{o(this,"InvalidRootOptionError")}constructor(t){super("deprecated 'root' option must be a non-empty string. Consider removing and updating 'files' glob pattern instead.",t)}},kP=class extends _i{static{o(this,"InvalidRootOptionUseError")}constructor(t){super("the 'root' option is deprecated and only supported if 'files' is a singular, non-empty string. Please remove the 'root' option and modify the 'files' glob pattern instead.",t)}},GP=class extends _i{static{o(this,"InvalidPathOptionError")}constructor(t){super("deprecated 'path' option must be a non-empty string. Consider replacing with 'urlPath'.",t)}},qP=class extends _i{static{o(this,"InvalidURLPathOptionError")}constructor(t){super("'urlPath' option must be a non-empty string that must not contain '..'.",t)}};o($l,"isNonEmptyString");o(MP,"isArrayOfNonEmptyStrings");o(Rj,"isObject");o(pge,"handleRoots");o(yj,"processResourceExtensionComponent")});var bj={};Ce(bj,{SERVERS:()=>Jd,portServer:()=>$P,setPortServerMap:()=>ZT});function ZT(e,t){let r=$P.get(e)??[];$P.set(e,[...r,t])}var Jd,$P,VP=fe(()=>{Jd={},$P=new Map;o(ZT,"setPortServerMap")});var iR={};Ce(iR,{deliverSocket:()=>Bj,getHttpOptions:()=>Sge,getRequestId:()=>Gj,handleApplication:()=>gge,httpServer:()=>XP,logRequest:()=>Ip,proxyRequest:()=>Tge,registerServer:()=>QP,suppressHandleApplicationWarning:()=>_ge});function gge(e){Np=e.options.getAll(),e.options.on("change",t=>{Np=e.options.getAll()})}function Sge(){return Np}function Bj(e,t,r){let n=e?.read?e:new Cj.Socket({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Jd[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=o(a=>{setTimeout(()=>{let c=Jd[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):a<5?i(a+1):(Wo.default.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}function Tge(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=Ij.get(s),r){case"connection":i=Bj(void 0,t),Ij.set(s,i),i.write=(c,l,u)=>(tR.parentPort.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(tR.parentPort.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let a=i.destroy;i.destroy=()=>{a.call(i),tR.parentPort.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}}function QP(e,t,r=!0){t||(t=xr.default.get(U.HTTP_PORT));let n=Jd[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",Oj),s.on("unhandled",(i,a)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,a)}),n.lastServer=e}else Jd[t]=e;e.on("unhandled",Oj)}function JP(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=[],xr.default.get(U.HTTP_PORT)!=null&&t.push({port:xr.default.get(U.HTTP_PORT),secure:xr.default.get(U.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),xr.default.get(U.HTTP_SECUREPORT)!=null&&t.push({port:xr.default.get(U.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&xr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:(0,Pj.resolvePath)(xr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}function XP(e,t){let r=[];for(let{port:n,secure:s}of JP(t))r.push(Fj(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?zP[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,QP(e,n,!1)),rR[n]=nR(zP,n);return r}function Fj(e,t,r,n){if(ZT(e,{protocol_name:t?"HTTPS":"HTTP",name:oR()}),!eR[e]){let s=r?"operationsApi_network":"http",i=xr.default.get(s+"_keepAliveTimeout"),a=xr.default.get(s+"_timeout"),c=xr.default.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:a,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:xr.default.get(U.HTTP_MAXHEADERSIZE)},u=xr.default.get(s+"_mtls"),d=xr.default.get(s+"_mtls_required"),f;if(t){let p=xr.default.get("tls");f=xr.default.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!d,requestCert:!!(u||n),ticketKeys:(0,Lj.getTicketKeys)(),SNICallback:(0,Dj.createTLSSelector)(r?"operations-api":"server",u),ciphers:p.ciphers??p[0]?.ciphers})}let m=(0,Mj.checkMemoryLimit)(),h=eR[e]=(t?f?vj.createSecureServer:Uj.createServer:sR.createServer)(l,async(p,_)=>{let g=performance.now(),y=0;try{let R=new La(p,_);r&&(R.isOperationsServer=!0),Np.logging?.id&&(R.requestId=y=Gj());let I=await rR[e](R);if(!I){if(R._nodeResponse.statusCode){Ip(p,R._nodeResponse.statusCode,y,performance.now()-g);return}I=Hj(R)}if(I.headers?.set||(I.headers=new bs(I.headers)),m?I.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):I.headers?.set?.("Server","HarperDB"),I.status===-1){for(let re of I.headers||[])_.setHeader(re[0],re[1]);return p.baseRequest=R,_.baseResponse=I,eR[e].emit("unhandled",p,_)}let P=I.status||200,Y=performance.now(),te=Y-g,x=I.body,$,j=!1;if(!I.handlesHeaders){let re=I.headers||new bs;x?x.length>=0?(typeof x=="string"?re.set("Content-Length",Buffer.byteLength(x)):re.set("Content-Length",x.length),$=!0):x instanceof gs&&(x.size?re.set("Content-Length",x.size):x.on&&(j=!0,x.on("size",_e=>{_.headersSent||_.setHeader("Content-Length",_e)})),x=x.stream()):(re.set("Content-Length","0"),$=!0);let se=`hdb;dur=${te.toFixed(2)}`;if(I.wasCacheMiss&&(se+=", miss"),$m(re,"Server-Timing",se,!0),!_.headersSent)if(j){if(_.statusCode=P,re)if(re[Symbol.iterator])for(let[_e,Ne]of re)_.setHeader(_e,Ne);else for(let _e in re)_.setHeader(_e,re[_e])}else _.writeHead(P,re&&(re[Symbol.iterator]?Array.from(re):re));$&&_.end(x)}let V=R.handlerPath,le=R.method;if(gt(te,"duration",V,le,I.wasCacheMiss==null?void 0:I.wasCacheMiss?"cache-miss":"cache-hit"),Vr(P<400,"success",V,le),Vr(1,"response_"+P,V,le),Ip(p,P,y,te),!$)if(x instanceof ReadableStream&&(x=WP.Readable.fromWeb(x)),(x[Symbol.iterator]||x[Symbol.asyncIterator])&&(x=WP.Readable.from(x)),x?.pipe){x.pipe(_),x.destroy&&_.on("close",()=>{x.destroy()});let re=0;x.on("data",se=>{re+=se.length}),x.on("end",()=>{gt(performance.now()-Y,"transfer",V,le),gt(re,"bytes-sent",V,le)})}else x?.then?x.then(re=>{_.end(re)},T):_.end(x)}catch(R){T(R)}function T(R){let I=R.headers,P=R.statusCode||500;_.writeHead(P,I&&(I[Symbol.iterator]?Array.from(I):I)),_.end(Ege(R)),Ip(p,P,y,performance.now()-g),R.statusCode?R.statusCode===500?Wo.default.warn(R):Wo.default.info(R):Wo.default.error(R)}o(T,"onError")});i>=0&&(h.keepAliveTimeout=i),c>=0&&(h.headersTimeout=c),t&&(h.ports||(h.ports=[]),h.ports.push(e),l.SNICallback.initialize(h),u&&(h.mtlsConfig=u),h.on("secureConnection",p=>{p._parent.startTime&&gt(performance.now()-p._parent.startTime,"tls-handshake",e),gt(p.isSessionReused(),"tls-reused",e)}),h.isSecure=!0),QP(h,e)}return eR[e]}function nR(e,t){let r=Hj;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let a=r;r=o((...c)=>s(...c,a),"nextCallback")}}return r}function Hj(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new bs}}function Rge(e,t){XP(e,{requestOnly:!0,...t})}function kj(e,t){for(let{port:r}of JP(t))Nj[t?.runFirst?"unshift":"push"]({listener:e,port:r}),jP[r]=nR(Nj,r)}function yge(e,t){let r=[];for(let{port:n,secure:s}of JP(t)){ZT(n,{protocol_name:s?"WSS":"WS",name:oR()});let i=Fj(n,s,t?.isOperationsServer,t?.mtls);Ap[n]||(Ap[n]=new xj.WebSocketServer({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),Ap[n].on("connection",(a,c)=>{try{let l=new La(c);l.isWebSocket=!0;let u=rR[n](l);Wo.default.debug("Received WS connection, calling listeners",KP),wj[n](a,l,u)}catch(l){Wo.default.warn("Error in handling WS connection",l)}}),kj((a,c,l,u)=>a.__harperdbRequestUpgraded?u(a,c,l):Ap[n].handleUpgrade(a,c,l,d=>{a.__harperdbRequestUpgraded=!0,u(a,c,l),Ap[n].emit("connection",d,a)}),{port:n}),i.on("upgrade",(a,c,l)=>{jP[n]&&jP[n](a,c,l)})),r.push(i),KP[t?.runFirst?"unshift":"push"]({listener:e,port:n}),wj[n]=nR(KP,n),rR[n]=nR(zP,n)}return r}function Oj(e,t){t.writeHead(404),t.end(`Not found
34
- `),Ip(e,404,0,e.requestId)}function Ip(e,t,r,n){let s=Np.logging;if(s){YP||(YP=Wo.default.forComponent("http"));let i=t<400?"info":t===500?"error":"warn";YP[i]?.(`${e.method} ${e.url} ${e.socket.encrypted?"HTTPS":"HTTP"}/${e.httpVersion}${s.headers?" "+Age(e.headers):""} ${t}${s.timing&&n?" "+n.toFixed(2)+"ms":""}${r?" id: "+r:""}`)}}function Age(e){let t=[];for(let r in e)t.push(`${r}: ${e[r]}`);return t.join(", ")}function Gj(){return bp||(bp=new BigInt64Array([1n]),bp=new BigInt64Array(databases.system.hdb_analytics.primaryStore.getUserSharedBuffer("next-request-id",bp.buffer))),Number(Atomics.add(bp,0,1n))}var Cj,Wo,tR,xr,Pj,Lj,Dj,Mj,vj,Uj,sR,WP,xj,Ege,Ap,eR,rR,zP,Np,_ge,Ij,Nj,jP,KP,wj,YP,bp,ZP=fe(()=>{Cj=require("node:net"),Wo=w(z()),tR=require("node:worker_threads"),xr=w(ce());k();Pj=w(At()),Lj=w(st()),Dj=w(es()),Mj=w(Ad()),vj=require("node:http2"),Uj=require("node:https"),sR=require("node:http");Km();Vm();Ss();Fi();WP=require("node:stream");Pr();VP();vd();xj=require("ws"),{errorToString:Ege}=Wo.default;ve.http=XP;ve.request=Rge;ve.ws=yge;ve.upgrade=kj;Ap={},eR={},rR={},zP=[],Np={},_ge=!0;o(gge,"handleApplication");o(Sge,"getHttpOptions");o(Bj,"deliverSocket");Ij=new Map;o(Tge,"proxyRequest");o(QP,"registerServer");o(JP,"getPorts");o(XP,"httpServer");o(Fj,"getHTTPServer");o(nR,"makeCallbackChain");o(Hj,"unhandled");o(Rge,"onRequest");Object.defineProperty(sR.IncomingMessage.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){}});Nj=[],jP={};o(kj,"onUpgrade");KP=[],wj={};o(yge,"onWebSocket");o(Oj,"defaultNotFound");o(Ip,"logRequest");o(Age,"headersToString");o(Gj,"getRequestId")});var Yh={};Ce(Yh,{componentErrors:()=>wp,getComponentName:()=>oR,loadComponent:()=>uR,loadComponentDirectories:()=>Vj,setErrorReporter:()=>Ige});function Vj(e,t){t&&(tL=t),e&&(iL=e);let r=[];if((0,Pt.existsSync)(eL)){let s=(0,Pt.readdirSync)(eL,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,Br.join)(eL,a);r.push(uR(c,tL,Cy,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(uR(n,tL,n,!1,void 0,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{$j=!0})}function Ige(e){cR=e}function Nge(e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{qo.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(qo.primaryStore.attemptLock(e,0,()=>{clearTimeout(s),r()}))try{(0,Pt.rmSync)(t,{recursive:!0,force:!0}),(0,Pt.existsSync)((0,Br.join)(e,"node_modules"))||(0,Pt.mkdirSync)((0,Br.join)(e,"node_modules")),(0,Pt.symlinkSync)(aL.PACKAGE_ROOT,t,"dir"),r()}finally{qo.primaryStore.unlock(e,0)}})}function Kj(e,t){return e.ready.then(()=>{let r=e.options.get(["timeout"])||t.defaultTimeout||3e4;if(typeof r!="number")throw new Error(`Invalid timeout value for ${e.name}. Expected a number, received: ${typeof r}`);let n,s;return qo.primaryStore.attemptLock(e.name,0,()=>{clearTimeout(s),n(Kj(e,t))})?Promise.race([t.handleApplication(e),new Promise((i,a)=>setTimeout(()=>a(new Error(`handleApplication timed out after ${r}ms for ${e.name}`)),r))]).finally(()=>{qo.primaryStore.unlock(e.name,0)}):new Promise((i,a)=>{n=i,s=setTimeout(()=>{a(new Error(`Timeout waiting for lock on ${e.name}`))},r+5e3)})})}async function uR(e,t,r,n,s,i){let a=(0,Pt.realpathSync)(e);if(aR.has(a))return aR.get(a);aR.set(a,!0),s&&(iL=s);try{let c;n&&(wp=new Map);let l=(0,Br.join)(e,"harperdb-config.yaml");(0,Pt.existsSync)(l)?c=n?(0,dR.getConfigObj)():(0,nL.parseDocument)((0,Pt.readFileSync)(l,"utf8")).toJSON():!n&&(0,Pt.existsSync)(l=(0,Br.join)(e,"config.yaml"))?c=(0,nL.parseDocument)((0,Pt.readFileSync)(l,"utf8")).toJSON():c=KT;try{let m=(0,Br.join)(e,"node_modules","harperdb");(n||((0,Pt.existsSync)(m)||!e.startsWith((0,sL.getHdbBasePath)()))&&(!(0,Pt.existsSync)(m)||(0,Pt.realpathSync)(aL.PACKAGE_ROOT)!==(0,Pt.realpathSync)(m)))&&await Nge(e,m)}catch(m){zo.default.error("Error symlinking harperdb module",m),m.code=="EPERM"&&process.platform==="win32"&&zo.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=lR,d={};for(let m in c){lR=m;let h=c[m];if(wp.set(n?m:(0,Br.basename)(e),!1),!h)continue;let p,_=h.package;try{if(_){let I=e,P;for(;!(0,Pt.existsSync)(P=(0,Br.join)(I,"node_modules",m));)if(I=(0,Br.dirname)(I),I.length<(0,sL.getHdbBasePath)().length){P=null;break}if(P)p=await uR(P,t,r,!1),d[m]=!0;else throw new Error(`Unable to find package ${m}:${_}`)}else p=bge[m];if(!p)continue;let g=o(I=>(I.origin=r,Ze(I)),"ensureTable"),y=h.network||(h.port||h.securePort)&&h,T=y?.securePort||y?.https&&y.port,R=!y?.https&&y?.port;if("handleApplication"in p&&("start"in p||"startOnMainThread"in p||"handleFile"in p||"handleDirectory"in p||"setupFile"in p||"setupDirectory"in p))throw new Error(`Component ${m} has both 'handleComponent' and 'start' or 'startOnMainThread' methods. Please use only one of them.`);if(t.isWorker&&p.handleApplication){p.suppressHandleApplicationWarning!==!0&&zo.default.warn(`Plugin ${m} is using the experimental handleApplication API`);let I=new jT(m,e,l,t,ve);await Kj(I,p);continue}if(rL.isMainThread&&(p=await p.startOnMainThread?.({server:ve,ensureTable:g,port:R,securePort:T,resources:t,...h})||p,n&&y))for(let I of[R,T])try{if(+I&&!qj.includes(I)){let P=oL.get(U.HTTP_SESSIONAFFINITY);P&&zo.default.warn("Session affinity is not recommended and may cause memory leaks"),(P||!eg)&&(qj.push(I),iP(I,P))}}catch(P){console.error("Error listening on socket",I,P,m)}if(t.isWorker&&(p=await p.start?.({server:ve,ensureTable:g,port:R,securePort:T,resources:t,...h})||p),iL.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&h.files!=null){let I=new XT({config:h,name:m,directory:e,module:p,resources:t});d[m]=await yj(I)}}catch(g){g.message=`Could not load component '${m}' for application '${(0,Br.basename)(e)}' due to: ${g.message}`,cR?.(g),((0,Op.getWorkerIndex)()===0?console:zo.default).error(g),t.set(h.path||"/",new Hc(g),null,!0),wp.set(n?m:(0,Br.basename)(e),g.message)}}if(lR=u,rL.isMainThread&&!$j&&i&&(0,Op.watchDir)(e,async()=>Vj()),c.extensionModule||c.pluginModule){let m=await Y_((0,Br.join)(e,c.extensionModule||c.pluginModule));return aR.set(a,m),m}let f=Object.values(d);if(f.length>0&&f.every(m=>!m)&&t.isWorker){let m=`${e} did not load any modules, resources, or files, is this a valid component?`;cR?.(new Error(m)),((0,Op.getWorkerIndex)()===0?console:zo.default).error(m),wp.set((0,Br.basename)(e),m)}for(let[m,h]of Object.entries(d))h||zo.default.warn(`Component ${m} from (${(0,Br.basename)(e)}) did not load any functionality.`)}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,cR?.(c),t.set("",new Hc(c))}}var Pt,Br,rL,nL,oL,aL,zo,Op,sL,dR,eL,iL,$j,tL,wp,bge,qj,aR,cR,lR,oR,vd=fe(()=>{Pt=require("node:fs"),Br=require("node:path"),rL=require("node:worker_threads"),nL=require("yaml"),oL=w(ce()),aL=w(Rt());k();qM();Cv();XF();sH();iH();KH();VW();QW();XW();zo=w(z());sz();Op=w(st());OI();Pr();Le();aP();sL=w(ce());wz();BS();Uz();Xn();jz();dR=w(At());Km();mA();_j();Aj();ZP();Zh();wP();eL=(0,dR.resolvePath)(oL.get(U.COMPONENTSROOT)),iL=new Map,wp=new Map;o(Vj,"loadComponentDirectories");bge={REST:ng,rest:ng,graphql:pA,graphqlSchema:Jy,roles:wI,jsResource:CI,fastifyRoutes:JC,login:LI,static:XC,operationsApi:lP,customFunctions:{},http:iR,clustering:pP,replication:Po,authentication:Hh,mqtt:TP,loadEnv:ZC,logging:zo.default,dataLoader:eP},qj=[],aR=new Map;o(Ige,"setErrorReporter");oR=o(()=>lR,"getComponentName");o(Nge,"symlinkHarperModule");o(Kj,"sequentiallyHandleApplication");o(uR,"loadComponent")});var DT=M((aBe,Wj)=>{var{isMainThread:Yj}=require("worker_threads"),{getTables:wge,getDatabases:iBe,table:oBe}=(Le(),v(ft)),{loadComponentDirectories:Oge,loadComponent:Cge}=(vd(),v(Yh)),{resetResources:Pge}=(_u(),v(Sv)),Lge=DO(),Dge=At(),{dirname:Mge}=require("path"),{getConnection:vge}=lr(),Uge=ce(),{CONFIG_PARAMS:xge}=(k(),v(K)),{loadCertificates:Bge}=es(),cL=new Map;async function Fge(e=!1){!Yj&&Uge.get(xge.CLUSTERING_ENABLED)&&vge();try{Yj&&await Lge()}catch(n){console.error(n)}let t=Pge();wge(),t.isWorker=e,await Bge(),await Cge(Mge(Dge.getConfigFilePath()),t,"hdb",!0,cL),await Oge(cL,t);let r=[];for(let[n]of cL)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}o(Fge,"loadRootComponents");Wj.exports.loadRootComponents=Fge});var st=M((lBe,Si)=>{"use strict";wy();var{Worker:Hge,MessageChannel:kge,parentPort:ji,isMainThread:mL,threadId:Gge,workerData:Qi}=require("worker_threads"),{PACKAGE_ROOT:qge}=Rt(),{join:Jj,isAbsolute:$ge,extname:Vge}=require("path"),{server:Xj}=(Pr(),v(Kf)),{watch:Kge,readdir:Yge}=require("fs/promises"),{totalmem:zj}=require("os"),Xd=(k(),v(K)),Zj=ce(),gi=z(),{randomBytes:Wge}=require("crypto"),{_assignPackageExport:zge}=Ws(),jj=1024*1024,nc=[],Fs=[],jge=50,hL=1e4,Qge="restart",e2="request_thread_info",t2="resource_report",r2="thread_info",n2="added-port",Jge="ack",lL;zge("threads",Fs);Si.exports={startWorker:uL,restartWorkers:EL,shutdownWorkers:rSe,workers:nc,setMonitorListener:uSe,onMessageFromWorkers:nSe,onMessageByType:u2,broadcast:iSe,broadcastWithAcknowledgement:aSe,setChildListenerByType:tSe,getWorkerIndex:s2,getWorkerCount:i2,getTicketKeys:a2,setMainIsWorker:Zge,setTerminateTimeout:Xge,restartNumber:Qi?.restartNumber||1};Fs.onMessageByType=u2;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};Si.exports.whenThreadsStarted=new Promise(e=>{Si.exports.threadsHaveStarted=e});var pL;function Xge(e){hL=e}o(Xge,"setTerminateTimeout");function s2(){return Qi?Qi.workerIndex:pL?0:void 0}o(s2,"getWorkerIndex");function i2(){return Qi?Qi.workerCount:pL?1:void 0}o(i2,"getWorkerCount");function Zge(e){pL=e,Si.exports.threadsHaveStarted()}o(Zge,"setMainIsWorker");var o2=1,fR;function a2(){return fR||(fR=mL?Wge(48):Qi.ticketKeys,fR)}o(a2,"getTicketKeys");Object.defineProperty(Xj,"workerIndex",{get(){return s2()}});Object.defineProperty(Xj,"workerCount",{get(){return i2()}});var c2={[e2](e,t){cSe(t)},[t2](e,t){lSe(t,e)}};function uL(e,t={}){let r=process.constrainedMemory?.()||zj();r=Math.min(r,zj(),2e4*jj);let n=Zj.get(Xd.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/jj/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],a=[];for(let l of Fs){let u=new kge;u.existingPort=l,i.push(u),a.push(u.port2)}Vge(e)||(e+=".js");let c=new Hge($ge(e)?e:Jj(qge,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:a,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:o2=t.threadCount,name:t.name,restartNumber:Si.exports.restartNumber,ticketKeys:a2()},transferList:a,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:n2,port:l,threadId:c.threadId},[l]);return hR(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>uL(e,t),c.on("error",l=>{gi.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{nc.splice(nc.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<jge?(t.unexpectedRestarts=c.unexpectedRestarts+1,uL(e,t)):gi.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{c2[l.type]?.(l,c)}),nc.push(c),fSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}o(uL,"startWorker");var eSe=[Xd.THREAD_TYPES.HTTP];async function EL(e=null,t=Math.max(o2>3,1),r=!0){if(mL){try{process.chdir(process.cwd())}catch(a){gi.error("Unable to reestablish current working directory",a)}if(r){let{loadRootComponents:a}=DT();await a()}Si.exports.restartNumber++,t<1&&(t=t*nc.length);let n=[],s=[];for(let a of nc.slice(0)){if(e&&a.name!==e||a.wasShutdown)continue;gi.trace("sending shutdown request to ",a.threadId),a.postMessage({restartNumber:Si.exports.restartNumber,type:Xd.ITC_EVENT_TYPES.SHUTDOWN}),a.wasShutdown=!0,a.emit("shutdown",{});let c=eSe.indexOf(a.name)>-1,l=new Promise(u=>{let d=setTimeout(()=>{gi.warn("Thread did not voluntarily terminate, terminating from the outside",a.threadId),a.terminate()},hL*2).unref();a.on("exit",()=>{clearTimeout(d),n.splice(n.indexOf(l)),!c&&r&&a.startCopy(),u()})});if(n.push(l),c&&r){let u=a.startCopy(),d=new Promise(f=>{let m=o(h=>{h.type===Xd.ITC_EVENT_TYPES.CHILD_STARTED&&(gi.trace("Worker has started",u.threadId),f(),s.splice(s.indexOf(d)),u.off("message",m))},"startListener");gi.trace("Waiting for worker to start",u.threadId),u.on("message",m)});s.push(d),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}=Pd();r&&(e==="http"||!e)&&Zj.get(Xd.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ji.postMessage({type:Qge,workerType:e})}o(EL,"restartWorkers");function tSe(e,t){c2[e]=t}o(tSe,"setChildListenerByType");function rSe(e){return EL(e,1/0,!1)}o(rSe,"shutdownWorkers");var l2=[];function nSe(e){l2.push(e)}o(nSe,"onMessageFromWorkers");var dL=new Map;function u2(e,t){let r=dL.get(e);r||dL.set(e,r=[]),r.push(t)}o(u2,"onMessageByType");var sSe=10;async function iSe(e,t){let r=0;for(let n of Fs)try{n.postMessage(e),r++>sSe&&(r=0,await new Promise(setImmediate))}catch(s){gi.error("Unable to send message to worker",s)}t&&f2(e,null)}o(iSe,"broadcast");var mR=new Map,oSe=1;function aSe(e){return new Promise(t=>{let r=0;for(let n of Fs)try{let s=oSe++,i=o(()=>{mR.delete(s),--r===0&&t(),n!==ji&&--n.refCount===0&&n.unref()},"ackHandler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,mR.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,a]of mR)a.port===n&&a()})),n.postMessage(e),r++}catch(s){gi.error("Unable to send message to worker",s)}r===0&&t()})}o(aSe,"broadcastWithAcknowledgement");function cSe(e){e.postMessage({type:r2,workers:d2()})}o(cSe,"sendThreadInfo");function d2(){let e=Date.now();return nc.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}))}o(d2,"getChildWorkerInfo");function lSe(e,t){e.resources=t,e.resources.updated=Date.now()}o(lSe,"recordResourceReport");var fL;function uSe(e){fL=e}o(uSe,"setMonitorListener");var dSe=1e3,Qj=!1;function fSe(){Qj||(Qj=!0,setInterval(()=>{for(let e of nc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}fL&&fL()},dSe).unref())}o(fSe,"startMonitoring");var mSe=1e3;if(ji&&Qi?.addPorts){hR(ji);for(let e=0,t=Qi.addPorts.length;e<t;e++){let r=Qi.addPorts[e];r.threadId=Qi.addThreadIds[e],hR(r)}setInterval(()=>{let e=process.memoryUsage();ji.postMessage({type:t2,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},mSe).unref(),lL=o(()=>new Promise((e,t)=>{ji.on("message",r),ji.postMessage({type:e2});function r(n){n.type===r2&&(ji.off("message",r),e(n.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else lL=d2;Si.exports.getThreadInfo=lL;function hR(e,t){Fs.push(e),e.on("message",r=>{if(r.type===n2)r.port.threadId=r.threadId,hR(r.port);else if(r.type===Jge){let n=mR.get(r.id);n&&n()}else f2(r,e)}).on("close",()=>{Fs.splice(Fs.indexOf(e),1)}).on("exit",()=>{Fs.splice(Fs.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(hR,"addPort");function f2(e,t){for(let n of l2)n(e,t);let r=dL.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){gi.error(s)}}o(f2,"notifyMessageListeners");if(mL){let e,t,r=new Set,n=o(async(s,i)=>{i&&(e=i);for(let a of await Yge(s,{withFileTypes:!0}))a.isDirectory()&&a.name!=="node_modules"&&n(Jj(s,a.name));try{for await(let{filename:a}of Kge(s,{persistent:!1}))r.add(a),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await EL(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(a){console.warn("Error trying to watch component directory",s,a)}},"watchDir");Si.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ji.on("message",async e=>{let{type:t}=e;t===Xd.ITC_EVENT_TYPES.SHUTDOWN&&(Si.exports.restartNumber=e.restartNumber,ji.unref(),setTimeout(()=>{gi.warn("Thread did not voluntarily terminate",Gge),process.exit(0)},hL).unref())})});var _2={};Ce(_2,{onStorageReclamation:()=>Cp,runReclamationHandlers:()=>TL,setAvailableSpaceRatioGetter:()=>pSe});function Cp(e,t,r){(r||(0,ER.getWorkerIndex)()===(0,ER.getWorkerCount)()-1)&&(pR.has(e)||pR.set(e,[]),pR.get(e).push({priority:0,handler:t}),SL||(SL=setTimeout(TL,h2).unref()))}async function TL(){for(let[e,t]of pR)try{let r=await E2(e),n=hSe/r;for(let s of t){let{priority:i,handler:a}=s;if(s.priority=n,n>1||i>1){let c=a(n>1?n:0);c&&(gL.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){gL.default.error?.("Error running storage reclamation handlers",r)}SL=setTimeout(TL,h2).unref()}function pSe(e){E2=e??p2}var _L,ER,gL,_R,m2,pR,hSe,h2,SL,p2,E2,gR=fe(()=>{_L=require("node:fs/promises"),ER=w(st()),gL=w(Ii());k();_R=w(ce()),m2=w(ie());_R.default.initSync();pR=new Map,hSe=_R.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,h2=(0,m2.convertToMS)(_R.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;o(Cp,"onStorageReclamation");p2=o(async e=>{if(_L.statfs){let t=await(0,_L.statfs)(e);return t.bavail/t.blocks}else return new Promise((t,r)=>{import("hdd-space").then(n=>{n.default(s=>{for(let i of s.parts)if(e.startsWith(i.place))return t(i.free/i.size);return t(1)})})})},"defaultGetAvailableSpaceRatio"),E2=p2;o(TL,"runReclamationHandlers");o(pSe,"setAvailableSpaceRatioGetter")});var pF={};Ce(pF,{ACTION_32_BIT:()=>AR,ACTION_64_BIT:()=>gSe,AUDIT_STORE_OPTIONS:()=>vh,Decoder:()=>Tl,HAS_BLOBS:()=>Dn,HAS_CURRENT_RESIDENCY_ID:()=>gl,HAS_EXPIRATION_EXTENDED_TYPE:()=>vp,HAS_ORIGINATING_OPERATION:()=>Mp,HAS_PREVIOUS_RESIDENCY_ID:()=>Sl,REMOTE_SEQUENCE_UPDATE:()=>Fg,createAuditEntry:()=>od,getLastRemoved:()=>ew,openAuditStore:()=>RR,readAuditEntry:()=>Ut,removeAuditEntry:()=>yR,setAuditRetention:()=>_Se,transactionKeyEncoder:()=>N2});function RR(e){let t=e.auditStore=e.openDB(RL.AUDIT_STORE_NAME,{create:!1,...vh});t||(t=e.auditStore=e.openDB(RL.AUDIT_STORE_NAME,vh),S2(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,d){return r[l]=d,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,a=AL;Cp(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(a=l),clearTimeout(n);let u=new Promise(d=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let f=0,m,h;try{for(let{key:p,value:_}of t.getRange({start:1,snapshot:!1,end:Date.now()-yL/(1+i*i)})){try{m=yR(t,p,_)}catch(g){Zd.warn("Error removing audit entry",g)}if(h=p,await new Promise(setImmediate),++f>=ESe){a=10;break}}await m}finally{f===0?a=Math.min(a<<1,yL/10):(S2(t,h),a>100&&(a=a>>1)),d(void 0),c()}},a).unref()});return u}if(o(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,Lp.getWorkerIndex)()===(0,Lp.getWorkerCount)()-1&&c(),(0,Lp.getWorkerIndex)()===0&&!g2)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(g2=!0,Zd.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 yR(e,t,r){let n=SSe(r),s;if(n&Dn){s=Ut(r);let i=e.tableStores[s.tableId],a=i?.getEntry(s.recordId);(!a||a.version!==s.version||!a.value)&&xc(()=>Ea(s.getValue(i)),i.rootStore)}if((n&15)===bL){s=s||Ut(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 S2(e,t){IL[0]=t,e.put(Symbol.for("last-removed"),w2)}function ew(e){let t=e.get(Symbol.for("last-removed"));if(t)return w2.set(t),IL[0]}function _Se(e,t=AL){yL=e,AL=t}function od(e,t,r,n,s,i,a,c,l,u,d,f,m){let h=O2[a];if(!h)throw new Error(`Invalid audit entry type ${a}`);let p=1;if(n&&(n>1?sc.setFloat64(0,n):Hs.set(NL),p=9),l){if(l&255)throw new Error("Illegal extended type");p+=3}y(s),y(t),g(r),sc.setFloat64(p,e),p+=8,l&gl&&y(u),l&Sl&&y(d),l&vp&&(sc.setFloat64(p,f),p+=8),l&Mp&&y(C2[m]),i?g(i):Hs[p++]=0,l?sc.setUint32(n?8:0,h|l|3221225472):Hs[n?8:0]=h;let _=Hs.subarray(0,p);if(c)return Buffer.concat([_,c]);return _;function g(T){let R=p;p+=1,p=(0,Vl.writeKey)(T,Hs,p);let I=p-R-1;I>127?I>16383?(Zd.error("Key or username was too large for audit entry",T),p=R+1,Hs[R]=0):(Hs.copyWithin(R+2,R+1,p),sc.setUint16(R,I|32768),p++):Hs[R]=I}function y(T){T<128?Hs[p++]=T:T<16384?(sc.setUint16(p,T|32768),p+=2):T<1056964608?(sc.setUint32(p,T|3221225472),p+=4):(Hs[p]=255,sc.setUint32(p+1,T),p+=5)}}function SSe(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 Tl(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Ut(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Tl(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),a=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,d=n.position+=l,f=n.readFloat64(),m,h,p,_;if(i&gl&&(m=n.readInt()),i&Sl&&(h=n.readInt()),i&vp&&(p=n.readFloat64()),i&Mp){let R=n.readInt();_=C2[R]}l=n.readInt();let g=n.position,y=n.position+=l,T;return{type:O2[i&7],tableId:c,nodeId:a,get recordId(){return(0,Vl.readKey)(e,u,d)},getBinaryRecordId(){return e.subarray(u,d)},version:f,previousLocalTime:s,get user(){return y>g?(0,Vl.readKey)(e,g,y):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(R,I,P){if(i&SR||i&Pp&&!I)return T||(T=xc(()=>R.decoder.decode(e.subarray(n.position,r)),R.rootStore)),T;if(i&Pp&&P)return fI(R.getEntry(this.recordId),P,R)},getBinaryValue(){return i&(SR|Pp)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:m,previousResidencyId:h,expiresAt:p,originatingOperation:_}}catch(n){return Zd.error("Reading audit entry error",n,e),{}}}var Vl,TR,RL,Lp,I2,Zd,Hs,sc,N2,vh,yL,ESe,IL,w2,AL,g2,SR,Pp,T2,bL,R2,y2,A2,b2,AR,gSe,Fg,gl,Sl,Mp,vp,Dn,O2,C2,Tl,Io=fe(()=>{Vl=require("ordered-binary"),TR=w(ce()),RL=w(kt());k();Lp=w(st()),I2=w(ie());kc();Zd=w(z());U_();Ss();gR();(0,TR.initSync)();Hs=Buffer.alloc(2816),sc=new DataView(Hs.buffer,Hs.byteOffset,2816),N2={writeKey(e,t,r){return e===Dp?(t.set(Dp,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Vl.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,Vl.readKey)(e,t,r)}},vh={encoding:"binary",keyEncoder:N2},yL=(0,I2.convertToMS)((0,TR.get)(U.LOGGING_AUDITRETENTION))||86400*3,ESe=1e3,IL=new Float64Array(1),w2=new Uint8Array(IL.buffer),AL=1e4,g2=!1;o(RR,"openAuditStore");o(yR,"removeAuditEntry");o(S2,"updateLastRemoved");o(ew,"getLastRemoved");o(_Se,"setAuditRetention");SR=16,Pp=32,T2=1,bL=2,R2=3,y2=4,A2=5,b2=6,AR=14,gSe=15,Fg=11,gl=512,Sl=1024,Mp=2048,vp=4096,Dn=8192,O2={put:T2|SR,[T2]:"put",delete:bL,[bL]:"delete",message:R2|SR,[R2]:"message",invalidate:y2|Pp,[y2]:"invalidate",patch:A2|Pp,[A2]:"patch",relocate:b2,[b2]:"relocate"},C2={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};o(od,"createAuditEntry");o(SSe,"readAction");o(Ut,"readAuditEntry");Tl=class extends DataView{static{o(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}}}});var Gv={};Ce(Gv,{ENTRY:()=>RSe,HAS_EXPIRATION:()=>NR,HAS_RESIDENCY_ID:()=>DL,HAS_STRUCTURE_UPDATE:()=>qg,LAST_TIMESTAMP_PLACEHOLDER:()=>Dp,LOCAL_TIMESTAMP:()=>TSe,METADATA:()=>ad,NEW_TIMESTAMP_PLACEHOLDER:()=>L2,NO_TIMESTAMP:()=>wL,PENDING_LOCAL_TIME:()=>ML,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>NL,RecordEncoder:()=>LL,TIMESTAMP_ASSIGN_LAST:()=>ASe,TIMESTAMP_ASSIGN_NEW:()=>D2,TIMESTAMP_ASSIGN_PREVIOUS:()=>M2,TIMESTAMP_PLACEHOLDER:()=>bR,TIMESTAMP_RECORD_PREVIOUS:()=>OL,entryMap:()=>ic,handleLocalTimeForGets:()=>wR,lastMetadata:()=>ct,recordUpdater:()=>vL,removeEntry:()=>Yl});function ISe(){return Bp[0]=Bp[0]^64,ySe.getFloat64(0)}function wR(e,t){let r=e.getEntry;e.readCount=0,e.cachePuts=!1,e.rootStore=t,e.encoder.rootStore=t,e.getEntry=function(a,c){e.readCount++,ct=null;let l=r.call(this,a,c);return l&&(ct&&(l.metadataFlags=ct[ad],l.localTime=ct.localTime,l.residencyId=ct.residencyId,ct.expiresAt>=0&&(l.expiresAt=ct.expiresAt),ct=null),l.value&&ic.set(l.value,l),l.key=a),l};let n=e.get;e.get=function(a,c){ct=null;let l=n.call(this,a,c);return ct&&l&&(ic.set(l,ct),ct=null),l};let s=e.getRange;e.getRange=function(a){let c=s.call(this,a);return a.valuesForKey?c.map(l=>l?.value):a.values===!1||a.onlyCount?c:c.map(l=>(ct&&(l.metadataFlags=ct[ad],l.localTime=ct.localTime,l.residencyId=ct.residencyId,ct.expiresAt>=0&&(l.expiresAt=ct.expiresAt),ct=null),l))};let i=e.useReadTransaction();if(i.done(),!i.done.isTracked){let a=i.constructor,c=i.use,l=i.done;a.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Kl.push(new WeakRef(this))),c.call(this)},a.prototype.done=function(){if(l.call(this),this.isDone)for(let u=0;u<Kl.length;u++){let d=Kl[u].deref();(!d||d.isDone||d.isCommitted)&&Kl.splice(u--,1)}},a.prototype.done.isTracked=!0}return e}function vL(e,t,r){return function(n,s,i,a,c=-1,l,u,d="put",f,m){f||l==null?ef=i?.localTime?OL|M2:wL:ef=l?i?.localTime?OL|16384:D2|16384:wL;let h=u?.expiresAt;if(h>=0&&(c|=NR),xp=c,CL=h,i?.version===a&&l===!1)throw new Error("Must retain local time if version is not changed");let p={version:a,instructedWrite:ef>0},_,g=0;try{let y=i?.residencyId,T=u?.residencyId;T&&(PL=T,xp|=DL,g|=gl),y!==T&&(g|=Sl,y||(y=0)),c&NR&&(g|=vp),u?.originatingOperation&&(g|=Mp),f&&(p.ifVersion=_=i?.version??null),i&&i.value&&i.metadataFlags&Dn&&(r.getBinaryFast(i.localTime)||Ea(i.value));let R;if(s!==void 0&&(R=$E(()=>e.put(n,s,p),n,e.rootStore),Uc&&(g|=Dn)),l){let I=u?.user?.username;if(m&&($E(()=>e.encoder.encode(m),n,e.rootStore),Uc&&(g|=Dn)),e.encoder.hasStructureUpdate&&(g|=qg,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let P=i?.localTime,Y=r.get(P);if(Y){let te=Ut(Y).previousLocalTime;return R=r.put(P,od(a,t,n,te,u?.nodeId??server.replication.getThisNodeId(r)??0,I,d,Up,g,T,y,h),{ifVersion:_}),R}}R=r.put(s===void 0?L2:Dp,od(a,t,n,i?.localTime?1:0,u?.nodeId??server.replication?.getThisNodeId(r)??0,I,d,Up,g,T,y,h,u?.originatingOperation),{append:d!=="invalidate",instructedWrite:!0,ifVersion:_})}return R}catch(y){throw y.message+=" id: "+n+" options: "+p,y}}}function Yl(e,t,r){if(t)return t.value&&t.metadataFlags&Dn&&!e.auditStore.getBinaryFast(t.localTime)&&Ea(t.value),e.remove(t.key,r)}var P2,IR,bR,Dp,NL,L2,TSe,ad,RSe,Bp,ySe,wL,D2,ASe,M2,OL,NR,DL,ML,qg,ic,bSe,Up,ef,xp,CL,PL,ct,LL,Kl,kc=fe(()=>{P2=require("msgpackr");Io();IR=w(z());Ss();Ss();bR=new Uint8Array([1,1,1,1,4,64,0,0]),Dp=new Uint8Array([1,1,1,1,1,0,0,0]),NL=new Uint8Array([1,1,1,1,3,64,0,0]),L2=new Uint8Array([1,1,1,1,0,64,0,0]),TSe=Symbol("local-timestamp"),ad=Symbol("metadata"),RSe=Symbol("entry"),Bp=new Uint8Array(8),ySe=new DataView(Bp.buffer,0,8),wL=0,D2=0,ASe=1,M2=3,OL=4,NR=16,DL=32,ML=1,qg=256,ic=new WeakMap,ef=0,xp=-1,CL=-1,PL=0,ct=null,LL=class extends P2.Encoder{static{o(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0;class r{static{o(this,"RecordObject")}getUpdatedTime(){return ic.get(this)?.version}getExpiresAt(){return ic.get(this)?.expiresAt}}t.structPrototype=r.prototype,super(t);let n=this.encode;this.encode=function(i,a){if(ef||xp>=0){let c=0,l=ef;l&&(c+=8,ef=0);let u=xp,d=CL,f=PL;u>=0&&(c+=4,xp=-1,d>=0&&(c+=8,CL=-1),f&&(c+=4,PL=0));let m=bSe=n.call(this,i,a|2048|c);Up=m.subarray((m.start||0)+c,m.end);let h=m.start||0;return l&&(bR[4]=l,bR[5]=l>>8,m.set(bR,h),h+=8),Uc&&(u|=Dn),u>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,u|AR<<24),h+=4,d>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setFloat64(h,d),h+=8),f&&(m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,f)),m}else return Up=n.call(this,i,a),Up};let s=this.saveStructures;this.saveStructures=function(i,a){let c=s.call(this,i,a);return this.hasStructureUpdate=!0,c}}decode(t,r){ct=null;let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],a=0;try{if(i<32&&s>2){let c=n,l;if(i===2){if(t.copy)t.copy(Bp,0,c),c+=8;else for(let m=0;m<8;m++)Bp[m]=t[c++];l=ISe(),i=t[c]}let u,d;i<32&&(i===AR?(a=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4):(a=i|t[c+1]<<5,c+=2),a&NR&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),a&DL&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=xc(()=>r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c),this.rootStore);return ct={localTime:l,[ad]:a,expiresAt:u,residencyId:d},f}return r?.valueAsBuffer?t:xc(()=>super.decode(t,r),this.rootStore)}catch(c){return IR.error("Error decoding record",c,"data: "+t.slice(0,40).toString("hex")),null}}};o(ISe,"getTimestamp");o(wR,"handleLocalTimeForGets");Kl=[];setInterval(()=>{for(let e=0;e<Kl.length;e++){let t=Kl[e].deref();!t||t.isDone||t.isCommitted?Kl.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(IR.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):IR.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();o(vL,"recordUpdater");o(Yl,"removeEntry")});function BL(e,t,r,n,s,i,a,c){let l=e[0];if(t==="or"){let f=u(l);for(let h=1;h<e.length;h++){let p=e[h],_=u(p);f=f.concat(_)}let m=new Set;return f.filter(h=>{let p=h.key??h;return m.has(p)?!1:(m.add(p),!0)})}else{let f=u(l),m=d(e.slice(1),!0,l.estimated_count);return m.length>0?a(f,m):f}function u(f){return f.conditions?BL(f.conditions,f.operator,r,n,s,i,a,c):sf(f,n,f.descending||s.reverse===!0,r,s.allowFullScan,c,i)}o(u,"executeCondition");function d(f,m,h){return f.map((p,_)=>{if(p.conditions){let T=p.operator==="or",R=d(p.conditions,!T,h);return T?(I,P)=>R.some(Y=>Y(I,P)):(I,P)=>R.every(Y=>Y(I,P))}let g=(p.attribute||p[0])===r.primaryKey,y=Hp(p,r,i,c,g,h);return m&&_<f.length-1&&h&&(h=vSe(r.primaryStore,p.estimated_count,h)),y}).filter(Boolean)}o(d,"mapConditionsToFilters")}function sf(e,t,r,n,s,i,a){let c=e[0]??e.attribute,l=e[1]??e.value,u=e.comparator;if(l===void 0&&u!=="sort")throw new Qr.ClientError(`Search condition for ${c} must have a value`);if(Array.isArray(c)){let R=c[0],I=Xi(n.attributes,R);if(I.relationship){if(c.length<2)throw new Qr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let P=I.definition?.tableClass||I.elements?.definition?.tableClass,Y=new Map,te=sf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:u},t,r,P,s,Y);if(I.relationship.to){i[c[0]]=Y;let x=!!Xi(P.attributes,I.relationship.to)?.elements;te=PSe(te,I,P.primaryStore,x,Y)}if(I.relationship.from){let x=o($=>($?.key!==void 0&&($=$.key),sf({attribute:I.relationship.from,value:$},t,r,n,s,Y)),"searchEntry");I.elements?(i[c[0]]=Y,te=LSe(te,I,P.primaryStore,Y,x)):te=te.flatMap(x)}return te}else if(c.length===1)c=c[0];else throw new Qr.ClientError("Unable to query by attribute "+JSON.stringify(c))}let d=c===n.primaryKey||c==null,f=d?n.primaryStore:n.indices[c],m,h,p,_;l instanceof Date&&(l=l.getTime());let g;switch(FL[u]||u){case"lt":m=!0,h=l;break;case"le":m=!0,h=l,p=!0;break;case"gt":m=l,_=!0;break;case"ge":m=l;break;case"prefix":Array.isArray(l)?l[l.length-1]!=null&&(l=l.concat(null)):l=[l,null],m=l,h=l.slice(0),h[h.length-1]=Ji.MAXIMUM_KEY;break;case"starts_with":m=l.toString(),h=l+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":m=l[0],m instanceof Date&&(m=m.getTime()),h=l[1],h instanceof Date&&(h=h.getTime()),p=u==="gele"||u==="gtle"||u==="between",_=u==="gtlt"||u==="gtle";break;case"equals":case void 0:m=l,h=l,p=!0;break;case"ne":if(l===null){m=l,_=!0;break}case"sort":case"contains":case"ends_with":m=!0,g=!0;break;default:throw new Qr.ClientError(`Unknown query comparator "${u}"`)}let y;if(typeof m=="string"&&m.length>ks.MAX_SEARCH_KEY_LENGTH&&(m=m.slice(0,ks.MAX_SEARCH_KEY_LENGTH)+ks.OVERFLOW_MARKER,_=!1,y=Hp(e,n,null,i,d)),typeof h=="string"&&h.length>ks.MAX_SEARCH_KEY_LENGTH&&(h=h.slice(0,ks.MAX_SEARCH_KEY_LENGTH)+ks.OVERFLOW_MARKER,p=!0,y=y??Hp(e,n,null,i,d)),r){let R=m;m=h,h=R,R=!_,_=!p,p=R}if(!f||f.isIndexing||g||l===null&&!f.indexNulls){if(s===!1&&!f)throw new Qr.ClientError(`"${c}" is not indexed, can not search for this attribute`,404);if(s===!1&&g)throw new Qr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${c}`,403);if(f?.isIndexing)throw new Qr.ServerError(`"${c}" is not indexed yet, can not search for this attribute`,503);if(l===null&&f&&!f.indexNulls)throw new Qr.ClientError(`"${c}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(y=y??Hp(e,n,null,i,d),!y)throw new Qr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:m,end:h,inclusiveEnd:p,exclusiveStart:_,values:!0,versions:d,transaction:t,reverse:r};if(d){let R=f.getRange(T).map(y?function({key:I,value:P}){return this?.isSync?P&&y(P)?I:oc.SKIP:new Promise((Y,te)=>setImmediate(()=>{try{Y(P&&y(P)?I:oc.SKIP)}catch(x){te(x)}}))}:I=>I.value==null&&!(I.metadataFlags&(Fn|ac))?oc.SKIP:I);return R.hasEntries=!0,R}else return f?f.customIndex?f.customIndex.search(e,a).map(R=>{if(typeof R=="object"&&R){let{key:I,...P}=R,Y=n.primaryStore.getEntry(I);return{...P,...Y}}return R}):f.getRange(T).map(y?function({key:R,value:I}){let P;return typeof R=="string"&&R.length>ks.MAX_SEARCH_KEY_LENGTH?P=n.primaryStore.get(I):P={[c]:R},this.isSync?y(P)?I:oc.SKIP:new Promise((Y,te)=>setImmediate(()=>{try{Y(y(P)?I:oc.SKIP)}catch(x){te(x)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:I}){return this.isSync?I&&y(I)?R:oc.SKIP:new Promise((P,Y)=>setImmediate(()=>{try{P(I&&y(I)?R:oc.SKIP)}catch(te){Y(te)}}))})}function Xi(e,t){if(Array.isArray(t))if(t.length>1){let r=Xi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Xi(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 PSe(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=o((u,d)=>{let f=s.get(u);f?f.push(d):s.set(u,f=[d])},"addEntry");for(let u of e){let d=u.value??r.get(u.key??u),f=d?.[c];if(f!=null&&!s.filters?.some(m=>!m(d)))if(n)for(let m=0;m<f.length;m++)l(f[m],u);else l(f,u)}return i=s.keys()[Symbol.iterator](),this.next()}let a=i.next();return a.done?a:{value:a.value}},return(){if(i?.return)return i.return()}}}})}function LSe(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,a,c=new Set;return{next(){let l;if(a)for(;l=a.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>u.has(f));for(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(m=>!m(f)))continue}u.add(d)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(a=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return a?.return?.()},throw(){return a?.throw?.()}}}})}function Hp(e,t,r,n,s,i){let a=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 d=c[0],f=Xi(t.attributes,d),m=f.definition?.tableClass||f.elements.definition?.tableClass,h=n?.[d],p=Hp({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:a},m,r,h?.[d]?.joined,c[1]===m.primaryKey,i);if(!p)return;if(h){h.filters||(h.filters=[]),h.filters.push(p);return}let _=t.propertyResolvers?.[d];_.to&&(p.to=_.to);let g,y=o((R,I)=>{let P,Y;return _?_.returnDirect?(P=_(R,r,I),Y=ct):(Y=_(R,r,I,!0),Array.isArray(Y)?(P=Y.map(te=>te.value),Y=null):P=Y?.value):P=R[d],{subObject:P,subEntry:Y}},"getSubObject"),T=o((R,I)=>{if(_&&p.idFilter){if(!g)if(p.idFilter.idSet?.size===1){for(let $ of p.idFilter.idSet)e={attribute:_.from??t.primaryKey,value:$};g=u(_.from??t.primaryKey,p.idFilter,!0,!0)}else g=u(_.from??t.primaryKey,p.idFilter,!1,!0);let x=g(R);return g.idFilter&&(T.idFilter=g.idFilter),x}let{subObject:P,subEntry:Y}=y(R,I);return P?Array.isArray(P)?(!n?.[d]&&n&&(n[d]={fromRecord(x){let $=y(x).subObject;return Array.isArray($)?$.filter(p).map(j=>j[m.primaryKey]):$}}),P.some(p)):p(P,Y):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),FL[a]||a){case ks.SEARCH_TYPES.EQUALS:case void 0:return u(c,d=>d===l,!0);case"contains":return u(c,d=>d?.toString().includes(l));case"ends_with":return u(c,d=>d?.toString().endsWith(l));case"starts_with":return u(c,d=>typeof d=="string"&&d.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,d=>{if(!Array.isArray(d))return!1;for(let f=0,m=l.length;f<m;f++)if(d[f]!==l[f])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,d=>(0,Ji.compareKeys)(d,l[0])>=0&&(0,Ji.compareKeys)(d,l[1])<=0,!0);case"gt":return u(c,d=>(0,Ji.compareKeys)(d,l)>0);case"ge":return u(c,d=>(0,Ji.compareKeys)(d,l)>=0);case"lt":return u(c,d=>(0,Ji.compareKeys)(d,l)<0);case"le":return u(c,d=>(0,Ji.compareKeys)(d,l)<=0);case"ne":return u(c,d=>(0,Ji.compareKeys)(d,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new Qr.ClientError(`Unknown query comparator "${a}"`)}function u(d,f,m,h){let p;m=m&&!s&&t?.indices[d]&&i>3,m&&(e.estimated_count==null&&CR(t)(e),p=e.estimated_count>>4,(isNaN(p)||p>=i)&&(m=!1));let _=0,g=3;function y(T){let R=T[d],I;if(typeof R!="object"||!R||h?I=f(R):Array.isArray(R)?I=R.some(f):R instanceof Date&&(I=f(R.getTime())),m&&(g++,!I&&!y.idFilter&&++_/g*i>p)){let P=sf(e,r.transaction.getReadTxn(),!1,t),Y;y.to?Y=P.flatMap(x=>t.primaryStore.get(x)[y.to]):Y=P.map(of);let te=new Set(Y);y.idFilter=x=>te.has(of(x)),y.idFilter.idSet=te}return I}return o(y,"recordFilter"),s&&(y.idFilter=f),y}o(u,"attributeComparator")}function CR(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/jo(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=FL[n]||n,n===ks.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=Xi(e.attributes,s[0]),a=i.definition?.tableClass||i.elements.definition?.tableClass,c=CR(a)({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*jo(e.indices[i.relationship.from])/(jo(a.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=jo(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else if(n==="starts_with"||n==="prefix")r.estimated_count=OSe*jo(e.primaryStore)+1;else if(n==="between")r.estimated_count=wSe*jo(e.primaryStore)+1;else if(n==="sort"){let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCountAsSort?r.estimated_count=i.customIndex.estimateCountAsSort(r):r.estimated_count=jo(e.primaryStore)+1}else{let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCount?r.estimated_count=i.customIndex.estimateCount(r.value):r.estimated_count=NSe*jo(e.primaryStore)+1}typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return o(t,"estimateConditionForTable"),t}function sg(e,t){if(e)if(Qo=e,tf.lastIndex=0,DSe.test(e))try{if(t&&(t.conditions=[]),Ti=t??new nf,Fp(Ti,""),Fr!==Qo.length&&Wt("Unable to parse query, unexpected end of query"),Ti.parseErrorMessage&&(Ti.parseError=new UL(t.parseErrorMessage),!t))throw Ti.parseError;return Ti}catch(r){if(r.statusCode=400,r.message=`Unable to parse query, ${r.message} at position ${Fr} in '${Qo}'`,Ti.parseErrorMessage&&(r.message+=", "+Ti.parseErrorMessage),t)t.parseError=r;else throw r}else return t??new URLSearchParams(e)}function Wt(e){let t=`${e} at position ${Fr}`;Ti.parseErrorMessage=Ti.parseErrorMessage?Ti.parseErrorMessage+", "+t:t}function Fp(e,t){let r=tf,n,s,i,a,c,l=decodeURIComponent,u;for(;n=r.exec(Qo);){Fr=r.lastIndex;let[,d,f]=n;a?(d&&Wt(`expected operator, but encountered '${d}'`),a=!1,c=!1):c=!0;let m;switch(f){case"=":s!=null?(d.length<=2?i=d:Wt(`invalid FIQL operator ${d}`),l=v2):(l=decodeURIComponent,i="equals",d||Wt("attribute must be specified before equality comparator"),s=rf(d));break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":i=CSe[f],l=xL[i]?v2:decodeURIComponent,d||Wt(`attribute must be specified before comparator ${f}`),s=rf(d);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null)s===void 0&&(t&&Wt(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`),Wt(`no comparison specified before ${f?"'"+f+"'":"end of string"}`));else{e.conditions||Wt("conditions/comparisons are not allowed in a property list");let p={comparator:i,attribute:s||null,value:l(d)};if(i==="eq"&&U2(p,d),s===""){let _=e.conditions[e.conditions.length-1];_.chainedConditions=_.chainedConditions||[],_.chainedConditions.push(p),_.operator=u}else OR(e,u),e.conditions.push(p)}f==="&"?(u="and",s=void 0):f==="|"?(u="or",s=void 0):f==="&="?(u="and",s=""):f==="|="&&(u="or",s="");break;case",":e.conditions?Wt("conditions/comparisons are not allowed in a property list"):e.push(rf(d)),s=void 0;break;case"(":tf.lastIndex=Fr;let h=Fp(d?[]:new nf,")");switch(d){case"":OR(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:Wt("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":Wt("group by is not implemented yet");case"sort":e.sort=x2(h);break;default:Wt(`unknown query function call ${d}`)}Qo[Fr]===","?r.lastIndex=++Fr:a=!0,s=null;break;case"{":e.conditions&&Wt("property sets are not allowed in a queries"),d||Wt("property sets must have a defined parent property name"),tf.lastIndex=Fr,m=Fp([],"}"),m.name=d,e.push(m),Qo[Fr]===","?r.lastIndex=++Fr:a=!0;break;case"[":if(tf.lastIndex=Fr,d?(m=Fp(new nf,"]"),m.name=d):m=Fp(e.conditions?new nf:[],"]"),e.conditions)if(OR(e,u),Qo[Fr]==="="){l=decodeURIComponent,i="equals",s=rf(d),r.lastIndex=++Fr;break}else e.conditions.push(m),s=null;else e.push(m);Qo[Fr]===","?r.lastIndex=++Fr:a=!0;break;case")":case"]":case"}":if(t===f[0]){if(e.conditions)if(s){let p={comparator:i||"equals",attribute:s,value:l(d)};i==="eq"&&U2(p,d),OR(e,u),e.conditions.push(p)}else d&&Wt("no attribute or comparison specified");else(d||e.length>0&&c)&&e.push(rf(d));return e}else Wt(t?`expected '${t}', but encountered '${f[0]}'`:`unexpected token '${f[0]}'`);default:Wt(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?MSe:tf,r.lastIndex=Fr),Fr===Qo.length)return e}t&&Wt(`expected '${t}', but encountered end of string`)}function OR(e,t){e.conditions.length>0&&(e.operator?e.operator!==t&&Wt("Can not mix operators within a condition grouping"):e.operator=t)}function rf(e){return e.indexOf(".")>-1?e.split(".").map(rf):decodeURIComponent(e)}function v2(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 Qr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function U2(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Qr.ClientError("wildcard can only be used at the end of a string")}function x2(e){let t=B2(e[0]);return e.length>1&&(t.next=x2(e.slice(1))),t}function B2(e){if(Array.isArray(e)){let t=B2(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}}Wt(`Unknown sort type ${e}`)}function of(e){return Array.isArray(e)?e.join("\0"):e}function jo(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function vSe(e,t,r){return t*r/jo(e)}var Qr,ks,Ji,oc,NSe,wSe,OSe,CSe,xL,FL,UL,DSe,tf,MSe,Fr,Ti,Qo,nf,ig=fe(()=>{Qr=w(Ee()),ks=w(kt()),Ji=require("ordered-binary"),oc=require("lmdb");op();kc();NSe=.3,wSe=.1,OSe=.05,CSe={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},xL={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};o(BL,"executeConditions");o(sf,"searchByIndex");o(Xi,"findAttribute");o(PSe,"joinTo");o(LSe,"joinFrom");FL={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"};o(Hp,"filterByType");o(CR,"estimateCondition");UL=class extends Qr.Violation{static{o(this,"SyntaxViolation")}},DSe=/[()[\]|!<>.]|(=\w*=)/,tf=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,MSe=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;o(sg,"parseQuery");o(Wt,"recordError");o(Fp,"parseBlock");o(OR,"assignOperator");o(rf,"decodeProperty");o(v2,"typedDecoding");o(U2,"wildcardDecoding");o(x2,"toSortObject");o(B2,"toSortEntry");nf=class{static{o(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}}getAll(){let t=[];for(let r=0,n=this.conditions.length;r<n;r++){let s=this.conditions[r];s.attribute&&t.push(s.value)}return t}};o(of,"flattenKey");o(jo,"estimatedEntryCount");o(vSe,"intersectionEstimate")});var SB={};Ce(SB,{MultiPartId:()=>PR,Resource:()=>vr,contextStorage:()=>cf,snakeCase:()=>xSe,transformForSelect:()=>LR});function xSe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function F2(e,t){if(Wl=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Wl=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new PR;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Wl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Wl=!0,null;e[e.length-1]==="/"&&(Wl=!0)}return t.coerceId(decodeURIComponent(e))}function Hn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,a){let c,l,u,d;if(r){if(a)d=i,a=a.getContext?.()||a;else if(i)typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(d=s,c=d[this.primaryKey]??null,a=i.getContext?.()||i):i?.transaction instanceof co?a=i:d=i;else if(s&&typeof s=="object")d=s,s=void 0,c=d.getId?.()??d[this.primaryKey];else throw new af.ClientError(`Invalid argument for data, must be an object, but got ${s}`);c===null&&(u=!0)}else i?a=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(a=s);if(c===void 0)if(typeof s=="object"&&s){if(l=s,c=s instanceof URLSearchParams?s.toString():s.url,s.conditions)c=s.id;else if(typeof c=="string")if(this.directURLMapping)c=c.slice(1),l.id=c;else{let _=c.indexOf("?");_>-1&&(l=this.parseQuery(c.slice(_+1),s),c=c.slice(0,_),c===""&&(u=!0));let g=this.parsePath(c,a,l);g?.id!==void 0?(g.query&&(l?l=Object.assign(g.query,l):l=g.query),u=g.isCollection,c=g.id):c=g,c&&(l.id=c)}else if(s[Symbol.iterator]){c=[],u=!0;for(let _ of s){if(typeof _=="object"&&_)break;c.push(_)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=new si,l.id=c,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new si,l.id=c,c==null&&(u=!0);l||(l=new si,l.id=c),u&&(l.isCollection=!0);let f;a||(a=cf.getStore()??{}),l.ensureLoaded!=null||l.async||u?(f={...t},l.ensureLoaded!=null&&(f.ensureLoaded=l.ensureLoaded),l.async&&(f.async=l.async),u&&(f.isCollection=!0)):f=t;let m=this.loadAsInstance,h=p;if((m===!1?!this.explicitContext:this.explicitContext===!1)&&(h=o(_=>cf.run(a,()=>p(_)),"runAction")),a?.transaction){let _=this.getResource(c,a,f);return _.then?_.then(h):h(_)}else return Mt(a,()=>{let _=this.getResource(c,a,f);return _.then?_.then(h):h(_)},f);function p(_){if(m!==!1&&a.authorize){a.authorize=!1;let g=t.type==="read"?_.allowRead(a.user,l,a):t.type==="update"?_.doesExist?.()===!1?_.allowCreate(a.user,d,a):_.allowUpdate(a.user,d,a):t.type==="create"?_.allowCreate(a.user,d,a):_.allowDelete(a.user,l,a);if(g?.then)return g.then(y=>{if(!y)throw new af.AccessViolation(a.user);return typeof d?.then=="function"?d.then(T=>e(_,l,a,T)):e(_,l,a,d)});if(!g)throw new af.AccessViolation(a.user)}return typeof d?.then=="function"?d.then(g=>e(_,l,a,g)):e(_,l,a,d)}o(p,"authorizeActionOnResource")}}function as(e,t){let r=new af.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 HL(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let a,c;return e.hasOwnProperty(i)&&typeof(a=e[i])!="function"?a: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 LR(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return o(function a(c){return c.then?c.then(a):Array.isArray(c)?c.map(a):HL(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],d=i(HL(l,r,n));for(let f of e)u.push(d(f));return u},"transform");let a=e.forceNulls;return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(m=>m&&typeof m=="object"?c(m):m);let u={},d=i(HL(l,r,n)),f;for(let m of e){let h=d(m);h===void 0&&a&&(h=null),h?.then?(f||(f=[]),f.push(h.then(p=>u[m.name||m]=p))):u[m.name||m]=h}return f?Promise.all(f).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(a){return c=>{if(typeof c=="string")return a(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let d=r[c.name]?.definition?.tableClass;l=s[c.name]=LR(c.select||c,d)}let u=a(c.name);return l(u)}else return a(c);else return c}}o(i,"handleProperty")}var H2,k2,af,G2,cf,USe,vr,Wl,PR,wa=fe(()=>{H2=require("crypto");Vf();mu();k2=w(Ws()),af=w(Ee());Dc();ig();G2=require("async_hooks");tg();cf=new G2.AsyncLocalStorage,USe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},vr=class{static{o(this,"Resource")}#e;#t;#r;static transactions;static directURLMapping=!1;static loadAsInstance;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=Hn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(a);return a(i);function a(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=LR(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=Hn(function(t,r,n,s){if(Array.isArray(s)&&t.#r&&t.constructor.loadAsInstance!==!1){let i=[];for(let a of s){let c=t.constructor,l=a[c.primaryKey],u=c.getResource(l,n,{async:!0});u.then?i.push(u.then(d=>d.put(a,n))):i.push(u.put(a,n))}return Promise.all(i)}return t.put?t.constructor.loadAsInstance===!1?t.put(r,s):t.put(s,r):as(t,"put")},{hasContent:!0,type:"update"});static patch=Hn(function(t,r,n,s){return t.patch?t.constructor.loadAsInstance===!1?t.patch(r,s):t.patch(s,r):as(t,"patch")},{hasContent:!0,type:"update"});static delete=Hn(function(t,r,n,s){return t.delete?t.delete(r):as(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,H2.randomUUID)()}static create(t,r,n){n?n.getContext&&(n=n.getContext()):n=cf.getStore()??{};let s;return this.loadAsInstance===!1?s=t: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),Mt(n,async()=>{let i=new this(s,n),a=await i.create?i.create(s,r):as(i,"create");return n.newLocation=s??a?.[this.primaryKey],n.createdResource=!0,this.loadAsInstance===!1?a:i})}static invalidate=Hn(function(t,r,n,s){return t.invalidate?t.invalidate(r):as(t,"delete")},{hasContent:!1,type:"update"});static post=Hn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.constructor.loadAsInstance===!1?t.post(r,s):t.post(s,r)},{hasContent:!0,type:"create"});static update=Hn(function(t,r,n,s){return t.update(r,s)},{hasContent:!0,type:"create"});static connect=Hn(function(t,r,n,s){return t.connect?t.constructor.loadAsInstance===!1?t.connect(r,s):t.connect(s,r):as(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Hn(function(t,r,n,s){return t.subscribe?t.subscribe(r):as(t,"subscribe")},{type:"read"});static publish=Hn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.constructor.loadAsInstance===!1?t.publish(r,s):t.publish(s,r):as(t,"publish")},{hasContent:!0,type:"create"});static search=Hn(function(t,r,n){let s=t.search?t.search(r):as(t,"search"),i=n.select;if(i&&n.hasOwnProperty("select")&&s!=null&&!s.selectApplied){let a=LR(i,t.constructor);return s.map(a)}return s},{type:"read"});static query=Hn(function(t,r,n,s){return t.search?t.constructor.loadAsInstance===!1?t.search(r,s):t.search(s,r):as(t,"search")},{hasContent:!0,type:"read"});static copy=Hn(function(t,r,n,s){return t.copy?t.constructor.loadAsInstance===!1?t.copy(r,s):t.copy(s,r):as(t,"copy")},{hasContent:!0,type:"create"});static move=Hn(function(t,r,n,s){return t.move?t.constructor.loadAsInstance===!1?t.move(r,s):t.move(s,r):as(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#r)return(await this.constructor.create(this.#e,t,this.#t)).#e;as(this,"post")}static isCollection(t){return t&&t.#r}get isCollection(){return this.#r}static coerceId(t){return t}static parseQuery(t,r){return sg(t,r)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let a=t.slice(s+1),c=r?.headers&&USe[a];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===a))if(t=t.slice(0,s),n)n.property=a;else return{query:{property:a},id:F2(t,this),isCollection:Wl}}let i=F2(t,this);return Wl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),a;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?a=r.isCollection:a=n?.isCollection;let c=a&&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(d=>d.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 d of l){let f=d.#e,m=u.get(f);m?m.push(d):u.set(f,[d])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return a&&(s.#r=!0),s}subscribe(t){return new Gn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Gn}allowRead(t,r){return t?.role.permission.super_user}allowUpdate(t,r,n){return t?.role.permission.super_user}allowCreate(t,r,n){return t?.role.permission.super_user}allowDelete(t,r){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,k2._assignPackageExport)("Resource",vr);o(xSe,"snakeCase");o(F2,"pathToId");PR=class extends Array{static{o(this,"MultiPartId")}toString(){return this.join("/")}};o(Hn,"transactional");o(as,"missingMethod");o(HL,"selectFromObject");o(LR,"transformForSelect")});var EY={};Ce(EY,{EVICTED:()=>ac,INVALIDATED:()=>Fn,coerceType:()=>MR,makeTable:()=>UR,setServerUtilities:()=>YC});function UR(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:a,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:h}=e,{expirationMS:p,evictionMS:_,audit:g,trackDeletes:y}=e;_??=0;let{attributes:T}=e;T||(T=[]);let R=vL(i,n,l),I,P,Y={},te=Promise.resolve(),x,$,j;for(let q of T)(q.assignCreatedTime||q.name==="__createdtime__")&&(x=q),(q.assignUpdatedTime||q.name==="__updatedtime__")&&($=q),q.expiresAt&&(j=q),q.isPrimaryKey&&(Y=q);let V,le=[],re=[],se=1,_e=2,Ne={},Fe={},He=864e5,_r=0,pt,gr,wr,ou=!1,au,Ft,If,Nf=jl.get(U.REPLICATION_DATABASES);if(Array.isArray(Nf)){for(let q of Nf)if(q.name===c&&q.replicateTo>=0){If=q.replicateTo;break}}let hE=i.getRange({start:!1,end:!1}).constructor,Ty=10,pE=6;g&&Nc(),Cp(i.env.path,q=>{if(P)return da(q)});class cu extends nl{static{o(this,"Updatable")}getUpdatedTime(){return ic.get(this.getRecord())?.version}getExpiresAt(){return ic.get(this.getRecord())?.expiresAt}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.set(E,new Um(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(E,S){return this.addTo(E,-S)}}class Me extends vr{#e;#t;#r;#n;#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=a;static databaseName=c;static attributes=T;static replicate=h;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=x;static updatedTimeProperty=$;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return p}static dbisDB=d;static schemaDefined=u;static sourcedFrom(E,S){if(S&&(this.sourceOptions=S,(S.expiration||S.eviction||S.scanInterval)&&this.setTTLExpiration(S)),S?.intermediateSource)E.intermediateSource=!0,this.sources.unshift(E);else{if(this.sources.some(O=>!O.intermediateSource)){if(this.sources.some(O=>O.name===E.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(E)}P=P||E.get&&(!E.get.reliesOnPrototype||E.prototype.get),I=I||E.load;let A=o(O=>{let D=this.sources;if(D=D.filter(F=>F.intermediateSource&&F[O]&&(!F[O].reliesOnPrototype||F.prototype[O])),D.length>0)if(D.length===1){let F=D[0];return(L,H,W)=>{if(L?.source!==F)return F[O](H,W,L)}}else return(F,L,H)=>{let W=[];for(let ee of D){if(F?.source===ee)break;W.push(ee[O](L,H,F))}return Promise.all(W)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1];N.intermediateSource&&(N={});let b=o(O=>{if(N[O]&&(!N[O].reliesOnPrototype||N.prototype[O]))return(D,F,L)=>{if(!D?.source)return N[O](F,L,D)}},"getApplyToCanonicalSource");Ne={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Fe={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=N.shouldRevalidateEvents;return(async()=>{let O=!1,D,F=o(async(L,H)=>{let W=L.value,ee=L.table?Ge[c][L.table]:Me;if(c===Mf&&(L.table===uu.ROLE_TABLE_NAME||L.table===uu.USER_TABLE_NAME)&&(O=!0),L.id===void 0&&(L.id=W[ee.primaryKey],L.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(L));L.source=E;let oe={residencyId:fa(L.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:L.nodeId},B=L.id,ue=await ee.getResource(B,H,oe);switch(L.finished&&await L.finished,L.type){case"put":return C?ue._writeInvalidate(B,W,oe):ue._writeUpdate(B,W,!0,oe);case"patch":return C?ue._writeInvalidate(B,W,oe):ue._writeUpdate(B,W,!1,oe);case"delete":return ue._writeDelete(B,oe);case"publish":case"message":return ue._writePublish(B,W,oe);case"invalidate":return ue._writeInvalidate(B,W,oe);case"relocate":return ue._writeRelocate(B,oe);default:xe.default.error?.("Unknown operation",L.type,L.id)}},"writeUpdate");try{let L=E.subscribe;L&&y==null&&(y=!0);let H={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},W=E.subscribeOnThisThread?E.subscribeOnThisThread((0,zl.getWorkerIndex)(),H):(0,zl.getWorkerIndex)()===0,ee=L&&W&&await E.subscribe?.(H);if(ee){let oe;for await(let B of ee)try{if(!(B.type==="transaction"?B.writes[0]:B)){xe.default.error?.("Bad subscription event",B);continue}if(B.source=E,B.type==="end_txn"){if(oe?.resolve(),B.localTime&&D!==B.localTime){if(B.remoteNodeIds?.length>0){let ge=[Symbol.for("seq"),B.remoteNodeIds[0]],X=d.get(ge),de=X?.nodes;de||(de=[]);for(let he of B.remoteNodeIds.slice(1)){let Ae=de.find(Oe=>Oe.id===he);de=de.filter(Oe=>Oe.id!==he||Oe===Ae),Ae||(Ae={id:he,seqId:0},de.push(Ae)),Ae.seqId=Math.max(X?.seqId??1,B.localTime),he===oe?.nodeId&&(Ae.lastTxnTime=B.timestamp)}let ne=Math.max(X?.seqId??1,B.localTime);xe.default.trace?.("Received txn",c,new Date(ne),new Date(B.localTime),B.remoteNodeIds),d.put(ge,{seqId:ne,nodes:de})}D=B.localTime}B.onCommit&&oe?.committed.then(B.onCommit);continue}if(oe)if(B.beginTxn)oe.resolve();else{oe.write_promises.push(F(B,oe));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let ae=Mt(B,()=>{if(B.type==="transaction"){let ge=[];for(let X of B.writes)try{ge.push(F(X,B))}catch(de){throw de.message+=" writing "+JSON.stringify(X)+" of event "+JSON.stringify(B),de}return Promise.all(ge)}else if(B.type==="define_schema"){let ge=this.attributes.slice(0),X=!1;for(let de of B.attributes)ge.find(ne=>ne.name===de.name)||(ge.push(de),X=!0);X&&(Ze({table:s,database:c,attributes:ge,origin:"cluster"}),Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,G.CREATE_TABLE,c,s)))}else return B.beginTxn?(oe=B,oe.write_promises=[F(B,B)],new Promise(ge=>{oe.resolve=()=>ge(Promise.all(oe.write_promises))})):F(B,B)});oe&&(oe.committed=ae),O&&ae&&!ae?.waitingForUserChange&&(ae.then(()=>Gp.signalUserChange(new qp.UserEventMsg(process.pid))),ae.waitingForUserChange=!0),B.onCommit&&(ae?ae.then(B.onCommit):B.onCommit())}catch(ue){xe.default.error?.("error in subscription handler",ue)}}}catch(L){xe.default.error?.(L)}})(),this}static get isCaching(){return P}static get shouldRevalidateEvents(){return this.prototype.get!==Me.prototype.get}static getResource(E,S,A){let N=super.getResource(E,S,A);if(E!=null&&this.loadAsInstance!==!1){Or(E);try{if(N.getRecord?.())return N;if(typeof E=="object"&&E&&!Array.isArray(E))throw new Error(`Invalid id ${JSON.stringify(E)}`);let b=!A?.async||i.cache?.get?.(E),C=Cr(S),O=C.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Tc(E,S,{transaction:O,ensureLoaded:A?.ensureLoaded},b,D=>{if(D?Me._updateResource(N,D):N.#e=null,S.onlyIfCached){if(!N.doesExist())throw new lt.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let F=yc(E,D,S,N);if(F)return C?.disregardReadTxn(),N.#i=!0,S.loadedFromSource=!0,Ri(F,L=>(Me._updateResource(N,L),N))}return N})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(E)),b}}return N}static _updateResource(E,S){E.#n=S,E.#e=S?.value??null,E.#r=S?.version}ensureLoaded(){let E=yc(this.getId(),this.#n,this.getContext());if(E)return this.#i=!0,this.getContext().loadedFromSource=!0,Ri(E,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let E=Y?.type;if(E==="String"||E==="ID")return super.getNewId();if(!Ft){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,O;if(C&&C.nodeName===server.hostname&&(!WSe(i)||C.pid===process.pid)){let D=C.start,F=C.end;O=D;for(let L of i.getKeys({start:F,end:D,limit:1,reverse:!0}))O=L}else C=N(b?.version??null),O=C.start;Ft=new BigInt64Array([BigInt(O)+1n]),Ft=new BigInt64Array(i.getUserSharedBuffer("id",Ft.buffer)),Ft.maxSafeId=C.end}let S=Number(Atomics.add(Ft,0,1n)),A=E==="Int"?512:1048576;if(S+A>=Ft.maxSafeId){let b=o(C=>{Ft.maxSafeId=S+(E==="Int"?1023:4194303);let O=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=C?void 0:i.useReadTransaction(),F=Number(Ft[0]);for(let W of i.getKeys({start:F+1,end:O,limit:1,transaction:D}))O=W;D?.done();let{value:L,version:H}=i.getEntry(Symbol.for("id_allocation"));if(Ft.maxSafeId<O){if(L.end>Ft.maxSafeId-100)return;xe.default.info?.("New id allocation",S,Ft.maxSafeId,H),i.put(Symbol.for("id_allocation"),{start:L.start,end:Ft.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),H)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ft.maxSafeId}, but id of ${O} detected`);let W=N(H);W.alreadyUpdated||Atomics.store(Ft,0,BigInt(W.start+1)),Ft.maxSafeId=W.end}},"updateEnd");S+A===Ft.maxSafeId?setImmediate(b):S+100>=Ft.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${E=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return S;function N(b){let C=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,O=C/4,D,F,L=!1,H,W;do{H=Math.floor(Math.random()*C),W={start:H,end:H+(E==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},D=0;for(let ee of i.getKeys({start:H,limit:1,reverse:!0}))D=ee;F=C;for(let ee of i.getKeys({start:H+1,end:C,limit:1}))F=ee;O*=.875,O<1e3&&!L&&(L=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${E==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,H,D,F,O))}while(!(O<F-H&&(O<H-D||D===0)));return i.transactionSync(()=>{let ee=i.getEntry(Symbol.for("id_allocation"));return(ee?.version??null)==b?(xe.default.info?.("Allocated new id range",W),i.put(Symbol.for("id_allocation"),W,Date.now()),W):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ee.value})})}}static setTTLExpiration(E){if(typeof E=="number")p=E*1e3,_||(_=0);else if(E&&typeof E=="object")p=E.expiration*1e3,_=(E.eviction||0)*1e3,He=E.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");He=He||(p+_)/4,da()}static getResidencyRecord(E){return d.get([Symbol.for("residency_by_id"),E])}static setResidency(E){Me.getResidency=E&&((S,A)=>{try{return E(S,A)}catch(N){throw N.message+=` in residency function for table ${s}`,N}})}static setResidencyById(E){Me.getResidencyById=E&&(S=>{try{return E(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(E,S){if(Me.getResidencyById)return Me.getResidencyById(E[t]);let A=If;if(S.replicateTo!=null){if(Array.isArray(S.replicateTo))return S.replicateTo.includes(server.hostname)?S.replicateTo:[server.hostname,...S.replicateTo];S.replicateTo>=0&&(A=S.replicateTo)}if(A>=0&&server.nodes){let N=[server.hostname];if(S.previousResidency)N.push(...S.previousResidency.slice(0,A));else{let b=server.nodes.map(D=>D.name),C=Math.floor(b.length*Math.random());N.push(...b.slice(C,C+A));let O=C+A-b.length;O>0&&N.push(...b.slice(0,O))}return N}}static enableAuditing(E=!0){g=E,E&&Nc(),Me.audit=E}static coerceId(E){return E===""?null:MR(E,Y)}static async dropTable(){delete Ge[c][s];for(let E of i.getRange({versions:!0,snapshot:!1,lazy:!0}))E.metadataFlags&Dn&&E.value&&Ea(E.value);if(c===a){for(let E of T)d.remove(Me.tableName+"/"+E.name),r[E.name]?.drop();d.remove(Me.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),GL.default.unlinkSync(i.env.path);Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,G.DROP_TABLE,c,s))}get(E){let S=this.constructor;if(typeof E=="string"&&S.loadAsInstance!==!1)return this.getProperty(E);if(Of(E))return this.search(E);if(E&&E.id===void 0&&!E.toString()){let A={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:T,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?Me.getRecordCount().then(N=>(A.recordCount=N.recordCount,A.estimatedRecordRange=N.estimatedRange,A)):A}if(E!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),N=Cr(A),b=N.getReadTxn();if(b?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let C=Sr(E);Or(C);let O=!0;return E.checkPermission&&(O=this.allowRead(A.user,E)),Ri(O,D=>{if(!D)throw new lt.AccessViolation(A.user);let F=!0;return Tc(C,A,{transaction:b,ensureLoaded:F},!1,L=>{if(A.onlyIfCached){if(!L?.value)throw new lt.ServerError("Entry is not cached",504)}else if(F){let H=yc(C,L,A);if(H)return N?.disregardReadTxn(),A.loadedFromSource=!0,H.then(W=>W?.value)}return L?.value})})}if(E?.property)return this.getProperty(E.property);if(this.doesExist()||E?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(E,S){let A=Rc(E,S);if(A?.read){if(A.isSuperUser)return!0;let N=A.attribute_permissions,b=S?.select;if(N?.length>0||ou&&b){if(S||(S={}),b){let C=N?.length>0&&kL(N,"read");S.select=b.map(O=>{let D=O.name||O;if(!C||C[D]){let F=wr[D]?.definition?.tableClass;if(F){if(O.name||(O={name:O}),!O.checkPermission&&S.checkPermission&&(O.checkPermission=S.checkPermission),!F.prototype.allowRead.call(null,E,O))return!1;if(!O.select)return O.name}return O}}).filter(Boolean)}else S.select=N.filter(C=>C.read&&!wr[C.attribute_name]).map(C=>C.attribute_name);return S}else return!0}}allowUpdate(E,S,A){let N=Rc(E,A);if(N?.update){let b=N.attribute_permissions;if(b?.length>0){let C=kL(b,"update");for(let O in S)if(!C[O])return!1;for(let O of b){let D=O.attribute_name;!O.update&&!(D in S)&&(S[D]=this.getProperty(D))}}return Ic(this.getContext())}}allowCreate(E,S,A){if(this.isCollection){let N=Rc(E,A);if(N?.insert){let b=N.attribute_permissions;if(b?.length>0){let C=kL(b,"insert");for(let O in S)if(!C[O])return!1;return Ic(this.getContext())}else return Ic(this.getContext())}}else return this.allowUpdate(E,{})}allowDelete(E,S){return Rc(E,S)?.delete&&Ic(this.getContext())}update(E,S){let A,N=typeof S=="boolean"||S===void 0&&(E==null||typeof E=="object"&&!(E instanceof URLSearchParams)),b=!1;N?(b=S,S=E,A=this.getId()):A=Sr(E);let C=this.getContext();if(!Cr(C))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(b)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(N){let D=this.#t;D&&(S=Object.assign(D,S)),this.#t=S}else{let D=!0;if(E==null)throw new TypeError("Can not put a record without a target");return E.checkPermission&&(D=this.allowUpdate(C.user,S,E)),Ri(D,F=>{if(!F)throw new lt.AccessViolation(C.user);return Ri(i.get(Sr(E)),L=>{let H=new cu(L);return H._setChanges(S),this._writeUpdate(A,H.getChanges(),!1),H})})}return this._writeUpdate(A,this.#t,b),this}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.#s===$2?this.set(E,(+this.getProperty(E)||0)+S):(this.#s||this.update(),this.set(E,new Um(S)));else throw new Error("Can not add a non-numeric value")}subtractFrom(E,S){if(typeof S=="number")return this.addTo(E,-S);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(E){this.#t=E}setRecord(E){this.#e=E}invalidate(E){let S=!0,A=this.getContext();return E?.checkPermission&&(S=this.allowDelete(A.user,E,A)),Ri(S,N=>{if(!N)throw new lt.AccessViolation(A.user);this._writeInvalidate(E?Sr(E):this.getId())})}_writeInvalidate(E,S,A){let N=this.getContext();Or(E),Cr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Ne.invalidate?.bind(this,N,E),beforeIntermediate:Fe.invalidate?.bind(this,N,E),commit:o((C,O)=>{if(!(bc(C,O,A?.nodeId)<=0)){S??=null;for(let D in r)S||(S={}),S[D]===void 0&&(S[D]=this.getProperty(D));xe.default.trace?.(`Invalidating entry in ${s} id: ${E}, timestamp: ${new Date(C).toISOString()}`),R(E,S,O,C,Fn,g,{user:N?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(E,S){let A=this.getContext();Or(E),Cr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Ne.relocate?.bind(this,A,E),beforeIntermediate:Fe.relocate?.bind(this,A,E),commit:o((b,C)=>{if(bc(b,C,S?.nodeId)<=0)return;let O=Me.getResidencyRecord(S.residencyId),D=0,F=null,L=C?.value;if(O&&!O.includes(server.hostname)){for(let H in r)F||(F={}),F[H]=L(H);D=Fn}else F=L;xe.default.trace?.(`Relocating entry id: ${E}, timestamp: ${new Date(b).toISOString()}`),R(E,F,C,b,D,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(E,S){let A={previousResidency:this.getResidencyRecord(E.residencyId),isRelocation:!0},N=wc(this.getResidency(S.value,A)),b;if(N){if(!N.includes(server.hostname))return!1;b=fa(N)}let O=R(E.key,S.value,E,E.version,0,!0,{residencyId:b,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(E,S,A){let N=this.Source,b;if(!((P||g)&&(!S||(b=i.getEntry(E),!b||!S)||b.version!==A))){if(P){if(i.hasLock(E,b.version))return;let C;for(let O in r)C||(C={}),C[O]=S[O];if(C)return R(E,C,b,A,ac,null,null,null,!0)}if(i.ifVersion(E,A,()=>{oo(E,S,null)}),g)return R(E,null,b,A,ac,null,null,null,!0);Yl(i,b??i.getEntry(E),A)}}lock(){throw new Error("Not yet implemented")}static operation(E,S){return E.table||=s,E.schema||=c,J2.operation(E,S)}put(E,S){if(S===void 0||S instanceof URLSearchParams)this.update(E,!0);else{let A=!0;if(E==null)throw new TypeError("Can not put a record without a target");let N=this.getContext();return E.checkPermission&&(A=this.allowUpdate(N.user,S,E)),Ri(A,b=>{if(!b)throw new lt.AccessViolation(N.user);if(Array.isArray(S))for(let C of S){let O=C[t];this._writeUpdate(O,C,!0)}else{let C=Sr(E);this._writeUpdate(C,S,!0)}})}}create(E,S){let A=!0,N=this.getContext();if(!S&&!(E instanceof URLSearchParams)&&(S=E,E=void 0),!S||typeof S!="object"||Array.isArray(S))throw new TypeError("Can not create a record without an object");return E?.checkPermission&&(A=this.allowCreate(N.user,S,E)),Ri(A,b=>{if(!b)throw new lt.AccessViolation(N.user);let C=Sr(E)??S[t];if(C===void 0)C=this.constructor.getNewId();else if(i.get(C))throw new lt.ClientError("Record already exists",409);return this._writeUpdate(C,S,!0),S})}patch(E,S){if(S===void 0||S instanceof URLSearchParams)this.update(E,!1);else{let A=this.update(E,S);if(A?.then)return A.then(()=>{})}}_writeUpdate(E,S,A,N){let b=this.getContext(),C=Cr(b);Or(E);let O=this.#n??i.getEntry(E);this.#s=A?$2:$Se;let D={key:E,store:i,entry:O,nodeName:b?.nodeName,validate:o(F=>{S||(S=this.#t),A||S&&x_(this.#t===S?this:S)?b?.source||(C.checkOverloaded(),this.validate(S,!A),$&&(S[$.name]=$.type==="Date"?new Date(F):$.type==="String"?new Date(F).toISOString():F),A&&(t&&S[t]!==E&&(S[t]=E),x&&(O?.value?S[x.name]=O?.value[x.name]:S[x.name]=x.type==="Date"?new Date(F):x.type==="String"?new Date(F).toISOString():F),S=Oa(S))):C.removeWrite(D)},"validate"),before:A?Ne.put?()=>Ne.put(b,E,S):null:Ne.patch?()=>Ne.patch(b,E,S):Ne.put?()=>Ne.put(b,E,Oa(this)):null,beforeIntermediate:A?Fe.put?()=>Fe.put(b,E,S):null:Fe.patch?()=>Fe.patch(b,E,S):Fe.put?()=>Fe.put(b,E,Oa(this)):null,commit:o((F,L,H)=>{if(H){if(b&&L?.version>(b.lastModified||0)&&(b.lastModified=L.version),this.#n=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=L?.value??null)}this.#t=void 0,this.#r=F;let W=L?.value,ee=S;this.#s=0;let oe=!1,B=bc(F,L,N?.nodeId),ue;if(B<=0){if(g){let ne=L.localTime,he=L.version;xe.default.trace?.("Applying CRDT update to record with id: ",E,"txn time",new Date(F),"applying later update from:",new Date(he),"local recorded time",new Date(ne));let Ae=[];for(;ne>F||he>=F&&ne>0;){let Oe=l.get(ne);if(!Oe)break;let ze=Ut(Oe);if(he=ze.version,he>=F){if(he===F){if(B=bc(F,{version:he,localTime:ne},N?.nodeId),B===0)return;if(B>0)continue}if(ze.type==="patch")Ae.push(ze),ue=S;else if(ze.type==="put"||ze.type==="delete")return}ne=ze.previousLocalTime}if(!ne){xe.default.debug?.("No further audit history, must drop update",E,"existing version preserved",L);return}Ae.sort((Oe,ze)=>Oe.version-ze.version);for(let Oe of Ae){let ze=Oe.getValue(i);if(xe.default.debug?.("Rebuilding update with future patch:",new Date(Oe.version),ze,Oe),ee=v_(ee,ze,A),!ee)return}}else{if(A)return;ee=v_(ee,W,A),xe.default.debug?.("Rebuilding update without audit:",ee)}xe.default.trace?.("Rebuilt record to save:",ee," is full update:",A)}let ae;if(A?ae=ee:this.constructor.loadAsInstance===!1?ae=Oa(W,ee):(this.#e=W,ae=Oa(this,ee)),this.#e=ae,ae&&ae.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ge;if(N?.residencyId!=null)ge=N.residencyId;else{O?.residencyId&&(b.previousResidency=Me.getResidencyRecord(O.residencyId));let ne=wc(Me.getResidency(ae,b));if(ne&&!ne.includes(server.hostname))if(ue??=ae,oe=!0,Me.getResidencyById)ae=void 0;else{ae=null;for(let he in r)ae||(ae={}),ae[he]=ue[he]}ge=fa(ne)}A||(ue=S);let X=b?.expiresAt??(p?p+Date.now():-1);xe.default.trace?.(`Saving record with id: ${E}, timestamp: ${new Date(F).toISOString()}${X?", expires at: "+new Date(X).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(ae).slice(0,100)}catch{return""}})()),oo(E,W,ae);let de=A?"put":"patch";R(E,ae,L,F,oe?Fn:0,g,{omitLocalRecord:oe,user:b?.user,residencyId:ge,expiresAt:X,nodeId:N?.nodeId,originatingOperation:b?.originatingOperation},de,!1,ue),b.expiresAt&&da()},"commit")};C.addWrite(D)}async delete(E){if(Of(E)){E.select=["$id"];for await(let S of this.search(E))this._writeDelete(S.$id);return!0}if(E){let S=!0,A=this.getContext();return E.checkPermission&&(S=this.allowDelete(A.user,E,A)),Ri(S,N=>{if(!N)throw new lt.AccessViolation(A.user);let b=Sr(E);return this._writeDelete(b),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(E,S){let A=Cr(this.getContext());Or(E);let N=this.getContext();return A.addWrite({key:E,store:i,entry:this.#n,nodeName:N?.nodeName,before:Ne.delete?.bind(this,N,E),beforeIntermediate:Fe.delete?.bind(this,N,E),commit:o((b,C,O)=>{let D=C?.value;O&&(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),Me._updateResource(this,C)),!(bc(b,C,S?.nodeId)<=0)&&(oo(this.getId(),D),xe.default.trace?.(`Deleting record with id: ${E}, txn timestamp: ${new Date(b).toISOString()}`),g||y?(R(E,null,C,b,0,g,{user:N?.user,nodeId:S?.nodeId},"delete"),g||da()):Yl(i,C))},"commit")}),!0}search(E){let S=this.getContext(),A=Cr(S);if(!E)throw new Error("No query provided");if(E.parseError)throw E.parseError;if(E.checkPermission&&!this.allowRead(S.user,E))throw new lt.AccessViolation(S.user);let N=E.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(E)?E:E[Symbol.iterator]?Array.from(E):[];let b=E.id??this.getId();b&&(N=[{attribute:null,comparator:Array.isArray(b)?"prefix":"starts_with",value:b}].concat(N));let C,O={};function D(ne,he){let Ae;switch(he){case"and":case void 0:if(ne.length<1)throw new Error('An "and" operator requires at least one condition');Ae=!0;break;case"or":if(ne.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+he)}for(let Oe of ne){if(Oe.conditions){Oe.conditions=D(Oe.conditions,Oe.operator);continue}let ze=Oe[0]??Oe.attribute,kr=ze==null?Y:Xi(T,ze);if(kr)(kr.type||xL[Oe.comparator])&&(Oe[1]===void 0?Oe.value=L(Oe.value,kr):Oe[1]=L(Oe[1],kr));else if(ze!=null)throw(0,lt.handleHDBError)(new Error,`${ze} is not a defined attribute`,404);if(Oe.chainedConditions)if(Oe.chainedConditions.length===1&&(!Oe.operator||Oe.operator=="and")){let ye=Oe.chainedConditions[0],We,Xe;if(ye.comparator==="gt"||ye.comparator==="greater_than"||ye.comparator==="ge"||ye.comparator==="greater_than_equal"?(We=Oe,Xe=ye):(We=ye,Xe=Oe),We.comparator!=="lt"&&We.comparator!=="less_than"&&We.comparator!=="le"&&We.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let jt=Xe.comparator==="ge"||Xe.comparator==="greater_than_equal",Dt=We.comparator==="le"||We.comparator==="less_than_equal";Oe.comparator=(jt?"ge":"gt")+(Dt?"le":"lt"),Oe.value=[Xe.value,We.value]}else throw new Error("Multiple chained conditions are not currently supported")}return ne}o(D,"prepareConditions");function F(ne,he){if(E.enforceExecutionOrder)return ne;for(let Ae of ne)Ae.conditions&&(Ae.conditions=F(Ae.conditions,Ae.operator));return ne.length>1&&he!=="or"?BSe(ne,CR(Me)):ne}o(F,"orderConditions");function L(ne,he){return Array.isArray(ne)?ne.map(Ae=>MR(Ae,he)):MR(ne,he)}o(L,"coerceTypedValues");let H=E.operator;(N.length>0||H)&&(N=D(N,H));let W=typeof E.sort=="object"&&E.sort,ee;if(W&&H!=="or"){let ne=W.attribute;if(ne==null)throw new lt.ClientError("Sort requires an attribute");if(C=N.find(he=>of(he.attribute)===of(ne)),!C){let he=Xi(T,ne);if(!he)throw(0,lt.handleHDBError)(new Error,`${Array.isArray(ne)?ne.join("."):ne} is not a defined attribute`,404);if(he.indexed)C={...W,comparator:"sort"},N.push(C);else if(N.length===0&&!E.allowFullScan)throw(0,lt.handleHDBError)(new Error,`${Array.isArray(ne)?ne.join("."):ne} is not indexed and not combined with any other conditions`,404)}C&&(C.descending=!!W.descending)}N=F(N,H),W&&(C&&N[0]===C?W.next&&(ee={dbOrderedAttribute:W.attribute,attribute:W.next.attribute,descending:W.next.descending,next:W.next.next}):(C&&N.splice(N.indexOf(C),1),ee=W));let oe=E.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),E.explain)return{conditions:N,operator:H,postOrdering:ee,selectApplied:!!oe};let B=A.useReadTxn(),ue=BL(N,H,Me,B,E,S,(ne,he)=>Cf(ne,oe,S,B,he),O),ae=E.ensureLoaded!==!1;ee||(ue=de(ue));let ge=Me.transformEntryForSelect(oe,S,B,O,ae,!0),X=Me.transformToOrderedSelect(ue,oe,ee,S,B,ge);function de(ne){return E.offset||E.limit!==void 0?ne.slice(E.offset,E.limit!==void 0?(E.offset||0)+E.limit:void 0):ne}return o(de,"applyOffset"),ee&&(X=de(X)),X.onDone=()=>{X.onDone=null,A.doneReadTxn()},X.selectApplied=!0,X.getColumns=()=>{if(oe){let ne=[];for(let he of oe)he==="*"?ne.push(...T.map(Ae=>Ae.name)):ne.push(he.name||he);return ne}return T.filter(ne=>!ne.computed&&!ne.relationship).map(ne=>ne.name)},X}static transformToOrderedSelect(E,S,A,N,b,C){let O=new hE;if(A){E=Cf(E,S,N,b,null);let D;O.iterate=function(){let L,H=E[Symbol.asyncIterator]?E[Symbol.asyncIterator]():E[Symbol.iterator](),W,ee=A.dbOrderedAttribute,oe,B,ue=!0;function ae(X){let de=X.next&&ae(X.next),ne=X.descending;return N.sort=X,(he,Ae)=>{let Oe=Ac(he,X.attribute,N),ze=Ac(Ae,X.attribute,N),kr=ne?(0,Ql.compareKeys)(ze,Oe):(0,Ql.compareKeys)(Oe,ze);return kr===0?de?.(he,Ae)||0:kr}}o(ae,"createComparator");let ge=ae(A);return{async next(){let X;if(L)if(X=L.next(),X.done){if(W)return O.onDone&&O.onDone(),X}else return{value:await C.call(this,X.value)};D=[],oe&&D.push(oe);do if(X=await H.next(),X.done){if(W=!0,D.length)break;return O.onDone&&O.onDone(),X}else{let de=X.value;if(de?.then&&(de=await de),ee){let ne=Ac(de,ee,N);if(ue)ue=!1,B=ne;else if(ne!==B){B=ne,oe=de;break}}D.push(de)}while(!0);return A.isGrouped,D.sort(ge),L=D[Symbol.iterator](),X=L.next(),X.done?(O.onDone&&O.onDone(),X):{value:await C.call(this,X.value)}},return(){O.onDone&&O.onDone(),H.return()},throw(){O.onDone&&O.onDone(),H.throw()}}};let F=o(L=>{if(typeof S=="object"&&Array.isArray(L.attribute))for(let H=0;H<S.length;H++){let W=S[H],ee;if(W.name===L.attribute[0]){for(ee=W.sort||(W.sort={});ee.next;)ee=ee.next;ee.attribute=L.attribute.slice(1),ee.descending=L.descending}else W===L.attribute[0]&&(S[H]=ee={name:W,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&F(L.next)},"applySortingOnSelect");F(A)}else O.iterate=(E[Symbol.asyncIterator]||E[Symbol.iterator]).bind(E),O=O.map(function(D){try{let F=C.call(this,D);return typeof F?.catch=="function"?F.catch(L=>{throw L.partialObject={[t]:D.key},L}):F}catch(F){throw F.partialObject={[t]:D.key},F}});return O}static transformEntryForSelect(E,S,A,N,b,C){let O;b&&P&&!(typeof E=="string"?[E]:E)?.every(L=>{let H;return typeof L=="object"?H=L.name:H=L,r[H]||H===t})&&(O=!0);let D,F=o(function(L){let H;if(S?.transaction?.stale&&(S.transaction.stale=!1),L!=null){if(H=L.deref?L.deref():L.value,!H&&(L.key===void 0||L.deref)||L.metadataFlags&Fn){if(L.metadataFlags&Fn&&S.replicateFrom===!1&&C&&L.residencyId)return lc.SKIP;if(L=Tc(L.key??L,S,{transaction:A,lazy:E?.length<4,ensureLoaded:b},this?.isSync,W=>W),L?.then)return L.then(F.bind(this));H=L?.value}if(O&&L?.metadataFlags&(Fn|ac)||L?.expiresAt!=null&&L?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:L.key,message:"This entry has expired"};let W=yc(L.key??L,L,S);if(W?.then)return W.then(F)}}if(H==null)return C?lc.SKIP:H;if(E&&!(E[0]==="*"&&E.length===1)){let W,ee=o((B,ue)=>{let ae;typeof B=="object"?ae=B.name:ae=B;let ge=wr?.[ae],X;if(ge){let de=N?.[ae];if(de)if(de.hasMappings){let he=ge.from?H[ge.from]:of(L.key);X=de.get(he),X||(X=[])}else X=de.fromRecord?.(H);else X=ge(H,S,L,!0);let ne=o(he=>{if(ge.directReturn)return ue(he,ae);if(he&&typeof he=="object"){let Ae=ge.definition?.tableClass||Me;D||(D={});let Oe=D[ae]||(D[ae]=Ae.transformEntryForSelect(ae===B?null:B.select||(Array.isArray(B)?B:null),S,A,de,b));if(Array.isArray(he)){let ze=[],kr=Ae.transformToOrderedSelect(he,B.select,typeof B.sort=="object"&&B.sort,S,A,Oe)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),ye=o(Xe=>{for(;!Xe.done;){if(Xe?.then)return Xe.then(ye);ze.push(Xe.value),Xe=kr.next()}ue(ze,ae)},"nextValue"),We=ye(kr.next());We&&(W||(W=[]),W.push(We));return}else if(he=Oe.call(this,he),he?.then){W||(W=[]),W.push(he.then(ze=>ue(ze,ae)));return}}ue(he,ae)},"handleResolvedValue");X?.then?(W||(W=[]),W.push(X.then(ne))):ne(X);return}else X=H[ae],X&&typeof X=="object"&&ae!==B&&(X=Me.transformEntryForSelect(B.select||B,S,A,null)({value:X}));ue(X,ae)},"selectAttribute"),oe;if(typeof E=="string")ee(E,B=>{oe=B});else if(Array.isArray(E))if(E.asArray)oe=[],E.forEach((B,ue)=>{B==="*"?E[ue]=H:ee(B,ae=>oe[ue]=ae)});else{oe={};let B=E.forceNulls;for(let ue of E)if(ue==="*")for(let ae in H)oe[ae]=H[ae];else ee(ue,(ae,ge)=>{ae===void 0&&B&&(ae=null),oe[ge]=ae})}else throw new lt.ClientError("Invalid select"+E);return W?Promise.all(W).then(()=>oe):oe}return H},"transform");return F}async subscribe(E){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||Ze({table:s,database:c,schemaDefined:u,attributes:T,audit:!0}),E||(E={});let S=!E.rawEvents,A=[],N=this,b=ON(Me,this.getId()??null,function(O,D,F,L){try{let H=D.getValue?.(i,S),W=D.type;if(!H&&W==="patch"&&S){let oe=i.getEntry(O);oe?.version===D.version?H=oe.value:H=D.getValue?.(i,!0,F),W="put"}let ee={id:O,localTime:F,value:H,version:D.version,type:W,beginTxn:L};A?A.push(ee):this.send(ee)}catch(H){xe.default.error?.(H)}},E.startTime||0,E),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,E.onlyChildren&&(b.onlyChildren=!0)),E.supportsTransactions&&(b.supportsTransactions=!0);let O=this.getId(),D=E.previousCount;D>1e3&&(D=1e3);let F=E.startTime;if(this.isCollection){if(F){if(D)throw new lt.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:L,value:H}of l.getRange({start:F,exclusiveStart:!0,snapshot:!1})){let W=Ut(H);if(W.tableId!==n)continue;let ee=W.recordId;if(O==null||W2(O,ee)){let oe=W.getValue(i,S,L);if(b.send({id:ee,localTime:L,value:oe,version:W.version,type:W.type}),b.queue?.length>K2&&await b.waitForDrain()===!1)return}b.startTime=L}}else if(D){let L=[];for(let{key:H,value:W}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ee=Ut(W);if(ee.tableId!==n)continue;let oe=ee.recordId;if(O==null||W2(O,oe)){let B=ee.getValue(i,S,H);if(L.push({id:oe,localTime:H,value:B,version:ee.version,type:ee.type}),--D<=0)break}}catch(ee){xe.default.error("Error getting history entry",H,ee)}for(let H=L.length;H>0;)b.send(L[--H]);L[0]&&(b.startTime=L[0].localTime)}else if(!E.omitCurrent){for(let{key:L,value:H,version:W,localTime:ee}of i.getRange({start:O??!1,end:O==null?void 0:[O,Ql.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(H&&(b.send({id:L,localTime:ee,value:H,version:W,type:"put"}),b.queue?.length>K2&&await b.waitForDrain()===!1))return}}else{D&&!F&&(F=0);let L=this.#n?.localTime;if(L===ML&&(i.cache?.delete(O),this.#n=i.getEntry(O),xe.default.trace?.("re-retrieved record",L,this.#n?.localTime),L=this.#n?.localTime),xe.default.trace?.("Subscription from",F,"from",O,L),F<L){let H=[],W=L;do{let ee=l.get(W);if(ee){E.omitCurrent=!0;let oe=Ut(ee),B=oe.getValue(i,S,W);S&&(oe.type="put"),H.push({id:O,value:B,localTime:W,...oe}),W=oe.previousLocalTime}else break;D&&D--}while(W>F&&D!==0);for(let ee=H.length;ee>0;)b.send(H[--ee]);b.startTime=L}!E.omitCurrent&&this.doesExist()&&b.send({id:O,localTime:L,value:this.#e,version:this.#r,type:"put"})}for(let L of A)b.send(L);A=null})();return E.listener&&b.on("data",E.listener),b}static subscribeOnThisThread(E,S){return E===0||S?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(E,S,A){if(S===void 0||S instanceof URLSearchParams)this._writePublish(this.getId(),E,S);else{let N=!0,b=this.getContext();return E.checkPermission&&(N=this.allowCreate(b.user,E,b)),Ri(N,C=>{if(!C)throw new lt.AccessViolation(b.user);let O=Sr(E);this._writePublish(O,S,A)})}}_writePublish(E,S,A){let N=Cr(this.getContext());E??=null,E!==null&&Or(E);let b=this.getContext();N.addWrite({key:E,store:i,entry:this.#n,nodeName:b?.nodeName,validate:o(()=>{b?.source||(N.checkOverloaded(),this.validate(S))},"validate"),before:Ne.publish?.bind(this,b,E,S),beforeIntermediate:Fe.publish?.bind(this,b,E,S),commit:o((C,O,D)=>{O===void 0&&y&&!g&&da(),xe.default.trace?.(`Publishing message to id: ${E}, timestamp: ${new Date(C).toISOString()}`),R(E,O?.value??null,O,O?.version||C,0,!0,{user:b?.user,residencyId:A?.residencyId,expiresAt:b?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(E,S){let A,N=o((b,C,O)=>{if(C.type&&b!=null)if(S&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be an object${C.type?" ("+C.type+")":""}`);let D=C.properties;for(let F=0,L=D.length;F<L;F++){let H=D[F];if(H.relationship||H.computed){E.hasOwnProperty(H.name)&&(A||(A=[])).push(`Computed property ${O}.${H.name} may not be directly assigned a value`);continue}let W=N(b[H.name],H,O+"."+H.name);W&&(b[H.name]=W)}if(C.sealed&&b!=null&&typeof b=="object")for(let F in b)D.find(L=>L.name===F)||(A||(A=[])).push(`Property ${F} is not allowed within object in property ${O}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} 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 ${Gs(b)} in property ${O} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(D=>typeof D=="string")||(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} 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 ${Gs(b)} in property ${O} 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 ${Gs(b)} in property ${O} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof gs)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let D=0,F=b.length;D<F;D++){let L=b[D],H=N(L,C.elements,O+"[*]");H&&(b[D]=H)}}else(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${O} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=T.length;b<C;b++){let O=T[b];if(O.relationship||O.computed){Object.hasOwn(E,O.name)&&(A||(A=[])).push(`Computed property ${O.name} may not be directly assigned a value`);continue}if(!S||O.name in E){let D=N(E[O.name],O,O.name);D!==void 0&&(E[O.name]=D)}}if(f)for(let b in E)T.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new lt.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return P?!!this.#i:void 0}static async addAttributes(E){let S=T.slice(0);for(let A of E){if(!A.name)throw new lt.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new lt.ClientError("Attribute names cannot include backticks or forward slashes");FSe(A.name),S.push(A)}return Ze({table:s,database:c,schemaDefined:u,attributes:S}),Me.indexingOperation}static async removeAttributes(E){let S=T.filter(A=>!E.includes(A.name));return Ze({table:s,database:c,schemaDefined:u,attributes:S}),Me.indexingOperation}static getSize(){let E=i.getStats();return(E.treeBranchPageCount+E.treeLeafPageCount+E.overflowPages)*E.pageSize}static getAuditSize(){let E=l?.getStats();return E&&(E.treeBranchPageCount+E.treeLeafPageCount+E.overflowPages)*E.pageSize}static getStorageStats(){let E=i.env.path,S=GL.default.statfsSync?.(E)??{};return{available:S.bavail*S.bsize,free:S.bfree*S.bsize,size:S.blocks*S.bsize}}static async getRecordCount(E){let S=i.getStats().entryCount,A=1e3/2,N=performance.now(),b=Math.floor(S/2),C=E?.exactCount,O=0,D=0,F;for(let{value:L}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(L!=null&&O++,D++,await cc(),!C&&D<b&&performance.now()-N>A){F=D;break}if(F){let L=O;O=0;for(let{value:X}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:F,snapshot:!1}))X!=null&&O++,await cc();let H=F*2,W=(O+L)/H,ee=Math.pow((O-L+1)/F/2,2)+W*(1-W)/H,oe=Math.max(Math.sqrt(ee)*S,1),B=Math.round(W*S),ue=Math.max(B-1.96*oe,O+L),ae=Math.min(B+1.96*oe,S),ge=Math.pow(10,Math.round(Math.log10(oe)));return ge>B&&(ge=ge/10),O=Math.round(B/ge)*ge,{recordCount:O,estimatedRange:[Math.round(ue),Math.round(ae)]}}return{recordCount:O}}static updatedAttributes(){wr=this.propertyResolvers={$id:o((E,S,A)=>({value:A.key}),"$id"),$updatedtime:o((E,S,A)=>A.version,"$updatedtime"),$updatedTime:o((E,S,A)=>A.version,"$updatedTime"),$expiresAt:o((E,S,A)=>A.expiresAt,"$expiresAt"),$record:o((E,S,A)=>A?{value:E}:E,"$record"),$distance:o((E,S,A)=>A&&(A.distance??S?.vectorDistances?.get(A)),"$distance")};for(let E of this.attributes){E.isPrimaryKey&&(Y=E),E.resolve=null;let S=E.relationship,A=E.computed;if(S)if(E.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,S.to)E.elements?.definition?(wr[E.name]=E.resolve=(N,b,C,O)=>{let D=N[S.from?S.from:t],F=E.elements.definition.tableClass;return O?sf({attribute:S.to,value:D},Cr(b).getReadTxn(),!1,F,!1).map(L=>L&&L.key!==void 0?L:F.primaryStore.getEntry(L,{transaction:Cr(b).getReadTxn()})).asArray:F.search([{attribute:S.to,value:D}],b).asArray},E.set=()=>{},E.resolve.definition=E.elements.definition,E.resolve.to=S.to,S.from&&(E.resolve.from=S.from)):console.error(`The one-to-many/many-to-many relationship property "${E.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(S.from){let N=E.definition||E.elements?.definition;N?(wr[E.name]=E.resolve=(b,C,O,D)=>{let F=b[S.from];if(F!==void 0){if(E.elements){let L,H=F?.map(W=>{let ee=N.tableClass.primaryStore[D?"getEntry":"get"](W,{transaction:Cr(C).getReadTxn()});return ee?.then&&(L=!0),ee});return S.filterMissing?L?Promise.all(H).then(W=>W.filter(z2)):H.filter(z2):L?Promise.all(H):H}return N.tableClass.primaryStore[D?"getEntry":"get"](F,{transaction:Cr(C).getReadTxn()})}},E.set=(b,C)=>{if(Array.isArray(C)){let O=C.map(D=>D.getId?.()||D[N.tableClass.primaryKey]);b[S.from]=O}else{let O=C.getId?.()||C[N.tableClass.primaryKey];b[S.from]=O}},E.resolve.definition=E.definition||E.elements?.definition,E.resolve.from=S.from):console.error(`The relationship property "${E.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${E.name}" in table "${s}" must use either "from" or "to" arguments`);else if(A)typeof A.from=="function"&&this.setComputedAttribute(E.name,A.from),wr[E.name]=E.resolve=(N,b,C)=>{let O=typeof A.from=="string"?N[A.from]:N,D=this.userResolvers[E.name];if(D)return D(O,b,C);xe.default.warn(`Computed attribute "${E.name}" does not have a function assigned to it. Please use setComputedAttribute('${E.name}', resolver) to assign a resolver function.`),this.userResolvers[E.name]=()=>{}},E.resolve.directReturn=!0;else if(r[E.name]?.customIndex?.propertyResolver){let N=r[E.name].customIndex;wr[E.name]=(b,C,O)=>{let D=b[E.name];return N.propertyResolver(D,C,O)},wr[E.name].directReturn=!0}}xm(this,this),xm(cu,this,!0);for(let E of T){let S=E.name;E.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return E.resolve(this,cf.getStore())},set(A){return E.set(this,A)},configurable:!0})}}static setComputedAttribute(E,S){let A=Xi(T,E);if(!A){console.error(`The attribute "${E}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${E}" is not defined as computed in the table "${s}"`);return}this.userResolvers[E]=S}static async deleteHistory(E=0,S=!1){let A;for(let{key:N,value:b}of l.getRange({start:0,end:E}))await cc(),Ut(b).tableId===n&&(A=yR(l,N,b));if(S)for(let N of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:O}=N;await cc(),C===null&&O<E&&(A=Yl(i,N))}await A}static async*getHistory(E=0,S=1/0){for(let{key:A,value:N}of l.getRange({start:E||1,end:S})){await cc();let b=Ut(N);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(E){let S=[];if(E==null)throw new Error("An id is required");let A=i.getEntry(E);if(!A)return S;let N=A.localTime;if(!N)throw new Error("The entry does not have a local audit time");let b=0;do{await cc();let C=l.get(N);if(C){let O=Ut(C);S.push({id:O.recordId,localTime:N,version:O.version,type:O.type,value:O.getValue(i,!0,N),user:O.user}),N=O.previousLocalTime}else break}while(b<1e3&&N);return S.reverse()}static cleanup(){V?.remove()}}Me.updatedAttributes();let wf=Me.prototype;return p&&Me.setTTLExpiration(p/1e3),j&&EE(),Me;function oo(q,E,S){let A;for(let N in r){let b=r[N],C=b.isIndexing,O=wr[N],D=S&&(O?O(S):S[N]),F=E&&(O?O(E):E[N]);if(D===F&&!C)continue;if(b.customIndex){b.customIndex.index(q,D,F);continue}A=!0;let L=b.indexNulls,H=(0,kp.getIndexedValues)(D,L),W=(0,kp.getIndexedValues)(F,L);if(W?.length>0){let ee=new Set(W);if(H=H?H.filter(oe=>{if(ee.has(oe))ee.delete(oe);else return!0}):[],W=Array.from(ee),(W.length>0||H.length>0)&&q2){let oe=W.concat(H).map(B=>({key:B,value:q}));b.prefetch(oe,Y2)}for(let oe=0,B=W.length;oe<B;oe++)b.remove(W[oe],q)}else H?.length>0&&q2&&b.prefetch(H.map(ee=>({key:ee,value:q})),Y2);if(H)for(let ee=0,oe=H.length;ee<oe;ee++)b.put(H[ee],q)}return A}o(oo,"updateIndices");function Or(q){switch(typeof q){case"number":return!0;case"string":if(q.length<659)return!0;if(q.length>V2)throw new Error("Primary key size is too large: "+q.length);break;case"object":if(q===null)throw new Error("Invalid primary key of null");break;case"bigint":if(q<2n**64n&&q>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof q)}if((0,Ql.writeKey)(q,VSe,0)>V2)throw new Error("Primary key size is too large: "+q.length);return!0}o(Or,"checkValidId");function Sr(q){return typeof q=="object"&&q?q.id:q}o(Sr,"requestTargetToId");function Of(q){return typeof q=="object"&&q&&q.isCollection}o(Of,"isSearchTarget");function Es(q){}o(Es,"isRequestTarget");function Tc(q,E,S,A,N){if(Me.getResidencyById&&S.ensureLoaded&&E?.replicateFrom!==!1){let C=wc(Me.getResidencyById(q));if(C&&!C.includes(server.hostname)&&I)return I({key:q,residency:C}).then(N)}let b=o(()=>{if(E?.transaction?.stale&&(E.transaction.stale=!1),S.transaction?.isDone)return N(null,q);let C=i.getEntry(q,S);return C?.residencyId&&C.metadataFlags&Fn&&I&&S.ensureLoaded&&E?.replicateFrom!==!1?I(C).then(O=>N(O,q),O=>(xe.default.error?.("Error loading remote record",q,C,S,O),N(null,q))):(C&&E&&(C?.version>(E.lastModified||0)&&(E.lastModified=C.version),C?.localTime&&!E.lastRefreshed&&(E.lastRefreshed=C.localTime)),N(C,q))},"whenPrefetched");return A?b():se>0?(se--,b()):new Promise((C,O)=>{se===0?(se--,i.prefetch([q],()=>{D(),F()})):(le.push(q),re.push(F),le.length>pE&&(se--,D()));function D(){if(le.length>0){let L=re;i.prefetch(le,()=>{se===-1?D():se++;for(let H of L)H()}),le=[],re=[],_e>2&&_e--}else se=_e,_e<Ty&&_e++}o(D,"prefetch");function F(){try{C(b())}catch(L){O(L)}}o(F,"load")})}o(Tc,"loadLocalRecord");function Rc(q,E){let S=E?.checkPermission;if(typeof S!="object"){if(!q?.role)return;S=q.role.permission}if(S.super_user)return KSe;let A=S[c],N,b=A?.tables;if(b)return b[s];if(c==="data"&&(N=S[s])&&!N.tables)return N}o(Rc,"getTablePermissions");function yc(q,E,S,A){if(P){let N=!1;if(S.noCache?N=!0:(E?(!E.value||E.metadataFlags&(Fn|ac)||E.expiresAt!=null&&E.expiresAt<Date.now())&&(N=!0):N=!0,Vr(!N,"cache-hit",s)),N){let b=lu(q,E,S).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),S&&(C?.version>(S.lastModified||0)&&(S.lastModified=C.version),S.lastRefreshed=Date.now()),C));if(S?.onlyIfCached||E?.value&&A?.allowStaleWhileRevalidate?.(E,q)){if(b.catch(C=>xe.default.warn?.(C)),S?.onlyIfCached&&!A.doesExist())throw new lt.ServerError("Entry is not cached",504);return}else return b}}else if(E?.value&&E.expiresAt!=null&&E.expiresAt<Date.now())return Me.evict(E.key,E.value,E.version),E.value=null,{then(N){return N(E)}}}o(yc,"ensureLoadedFromSource");function Cr(q){let E=q?.transaction;if(E){if(!E.lmdbDb)return E.lmdbDb=i,E;do{if(E.lmdbDb?.path===i.path)return E;let S=E.next;if(!S)return E=E.next=new co,E.lmdbDb=i,E;E=S}while(!0)}else return new ME}o(Cr,"txnForContext");function Ac(q,E,S){if(!q)return;let A=(q.deref?q.deref():q.value)??i.getEntry(q.key)?.value;if(typeof E=="object"){let b=wr,C=A;for(let O=0,D=E.length;O<D;O++){let F=E[O],L=b?.[F];C=L&&C?L(C,S,q):C?.[F],q=null,b=L?.definition?.tableClass?.propertyResolvers}return C}let N=wr[E];return N?N(A,S,q):A[E]}o(Ac,"getAttributeValue");function Cf(q,E,S,A,N){let b=N?.length,C={transaction:A,lazy:b>0||typeof E=="string"||E?.length<4,alwaysPrefetch:!0},O;function D(F,L){let H=F?.value;if(!H)return lc.SKIP;for(let W=0;W<b;W++)if(!O?.includes(W)&&!N[W](H,F))return lc.SKIP;return L!==void 0&&(F.key=L),F}if(o(D,"processEntry"),b>0||!q.hasEntries){let F=q.map(L=>{if(O=null,typeof L=="object"&&L?.key!==void 0)return b>0?D(L):L;if(L==null)return lc.SKIP;for(let H=0;H<b;H++){let ee=N[H].idFilter;if(ee){if(!ee(L))return lc.SKIP;O||(O=[]),O.push(H)}}return Tc(L,S,C,!1,D)});return Array.isArray(q)&&(F=F.filter(L=>L!==lc.SKIP)),F.hasEntries=!0,F}return q}o(Cf,"transformToEntries");function bc(q,E,S=server.replication?.getThisNodeId(l)){if(q<=E?.version){if(E?.version===q&&S!==void 0){let A=server.replication?.exportIdMapping(l),N=E.localTime,b=N&&l.get(N);if(b){let C,O,D=Ut(b);for(let F in A)A[F]===S&&(C=F),A[F]===D.nodeId&&(O=F);if(C>O)return 1;if(C===O)return 0}}return-1}return 1}o(bc,"precedesExistingVersion");async function lu(q,E,S){let A=E?.metadataFlags,N=E?.version,b,C;if(!i.attemptLock(q,N,()=>{clearTimeout(C);let L=i.getEntry(q);!L||!L.value||L.metadataFlags&(Fn|ac)?b(lu(q,i.getEntry(q),S)):b(L)}))return new Promise(L=>{b=L,C=setTimeout(()=>{i.unlock(q,N)},qSe)});let O=E?.value,D={requestContext:S,replacingRecord:O,replacingEntry:E,replacingVersion:N,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},F=S?.responseHeaders;return new Promise((L,H)=>{let W;Ri(Mt(D,async ee=>{let oe=performance.now(),B,ue,ae;try{for(let ne of Me.sources)if(ne.get&&(!ne.get.reliesOnPrototype||ne.prototype.get)){if(ne.available?.(E)===!1)continue;if(D.source=ne,B=await ne.get(q,D),B)break}ae=A&Fn;let X=D.lastModified||ae&&N;ue=ae||X>N||!O,X||(X=(0,kp.getNextMonotonicTime)());let de=performance.now()-oe;if(gt(de,"cache-resolution",s,null,"success"),F&&$m(F,"Server-Timing",`cache-resolve;dur=${de.toFixed(2)}`,!0),ee.timestamp=X,p&&D.expiresAt==null&&(D.expiresAt=Date.now()+p),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=O,X=N;else throw new lt.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==q&&(B[t]=q)}W=!0,L({key:q,version:X,value:B})}catch(X){X.message+=` while resolving record ${q} for ${s}`,O&&((X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(X.statusCode===500||X.statusCode===502||X.statusCode===503||X.statusCode===504))?(L({key:q,version:N,value:O}),xe.default.trace?.(X.message,"(returned stale record)")):H(X);let de=performance.now()-oe;gt(de,"cache-resolution",s,null,"fail"),F&&$m(F,"Server-Timing",`cache-resolve;dur=${de.toFixed(2)}`,!0),D.transaction.abort();return}if(S?.noCacheStore||D.noCacheStore){D.transaction.abort();return}Cr(D).addWrite({key:q,store:i,entry:E,nodeName:"source",commit:o((X,de)=>{if(de?.version!==N)return;let ne=oo(q,O,B);if(B){Fe.put?.(D,q,B),de&&(S.previousResidency=Me.getResidencyRecord(de.residencyId));let he,Ae=!1,Oe,ze=wc(Me.getResidency(B,S));if(ze){if(!ze.includes(server.hostname))if(he=B,Ae=!0,Me.getResidencyById)B=void 0;else{B=null;for(let kr in r)B||(B={}),B[kr]=he[kr]}Oe=fa(ze)}xe.default.trace?.(`Writing resolved record from source with id: ${q}, timestamp: ${new Date(X).toISOString()}`),R(q,B,de,X,Ae?Fn:0,g&&(ue||Ae)||null,{user:D?.user,expiresAt:D.expiresAt,residencyId:Oe},"put",!!ae,he)}else de&&(Fe.delete?.(D,q),xe.default.trace?.(`Deleting resolved record from source with id: ${q}, timestamp: ${new Date(X).toISOString()}`),g||y?R(q,null,de,X,0,g&&ue||null,{user:D?.user},"delete",!!ae):Yl(i,de,N))},"commit")})}),()=>{i.unlock(q,N)},ee=>{i.unlock(q,N),W&&xe.default.error?.("Error committing cache update",ee)})})}o(lu,"getFromSource");function Ic(q){if(!q||q.user?.role?.permission?.super_user)return!0;if(q.replicateTo)throw new lt.ClientError("Can not specify replication parameters without super user permissions",403);if(q.replicatedConfirmation)throw new lt.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Ic,"checkContextPermissions");function da(q){let E=!1;if(q&&(q-_r>1&&(E=!0),_r=q),!(He===pt&&!E)&&(pt=He,(0,zl.getWorkerIndex)()===(0,zl.getWorkerCount)()-1))return gr&&clearTimeout(gr),He?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let N=He/(1+_r),b=E?Date.now():Math.ceil((Date.now()-A.getTime())/N)*N+A.getTime(),C=o(O=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(O)}`),gr=setTimeout(()=>te=te.then(async()=>{if(C(Math.max(O+He,Date.now())),i.rootStore.status!=="open"){clearTimeout(gr);return}let D=50,F=new Array(D),L=0,H=Math.pow(_r,8)*(jl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),W=_/Math.pow(Math.max(_r,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${H}, adjusted eviction ${W}ms`);function ee(oe,B,ue,ae){let ge=oe+W-Date.now();if(ge<0)return!0;if(_r){let X=i.lastSize;return ue&Dn&&pu(ae,de=>{de.size&&(X+=de.size)}),xe.default.trace?.(`shouldEvict adjusted ${ge} ${X}, ${ge*(oe-B)/X} < ${H}`),ge*(oe-B)/X<H}return!1}o(ee,"shouldEvict");try{let oe=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:ue,value:ae,version:ge,expiresAt:X,metadataFlags:de}=B,ne;ae===null&&!g&&ge+GSe<Date.now()?ne=Yl(i,B,ge):X!=null&&ee(X,ge,de,ae)&&(ne=Me.evict(ue,ae,ge),oe++),ne&&(await F[L],F[L]=ne.catch(he=>{xe.default.error?.("Cleanup error",he)}),++L>=D&&(L=0)),await cc()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${oe} entries`)}catch(oe){xe.default.warn?.(`Error in cleanup scan for ${s}:`,oe)}S(void 0),_r=0}),Math.min(O-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}o(da,"scheduleCleanup");function Nc(){V=l?.addDeleteRemovalCallback(n,i,(q,E)=>{i.remove(q,E)})}o(Nc,"addDeleteRemoval");function EE(){(0,zl.getWorkerIndex)()===0&&setInterval(async()=>{if(!au){au=!0;try{let q=j.name,E=r[q];if(!E)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let S of E.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of E.getValues(S)){let N=i.getEntry(A);N?.value?N.value[q]<Date.now()&&Me.evict(A,N.value,N.version):i.ifVersion(A,N?.version,()=>E.remove(S,A))}await cc()}}catch(q){xe.default.error?.("Error in evicting old records",q)}finally{au=!1}}},kSe).unref()}o(EE,"runRecordExpirationEviction");function wc(q){if(q!=null){if(Array.isArray(q))return q;if(typeof q=="number"){if(q>=65536)throw new Error(`Shard id ${q} must be below 65536`);let E=server.shards?.get?.(q);if(E)return xe.default.trace?.(`Shard ${q} mapped to ${E.map(S=>S.name).join(", ")}`),E.map(S=>S.name);throw new Error(`Shard ${q} is not defined`)}throw new Error(`Shard or residency list ${q} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(wc,"residencyFromFunction");function fa(q){if(q){let E=q.join(","),S=d.get([Symbol.for("residency_by_set"),E]);return S||(d.put([Symbol.for("residency_by_set"),E],S=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),S],q),S)}}o(fa,"getResidencyId")}function kL(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 Y2(){}function YC(e){J2=e}function MR(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 DR(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return DR(+e);case"Float":return e==="null"?null:DR(+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;YSe.test(e)||(e+="Z");let n=new Date(e);return DR(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,vR.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function DR(e){if(isNaN(e))throw new SyntaxError;return e}function W2(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 Ri(e,t,r){return e?.then?e.then(t,r):t(e)}function z2(e){return e!=null}function Gs(e){try{return JSON.stringify(e)}catch{return e}}function WSe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var lc,kp,j2,Q2,jl,lt,Gp,qp,xe,Ql,zl,vR,GL,BSe,FSe,HSe,J2,kSe,GSe,q2,qSe,$2,$Se,Fn,ac,VSe,V2,K2,KSe,QBe,YSe,cc,op=fe(()=>{k();lc=require("lmdb"),kp=w(Rn()),j2=w(require("lodash")),Q2=w(qf());wa();Vf();jl=w(ce());CN();lt=w(Ee()),Gp=w(yo()),qp=w(ti());Le();ig();xe=w(Ii());pI();Dc();Ql=require("ordered-binary"),zl=w(st());Io();vR=w(ie());kc();Fi();U_();Vm();GL=w(require("node:fs"));Ss();gR();({sortBy:BSe}=j2.default),{validateAttribute:FSe}=Q2.default,HSe=new Uint8Array(9);HSe[8]=192;kSe=6e4,GSe=864e5;jl.initSync();q2=jl.get(U.STORAGE_PREFETCHWRITES),qSe=1e4,$2=1,$Se=2,Fn=1,ac=8,VSe=Buffer.allocUnsafeSlow(8192),V2=1978,K2=100,KSe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},QBe=(0,vR.convertToMS)(jl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(UR,"makeTable");o(kL,"attributesAsObject");o(Y2,"noop");o(YC,"setServerUtilities");YSe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(MR,"coerceType");o(DR,"rejectNaN");o(W2,"isDescendantId");cc=o(()=>new Promise(setImmediate),"rest");o(Ri,"when");o(z2,"exists");o(Gs,"stringify");o(WSe,"hasOtherProcesses")});function xR(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Euclidean distance comparison requires an array");let r=0,n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let i=e[s]||0,a=t[s]||0,c=i-a;r+=c*c}return r}function BR(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let a=0;a<i;a++){let c=e[a]||0,l=t[a]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var X2=fe(()=>{o(xR,"euclideanDistance");o(BR,"cosineDistance")});var Z2,eQ,uf,Zi,lf,zSe,jSe,FR,tQ=fe(()=>{X2();Z2=require("msgpackr"),eQ=w(Ii()),uf=w(Ee()),Zi=(0,eQ.loggerWithTag)("HNSW"),lf=Symbol.for("entryPoint"),zSe=Symbol.for("key"),jSe=10,FR=class{static{o(this,"HierarchicalNavigableSmallWorld")}static useObjectStore=!0;indexStore;M=16;efConstruction=100;efConstructionSearch=50;mL=1/Math.log(this.M);optimizeRouting=.5;nodesVisitedCount=0;idIncrementer;distance;constructor(t,r){this.indexStore=t,t&&(this.indexStore.encoder.useFloat32=Z2.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?xR:BR,r&&(r.M!==void 0&&(this.M=r.M,this.mL=1/Math.log(this.M)),r.efConstruction!==void 0&&(this.efConstruction=this.efConstructionSearch=r.efConstruction),r.efConstructionSearch!==void 0&&(this.efConstructionSearch=r.efConstructionSearch),r.mL!==void 0&&(this.mL=r.mL),r.optimizeRouting!==void 0&&(this.optimizeRouting=r.optimizeRouting))}index(t,r,n){let s=typeof t=="number"?[zSe,t]:t,i=this.indexStore.get(s);if(!i){if(!r)return;if(!this.idIncrementer){let f=0;for(let m of this.indexStore.getKeys({reverse:!0,limit:1,start:1/0,end:0}))typeof m=="number"&&(f=m);this.idIncrementer=new BigInt64Array([BigInt(f)+1n]),this.idIncrementer=new BigInt64Array(this.indexStore.getUserSharedBuffer("next-id",this.idIncrementer.buffer))}i=Number(Atomics.add(this.idIncrementer,0,1n)),this.indexStore.put(s,i)}let a=new Map,c,l=this.indexStore.get(lf);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let _=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:_,primaryKey:t};for(let y=0;y<=_;y++)g[y]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);Zi.debug?.("setting entry point to",i),this.indexStore.put(lf,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),jSe),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);Zi.debug?.("setting entry point to",i),this.indexStore.put(lf,i)}for(;h>m;){let _=this.searchLayer(r,l,f,this.efConstruction,h);_.length>0&&(l=_[0].id,f=_[0].node),h--}let p=new Array(m+1);for(let _=0;_<=m;_++)p[_]=[];for(let _=Math.min(m,h);_>=0;_--){let g=this.searchLayer(r,l,f,this.efConstruction,_);g=g.slice(0,this.M<<1),g.length===0&&_===0&&Zi.info?.("should not have zero connections for",l);let y=p[_];for(let T=0;T<g.length;T++){let{id:R,distance:I,node:P}=g[T];if(R===i)continue;let Y=[];if(this.optimizeRouting){let $=!1,j=P[_],V=1+this.optimizeRouting*(1+.5*T/this.M);for(let le=0;le<j.length;le++){let{id:re,distance:se}=j[le],_e=1+this.optimizeRouting*(1+.5*le/this.M);for(let Ne=0;Ne<y.length;Ne++){let{id:Fe,distance:He}=y[Ne];if(Fe===re){I*V>He+se?$=!0:se*_e>I+He&&(Y.push({fromId:Fe,toId:R}),Y.push({fromId:R,toId:Fe}));break}}if($)break}if($)continue}else if(T>=(_>0?this.M:this.M<<1))continue;y.push({id:R,distance:I});for(let{fromId:$,toId:j}of Y){let V=d($);V||(V=d($,this.indexStore.get($)));for(let le=0;le<V[_].length;le++)if(V[_][le].id===j){Object.isFrozen(V[_])&&(V[_]=V[_].slice()),V[_].splice(le,1);break}}let te=c[_],x=te?.find(({id:$})=>$===R);if(x){let $=te?.indexOf(x);te.copied||(te=[...te],te.copied=!0,c[_]=te),te.splice($,1)}else this.addConnection(R,d(R,P),i,_,I,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...p})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m][0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:h,value:p}of this.indexStore.getRange({start:0,end:1/0}))if(p.level>m){if(l=h,p.level===f)break;m=p.level}}if(l===void 0)this.indexStore.remove(lf);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);Zi.debug?.("setting entry point to",l),this.indexStore.put(lf,l)}}this.indexStore.remove(i)}let u=new Map;if(c.level!==void 0)for(let f=0;f<=c.level;f++){let m=c[f];for(let{id:h}of m){let p=d(h,this.indexStore.get(h));for(let _=0;_<=f;_++)p[_]=p[_]?.filter(({id:g})=>g!==i),p[_].length===0&&(Zi.info?.("node was left orphaned, will reindex",h),u.set(p.primaryKey,p.vector))}}function d(f,m){let h=a.get(f);return!h&&m&&(h={...m},a.set(f,h)),h}o(d,"updateNode");for(let[f,m]of a)this.indexStore.put(f,m);for(let[f,m]of u)this.index(f,m,m);this.checkSymmetry(i,this.indexStore.get(i))}getEntryPoint(){let t=this.indexStore.get(lf);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,a=this.distance){let c=new Set([r]),l=[{id:r,distance:this.distance(t,n.vector),node:n}],u=[...l];for(;l.length>0;){l.sort((h,p)=>h.distance-p.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:h}of m[i]||[]){if(c.has(h)||h===void 0)continue;c.add(h);let p=this.indexStore.get(h);if(!p)continue;this.nodesVisitedCount++;let _=a(t,p.vector);if(_<f||u.length<s){let g={id:h,distance:_,node:p};l.push(g),u.push(g)}}u.sort((h,p)=>h.distance-p.distance),u.length>s&&u.splice(s,u.length-s)}return u.visited=c.size,u}search({target:t,value:r,descending:n,distance:s,comparator:i}){let a=0;switch(i){case"lt":case"le":a=r;case"sort":break;default:throw new uf.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new uf.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=BR;else if(s==="euclidean")c=xR;else{if(s)throw new uf.ClientError("Unknown distance function");c=this.distance}if(!t)throw new uf.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new uf.ClientError("The target vector must be an array");let l=this.getEntryPoint();if(!l)return[];let u=l.id,d=[];for(let f=l.level;f>=0;f--)if(d=this.searchLayer(t,u,l,this.efConstructionSearch,f,c),d.length>0){let m=d[0];l=m.node,u=m.id}return a&&(d=d.filter(f=>f.distance<a)),d.map(f=>({key:f.node.primaryKey,distance:f.distance}))}checkSymmetry(t,r){if(!r)return;let n=0,s;for(;(s=r[n])&&s.length!==0;){for(let{id:i}of s){let a=this.indexStore.get(i);if(!a){Zi.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||Zi.info?.("asymmetry detected",a[n])}n++}}addConnection(t,r,n,s,i,a){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){Zi.warn?.("maxConnections reached, removing some connections",c);let l=[...r[s]];l.sort((f,m)=>f.distance-m.distance);let u=l.slice(0,c),d=l.slice(c);r[s]=u;for(let f of d){let m=a(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=a(f.id,m),m[s]=m[s].filter(({id:h})=>h!==t),s===0&&m[s].length===0&&Zi.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?Zi.debug?.("already connected",t,n):r[s]=[...r[s],{id:n,distance:i}]}validateConnectivity(t=0){let r=this.getEntryPoint(),n=new Set,s=[r.id];n.add(r.id);let i=0;for(;s.length>0;){let a=s.shift(),c=this.indexStore.get(a);for(let l=t;l<=c.level;l++)for(let{id:u}of c[l]||[])i++,n.has(u)||(n.add(u),s.push(u))}return n.size!==this.totalNodes&&console.log("visited",n.size,"total",this.totalNodes),{isFullyConnected:n.size===this.totalNodes,averageConnections:i/n.size}}get totalNodes(){return Array.from(this.indexStore.getKeys({start:0,end:1/0})).length}estimateCountAsSort(){return Math.sqrt(this.indexStore.getStats().entryCount*this.efConstructionSearch)}propertyResolver(t,r,n){let s=r?.sort;if(s){let i=s.vectorDistances;if(i){let l=i.get(n);if(l)return l}else i=r.vectorDistances=s.vectorDistances=new Map;let a=this.distance;s.type&&(a=s.distance==="euclidean"?xR:BR);let c=a(s.target,t);return i.set(n,c),c}return t}}});var qL,rQ=fe(()=>{tQ();qL={HNSW:FR}});var ft={};Ce(ft,{database:()=>Mu,databaseEnvs:()=>Jo,databases:()=>Ge,dropDatabase:()=>TI,dropTableMeta:()=>eTe,getDatabases:()=>it,getDefaultCompression:()=>LS,getTables:()=>QSe,onRemovedDB:()=>dh,onUpdatedTable:()=>Rl,readMetaDb:()=>$p,resetDatabases:()=>Od,table:()=>Ze,tables:()=>cn});function QSe(){return qR||it(),cn||{}}function it(){if(qR)return Ge;qR=!0,mf=new Map;let e=(0,zt.getHdbBasePath)()&&(0,xt.join)((0,zt.getHdbBasePath)(),Pc),t=(0,zt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(U.STORAGE_PATH)||e&&((0,cs.existsSync)(e)?e:(0,xt.join)((0,zt.getHdbBasePath)(),yE)),!e)return;if((0,cs.existsSync)(e))for(let n of(0,cs.readdirSync)(e,{withFileTypes:!0})){let s=(0,xt.basename)(n.name,".mdb");n.isFile()&&(0,xt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&$p((0,xt.join)(e,n.name),null,s)}if((0,cs.existsSync)((0,ff.getBaseSchemaPath)())){for(let n of(0,cs.readdirSync)((0,ff.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,xt.join)((0,ff.getBaseSchemaPath)(),n.name),i=(0,xt.join)((0,ff.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,cs.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,xt.extname)(a.name).toLowerCase()===".mdb"){let c=(0,xt.join)(i,a.name);$p((0,xt.join)(s,a.name),(0,xt.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,cs.existsSync)(i))for(let c of(0,cs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,xt.extname)(c.name).toLowerCase()===".mdb"&&$p((0,xt.join)(i,c.name),(0,xt.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,xt.join)(l.path,(0,xt.basename)(c+".mdb"));(0,cs.existsSync)(u)&&$p(u,c,n,null,!0)}}for(let n in Ge){let s=mf.get(n);if(s){let i=Ge[n];n.includes("delete")&&Ir.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Ir.trace(`delete table class ${a}`),delete i[a])}else if(delete Ge[n],n==="data"){for(let i in cn)delete cn[i];delete cn[$R]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,zt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(Ge.system?.hdb_analytics?.enableAuditing(),Ge.system?.hdb_analytics_hostname?.enableAuditing()),Ge.system)for(let n of r)Ge.system[n]&&(Ge.system[n].replicate=!1);return mf=null,Ge}function Od(){qR=!1;for(let[,e]of Jo)e.needsDeletion=!0;it();for(let[e,t]of Jo)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),Jo.delete(e);let r=Ge[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Ge[t.databaseName],Kp.forEach(i=>i(t.databaseName));break}}return Ge}function $p(e,t,r=KL,n,s){let i=new $L.default(e,!1);try{let a=Jo.get(e);a?a.needsDeletion=!1:(a=(0,hf.open)(i),Jo.set(e,a));let c=new pf.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(HR.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,cs.existsSync)(n)&&(i.path=n,u=(0,hf.open)(i),u.isLegacy=!0):u=RR(a));let d=aQ(r),f=d[$R],m=new Map;for(let{key:h,value:p}of l.getRange({start:!1})){let[_,g]=h.toString().split("/");g===""?g=p.name:g||(g=_,_=t,p.name||(p.name=g,p.indexed=!p.is_hash_attribute)),f?.add(_);let y=m.get(_);y||m.set(_,y={attributes:[]}),(g==null||p.is_hash_attribute)&&(y.primary=p),g!=null&&y.attributes.push(p),Object.defineProperty(p,"key",{value:h,configurable:!0})}for(let[h,p]of m){let{attributes:_,primary:g}=p;if(!g){for(let se of _)if(se.is_hash_attribute||se.isPrimaryKey){g=se;break}if(!g){Ir.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(_)}`);continue}}let y=d[h],T={},R=[],I,P,Y=typeof g.audit=="boolean"?g.audit:(0,zt.get)(U.LOGGING_AUDITLOG),te=g.trackDeletes,x=g.expiration,$=g.eviction,j=g.sealed,V=g.splitSegments,le=g.replicate;if(y)T=y.indices,R=y.attributes,y.schemaVersion++;else{I=g.tableId,I?I>=(l.get(df)||0)&&(l.putSync(df,I+1),Ir.info(`Updating next table id (it was out of sync) to ${I+1} for ${h}`)):(g.tableId=I=l.get(df),I||(I=1),Ir.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(df,I+1),l.putSync(g.key,g));let se=new pf.default(!g.is_hash_attribute,g.is_hash_attribute);if(se.compression=g.compression,se.compression){let _e=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||oQ;se.compression.threshold=_e}P=wR(a.openDB(g.key,se),a),a.databaseName=r,P.tableId=I}let re;for(let se of _){se.attribute=se.name;try{if(!se.is_hash_attribute&&(se.indexed||se.attribute&&!se.name)){if(!T[se.name]){let Ne=lQ(se.key,a,se);T[se.name]=Ne,T[se.name].indexNulls=se.indexNulls}let _e=R.find(Ne=>Ne.name===se.name);_e?R.splice(R.indexOf(_e),1,se):R.push(se),re=!0}}catch(_e){Ir.error("Error trying to update attribute",se,R,T,_e)}}for(let se of R)if(!_.find(Ne=>Ne.name===se.name)){if(se.is_hash_attribute){Ir.error("Unable to remove existing primary key attribute",se);continue}se.indexed&&(R.splice(R.indexOf(se),1),re=!0)}if(y)re&&(y.schemaVersion++,y.updatedAttributes());else{y=cQ(d,h,UR({primaryStore:P,auditStore:u,audit:Y,sealed:j,splitSegments:V,replicate:le,expirationMS:x&&x*1e3,evictionMS:$&&$*1e3,trackDeletes:te,tableName:h,tableId:I,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:_,schemaDefined:g.schemaDefined,dbisDB:l})),y.schemaVersion=1;for(let se of Vp)se(y)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function aQ(e){let t=Ge[e];if(t||(e==="data"?t=Ge[e]=cn:e==="system"?Object.defineProperty(Ge,"system",{value:t=Object.create(null),configurable:!0}):t=Ge[e]=Object.create(null)),mf&&!mf.has(e)){let r=new Set;t[$R]=r,mf.set(e,r)}return t}function cQ(e,t,r){return e[t]=r,r}function Mu({database:e,table:t}){e||(e=KL),it();let r=aQ(e),n=(0,xt.join)((0,zt.getHdbBasePath)(),Pc),s=(0,zt.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,zt.get)(U.STORAGE_PATH)||((0,cs.existsSync)(n)?n:(0,xt.join)((0,zt.getHdbBasePath)(),yE));let a=(0,xt.join)(n,(i?t:e)+".mdb"),c=Jo.get(a);if(!c||c.status==="closed"){let l=new $L.default(a,!1);c=(0,hf.open)(l),Jo.set(a,c)}return c.auditStore||(c.auditStore=RR(c)),c}async function TI(e){if(!Ge[e])throw new Error("Schema does not exist");let t=Ge[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Jo.delete(r.path),r.status==="open"&&(await r.close(),await Yp.remove(r.path));if(r||(r=Mu({database:e,table:null}),r.status==="open"&&(await r.close(),await Yp.remove(r.path))),e==="data"){for(let n in cn)delete cn[n];delete cn[$R]}delete Ge[e],Kp.forEach(n=>n(e)),await iA(r)}function lQ(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&qL[r.indexed.type]?.useObjectStore,s=new pf.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=qL[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Ir.error(`The indexing type '${r.indexed.type}' is unknown`)}return i}function Ze(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:a,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:h}=e;r||(r=KL);let p=Mu({database:r,table:t}),_=Ge[r];Ir.trace(`Defining ${t} in ${r}`);let g=_?.[t];if(p.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let y,T,R;m==null&&(m=!0);let I=new pf.default(!1);for(let V of a)V.attribute&&!V.name?(V.name=V.attribute,V.indexed=!0):V.attribute=V.name,V.expiresAt&&(V.indexed=!0);let P,Y;if(g){if(y=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,...a)}else{let V=p.auditStore;T=a.find(_e=>_e.isPrimaryKey)||{},y=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=LS(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,zt.get)(U.LOGGING_AUDITLOG),n&&(T.expiration=n),s&&(T.eviction=s),u??=!1,T.splitSegments=u,typeof l=="boolean"&&(T.sealed=l),typeof d=="boolean"&&(T.replicate=d),h&&(T.origins?T.origins.includes(h)||T.origins.push(h):T.origins=[h]),Ir.trace(`${t} table loading, opening primary store`);let le=new pf.default(!1,!0);le.compression=T.compression;let re=t+"/";if(R=p.dbisDb=p.openDB(HR.INTERNAL_DBIS_NAME,I),j(),R.get(re))return Y&&Y(),Od(),Ze(e);let se=wR(p.openDB(re,le),p);p.databaseName=r,se.tableId=R.get(df),Ir.trace(`Assigning new table id ${se.tableId} for ${t}`),se.tableId||(se.tableId=1),R.put(df,se.tableId+1),T.tableId=se.tableId,g=cQ(_,t,UR({primaryStore:se,auditStore:V,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:y,tableName:t,tableId:se.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:R})),g.schemaVersion=1,P=!0,R.put(re,T)}let te=g.indices;R=R||(p.dbisDb=p.openDB(HR.INTERNAL_DBIS_NAME,I)),g.dbisDB=R;let x=[];for(let{key:V,value:le}of R.getRange({start:!0})){let[re,se]=V.toString().split("/");if(se===""&&(se=le.name),se){if(re!==t)continue}else continue;let _e=a.find(Fe=>Fe.name===se),Ne=!_e?.indexed&&le.indexed&&!le.isPrimaryKey;if((!_e||Ne)&&(j(),P=!0,_e||R.remove(V),Ne)){let Fe=g.indices[re];Fe&&x.push(Fe)}}let $=[];try{for(let V of a||[]){if((V.relationship||V.computed)&&(P=!0,V.relationship))continue;let le=t+"/"+(V.name||"");Object.defineProperty(V,"key",{value:le,configurable:!0});let re=R.get(le);if(V.isPrimaryKey){if(re=re||R.get(le=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+re.expiration||void 0)||(+s||void 0)!==(+re.eviction||void 0)||V.type!==re.type){let _e={...re};typeof c=="boolean"&&(c&&g.enableAuditing(c),_e.audit=c),n&&(_e.expiration=+n),s&&(_e.eviction=+s),l!==void 0&&(_e.sealed=l),d!==void 0&&(_e.replicate=d),V.type&&(_e.type=V.type),P=!0,j(),R.put(le,_e)}continue}re?.attribute&&!re.name&&(re.indexed=!0);let se=!re||re.type!==V.type||JSON.stringify(re.indexed)!==JSON.stringify(V.indexed)||re.nullable!==V.nullable||re.version!==V.version||JSON.stringify(re.properties)!==JSON.stringify(V.properties)||JSON.stringify(re.elements)!==JSON.stringify(V.elements);if(V.indexed){let _e=lQ(le,p,V);(se||re.indexingPID&&re.indexingPID!==process.pid||re.restartNumber<Wp.workerData?.restartNumber)&&(P=!0,j(),re=R.get(le),(se||re.indexingPID&&re.indexingPID!==process.pid||re.restartNumber<Wp.workerData?.restartNumber)&&(P=!0,V.indexNulls===void 0&&(V.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(V.lastIndexedKey=re?.lastIndexedKey??void 0,V.indexingPID=process.pid,_e.isIndexing=!0,Object.defineProperty(V,"dbi",{value:_e}),$.push(V))),R.put(le,V)),re?.indexNulls&&V.indexNulls===void 0&&(V.indexNulls=!0),_e.indexNulls=V.indexNulls,te[V.name]=_e}else se&&(P=!0,j(),R.put(le,V))}}finally{Y&&Y()}if(P&&(g.schemaVersion++,g.updatedAttributes()),Ir.trace(`${t} table loading, running index`),$.length>0||x.length>0?g.indexingOperation=ZSe(g,$,x):P&&kR.signalSchemaChange(new GR.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,P)for(let V of Vp)V(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Ir.trace(`${t} table loaded`),g;function j(){Y||p.transactionSync(()=>({then(V){Y=V}}))}o(j,"startTxn")}async function ZSe(e,t,r){try{Ir.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await kR.signalSchemaChange(new GR.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,a={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,hf.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,h,()=>{for(let p=0;p<l;p++){let _=t[p],g=_.name,y=_.dbi;try{let T=_.resolve,R=m&&(T?T(m):m[g]);if(y.customIndex){y.customIndex.index(f,R);continue}let I=(0,nQ.getIndexedValues)(R);if(I)for(let P=0,Y=I.length;P<Y;P++)y.put(I[P],f)}catch(T){a[g]||(a[g]=!0,Ir.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Ir.error(p)}),Wp.workerData&&Wp.workerData.restartNumber!==iQ.restartNumber&&(i=!0),++c%100===0||i){for(let p of t)p.lastIndexedKey=f,e.dbisDB.put(p.key,p);if(i)return}d>JSe?await s:d>XSe&&await new Promise(p=>setImmediate(p))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await kR.signalSchemaChange(new GR.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Ir.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Ir.error("Error in indexing",n)}}function eTe({table:e,database:t}){let r=Mu({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 Rl(e){return Vp.push(e),{remove(){let t=Vp.indexOf(e);t>-1&&Vp.splice(t,1)}}}function dh(e){return Kp.push(e),{remove(){let t=Kp.indexOf(e);t>-1&&Kp.splice(t,1)}}}function LS(){let e=(0,zt.get)(U.STORAGE_COMPRESSION),t=(0,zt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||oQ,n={startingOffset:32};return t&&(n.dictionary=Yp.readFileSync(t)),r&&(n.threshold=r),e&&n}var zt,HR,hf,xt,cs,ff,pf,$L,Yp,VL,nQ,kR,GR,Wp,sQ,iQ,Ir,KL,$R,oQ,cn,Ge,df,Vp,Kp,qR,Jo,mf,JSe,XSe,Le=fe(()=>{zt=w(ce()),HR=w(kt()),hf=require("lmdb"),xt=require("path"),cs=require("fs"),ff=w(yt());op();pf=w(rm()),$L=w(nm());k();Yp=w(require("fs-extra")),VL=w(Ws()),nQ=w(Rn()),kR=w(yo()),GR=w(ti()),Wp=require("worker_threads"),sQ=w(z()),iQ=w(st());Io();kc();Ss();rQ();Ir=(0,sQ.forComponent)("storage"),KL="data",$R=Symbol("defined-tables"),oQ=((0,zt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,zt.initSync)();cn=Object.create(null),Ge=Object.create(null);(0,VL._assignPackageExport)("databases",Ge);(0,VL._assignPackageExport)("tables",cn);df=Symbol.for("next-table-id"),Vp=[],Kp=[],Jo=new Map;o(QSe,"getTables");o(it,"getDatabases");o(Od,"resetDatabases");o($p,"readMetaDb");o(aQ,"ensureDB");o(cQ,"setTable");o(Mu,"database");o(TI,"dropDatabase");o(lQ,"openIndex");o(Ze,"table");JSe=1e3,XSe=10;o(ZSe,"runIndexing");o(eTe,"dropTableMeta");o(Rl,"onUpdatedTable");o(dh,"onRemovedDB");o(LS,"getDefaultCompression")});var ie=M(be=>{"use strict";var uc=require("path"),hQ=require("fs-extra"),kn=z(),uQ=require("fs-extra"),VR=require("os"),tTe=require("net"),rTe=require("recursive-iterator"),Nr=(k(),v(K)),{PACKAGE_ROOT:nTe}=Rt(),sTe=Hy(),dQ=require("papaparse"),KR=require("moment"),{inspect:iTe}=require("util"),fQ=require("is-number"),oTe=require("minimist"),aTe=require("https"),cTe=require("http"),lTe=/^((\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)))$/,pQ=require("util").promisify(setTimeout),uTe=100,dTe=5,fTe="",mTe=4,mQ={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};be.isEmpty=ls;be.isEmptyOrZeroLength=eo;be.arrayHasEmptyValues=ETe;be.arrayHasEmptyOrZeroLengthValues=_Te;be.buildFolderPath=gTe;be.isBoolean=EQ;be.errorizeMessage=hTe;be.stripFileExtension=TTe;be.autoCast=RTe;be.autoCastJSON=_Q;be.autoCastJSONDeep=WL;be.removeDir=yTe;be.compareVersions=ATe;be.isCompatibleDataVersion=bTe;be.escapeRawValue=ITe;be.unescapeValue=NTe;be.stringifyProps=wTe;be.timeoutPromise=CTe;be.isClusterOperation=LTe;be.getClusterUser=MTe;be.checkGlobalSchemaTable=DTe;be.getHomeDir=SQ;be.getPropsFilePath=OTe;be.promisifyPapaParse=vTe;be.removeBOM=TQ;be.createEventPromise=UTe;be.checkProcessRunning=xTe;be.checkSchemaTableExist=BTe;be.checkSchemaExists=RQ;be.checkTableExists=yQ;be.getStartOfTomorrowInSeconds=FTe;be.getLimitKey=HTe;be.isObject=STe;be.isNotEmptyAndHasValue=pTe;be.autoCasterIsNumberCheck=gQ;be.backtickASTSchemaItems=kTe;be.isPortTaken=PTe;be.createForkArgs=GTe;be.autoCastBoolean=qTe;be.asyncSetTimeout=pQ;be.getTableHashAttribute=$Te;be.doesSchemaExist=VTe;be.doesTableExist=KTe;be.stringifyObj=YTe;be.ms_to_time=WTe;be.changeExtension=zTe;be.getEnvCliRootPath=zL;be.noBootFile=jTe;be.httpRequest=QTe;be.transformReq=JTe;be.convertToMS=XTe;be.PACKAGE_ROOT=nTe;function hTe(e){return e instanceof Error?e:new Error(e)}o(hTe,"errorizeMessage");function ls(e){return e==null}o(ls,"isEmpty");function pTe(e){return!ls(e)&&(e||e===0||e===""||EQ(e))}o(pTe,"isNotEmptyAndHasValue");function eo(e){return ls(e)||e.length===0||e.size===0}o(eo,"isEmptyOrZeroLength");function ETe(e){if(ls(e))return!0;for(let t=0;t<e.length;t++)if(ls(e[t]))return!0;return!1}o(ETe,"arrayHasEmptyValues");function _Te(e){if(eo(e))return!0;for(let t=0;t<e.length;t++)if(eo(e[t]))return!0;return!1}o(_Te,"arrayHasEmptyOrZeroLengthValues");function gTe(...e){try{return e.join(uc.sep)}catch{console.error(e)}}o(gTe,"buildFolderPath");function EQ(e){return ls(e)?!1:e===!0||e===!1}o(EQ,"isBoolean");function STe(e){return ls(e)?!1:typeof e=="object"}o(STe,"isObject");function TTe(e){return eo(e)?fTe:e.slice(0,-mTe)}o(TTe,"stripFileExtension");function RTe(e){return ls(e)||e===""||typeof e!="string"?e:mQ[e]!==void 0?mQ[e]:gQ(e)===!0?Number(e):lTe.test(e)?new Date(e):e}o(RTe,"autoCast");function _Q(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(_Q,"autoCastJSON");function WL(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=WL(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=WL(r);n!==r&&(e[t]=n)}return e}else return _Q(e)}o(WL,"autoCastJSONDeep");function gQ(e){if(e.startsWith("0.")&&fQ(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&fQ(e))}o(gQ,"autoCasterIsNumberCheck");async function yTe(e){if(eo(e))throw new Error(`Directory path: ${e} does not exist`);try{await uQ.emptyDir(e),await uQ.remove(e)}catch(t){throw kn.error(`Error removing files in ${e} -- ${t}`),t}}o(yTe,"removeDir");function ATe(e,t){if(eo(e)){kn.info("Invalid current version sent as parameter.");return}if(eo(t)){kn.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,a=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(a[u],10)-parseInt(c[u],10),r)return r;return a.length-c.length}o(ATe,"compareVersions");function bTe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}o(bTe,"isCompatibleDataVersion");function ITe(e){if(ls(e))return e;let t=String(e);return t==="."?Nr.UNICODE_PERIOD:t===".."?Nr.UNICODE_PERIOD+Nr.UNICODE_PERIOD:t.replace(Nr.FORWARD_SLASH_REGEX,Nr.UNICODE_FORWARD_SLASH)}o(ITe,"escapeRawValue");function NTe(e){if(ls(e))return e;let t=String(e);return t===Nr.UNICODE_PERIOD?".":t===Nr.UNICODE_PERIOD+Nr.UNICODE_PERIOD?"..":String(e).replace(Nr.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(NTe,"unescapeValue");function wTe(e,t){if(ls(e))return kn.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let a of i)r+=";"+a+VR.EOL}!eo(n)&&n[0]===";"?r+=" "+n+s+VR.EOL:eo(n)||(r+=n+"="+s+VR.EOL)}catch{kn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}o(wTe,"stringifyProps");function SQ(){let e;try{e=VR.homedir()}catch{e=process.env.HOME}return e}o(SQ,"getHomeDir");function OTe(){let e=uc.join(SQ(),Nr.HDB_HOME_DIR_NAME,Nr.BOOT_PROPS_FILE_NAME);return hQ.existsSync(e)||(e=uc.join(__dirname,"../","hdb_boot_properties.file")),e}o(OTe,"getPropsFilePath");function CTe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:o(function(){clearTimeout(r)},"cancel")}}o(CTe,"timeoutPromise");async function PTe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=tTe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}o(PTe,"isPortTaken");function LTe(e){try{return Nr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){kn.error(`Error checking operation against cluster ops ${t}`)}return!1}o(LTe,"isClusterOperation");function DTe(e,t){let r=(Le(),v(ft)).getDatabases();if(!r[e])return YR.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return YR.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(DTe,"checkGlobalSchemaTable");function MTe(e,t){if(ls(t)){kn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ls(e)||eo(e)){kn.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){kn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){kn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}o(MTe,"getClusterUser");function vTe(){dQ.parsePromise=function(e,t,r){return new Promise(function(n,s){dQ.parse(e,{header:!0,transformHeader:TQ,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}o(vTe,"promisifyPapaParse");function TQ(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o(TQ,"removeBOM");function UTe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;kn.info(`Got cluster status event response: ${iTe(s)}`);try{i.cancel()}catch{kn.error("Error trying to cancel timeout.")}n(s)})})}o(UTe,"createEventPromise");async function xTe(e){let t=!0,r=0;do await pQ(uTe*r++),(await sTe.findPs(e)).length>0&&(t=!1);while(t&&r<dTe);if(t)throw new Error(`process ${e} was not started`)}o(xTe,"checkProcessRunning");function BTe(e,t){let r=RQ(e);if(r)return r;let n=yQ(e,t);if(n)return n}o(BTe,"checkSchemaTableExist");function RQ(e){let{getDatabases:t}=(Le(),v(ft));if(!t()[e])return YR.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(RQ,"checkSchemaExists");function yQ(e,t){let{getDatabases:r}=(Le(),v(ft));if(!r()[e][t])return YR.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(yQ,"checkTableExists");function FTe(){let e=KR().utc().add(1,"d").startOf("d").unix(),t=KR().utc().unix();return e-t}o(FTe,"getStartOfTomorrowInSeconds");function HTe(){return KR().utc().format("DD-MM-YYYY")}o(HTe,"getLimitKey");function kTe(e){try{let t=new rTe(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){kn.error("Got an error back ticking items."),kn.error(t)}}o(kTe,"backtickASTSchemaItems");function GTe(e){return[e]}o(GTe,"createForkArgs");function qTe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(qTe,"autoCastBoolean");function $Te(e,t){let{getDatabases:r}=(Le(),v(ft)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}o($Te,"getTableHashAttribute");function VTe(e){let{getDatabases:t}=(Le(),v(ft));return t()[e]!==void 0}o(VTe,"doesSchemaExist");function KTe(e,t){let{getDatabases:r}=(Le(),v(ft));return r()[e]?.[t]!==void 0}o(KTe,"doesTableExist");function YTe(e){try{return JSON.stringify(e)}catch{return e}}o(YTe,"stringifyObj");function WTe(e){let t=KR.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}o(WTe,"ms_to_time");function zTe(e,t){let r=uc.basename(e,uc.extname(e));return uc.join(uc.dirname(e),r+t)}o(zTe,"changeExtension");function zL(){if(process.env[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=oTe(process.argv);if(e[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(zL,"getEnvCliRootPath");var YL;function jTe(){if(YL)return YL;let e=zL();if(zL()&&hQ.pathExistsSync(uc.join(e,Nr.HDB_CONFIG_FILE)))return YL=!0,!0}o(jTe,"noBootFile");function QTe(e,t){let r;return e.protocol==="http:"?r=cTe:r=aTe,new Promise((n,s)=>{let i=r.request(e,a=>{a.setEncoding("utf8"),a.body="",a.on("data",c=>{a.body+=c}),a.on("end",()=>{n(a)})});i.on("error",a=>{s(a)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}o(QTe,"httpRequest");function JTe(e){if(!e.schema&&!e.database){e.schema=Nr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(JTe,"transformReq");function XTe(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}o(XTe,"convertToMS");var YR=en()});var ce=M((wQ,OQ)=>{"use strict";var jL=require("fs-extra"),Jl=require("path"),AQ=require("os"),ZTe=require("properties-reader"),jp=z(),zp=ie(),Be=(k(),v(K)),WR=At(),eRe="Error initializing environment manager",zR="BOOT_PROPS_FILE_PATH",bQ=!1,tRe={[Be.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Xo={};Object.assign(wQ,OQ.exports={BOOT_PROPS_FILE_PATH:zR,getHdbBasePath:rRe,setHdbBasePath:nRe,get:IQ,initSync:iRe,setProperty:Je,initTestEnvironment:aRe,setCloneVar:oRe});function rRe(){return Xo[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(rRe,"getHdbBasePath");function nRe(e){Xo[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(nRe,"setHdbBasePath");function IQ(e){let t=WR.getConfigValue(e);return t===void 0?Xo[e]:t}o(IQ,"get");function Je(e,t){tRe[e]&&(Xo[e]=t),WR.updateConfigObject(e,t)}o(Je,"setProperty");function sRe(){let e;try{e=zp.getPropsFilePath(),jL.accessSync(e,jL.constants.F_OK|jL.constants.R_OK),bQ=!0;let t=ZTe(e);return Xo[Be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Be.HDB_SETTINGS_NAMES.INSTALL_USER),Xo[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Xo[zR]=e,!0}catch{return jp.trace(`Environment manager found no properties file at ${e}`),!1}}o(sRe,"doesPropFileExist");function iRe(e=!1){try{((bQ||sRe()||zp.noBootFile())&&!NQ||e)&&(WR.initConfig(e),Xo[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=WR.getConfigValue(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){jp.error(eRe),jp.error(t),console.error(t),process.exit(1)}}o(iRe,"initSync");var NQ=!1;function oRe(e){NQ=e}o(oRe,"setCloneVar");function aRe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:a,local_studio_on:c}=e,l=Jl.join(__dirname,"../../","unitTests");Xo[zR]=Jl.join(l,"hdb_boot_properties.file"),Je(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Jl.join(l,"settings.test")),Je(Be.HDB_SETTINGS_NAMES.INSTALL_USER,AQ.userInfo()?AQ.userInfo().username:void 0),Je(Be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Je(Be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Jl.join(l,"envDir","log")),Je(Be.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Je(Be.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Je(Be.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Je(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Jl.join(l,"envDir")),Je(Be.CONFIG_PARAMS.STORAGE_PATH,Jl.join(l,"envDir")),s&&(Je(Be.CONFIG_PARAMS.HTTP_SECUREPORT,IQ(Be.CONFIG_PARAMS.HTTP_PORT)),Je(Be.CONFIG_PARAMS.HTTP_PORT,null)),Je(Be.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Je(Be.CONFIG_PARAMS.HTTP_PORT,9926),Je(Be.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Je(Be.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Je(Be.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,zp.isEmpty(i)?!1:i),Je(Be.CONFIG_PARAMS.HTTP_CORS,zp.isEmpty(i)?!1:i),Je(Be.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Je(Be.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Je(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Je(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Je(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Jl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Je(Be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,zp.isEmpty(c)?!1:c),a&&(Je("CORS_ACCESSLIST",a),Je(Be.CONFIG_PARAMS.HTTP_CORSACCESSLIST,a)),n&&(Je(Be.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Je(Be.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Je(Be.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Je(Be.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Je(Be.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Je(Be.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${zR}. Please check your boot props and settings files`;jp.fatal(r),jp.error(t)}}o(aRe,"initTestEnvironment")});var vQ=M((SFe,MQ)=>{"use strict";var{promises:Ef,createReadStream:cRe,createWriteStream:lRe}=require("fs"),{createGzip:uRe}=require("zlib"),{promisify:dRe}=require("util"),{pipeline:fRe}=require("stream"),mRe=dRe(fRe),JL=require("path"),DQ=ce();DQ.initSync();var jR=z(),{CONFIG_PARAMS:hRe,ITC_EVENT_TYPES:_Fe}=(k(),v(K)),{onMessageFromWorkers:gFe}=st(),{convertToMS:CQ}=ie(),{onStorageReclamation:pRe}=(gR(),v(_2)),ERe=6e4,_Re="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",gRe="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",QL,PQ;MQ.exports=SRe;function SRe({logger:e,maxSize:t,interval:r,retention:n,enabled:s,path:i,auditInterval:a}){if(s===!1)return;let c=0;if(pRe(e.path,f=>{c=f},!0),!t&&!r)throw new Error(_Re);if(!i)throw new Error(gRe);let l;if(t){let f=t.slice(-1),m=t.slice(0,-1);f==="G"?l=m*1e9:f==="M"?l=m*1e6:l=m*1e3}let u;r&&(u=CQ(r));let d;return QL=Date.now(),jR.trace("Log rotate enabled, maxSize:",t,"interval:",r),PQ=setInterval(async()=>{if(l){let f;f=await Ef.stat(e.path),f.size>=l&&(d=await LQ(e.path,i))}if(u&&Date.now()-QL>=u&&(d=await LQ(e.path,i),QL=Date.now()),n||c){let f=CQ(n??"1M")/(1+c);c=0;let m=await Ef.readdir(i);for(let h of m)try{let p=await Ef.stat(JL.join(i,h));Date.now()-p.mtimeMs>f&&await Ef.unlink(JL.join(i,h))}catch(p){jR.error("Error trying to remove log",h,p)}}},a??ERe).unref(),{end(){clearInterval(PQ)},getLastRotatedLogPath(){return d}}}o(SRe,"logRotator");async function LQ(e,t){let r=DQ.get(hRe.LOGGING_ROTATION_COMPRESS),n=JL.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.log`);return await Ef.rename(e,n),r&&(e=n,n+=".gz",await mRe(cRe(e),uRe(),lRe(n)),await Ef.unlink(e)),jR.closeLogFile(),jR.notify(`hdb.log rotated, old log moved to ${n}`),n}o(LQ,"moveLogFile")});var HQ={};Ce(HQ,{RootConfigWatcher:()=>XL});var UQ,xQ,BQ,QR,FQ,XL,kQ=fe(()=>{UQ=w(require("chokidar")),xQ=require("node:fs/promises"),BQ=w(At()),QR=require("node:stream"),FQ=require("yaml"),XL=class extends QR.EventEmitter{static{o(this,"RootConfigWatcher")}#e;#t;#r;constructor(){super(),this.#e=(0,BQ.getConfigFilePath)(),this.#t=UQ.default.watch(this.#e,{persistent:!1}).on("add",this.handleChange.bind(this)).on("change",this.handleChange.bind(this)).on("error",this.handleError.bind(this))}handleError(t){this.emit("error",t)}handleChange(){(0,xQ.readFile)(this.#e,"utf-8").then(t=>{if(!t)return;let r=(0,FQ.parse)(t);if(!this.#r){this.#r=r,this.emit("ready",this.#r);return}this.emit("change",this.#r=r)}).catch(t=>{})}ready(){return(0,QR.once)(this,"ready")}close(){return this.#t.close(),this.#r=void 0,this.emit("close"),this.removeAllListeners(),this}get config(){return this.#r}}});var z=M((bFe,sy)=>{"use strict";var ea=require("fs-extra"),{workerData:TRe,threadId:RRe,isMainThread:WQ}=require("worker_threads"),Xp=require("path"),zQ=require("yaml"),jQ=require("properties-reader"),Hr=(k(),v(K)),GQ=Lc(),yRe=require("os"),{PACKAGE_ROOT:iD}=Rt(),{_assignPackageExport:ARe}=Ws(),{Console:bRe}=require("console"),qQ=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),$Q=new Map,{join:ta}=Xp,VQ=1e4,nr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},IRe={STDOUT:"stdOut",STDERR:"stdErr"},AFe=ta(iD,"logs"),NRe=ta(iD,"config/yaml/",Hr.HDB_DEFAULT_CONFIG_FILE),wRe=1e4,Zp,eE,JR,Zo,eD,ZL,ZR,Lt,us,ey,ty,_f,Jp,Qp;function XR(e,t,r){e.rotation=t.rotation;let n=t.path;n?t.root||(t.root=Xp.dirname(n)):t.root?n=ta(t.root,eD):(n=Lt.path,t.root||(t.root=Xp.dirname(n))),n?e.path=n:console.error("No path for logger",t),e.level=nr[t.level]??Lt?.level??nr.info,QQ(e),e.logToStdstreams=t.stdStreams??!1,e.tag=t.tag??(Lt.path===e.path&&r)}o(XR,"updateLogger");function QQ(e){let t=e.conditional??(e.conditional={});t.notify=nr.notify>=e.level?e.notify.bind(e):void 0,t.fatal=nr.fatal>=e.level?e.fatal.bind(e):void 0,t.error=nr.error>=e.level?e.error.bind(e):void 0,t.warn=nr.warn>=e.level?e.warn.bind(e):void 0,t.info=nr.info>=e.level?e.info.bind(e):void 0,t.debug=nr.debug>=e.level?e.debug.bind(e):void 0,t.trace=nr.trace>=e.level?e.trace.bind(e):void 0}o(QQ,"updateConditional");async function tD(){Qp||(Qp=new KRe,await Qp.ready(),Qp.on("change",tD));let e=Qp.config,t=e.logging??{};XR(Lt,t),ZR=Lt.path,Zp=t.console??!1,t.external&&XR(us,t.external);for(let r in e){let n=e[r];n.logging?XR(Lt.forComponent(r),n.logging,r):Lt.hasComponent(r)&&XR(Lt.forComponent(r),t,r)}}o(tD,"updateLogSettings");var rD=class extends bRe{static{o(this,"HarperLogger")}constructor(t,r){t.stdout.removeListener=()=>{},t.stderr.removeListener=()=>{},t.stdout.listenerCount=()=>{},t.stderr.listenerCount=()=>{},super(t),this.level=r}trace(...t){gn="trace",this.level<=nr.trace&&super.info(...t),gn="info"}debug(...t){gn="debug",this.level<=nr.debug&&super.info(...t),gn="info"}info(...t){gn="info",this.level<=nr.info&&super.info(...t),gn="info"}warn(...t){gn="warn",this.level<=nr.warn&&super.warn(...t),gn="info"}error(...t){gn="error",this.level<=nr.error&&super.error(...t),gn="info"}fatal(...t){_f=!0;try{gn="fatal",this.level<=nr.fatal&&super.error(...t),gn="info"}finally{_f=!1}}notify(...t){_f=!0;try{gn="notify",this.level<=nr.notify&&super.info(...t),gn="info"}finally{_f=!1}}withTag(t){return XQ(t,!0,this)}forComponent(t){return this}hasComponent(t){return!1}};Jp===void 0&&JQ();sy.exports={notify:URe,fatal:xRe,error:sD,warn:BRe,info:DRe,debug:vRe,trace:MRe,logLevel:Zo,loggerWithTag:XQ,suppressLogging:PRe,initLogSettings:JQ,logCustomLevel:FRe,closeLogFile:ZQ,createLogger:ny,logsAtLevel:ORe,getLogFilePath:o(()=>ZR,"getLogFilePath"),forComponent:o(e=>Lt.forComponent(e),"forComponent"),setMainLogger:$Re,OUTPUTS:IRe,AuthAuditLog:VRe,start:tD,startOnMainThread:tD,errorToString:qRe};sy.exports.externalLogger={notify(...e){us.notify(...e)},fatal(...e){us.fatal(...e)},error(...e){us.error(...e)},warn(...e){us.warn(...e)},info(...e){us.info(...e)},debug(...e){us.debug(...e)},trace(...e){us.trace(...e)},withTag(e){return us.withTag(e)}};ARe("logger",sy.exports.externalLogger);function ORe(e){return nr[Zo]<=nr[e]}o(ORe,"logsAtLevel");function JQ(e=!1){try{if(Jp===void 0||e){ZQ();let t=HRe(),r=GQ(["ROOTPATH"]);try{Jp=jQ(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!ea.pathExistsSync(ta(r.ROOTPATH,Hr.HDB_CONFIG_FILE)))throw s}let n;if({level:Zo,configLogPath:ZL,toFile:eE,logConsole:Zp,rotation:n,toStream:JR}=kRe(r.ROOTPATH?ta(r.ROOTPATH,Hr.HDB_CONFIG_FILE):Jp.get("settings_path")),eD=Hr.LOG_NAMES.HDB,ZR=ta(ZL,eD),Lt=ny({path:ZR,level:Zo,stdStreams:JR,rotation:n}),us=Lt.forComponent("external"),us.tag=null,WQ)try{require("segfault-handler").registerHandler(ta(ZL,"crash.log"))}catch{}}}catch(t){if(Jp=void 0,t.code===Hr.NODE_ERROR_CODES.ENOENT||t.code===Hr.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=GQ(Object.keys(Hr.CONFIG_PARAM_MAP),!0);for(let s in r){let i=Hr.CONFIG_PARAM_MAP[s];i&&i.toLowerCase();let a=r[s];if(i===Hr.CONFIG_PARAMS.LOGGING_LEVEL){Zo=a;continue}i===Hr.CONFIG_PARAMS.LOGGING_CONSOLE&&(Zp=i)}let{defaultLevel:n}=GRe();eE=!1,JR=!0,Zo=Zo===void 0?n:Zo,Lt=ny({level:Zo}),us=Lt.forComponent("external"),us.tag=null;return}throw sD("Error initializing log settings"),sD(t),t}process.env.DEV_MODE&&(JR=!0),CRe()}o(JQ,"initLogSettings");var dc=!0;function CRe(){eE&&(process.stdout.write=function(e){return typeof e=="string"&&dc&&Zp&&(e=e.toString(),e[e.length-1]===`
34
+ `),Ip(e,404,0,e.requestId)}function Ip(e,t,r,n){let s=Np.logging;if(s){YP||(YP=Wo.default.forComponent("http"));let i=t<400?"info":t===500?"error":"warn";YP[i]?.(`${e.method} ${e.url} ${e.socket.encrypted?"HTTPS":"HTTP"}/${e.httpVersion}${s.headers?" "+Age(e.headers):""} ${t}${s.timing&&n?" "+n.toFixed(2)+"ms":""}${r?" id: "+r:""}`)}}function Age(e){let t=[];for(let r in e)t.push(`${r}: ${e[r]}`);return t.join(", ")}function Gj(){return bp||(bp=new BigInt64Array([1n]),bp=new BigInt64Array(databases.system.hdb_analytics.primaryStore.getUserSharedBuffer("next-request-id",bp.buffer))),Number(Atomics.add(bp,0,1n))}var Cj,Wo,tR,xr,Pj,Lj,Dj,Mj,vj,Uj,sR,WP,xj,Ege,Ap,eR,rR,zP,Np,_ge,Ij,Nj,jP,KP,wj,YP,bp,ZP=fe(()=>{Cj=require("node:net"),Wo=w(z()),tR=require("node:worker_threads"),xr=w(ce());k();Pj=w(At()),Lj=w(st()),Dj=w(es()),Mj=w(Ad()),vj=require("node:http2"),Uj=require("node:https"),sR=require("node:http");Km();Vm();Ss();Fi();WP=require("node:stream");Pr();VP();vd();xj=require("ws"),{errorToString:Ege}=Wo.default;ve.http=XP;ve.request=Rge;ve.ws=yge;ve.upgrade=kj;Ap={},eR={},rR={},zP=[],Np={},_ge=!0;o(gge,"handleApplication");o(Sge,"getHttpOptions");o(Bj,"deliverSocket");Ij=new Map;o(Tge,"proxyRequest");o(QP,"registerServer");o(JP,"getPorts");o(XP,"httpServer");o(Fj,"getHTTPServer");o(nR,"makeCallbackChain");o(Hj,"unhandled");o(Rge,"onRequest");Object.defineProperty(sR.IncomingMessage.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){}});Nj=[],jP={};o(kj,"onUpgrade");KP=[],wj={};o(yge,"onWebSocket");o(Oj,"defaultNotFound");o(Ip,"logRequest");o(Age,"headersToString");o(Gj,"getRequestId")});var Yh={};Ce(Yh,{componentErrors:()=>wp,getComponentName:()=>oR,loadComponent:()=>uR,loadComponentDirectories:()=>Vj,setErrorReporter:()=>Ige});function Vj(e,t){t&&(tL=t),e&&(iL=e);let r=[];if((0,Pt.existsSync)(eL)){let s=(0,Pt.readdirSync)(eL,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,Br.join)(eL,a);r.push(uR(c,tL,Cy,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(uR(n,tL,n,!1,void 0,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{$j=!0})}function Ige(e){cR=e}function Nge(e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{qo.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(qo.primaryStore.attemptLock(e,0,()=>{clearTimeout(s),r()}))try{(0,Pt.rmSync)(t,{recursive:!0,force:!0}),(0,Pt.existsSync)((0,Br.join)(e,"node_modules"))||(0,Pt.mkdirSync)((0,Br.join)(e,"node_modules")),(0,Pt.symlinkSync)(aL.PACKAGE_ROOT,t,"dir"),r()}finally{qo.primaryStore.unlock(e,0)}})}function Kj(e,t){return e.ready.then(()=>{let r=e.options.get(["timeout"])||t.defaultTimeout||3e4;if(typeof r!="number")throw new Error(`Invalid timeout value for ${e.name}. Expected a number, received: ${typeof r}`);let n,s;return qo.primaryStore.attemptLock(e.name,0,()=>{clearTimeout(s),n(Kj(e,t))})?Promise.race([t.handleApplication(e),new Promise((i,a)=>setTimeout(()=>a(new Error(`handleApplication timed out after ${r}ms for ${e.name}`)),r))]).finally(()=>{qo.primaryStore.unlock(e.name,0)}):new Promise((i,a)=>{n=i,s=setTimeout(()=>{a(new Error(`Timeout waiting for lock on ${e.name}`))},r+5e3)})})}async function uR(e,t,r,n,s,i){let a=(0,Pt.realpathSync)(e);if(aR.has(a))return aR.get(a);aR.set(a,!0),s&&(iL=s);try{let c;n&&(wp=new Map);let l=(0,Br.join)(e,"harperdb-config.yaml");(0,Pt.existsSync)(l)?c=n?(0,dR.getConfigObj)():(0,nL.parseDocument)((0,Pt.readFileSync)(l,"utf8")).toJSON():!n&&(0,Pt.existsSync)(l=(0,Br.join)(e,"config.yaml"))?c=(0,nL.parseDocument)((0,Pt.readFileSync)(l,"utf8")).toJSON():c=KT;try{let m=(0,Br.join)(e,"node_modules","harperdb");(n||((0,Pt.existsSync)(m)||!e.startsWith((0,sL.getHdbBasePath)()))&&(!(0,Pt.existsSync)(m)||(0,Pt.realpathSync)(aL.PACKAGE_ROOT)!==(0,Pt.realpathSync)(m)))&&await Nge(e,m)}catch(m){zo.default.error("Error symlinking harperdb module",m),m.code=="EPERM"&&process.platform==="win32"&&zo.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=lR,d={};for(let m in c){lR=m;let h=c[m];if(wp.set(n?m:(0,Br.basename)(e),!1),!h)continue;let p,_=h.package;try{if(_){let I=e,P;for(;!(0,Pt.existsSync)(P=(0,Br.join)(I,"node_modules",m));)if(I=(0,Br.dirname)(I),I.length<(0,sL.getHdbBasePath)().length){P=null;break}if(P)p=await uR(P,t,r,!1),d[m]=!0;else throw new Error(`Unable to find package ${m}:${_}`)}else p=bge[m];if(!p)continue;let g=o(I=>(I.origin=r,Ze(I)),"ensureTable"),y=h.network||(h.port||h.securePort)&&h,T=y?.securePort||y?.https&&y.port,R=!y?.https&&y?.port;if("handleApplication"in p&&("start"in p||"startOnMainThread"in p||"handleFile"in p||"handleDirectory"in p||"setupFile"in p||"setupDirectory"in p))throw new Error(`Component ${m} has both 'handleComponent' and 'start' or 'startOnMainThread' methods. Please use only one of them.`);if(t.isWorker&&p.handleApplication){p.suppressHandleApplicationWarning!==!0&&zo.default.warn(`Plugin ${m} is using the experimental handleApplication API`);let I=new jT(m,e,l,t,ve);await Kj(I,p);continue}if(rL.isMainThread&&(p=await p.startOnMainThread?.({server:ve,ensureTable:g,port:R,securePort:T,resources:t,...h})||p,n&&y))for(let I of[R,T])try{if(+I&&!qj.includes(I)){let P=oL.get(U.HTTP_SESSIONAFFINITY);P&&zo.default.warn("Session affinity is not recommended and may cause memory leaks"),(P||!eg)&&(qj.push(I),iP(I,P))}}catch(P){console.error("Error listening on socket",I,P,m)}if(t.isWorker&&(p=await p.start?.({server:ve,ensureTable:g,port:R,securePort:T,resources:t,...h})||p),iL.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&h.files!=null){let I=new XT({config:h,name:m,directory:e,module:p,resources:t});d[m]=await yj(I)}}catch(g){g.message=`Could not load component '${m}' for application '${(0,Br.basename)(e)}' due to: ${g.message}`,cR?.(g),((0,Op.getWorkerIndex)()===0?console:zo.default).error(g),t.set(h.path||"/",new Hc(g),null,!0),wp.set(n?m:(0,Br.basename)(e),g.message)}}if(lR=u,rL.isMainThread&&!$j&&i&&(0,Op.watchDir)(e,async()=>Vj()),c.extensionModule||c.pluginModule){let m=await Y_((0,Br.join)(e,c.extensionModule||c.pluginModule));return aR.set(a,m),m}let f=Object.values(d);if(f.length>0&&f.every(m=>!m)&&t.isWorker){let m=`${e} did not load any modules, resources, or files, is this a valid component?`;cR?.(new Error(m)),((0,Op.getWorkerIndex)()===0?console:zo.default).error(m),wp.set((0,Br.basename)(e),m)}for(let[m,h]of Object.entries(d))h||zo.default.warn(`Component ${m} from (${(0,Br.basename)(e)}) did not load any functionality.`)}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,cR?.(c),t.set("",new Hc(c))}}var Pt,Br,rL,nL,oL,aL,zo,Op,sL,dR,eL,iL,$j,tL,wp,bge,qj,aR,cR,lR,oR,vd=fe(()=>{Pt=require("node:fs"),Br=require("node:path"),rL=require("node:worker_threads"),nL=require("yaml"),oL=w(ce()),aL=w(Rt());k();qM();Cv();XF();sH();iH();KH();VW();QW();XW();zo=w(z());sz();Op=w(st());OI();Pr();Le();aP();sL=w(ce());wz();BS();Uz();Xn();jz();dR=w(At());Km();mA();_j();Aj();ZP();Zh();wP();eL=(0,dR.resolvePath)(oL.get(U.COMPONENTSROOT)),iL=new Map,wp=new Map;o(Vj,"loadComponentDirectories");bge={REST:ng,rest:ng,graphql:pA,graphqlSchema:Jy,roles:wI,jsResource:CI,fastifyRoutes:JC,login:LI,static:XC,operationsApi:lP,customFunctions:{},http:iR,clustering:pP,replication:Po,authentication:Hh,mqtt:TP,loadEnv:ZC,logging:zo.default,dataLoader:eP},qj=[],aR=new Map;o(Ige,"setErrorReporter");oR=o(()=>lR,"getComponentName");o(Nge,"symlinkHarperModule");o(Kj,"sequentiallyHandleApplication");o(uR,"loadComponent")});var DT=M((aBe,Wj)=>{var{isMainThread:Yj}=require("worker_threads"),{getTables:wge,getDatabases:iBe,table:oBe}=(Le(),v(ft)),{loadComponentDirectories:Oge,loadComponent:Cge}=(vd(),v(Yh)),{resetResources:Pge}=(_u(),v(Sv)),Lge=DO(),Dge=At(),{dirname:Mge}=require("path"),{getConnection:vge}=lr(),Uge=ce(),{CONFIG_PARAMS:xge}=(k(),v(K)),{loadCertificates:Bge}=es(),cL=new Map;async function Fge(e=!1){!Yj&&Uge.get(xge.CLUSTERING_ENABLED)&&vge();try{Yj&&await Lge()}catch(n){console.error(n)}let t=Pge();wge(),t.isWorker=e,await Bge(),await Cge(Mge(Dge.getConfigFilePath()),t,"hdb",!0,cL),await Oge(cL,t);let r=[];for(let[n]of cL)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}o(Fge,"loadRootComponents");Wj.exports.loadRootComponents=Fge});var st=M((lBe,Si)=>{"use strict";wy();var{Worker:Hge,MessageChannel:kge,parentPort:ji,isMainThread:mL,threadId:Gge,workerData:Qi}=require("worker_threads"),{PACKAGE_ROOT:qge}=Rt(),{join:Jj,isAbsolute:$ge,extname:Vge}=require("path"),{server:Xj}=(Pr(),v(Kf)),{watch:Kge,readdir:Yge}=require("fs/promises"),{totalmem:zj}=require("os"),Xd=(k(),v(K)),Zj=ce(),gi=z(),{randomBytes:Wge}=require("crypto"),{_assignPackageExport:zge}=Ws(),jj=1024*1024,nc=[],Fs=[],jge=50,hL=1e4,Qge="restart",e2="request_thread_info",t2="resource_report",r2="thread_info",n2="added-port",Jge="ack",lL;zge("threads",Fs);Si.exports={startWorker:uL,restartWorkers:EL,shutdownWorkers:rSe,workers:nc,setMonitorListener:uSe,onMessageFromWorkers:nSe,onMessageByType:u2,broadcast:iSe,broadcastWithAcknowledgement:aSe,setChildListenerByType:tSe,getWorkerIndex:s2,getWorkerCount:i2,getTicketKeys:a2,setMainIsWorker:Zge,setTerminateTimeout:Xge,restartNumber:Qi?.restartNumber||1};Fs.onMessageByType=u2;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};Si.exports.whenThreadsStarted=new Promise(e=>{Si.exports.threadsHaveStarted=e});var pL;function Xge(e){hL=e}o(Xge,"setTerminateTimeout");function s2(){return Qi?Qi.workerIndex:pL?0:void 0}o(s2,"getWorkerIndex");function i2(){return Qi?Qi.workerCount:pL?1:void 0}o(i2,"getWorkerCount");function Zge(e){pL=e,Si.exports.threadsHaveStarted()}o(Zge,"setMainIsWorker");var o2=1,fR;function a2(){return fR||(fR=mL?Wge(48):Qi.ticketKeys,fR)}o(a2,"getTicketKeys");Object.defineProperty(Xj,"workerIndex",{get(){return s2()}});Object.defineProperty(Xj,"workerCount",{get(){return i2()}});var c2={[e2](e,t){cSe(t)},[t2](e,t){lSe(t,e)}};function uL(e,t={}){let r=process.constrainedMemory?.()||zj();r=Math.min(r,zj(),2e4*jj);let n=Zj.get(Xd.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/jj/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],a=[];for(let l of Fs){let u=new kge;u.existingPort=l,i.push(u),a.push(u.port2)}Vge(e)||(e+=".js");let c=new Hge($ge(e)?e:Jj(qge,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:a,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:o2=t.threadCount,name:t.name,restartNumber:Si.exports.restartNumber,ticketKeys:a2()},transferList:a,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:n2,port:l,threadId:c.threadId},[l]);return hR(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>uL(e,t),c.on("error",l=>{gi.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{nc.splice(nc.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<jge?(t.unexpectedRestarts=c.unexpectedRestarts+1,uL(e,t)):gi.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{c2[l.type]?.(l,c)}),nc.push(c),fSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}o(uL,"startWorker");var eSe=[Xd.THREAD_TYPES.HTTP];async function EL(e=null,t=Math.max(o2>3,1),r=!0){if(mL){try{process.chdir(process.cwd())}catch(a){gi.error("Unable to reestablish current working directory",a)}if(r){let{loadRootComponents:a}=DT();await a()}Si.exports.restartNumber++,t<1&&(t=t*nc.length);let n=[],s=[];for(let a of nc.slice(0)){if(e&&a.name!==e||a.wasShutdown)continue;gi.trace("sending shutdown request to ",a.threadId),a.postMessage({restartNumber:Si.exports.restartNumber,type:Xd.ITC_EVENT_TYPES.SHUTDOWN}),a.wasShutdown=!0,a.emit("shutdown",{});let c=eSe.indexOf(a.name)>-1,l=new Promise(u=>{let d=setTimeout(()=>{gi.warn("Thread did not voluntarily terminate, terminating from the outside",a.threadId),a.terminate()},hL*2).unref();a.on("exit",()=>{clearTimeout(d),n.splice(n.indexOf(l)),!c&&r&&a.startCopy(),u()})});if(n.push(l),c&&r){let u=a.startCopy(),d=new Promise(f=>{let m=o(h=>{h.type===Xd.ITC_EVENT_TYPES.CHILD_STARTED&&(gi.trace("Worker has started",u.threadId),f(),s.splice(s.indexOf(d)),u.off("message",m))},"startListener");gi.trace("Waiting for worker to start",u.threadId),u.on("message",m)});s.push(d),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}=Pd();r&&(e==="http"||!e)&&Zj.get(Xd.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ji.postMessage({type:Qge,workerType:e})}o(EL,"restartWorkers");function tSe(e,t){c2[e]=t}o(tSe,"setChildListenerByType");function rSe(e){return EL(e,1/0,!1)}o(rSe,"shutdownWorkers");var l2=[];function nSe(e){l2.push(e)}o(nSe,"onMessageFromWorkers");var dL=new Map;function u2(e,t){let r=dL.get(e);r||dL.set(e,r=[]),r.push(t)}o(u2,"onMessageByType");var sSe=10;async function iSe(e,t){let r=0;for(let n of Fs)try{n.postMessage(e),r++>sSe&&(r=0,await new Promise(setImmediate))}catch(s){gi.error("Unable to send message to worker",s)}t&&f2(e,null)}o(iSe,"broadcast");var mR=new Map,oSe=1;function aSe(e){return new Promise(t=>{let r=0;for(let n of Fs)try{let s=oSe++,i=o(()=>{mR.delete(s),--r===0&&t(),n!==ji&&--n.refCount===0&&n.unref()},"ackHandler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,mR.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,a]of mR)a.port===n&&a()})),n.postMessage(e),r++}catch(s){gi.error("Unable to send message to worker",s)}r===0&&t()})}o(aSe,"broadcastWithAcknowledgement");function cSe(e){e.postMessage({type:r2,workers:d2()})}o(cSe,"sendThreadInfo");function d2(){let e=Date.now();return nc.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}))}o(d2,"getChildWorkerInfo");function lSe(e,t){e.resources=t,e.resources.updated=Date.now()}o(lSe,"recordResourceReport");var fL;function uSe(e){fL=e}o(uSe,"setMonitorListener");var dSe=1e3,Qj=!1;function fSe(){Qj||(Qj=!0,setInterval(()=>{for(let e of nc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}fL&&fL()},dSe).unref())}o(fSe,"startMonitoring");var mSe=1e3;if(ji&&Qi?.addPorts){hR(ji);for(let e=0,t=Qi.addPorts.length;e<t;e++){let r=Qi.addPorts[e];r.threadId=Qi.addThreadIds[e],hR(r)}setInterval(()=>{let e=process.memoryUsage();ji.postMessage({type:t2,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},mSe).unref(),lL=o(()=>new Promise((e,t)=>{ji.on("message",r),ji.postMessage({type:e2});function r(n){n.type===r2&&(ji.off("message",r),e(n.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else lL=d2;Si.exports.getThreadInfo=lL;function hR(e,t){Fs.push(e),e.on("message",r=>{if(r.type===n2)r.port.threadId=r.threadId,hR(r.port);else if(r.type===Jge){let n=mR.get(r.id);n&&n()}else f2(r,e)}).on("close",()=>{Fs.splice(Fs.indexOf(e),1)}).on("exit",()=>{Fs.splice(Fs.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(hR,"addPort");function f2(e,t){for(let n of l2)n(e,t);let r=dL.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){gi.error(s)}}o(f2,"notifyMessageListeners");if(mL){let e,t,r=new Set,n=o(async(s,i)=>{i&&(e=i);for(let a of await Yge(s,{withFileTypes:!0}))a.isDirectory()&&a.name!=="node_modules"&&n(Jj(s,a.name));try{for await(let{filename:a}of Kge(s,{persistent:!1}))r.add(a),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await EL(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(a){console.warn("Error trying to watch component directory",s,a)}},"watchDir");Si.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ji.on("message",async e=>{let{type:t}=e;t===Xd.ITC_EVENT_TYPES.SHUTDOWN&&(Si.exports.restartNumber=e.restartNumber,ji.unref(),setTimeout(()=>{gi.warn("Thread did not voluntarily terminate",Gge),process.exit(0)},hL).unref())})});var _2={};Ce(_2,{onStorageReclamation:()=>Cp,runReclamationHandlers:()=>TL,setAvailableSpaceRatioGetter:()=>pSe});function Cp(e,t,r){(r||(0,ER.getWorkerIndex)()===(0,ER.getWorkerCount)()-1)&&(pR.has(e)||pR.set(e,[]),pR.get(e).push({priority:0,handler:t}),SL||(SL=setTimeout(TL,h2).unref()))}async function TL(){for(let[e,t]of pR)try{let r=await E2(e),n=hSe/r;for(let s of t){let{priority:i,handler:a}=s;if(s.priority=n,n>1||i>1){let c=a(n>1?n:0);c&&(gL.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){gL.default.error?.("Error running storage reclamation handlers",r)}SL=setTimeout(TL,h2).unref()}function pSe(e){E2=e??p2}var _L,ER,gL,_R,m2,pR,hSe,h2,SL,p2,E2,gR=fe(()=>{_L=require("node:fs/promises"),ER=w(st()),gL=w(Ii());k();_R=w(ce()),m2=w(ie());_R.default.initSync();pR=new Map,hSe=_R.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,h2=(0,m2.convertToMS)(_R.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;o(Cp,"onStorageReclamation");p2=o(async e=>{if(_L.statfs){let t=await(0,_L.statfs)(e);return t.bavail/t.blocks}else return new Promise((t,r)=>{import("hdd-space").then(n=>{n.default(s=>{for(let i of s.parts)if(e.startsWith(i.place))return t(i.free/i.size);return t(1)})})})},"defaultGetAvailableSpaceRatio"),E2=p2;o(TL,"runReclamationHandlers");o(pSe,"setAvailableSpaceRatioGetter")});var pF={};Ce(pF,{ACTION_32_BIT:()=>AR,ACTION_64_BIT:()=>gSe,AUDIT_STORE_OPTIONS:()=>vh,Decoder:()=>Tl,HAS_BLOBS:()=>Dn,HAS_CURRENT_RESIDENCY_ID:()=>gl,HAS_EXPIRATION_EXTENDED_TYPE:()=>vp,HAS_ORIGINATING_OPERATION:()=>Mp,HAS_PREVIOUS_RESIDENCY_ID:()=>Sl,REMOTE_SEQUENCE_UPDATE:()=>Fg,createAuditEntry:()=>od,getLastRemoved:()=>ew,openAuditStore:()=>RR,readAuditEntry:()=>Ut,removeAuditEntry:()=>yR,setAuditRetention:()=>_Se,transactionKeyEncoder:()=>N2});function RR(e){let t=e.auditStore=e.openDB(RL.AUDIT_STORE_NAME,{create:!1,...vh});t||(t=e.auditStore=e.openDB(RL.AUDIT_STORE_NAME,vh),S2(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,d){return r[l]=d,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,a=AL;Cp(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(a=l),clearTimeout(n);let u=new Promise(d=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let f=0,m,h;try{for(let{key:p,value:_}of t.getRange({start:1,snapshot:!1,end:Date.now()-yL/(1+i*i)})){try{m=yR(t,p,_)}catch(g){Zd.warn("Error removing audit entry",g)}if(h=p,await new Promise(setImmediate),++f>=ESe){a=10;break}}await m}finally{f===0?a=Math.min(a<<1,yL/10):(S2(t,h),a>100&&(a=a>>1)),d(void 0),c()}},a).unref()});return u}if(o(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,Lp.getWorkerIndex)()===(0,Lp.getWorkerCount)()-1&&c(),(0,Lp.getWorkerIndex)()===0&&!g2)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(g2=!0,Zd.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 yR(e,t,r){let n=SSe(r),s;if(n&Dn){s=Ut(r);let i=e.tableStores[s.tableId],a=i?.getEntry(s.recordId);(!a||a.version!==s.version||!a.value)&&xc(()=>Ea(s.getValue(i)),i.rootStore)}if((n&15)===bL){s=s||Ut(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 S2(e,t){IL[0]=t,e.put(Symbol.for("last-removed"),w2)}function ew(e){let t=e.get(Symbol.for("last-removed"));if(t)return w2.set(t),IL[0]}function _Se(e,t=AL){yL=e,AL=t}function od(e,t,r,n,s,i,a,c,l,u,d,f,m){let h=O2[a];if(!h)throw new Error(`Invalid audit entry type ${a}`);let p=1;if(n&&(n>1?sc.setFloat64(0,n):Hs.set(NL),p=9),l){if(l&255)throw new Error("Illegal extended type");p+=3}y(s),y(t),g(r),sc.setFloat64(p,e),p+=8,l&gl&&y(u),l&Sl&&y(d),l&vp&&(sc.setFloat64(p,f),p+=8),l&Mp&&y(C2[m]),i?g(i):Hs[p++]=0,l?sc.setUint32(n?8:0,h|l|3221225472):Hs[n?8:0]=h;let _=Hs.subarray(0,p);if(c)return Buffer.concat([_,c]);return _;function g(T){let R=p;p+=1,p=(0,Vl.writeKey)(T,Hs,p);let I=p-R-1;I>127?I>16383?(Zd.error("Key or username was too large for audit entry",T),p=R+1,Hs[R]=0):(Hs.copyWithin(R+2,R+1,p),sc.setUint16(R,I|32768),p++):Hs[R]=I}function y(T){T<128?Hs[p++]=T:T<16384?(sc.setUint16(p,T|32768),p+=2):T<1056964608?(sc.setUint32(p,T|3221225472),p+=4):(Hs[p]=255,sc.setUint32(p+1,T),p+=5)}}function SSe(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 Tl(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Ut(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Tl(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),a=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,d=n.position+=l,f=n.readFloat64(),m,h,p,_;if(i&gl&&(m=n.readInt()),i&Sl&&(h=n.readInt()),i&vp&&(p=n.readFloat64()),i&Mp){let R=n.readInt();_=C2[R]}l=n.readInt();let g=n.position,y=n.position+=l,T;return{type:O2[i&7],tableId:c,nodeId:a,get recordId(){return(0,Vl.readKey)(e,u,d)},getBinaryRecordId(){return e.subarray(u,d)},version:f,previousLocalTime:s,get user(){return y>g?(0,Vl.readKey)(e,g,y):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(R,I,P){if(i&SR||i&Pp&&!I)return T||(T=xc(()=>R.decoder.decode(e.subarray(n.position,r)),R.rootStore)),T;if(i&Pp&&P)return fI(R.getEntry(this.recordId),P,R)},getBinaryValue(){return i&(SR|Pp)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:m,previousResidencyId:h,expiresAt:p,originatingOperation:_}}catch(n){return Zd.error("Reading audit entry error",n,e),{}}}var Vl,TR,RL,Lp,I2,Zd,Hs,sc,N2,vh,yL,ESe,IL,w2,AL,g2,SR,Pp,T2,bL,R2,y2,A2,b2,AR,gSe,Fg,gl,Sl,Mp,vp,Dn,O2,C2,Tl,Io=fe(()=>{Vl=require("ordered-binary"),TR=w(ce()),RL=w(kt());k();Lp=w(st()),I2=w(ie());kc();Zd=w(z());U_();Ss();gR();(0,TR.initSync)();Hs=Buffer.alloc(2816),sc=new DataView(Hs.buffer,Hs.byteOffset,2816),N2={writeKey(e,t,r){return e===Dp?(t.set(Dp,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Vl.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,Vl.readKey)(e,t,r)}},vh={encoding:"binary",keyEncoder:N2},yL=(0,I2.convertToMS)((0,TR.get)(U.LOGGING_AUDITRETENTION))||86400*3,ESe=1e3,IL=new Float64Array(1),w2=new Uint8Array(IL.buffer),AL=1e4,g2=!1;o(RR,"openAuditStore");o(yR,"removeAuditEntry");o(S2,"updateLastRemoved");o(ew,"getLastRemoved");o(_Se,"setAuditRetention");SR=16,Pp=32,T2=1,bL=2,R2=3,y2=4,A2=5,b2=6,AR=14,gSe=15,Fg=11,gl=512,Sl=1024,Mp=2048,vp=4096,Dn=8192,O2={put:T2|SR,[T2]:"put",delete:bL,[bL]:"delete",message:R2|SR,[R2]:"message",invalidate:y2|Pp,[y2]:"invalidate",patch:A2|Pp,[A2]:"patch",relocate:b2,[b2]:"relocate"},C2={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};o(od,"createAuditEntry");o(SSe,"readAction");o(Ut,"readAuditEntry");Tl=class extends DataView{static{o(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}}}});var Gv={};Ce(Gv,{ENTRY:()=>RSe,HAS_EXPIRATION:()=>NR,HAS_RESIDENCY_ID:()=>DL,HAS_STRUCTURE_UPDATE:()=>qg,LAST_TIMESTAMP_PLACEHOLDER:()=>Dp,LOCAL_TIMESTAMP:()=>TSe,METADATA:()=>ad,NEW_TIMESTAMP_PLACEHOLDER:()=>L2,NO_TIMESTAMP:()=>wL,PENDING_LOCAL_TIME:()=>ML,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>NL,RecordEncoder:()=>LL,TIMESTAMP_ASSIGN_LAST:()=>ASe,TIMESTAMP_ASSIGN_NEW:()=>D2,TIMESTAMP_ASSIGN_PREVIOUS:()=>M2,TIMESTAMP_PLACEHOLDER:()=>bR,TIMESTAMP_RECORD_PREVIOUS:()=>OL,entryMap:()=>ic,handleLocalTimeForGets:()=>wR,lastMetadata:()=>ct,recordUpdater:()=>vL,removeEntry:()=>Yl});function ISe(){return Bp[0]=Bp[0]^64,ySe.getFloat64(0)}function wR(e,t){let r=e.getEntry;e.readCount=0,e.cachePuts=!1,e.rootStore=t,e.encoder.rootStore=t,e.getEntry=function(a,c){e.readCount++,ct=null;let l=r.call(this,a,c);return l&&(ct&&(l.metadataFlags=ct[ad],l.localTime=ct.localTime,l.residencyId=ct.residencyId,ct.expiresAt>=0&&(l.expiresAt=ct.expiresAt),ct=null),l.value&&ic.set(l.value,l),l.key=a),l};let n=e.get;e.get=function(a,c){ct=null;let l=n.call(this,a,c);return ct&&l&&(ic.set(l,ct),ct=null),l};let s=e.getRange;e.getRange=function(a){let c=s.call(this,a);return a.valuesForKey?c.map(l=>l?.value):a.values===!1||a.onlyCount?c:c.map(l=>(ct&&(l.metadataFlags=ct[ad],l.localTime=ct.localTime,l.residencyId=ct.residencyId,ct.expiresAt>=0&&(l.expiresAt=ct.expiresAt),ct=null),l))};let i=e.useReadTransaction();if(i.done(),!i.done.isTracked){let a=i.constructor,c=i.use,l=i.done;a.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Kl.push(new WeakRef(this))),c.call(this)},a.prototype.done=function(){if(l.call(this),this.isDone)for(let u=0;u<Kl.length;u++){let d=Kl[u].deref();(!d||d.isDone||d.isCommitted)&&Kl.splice(u--,1)}},a.prototype.done.isTracked=!0}return e}function vL(e,t,r){return function(n,s,i,a,c=-1,l,u,d="put",f,m){f||l==null?ef=i?.localTime?OL|M2:wL:ef=l?i?.localTime?OL|16384:D2|16384:wL;let h=u?.expiresAt;if(h>=0&&(c|=NR),xp=c,CL=h,i?.version===a&&l===!1)throw new Error("Must retain local time if version is not changed");let p={version:a,instructedWrite:ef>0},_,g=0;try{let y=i?.residencyId,T=u?.residencyId;T&&(PL=T,xp|=DL,g|=gl),y!==T&&(g|=Sl,y||(y=0)),c&NR&&(g|=vp),u?.originatingOperation&&(g|=Mp),f&&(p.ifVersion=_=i?.version??null),i&&i.value&&i.metadataFlags&Dn&&(r.getBinaryFast(i.localTime)||Ea(i.value));let R;if(s!==void 0&&(R=$E(()=>e.put(n,s,p),n,e.rootStore),Uc&&(g|=Dn)),l){let I=u?.user?.username;if(m&&($E(()=>e.encoder.encode(m),n,e.rootStore),Uc&&(g|=Dn)),e.encoder.hasStructureUpdate&&(g|=qg,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let P=i?.localTime,Y=r.get(P);if(Y){let te=Ut(Y).previousLocalTime;return R=r.put(P,od(a,t,n,te,u?.nodeId??server.replication.getThisNodeId(r)??0,I,d,Up,g,T,y,h),{ifVersion:_}),R}}R=r.put(s===void 0?L2:Dp,od(a,t,n,i?.localTime?1:0,u?.nodeId??server.replication?.getThisNodeId(r)??0,I,d,Up,g,T,y,h,u?.originatingOperation),{append:d!=="invalidate",instructedWrite:!0,ifVersion:_})}return R}catch(y){throw y.message+=" id: "+n+" options: "+p,y}}}function Yl(e,t,r){if(t)return t.value&&t.metadataFlags&Dn&&!e.auditStore.getBinaryFast(t.localTime)&&Ea(t.value),e.remove(t.key,r)}var P2,IR,bR,Dp,NL,L2,TSe,ad,RSe,Bp,ySe,wL,D2,ASe,M2,OL,NR,DL,ML,qg,ic,bSe,Up,ef,xp,CL,PL,ct,LL,Kl,kc=fe(()=>{P2=require("msgpackr");Io();IR=w(z());Ss();Ss();bR=new Uint8Array([1,1,1,1,4,64,0,0]),Dp=new Uint8Array([1,1,1,1,1,0,0,0]),NL=new Uint8Array([1,1,1,1,3,64,0,0]),L2=new Uint8Array([1,1,1,1,0,64,0,0]),TSe=Symbol("local-timestamp"),ad=Symbol("metadata"),RSe=Symbol("entry"),Bp=new Uint8Array(8),ySe=new DataView(Bp.buffer,0,8),wL=0,D2=0,ASe=1,M2=3,OL=4,NR=16,DL=32,ML=1,qg=256,ic=new WeakMap,ef=0,xp=-1,CL=-1,PL=0,ct=null,LL=class extends P2.Encoder{static{o(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0;class r{static{o(this,"RecordObject")}getUpdatedTime(){return ic.get(this)?.version}getExpiresAt(){return ic.get(this)?.expiresAt}}t.structPrototype=r.prototype,super(t);let n=this.encode;this.encode=function(i,a){if(ef||xp>=0){let c=0,l=ef;l&&(c+=8,ef=0);let u=xp,d=CL,f=PL;u>=0&&(c+=4,xp=-1,d>=0&&(c+=8,CL=-1),f&&(c+=4,PL=0));let m=bSe=n.call(this,i,a|2048|c);Up=m.subarray((m.start||0)+c,m.end);let h=m.start||0;return l&&(bR[4]=l,bR[5]=l>>8,m.set(bR,h),h+=8),Uc&&(u|=Dn),u>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,u|AR<<24),h+=4,d>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setFloat64(h,d),h+=8),f&&(m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,f)),m}else return Up=n.call(this,i,a),Up};let s=this.saveStructures;this.saveStructures=function(i,a){let c=s.call(this,i,a);return this.hasStructureUpdate=!0,c}}decode(t,r){ct=null;let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],a=0;try{if(i<32&&s>2){let c=n,l;if(i===2){if(t.copy)t.copy(Bp,0,c),c+=8;else for(let m=0;m<8;m++)Bp[m]=t[c++];l=ISe(),i=t[c]}let u,d;i<32&&(i===AR?(a=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4):(a=i|t[c+1]<<5,c+=2),a&NR&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),a&DL&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=xc(()=>r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c),this.rootStore);return ct={localTime:l,[ad]:a,expiresAt:u,residencyId:d},f}return r?.valueAsBuffer?t:xc(()=>super.decode(t,r),this.rootStore)}catch(c){return IR.error("Error decoding record",c,"data: "+t.slice(0,40).toString("hex")),null}}};o(ISe,"getTimestamp");o(wR,"handleLocalTimeForGets");Kl=[];setInterval(()=>{for(let e=0;e<Kl.length;e++){let t=Kl[e].deref();!t||t.isDone||t.isCommitted?Kl.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(IR.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):IR.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();o(vL,"recordUpdater");o(Yl,"removeEntry")});function BL(e,t,r,n,s,i,a,c){let l=e[0];if(t==="or"){let f=u(l);for(let h=1;h<e.length;h++){let p=e[h],_=u(p);f=f.concat(_)}let m=new Set;return f.filter(h=>{let p=h.key??h;return m.has(p)?!1:(m.add(p),!0)})}else{let f=u(l),m=d(e.slice(1),!0,l.estimated_count);return m.length>0?a(f,m):f}function u(f){return f.conditions?BL(f.conditions,f.operator,r,n,s,i,a,c):sf(f,n,f.descending||s.reverse===!0,r,s.allowFullScan,c,i)}o(u,"executeCondition");function d(f,m,h){return f.map((p,_)=>{if(p.conditions){let T=p.operator==="or",R=d(p.conditions,!T,h);return T?(I,P)=>R.some(Y=>Y(I,P)):(I,P)=>R.every(Y=>Y(I,P))}let g=(p.attribute||p[0])===r.primaryKey,y=Hp(p,r,i,c,g,h);return m&&_<f.length-1&&h&&(h=vSe(r.primaryStore,p.estimated_count,h)),y}).filter(Boolean)}o(d,"mapConditionsToFilters")}function sf(e,t,r,n,s,i,a){let c=e[0]??e.attribute,l=e[1]??e.value,u=e.comparator;if(l===void 0&&u!=="sort")throw new Qr.ClientError(`Search condition for ${c} must have a value`);if(Array.isArray(c)){let R=c[0],I=Xi(n.attributes,R);if(I.relationship){if(c.length<2)throw new Qr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let P=I.definition?.tableClass||I.elements?.definition?.tableClass,Y=new Map,te=sf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:u},t,r,P,s,Y);if(I.relationship.to){i[c[0]]=Y;let x=!!Xi(P.attributes,I.relationship.to)?.elements;te=PSe(te,I,P.primaryStore,x,Y)}if(I.relationship.from){let x=o($=>($?.key!==void 0&&($=$.key),sf({attribute:I.relationship.from,value:$},t,r,n,s,Y)),"searchEntry");I.elements?(i[c[0]]=Y,te=LSe(te,I,P.primaryStore,Y,x)):te=te.flatMap(x)}return te}else if(c.length===1)c=c[0];else throw new Qr.ClientError("Unable to query by attribute "+JSON.stringify(c))}let d=c===n.primaryKey||c==null,f=d?n.primaryStore:n.indices[c],m,h,p,_;l instanceof Date&&(l=l.getTime());let g;switch(FL[u]||u){case"lt":m=!0,h=l;break;case"le":m=!0,h=l,p=!0;break;case"gt":m=l,_=!0;break;case"ge":m=l;break;case"prefix":Array.isArray(l)?l[l.length-1]!=null&&(l=l.concat(null)):l=[l,null],m=l,h=l.slice(0),h[h.length-1]=Ji.MAXIMUM_KEY;break;case"starts_with":m=l.toString(),h=l+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":m=l[0],m instanceof Date&&(m=m.getTime()),h=l[1],h instanceof Date&&(h=h.getTime()),p=u==="gele"||u==="gtle"||u==="between",_=u==="gtlt"||u==="gtle";break;case"equals":case void 0:m=l,h=l,p=!0;break;case"ne":if(l===null){m=l,_=!0;break}case"sort":case"contains":case"ends_with":m=!0,g=!0;break;default:throw new Qr.ClientError(`Unknown query comparator "${u}"`)}let y;if(typeof m=="string"&&m.length>ks.MAX_SEARCH_KEY_LENGTH&&(m=m.slice(0,ks.MAX_SEARCH_KEY_LENGTH)+ks.OVERFLOW_MARKER,_=!1,y=Hp(e,n,null,i,d)),typeof h=="string"&&h.length>ks.MAX_SEARCH_KEY_LENGTH&&(h=h.slice(0,ks.MAX_SEARCH_KEY_LENGTH)+ks.OVERFLOW_MARKER,p=!0,y=y??Hp(e,n,null,i,d)),r){let R=m;m=h,h=R,R=!_,_=!p,p=R}if(!f||f.isIndexing||g||l===null&&!f.indexNulls){if(s===!1&&!f)throw new Qr.ClientError(`"${c}" is not indexed, can not search for this attribute`,404);if(s===!1&&g)throw new Qr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${c}`,403);if(f?.isIndexing)throw new Qr.ServerError(`"${c}" is not indexed yet, can not search for this attribute`,503);if(l===null&&f&&!f.indexNulls)throw new Qr.ClientError(`"${c}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(y=y??Hp(e,n,null,i,d),!y)throw new Qr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:m,end:h,inclusiveEnd:p,exclusiveStart:_,values:!0,versions:d,transaction:t,reverse:r};if(d){let R=f.getRange(T).map(y?function({key:I,value:P}){return this?.isSync?P&&y(P)?I:oc.SKIP:new Promise((Y,te)=>setImmediate(()=>{try{Y(P&&y(P)?I:oc.SKIP)}catch(x){te(x)}}))}:I=>I.value==null&&!(I.metadataFlags&(Fn|ac))?oc.SKIP:I);return R.hasEntries=!0,R}else return f?f.customIndex?f.customIndex.search(e,a).map(R=>{if(typeof R=="object"&&R){let{key:I,...P}=R,Y=n.primaryStore.getEntry(I);return{...P,...Y}}return R}):f.getRange(T).map(y?function({key:R,value:I}){let P;return typeof R=="string"&&R.length>ks.MAX_SEARCH_KEY_LENGTH?P=n.primaryStore.get(I):P={[c]:R},this.isSync?y(P)?I:oc.SKIP:new Promise((Y,te)=>setImmediate(()=>{try{Y(y(P)?I:oc.SKIP)}catch(x){te(x)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:I}){return this.isSync?I&&y(I)?R:oc.SKIP:new Promise((P,Y)=>setImmediate(()=>{try{P(I&&y(I)?R:oc.SKIP)}catch(te){Y(te)}}))})}function Xi(e,t){if(Array.isArray(t))if(t.length>1){let r=Xi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Xi(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 PSe(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=o((u,d)=>{let f=s.get(u);f?f.push(d):s.set(u,f=[d])},"addEntry");for(let u of e){let d=u.value??r.get(u.key??u),f=d?.[c];if(f!=null&&!s.filters?.some(m=>!m(d)))if(n)for(let m=0;m<f.length;m++)l(f[m],u);else l(f,u)}return i=s.keys()[Symbol.iterator](),this.next()}let a=i.next();return a.done?a:{value:a.value}},return(){if(i?.return)return i.return()}}}})}function LSe(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,a,c=new Set;return{next(){let l;if(a)for(;l=a.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>u.has(f));for(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(m=>!m(f)))continue}u.add(d)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(a=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return a?.return?.()},throw(){return a?.throw?.()}}}})}function Hp(e,t,r,n,s,i){let a=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 d=c[0],f=Xi(t.attributes,d),m=f.definition?.tableClass||f.elements.definition?.tableClass,h=n?.[d],p=Hp({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:a},m,r,h?.[d]?.joined,c[1]===m.primaryKey,i);if(!p)return;if(h){h.filters||(h.filters=[]),h.filters.push(p);return}let _=t.propertyResolvers?.[d];_.to&&(p.to=_.to);let g,y=o((R,I)=>{let P,Y;return _?_.returnDirect?(P=_(R,r,I),Y=ct):(Y=_(R,r,I,!0),Array.isArray(Y)?(P=Y.map(te=>te.value),Y=null):P=Y?.value):P=R[d],{subObject:P,subEntry:Y}},"getSubObject"),T=o((R,I)=>{if(_&&p.idFilter){if(!g)if(p.idFilter.idSet?.size===1){for(let $ of p.idFilter.idSet)e={attribute:_.from??t.primaryKey,value:$};g=u(_.from??t.primaryKey,p.idFilter,!0,!0)}else g=u(_.from??t.primaryKey,p.idFilter,!1,!0);let x=g(R);return g.idFilter&&(T.idFilter=g.idFilter),x}let{subObject:P,subEntry:Y}=y(R,I);return P?Array.isArray(P)?(!n?.[d]&&n&&(n[d]={fromRecord(x){let $=y(x).subObject;return Array.isArray($)?$.filter(p).map(j=>j[m.primaryKey]):$}}),P.some(p)):p(P,Y):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),FL[a]||a){case ks.SEARCH_TYPES.EQUALS:case void 0:return u(c,d=>d===l,!0);case"contains":return u(c,d=>d?.toString().includes(l));case"ends_with":return u(c,d=>d?.toString().endsWith(l));case"starts_with":return u(c,d=>typeof d=="string"&&d.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,d=>{if(!Array.isArray(d))return!1;for(let f=0,m=l.length;f<m;f++)if(d[f]!==l[f])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,d=>(0,Ji.compareKeys)(d,l[0])>=0&&(0,Ji.compareKeys)(d,l[1])<=0,!0);case"gt":return u(c,d=>(0,Ji.compareKeys)(d,l)>0);case"ge":return u(c,d=>(0,Ji.compareKeys)(d,l)>=0);case"lt":return u(c,d=>(0,Ji.compareKeys)(d,l)<0);case"le":return u(c,d=>(0,Ji.compareKeys)(d,l)<=0);case"ne":return u(c,d=>(0,Ji.compareKeys)(d,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new Qr.ClientError(`Unknown query comparator "${a}"`)}function u(d,f,m,h){let p;m=m&&!s&&t?.indices[d]&&i>3,m&&(e.estimated_count==null&&CR(t)(e),p=e.estimated_count>>4,(isNaN(p)||p>=i)&&(m=!1));let _=0,g=3;function y(T){let R=T[d],I;if(typeof R!="object"||!R||h?I=f(R):Array.isArray(R)?I=R.some(f):R instanceof Date&&(I=f(R.getTime())),m&&(g++,!I&&!y.idFilter&&++_/g*i>p)){let P=sf(e,r.transaction.getReadTxn(),!1,t),Y;y.to?Y=P.flatMap(x=>t.primaryStore.get(x)[y.to]):Y=P.map(of);let te=new Set(Y);y.idFilter=x=>te.has(of(x)),y.idFilter.idSet=te}return I}return o(y,"recordFilter"),s&&(y.idFilter=f),y}o(u,"attributeComparator")}function CR(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/jo(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=FL[n]||n,n===ks.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=Xi(e.attributes,s[0]),a=i.definition?.tableClass||i.elements.definition?.tableClass,c=CR(a)({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*jo(e.indices[i.relationship.from])/(jo(a.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=jo(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else if(n==="starts_with"||n==="prefix")r.estimated_count=OSe*jo(e.primaryStore)+1;else if(n==="between")r.estimated_count=wSe*jo(e.primaryStore)+1;else if(n==="sort"){let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCountAsSort?r.estimated_count=i.customIndex.estimateCountAsSort(r):r.estimated_count=jo(e.primaryStore)+1}else{let s=r[0]??r.attribute,i=e.indices[s];i?.customIndex?.estimateCount?r.estimated_count=i.customIndex.estimateCount(r.value):r.estimated_count=NSe*jo(e.primaryStore)+1}typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return o(t,"estimateConditionForTable"),t}function sg(e,t){if(e)if(Qo=e,tf.lastIndex=0,DSe.test(e))try{if(t&&(t.conditions=[]),Ti=t??new nf,Fp(Ti,""),Fr!==Qo.length&&Wt("Unable to parse query, unexpected end of query"),Ti.parseErrorMessage&&(Ti.parseError=new UL(t.parseErrorMessage),!t))throw Ti.parseError;return Ti}catch(r){if(r.statusCode=400,r.message=`Unable to parse query, ${r.message} at position ${Fr} in '${Qo}'`,Ti.parseErrorMessage&&(r.message+=", "+Ti.parseErrorMessage),t)t.parseError=r;else throw r}else return t??new URLSearchParams(e)}function Wt(e){let t=`${e} at position ${Fr}`;Ti.parseErrorMessage=Ti.parseErrorMessage?Ti.parseErrorMessage+", "+t:t}function Fp(e,t){let r=tf,n,s,i,a,c,l=decodeURIComponent,u;for(;n=r.exec(Qo);){Fr=r.lastIndex;let[,d,f]=n;a?(d&&Wt(`expected operator, but encountered '${d}'`),a=!1,c=!1):c=!0;let m;switch(f){case"=":s!=null?(d.length<=2?i=d:Wt(`invalid FIQL operator ${d}`),l=v2):(l=decodeURIComponent,i="equals",d||Wt("attribute must be specified before equality comparator"),s=rf(d));break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":i=CSe[f],l=xL[i]?v2:decodeURIComponent,d||Wt(`attribute must be specified before comparator ${f}`),s=rf(d);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null)s===void 0&&(t&&Wt(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`),Wt(`no comparison specified before ${f?"'"+f+"'":"end of string"}`));else{e.conditions||Wt("conditions/comparisons are not allowed in a property list");let p={comparator:i,attribute:s||null,value:l(d)};if(i==="eq"&&U2(p,d),s===""){let _=e.conditions[e.conditions.length-1];_.chainedConditions=_.chainedConditions||[],_.chainedConditions.push(p),_.operator=u}else OR(e,u),e.conditions.push(p)}f==="&"?(u="and",s=void 0):f==="|"?(u="or",s=void 0):f==="&="?(u="and",s=""):f==="|="&&(u="or",s="");break;case",":e.conditions?Wt("conditions/comparisons are not allowed in a property list"):e.push(rf(d)),s=void 0;break;case"(":tf.lastIndex=Fr;let h=Fp(d?[]:new nf,")");switch(d){case"":OR(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:Wt("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":Wt("group by is not implemented yet");case"sort":e.sort=x2(h);break;default:Wt(`unknown query function call ${d}`)}Qo[Fr]===","?r.lastIndex=++Fr:a=!0,s=null;break;case"{":e.conditions&&Wt("property sets are not allowed in a queries"),d||Wt("property sets must have a defined parent property name"),tf.lastIndex=Fr,m=Fp([],"}"),m.name=d,e.push(m),Qo[Fr]===","?r.lastIndex=++Fr:a=!0;break;case"[":if(tf.lastIndex=Fr,d?(m=Fp(new nf,"]"),m.name=d):m=Fp(e.conditions?new nf:[],"]"),e.conditions)if(OR(e,u),Qo[Fr]==="="){l=decodeURIComponent,i="equals",s=rf(d),r.lastIndex=++Fr;break}else e.conditions.push(m),s=null;else e.push(m);Qo[Fr]===","?r.lastIndex=++Fr:a=!0;break;case")":case"]":case"}":if(t===f[0]){if(e.conditions)if(s){let p={comparator:i||"equals",attribute:s,value:l(d)};i==="eq"&&U2(p,d),OR(e,u),e.conditions.push(p)}else d&&Wt("no attribute or comparison specified");else(d||e.length>0&&c)&&e.push(rf(d));return e}else Wt(t?`expected '${t}', but encountered '${f[0]}'`:`unexpected token '${f[0]}'`);default:Wt(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?MSe:tf,r.lastIndex=Fr),Fr===Qo.length)return e}t&&Wt(`expected '${t}', but encountered end of string`)}function OR(e,t){e.conditions.length>0&&(e.operator?e.operator!==t&&Wt("Can not mix operators within a condition grouping"):e.operator=t)}function rf(e){return e.indexOf(".")>-1?e.split(".").map(rf):decodeURIComponent(e)}function v2(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 Qr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function U2(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Qr.ClientError("wildcard can only be used at the end of a string")}function x2(e){let t=B2(e[0]);return e.length>1&&(t.next=x2(e.slice(1))),t}function B2(e){if(Array.isArray(e)){let t=B2(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}}Wt(`Unknown sort type ${e}`)}function of(e){return Array.isArray(e)?e.join("\0"):e}function jo(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function vSe(e,t,r){return t*r/jo(e)}var Qr,ks,Ji,oc,NSe,wSe,OSe,CSe,xL,FL,UL,DSe,tf,MSe,Fr,Ti,Qo,nf,ig=fe(()=>{Qr=w(Ee()),ks=w(kt()),Ji=require("ordered-binary"),oc=require("lmdb");op();kc();NSe=.3,wSe=.1,OSe=.05,CSe={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},xL={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};o(BL,"executeConditions");o(sf,"searchByIndex");o(Xi,"findAttribute");o(PSe,"joinTo");o(LSe,"joinFrom");FL={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"};o(Hp,"filterByType");o(CR,"estimateCondition");UL=class extends Qr.Violation{static{o(this,"SyntaxViolation")}},DSe=/[()[\]|!<>.]|(=\w*=)/,tf=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,MSe=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;o(sg,"parseQuery");o(Wt,"recordError");o(Fp,"parseBlock");o(OR,"assignOperator");o(rf,"decodeProperty");o(v2,"typedDecoding");o(U2,"wildcardDecoding");o(x2,"toSortObject");o(B2,"toSortEntry");nf=class{static{o(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}}getAll(){let t=[];for(let r=0,n=this.conditions.length;r<n;r++){let s=this.conditions[r];s.attribute&&t.push(s.value)}return t}};o(of,"flattenKey");o(jo,"estimatedEntryCount");o(vSe,"intersectionEstimate")});var SB={};Ce(SB,{MultiPartId:()=>PR,Resource:()=>vr,contextStorage:()=>cf,snakeCase:()=>xSe,transformForSelect:()=>LR});function xSe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function F2(e,t){if(Wl=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Wl=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new PR;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Wl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Wl=!0,null;e[e.length-1]==="/"&&(Wl=!0)}return t.coerceId(decodeURIComponent(e))}function Hn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,a){let c,l,u,d;if(r){if(a)d=i,a=a.getContext?.()||a;else if(i)typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(d=s,c=d[this.primaryKey]??null,a=i.getContext?.()||i):i?.transaction instanceof co?a=i:d=i;else if(s&&typeof s=="object")d=s,s=void 0,c=d.getId?.()??d[this.primaryKey];else throw new af.ClientError(`Invalid argument for data, must be an object, but got ${s}`);c===null&&(u=!0)}else i?a=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(a=s);if(c===void 0)if(typeof s=="object"&&s){if(l=s,c=s instanceof URLSearchParams?s.toString():s.url,s.conditions)c=s.id;else if(typeof c=="string")if(this.directURLMapping)c=c.slice(1),l.id=c;else{let _=c.indexOf("?");_>-1&&(l=this.parseQuery(c.slice(_+1),s),c=c.slice(0,_),c===""&&(u=!0));let g=this.parsePath(c,a,l);g?.id!==void 0?(g.query&&(l?l=Object.assign(g.query,l):l=g.query),u=g.isCollection,c=g.id):c=g,c&&(l.id=c)}else if(s[Symbol.iterator]){c=[],u=!0;for(let _ of s){if(typeof _=="object"&&_)break;c.push(_)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=new si,l.id=c,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new si,l.id=c,c==null&&(u=!0);l||(l=new si,l.id=c),u&&(l.isCollection=!0);let f;a||(a=cf.getStore()??{}),l.ensureLoaded!=null||l.async||u?(f={...t},l.ensureLoaded!=null&&(f.ensureLoaded=l.ensureLoaded),l.async&&(f.async=l.async),u&&(f.isCollection=!0)):f=t;let m=this.loadAsInstance,h=p;if((m===!1?!this.explicitContext:this.explicitContext===!1)&&(h=o(_=>cf.run(a,()=>p(_)),"runAction")),a?.transaction){let _=this.getResource(c,a,f);return _.then?_.then(h):h(_)}else return Mt(a,()=>{let _=this.getResource(c,a,f);return _.then?_.then(h):h(_)},f);function p(_){if(m!==!1&&a.authorize){a.authorize=!1;let g=t.type==="read"?_.allowRead(a.user,l,a):t.type==="update"?_.doesExist?.()===!1?_.allowCreate(a.user,d,a):_.allowUpdate(a.user,d,a):t.type==="create"?_.allowCreate(a.user,d,a):_.allowDelete(a.user,l,a);if(g?.then)return g.then(y=>{if(!y)throw new af.AccessViolation(a.user);return typeof d?.then=="function"?d.then(T=>e(_,l,a,T)):e(_,l,a,d)});if(!g)throw new af.AccessViolation(a.user)}return typeof d?.then=="function"?d.then(g=>e(_,l,a,g)):e(_,l,a,d)}o(p,"authorizeActionOnResource")}}function as(e,t){let r=new af.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 HL(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let a,c;return e.hasOwnProperty(i)&&typeof(a=e[i])!="function"?a: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 LR(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return o(function a(c){return c.then?c.then(a):Array.isArray(c)?c.map(a):HL(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let u=[],d=i(HL(l,r,n));for(let f of e)u.push(d(f));return u},"transform");let a=e.forceNulls;return o(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(m=>m&&typeof m=="object"?c(m):m);let u={},d=i(HL(l,r,n)),f;for(let m of e){let h=d(m);h===void 0&&a&&(h=null),h?.then?(f||(f=[]),f.push(h.then(p=>u[m.name||m]=p))):u[m.name||m]=h}return f?Promise.all(f).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(a){return c=>{if(typeof c=="string")return a(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let d=r[c.name]?.definition?.tableClass;l=s[c.name]=LR(c.select||c,d)}let u=a(c.name);return l(u)}else return a(c);else return c}}o(i,"handleProperty")}var H2,k2,af,G2,cf,USe,vr,Wl,PR,wa=fe(()=>{H2=require("crypto");Vf();mu();k2=w(Ws()),af=w(Ee());Dc();ig();G2=require("async_hooks");tg();cf=new G2.AsyncLocalStorage,USe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},vr=class{static{o(this,"Resource")}#e;#t;#r;static transactions;static directURLMapping=!1;static loadAsInstance;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=Hn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(a);return a(i);function a(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=LR(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=Hn(function(t,r,n,s){if(Array.isArray(s)&&t.#r&&t.constructor.loadAsInstance!==!1){let i=[];for(let a of s){let c=t.constructor,l=a[c.primaryKey],u=c.getResource(l,n,{async:!0});u.then?i.push(u.then(d=>d.put(a,n))):i.push(u.put(a,n))}return Promise.all(i)}return t.put?t.constructor.loadAsInstance===!1?t.put(r,s):t.put(s,r):as(t,"put")},{hasContent:!0,type:"update"});static patch=Hn(function(t,r,n,s){return t.patch?t.constructor.loadAsInstance===!1?t.patch(r,s):t.patch(s,r):as(t,"patch")},{hasContent:!0,type:"update"});static delete=Hn(function(t,r,n,s){return t.delete?t.delete(r):as(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,H2.randomUUID)()}static create(t,r,n){n?n.getContext&&(n=n.getContext()):n=cf.getStore()??{};let s;return this.loadAsInstance===!1?s=t: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),Mt(n,async()=>{let i=new this(s,n),a=await i.create?i.create(s,r):as(i,"create");return n.newLocation=s??a?.[this.primaryKey],n.createdResource=!0,this.loadAsInstance===!1?a:i})}static invalidate=Hn(function(t,r,n,s){return t.invalidate?t.invalidate(r):as(t,"delete")},{hasContent:!1,type:"update"});static post=Hn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.constructor.loadAsInstance===!1?t.post(r,s):t.post(s,r)},{hasContent:!0,type:"create"});static update=Hn(function(t,r,n,s){return t.update(r,s)},{hasContent:!0,type:"create"});static connect=Hn(function(t,r,n,s){return t.connect?t.constructor.loadAsInstance===!1?t.connect(r,s):t.connect(s,r):as(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Hn(function(t,r,n,s){return t.subscribe?t.subscribe(r):as(t,"subscribe")},{type:"read"});static publish=Hn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.constructor.loadAsInstance===!1?t.publish(r,s):t.publish(s,r):as(t,"publish")},{hasContent:!0,type:"create"});static search=Hn(function(t,r,n){let s=t.search?t.search(r):as(t,"search"),i=n.select;if(i&&n.hasOwnProperty("select")&&s!=null&&!s.selectApplied){let a=LR(i,t.constructor);return s.map(a)}return s},{type:"read"});static query=Hn(function(t,r,n,s){return t.search?t.constructor.loadAsInstance===!1?t.search(r,s):t.search(s,r):as(t,"search")},{hasContent:!0,type:"read"});static copy=Hn(function(t,r,n,s){return t.copy?t.constructor.loadAsInstance===!1?t.copy(r,s):t.copy(s,r):as(t,"copy")},{hasContent:!0,type:"create"});static move=Hn(function(t,r,n,s){return t.move?t.constructor.loadAsInstance===!1?t.move(r,s):t.move(s,r):as(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#r)return(await this.constructor.create(this.#e,t,this.#t)).#e;as(this,"post")}static isCollection(t){return t&&t.#r}get isCollection(){return this.#r}static coerceId(t){return t}static parseQuery(t,r){return sg(t,r)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let a=t.slice(s+1),c=r?.headers&&USe[a];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===a))if(t=t.slice(0,s),n)n.property=a;else return{query:{property:a},id:F2(t,this),isCollection:Wl}}let i=F2(t,this);return Wl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),a;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?a=r.isCollection:a=n?.isCollection;let c=a&&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(d=>d.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 d of l){let f=d.#e,m=u.get(f);m?m.push(d):u.set(f,[d])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return a&&(s.#r=!0),s}subscribe(t){return new Gn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Gn}allowRead(t,r){return t?.role.permission.super_user}allowUpdate(t,r,n){return t?.role.permission.super_user}allowCreate(t,r,n){return t?.role.permission.super_user}allowDelete(t,r){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,k2._assignPackageExport)("Resource",vr);o(xSe,"snakeCase");o(F2,"pathToId");PR=class extends Array{static{o(this,"MultiPartId")}toString(){return this.join("/")}};o(Hn,"transactional");o(as,"missingMethod");o(HL,"selectFromObject");o(LR,"transformForSelect")});var EY={};Ce(EY,{EVICTED:()=>ac,INVALIDATED:()=>Fn,coerceType:()=>MR,makeTable:()=>UR,setServerUtilities:()=>YC});function UR(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:a,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:h}=e,{expirationMS:p,evictionMS:_,audit:g,trackDeletes:y}=e;_??=0;let{attributes:T}=e;T||(T=[]);let R=vL(i,n,l),I,P,Y={},te=Promise.resolve(),x,$,j;for(let q of T)(q.assignCreatedTime||q.name==="__createdtime__")&&(x=q),(q.assignUpdatedTime||q.name==="__updatedtime__")&&($=q),q.expiresAt&&(j=q),q.isPrimaryKey&&(Y=q);let V,le=[],re=[],se=1,_e=2,Ne={},Fe={},He=864e5,_r=0,pt,gr,wr,ou=!1,au,Ft,If,Nf=jl.get(U.REPLICATION_DATABASES);if(Array.isArray(Nf)){for(let q of Nf)if(q.name===c&&q.replicateTo>=0){If=q.replicateTo;break}}let hE=i.getRange({start:!1,end:!1}).constructor,Ty=10,pE=6;g&&Nc(),Cp(i.env.path,q=>{if(P)return da(q)});class cu extends nl{static{o(this,"Updatable")}getUpdatedTime(){return ic.get(this.getRecord())?.version}getExpiresAt(){return ic.get(this.getRecord())?.expiresAt}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.set(E,new Um(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(E,S){return this.addTo(E,-S)}}class Me extends vr{#e;#t;#r;#n;#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=a;static databaseName=c;static attributes=T;static replicate=h;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=x;static updatedTimeProperty=$;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return p}static dbisDB=d;static schemaDefined=u;static sourcedFrom(E,S){if(S&&(this.sourceOptions=S,(S.expiration||S.eviction||S.scanInterval)&&this.setTTLExpiration(S)),S?.intermediateSource)E.intermediateSource=!0,this.sources.unshift(E);else{if(this.sources.some(O=>!O.intermediateSource)){if(this.sources.some(O=>O.name===E.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(E)}P=P||E.get&&(!E.get.reliesOnPrototype||E.prototype.get),I=I||E.load;let A=o(O=>{let D=this.sources;if(D=D.filter(F=>F.intermediateSource&&F[O]&&(!F[O].reliesOnPrototype||F.prototype[O])),D.length>0)if(D.length===1){let F=D[0];return(L,H,W)=>{if(L?.source!==F)return F[O](H,W,L)}}else return(F,L,H)=>{let W=[];for(let ee of D){if(F?.source===ee)break;W.push(ee[O](L,H,F))}return Promise.all(W)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1];N.intermediateSource&&(N={});let b=o(O=>{if(N[O]&&(!N[O].reliesOnPrototype||N.prototype[O]))return(D,F,L)=>{if(!D?.source)return N[O](F,L,D)}},"getApplyToCanonicalSource");Ne={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Fe={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=N.shouldRevalidateEvents;return(async()=>{let O=!1,D,F=o(async(L,H)=>{let W=L.value,ee=L.table?Ge[c][L.table]:Me;if(c===Mf&&(L.table===uu.ROLE_TABLE_NAME||L.table===uu.USER_TABLE_NAME)&&(O=!0),L.id===void 0&&(L.id=W[ee.primaryKey],L.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(L));L.source=E;let oe={residencyId:fa(L.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:L.nodeId},B=L.id,ue=await ee.getResource(B,H,oe);switch(L.finished&&await L.finished,L.type){case"put":return C?ue._writeInvalidate(B,W,oe):ue._writeUpdate(B,W,!0,oe);case"patch":return C?ue._writeInvalidate(B,W,oe):ue._writeUpdate(B,W,!1,oe);case"delete":return ue._writeDelete(B,oe);case"publish":case"message":return ue._writePublish(B,W,oe);case"invalidate":return ue._writeInvalidate(B,W,oe);case"relocate":return ue._writeRelocate(B,oe);default:xe.default.error?.("Unknown operation",L.type,L.id)}},"writeUpdate");try{let L=E.subscribe;L&&y==null&&(y=!0);let H={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},W=E.subscribeOnThisThread?E.subscribeOnThisThread((0,zl.getWorkerIndex)(),H):(0,zl.getWorkerIndex)()===0,ee=L&&W&&await E.subscribe?.(H);if(ee){let oe;for await(let B of ee)try{if(!(B.type==="transaction"?B.writes[0]:B)){xe.default.error?.("Bad subscription event",B);continue}if(B.source=E,B.type==="end_txn"){if(oe?.resolve(),B.localTime&&D!==B.localTime){if(B.remoteNodeIds?.length>0){let ge=[Symbol.for("seq"),B.remoteNodeIds[0]],X=d.get(ge),de=X?.nodes;de||(de=[]);for(let he of B.remoteNodeIds.slice(1)){let Ae=de.find(Oe=>Oe.id===he);de=de.filter(Oe=>Oe.id!==he||Oe===Ae),Ae||(Ae={id:he,seqId:0},de.push(Ae)),Ae.seqId=Math.max(X?.seqId??1,B.localTime),he===oe?.nodeId&&(Ae.lastTxnTime=B.timestamp)}let ne=Math.max(X?.seqId??1,B.localTime);xe.default.trace?.("Received txn",c,new Date(ne),new Date(B.localTime),B.remoteNodeIds),d.put(ge,{seqId:ne,nodes:de})}D=B.localTime}B.onCommit&&oe?.committed.then(B.onCommit);continue}if(oe)if(B.beginTxn)oe.resolve();else{oe.write_promises.push(F(B,oe));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let ae=Mt(B,()=>{if(B.type==="transaction"){let ge=[];for(let X of B.writes)try{ge.push(F(X,B))}catch(de){throw de.message+=" writing "+JSON.stringify(X)+" of event "+JSON.stringify(B),de}return Promise.all(ge)}else if(B.type==="define_schema"){let ge=this.attributes.slice(0),X=!1;for(let de of B.attributes)ge.find(ne=>ne.name===de.name)||(ge.push(de),X=!0);X&&(Ze({table:s,database:c,attributes:ge,origin:"cluster"}),Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,G.CREATE_TABLE,c,s)))}else return B.beginTxn?(oe=B,oe.write_promises=[F(B,B)],new Promise(ge=>{oe.resolve=()=>ge(Promise.all(oe.write_promises))})):F(B,B)});oe&&(oe.committed=ae),O&&ae&&!ae?.waitingForUserChange&&(ae.then(()=>Gp.signalUserChange(new qp.UserEventMsg(process.pid))),ae.waitingForUserChange=!0),B.onCommit&&(ae?ae.then(B.onCommit):B.onCommit())}catch(ue){xe.default.error?.("error in subscription handler",ue)}}}catch(L){xe.default.error?.(L)}})(),this}static get isCaching(){return P}static get shouldRevalidateEvents(){return this.prototype.get!==Me.prototype.get}static getResource(E,S,A){let N=super.getResource(E,S,A);if(E!=null&&this.loadAsInstance!==!1){Or(E);try{if(N.getRecord?.())return N;if(typeof E=="object"&&E&&!Array.isArray(E))throw new Error(`Invalid id ${JSON.stringify(E)}`);let b=!A?.async||i.cache?.get?.(E),C=Cr(S),O=C.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Tc(E,S,{transaction:O,ensureLoaded:A?.ensureLoaded},b,D=>{if(D?Me._updateResource(N,D):N.#e=null,S.onlyIfCached){if(!N.doesExist())throw new lt.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let F=yc(E,D,S,N);if(F)return C?.disregardReadTxn(),N.#i=!0,S.loadedFromSource=!0,Ri(F,L=>(Me._updateResource(N,L),N))}return N})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(E)),b}}return N}static _updateResource(E,S){E.#n=S,E.#e=S?.value??null,E.#r=S?.version}ensureLoaded(){let E=yc(this.getId(),this.#n,this.getContext());if(E)return this.#i=!0,this.getContext().loadedFromSource=!0,Ri(E,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let E=Y?.type;if(E==="String"||E==="ID")return super.getNewId();if(!Ft){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,O;if(C&&C.nodeName===server.hostname&&(!WSe(i)||C.pid===process.pid)){let D=C.start,F=C.end;O=D;for(let L of i.getKeys({start:F,end:D,limit:1,reverse:!0}))O=L}else C=N(b?.version??null),O=C.start;Ft=new BigInt64Array([BigInt(O)+1n]),Ft=new BigInt64Array(i.getUserSharedBuffer("id",Ft.buffer)),Ft.maxSafeId=C.end}let S=Number(Atomics.add(Ft,0,1n)),A=E==="Int"?512:1048576;if(S+A>=Ft.maxSafeId){let b=o(C=>{Ft.maxSafeId=S+(E==="Int"?1023:4194303);let O=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=C?void 0:i.useReadTransaction(),F=Number(Ft[0]);for(let W of i.getKeys({start:F+1,end:O,limit:1,transaction:D}))O=W;D?.done();let{value:L,version:H}=i.getEntry(Symbol.for("id_allocation"));if(Ft.maxSafeId<O){if(L.end>Ft.maxSafeId-100)return;xe.default.info?.("New id allocation",S,Ft.maxSafeId,H),i.put(Symbol.for("id_allocation"),{start:L.start,end:Ft.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),H)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ft.maxSafeId}, but id of ${O} detected`);let W=N(H);W.alreadyUpdated||Atomics.store(Ft,0,BigInt(W.start+1)),Ft.maxSafeId=W.end}},"updateEnd");S+A===Ft.maxSafeId?setImmediate(b):S+100>=Ft.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${E=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return S;function N(b){let C=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,O=C/4,D,F,L=!1,H,W;do{H=Math.floor(Math.random()*C),W={start:H,end:H+(E==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},D=0;for(let ee of i.getKeys({start:H,limit:1,reverse:!0}))D=ee;F=C;for(let ee of i.getKeys({start:H+1,end:C,limit:1}))F=ee;O*=.875,O<1e3&&!L&&(L=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${E==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,H,D,F,O))}while(!(O<F-H&&(O<H-D||D===0)));return i.transactionSync(()=>{let ee=i.getEntry(Symbol.for("id_allocation"));return(ee?.version??null)==b?(xe.default.info?.("Allocated new id range",W),i.put(Symbol.for("id_allocation"),W,Date.now()),W):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ee.value})})}}static setTTLExpiration(E){if(typeof E=="number")p=E*1e3,_||(_=0);else if(E&&typeof E=="object")p=E.expiration*1e3,_=(E.eviction||0)*1e3,He=E.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");He=He||(p+_)/4,da()}static getResidencyRecord(E){return d.get([Symbol.for("residency_by_id"),E])}static setResidency(E){Me.getResidency=E&&((S,A)=>{try{return E(S,A)}catch(N){throw N.message+=` in residency function for table ${s}`,N}})}static setResidencyById(E){Me.getResidencyById=E&&(S=>{try{return E(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(E,S){if(Me.getResidencyById)return Me.getResidencyById(E[t]);let A=If;if(S.replicateTo!=null){if(Array.isArray(S.replicateTo))return S.replicateTo.includes(server.hostname)?S.replicateTo:[server.hostname,...S.replicateTo];S.replicateTo>=0&&(A=S.replicateTo)}if(A>=0&&server.nodes){let N=[server.hostname];if(S.previousResidency)N.push(...S.previousResidency.slice(0,A));else{let b=server.nodes.map(D=>D.name),C=Math.floor(b.length*Math.random());N.push(...b.slice(C,C+A));let O=C+A-b.length;O>0&&N.push(...b.slice(0,O))}return N}}static enableAuditing(E=!0){g=E,E&&Nc(),Me.audit=E}static coerceId(E){return E===""?null:MR(E,Y)}static async dropTable(){delete Ge[c][s];for(let E of i.getRange({versions:!0,snapshot:!1,lazy:!0}))E.metadataFlags&Dn&&E.value&&Ea(E.value);if(c===a){for(let E of T)d.remove(Me.tableName+"/"+E.name),r[E.name]?.drop();d.remove(Me.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),GL.default.unlinkSync(i.env.path);Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,G.DROP_TABLE,c,s))}get(E){let S=this.constructor;if(typeof E=="string"&&S.loadAsInstance!==!1)return this.getProperty(E);if(Of(E))return this.search(E);if(E&&E.id===void 0&&!E.toString()){let A={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:T,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?Me.getRecordCount().then(N=>(A.recordCount=N.recordCount,A.estimatedRecordRange=N.estimatedRange,A)):A}if(E!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),N=Cr(A),b=N.getReadTxn();if(b?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let C=Sr(E);Or(C);let O=!0;return E.checkPermission&&(O=this.allowRead(A.user,E)),Ri(O,D=>{if(!D)throw new lt.AccessViolation(A.user);let F=!0;return Tc(C,A,{transaction:b,ensureLoaded:F},!1,L=>{if(A.onlyIfCached){if(!L?.value)throw new lt.ServerError("Entry is not cached",504)}else if(F){let H=yc(C,L,A);if(H)return N?.disregardReadTxn(),A.loadedFromSource=!0,H.then(W=>W?.value)}return L?.value})})}if(E?.property)return this.getProperty(E.property);if(this.doesExist()||E?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(E,S){let A=Rc(E,S);if(A?.read){if(A.isSuperUser)return!0;let N=A.attribute_permissions,b=S?.select;if(N?.length>0||ou&&b){if(S||(S={}),b){let C=N?.length>0&&kL(N,"read");S.select=b.map(O=>{let D=O.name||O;if(!C||C[D]){let F=wr[D]?.definition?.tableClass;if(F){if(O.name||(O={name:O}),!O.checkPermission&&S.checkPermission&&(O.checkPermission=S.checkPermission),!F.prototype.allowRead.call(null,E,O))return!1;if(!O.select)return O.name}return O}}).filter(Boolean)}else S.select=N.filter(C=>C.read&&!wr[C.attribute_name]).map(C=>C.attribute_name);return S}else return!0}}allowUpdate(E,S,A){let N=Rc(E,A);if(N?.update){let b=N.attribute_permissions;if(b?.length>0){let C=kL(b,"update");for(let O in S)if(!C[O])return!1;for(let O of b){let D=O.attribute_name;!O.update&&!(D in S)&&(S[D]=this.getProperty(D))}}return Ic(this.getContext())}}allowCreate(E,S,A){if(this.isCollection){let N=Rc(E,A);if(N?.insert){let b=N.attribute_permissions;if(b?.length>0){let C=kL(b,"insert");for(let O in S)if(!C[O])return!1;return Ic(this.getContext())}else return Ic(this.getContext())}}else return this.allowUpdate(E,{})}allowDelete(E,S){return Rc(E,S)?.delete&&Ic(this.getContext())}update(E,S){let A,N=typeof S=="boolean"||S===void 0&&(E==null||typeof E=="object"&&!(E instanceof URLSearchParams)),b=!1;N?(b=S,S=E,A=this.getId()):A=Sr(E);let C=this.getContext();if(!Cr(C))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(b)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(N){let D=this.#t;D&&(S=Object.assign(D,S)),this.#t=S}else{let D=!0;if(E==null)throw new TypeError("Can not put a record without a target");return E.checkPermission&&(D=this.allowUpdate(C.user,S,E)),Ri(D,F=>{if(!F)throw new lt.AccessViolation(C.user);return Ri(i.get(Sr(E)),L=>{let H=new cu(L);return H._setChanges(S),this._writeUpdate(A,H.getChanges(),!1),H})})}return this._writeUpdate(A,this.#t,b),this}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.#s===$2?this.set(E,(+this.getProperty(E)||0)+S):(this.#s||this.update(),this.set(E,new Um(S)));else throw new Error("Can not add a non-numeric value")}subtractFrom(E,S){if(typeof S=="number")return this.addTo(E,-S);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(E){this.#t=E}setRecord(E){this.#e=E}invalidate(E){let S=!0,A=this.getContext();return E?.checkPermission&&(S=this.allowDelete(A.user,E,A)),Ri(S,N=>{if(!N)throw new lt.AccessViolation(A.user);this._writeInvalidate(E?Sr(E):this.getId())})}_writeInvalidate(E,S,A){let N=this.getContext();Or(E),Cr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Ne.invalidate?.bind(this,N,E),beforeIntermediate:Fe.invalidate?.bind(this,N,E),commit:o((C,O)=>{if(!(bc(C,O,A?.nodeId)<=0)){S??=null;for(let D in r)S||(S={}),S[D]===void 0&&(S[D]=this.getProperty(D));xe.default.trace?.(`Invalidating entry in ${s} id: ${E}, timestamp: ${new Date(C).toISOString()}`),R(E,S,O,C,Fn,g,{user:N?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(E,S){let A=this.getContext();Or(E),Cr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Ne.relocate?.bind(this,A,E),beforeIntermediate:Fe.relocate?.bind(this,A,E),commit:o((b,C)=>{if(bc(b,C,S?.nodeId)<=0)return;let O=Me.getResidencyRecord(S.residencyId),D=0,F=null,L=C?.value;if(O&&!O.includes(server.hostname)){for(let H in r)F||(F={}),F[H]=L(H);D=Fn}else F=L;xe.default.trace?.(`Relocating entry id: ${E}, timestamp: ${new Date(b).toISOString()}`),R(E,F,C,b,D,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(E,S){let A={previousResidency:this.getResidencyRecord(E.residencyId),isRelocation:!0},N=wc(this.getResidency(S.value,A)),b;if(N){if(!N.includes(server.hostname))return!1;b=fa(N)}let O=R(E.key,S.value,E,E.version,0,!0,{residencyId:b,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(E,S,A){let N=this.Source,b;if(!((P||g)&&(!S||(b=i.getEntry(E),!b||!S)||b.version!==A))){if(P){if(i.hasLock(E,b.version))return;let C;for(let O in r)C||(C={}),C[O]=S[O];if(C)return R(E,C,b,A,ac,null,null,null,!0)}if(i.ifVersion(E,A,()=>{oo(E,S,null)}),g)return R(E,null,b,A,ac,null,null,null,!0);Yl(i,b??i.getEntry(E),A)}}lock(){throw new Error("Not yet implemented")}static operation(E,S){return E.table||=s,E.schema||=c,J2.operation(E,S)}put(E,S){if(S===void 0||S instanceof URLSearchParams)this.update(E,!0);else{let A=!0;if(E==null)throw new TypeError("Can not put a record without a target");let N=this.getContext();return E.checkPermission&&(A=this.allowUpdate(N.user,S,E)),Ri(A,b=>{if(!b)throw new lt.AccessViolation(N.user);if(Array.isArray(S))for(let C of S){let O=C[t];this._writeUpdate(O,C,!0)}else{let C=Sr(E);this._writeUpdate(C,S,!0)}})}}create(E,S){let A=!0,N=this.getContext();if(!S&&!(E instanceof URLSearchParams)&&(S=E,E=void 0),!S||typeof S!="object"||Array.isArray(S))throw new TypeError("Can not create a record without an object");return E?.checkPermission&&(A=this.allowCreate(N.user,S,E)),Ri(A,b=>{if(!b)throw new lt.AccessViolation(N.user);let C=Sr(E)??S[t];if(C===void 0)C=this.constructor.getNewId();else if(i.get(C))throw new lt.ClientError("Record already exists",409);return this._writeUpdate(C,S,!0),S})}patch(E,S){if(S===void 0||S instanceof URLSearchParams)this.update(E,!1);else{let A=this.update(E,S);if(A?.then)return A.then(()=>{})}}_writeUpdate(E,S,A,N){let b=this.getContext(),C=Cr(b);Or(E);let O=this.#n??i.getEntry(E);this.#s=A?$2:$Se;let D={key:E,store:i,entry:O,nodeName:b?.nodeName,validate:o(F=>{S||(S=this.#t),A||S&&x_(this.#t===S?this:S)?b?.source||(C.checkOverloaded(),this.validate(S,!A),$&&(S[$.name]=$.type==="Date"?new Date(F):$.type==="String"?new Date(F).toISOString():F),A&&(t&&S[t]!==E&&(S[t]=E),x&&(O?.value?S[x.name]=O?.value[x.name]:S[x.name]=x.type==="Date"?new Date(F):x.type==="String"?new Date(F).toISOString():F),S=Oa(S))):C.removeWrite(D)},"validate"),before:A?Ne.put?()=>Ne.put(b,E,S):null:Ne.patch?()=>Ne.patch(b,E,S):Ne.put?()=>Ne.put(b,E,Oa(this)):null,beforeIntermediate:A?Fe.put?()=>Fe.put(b,E,S):null:Fe.patch?()=>Fe.patch(b,E,S):Fe.put?()=>Fe.put(b,E,Oa(this)):null,commit:o((F,L,H)=>{if(H){if(b&&L?.version>(b.lastModified||0)&&(b.lastModified=L.version),this.#n=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=L?.value??null)}this.#t=void 0,this.#r=F;let W=L?.value,ee=S;this.#s=0;let oe=!1,B=bc(F,L,N?.nodeId),ue;if(B<=0){if(g){let ne=L.localTime,he=L.version;xe.default.trace?.("Applying CRDT update to record with id: ",E,"txn time",new Date(F),"applying later update from:",new Date(he),"local recorded time",new Date(ne));let Ae=[];for(;ne>F||he>=F&&ne>0;){let Oe=l.get(ne);if(!Oe)break;let ze=Ut(Oe);if(he=ze.version,he>=F){if(he===F){if(B=bc(F,{version:he,localTime:ne},N?.nodeId),B===0)return;if(B>0)continue}if(ze.type==="patch")Ae.push(ze),ue=S;else if(ze.type==="put"||ze.type==="delete")return}ne=ze.previousLocalTime}if(!ne){xe.default.debug?.("No further audit history, must drop update",E,"existing version preserved",L);return}Ae.sort((Oe,ze)=>Oe.version-ze.version);for(let Oe of Ae){let ze=Oe.getValue(i);if(xe.default.debug?.("Rebuilding update with future patch:",new Date(Oe.version),ze,Oe),ee=v_(ee,ze,A),!ee)return}}else{if(A)return;ee=v_(ee,W,A),xe.default.debug?.("Rebuilding update without audit:",ee)}xe.default.trace?.("Rebuilt record to save:",ee," is full update:",A)}let ae;if(A?ae=ee:this.constructor.loadAsInstance===!1?ae=Oa(W,ee):(this.#e=W,ae=Oa(this,ee)),this.#e=ae,ae&&ae.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ge;if(N?.residencyId!=null)ge=N.residencyId;else{O?.residencyId&&(b.previousResidency=Me.getResidencyRecord(O.residencyId));let ne=wc(Me.getResidency(ae,b));if(ne&&!ne.includes(server.hostname))if(ue??=ae,oe=!0,Me.getResidencyById)ae=void 0;else{ae=null;for(let he in r)ae||(ae={}),ae[he]=ue[he]}ge=fa(ne)}A||(ue=S);let X=b?.expiresAt??(p?p+Date.now():-1);xe.default.trace?.(`Saving record with id: ${E}, timestamp: ${new Date(F).toISOString()}${X?", expires at: "+new Date(X).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(ae).slice(0,100)}catch{return""}})()),oo(E,W,ae);let de=A?"put":"patch";R(E,ae,L,F,oe?Fn:0,g,{omitLocalRecord:oe,user:b?.user,residencyId:ge,expiresAt:X,nodeId:N?.nodeId,originatingOperation:b?.originatingOperation},de,!1,ue),b.expiresAt&&da()},"commit")};C.addWrite(D)}async delete(E){if(Of(E)){E.select=["$id"];for await(let S of this.search(E))this._writeDelete(S.$id);return!0}if(E){let S=!0,A=this.getContext();return E.checkPermission&&(S=this.allowDelete(A.user,E,A)),Ri(S,N=>{if(!N)throw new lt.AccessViolation(A.user);let b=Sr(E);return this._writeDelete(b),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(E,S){let A=Cr(this.getContext());Or(E);let N=this.getContext();return A.addWrite({key:E,store:i,entry:this.#n,nodeName:N?.nodeName,before:Ne.delete?.bind(this,N,E),beforeIntermediate:Fe.delete?.bind(this,N,E),commit:o((b,C,O)=>{let D=C?.value;O&&(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),Me._updateResource(this,C)),!(bc(b,C,S?.nodeId)<=0)&&(oo(this.getId(),D),xe.default.trace?.(`Deleting record with id: ${E}, txn timestamp: ${new Date(b).toISOString()}`),g||y?(R(E,null,C,b,0,g,{user:N?.user,nodeId:S?.nodeId},"delete"),g||da()):Yl(i,C))},"commit")}),!0}search(E){let S=this.getContext(),A=Cr(S);if(!E)throw new Error("No query provided");if(E.parseError)throw E.parseError;if(E.checkPermission&&!this.allowRead(S.user,E))throw new lt.AccessViolation(S.user);let N=E.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(E)?E:E[Symbol.iterator]?Array.from(E):[];let b=E.id??this.getId();b&&(N=[{attribute:null,comparator:Array.isArray(b)?"prefix":"starts_with",value:b}].concat(N));let C,O={};function D(ne,he){let Ae;switch(he){case"and":case void 0:if(ne.length<1)throw new Error('An "and" operator requires at least one condition');Ae=!0;break;case"or":if(ne.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+he)}for(let Oe of ne){if(Oe.conditions){Oe.conditions=D(Oe.conditions,Oe.operator);continue}let ze=Oe[0]??Oe.attribute,kr=ze==null?Y:Xi(T,ze);if(kr)(kr.type||xL[Oe.comparator])&&(Oe[1]===void 0?Oe.value=L(Oe.value,kr):Oe[1]=L(Oe[1],kr));else if(ze!=null)throw(0,lt.handleHDBError)(new Error,`${ze} is not a defined attribute`,404);if(Oe.chainedConditions)if(Oe.chainedConditions.length===1&&(!Oe.operator||Oe.operator=="and")){let ye=Oe.chainedConditions[0],We,Xe;if(ye.comparator==="gt"||ye.comparator==="greater_than"||ye.comparator==="ge"||ye.comparator==="greater_than_equal"?(We=Oe,Xe=ye):(We=ye,Xe=Oe),We.comparator!=="lt"&&We.comparator!=="less_than"&&We.comparator!=="le"&&We.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let jt=Xe.comparator==="ge"||Xe.comparator==="greater_than_equal",Dt=We.comparator==="le"||We.comparator==="less_than_equal";Oe.comparator=(jt?"ge":"gt")+(Dt?"le":"lt"),Oe.value=[Xe.value,We.value]}else throw new Error("Multiple chained conditions are not currently supported")}return ne}o(D,"prepareConditions");function F(ne,he){if(E.enforceExecutionOrder)return ne;for(let Ae of ne)Ae.conditions&&(Ae.conditions=F(Ae.conditions,Ae.operator));return ne.length>1&&he!=="or"?BSe(ne,CR(Me)):ne}o(F,"orderConditions");function L(ne,he){return Array.isArray(ne)?ne.map(Ae=>MR(Ae,he)):MR(ne,he)}o(L,"coerceTypedValues");let H=E.operator;(N.length>0||H)&&(N=D(N,H));let W=typeof E.sort=="object"&&E.sort,ee;if(W&&H!=="or"){let ne=W.attribute;if(ne==null)throw new lt.ClientError("Sort requires an attribute");if(C=N.find(he=>of(he.attribute)===of(ne)),!C){let he=Xi(T,ne);if(!he)throw(0,lt.handleHDBError)(new Error,`${Array.isArray(ne)?ne.join("."):ne} is not a defined attribute`,404);if(he.indexed)C={...W,comparator:"sort"},N.push(C);else if(N.length===0&&!E.allowFullScan)throw(0,lt.handleHDBError)(new Error,`${Array.isArray(ne)?ne.join("."):ne} is not indexed and not combined with any other conditions`,404)}C&&(C.descending=!!W.descending)}N=F(N,H),W&&(C&&N[0]===C?W.next&&(ee={dbOrderedAttribute:W.attribute,attribute:W.next.attribute,descending:W.next.descending,next:W.next.next}):(C&&N.splice(N.indexOf(C),1),ee=W));let oe=E.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),E.explain)return{conditions:N,operator:H,postOrdering:ee,selectApplied:!!oe};let B=A.useReadTxn(),ue=BL(N,H,Me,B,E,S,(ne,he)=>Cf(ne,oe,S,B,he),O),ae=E.ensureLoaded!==!1;ee||(ue=de(ue));let ge=Me.transformEntryForSelect(oe,S,B,O,ae,!0),X=Me.transformToOrderedSelect(ue,oe,ee,S,B,ge);function de(ne){return E.offset||E.limit!==void 0?ne.slice(E.offset,E.limit!==void 0?(E.offset||0)+E.limit:void 0):ne}return o(de,"applyOffset"),ee&&(X=de(X)),X.onDone=()=>{X.onDone=null,A.doneReadTxn()},X.selectApplied=!0,X.getColumns=()=>{if(oe){let ne=[];for(let he of oe)he==="*"?ne.push(...T.map(Ae=>Ae.name)):ne.push(he.name||he);return ne}return T.filter(ne=>!ne.computed&&!ne.relationship).map(ne=>ne.name)},X}static transformToOrderedSelect(E,S,A,N,b,C){let O=new hE;if(A){E=Cf(E,S,N,b,null);let D;O.iterate=function(){let L,H=E[Symbol.asyncIterator]?E[Symbol.asyncIterator]():E[Symbol.iterator](),W,ee=A.dbOrderedAttribute,oe,B,ue=!0;function ae(X){let de=X.next&&ae(X.next),ne=X.descending;return N.sort=X,(he,Ae)=>{let Oe=Ac(he,X.attribute,N),ze=Ac(Ae,X.attribute,N),kr=ne?(0,Ql.compareKeys)(ze,Oe):(0,Ql.compareKeys)(Oe,ze);return kr===0?de?.(he,Ae)||0:kr}}o(ae,"createComparator");let ge=ae(A);return{async next(){let X;if(L)if(X=L.next(),X.done){if(W)return O.onDone&&O.onDone(),X}else return{value:await C.call(this,X.value)};D=[],oe&&D.push(oe);do if(X=await H.next(),X.done){if(W=!0,D.length)break;return O.onDone&&O.onDone(),X}else{let de=X.value;if(de?.then&&(de=await de),ee){let ne=Ac(de,ee,N);if(ue)ue=!1,B=ne;else if(ne!==B){B=ne,oe=de;break}}D.push(de)}while(!0);return A.isGrouped,D.sort(ge),L=D[Symbol.iterator](),X=L.next(),X.done?(O.onDone&&O.onDone(),X):{value:await C.call(this,X.value)}},return(){O.onDone&&O.onDone(),H.return()},throw(){O.onDone&&O.onDone(),H.throw()}}};let F=o(L=>{if(typeof S=="object"&&Array.isArray(L.attribute))for(let H=0;H<S.length;H++){let W=S[H],ee;if(W.name===L.attribute[0]){for(ee=W.sort||(W.sort={});ee.next;)ee=ee.next;ee.attribute=L.attribute.slice(1),ee.descending=L.descending}else W===L.attribute[0]&&(S[H]=ee={name:W,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&F(L.next)},"applySortingOnSelect");F(A)}else O.iterate=(E[Symbol.asyncIterator]||E[Symbol.iterator]).bind(E),O=O.map(function(D){try{let F=C.call(this,D);return typeof F?.catch=="function"?F.catch(L=>{throw L.partialObject={[t]:D.key},L}):F}catch(F){throw F.partialObject={[t]:D.key},F}});return O}static transformEntryForSelect(E,S,A,N,b,C){let O;b&&P&&!(typeof E=="string"?[E]:E)?.every(L=>{let H;return typeof L=="object"?H=L.name:H=L,r[H]||H===t})&&(O=!0);let D,F=o(function(L){let H;if(S?.transaction?.stale&&(S.transaction.stale=!1),L!=null){if(H=L.deref?L.deref():L.value,!H&&(L.key===void 0||L.deref)||L.metadataFlags&Fn){if(L.metadataFlags&Fn&&S.replicateFrom===!1&&C&&L.residencyId)return lc.SKIP;if(L=Tc(L.key??L,S,{transaction:A,lazy:E?.length<4,ensureLoaded:b},this?.isSync,W=>W),L?.then)return L.then(F.bind(this));H=L?.value}if(O&&L?.metadataFlags&(Fn|ac)||L?.expiresAt!=null&&L?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:L.key,message:"This entry has expired"};let W=yc(L.key??L,L,S);if(W?.then)return W.then(F)}}if(H==null)return C?lc.SKIP:H;if(E&&!(E[0]==="*"&&E.length===1)){let W,ee=o((B,ue)=>{let ae;typeof B=="object"?ae=B.name:ae=B;let ge=wr?.[ae],X;if(ge){let de=N?.[ae];if(de)if(de.hasMappings){let he=ge.from?H[ge.from]:of(L.key);X=de.get(he),X||(X=[])}else X=de.fromRecord?.(H);else X=ge(H,S,L,!0);let ne=o(he=>{if(ge.directReturn)return ue(he,ae);if(he&&typeof he=="object"){let Ae=ge.definition?.tableClass||Me;D||(D={});let Oe=D[ae]||(D[ae]=Ae.transformEntryForSelect(ae===B?null:B.select||(Array.isArray(B)?B:null),S,A,de,b));if(Array.isArray(he)){let ze=[],kr=Ae.transformToOrderedSelect(he,B.select,typeof B.sort=="object"&&B.sort,S,A,Oe)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),ye=o(Xe=>{for(;!Xe.done;){if(Xe?.then)return Xe.then(ye);ze.push(Xe.value),Xe=kr.next()}ue(ze,ae)},"nextValue"),We=ye(kr.next());We&&(W||(W=[]),W.push(We));return}else if(he=Oe.call(this,he),he?.then){W||(W=[]),W.push(he.then(ze=>ue(ze,ae)));return}}ue(he,ae)},"handleResolvedValue");X?.then?(W||(W=[]),W.push(X.then(ne))):ne(X);return}else X=H[ae],X&&typeof X=="object"&&ae!==B&&(X=Me.transformEntryForSelect(B.select||B,S,A,null)({value:X}));ue(X,ae)},"selectAttribute"),oe;if(typeof E=="string")ee(E,B=>{oe=B});else if(Array.isArray(E))if(E.asArray)oe=[],E.forEach((B,ue)=>{B==="*"?E[ue]=H:ee(B,ae=>oe[ue]=ae)});else{oe={};let B=E.forceNulls;for(let ue of E)if(ue==="*")for(let ae in H)oe[ae]=H[ae];else ee(ue,(ae,ge)=>{ae===void 0&&B&&(ae=null),oe[ge]=ae})}else throw new lt.ClientError("Invalid select"+E);return W?Promise.all(W).then(()=>oe):oe}return H},"transform");return F}async subscribe(E){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||Ze({table:s,database:c,schemaDefined:u,attributes:T,audit:!0}),E||(E={});let S=!E.rawEvents,A=[],N=this,b=ON(Me,this.getId()??null,function(O,D,F,L){try{let H=D.getValue?.(i,S),W=D.type;if(!H&&W==="patch"&&S){let oe=i.getEntry(O);oe?.version===D.version?H=oe.value:H=D.getValue?.(i,!0,F),W="put"}let ee={id:O,localTime:F,value:H,version:D.version,type:W,beginTxn:L};A?A.push(ee):this.send(ee)}catch(H){xe.default.error?.(H)}},E.startTime||0,E),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,E.onlyChildren&&(b.onlyChildren=!0)),E.supportsTransactions&&(b.supportsTransactions=!0);let O=this.getId(),D=E.previousCount;D>1e3&&(D=1e3);let F=E.startTime;if(this.isCollection){if(F){if(D)throw new lt.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:L,value:H}of l.getRange({start:F,exclusiveStart:!0,snapshot:!1})){let W=Ut(H);if(W.tableId!==n)continue;let ee=W.recordId;if(O==null||W2(O,ee)){let oe=W.getValue(i,S,L);if(b.send({id:ee,localTime:L,value:oe,version:W.version,type:W.type}),b.queue?.length>K2&&await b.waitForDrain()===!1)return}b.startTime=L}}else if(D){let L=[];for(let{key:H,value:W}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ee=Ut(W);if(ee.tableId!==n)continue;let oe=ee.recordId;if(O==null||W2(O,oe)){let B=ee.getValue(i,S,H);if(L.push({id:oe,localTime:H,value:B,version:ee.version,type:ee.type}),--D<=0)break}}catch(ee){xe.default.error("Error getting history entry",H,ee)}for(let H=L.length;H>0;)b.send(L[--H]);L[0]&&(b.startTime=L[0].localTime)}else if(!E.omitCurrent){for(let{key:L,value:H,version:W,localTime:ee}of i.getRange({start:O??!1,end:O==null?void 0:[O,Ql.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(H&&(b.send({id:L,localTime:ee,value:H,version:W,type:"put"}),b.queue?.length>K2&&await b.waitForDrain()===!1))return}}else{D&&!F&&(F=0);let L=this.#n?.localTime;if(L===ML&&(i.cache?.delete(O),this.#n=i.getEntry(O),xe.default.trace?.("re-retrieved record",L,this.#n?.localTime),L=this.#n?.localTime),xe.default.trace?.("Subscription from",F,"from",O,L),F<L){let H=[],W=L;do{let ee=l.get(W);if(ee){E.omitCurrent=!0;let oe=Ut(ee),B=oe.getValue(i,S,W);S&&(oe.type="put"),H.push({id:O,value:B,localTime:W,...oe}),W=oe.previousLocalTime}else break;D&&D--}while(W>F&&D!==0);for(let ee=H.length;ee>0;)b.send(H[--ee]);b.startTime=L}!E.omitCurrent&&this.doesExist()&&b.send({id:O,localTime:L,value:this.#e,version:this.#r,type:"put"})}for(let L of A)b.send(L);A=null})();return E.listener&&b.on("data",E.listener),b}static subscribeOnThisThread(E,S){return E===0||S?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(E,S,A){if(S===void 0||S instanceof URLSearchParams)this._writePublish(this.getId(),E,S);else{let N=!0,b=this.getContext();return E.checkPermission&&(N=this.allowCreate(b.user,E,b)),Ri(N,C=>{if(!C)throw new lt.AccessViolation(b.user);let O=Sr(E);this._writePublish(O,S,A)})}}_writePublish(E,S,A){let N=Cr(this.getContext());E??=null,E!==null&&Or(E);let b=this.getContext();N.addWrite({key:E,store:i,entry:this.#n,nodeName:b?.nodeName,validate:o(()=>{b?.source||(N.checkOverloaded(),this.validate(S))},"validate"),before:Ne.publish?.bind(this,b,E,S),beforeIntermediate:Fe.publish?.bind(this,b,E,S),commit:o((C,O,D)=>{O===void 0&&y&&!g&&da(),xe.default.trace?.(`Publishing message to id: ${E}, timestamp: ${new Date(C).toISOString()}`),R(E,O?.value??null,O,O?.version||C,0,!0,{user:b?.user,residencyId:A?.residencyId,expiresAt:b?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(E,S){let A,N=o((b,C,O)=>{if(C.type&&b!=null)if(S&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be an object${C.type?" ("+C.type+")":""}`);let D=C.properties;for(let F=0,L=D.length;F<L;F++){let H=D[F];if(H.relationship||H.computed){E.hasOwnProperty(H.name)&&(A||(A=[])).push(`Computed property ${O}.${H.name} may not be directly assigned a value`);continue}let W=N(b[H.name],H,O+"."+H.name);W&&(b[H.name]=W)}if(C.sealed&&b!=null&&typeof b=="object")for(let F in b)D.find(L=>L.name===F)||(A||(A=[])).push(`Property ${F} is not allowed within object in property ${O}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} 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 ${Gs(b)} in property ${O} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(D=>typeof D=="string")||(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${Gs(b)} in property ${O} 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 ${Gs(b)} in property ${O} 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 ${Gs(b)} in property ${O} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof gs)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let D=0,F=b.length;D<F;D++){let L=b[D],H=N(L,C.elements,O+"[*]");H&&(b[D]=H)}}else(A||(A=[])).push(`Value ${Gs(b)} in property ${O} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${O} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=T.length;b<C;b++){let O=T[b];if(O.relationship||O.computed){Object.hasOwn(E,O.name)&&(A||(A=[])).push(`Computed property ${O.name} may not be directly assigned a value`);continue}if(!S||O.name in E){let D=N(E[O.name],O,O.name);D!==void 0&&(E[O.name]=D)}}if(f)for(let b in E)T.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new lt.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return P?!!this.#i:void 0}static async addAttributes(E){let S=T.slice(0);for(let A of E){if(!A.name)throw new lt.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new lt.ClientError("Attribute names cannot include backticks or forward slashes");FSe(A.name),S.push(A)}return Ze({table:s,database:c,schemaDefined:u,attributes:S}),Me.indexingOperation}static async removeAttributes(E){let S=T.filter(A=>!E.includes(A.name));return Ze({table:s,database:c,schemaDefined:u,attributes:S}),Me.indexingOperation}static getSize(){let E=i.getStats();return(E.treeBranchPageCount+E.treeLeafPageCount+E.overflowPages)*E.pageSize}static getAuditSize(){let E=l?.getStats();return E&&(E.treeBranchPageCount+E.treeLeafPageCount+E.overflowPages)*E.pageSize}static getStorageStats(){let E=i.env.path,S=GL.default.statfsSync?.(E)??{};return{available:S.bavail*S.bsize,free:S.bfree*S.bsize,size:S.blocks*S.bsize}}static async getRecordCount(E){let S=i.getStats().entryCount,A=1e3/2,N=performance.now(),b=Math.floor(S/2),C=E?.exactCount,O=0,D=0,F;for(let{value:L}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(L!=null&&O++,D++,await cc(),!C&&D<b&&performance.now()-N>A){F=D;break}if(F){let L=O;O=0;for(let{value:X}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:F,snapshot:!1}))X!=null&&O++,await cc();let H=F*2,W=(O+L)/H,ee=Math.pow((O-L+1)/F/2,2)+W*(1-W)/H,oe=Math.max(Math.sqrt(ee)*S,1),B=Math.round(W*S),ue=Math.max(B-1.96*oe,O+L),ae=Math.min(B+1.96*oe,S),ge=Math.pow(10,Math.round(Math.log10(oe)));return ge>B&&(ge=ge/10),O=Math.round(B/ge)*ge,{recordCount:O,estimatedRange:[Math.round(ue),Math.round(ae)]}}return{recordCount:O}}static updatedAttributes(){wr=this.propertyResolvers={$id:o((E,S,A)=>({value:A.key}),"$id"),$updatedtime:o((E,S,A)=>A.version,"$updatedtime"),$updatedTime:o((E,S,A)=>A.version,"$updatedTime"),$expiresAt:o((E,S,A)=>A.expiresAt,"$expiresAt"),$record:o((E,S,A)=>A?{value:E}:E,"$record"),$distance:o((E,S,A)=>A&&(A.distance??S?.vectorDistances?.get(A)),"$distance")};for(let E of this.attributes){E.isPrimaryKey&&(Y=E),E.resolve=null;let S=E.relationship,A=E.computed;if(S)if(E.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,S.to)E.elements?.definition?(wr[E.name]=E.resolve=(N,b,C,O)=>{let D=N[S.from?S.from:t],F=E.elements.definition.tableClass;return O?sf({attribute:S.to,value:D},Cr(b).getReadTxn(),!1,F,!1).map(L=>L&&L.key!==void 0?L:F.primaryStore.getEntry(L,{transaction:Cr(b).getReadTxn()})).asArray:F.search([{attribute:S.to,value:D}],b).asArray},E.set=()=>{},E.resolve.definition=E.elements.definition,E.resolve.to=S.to,S.from&&(E.resolve.from=S.from)):console.error(`The one-to-many/many-to-many relationship property "${E.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(S.from){let N=E.definition||E.elements?.definition;N?(wr[E.name]=E.resolve=(b,C,O,D)=>{let F=b[S.from];if(F!==void 0){if(E.elements){let L,H=F?.map(W=>{let ee=N.tableClass.primaryStore[D?"getEntry":"get"](W,{transaction:Cr(C).getReadTxn()});return ee?.then&&(L=!0),ee});return S.filterMissing?L?Promise.all(H).then(W=>W.filter(z2)):H.filter(z2):L?Promise.all(H):H}return N.tableClass.primaryStore[D?"getEntry":"get"](F,{transaction:Cr(C).getReadTxn()})}},E.set=(b,C)=>{if(Array.isArray(C)){let O=C.map(D=>D.getId?.()||D[N.tableClass.primaryKey]);b[S.from]=O}else{let O=C.getId?.()||C[N.tableClass.primaryKey];b[S.from]=O}},E.resolve.definition=E.definition||E.elements?.definition,E.resolve.from=S.from):console.error(`The relationship property "${E.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${E.name}" in table "${s}" must use either "from" or "to" arguments`);else if(A)typeof A.from=="function"&&this.setComputedAttribute(E.name,A.from),wr[E.name]=E.resolve=(N,b,C)=>{let O=typeof A.from=="string"?N[A.from]:N,D=this.userResolvers[E.name];if(D)return D(O,b,C);xe.default.warn(`Computed attribute "${E.name}" does not have a function assigned to it. Please use setComputedAttribute('${E.name}', resolver) to assign a resolver function.`),this.userResolvers[E.name]=()=>{}},E.resolve.directReturn=!0;else if(r[E.name]?.customIndex?.propertyResolver){let N=r[E.name].customIndex;wr[E.name]=(b,C,O)=>{let D=b[E.name];return N.propertyResolver(D,C,O)},wr[E.name].directReturn=!0}}xm(this,this),xm(cu,this,!0);for(let E of T){let S=E.name;E.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return E.resolve(this,cf.getStore())},set(A){return E.set(this,A)},configurable:!0})}}static setComputedAttribute(E,S){let A=Xi(T,E);if(!A){console.error(`The attribute "${E}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${E}" is not defined as computed in the table "${s}"`);return}this.userResolvers[E]=S}static async deleteHistory(E=0,S=!1){let A;for(let{key:N,value:b}of l.getRange({start:0,end:E}))await cc(),Ut(b).tableId===n&&(A=yR(l,N,b));if(S)for(let N of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:O}=N;await cc(),C===null&&O<E&&(A=Yl(i,N))}await A}static async*getHistory(E=0,S=1/0){for(let{key:A,value:N}of l.getRange({start:E||1,end:S})){await cc();let b=Ut(N);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(E){let S=[];if(E==null)throw new Error("An id is required");let A=i.getEntry(E);if(!A)return S;let N=A.localTime;if(!N)throw new Error("The entry does not have a local audit time");let b=0;do{await cc();let C=l.get(N);if(C){let O=Ut(C);S.push({id:O.recordId,localTime:N,version:O.version,type:O.type,value:O.getValue(i,!0,N),user:O.user}),N=O.previousLocalTime}else break}while(b<1e3&&N);return S.reverse()}static cleanup(){V?.remove()}}Me.updatedAttributes();let wf=Me.prototype;return p&&Me.setTTLExpiration(p/1e3),j&&EE(),Me;function oo(q,E,S){let A;for(let N in r){let b=r[N],C=b.isIndexing,O=wr[N],D=S&&(O?O(S):S[N]),F=E&&(O?O(E):E[N]);if(D===F&&!C)continue;if(b.customIndex){b.customIndex.index(q,D,F);continue}A=!0;let L=b.indexNulls,H=(0,kp.getIndexedValues)(D,L),W=(0,kp.getIndexedValues)(F,L);if(W?.length>0){let ee=new Set(W);if(H=H?H.filter(oe=>{if(ee.has(oe))ee.delete(oe);else return!0}):[],W=Array.from(ee),(W.length>0||H.length>0)&&q2){let oe=W.concat(H).map(B=>({key:B,value:q}));b.prefetch(oe,Y2)}for(let oe=0,B=W.length;oe<B;oe++)b.remove(W[oe],q)}else H?.length>0&&q2&&b.prefetch(H.map(ee=>({key:ee,value:q})),Y2);if(H)for(let ee=0,oe=H.length;ee<oe;ee++)b.put(H[ee],q)}return A}o(oo,"updateIndices");function Or(q){switch(typeof q){case"number":return!0;case"string":if(q.length<659)return!0;if(q.length>V2)throw new Error("Primary key size is too large: "+q.length);break;case"object":if(q===null)throw new Error("Invalid primary key of null");break;case"bigint":if(q<2n**64n&&q>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof q)}if((0,Ql.writeKey)(q,VSe,0)>V2)throw new Error("Primary key size is too large: "+q.length);return!0}o(Or,"checkValidId");function Sr(q){return typeof q=="object"&&q?q.id:q}o(Sr,"requestTargetToId");function Of(q){return typeof q=="object"&&q&&q.isCollection}o(Of,"isSearchTarget");function Es(q){}o(Es,"isRequestTarget");function Tc(q,E,S,A,N){if(Me.getResidencyById&&S.ensureLoaded&&E?.replicateFrom!==!1){let C=wc(Me.getResidencyById(q));if(C&&!C.includes(server.hostname)&&I)return I({key:q,residency:C}).then(N)}let b=o(()=>{if(E?.transaction?.stale&&(E.transaction.stale=!1),S.transaction?.isDone)return N(null,q);let C=i.getEntry(q,S);return C?.residencyId&&C.metadataFlags&Fn&&I&&S.ensureLoaded&&E?.replicateFrom!==!1?I(C).then(O=>N(O,q),O=>(xe.default.error?.("Error loading remote record",q,C,S,O),N(null,q))):(C&&E&&(C?.version>(E.lastModified||0)&&(E.lastModified=C.version),C?.localTime&&!E.lastRefreshed&&(E.lastRefreshed=C.localTime)),N(C,q))},"whenPrefetched");return A?b():se>0?(se--,b()):new Promise((C,O)=>{se===0?(se--,i.prefetch([q],()=>{D(),F()})):(le.push(q),re.push(F),le.length>pE&&(se--,D()));function D(){if(le.length>0){let L=re;i.prefetch(le,()=>{se===-1?D():se++;for(let H of L)H()}),le=[],re=[],_e>2&&_e--}else se=_e,_e<Ty&&_e++}o(D,"prefetch");function F(){try{C(b())}catch(L){O(L)}}o(F,"load")})}o(Tc,"loadLocalRecord");function Rc(q,E){let S=E?.checkPermission;if(typeof S!="object"){if(!q?.role)return;S=q.role.permission}if(S.super_user)return KSe;let A=S[c],N,b=A?.tables;if(b)return b[s];if(c==="data"&&(N=S[s])&&!N.tables)return N}o(Rc,"getTablePermissions");function yc(q,E,S,A){if(P){let N=!1;if(S.noCache?N=!0:(E?(!E.value||E.metadataFlags&(Fn|ac)||E.expiresAt!=null&&E.expiresAt<Date.now())&&(N=!0):N=!0,Vr(!N,"cache-hit",s)),N){let b=lu(q,E,S).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),S&&(C?.version>(S.lastModified||0)&&(S.lastModified=C.version),S.lastRefreshed=Date.now()),C));if(S?.onlyIfCached||E?.value&&A?.allowStaleWhileRevalidate?.(E,q)){if(b.catch(C=>xe.default.warn?.(C)),S?.onlyIfCached&&!A.doesExist())throw new lt.ServerError("Entry is not cached",504);return}else return b}}else if(E?.value&&E.expiresAt!=null&&E.expiresAt<Date.now())return Me.evict(E.key,E.value,E.version),E.value=null,{then(N){return N(E)}}}o(yc,"ensureLoadedFromSource");function Cr(q){let E=q?.transaction;if(E){if(!E.lmdbDb)return E.lmdbDb=i,E;do{if(E.lmdbDb?.path===i.path)return E;let S=E.next;if(!S)return E=E.next=new co,E.lmdbDb=i,E;E=S}while(!0)}else return new ME}o(Cr,"txnForContext");function Ac(q,E,S){if(!q)return;let A=(q.deref?q.deref():q.value)??i.getEntry(q.key)?.value;if(typeof E=="object"){let b=wr,C=A;for(let O=0,D=E.length;O<D;O++){let F=E[O],L=b?.[F];C=L&&C?L(C,S,q):C?.[F],q=null,b=L?.definition?.tableClass?.propertyResolvers}return C}let N=wr[E];return N?N(A,S,q):A[E]}o(Ac,"getAttributeValue");function Cf(q,E,S,A,N){let b=N?.length,C={transaction:A,lazy:b>0||typeof E=="string"||E?.length<4,alwaysPrefetch:!0},O;function D(F,L){let H=F?.value;if(!H)return lc.SKIP;for(let W=0;W<b;W++)if(!O?.includes(W)&&!N[W](H,F))return lc.SKIP;return L!==void 0&&(F.key=L),F}if(o(D,"processEntry"),b>0||!q.hasEntries){let F=q.map(L=>{if(O=null,typeof L=="object"&&L?.key!==void 0)return b>0?D(L):L;if(L==null)return lc.SKIP;for(let H=0;H<b;H++){let ee=N[H].idFilter;if(ee){if(!ee(L))return lc.SKIP;O||(O=[]),O.push(H)}}return Tc(L,S,C,!1,D)});return Array.isArray(q)&&(F=F.filter(L=>L!==lc.SKIP)),F.hasEntries=!0,F}return q}o(Cf,"transformToEntries");function bc(q,E,S=server.replication?.getThisNodeId(l)){if(q<=E?.version){if(E?.version===q&&S!==void 0){let A=server.replication?.exportIdMapping(l),N=E.localTime,b=N&&l.get(N);if(b){let C,O,D=Ut(b);for(let F in A)A[F]===S&&(C=F),A[F]===D.nodeId&&(O=F);if(C>O)return 1;if(C===O)return 0}}return-1}return 1}o(bc,"precedesExistingVersion");async function lu(q,E,S){let A=E?.metadataFlags,N=E?.version,b,C;if(!i.attemptLock(q,N,()=>{clearTimeout(C);let L=i.getEntry(q);!L||!L.value||L.metadataFlags&(Fn|ac)?b(lu(q,i.getEntry(q),S)):b(L)}))return new Promise(L=>{b=L,C=setTimeout(()=>{i.unlock(q,N)},qSe)});let O=E?.value,D={requestContext:S,replacingRecord:O,replacingEntry:E,replacingVersion:N,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},F=S?.responseHeaders;return new Promise((L,H)=>{let W;Ri(Mt(D,async ee=>{let oe=performance.now(),B,ue,ae;try{for(let ne of Me.sources)if(ne.get&&(!ne.get.reliesOnPrototype||ne.prototype.get)){if(ne.available?.(E)===!1)continue;if(D.source=ne,B=await ne.get(q,D),B)break}ae=A&Fn;let X=D.lastModified||ae&&N;ue=ae||X>N||!O,X||(X=(0,kp.getNextMonotonicTime)());let de=performance.now()-oe;if(gt(de,"cache-resolution",s,null,"success"),F&&$m(F,"Server-Timing",`cache-resolve;dur=${de.toFixed(2)}`,!0),ee.timestamp=X,p&&D.expiresAt==null&&(D.expiresAt=Date.now()+p),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=O,X=N;else throw new lt.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==q&&(B[t]=q)}W=!0,L({key:q,version:X,value:B})}catch(X){X.message+=` while resolving record ${q} for ${s}`,O&&((X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(X.statusCode===500||X.statusCode===502||X.statusCode===503||X.statusCode===504))?(L({key:q,version:N,value:O}),xe.default.trace?.(X.message,"(returned stale record)")):H(X);let de=performance.now()-oe;gt(de,"cache-resolution",s,null,"fail"),F&&$m(F,"Server-Timing",`cache-resolve;dur=${de.toFixed(2)}`,!0),D.transaction.abort();return}if(S?.noCacheStore||D.noCacheStore){D.transaction.abort();return}Cr(D).addWrite({key:q,store:i,entry:E,nodeName:"source",commit:o((X,de)=>{if(de?.version!==N)return;let ne=oo(q,O,B);if(B){Fe.put?.(D,q,B),de&&(S.previousResidency=Me.getResidencyRecord(de.residencyId));let he,Ae=!1,Oe,ze=wc(Me.getResidency(B,S));if(ze){if(!ze.includes(server.hostname))if(he=B,Ae=!0,Me.getResidencyById)B=void 0;else{B=null;for(let kr in r)B||(B={}),B[kr]=he[kr]}Oe=fa(ze)}xe.default.trace?.(`Writing resolved record from source with id: ${q}, timestamp: ${new Date(X).toISOString()}`),R(q,B,de,X,Ae?Fn:0,g&&(ue||Ae)||null,{user:D?.user,expiresAt:D.expiresAt,residencyId:Oe},"put",!!ae,he)}else de&&(Fe.delete?.(D,q),xe.default.trace?.(`Deleting resolved record from source with id: ${q}, timestamp: ${new Date(X).toISOString()}`),g||y?R(q,null,de,X,0,g&&ue||null,{user:D?.user},"delete",!!ae):Yl(i,de,N))},"commit")})}),()=>{i.unlock(q,N)},ee=>{i.unlock(q,N),W&&xe.default.error?.("Error committing cache update",ee)})})}o(lu,"getFromSource");function Ic(q){if(!q||q.user?.role?.permission?.super_user)return!0;if(q.replicateTo)throw new lt.ClientError("Can not specify replication parameters without super user permissions",403);if(q.replicatedConfirmation)throw new lt.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Ic,"checkContextPermissions");function da(q){let E=!1;if(q&&(q-_r>1&&(E=!0),_r=q),!(He===pt&&!E)&&(pt=He,(0,zl.getWorkerIndex)()===(0,zl.getWorkerCount)()-1))return gr&&clearTimeout(gr),He?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let N=He/(1+_r),b=E?Date.now():Math.ceil((Date.now()-A.getTime())/N)*N+A.getTime(),C=o(O=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(O)}`),gr=setTimeout(()=>te=te.then(async()=>{if(C(Math.max(O+He,Date.now())),i.rootStore.status!=="open"){clearTimeout(gr);return}let D=50,F=new Array(D),L=0,H=Math.pow(_r,8)*(jl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),W=_/Math.pow(Math.max(_r,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${H}, adjusted eviction ${W}ms`);function ee(oe,B,ue,ae){let ge=oe+W-Date.now();if(ge<0)return!0;if(_r){let X=i.lastSize;return ue&Dn&&pu(ae,de=>{de.size&&(X+=de.size)}),xe.default.trace?.(`shouldEvict adjusted ${ge} ${X}, ${ge*(oe-B)/X} < ${H}`),ge*(oe-B)/X<H}return!1}o(ee,"shouldEvict");try{let oe=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:ue,value:ae,version:ge,expiresAt:X,metadataFlags:de}=B,ne;ae===null&&!g&&ge+GSe<Date.now()?ne=Yl(i,B,ge):X!=null&&ee(X,ge,de,ae)&&(ne=Me.evict(ue,ae,ge),oe++),ne&&(await F[L],F[L]=ne.catch(he=>{xe.default.error?.("Cleanup error",he)}),++L>=D&&(L=0)),await cc()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${oe} entries`)}catch(oe){xe.default.warn?.(`Error in cleanup scan for ${s}:`,oe)}S(void 0),_r=0}),Math.min(O-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}o(da,"scheduleCleanup");function Nc(){V=l?.addDeleteRemovalCallback(n,i,(q,E)=>{i.remove(q,E)})}o(Nc,"addDeleteRemoval");function EE(){(0,zl.getWorkerIndex)()===0&&setInterval(async()=>{if(!au){au=!0;try{let q=j.name,E=r[q];if(!E)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let S of E.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of E.getValues(S)){let N=i.getEntry(A);N?.value?N.value[q]<Date.now()&&Me.evict(A,N.value,N.version):i.ifVersion(A,N?.version,()=>E.remove(S,A))}await cc()}}catch(q){xe.default.error?.("Error in evicting old records",q)}finally{au=!1}}},kSe).unref()}o(EE,"runRecordExpirationEviction");function wc(q){if(q!=null){if(Array.isArray(q))return q;if(typeof q=="number"){if(q>=65536)throw new Error(`Shard id ${q} must be below 65536`);let E=server.shards?.get?.(q);if(E)return xe.default.trace?.(`Shard ${q} mapped to ${E.map(S=>S.name).join(", ")}`),E.map(S=>S.name);throw new Error(`Shard ${q} is not defined`)}throw new Error(`Shard or residency list ${q} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(wc,"residencyFromFunction");function fa(q){if(q){let E=q.join(","),S=d.get([Symbol.for("residency_by_set"),E]);return S||(d.put([Symbol.for("residency_by_set"),E],S=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),S],q),S)}}o(fa,"getResidencyId")}function kL(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 Y2(){}function YC(e){J2=e}function MR(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 DR(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return DR(+e);case"Float":return e==="null"?null:DR(+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;YSe.test(e)||(e+="Z");let n=new Date(e);return DR(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,vR.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function DR(e){if(isNaN(e))throw new SyntaxError;return e}function W2(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 Ri(e,t,r){return e?.then?e.then(t,r):t(e)}function z2(e){return e!=null}function Gs(e){try{return JSON.stringify(e)}catch{return e}}function WSe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var lc,kp,j2,Q2,jl,lt,Gp,qp,xe,Ql,zl,vR,GL,BSe,FSe,HSe,J2,kSe,GSe,q2,qSe,$2,$Se,Fn,ac,VSe,V2,K2,KSe,QBe,YSe,cc,op=fe(()=>{k();lc=require("lmdb"),kp=w(Rn()),j2=w(require("lodash")),Q2=w(qf());wa();Vf();jl=w(ce());CN();lt=w(Ee()),Gp=w(yo()),qp=w(ti());Le();ig();xe=w(Ii());pI();Dc();Ql=require("ordered-binary"),zl=w(st());Io();vR=w(ie());kc();Fi();U_();Vm();GL=w(require("node:fs"));Ss();gR();({sortBy:BSe}=j2.default),{validateAttribute:FSe}=Q2.default,HSe=new Uint8Array(9);HSe[8]=192;kSe=6e4,GSe=864e5;jl.initSync();q2=jl.get(U.STORAGE_PREFETCHWRITES),qSe=1e4,$2=1,$Se=2,Fn=1,ac=8,VSe=Buffer.allocUnsafeSlow(8192),V2=1978,K2=100,KSe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},QBe=(0,vR.convertToMS)(jl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(UR,"makeTable");o(kL,"attributesAsObject");o(Y2,"noop");o(YC,"setServerUtilities");YSe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(MR,"coerceType");o(DR,"rejectNaN");o(W2,"isDescendantId");cc=o(()=>new Promise(setImmediate),"rest");o(Ri,"when");o(z2,"exists");o(Gs,"stringify");o(WSe,"hasOtherProcesses")});function xR(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Euclidean distance comparison requires an array");let r=0,n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let i=e[s]||0,a=t[s]||0,c=i-a;r+=c*c}return r}function BR(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let a=0;a<i;a++){let c=e[a]||0,l=t[a]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var X2=fe(()=>{o(xR,"euclideanDistance");o(BR,"cosineDistance")});var Z2,eQ,uf,Zi,lf,zSe,jSe,FR,tQ=fe(()=>{X2();Z2=require("msgpackr"),eQ=w(Ii()),uf=w(Ee()),Zi=(0,eQ.loggerWithTag)("HNSW"),lf=Symbol.for("entryPoint"),zSe=Symbol.for("key"),jSe=10,FR=class{static{o(this,"HierarchicalNavigableSmallWorld")}static useObjectStore=!0;indexStore;M=16;efConstruction=100;efConstructionSearch=50;mL=1/Math.log(this.M);optimizeRouting=.5;nodesVisitedCount=0;idIncrementer;distance;constructor(t,r){this.indexStore=t,t&&(this.indexStore.encoder.useFloat32=Z2.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?xR:BR,r&&(r.M!==void 0&&(this.M=r.M,this.mL=1/Math.log(this.M)),r.efConstruction!==void 0&&(this.efConstruction=this.efConstructionSearch=r.efConstruction),r.efConstructionSearch!==void 0&&(this.efConstructionSearch=r.efConstructionSearch),r.mL!==void 0&&(this.mL=r.mL),r.optimizeRouting!==void 0&&(this.optimizeRouting=r.optimizeRouting))}index(t,r,n){let s=typeof t=="number"?[zSe,t]:t,i=this.indexStore.get(s);if(!i){if(!r)return;if(!this.idIncrementer){let f=0;for(let m of this.indexStore.getKeys({reverse:!0,limit:1,start:1/0,end:0}))typeof m=="number"&&(f=m);this.idIncrementer=new BigInt64Array([BigInt(f)+1n]),this.idIncrementer=new BigInt64Array(this.indexStore.getUserSharedBuffer("next-id",this.idIncrementer.buffer))}i=Number(Atomics.add(this.idIncrementer,0,1n)),this.indexStore.put(s,i)}let a=new Map,c,l=this.indexStore.get(lf);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let _=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:_,primaryKey:t};for(let y=0;y<=_;y++)g[y]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);Zi.debug?.("setting entry point to",i),this.indexStore.put(lf,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),jSe),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);Zi.debug?.("setting entry point to",i),this.indexStore.put(lf,i)}for(;h>m;){let _=this.searchLayer(r,l,f,this.efConstruction,h);_.length>0&&(l=_[0].id,f=_[0].node),h--}let p=new Array(m+1);for(let _=0;_<=m;_++)p[_]=[];for(let _=Math.min(m,h);_>=0;_--){let g=this.searchLayer(r,l,f,this.efConstruction,_);g=g.slice(0,this.M<<1),g.length===0&&_===0&&Zi.info?.("should not have zero connections for",l);let y=p[_];for(let T=0;T<g.length;T++){let{id:R,distance:I,node:P}=g[T];if(R===i)continue;let Y=[];if(this.optimizeRouting){let $=!1,j=P[_],V=1+this.optimizeRouting*(1+.5*T/this.M);for(let le=0;le<j.length;le++){let{id:re,distance:se}=j[le],_e=1+this.optimizeRouting*(1+.5*le/this.M);for(let Ne=0;Ne<y.length;Ne++){let{id:Fe,distance:He}=y[Ne];if(Fe===re){I*V>He+se?$=!0:se*_e>I+He&&(Y.push({fromId:Fe,toId:R}),Y.push({fromId:R,toId:Fe}));break}}if($)break}if($)continue}else if(T>=(_>0?this.M:this.M<<1))continue;y.push({id:R,distance:I});for(let{fromId:$,toId:j}of Y){let V=d($);V||(V=d($,this.indexStore.get($)));for(let le=0;le<V[_].length;le++)if(V[_][le].id===j){Object.isFrozen(V[_])&&(V[_]=V[_].slice()),V[_].splice(le,1);break}}let te=c[_],x=te?.find(({id:$})=>$===R);if(x){let $=te?.indexOf(x);te.copied||(te=[...te],te.copied=!0,c[_]=te),te.splice($,1)}else this.addConnection(R,d(R,P),i,_,I,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...p})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m][0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:h,value:p}of this.indexStore.getRange({start:0,end:1/0}))if(p.level>m){if(l=h,p.level===f)break;m=p.level}}if(l===void 0)this.indexStore.remove(lf);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);Zi.debug?.("setting entry point to",l),this.indexStore.put(lf,l)}}this.indexStore.remove(i)}let u=new Map;if(c.level!==void 0)for(let f=0;f<=c.level;f++){let m=c[f];for(let{id:h}of m){let p=d(h,this.indexStore.get(h));for(let _=0;_<=f;_++)p[_]=p[_]?.filter(({id:g})=>g!==i),p[_].length===0&&(Zi.info?.("node was left orphaned, will reindex",h),u.set(p.primaryKey,p.vector))}}function d(f,m){let h=a.get(f);return!h&&m&&(h={...m},a.set(f,h)),h}o(d,"updateNode");for(let[f,m]of a)this.indexStore.put(f,m);for(let[f,m]of u)this.index(f,m,m);this.checkSymmetry(i,this.indexStore.get(i))}getEntryPoint(){let t=this.indexStore.get(lf);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,a=this.distance){let c=new Set([r]),l=[{id:r,distance:this.distance(t,n.vector),node:n}],u=[...l];for(;l.length>0;){l.sort((h,p)=>h.distance-p.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:h}of m[i]||[]){if(c.has(h)||h===void 0)continue;c.add(h);let p=this.indexStore.get(h);if(!p)continue;this.nodesVisitedCount++;let _=a(t,p.vector);if(_<f||u.length<s){let g={id:h,distance:_,node:p};l.push(g),u.push(g)}}u.sort((h,p)=>h.distance-p.distance),u.length>s&&u.splice(s,u.length-s)}return u.visited=c.size,u}search({target:t,value:r,descending:n,distance:s,comparator:i}){let a=0;switch(i){case"lt":case"le":a=r;case"sort":break;default:throw new uf.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new uf.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=BR;else if(s==="euclidean")c=xR;else{if(s)throw new uf.ClientError("Unknown distance function");c=this.distance}if(!t)throw new uf.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new uf.ClientError("The target vector must be an array");let l=this.getEntryPoint();if(!l)return[];let u=l.id,d=[];for(let f=l.level;f>=0;f--)if(d=this.searchLayer(t,u,l,this.efConstructionSearch,f,c),d.length>0){let m=d[0];l=m.node,u=m.id}return a&&(d=d.filter(f=>f.distance<a)),d.map(f=>({key:f.node.primaryKey,distance:f.distance}))}checkSymmetry(t,r){if(!r)return;let n=0,s;for(;(s=r[n])&&s.length!==0;){for(let{id:i}of s){let a=this.indexStore.get(i);if(!a){Zi.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||Zi.info?.("asymmetry detected",a[n])}n++}}addConnection(t,r,n,s,i,a){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){Zi.warn?.("maxConnections reached, removing some connections",c);let l=[...r[s]];l.sort((f,m)=>f.distance-m.distance);let u=l.slice(0,c),d=l.slice(c);r[s]=u;for(let f of d){let m=a(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=a(f.id,m),m[s]=m[s].filter(({id:h})=>h!==t),s===0&&m[s].length===0&&Zi.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?Zi.debug?.("already connected",t,n):r[s]=[...r[s],{id:n,distance:i}]}validateConnectivity(t=0){let r=this.getEntryPoint(),n=new Set,s=[r.id];n.add(r.id);let i=0;for(;s.length>0;){let a=s.shift(),c=this.indexStore.get(a);for(let l=t;l<=c.level;l++)for(let{id:u}of c[l]||[])i++,n.has(u)||(n.add(u),s.push(u))}return n.size!==this.totalNodes&&console.log("visited",n.size,"total",this.totalNodes),{isFullyConnected:n.size===this.totalNodes,averageConnections:i/n.size}}get totalNodes(){return Array.from(this.indexStore.getKeys({start:0,end:1/0})).length}estimateCountAsSort(){return Math.sqrt(this.indexStore.getStats().entryCount*this.efConstructionSearch)}propertyResolver(t,r,n){let s=r?.sort;if(s){let i=s.vectorDistances;if(i){let l=i.get(n);if(l)return l}else i=r.vectorDistances=s.vectorDistances=new Map;let a=this.distance;s.type&&(a=s.distance==="euclidean"?xR:BR);let c=a(s.target,t);return i.set(n,c),c}return t}}});var qL,rQ=fe(()=>{tQ();qL={HNSW:FR}});var ft={};Ce(ft,{database:()=>Mu,databaseEnvs:()=>Jo,databases:()=>Ge,dropDatabase:()=>TI,dropTableMeta:()=>eTe,getDatabases:()=>it,getDefaultCompression:()=>LS,getTables:()=>QSe,onRemovedDB:()=>dh,onUpdatedTable:()=>Rl,readMetaDb:()=>$p,resetDatabases:()=>Od,table:()=>Ze,tables:()=>cn});function QSe(){return qR||it(),cn||{}}function it(){if(qR)return Ge;qR=!0,mf=new Map;let e=(0,zt.getHdbBasePath)()&&(0,xt.join)((0,zt.getHdbBasePath)(),Pc),t=(0,zt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(U.STORAGE_PATH)||e&&((0,cs.existsSync)(e)?e:(0,xt.join)((0,zt.getHdbBasePath)(),yE)),!e)return;if((0,cs.existsSync)(e))for(let n of(0,cs.readdirSync)(e,{withFileTypes:!0})){let s=(0,xt.basename)(n.name,".mdb");n.isFile()&&(0,xt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&$p((0,xt.join)(e,n.name),null,s)}if((0,cs.existsSync)((0,ff.getBaseSchemaPath)())){for(let n of(0,cs.readdirSync)((0,ff.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,xt.join)((0,ff.getBaseSchemaPath)(),n.name),i=(0,xt.join)((0,ff.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,cs.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,xt.extname)(a.name).toLowerCase()===".mdb"){let c=(0,xt.join)(i,a.name);$p((0,xt.join)(s,a.name),(0,xt.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,cs.existsSync)(i))for(let c of(0,cs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,xt.extname)(c.name).toLowerCase()===".mdb"&&$p((0,xt.join)(i,c.name),(0,xt.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,xt.join)(l.path,(0,xt.basename)(c+".mdb"));(0,cs.existsSync)(u)&&$p(u,c,n,null,!0)}}for(let n in Ge){let s=mf.get(n);if(s){let i=Ge[n];n.includes("delete")&&Ir.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Ir.trace(`delete table class ${a}`),delete i[a])}else if(delete Ge[n],n==="data"){for(let i in cn)delete cn[i];delete cn[$R]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,zt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(Ge.system?.hdb_analytics?.enableAuditing(),Ge.system?.hdb_analytics_hostname?.enableAuditing()),Ge.system)for(let n of r)Ge.system[n]&&(Ge.system[n].replicate=!1);return mf=null,Ge}function Od(){qR=!1;for(let[,e]of Jo)e.needsDeletion=!0;it();for(let[e,t]of Jo)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),Jo.delete(e);let r=Ge[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Ge[t.databaseName],Kp.forEach(i=>i(t.databaseName));break}}return Ge}function $p(e,t,r=KL,n,s){let i=new $L.default(e,!1);try{let a=Jo.get(e);a?a.needsDeletion=!1:(a=(0,hf.open)(i),Jo.set(e,a));let c=new pf.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(HR.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,cs.existsSync)(n)&&(i.path=n,u=(0,hf.open)(i),u.isLegacy=!0):u=RR(a));let d=aQ(r),f=d[$R],m=new Map;for(let{key:h,value:p}of l.getRange({start:!1})){let[_,g]=h.toString().split("/");g===""?g=p.name:g||(g=_,_=t,p.name||(p.name=g,p.indexed=!p.is_hash_attribute)),f?.add(_);let y=m.get(_);y||m.set(_,y={attributes:[]}),(g==null||p.is_hash_attribute)&&(y.primary=p),g!=null&&y.attributes.push(p),Object.defineProperty(p,"key",{value:h,configurable:!0})}for(let[h,p]of m){let{attributes:_,primary:g}=p;if(!g){for(let se of _)if(se.is_hash_attribute||se.isPrimaryKey){g=se;break}if(!g){Ir.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(_)}`);continue}}let y=d[h],T={},R=[],I,P,Y=typeof g.audit=="boolean"?g.audit:(0,zt.get)(U.LOGGING_AUDITLOG),te=g.trackDeletes,x=g.expiration,$=g.eviction,j=g.sealed,V=g.splitSegments,le=g.replicate;if(y)T=y.indices,R=y.attributes,y.schemaVersion++;else{I=g.tableId,I?I>=(l.get(df)||0)&&(l.putSync(df,I+1),Ir.info(`Updating next table id (it was out of sync) to ${I+1} for ${h}`)):(g.tableId=I=l.get(df),I||(I=1),Ir.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(df,I+1),l.putSync(g.key,g));let se=new pf.default(!g.is_hash_attribute,g.is_hash_attribute);if(se.compression=g.compression,se.compression){let _e=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||oQ;se.compression.threshold=_e}P=wR(a.openDB(g.key,se),a),a.databaseName=r,P.tableId=I}let re;for(let se of _){se.attribute=se.name;try{if(!se.is_hash_attribute&&(se.indexed||se.attribute&&!se.name)){if(!T[se.name]){let Ne=lQ(se.key,a,se);T[se.name]=Ne,T[se.name].indexNulls=se.indexNulls}let _e=R.find(Ne=>Ne.name===se.name);_e?R.splice(R.indexOf(_e),1,se):R.push(se),re=!0}}catch(_e){Ir.error("Error trying to update attribute",se,R,T,_e)}}for(let se of R)if(!_.find(Ne=>Ne.name===se.name)){if(se.is_hash_attribute){Ir.error("Unable to remove existing primary key attribute",se);continue}se.indexed&&(R.splice(R.indexOf(se),1),re=!0)}if(y)re&&(y.schemaVersion++,y.updatedAttributes());else{y=cQ(d,h,UR({primaryStore:P,auditStore:u,audit:Y,sealed:j,splitSegments:V,replicate:le,expirationMS:x&&x*1e3,evictionMS:$&&$*1e3,trackDeletes:te,tableName:h,tableId:I,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:_,schemaDefined:g.schemaDefined,dbisDB:l})),y.schemaVersion=1;for(let se of Vp)se(y)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function aQ(e){let t=Ge[e];if(t||(e==="data"?t=Ge[e]=cn:e==="system"?Object.defineProperty(Ge,"system",{value:t=Object.create(null),configurable:!0}):t=Ge[e]=Object.create(null)),mf&&!mf.has(e)){let r=new Set;t[$R]=r,mf.set(e,r)}return t}function cQ(e,t,r){return e[t]=r,r}function Mu({database:e,table:t}){e||(e=KL),it();let r=aQ(e),n=(0,xt.join)((0,zt.getHdbBasePath)(),Pc),s=(0,zt.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,zt.get)(U.STORAGE_PATH)||((0,cs.existsSync)(n)?n:(0,xt.join)((0,zt.getHdbBasePath)(),yE));let a=(0,xt.join)(n,(i?t:e)+".mdb"),c=Jo.get(a);if(!c||c.status==="closed"){let l=new $L.default(a,!1);c=(0,hf.open)(l),Jo.set(a,c)}return c.auditStore||(c.auditStore=RR(c)),c}async function TI(e){if(!Ge[e])throw new Error("Schema does not exist");let t=Ge[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Jo.delete(r.path),r.status==="open"&&(await r.close(),await Yp.remove(r.path));if(r||(r=Mu({database:e,table:null}),r.status==="open"&&(await r.close(),await Yp.remove(r.path))),e==="data"){for(let n in cn)delete cn[n];delete cn[$R]}delete Ge[e],Kp.forEach(n=>n(e)),await iA(r)}function lQ(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&qL[r.indexed.type]?.useObjectStore,s=new pf.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=qL[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Ir.error(`The indexing type '${r.indexed.type}' is unknown`)}return i}function Ze(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:a,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:h}=e;r||(r=KL);let p=Mu({database:r,table:t}),_=Ge[r];Ir.trace(`Defining ${t} in ${r}`);let g=_?.[t];if(p.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let y,T,R;m==null&&(m=!0);let I=new pf.default(!1);for(let V of a)V.attribute&&!V.name?(V.name=V.attribute,V.indexed=!0):V.attribute=V.name,V.expiresAt&&(V.indexed=!0);let P,Y;if(g){if(y=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,...a)}else{let V=p.auditStore;T=a.find(_e=>_e.isPrimaryKey)||{},y=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=LS(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,zt.get)(U.LOGGING_AUDITLOG),n&&(T.expiration=n),s&&(T.eviction=s),u??=!1,T.splitSegments=u,typeof l=="boolean"&&(T.sealed=l),typeof d=="boolean"&&(T.replicate=d),h&&(T.origins?T.origins.includes(h)||T.origins.push(h):T.origins=[h]),Ir.trace(`${t} table loading, opening primary store`);let le=new pf.default(!1,!0);le.compression=T.compression;let re=t+"/";if(R=p.dbisDb=p.openDB(HR.INTERNAL_DBIS_NAME,I),j(),R.get(re))return Y&&Y(),Od(),Ze(e);let se=wR(p.openDB(re,le),p);p.databaseName=r,se.tableId=R.get(df),Ir.trace(`Assigning new table id ${se.tableId} for ${t}`),se.tableId||(se.tableId=1),R.put(df,se.tableId+1),T.tableId=se.tableId,g=cQ(_,t,UR({primaryStore:se,auditStore:V,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:y,tableName:t,tableId:se.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:R})),g.schemaVersion=1,P=!0,R.put(re,T)}let te=g.indices;R=R||(p.dbisDb=p.openDB(HR.INTERNAL_DBIS_NAME,I)),g.dbisDB=R;let x=[];for(let{key:V,value:le}of R.getRange({start:!0})){let[re,se]=V.toString().split("/");if(se===""&&(se=le.name),se){if(re!==t)continue}else continue;let _e=a.find(Fe=>Fe.name===se),Ne=!_e?.indexed&&le.indexed&&!le.isPrimaryKey;if((!_e||Ne)&&(j(),P=!0,_e||R.remove(V),Ne)){let Fe=g.indices[re];Fe&&x.push(Fe)}}let $=[];try{for(let V of a||[]){if((V.relationship||V.computed)&&(P=!0,V.relationship))continue;let le=t+"/"+(V.name||"");Object.defineProperty(V,"key",{value:le,configurable:!0});let re=R.get(le);if(V.isPrimaryKey){if(re=re||R.get(le=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+re.expiration||void 0)||(+s||void 0)!==(+re.eviction||void 0)||V.type!==re.type){let _e={...re};typeof c=="boolean"&&(c&&g.enableAuditing(c),_e.audit=c),n&&(_e.expiration=+n),s&&(_e.eviction=+s),l!==void 0&&(_e.sealed=l),d!==void 0&&(_e.replicate=d),V.type&&(_e.type=V.type),P=!0,j(),R.put(le,_e)}continue}re?.attribute&&!re.name&&(re.indexed=!0);let se=!re||re.type!==V.type||JSON.stringify(re.indexed)!==JSON.stringify(V.indexed)||re.nullable!==V.nullable||re.version!==V.version||JSON.stringify(re.properties)!==JSON.stringify(V.properties)||JSON.stringify(re.elements)!==JSON.stringify(V.elements);if(V.indexed){let _e=lQ(le,p,V);(se||re.indexingPID&&re.indexingPID!==process.pid||re.restartNumber<Wp.workerData?.restartNumber)&&(P=!0,j(),re=R.get(le),(se||re.indexingPID&&re.indexingPID!==process.pid||re.restartNumber<Wp.workerData?.restartNumber)&&(P=!0,V.indexNulls===void 0&&(V.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(V.lastIndexedKey=re?.lastIndexedKey??void 0,V.indexingPID=process.pid,_e.isIndexing=!0,Object.defineProperty(V,"dbi",{value:_e}),$.push(V))),R.put(le,V)),re?.indexNulls&&V.indexNulls===void 0&&(V.indexNulls=!0),_e.indexNulls=V.indexNulls,te[V.name]=_e}else se&&(P=!0,j(),R.put(le,V))}}finally{Y&&Y()}if(P&&(g.schemaVersion++,g.updatedAttributes()),Ir.trace(`${t} table loading, running index`),$.length>0||x.length>0?g.indexingOperation=ZSe(g,$,x):P&&kR.signalSchemaChange(new GR.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,P)for(let V of Vp)V(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Ir.trace(`${t} table loaded`),g;function j(){Y||p.transactionSync(()=>({then(V){Y=V}}))}o(j,"startTxn")}async function ZSe(e,t,r){try{Ir.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await kR.signalSchemaChange(new GR.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,a={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,hf.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,h,()=>{for(let p=0;p<l;p++){let _=t[p],g=_.name,y=_.dbi;try{let T=_.resolve,R=m&&(T?T(m):m[g]);if(y.customIndex){y.customIndex.index(f,R);continue}let I=(0,nQ.getIndexedValues)(R);if(I)for(let P=0,Y=I.length;P<Y;P++)y.put(I[P],f)}catch(T){a[g]||(a[g]=!0,Ir.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Ir.error(p)}),Wp.workerData&&Wp.workerData.restartNumber!==iQ.restartNumber&&(i=!0),++c%100===0||i){for(let p of t)p.lastIndexedKey=f,e.dbisDB.put(p.key,p);if(i)return}d>JSe?await s:d>XSe&&await new Promise(p=>setImmediate(p))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await kR.signalSchemaChange(new GR.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Ir.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Ir.error("Error in indexing",n)}}function eTe({table:e,database:t}){let r=Mu({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 Rl(e){return Vp.push(e),{remove(){let t=Vp.indexOf(e);t>-1&&Vp.splice(t,1)}}}function dh(e){return Kp.push(e),{remove(){let t=Kp.indexOf(e);t>-1&&Kp.splice(t,1)}}}function LS(){let e=(0,zt.get)(U.STORAGE_COMPRESSION),t=(0,zt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||oQ,n={startingOffset:32};return t&&(n.dictionary=Yp.readFileSync(t)),r&&(n.threshold=r),e&&n}var zt,HR,hf,xt,cs,ff,pf,$L,Yp,VL,nQ,kR,GR,Wp,sQ,iQ,Ir,KL,$R,oQ,cn,Ge,df,Vp,Kp,qR,Jo,mf,JSe,XSe,Le=fe(()=>{zt=w(ce()),HR=w(kt()),hf=require("lmdb"),xt=require("path"),cs=require("fs"),ff=w(yt());op();pf=w(rm()),$L=w(nm());k();Yp=w(require("fs-extra")),VL=w(Ws()),nQ=w(Rn()),kR=w(yo()),GR=w(ti()),Wp=require("worker_threads"),sQ=w(z()),iQ=w(st());Io();kc();Ss();rQ();Ir=(0,sQ.forComponent)("storage"),KL="data",$R=Symbol("defined-tables"),oQ=((0,zt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,zt.initSync)();cn=Object.create(null),Ge=Object.create(null);(0,VL._assignPackageExport)("databases",Ge);(0,VL._assignPackageExport)("tables",cn);df=Symbol.for("next-table-id"),Vp=[],Kp=[],Jo=new Map;o(QSe,"getTables");o(it,"getDatabases");o(Od,"resetDatabases");o($p,"readMetaDb");o(aQ,"ensureDB");o(cQ,"setTable");o(Mu,"database");o(TI,"dropDatabase");o(lQ,"openIndex");o(Ze,"table");JSe=1e3,XSe=10;o(ZSe,"runIndexing");o(eTe,"dropTableMeta");o(Rl,"onUpdatedTable");o(dh,"onRemovedDB");o(LS,"getDefaultCompression")});var ie=M(be=>{"use strict";var uc=require("path"),hQ=require("fs-extra"),kn=z(),uQ=require("fs-extra"),VR=require("os"),tTe=require("net"),rTe=require("recursive-iterator"),Nr=(k(),v(K)),{PACKAGE_ROOT:nTe}=Rt(),sTe=Hy(),dQ=require("papaparse"),KR=require("moment"),{inspect:iTe}=require("util"),fQ=require("is-number"),oTe=require("minimist"),aTe=require("https"),cTe=require("http"),lTe=/^((\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)))$/,pQ=require("util").promisify(setTimeout),uTe=100,dTe=5,fTe="",mTe=4,mQ={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};be.isEmpty=ls;be.isEmptyOrZeroLength=eo;be.arrayHasEmptyValues=ETe;be.arrayHasEmptyOrZeroLengthValues=_Te;be.buildFolderPath=gTe;be.isBoolean=EQ;be.errorizeMessage=hTe;be.stripFileExtension=TTe;be.autoCast=RTe;be.autoCastJSON=_Q;be.autoCastJSONDeep=WL;be.removeDir=yTe;be.compareVersions=ATe;be.isCompatibleDataVersion=bTe;be.escapeRawValue=ITe;be.unescapeValue=NTe;be.stringifyProps=wTe;be.timeoutPromise=CTe;be.isClusterOperation=LTe;be.getClusterUser=MTe;be.checkGlobalSchemaTable=DTe;be.getHomeDir=SQ;be.getPropsFilePath=OTe;be.promisifyPapaParse=vTe;be.removeBOM=TQ;be.createEventPromise=UTe;be.checkProcessRunning=xTe;be.checkSchemaTableExist=BTe;be.checkSchemaExists=RQ;be.checkTableExists=yQ;be.getStartOfTomorrowInSeconds=FTe;be.getLimitKey=HTe;be.isObject=STe;be.isNotEmptyAndHasValue=pTe;be.autoCasterIsNumberCheck=gQ;be.backtickASTSchemaItems=kTe;be.isPortTaken=PTe;be.createForkArgs=GTe;be.autoCastBoolean=qTe;be.asyncSetTimeout=pQ;be.getTableHashAttribute=$Te;be.doesSchemaExist=VTe;be.doesTableExist=KTe;be.stringifyObj=YTe;be.ms_to_time=WTe;be.changeExtension=zTe;be.getEnvCliRootPath=zL;be.noBootFile=jTe;be.httpRequest=QTe;be.transformReq=JTe;be.convertToMS=XTe;be.PACKAGE_ROOT=nTe;function hTe(e){return e instanceof Error?e:new Error(e)}o(hTe,"errorizeMessage");function ls(e){return e==null}o(ls,"isEmpty");function pTe(e){return!ls(e)&&(e||e===0||e===""||EQ(e))}o(pTe,"isNotEmptyAndHasValue");function eo(e){return ls(e)||e.length===0||e.size===0}o(eo,"isEmptyOrZeroLength");function ETe(e){if(ls(e))return!0;for(let t=0;t<e.length;t++)if(ls(e[t]))return!0;return!1}o(ETe,"arrayHasEmptyValues");function _Te(e){if(eo(e))return!0;for(let t=0;t<e.length;t++)if(eo(e[t]))return!0;return!1}o(_Te,"arrayHasEmptyOrZeroLengthValues");function gTe(...e){try{return e.join(uc.sep)}catch{console.error(e)}}o(gTe,"buildFolderPath");function EQ(e){return ls(e)?!1:e===!0||e===!1}o(EQ,"isBoolean");function STe(e){return ls(e)?!1:typeof e=="object"}o(STe,"isObject");function TTe(e){return eo(e)?fTe:e.slice(0,-mTe)}o(TTe,"stripFileExtension");function RTe(e){return ls(e)||e===""||typeof e!="string"?e:mQ[e]!==void 0?mQ[e]:gQ(e)===!0?Number(e):lTe.test(e)?new Date(e):e}o(RTe,"autoCast");function _Q(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(_Q,"autoCastJSON");function WL(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=WL(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=WL(r);n!==r&&(e[t]=n)}return e}else return _Q(e)}o(WL,"autoCastJSONDeep");function gQ(e){if(e.startsWith("0.")&&fQ(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&fQ(e))}o(gQ,"autoCasterIsNumberCheck");async function yTe(e){if(eo(e))throw new Error(`Directory path: ${e} does not exist`);try{await uQ.emptyDir(e),await uQ.remove(e)}catch(t){throw kn.error(`Error removing files in ${e} -- ${t}`),t}}o(yTe,"removeDir");function ATe(e,t){if(eo(e)){kn.info("Invalid current version sent as parameter.");return}if(eo(t)){kn.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,a=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(a[u],10)-parseInt(c[u],10),r)return r;return a.length-c.length}o(ATe,"compareVersions");function bTe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}o(bTe,"isCompatibleDataVersion");function ITe(e){if(ls(e))return e;let t=String(e);return t==="."?Nr.UNICODE_PERIOD:t===".."?Nr.UNICODE_PERIOD+Nr.UNICODE_PERIOD:t.replace(Nr.FORWARD_SLASH_REGEX,Nr.UNICODE_FORWARD_SLASH)}o(ITe,"escapeRawValue");function NTe(e){if(ls(e))return e;let t=String(e);return t===Nr.UNICODE_PERIOD?".":t===Nr.UNICODE_PERIOD+Nr.UNICODE_PERIOD?"..":String(e).replace(Nr.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(NTe,"unescapeValue");function wTe(e,t){if(ls(e))return kn.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let a of i)r+=";"+a+VR.EOL}!eo(n)&&n[0]===";"?r+=" "+n+s+VR.EOL:eo(n)||(r+=n+"="+s+VR.EOL)}catch{kn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}o(wTe,"stringifyProps");function SQ(){let e;try{e=VR.homedir()}catch{e=process.env.HOME}return e}o(SQ,"getHomeDir");function OTe(){let e=uc.join(SQ(),Nr.HDB_HOME_DIR_NAME,Nr.BOOT_PROPS_FILE_NAME);return hQ.existsSync(e)||(e=uc.join(__dirname,"../","hdb_boot_properties.file")),e}o(OTe,"getPropsFilePath");function CTe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:o(function(){clearTimeout(r)},"cancel")}}o(CTe,"timeoutPromise");async function PTe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=tTe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}o(PTe,"isPortTaken");function LTe(e){try{return Nr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){kn.error(`Error checking operation against cluster ops ${t}`)}return!1}o(LTe,"isClusterOperation");function DTe(e,t){let r=(Le(),v(ft)).getDatabases();if(!r[e])return YR.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return YR.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(DTe,"checkGlobalSchemaTable");function MTe(e,t){if(ls(t)){kn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ls(e)||eo(e)){kn.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){kn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){kn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}o(MTe,"getClusterUser");function vTe(){dQ.parsePromise=function(e,t,r){return new Promise(function(n,s){dQ.parse(e,{header:!0,transformHeader:TQ,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}o(vTe,"promisifyPapaParse");function TQ(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o(TQ,"removeBOM");function UTe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;kn.info(`Got cluster status event response: ${iTe(s)}`);try{i.cancel()}catch{kn.error("Error trying to cancel timeout.")}n(s)})})}o(UTe,"createEventPromise");async function xTe(e){let t=!0,r=0;do await pQ(uTe*r++),(await sTe.findPs(e)).length>0&&(t=!1);while(t&&r<dTe);if(t)throw new Error(`process ${e} was not started`)}o(xTe,"checkProcessRunning");function BTe(e,t){let r=RQ(e);if(r)return r;let n=yQ(e,t);if(n)return n}o(BTe,"checkSchemaTableExist");function RQ(e){let{getDatabases:t}=(Le(),v(ft));if(!t()[e])return YR.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(RQ,"checkSchemaExists");function yQ(e,t){let{getDatabases:r}=(Le(),v(ft));if(!r()[e][t])return YR.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(yQ,"checkTableExists");function FTe(){let e=KR().utc().add(1,"d").startOf("d").unix(),t=KR().utc().unix();return e-t}o(FTe,"getStartOfTomorrowInSeconds");function HTe(){return KR().utc().format("DD-MM-YYYY")}o(HTe,"getLimitKey");function kTe(e){try{let t=new rTe(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){kn.error("Got an error back ticking items."),kn.error(t)}}o(kTe,"backtickASTSchemaItems");function GTe(e){return[e]}o(GTe,"createForkArgs");function qTe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(qTe,"autoCastBoolean");function $Te(e,t){let{getDatabases:r}=(Le(),v(ft)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}o($Te,"getTableHashAttribute");function VTe(e){let{getDatabases:t}=(Le(),v(ft));return t()[e]!==void 0}o(VTe,"doesSchemaExist");function KTe(e,t){let{getDatabases:r}=(Le(),v(ft));return r()[e]?.[t]!==void 0}o(KTe,"doesTableExist");function YTe(e){try{return JSON.stringify(e)}catch{return e}}o(YTe,"stringifyObj");function WTe(e){let t=KR.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}o(WTe,"ms_to_time");function zTe(e,t){let r=uc.basename(e,uc.extname(e));return uc.join(uc.dirname(e),r+t)}o(zTe,"changeExtension");function zL(){if(process.env[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=oTe(process.argv);if(e[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Nr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(zL,"getEnvCliRootPath");var YL;function jTe(){if(YL)return YL;let e=zL();if(zL()&&hQ.pathExistsSync(uc.join(e,Nr.HDB_CONFIG_FILE)))return YL=!0,!0}o(jTe,"noBootFile");function QTe(e,t){let r;return e.protocol==="http:"?r=cTe:r=aTe,new Promise((n,s)=>{let i=r.request(e,a=>{a.setEncoding("utf8"),a.body="",a.on("data",c=>{a.body+=c}),a.on("end",()=>{n(a)})});i.on("error",a=>{s(a)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}o(QTe,"httpRequest");function JTe(e){if(!e.schema&&!e.database){e.schema=Nr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(JTe,"transformReq");function XTe(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}o(XTe,"convertToMS");var YR=en()});var ce=M((wQ,OQ)=>{"use strict";var jL=require("fs-extra"),Jl=require("path"),AQ=require("os"),ZTe=require("properties-reader"),jp=z(),zp=ie(),Be=(k(),v(K)),WR=At(),eRe="Error initializing environment manager",zR="BOOT_PROPS_FILE_PATH",bQ=!1,tRe={[Be.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Xo={};Object.assign(wQ,OQ.exports={BOOT_PROPS_FILE_PATH:zR,getHdbBasePath:rRe,setHdbBasePath:nRe,get:IQ,initSync:iRe,setProperty:Je,initTestEnvironment:aRe,setCloneVar:oRe});function rRe(){return Xo[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(rRe,"getHdbBasePath");function nRe(e){Xo[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(nRe,"setHdbBasePath");function IQ(e){let t=WR.getConfigValue(e);return t===void 0?Xo[e]:t}o(IQ,"get");function Je(e,t){tRe[e]&&(Xo[e]=t),WR.updateConfigObject(e,t)}o(Je,"setProperty");function sRe(){let e;try{e=zp.getPropsFilePath(),jL.accessSync(e,jL.constants.F_OK|jL.constants.R_OK),bQ=!0;let t=ZTe(e);return Xo[Be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Be.HDB_SETTINGS_NAMES.INSTALL_USER),Xo[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Xo[zR]=e,!0}catch{return jp.trace(`Environment manager found no properties file at ${e}`),!1}}o(sRe,"doesPropFileExist");function iRe(e=!1){try{((bQ||sRe()||zp.noBootFile())&&!NQ||e)&&(WR.initConfig(e),Xo[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=WR.getConfigValue(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){jp.error(eRe),jp.error(t),console.error(t),process.exit(1)}}o(iRe,"initSync");var NQ=!1;function oRe(e){NQ=e}o(oRe,"setCloneVar");function aRe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:a,local_studio_on:c}=e,l=Jl.join(__dirname,"../../","unitTests");Xo[zR]=Jl.join(l,"hdb_boot_properties.file"),Je(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Jl.join(l,"settings.test")),Je(Be.HDB_SETTINGS_NAMES.INSTALL_USER,AQ.userInfo()?AQ.userInfo().username:void 0),Je(Be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Je(Be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Jl.join(l,"envDir","log")),Je(Be.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Je(Be.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Je(Be.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Je(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Jl.join(l,"envDir")),Je(Be.CONFIG_PARAMS.STORAGE_PATH,Jl.join(l,"envDir")),s&&(Je(Be.CONFIG_PARAMS.HTTP_SECUREPORT,IQ(Be.CONFIG_PARAMS.HTTP_PORT)),Je(Be.CONFIG_PARAMS.HTTP_PORT,null)),Je(Be.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Je(Be.CONFIG_PARAMS.HTTP_PORT,9926),Je(Be.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Je(Be.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Je(Be.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,zp.isEmpty(i)?!1:i),Je(Be.CONFIG_PARAMS.HTTP_CORS,zp.isEmpty(i)?!1:i),Je(Be.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Je(Be.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Je(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Je(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Je(Be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Jl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Je(Be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,zp.isEmpty(c)?!1:c),a&&(Je("CORS_ACCESSLIST",a),Je(Be.CONFIG_PARAMS.HTTP_CORSACCESSLIST,a)),n&&(Je(Be.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Je(Be.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Je(Be.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Je(Be.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Je(Be.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Je(Be.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${zR}. Please check your boot props and settings files`;jp.fatal(r),jp.error(t)}}o(aRe,"initTestEnvironment")});var vQ=M((SFe,MQ)=>{"use strict";var{promises:Ef,createReadStream:cRe,createWriteStream:lRe}=require("fs"),{createGzip:uRe}=require("zlib"),{promisify:dRe}=require("util"),{pipeline:fRe}=require("stream"),mRe=dRe(fRe),JL=require("path"),DQ=ce();DQ.initSync();var jR=z(),{CONFIG_PARAMS:hRe,ITC_EVENT_TYPES:_Fe}=(k(),v(K)),{onMessageFromWorkers:gFe}=st(),{convertToMS:CQ}=ie(),{onStorageReclamation:pRe}=(gR(),v(_2)),ERe=6e4,_Re="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",gRe="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",QL,PQ;MQ.exports=SRe;function SRe({logger:e,maxSize:t,interval:r,retention:n,enabled:s,path:i,auditInterval:a}){if(s===!1)return;let c=0;if(pRe(e.path,f=>{c=f},!0),!t&&!r)throw new Error(_Re);if(!i)throw new Error(gRe);let l;if(t){let f=t.slice(-1),m=t.slice(0,-1);f==="G"?l=m*1e9:f==="M"?l=m*1e6:l=m*1e3}let u;r&&(u=CQ(r));let d;return QL=Date.now(),jR.trace("Log rotate enabled, maxSize:",t,"interval:",r),PQ=setInterval(async()=>{if(l){let f;f=await Ef.stat(e.path),f.size>=l&&(d=await LQ(e.path,i))}if(u&&Date.now()-QL>=u&&(d=await LQ(e.path,i),QL=Date.now()),n||c){let f=CQ(n??"1M")/(1+c);c=0;let m=await Ef.readdir(i);for(let h of m)try{let p=await Ef.stat(JL.join(i,h));Date.now()-p.mtimeMs>f&&await Ef.unlink(JL.join(i,h))}catch(p){jR.error("Error trying to remove log",h,p)}}},a??ERe).unref(),{end(){clearInterval(PQ)},getLastRotatedLogPath(){return d}}}o(SRe,"logRotator");async function LQ(e,t){let r=DQ.get(hRe.LOGGING_ROTATION_COMPRESS),n=JL.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.log`);return await Ef.rename(e,n),r&&(e=n,n+=".gz",await mRe(cRe(e),uRe(),lRe(n)),await Ef.unlink(e)),jR.closeLogFile(),jR.notify(`hdb.log rotated, old log moved to ${n}`),n}o(LQ,"moveLogFile")});var HQ={};Ce(HQ,{RootConfigWatcher:()=>XL});var UQ,xQ,BQ,QR,FQ,XL,kQ=fe(()=>{UQ=w(require("chokidar")),xQ=require("node:fs/promises"),BQ=w(At()),QR=require("node:stream"),FQ=require("yaml"),XL=class extends QR.EventEmitter{static{o(this,"RootConfigWatcher")}#e;#t;#r;constructor(){super(),this.#e=(0,BQ.getConfigFilePath)(),this.#t=UQ.default.watch(this.#e,{persistent:!1}).on("add",this.handleChange.bind(this)).on("change",this.handleChange.bind(this)).on("error",this.handleError.bind(this))}handleError(t){this.emit("error",t)}handleChange(){(0,xQ.readFile)(this.#e,"utf-8").then(t=>{if(!t)return;let r=(0,FQ.parse)(t);if(!this.#r){this.#r=r,this.emit("ready",this.#r);return}this.emit("change",this.#r=r)}).catch(t=>{})}ready(){return(0,QR.once)(this,"ready")}close(){return this.#t.close(),this.#r=void 0,this.emit("close"),this.removeAllListeners(),this}get config(){return this.#r}}});var z=M((bFe,sy)=>{"use strict";var ea=require("fs-extra"),{workerData:TRe,threadId:RRe,isMainThread:WQ}=require("worker_threads"),Xp=require("path"),zQ=require("yaml"),jQ=require("properties-reader"),Hr=(k(),v(K)),GQ=Lc(),yRe=require("os"),{PACKAGE_ROOT:iD}=Rt(),{_assignPackageExport:ARe}=Ws(),{Console:bRe}=require("console"),qQ=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),$Q=new Map,{join:ta}=Xp,VQ=1e4,nr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},IRe={STDOUT:"stdOut",STDERR:"stdErr"},AFe=ta(iD,"logs"),NRe=ta(iD,"config/yaml/",Hr.HDB_DEFAULT_CONFIG_FILE),wRe=1e4,Zp,eE,JR,Zo,eD,ZL,ZR,Lt,us,ey,ty,_f,Jp,Qp;function XR(e,t,r){e.rotation=t.rotation;let n=t.path;n?t.root||(t.root=Xp.dirname(n)):t.root?n=ta(t.root,eD):(n=Lt.path,t.root||(t.root=Xp.dirname(n))),n?e.path=n:console.error("No path for logger",t),e.level=nr[t.level]??Lt?.level??nr.info,QQ(e),e.logToStdstreams=t.stdStreams??!1,e.tag=t.tag??(Lt.path===e.path&&r)}o(XR,"updateLogger");function QQ(e){let t=e.conditional??(e.conditional={});t.notify=nr.notify>=e.level?e.notify.bind(e):void 0,t.fatal=nr.fatal>=e.level?e.fatal.bind(e):void 0,t.error=nr.error>=e.level?e.error.bind(e):void 0,t.warn=nr.warn>=e.level?e.warn.bind(e):void 0,t.info=nr.info>=e.level?e.info.bind(e):void 0,t.debug=nr.debug>=e.level?e.debug.bind(e):void 0,t.trace=nr.trace>=e.level?e.trace.bind(e):void 0}o(QQ,"updateConditional");async function tD(){Qp||(Qp=new KRe,await Qp.ready(),Qp.on("change",tD));let e=Qp.config,t=e.logging??{};XR(Lt,t),ZR=Lt.path,Zp=t.console??!1,t.external&&XR(us,t.external);for(let r in e){let n=e[r];n.logging?XR(Lt.forComponent(r),n.logging,r):Lt.hasComponent(r)&&XR(Lt.forComponent(r),t,r)}}o(tD,"updateLogSettings");var rD=class extends bRe{static{o(this,"HarperLogger")}constructor(t,r){t.stdout.removeListener=()=>{},t.stderr.removeListener=()=>{},t.stdout.listenerCount=()=>{},t.stderr.listenerCount=()=>{},super(t),this.level=r}trace(...t){gn="trace",this.level<=nr.trace&&super.info(...t),gn="info"}debug(...t){gn="debug",this.level<=nr.debug&&super.info(...t),gn="info"}info(...t){gn="info",this.level<=nr.info&&super.info(...t),gn="info"}warn(...t){gn="warn",this.level<=nr.warn&&super.warn(...t),gn="info"}error(...t){gn="error",this.level<=nr.error&&super.error(...t),gn="info"}fatal(...t){_f=!0;try{gn="fatal",this.level<=nr.fatal&&super.error(...t),gn="info"}finally{_f=!1}}notify(...t){_f=!0;try{gn="notify",this.level<=nr.notify&&super.info(...t),gn="info"}finally{_f=!1}}withTag(t){return XQ(t,!0,this)}forComponent(t){return this}hasComponent(t){return!1}};Jp===void 0&&JQ();sy.exports={notify:URe,fatal:xRe,error:sD,warn:BRe,info:DRe,debug:vRe,trace:MRe,logLevel:Zo,loggerWithTag:XQ,suppressLogging:PRe,initLogSettings:JQ,logCustomLevel:FRe,closeLogFile:ZQ,createLogger:ny,logsAtLevel:ORe,getLogFilePath:o(()=>ZR,"getLogFilePath"),forComponent:o(e=>Lt.forComponent(e),"forComponent"),setMainLogger:$Re,OUTPUTS:IRe,AuthAuditLog:VRe,start:tD,startOnMainThread:tD,errorToString:qRe};sy.exports.externalLogger={notify(...e){us.notify(...e)},fatal(...e){us.fatal(...e)},error(...e){us.error(...e)},warn(...e){us.warn(...e)},info(...e){us.info(...e)},debug(...e){us.debug(...e)},trace(...e){us.trace(...e)},withTag(e){return us.withTag(e)}};ARe("logger",sy.exports.externalLogger);function ORe(e){return nr[Zo]<=nr[e]}o(ORe,"logsAtLevel");function JQ(e=!1){try{if(Jp===void 0||e){ZQ();let t=HRe(),r=GQ(["ROOTPATH"]);try{Jp=jQ(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!ea.pathExistsSync(ta(r.ROOTPATH,Hr.HDB_CONFIG_FILE)))throw s}let n;if({level:Zo,configLogPath:ZL,toFile:eE,logConsole:Zp,rotation:n,toStream:JR}=kRe(r.ROOTPATH?ta(r.ROOTPATH,Hr.HDB_CONFIG_FILE):Jp.get("settings_path")),eD=Hr.LOG_NAMES.HDB,ZR=ta(ZL,eD),Lt=ny({path:ZR,level:Zo,stdStreams:JR,rotation:n}),us=Lt.forComponent("external"),us.tag=null,WQ)try{require("segfault-handler").registerHandler(ta(ZL,"crash.log"))}catch{}}}catch(t){if(Jp=void 0,t.code===Hr.NODE_ERROR_CODES.ENOENT||t.code===Hr.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=GQ(Object.keys(Hr.CONFIG_PARAM_MAP),!0);for(let s in r){let i=Hr.CONFIG_PARAM_MAP[s];i&&i.toLowerCase();let a=r[s];if(i===Hr.CONFIG_PARAMS.LOGGING_LEVEL){Zo=a;continue}i===Hr.CONFIG_PARAMS.LOGGING_CONSOLE&&(Zp=i)}let{defaultLevel:n}=GRe();eE=!1,JR=!0,Zo=Zo===void 0?n:Zo,Lt=ny({level:Zo}),us=Lt.forComponent("external"),us.tag=null;return}throw sD("Error initializing log settings"),sD(t),t}process.env.DEV_MODE&&(JR=!0),CRe()}o(JQ,"initLogSettings");var dc=!0;function CRe(){eE&&(process.stdout.write=function(e){return typeof e=="string"&&dc&&Zp&&(e=e.toString(),e[e.length-1]===`
35
35
  `&&(e=e.slice(0,-1)),ty(e)),qQ.apply(process.stdout,arguments)},process.stderr.write=function(e){return typeof e=="string"&&dc&&Zp&&(e[e.length-1]===`
36
36
  `&&(e=e.slice(0,-1)),ty(e)),qQ.apply(process.stderr,arguments)})}o(CRe,"stdioLogging");function XQ(e,t,r=Lt){return e=e.replace(/ /g,"-"),{notify:n(r.notify,"notify"),fatal:n(r.fatal,"fatal"),error:n(r.error,"error"),warn:n(r.warn,"warn"),info:n(r.info,"info"),debug:n(r.debug,"debug"),trace:n(r.trace,"trace")};function n(s,i){return!t||r.level<=nr[i]?function(...a){ry=e;try{return s.call(r,...a)}finally{ry=void 0}}:null}o(n,"logWithTag")}o(XQ,"loggerWithTag");function PRe(e){try{dc=!1,e()}finally{dc=!0}}o(PRe,"suppressLogging");var LRe=TRe?.name?.replace(/ /g,"-")||"main",gn="info",nD,ry;function ny({path:e,level:t,stdStreams:r,rotation:n,isExternalInstance:s,writeToLog:i,component:a}){t||(t="info");let c=nr[t],l;function u(h){if(eE)if(l.logToStdstreams){f(h.replace(/\x1b\[[0-9;]*m/g,"")),dc=!1;try{process.stdout.write(h)}finally{dc=!0}}else f(h);else r&&process.stdout.write(h)}o(u,"logStdOut");function d(h){if(eE){if(f(h),r){dc=!1;try{process.stderr.write(h)}finally{dc=!0}}}else r&&process.stderr.write(h)}o(d,"logStdErr");let f=e&&YQ(e,n,s);function m(h){return{write(p){let _=[gn];_.unshift(nD||LRe+"/"+RRe),ry&&_.push(ry),l.tag&&_.push(l.tag),h(`[${_.join("] [")}]: ${p}`)}}}if(o(m,"logPrepend"),s&&(ty=f),l=new rD({stdout:m(i??u),stderr:m(i??d),colorMode:r??!1},c),QQ(l),l.path=e,Object.defineProperty(l,"path",{get(){return e},set(h){e=h,f=YQ(e,l.rotation,s),s&&(ty=f)},enumerable:!0}),l.closeLogFile=f?.closeLogFile,l.logToStdstreams=r,!a){let h=new Map;l.forComponent=function(p){let _=h.get(p);return _||(_=ny({path:e,level:t,stdStreams:r,isExternalInstance:p==="external",rotation:n,writeToLog:i,component:!0}),h.set(p,_)),_},l.hasComponent=function(p){return h.has(p)}}return l}o(ny,"createLogger");var KQ=100;function YQ(e,t,r){let n=$Q.get(e),s,i,a,c,l=0;n||(n=d,n.closeLogFile=m,n.path=e,$Q.set(e,n)),WQ&&JSON.stringify(t)!==JSON.stringify(n.rotation)&&(n.rotation=t,setTimeout(()=>{if(n.rotator?.end(),!t)return;let p=vQ();try{n.rotator=p({logger:n,...t})}catch(_){n("Error initializing log rotator",_)}},100));let u=0;return n;function d(p){u++;let _=`${new Date().toISOString()} ${p}${p.endsWith(`
37
37
  `)?"":`