harperdb 4.6.24 → 4.6.25

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.
@@ -30,8 +30,8 @@ Host ${s}
30
30
  IdentitiesOnly yes`;await Ie.pathExists(l)?await Ie.appendFile(l,`
31
31
  `+u):await Ie.outputFile(l,u);let d="";if(await Ie.pathExists(Wo)||(await Ie.writeFile(Wo,""),await Ie.chmod(Wo,"0600")),i=="github.com"&&!(await Ie.readFile(Wo,"utf8")).includes("github.com"))try{let _=(await(await fetch("https://api.github.com/meta")).json()).ssh_keys;for(let g of _)Ie.appendFile(Wo,"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(Wo,a);let f=await Si(e);return f.message=`Added ssh key: ${r}${d}`,f}o(khe,"addSSHKey");async function Ghe(e){let t=Un.updateSSHKeyValidator(e);if(t)throw zt(t,t.message,jt.BAD_REQUEST);let{name:r,key:n}=e;Wt.trace("updating ssh key",r);let s=Oe.join(ic,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 Si(e);return i.message=`Updated ssh key: ${r}`,i}o(Ghe,"updateSSHKey");async function qhe(e){let t=Un.deleteSSHKeyValidator(e);if(t)throw zt(t,t.message,jt.BAD_REQUEST);let{name:r}=e;Wt.trace("deleting ssh key",r);let n=Oe.join(ic,r+".key"),s=Oe.join(ic,"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 Si(e);return c.message=`Deleted ssh key: ${r}`,c}o(qhe,"deleteSSHKey");async function $he(e){let t=[];return await Ie.pathExists(ic)&&(await Ie.readdir(ic)).forEach(r=>{r!="known_hosts"&&r!="config"&&t.push({name:r.split(".")[0]})}),t}o($he,"listSSHKeys");async function Vhe(e){let t=Un.setSSHKnownHostsValidator(e);if(t)throw zt(t,t.message,jt.BAD_REQUEST);let{known_hosts:r}=e;await Ie.outputFile(Wo,r);let n=await Si(e);return n.message="Known hosts successfully set",n}o(Vhe,"setSSHKnownHosts");async function Khe(e){return await Ie.pathExists(Wo)?{known_hosts:await Ie.readFile(Wo,"utf8")}:{known_hosts:null}}o(Khe,"getSSHKnownHosts");sr.customFunctionsStatus=Nhe;sr.getCustomFunctions=whe;sr.getCustomFunction=Ohe;sr.setCustomFunction=Che;sr.dropCustomFunction=Phe;sr.addComponent=Lhe;sr.dropCustomFunctionProject=Dhe;sr.packageComponent=Mhe;sr.deployComponent=vhe;sr.getComponents=xhe;sr.getComponentFile=Bhe;sr.setComponentFile=Fhe;sr.dropComponent=Hhe;sr.addSSHKey=khe;sr.updateSSHKey=Ghe;sr.deleteSSHKey=qhe;sr.listSSHKeys=$he;sr.setSSHKnownHosts=Vhe;sr.getSSHKnownHosts=Khe});var XO=M((CUe,_K)=>{"use strict";var Ms=require("joi"),EK=lt();_K.exports={readTransactionLogValidator:Yhe,deleteTransactionLogsBeforeValidator:Whe};function Yhe(e){let t=Ms.object({schema:Ms.string(),database:Ms.string(),table:Ms.string().required(),from:Ms.date().timestamp(),to:Ms.date().timestamp(),limit:Ms.number().min(1)});return EK.validateBySchema(e,t)}o(Yhe,"readTransactionLogValidator");function Whe(e){let t=Ms.object({schema:Ms.string(),database:Ms.string(),table:Ms.string().required(),timestamp:Ms.date().timestamp().required()});return EK.validateBySchema(e,t)}o(Whe,"deleteTransactionLogsBeforeValidator")});var nT=M((LUe,AK)=>{"use strict";var ZO=(k(),v(W)),ip=mr(),gK=ie(),SK=oe(),TK=ki(),RK=Q(),{handleHDBError:tT,hdbErrors:zhe}=ge(),{HTTP_STATUS_CODES:rT}=zhe,{readTransactionLogValidator:jhe,deleteTransactionLogsBeforeValidator:Qhe}=XO(),yK=jn(),Jhe="Logs successfully deleted from transaction log.",Xhe="All logs successfully deleted from transaction log.";AK.exports={readTransactionLog:Zhe,deleteTransactionLogsBefore:tpe};async function Zhe(e){let t=jhe(e);if(t)throw tT(t,t.message,rT.BAD_REQUEST,void 0,void 0,!0);e.database=e.database??e.schema??"data";let r=gK.checkSchemaTableExist(e.database,e.table);if(r)throw tT(new Error,r,rT.NOT_FOUND,void 0,void 0,!0);return SK.get(ZO.CONFIG_PARAMS.CLUSTERING_ENABLED)?await epe(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)),yK.readAuditLog(e))}o(Zhe,"readTransactionLog");async function*epe(e){let t=TK.createNatsTableStreamName(e.database,e.table),r=await ip.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===ZO.OPERATIONS_ENUM.DELETE&&(i.hash_values=n?.entry?.hash_values),yield i}}o(epe,"readTransactionLogNats");async function tpe(e){let t=Qhe(e);if(t)throw tT(t,t.message,rT.BAD_REQUEST,void 0,void 0,!0);if(e.database=e.database??e.schema??"data",!SK.get(ZO.CONFIG_PARAMS.CLUSTERING_ENABLED))return RK.info("Delete transaction logs called for Plexus"),yK.deleteAuditLogsBefore(e);let{database:r,table:n,timestamp:s}=e,i=gK.checkSchemaTableExist(r,n);if(i)throw tT(new Error,i,rT.NOT_FOUND,void 0,void 0,!0);let a=TK.createNatsTableStreamName(r,n),{jsm:c}=await ip.getNATSReferences(),l=await ip.getStreamInfo(a),u=new Date(l.state.first_ts).getTime();if(s<=u)return`No transactions exist before: ${s}`;let d=Jhe,f,m=new Date(l.state.last_ts).getTime();return s>m?(f=l.state.last_seq+1,d=Xhe):f=(await ip.viewStream(a,parseInt(s),1))[0].nats_sequence,await ip.purgeTableStream(r,n,{seq:f}),d}o(tpe,"deleteTransactionLogsBefore")});var nC={};we(nC,{describeMetric:()=>CK,describeMetricOp:()=>rC,get:()=>wK,getOp:()=>eC,listMetrics:()=>OK,listMetricsOp:()=>tC});async function npe(e){return(await rg().get(e)).hostname}function bK(e,t){return e.length===0||e.includes(t)}function eC(e){return op.trace?.("get_analytics request:",e),wK(e.metric,e.get_attributes,e.start_time,e.end_time,e.conditions)}function NK(e){return"conditions"in e?{...e,conditions:e.conditions.map(NK)}:{attribute:e.search_attribute??e.attribute,comparator:e.search_type??e.comparator,value:e.search_value??e.value}}async function wK(e,t,r,n,s){let i=[{attribute:"metric",comparator:"equals",value:e}];s&&i.push(...s.map(NK));let a=t??[];bK(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,allowConditionsOnDynamicAttributes:!0};return a.length>0&&(c.select=a),op.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],bK(a,"node")&&(op.trace?.(`get_analytics lookup hostname for nodeId: ${d}`),u.node=await npe(d)),op.trace?.("get_analytics result:",JSON.stringify(u)),u})}function tC(e){return OK(e.metric_types,e.custom_metrics_window)}async function OK(e=["builtin"],t=rpe){let r=[],n=Object.values(Do);if(e.includes("builtin")&&(r=n),e.includes("custom")){let i=[{attribute:"id",comparator:"greater_than",value:Date.now()-t}],a=n.map(d=>({attribute:"metric",comparator:"not_equal",value:d}));i.push(...a);let c={select:["metric"],conditions:i},l=new Set,u=await databases.system.hdb_analytics.search(c);for await(let d of u)l.add(d.metric);r.push(...Array.from(l.values()))}return r}function rC(e){return CK(e.metric)}async function CK(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 op.trace?.("describe_metric result:",JSON.stringify(i)),i}return{}}var IK,rpe,op,sC=ce(()=>{IK=w(Q());JI();XI();rpe=1e3*60*60*24*7,op=(0,IK.forComponent)("analytics").conditional;o(npe,"lookupHostname");o(bK,"isSelected");o(eC,"getOp");o(NK,"conformCondition");o(wK,"get");o(tC,"listMetricsOp");o(OK,"listMetrics");o(rC,"describeMetricOp");o(CK,"describeMetric")});var sT,iT,ap,oT=ce(()=>{sT={primary:{allowedValues:null},maintenance:{allowedValues:null},availability:{allowedValues:["Available","Unavailable"]}},iT=Object.keys(sT),ap="primary"});function LK(e){return PK.validateBySchema(e,ape)}var cp,PK,spe,ipe,ope,ape,DK=ce(()=>{cp=w(require("joi")),PK=w(lt());oT();spe=iT,ipe=Object.entries(sT).reduce((e,[t,r])=>(r.allowedValues&&(e[t]=`Status "${t}" only accepts these values: ${r.allowedValues.join(", ")}`),e),{}),ope=o(()=>{let e=cp.default.string().min(1).max(512);return Object.entries(sT).forEach(([t,r])=>{r.allowedValues&&(e=e.when("id",{is:t,then:cp.default.string().valid(...r.allowedValues).messages({"any.only":ipe[t]})}))}),e.required()},"createStatusValidationSchema"),ape=cp.default.object({id:cp.default.string().valid(...spe).required(),status:ope()});o(LK,"validateStatus")});var lC={};we(lC,{DEFAULT_STATUS_ID:()=>ap,STATUS_IDS:()=>iT,Status:()=>zo,clear:()=>oC,get:()=>aC,set:()=>cC});function up(){return iC||(iC=ze({database:"system",table:"hdb_status",replicate:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"status"},{name:"__createdtime__"},{name:"__updatedtime__"}]})),iC}function oC({id:e}){return lp.debug?.("clearStatus",e),up().delete(e)}function lpe(){return lp.debug?.("getAllStatus"),up().get({})}function aC({id:e}){return e?(lp.debug?.("getStatus",e),up().get(e)):(lp.debug?.("getStatus","all"),lpe())}function cC({status:e,id:t=ap}){let r=LK({status:e,id:t});if(r)throw(0,aT.handleHDBError)(r,r.message,cpe.BAD_REQUEST);return lp.debug?.("setStatus",t,e),up().put(t,{status:e})}var aT,MK,cpe,iC,zo,lp,dp=ce(()=>{Me();aT=w(ge()),MK=w(ei());DK();oT();oT();({HTTP_STATUS_CODES:cpe}=aT.hdbErrors);o(up,"getStatusTable");zo={get primaryStore(){return up().primaryStore}},lp=(0,MK.loggerWithTag)("status");o(oC,"clearStatus");o(lpe,"getAllStatus");o(aC,"getStatus");o(cC,"setStatus")});var UK=M((jUe,vK)=>{"use strict";var uC=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}};vK.exports=uC});var BK=M((JUe,xK)=>{"use strict";var dC=class{static{o(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};xK.exports=dC});var mC=M((ZUe,HK)=>{"use strict";var FK=UK(),upe=BK(),{HDB_ERROR_MSGS:dpe}=tn(),fC=class{static{o(this,"PermissionResponseObject")}constructor(){this.error=dpe.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 FK(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new upe(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 FK(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}};HK.exports=fC});var dT=M((t0e,rY)=>{"use strict";var hC=Cn(),cT=nn(),vs=wh(),hp=Ca(),pC=Xc(),fpe=gw(),mpe=$q(),pp=Xn(),lT=jm(),br=Q(),hpe=Aw(),ppe=RS(),Epe=Qw(),_pe=AS(),gpe=Zw(),Spe=eO(),Tpe=nO(),Rpe=iO(),EC=OS(),jo=ie(),ype=RV(),_C=gO(),qK=kd(),_n=(k(),v(W)),$K=U1(),Ape=bd(),VK=(ed(),v(oh)),KK=(jS(),v(Jh)),YK=wt(),Er=jO(),bpe=require("alasql"),WK=nT(),zK=tp(),Kd=ss(),jK=(Nd(),v(Id)),gC=(sC(),v(nC)),SC=(dp(),v(lC)),QK=mC(),{handleHDBError:xn,hdbErrors:JK}=ge(),{HDB_ERROR_MSGS:Qr,HTTP_STATUS_CODES:fp}=JK,{cleanupOrphanBlobs:Ipe}=wh(),X=new Map,XK="delete",oc="insert",Us="read",Gl="update",mp="describe",kK=hp.describeSchema.name,GK=hp.describeTable.name,ZK={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},Npe={insert:!0,delete:!0,deleteRecord:!0,update:!0,updateData:!0,upsert:!0,upsertData:!0},wpe="catchup",Ope="handleGetJob",Cpe="handleGetJobsByStartDate",uT={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},Ppe=[vs.createTable.name,vs.createAttribute.name,vs.dropTable.name,vs.dropAttribute.name],eY={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},te=class{static{o(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};X.set(hC.insert.name,new te(!1,[oc]));X.set(hC.update.name,new te(!1,[Gl]));X.set(hC.upsert.name,new te(!1,[oc,Gl]));X.set(cT.searchByConditions.name,new te(!1,[Us]));X.set(cT.searchByHash.name,new te(!1,[Us]));X.set(cT.searchByValue.name,new te(!1,[Us]));X.set(cT.search.name,new te(!1,[Us]));X.set(vs.createSchema.name,new te(!0,[]));X.set(vs.createTable.name,new te(!0,[]));X.set(vs.createAttribute.name,new te(!1,[oc]));X.set(vs.dropSchema.name,new te(!0,[]));X.set(vs.dropTable.name,new te(!0,[]));X.set(vs.dropAttribute.name,new te(!0,[]));X.set(hp.describeSchema.name,new te(!1,[Us]));X.set(hp.describeTable.name,new te(!1,[Us]));X.set(pC.deleteRecord.name,new te(!1,[XK]));X.set(pp.addUser.name,new te(!0,[]));X.set(pp.alterUser.name,new te(!0,[]));X.set(pp.dropUser.name,new te(!0,[]));X.set(pp.listUsersExternal.name,new te(!0,[]));X.set(lT.listRoles.name,new te(!0,[]));X.set(lT.addRole.name,new te(!0,[]));X.set(lT.alterRole.name,new te(!0,[]));X.set(lT.dropRole.name,new te(!0,[]));X.set(hpe.name,new te(!0,[]));X.set(ppe.name,new te(!0,[]));X.set(Epe.name,new te(!0,[]));X.set(_pe.name,new te(!0,[]));X.set(gpe.name,new te(!0,[]));X.set(Spe.name,new te(!0,[]));X.set(EC.setRoutes.name,new te(!0,[]));X.set(EC.getRoutes.name,new te(!0,[]));X.set(EC.deleteRoutes.name,new te(!0,[]));X.set(YK.setConfiguration.name,new te(!0,[]));X.set(Tpe.clusterStatus.name,new te(!0,[]));X.set(Rpe.name,new te(!0,[]));X.set(_C.getFingerprint.name,new te(!0,[]));X.set(_C.setLicense.name,new te(!0,[]));X.set(pC.deleteFilesBefore.name,new te(!0,[]));X.set(pC.deleteAuditLogsBefore.name,new te(!0,[]));X.set(qK.restart.name,new te(!0,[]));X.set(qK.restartService.name,new te(!0,[]));X.set(fpe.name,new te(!0,[]));X.set(mpe.name,new te(!0,[Us]));X.set(Ipe.name,new te(!0,[]));X.set(Ape.systemInformation.name,new te(!0,[]));X.set(YK.getConfiguration.name,new te(!0,[]));X.set(WK.readTransactionLog.name,new te(!0,[]));X.set(WK.deleteTransactionLogsBefore.name,new te(!0,[]));X.set(zK.installModules.name,new te(!0,[]));X.set(zK.auditModules.name,new te(!0,[]));X.set(Kd.createCsr.name,new te(!0,[]));X.set(Kd.signCertificate.name,new te(!0,[]));X.set(Kd.listCertificates.name,new te(!0,[]));X.set(Kd.addCertificate.name,new te(!0,[]));X.set(Kd.removeCertificate.name,new te(!0,[]));X.set(Kd.getKey.name,new te(!0,[]));X.set(jK.addNodeBack.name,new te(!0,[]));X.set(jK.removeNodeBack.name,new te(!0,[]));X.set(gC.getOp.name,new te(!1,[Us]));X.set(gC.listMetricsOp.name,new te(!1,[Us]));X.set(gC.describeMetricOp.name,new te(!1,[Us]));X.set(SC.clear.name,new te(!0,[]));X.set(SC.get.name,new te(!0,[]));X.set(SC.set.name,new te(!0,[]));X.set(VK.createTokens.name,new te(!1,[]));X.set(VK.refreshOperationToken.name,new te(!1,[]));X.set(KK.login.name,new te(!1,[]));X.set(KK.logout.name,new te(!1,[]));X.set(Er.customFunctionsStatus.name,new te(!0,[]));X.set(Er.getCustomFunctions.name,new te(!0,[]));X.set(Er.getComponents.name,new te(!0,[]));X.set(Er.getComponentFile.name,new te(!0,[]));X.set(Er.setComponentFile.name,new te(!0,[]));X.set(Er.dropComponent.name,new te(!0,[]));X.set(Er.getCustomFunction.name,new te(!0,[]));X.set(Er.setCustomFunction.name,new te(!0,[]));X.set(Er.dropCustomFunction.name,new te(!0,[]));X.set(Er.addComponent.name,new te(!0,[]));X.set(Er.dropCustomFunctionProject.name,new te(!0,[]));X.set(Er.packageComponent.name,new te(!0,[]));X.set(Er.deployComponent.name,new te(!0,[]));X.set(Er.addSSHKey.name,new te(!0,[]));X.set(Er.updateSSHKey.name,new te(!0,[]));X.set(Er.deleteSSHKey.name,new te(!0,[]));X.set(Er.listSSHKeys.name,new te(!0,[]));X.set(Er.setSSHKnownHosts.name,new te(!0,[]));X.set(Er.getSSHKnownHosts.name,new te(!0,[]));X.set(_C.getRegistrationInfo.name,new te(!1,[]));X.set(pp.userInfo.name,new te(!1,[]));X.set(hp.describeAll.name,new te(!1,[]));X.set(Ope,new te(!1,[]));X.set(Cpe,new te(!0,[]));X.set(wpe,new te(!0,[]));X.set(uT.CSV_DATA_LOAD,new te(!1,[oc,Gl]));X.set(uT.CSV_URL_LOAD,new te(!1,[oc,Gl]));X.set(uT.CSV_FILE_LOAD,new te(!1,[oc,Gl]));X.set(uT.IMPORT_FROM_S3,new te(!1,[oc,Gl]));X.set(eY.EXPORT_TO_S3,new te(!0,[]));X.set(eY.EXPORT_LOCAL,new te(!0,[]));X.set(_n.VALID_SQL_OPS_ENUM.DELETE,new te(!1,[XK]));X.set(_n.VALID_SQL_OPS_ENUM.SELECT,new te(!1,[Us]));X.set(_n.VALID_SQL_OPS_ENUM.INSERT,new te(!1,[oc]));X.set(_n.VALID_SQL_OPS_ENUM.UPDATE,new te(!1,[Gl]));rY.exports={verifyPerms:Dpe,verifyPermsAst:Lpe,verifyBulkLoadAttributePerms:vpe};function Lpe(e,t,r){if(jo.isEmptyOrZeroLength(e))throw br.info("verify_perms_ast has an empty user parameter"),xn(new Error);if(jo.isEmptyOrZeroLength(t))throw br.info("verify_perms_ast has an empty user parameter"),xn(new Error);if(jo.isEmptyOrZeroLength(r))throw br.info("verify_perms_ast has a null operation parameter"),xn(new Error);try{let n=new QK,s=new ype(e),i=s.getSchemas(),a=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw br.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&&ZK[r])throw xn(new Error,Qr.DROP_SYSTEM,fp.FORBIDDEN);if(c&&!l)return null;let u=$K.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof bpe.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=tY(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]),_=RC(t.role.permission,m,f[h]);TC(p,_,r,f[h],m,n)}}),n.getPermsResponse())}catch(n){throw xn(n)}}o(Lpe,"verifyPermsAst");function Dpe(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw br.info("null required parameter in verifyPerms"),xn(new Error,Qr.DEFAULT_INVALID_REQUEST,fp.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 QK;if(jo.isEmptyOrZeroLength(e.hdb_user?.role)||jo.isEmptyOrZeroLength(e.hdb_user?.role?.permission))return br.info(`User ${e.hdb_user?.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Qr.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(_n.SYSTEM_SCHEMA_NAME)||s===_n.SYSTEM_SCHEMA_NAME;if(l&&d&&Npe[e.operation]&&(i===_n.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME||i===_n.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||i===_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME))return null;if(d&&ZK[r])throw xn(new Error,Qr.DROP_SYSTEM,fp.FORBIDDEN);if(l&&!d||u===!0&&(r===vs.createSchema.name||r===vs.dropSchema.name))return null;if(Ppe.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=$K.getRolePermissions(e.hdb_user?.role);if(e.hdb_user?.role&&(e.hdb_user.role.permission=f),(r===kK||r===GK)&&!f.super_user){if(s===_n.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Qr.SCHEMA_PERM_ERROR(s));if(r===kK&&(!f[s]||!f[s][mp]))return c.handleInvalidItem(Qr.SCHEMA_NOT_FOUND(s));if(r===GK&&(!f[s]||!f[s].tables[i]||!f[s].tables[i][mp]))return c.handleInvalidItem(Qr.TABLE_NOT_FOUND(s,i))}let m=tY(e.hdb_user,r,a,c,n);if(m)return m;if(X.get(r)&&X.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&_n.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let _=[],g=f[s].tables[i];g[_n.PERMS_CRUD_ENUM.READ]&&(g.attribute_permissions.length>0?g.attribute_permissions.filter(T=>T[_n.PERMS_CRUD_ENUM.READ]).forEach(T=>{_.push(T.attribute_name)}):_=global.hdb_schema[s][i].attributes.map(R=>R.attribute),e.get_attributes=_)}let h=Mpe(e),p=RC(e.hdb_user?.role?.permission,s,i);return TC(h,p,r,i,s,c,n),c.getPermsResponse()}o(Dpe,"verifyPerms");function tY(e,t,r,n,s){if(jo.arrayHasEmptyValues([e,t,r]))throw br.info("hasPermissions has an invalid parameter"),xn(new Error);let i=r.has("system"),a=e.role.permission;if(a.super_user&&(!i||X.get(t).requires_su))return null;if(!X.get(t))throw br.info(`operation ${t} not found.`),xn(new Error,Qr.OP_NOT_FOUND(t),fp.BAD_REQUEST);if(X.get(t)&&X.get(t).requires_su)return br.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Qr.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!a[l]||a[l][mp]===!1){n.addInvalidItem(Qr.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(Qr.SCHEMA_NOT_FOUND(l));continue}let u=r.get(l);for(let d of u){let f=a[l].tables[d];if(!f||f[mp]===!1)n.addInvalidItem(Qr.TABLE_NOT_FOUND(l,d));else try{let m=[],h=X.get(t).perms;!jo.isEmpty(s)&&h.includes(s)&&(h=[s]);for(let p=0;p<h.length;p++){let _=h[p],g=f[_];(g==null||g===!1)&&(br.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=Qr.UNKNOWN_OP_AUTH_ERROR(t,l,d);throw br.error(h),br.error(m),xn(JK.CHECK_LOGS_WRAPPER(h))}}}return r.size<2?n.getPermsResponse():null}o(tY,"hasPermissions");function TC(e,t,r,n,s,i,a){if(!e||!t)throw br.info("no attributes specified in checkAttributePerms."),xn(new Error);let c=X.get(r).perms;if(!c||c==="")throw br.info(`no permissions found for ${r} in checkAttributePerms().`),xn(new Error);if(jo.isEmptyOrZeroLength(t))return br.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[mp]===!1){i.addInvalidItem(Qr.ATTR_NOT_FOUND(s,n,d),s,n);continue}if(c)for(let m of c){if(_n.TIME_STAMP_NAMES.includes(f.attribute_name)&&m!==Us)throw xn(new Error,Qr.SYSTEM_TIMESTAMP_PERMS_ERR,fp.FORBIDDEN);f[m]===!1&&(l[f.attribute_name]?l[f.attribute_name].push(m):l[f.attribute_name]=[m])}}else i.addInvalidItem(Qr.ATTR_NOT_FOUND(s,n,d),s,n)}let u=Object.keys(l);u.length>0&&i.addUnauthorizedAttributes(u,s,n,l)}o(TC,"checkAttributePerms");function Mpe(e){let t=new Set;try{if(e.action)return t;if(e.operation===_n.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){br.info(r)}return t}o(Mpe,"getRecordAttributes");function RC(e,t,r){let n=new Map;if(jo.isEmpty(e))return br.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{br.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}o(RC,"getAttributePermissions");function vpe(e,t,r,n,s,i,a){let c=new Set(i),l=RC(e,n,s);TC(c,l,t,s,n,a,r)}o(vpe,"verifyBulkLoadAttributePerms")});var mT=M((n0e,aY)=>{"use strict";aY.exports={evaluateSQL:Wpe,processAST:oY,convertSQLToAST:iY,checkASTPermissions:sY};var Upe=Cn(),nY=require("util"),xpe=nY.callbackify(Upe.insert),Bpe=nn().search,Fpe=Ck().update,Hpe=nY.callbackify(Fpe),kpe=Lk().convertDelete,ac=require("alasql"),Gpe=dT(),fT=Q(),qpe=p_(),$pe=ie(),Ep=(k(),v(W)),{hdbErrors:Vpe,handleHDBError:yC}=ge(),{HTTP_STATUS_CODES:AC}=Vpe;qpe(ac);var Kpe=403,Ype="There was a problem performing this insert. Please check the logs and try again.",bC=class{static{o(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Wpe(e,t){let r=e.parsed_sql_object;if(!r){r=iY(e.sql);let n,s=r.ast.statements[0];if(s instanceof ac.yy.Insert?n=s.into.databaseid:s instanceof ac.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof ac.yy.Update||s instanceof ac.yy.Delete?n=s.table.databaseid:fT.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof ac.yy.Select)&&$pe.isEmptyOrZeroLength(n))return t("No schema specified",null)}oY(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}o(Wpe,"evaluateSQL");function sY(e,t){let r;try{r=Gpe.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}o(sY,"checkASTPermissions");function iY(e){let t=new bC;if(!e)throw yC(new Error,"The 'sql' parameter is missing from the request body",AC.BAD_REQUEST);try{let r=e.trim(),n=ac.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
33
- `);throw n[1]?yC(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,AC.BAD_REQUEST):yC(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",AC.BAD_REQUEST)}return t}o(iY,"convertSQLToAST");function oY(e,t,r){try{let n=zpe;if(!e.bypass_auth&&!t.permissions_checked){let i=sY(e,t);if(i&&i.length>0)return r(Kpe,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Ep.VALID_SQL_OPS_ENUM.SELECT:n=Bpe,s=t.ast.statements[0];break;case Ep.VALID_SQL_OPS_ENUM.INSERT:n=jpe;break;case Ep.VALID_SQL_OPS_ENUM.UPDATE:n=Hpe;break;case Ep.VALID_SQL_OPS_ENUM.DELETE:n=kpe;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(oY,"processAST");function zpe(e,t){fT.info(e),t("unknown sql statement")}o(zpe,"nullFunction");function jpe({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=Qpe(i,e.values)}catch(a){return r(a)}xpe(s,(a,c)=>{if(a)return r(a);try{delete c.new_attributes,delete c.txn_time}catch(l){fT.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}o(jpe,"convertInsert");function Qpe(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]]=ac.compile(`SELECT ${s.toString()} AS [${Ep.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw fT.error(r),new Error(Ype)}}o(Qpe,"createDataObjects")});var PC=M((a0e,dY)=>{var _T=require("clone"),gT=lt(),Jpe=ie(),pT=(k(),v(W)),i0e=Q(),IC=require("fs"),wC=require("joi"),{string:ET}=wC.types(),{hdbErrors:Xpe,handleHDBError:hT}=ge(),{HDB_ERROR_MSGS:o0e,HTTP_STATUS_CODES:NC}=Xpe,{commonValidators:Yd}=Bi(),cY=" is required",Zpe=["insert","update","upsert"],OC={database:{presence:!1,format:Yd.schema_format,length:Yd.schema_length},schema:{presence:!1,format:Yd.schema_format,length:Yd.schema_length},table:{presence:!0,format:Yd.schema_format,length:Yd.schema_length},action:{inclusion:{within:Zpe,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},eEe={schema:ET.required(),table:ET.required(),action:ET.valid("insert","update","upsert")},{AWS_ACCESS_KEY:tEe,AWS_SECRET:rEe,AWS_BUCKET:nEe,AWS_FILE_KEY:sEe,REGION:iEe}=pT.S3_BUCKET_AUTH_KEYS,oEe={s3:{presence:!0},[`s3.${tEe}`]:{presence:!0,type:"String"},[`s3.${rEe}`]:{presence:!0,type:"String"},[`s3.${nEe}`]:{presence:!0,type:"String"},[`s3.${sEe}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${iEe}`]:{presence:!0,type:"String"}},lY=_T(OC);lY.data.presence={message:cY};var uY=_T(OC);uY.file_path.presence={message:cY};var aEe=Object.assign(_T(OC),oEe),CC=_T(eEe);CC.csv_url=ET.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();CC.passthrough_headers=wC.object();function cEe(e){let t=gT.validateObject(e,lY);return ST(e,t)}o(cEe,"dataObject");function lEe(e){let t=gT.validateBySchema(e,wC.object(CC));return ST(e,t)}o(lEe,"urlObject");function uEe(e){let t=gT.validateObject(e,uY);return ST(e,t)}o(uEe,"fileObject");function dEe(e){let t=gT.validateObject(e,aEe);return ST(e,t)}o(dEe,"s3FileObject");function ST(e,t){if(!t){let r=Jpe.checkGlobalSchemaTable(e.schema,e.table);if(r)return hT(new Error,r,NC.BAD_REQUEST);if(e.operation===pT.OPERATIONS_ENUM.CSV_FILE_LOAD)try{IC.accessSync(e.file_path,IC.constants.R_OK|IC.constants.F_OK)}catch(n){return n.code===pT.NODE_ERROR_CODES.ENOENT?hT(n,`No such file or directory ${n.path}`,NC.BAD_REQUEST):n.code===pT.NODE_ERROR_CODES.EACCES?hT(n,`Permission denied ${n.path}`,NC.BAD_REQUEST):hT(n)}}return t}o(ST,"postValidateChecks");dY.exports={dataObject:cEe,urlObject:lEe,fileObject:uEe,s3FileObject:dEe}});var LC=M((l0e,fY)=>{"use strict";var _p=Q(),TT=(k(),v(W));async function fEe(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===TT.OPERATIONS_ENUM.INSERT||t.operation===TT.OPERATIONS_ENUM.UPDATE||t.operation===TT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===TT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(_p.info(i.message),i):i.http_resp_msg?(_p.error(`Error calling operation: ${e.name}`),_p.error(i.http_resp_msg),i):(_p.error(`Error calling operation: ${e.name}`),_p.error(i),i)}}o(fEe,"callOperationFunctionAsAwait");fY.exports={callOperationFunctionAsAwait:fEe}});var DC=M((d0e,hY)=>{"use strict";var{S3:mEe,GetObjectCommand:hEe}=require("@aws-sdk/client-s3");hY.exports={getFileStreamFromS3:pEe,getS3AuthObj:mY};async function pEe(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await mY(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new hEe(r))).Body}o(pEe,"getFileStreamFromS3");function mY(e,t,r){return new mEe({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}o(mY,"getS3AuthObj")});var EY=M((m0e,pY)=>{"use strict";var MC=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}},vC=class{static{o(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};pY.exports={BulkLoadFileObject:MC,BulkLoadDataObject:vC}});var xC=M((p0e,_Y)=>{"use strict";var UC=class{static{o(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};_Y.exports=UC});var qC=M((R0e,vY)=>{"use strict";var RT=Cn(),AT=PC(),EEe=require("needle"),Ti=(k(),v(W)),_0e=Ot(),Wd=ie(),{handleHDBError:Qt,hdbErrors:NY}=ge(),{HTTP_STATUS_CODES:Jr,HDB_ERROR_MSGS:Ir,CHECK_LOGS_WRAPPER:$l}=NY,zd=Q(),BC=require("papaparse");Wd.promisifyPapaParse();var Ri=require("fs-extra"),_Ee=require("path"),{chain:gY}=require("stream-chain"),SY=require("stream-json/streamers/StreamArray"),TY=require("stream-json/utils/Batch"),RY=require("stream-chain/utils/comp"),{finished:yY}=require("stream"),gEe=oe(),wY=LC(),SEe=DC(),{BulkLoadFileObject:HC,BulkLoadDataObject:TEe}=EY(),kC=mC(),{verifyBulkLoadAttributePerms:OY}=dT(),g0e=xC(),S0e=mr(),T0e=ki(),{databases:REe}=(Me(),v(Et)),{coerceType:yEe}=(bT(),v(UY)),AY="No records parsed from csv file.",ql=`${gEe.get("HDB_ROOT")}/tmp`,{schemaRegex:AEe}=Bi(),bY=1024*1024*2,IY=5e3,bEe={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};vY.exports={csvDataLoad:IEe,csvURLLoad:NEe,csvFileLoad:wEe,importFromS3:OEe};async function IEe(e,t){let r=AT.dataObject(e);if(r)throw Qt(r,r.message,Jr.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=LY(e.schema,e.table),i=BC.parse(e.data,{header:!0,skipEmptyLines:!0,transform:FC.bind(null,s),dynamicTyping:!1}),a=new kC;e.hdb_user&&e.hdb_user?.role&&e.hdb_user?.role?.permission&&e.hdb_user?.role?.permission?.super_user!==!0&&OY(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 Qt(new Error,c,Jr.BAD_REQUEST,void 0,void 0,!0);let l=new TEe(e.action,e.schema,e.table,i.data);return n=await wY.callOperationFunctionAsAwait(DY,l,null),n.message===AY?AY:MY(n.records,n.number_written)}catch(s){throw Vl(s)}}o(IEe,"csvDataLoad");async function NEe(e){let t=AT.urlObject(e);if(t)throw Qt(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${ql}/${r}`;try{await CEe(e,r)}catch(s){throw zd.error(Ir.DOWNLOAD_FILE_ERR(r)+" - "+s),Qt(s,$l(Ir.DOWNLOAD_FILE_ERR(r)))}try{let s=new HC(this.job_operation_function.name,e.action,e.schema,e.table,n,Ti.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission),i=await GC(s);return await yT(n),i}catch(s){throw await yT(n),Vl(s)}}o(NEe,"csvURLLoad");async function wEe(e){let t=AT.fileObject(e);if(t)throw Qt(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=new HC(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Ti.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission);try{return await GC(r)}catch(n){throw Vl(n)}}o(wEe,"csvFileLoad");async function OEe(e){let t=AT.s3FileObject(e);if(t)throw Qt(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=_Ee.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${ql}/${s}`;let i=new HC(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user?.role?.permission);await PEe(s,e);let a=await GC(i);return await yT(r),a}catch(n){throw await yT(r),Vl(n)}}o(OEe,"importFromS3");async function CEe(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await EEe("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 Qt(n,s,n.statusCode,Ti.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}DEe(r,e.csv_url),await LEe(t,r.raw)}o(CEe,"downloadCSVFile");async function PEe(e,t){try{let r=`${ql}/${e}`;await Ri.mkdirp(ql),await Ri.writeFile(`${ql}/${e}`,"",{flag:"a+"});let n=await Ri.createWriteStream(r),s=await SEe.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(){zd.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw zd.error(Ir.S3_DOWNLOAD_ERR+" - "+r),Qt(r,$l(Ir.S3_DOWNLOAD_ERR))}}o(PEe,"downloadFileFromS3");async function LEe(e,t){try{await Ri.mkdirp(ql),await Ri.writeFile(`${ql}/${e}`,t)}catch(r){throw zd.error(Ir.WRITE_TEMP_FILE_ERR),Qt(r,$l(Ir.DEFAULT_BULK_LOAD_ERR))}}o(LEe,"writeFileToTempFolder");async function yT(e){if(e)try{await Ri.access(e),await Ri.unlink(e)}catch{zd.warn(`could not delete temp csv file at ${e}, file does not exist`)}}o(yT,"deleteTempFile");function DEe(e,t){if(e.statusCode!==NY.HTTP_STATUS_CODES.OK)throw Qt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Jr.BAD_REQUEST);if(!bEe[e.headers["content-type"]])throw Qt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Jr.BAD_REQUEST);if(!e.raw)throw Qt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Jr.BAD_REQUEST)}o(DEe,"validateURLResponse");async function GC(e){try{let t;switch(e.file_type){case Ti.VALID_S3_FILE_TYPES.CSV:t=await MEe(e);break;case Ti.VALID_S3_FILE_TYPES.JSON:t=await vEe(e);break;default:throw Qt(new Error,Ir.DEFAULT_BULK_LOAD_ERR,Jr.BAD_REQUEST,Ti.LOG_LEVELS.ERROR,Ir.INVALID_FILE_EXT_ERR(e))}return MY(t.records,t.number_written)}catch(t){throw Vl(t)}}o(GC,"fileLoad");async function CY(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 RT.validation(a);e.role_perms&&e.role_perms.super_user!==!0&&OY(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=Qt(c);r(l)}}o(CY,"validateChunk");async function PY(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Wd.autoCastJSONDeep(i),s&&s.pause();let a=n.meta?n.meta.fields:null;if(a)i.forEach(c=>{!Wd.isEmpty(c)&&!Wd.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 wY.callOperationFunctionAsAwait(DY,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=Qt(c,$l(Ir.INSERT_CSV_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.INSERT_CSV_ERR+" - "+c);r(l)}}o(PY,"insertChunk");async function MEe(e){let t={records:0,number_written:0},r=LY(e.schema,e.table);try{let n=new kC,s=Ri.createReadStream(e.file_path,{highWaterMark:bY});s.setEncoding("utf8"),await BC.parsePromise(s,CY.bind(null,e,n),FC.bind(null,r));let i=n.getPermsResponse();if(i)throw Qt(new Error,i,Jr.BAD_REQUEST);return s=Ri.createReadStream(e.file_path,{highWaterMark:bY}),s.setEncoding("utf8"),await BC.parsePromise(s,PY.bind(null,e,t),FC.bind(null,r)),s.destroy(),t}catch(n){throw Qt(n,$l(Ir.PAPA_PARSE_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.PAPA_PARSE_ERR+n)}}o(MEe,"callPapaParse");function LY(e,t){let r=REe[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>yEe(i,s));return n}o(LY,"createTransformMap");function FC(e,t,r){let n=e.get(r);return n?n(t):Wd.autoCast(t)}o(FC,"typeFunction");async function vEe(e){let t={records:0,number_written:0},r=o(n=>{throw n},"throwErr");try{let n=new kC,s=gY([Ri.createReadStream(e.file_path,{encoding:"utf-8"}),SY.withParser(),c=>c.value,new TY({batchSize:IY}),RY(async c=>{await CY(e,n,r,c)})]);await new Promise((c,l)=>{yY(s,u=>{u?l(u):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw Qt(new Error,i,Jr.BAD_REQUEST);let a=gY([Ri.createReadStream(e.file_path,{encoding:"utf-8"}),SY.withParser(),c=>c.value,new TY({batchSize:IY}),RY(async c=>{await PY(e,t,r,c)})]);return await new Promise((c,l)=>{yY(a,u=>{u?l(u):c()}),a.resume()}),t}catch(n){throw Qt(n,$l(Ir.INSERT_JSON_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.INSERT_JSON_ERR+n)}}o(vEe,"insertJson");async function DY(e){let t={};try{e.data&&e.data.length>0&&UEe(e.data[0])?t=await xEe(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",zd.info(t.message))}catch(r){throw Vl(r)}return t}o(DY,"callBulkFileLoad");function UEe(e){let t=Object.keys(e);for(let r of t)if(!AEe.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}o(UEe,"validateColumnNames");async function xEe(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=RT.insert;break;case"update":i=RT.update;break;case"upsert":i=RT.upsert;break;default:throw Qt(new Error,Ir.INVALID_ACTION_PARAM_ERR(n),Jr.BAD_REQUEST,Ti.LOG_LEVELS.ERROR,Ir.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=Wd.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:a.new_attributes}}catch(a){throw Vl(a)}}o(xEe,"bulkFileLoad");function MY(e,t){return`successfully loaded ${t} of ${e} records`}o(MY,"buildResponseMsg");function Vl(e){return Qt(e,$l(Ir.DEFAULT_BULK_LOAD_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.DEFAULT_BULK_LOAD_ERR+" - "+e)}o(Vl,"buildTopLevelErrMsg")});var KC=M((A0e,$Y)=>{"use strict";var VC=nn(),BEe=DC(),{AsyncParser:FEe}=require("json2csv"),IT=require("stream"),ls=ie(),$C=require("fs-extra"),HEe=require("path"),xs=Q(),{promisify:FY}=require("util"),gp=ie(),{handleHDBError:_r,hdbErrors:kEe}=ge(),{HDB_ERROR_MSGS:Bn,HTTP_STATUS_CODES:gr}=kEe,{streamAsJSON:GEe}=(EA(),v(fv)),{Upload:qEe}=require("@aws-sdk/lib-storage"),{toCsvStream:$Ee}=(To(),v(Dv)),xY=["search_by_value","search_by_hash","sql","search_by_conditions"],BY=["json","csv"],HY="json",kY="csv",VEe="Successfully exported JSON locally.",KEe="Successfully exported CSV locally.",YEe=1e3,WEe=VC.searchByHash,zEe=VC.searchByValue,jEe=FY(IT.finished);$Y.exports={export_to_s3:ZEe,export_local:QEe};async function QEe(e){xs.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=GY(e);if(!ls.isEmpty(t))throw xs.error(t),_r(new Error,t,gr.BAD_REQUEST,void 0,void 0,!0);if(ls.isEmpty(e.path))throw xs.error(Bn.MISSING_VALUE("path")),_r(new Error,Bn.MISSING_VALUE("path"),gr.BAD_REQUEST,void 0,void 0,!0);let r=(ls.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(HEe.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=ls.buildFolderPath(e.path,r);await JEe(e.path);let s=await qY(e);return await XEe(n,e.format,s)}o(QEe,"export_local");async function JEe(e){if(xs.trace("in confirmPath"),ls.isEmptyOrZeroLength(e))throw _r(new Error,`Invalid path: ${e}`,gr.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await $C.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,xs.error(n),_r(new Error,n,gr.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw xs.error(r),_r(new Error,r,gr.BAD_REQUEST,void 0,void 0,!0)}return!0}o(JEe,"confirmPath");async function XEe(e,t,r){if(xs.trace("in saveToLocal"),gp.isEmptyOrZeroLength(e))throw _r(new Error,Bn.INVALID_VALUE("file_path"),gr.BAD_REQUEST,void 0,void 0,!0);if(gp.isEmptyOrZeroLength(t))throw _r(new Error,Bn.INVALID_VALUE("Source format"),gr.BAD_REQUEST,void 0,void 0,!0);if(gp.isEmpty(r))throw _r(new Error,Bn.NOT_FOUND("Data"),gr.BAD_REQUEST,void 0,void 0,!0);if(t===HY){let n=$C.createWriteStream(e);return GEe(r).pipe(n),await jEe(n),{message:VEe,path:e}}else if(t===kY){let n=$C.createWriteStream(e),s=IT.Readable.from(r),i={},a=r.getColumns?.();a&&(i.fields=a.map(d=>({label:d,value:d})));let c={objectMode:!0};return await new FEe(i,c).fromInput(s).toOutput(n).promise(!1),{message:KEe,path:e}}throw _r(new Error,Bn.INVALID_VALUE("format"),gr.BAD_REQUEST)}o(XEe,"saveToLocal");async function ZEe(e){if(!e.s3||Object.keys(e.s3).length===0)throw _r(new Error,Bn.MISSING_VALUE("S3 object"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw _r(new Error,Bn.MISSING_VALUE("aws_access_key_id"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw _r(new Error,Bn.MISSING_VALUE("aws_secret_access_key"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.bucket))throw _r(new Error,Bn.MISSING_VALUE("bucket"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.key))throw _r(new Error,Bn.MISSING_VALUE("key"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.region))throw _r(new Error,Bn.MISSING_VALUE("region"),gr.BAD_REQUEST);let t=GY(e);if(!ls.isEmpty(t))throw _r(new Error,t,gr.BAD_REQUEST);xs.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await qY(e)}catch(l){throw xs.error(l),l}let n,s=await BEe.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,a=new IT.PassThrough;if(e.format===kY){i=e.s3.key+".csv";let l=$Ee(r,r.getColumns?.());l.on("error",u=>{throw u}),l.pipe(a)}else if(e.format===HY){i=e.s3.key+".json";let l=new IT.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%YEe===0&&(l.push(d),d="")}d.length!==0&&l.push(d),l.push("]"),l.push(null)}else throw _r(new Error,Bn.INVALID_VALUE("format"),gr.BAD_REQUEST);return new qEe({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:a}}).done()}o(ZEe,"export_to_s3");function GY(e){if(xs.trace("in exportCoreValidation"),ls.isEmpty(e.format))return"format missing";if(BY.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${BY.join(", ")}`;let t=e.search_operation.operation;if(ls.isEmpty(t))return"search_operation.operation missing";if(xY.indexOf(t)<0)return`searchOperation.operation must be one of the following values: ${xY.join(", ")}`}o(GY,"exportCoreValidation");async function qY(e){xs.trace("in getRecords");let t,r;if(gp.isEmpty(e.search_operation)||gp.isEmptyOrZeroLength(e.search_operation.operation))throw _r(new Error,Bn.INVALID_VALUE("Search operation"),gr.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=zEe;break;case"search_by_hash":t=WEe;break;case"search_by_conditions":t=VC.searchByConditions;break;case"sql":{let n=mT();t=FY(n.evaluateSQL);break}default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,xs.error(r),_r(new Error,r,gr.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}o(qY,"getRecords")});var KY=M((I0e,VY)=>{"use strict";var YC=class{static{o(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};VY.exports=YC});var zY=M((w0e,WY)=>{"use strict";var e_e=(k(),v(W)),YY=require("moment"),t_e=require("uuid").v4,WC=class{static{o(this,"JobObject")}constructor(){this.id=t_e(),this.type=void 0,this.start_datetime=YY().valueOf(),this.created_datetime=YY().valueOf(),this.end_datetime=void 0,this.status=e_e.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};WY.exports=WC});var zC=M((C0e,rW)=>{"use strict";var r_e=require("uuid").v4,ZY=Cn(),eW=nn(),n_e=ci(),s_e=qu(),i_e=KY(),Dt=(k(),v(W)),o_e=zY(),a_e=pg(),yi=Q(),c_e=Xf(),jd=ie(),{promisify:l_e}=require("util"),Kl=require("moment"),u_e=mT(),NT=PC(),jY=hb(),{deleteTransactionLogsBeforeValidator:d_e}=XO(),{handleHDBError:QY,hdbErrors:f_e,ClientError:m_e}=ge(),{HTTP_STATUS_CODES:JY}=f_e,XY=eW.searchByValue,h_e=eW.searchByHash,p_e=ZY.insert,E_e=l_e(u_e.evaluateSQL),__e=ZY.update;rW.exports={addJob:T_e,updateJob:y_e,handleGetJob:g_e,handleGetJobsByStartDate:S_e,getJobById:tW};async function g_e(e){if(e.id===void 0)throw new m_e("'id' is required");let t=await tW(e.id);return jd.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(g_e,"handleGetJob");async function S_e(e){try{let t=await R_e(e);if(yi.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=Kl(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Kl(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 yi.error(r),new Error(r)}}o(S_e,"handleGetJobsByStartDate");async function T_e(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||jd.isEmptyOrZeroLength(e.operation)){let d="job parameter is invalid";return yi.info(d),t.error=d,t}if(!Dt.JOB_TYPE_ENUM[e.operation])return yi.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Dt.OPERATIONS_ENUM.CSV_FILE_LOAD:n=NT.fileObject(e);break;case Dt.OPERATIONS_ENUM.CSV_URL_LOAD:n=NT.urlObject(e);break;case Dt.OPERATIONS_ENUM.CSV_DATA_LOAD:n=NT.dataObject(e);break;case Dt.OPERATIONS_ENUM.IMPORT_FROM_S3:n=NT.s3FileObject(e);break;case Dt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Dt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=jY(e,"date");break;case Dt.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=jY(e,"timestamp");break;case Dt.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=d_e(e);break;case Dt.OPERATIONS_ENUM.RESTART_SERVICE:if(Dt.HDB_PROCESS_SERVICES[e.service]===void 0)throw QY(new Error,"Invalid service",JY.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw QY(n,n.message,JY.BAD_REQUEST,void 0,void 0,!0);let s=new o_e;s.type=e.operation===Dt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Dt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user?.username;let i=new n_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),a;try{a=Array.from(await XY(i))}catch(d){let f=`There was an error inserting a new job: ${d}`;return yi.error(f),t}let c=Array.isArray(a)?a:Object.keys(a);if(c&&c.length>0){s.id=r_e();try{a=await XY(i)}catch(d){let f=`There was an error inserting a new job: ${d}`;return yi.error(f),t}if(c=Array.isArray(a)?a:Object.keys(a),c&&c.length>0)return yi.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new c_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),u;try{u=await p_e(l)}catch(d){return yi.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,yi.trace(d)}return t}o(T_e,"addJob");async function R_e(e){let t=Kl(e.from_date,Kl.ISO_8601),r=Kl(e.to_date,Kl.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 i_e(n,e.hdb_user);try{return await E_e(s)}catch(i){throw yi.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(R_e,"getJobsInDateRange");async function tW(e){if(jd.isEmptyOrZeroLength(e))return jd.errorizeMessage("Invalid job ID specified.");let t=new s_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await h_e(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return yi.error(n),jd.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}o(tW,"getJobById");async function y_e(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(jd.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Dt.JOB_STATUS_ENUM.COMPLETE||e.status===Dt.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Kl().valueOf());let t=new a_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await __e(t),r}o(y_e,"updateJob")});var uW=M((L0e,lW)=>{"use strict";var nW=ie(),Nr=(k(),v(W)),A_e=require("moment"),wT=qC(),Sp=Q(),sW=zC(),iW=KC(),oW=Xc(),aW=nt(),b_e=nT(),I_e=kd(),{parentPort:N_e,isMainThread:cW}=require("worker_threads"),{onMessageByType:w_e}=nt(),jC=class{static{o(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function O_e(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(nW.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(nW.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nr.JOB_TYPE_ENUM.csv_file_load:await Zi(e,wT.csvFileLoad);break;case Nr.JOB_TYPE_ENUM.csv_url_load:await Zi(e,wT.csvURLLoad);break;case Nr.JOB_TYPE_ENUM.csv_data_load:await Zi(e,wT.csvDataLoad);break;case Nr.JOB_TYPE_ENUM.import_from_s3:await Zi(e,wT.importFromS3);break;case Nr.JOB_TYPE_ENUM.empty_trash:break;case Nr.JOB_TYPE_ENUM.export_local:await Zi(e,iW.export_local);break;case Nr.JOB_TYPE_ENUM.export_to_s3:await Zi(e,iW.export_to_s3);break;case Nr.JOB_TYPE_ENUM.delete_files_before:case Nr.JOB_TYPE_ENUM.delete_records_before:await Zi(e,oW.deleteFilesBefore);break;case Nr.JOB_TYPE_ENUM.delete_audit_logs_before:await Zi(e,oW.deleteAuditLogsBefore);break;case Nr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Zi(e,b_e.deleteTransactionLogsBefore);break;case Nr.JOB_TYPE_ENUM.restart_service:return await Zi(e,I_e.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}o(O_e,"parseMessage");async function Zi(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=A_e().valueOf(),await sW.updateJob(e.job),await C_e(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):Sp.error(`There was an error running ${t.name} job with id ${e.job.id}`),Sp.error(n),e.job.message=n,e.job.status=Nr.JOB_STATUS_ENUM.ERROR;try{await sW.updateJob(e.job)}catch(s){throw Sp.error(`Unable to update job with id ${e.job.id}`),s}throw r}}o(Zi,"runJob");async function C_e(e){Sp.trace("launching job thread:",e),cW?aW.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):N_e.postMessage({type:Nr.ITC_EVENT_TYPES.START_JOB,jobId:e})}o(C_e,"launchJobThread");cW&&w_e(Nr.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{aW.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){Sp.error(r)}});lW.exports={parseMessage:O_e,RunnerMessage:jC}});var fW=M((M0e,dW)=>{"use strict";var P_e=ie(),QC=oe(),cc=(k(),v(W)),L_e=Ot(),D_e=mr(),eo=Q(),M_e=xC(),v_e=ki();QC.initSync();dW.exports={postOperationHandler:x_e,sendOperationTransaction:Tp};async function Tp(e,t,r,n){if(e.schema===cc.SYSTEM_SCHEMA_NAME)return;let s=U_e(e,t,r);s&&(eo.trace(`sendOperationTransaction publishing to schema ${e.schema} following transaction:`,s),await D_e.publishToStream(`${L_e.SUBJECT_PREFIXES.TXN}.${e.schema}`,v_e.createNatsTableStreamName(e.schema,e.table),n,s))}o(Tp,"sendOperationTransaction");function U_e(e,t,r){if(P_e.isEmptyOrZeroLength(t))return null;let n={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===cc.OPERATIONS_ENUM.DELETE?n.hash_values=t:n.records=e.records,n}o(U_e,"convertCRUDOperationToTransaction");async function x_e(e,t,r){if(!QC.get(cc.CONFIG_PARAMS.CLUSTERING_ENABLED))return;eo.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let n=e.hdb_user?.username,s=QC.get(cc.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new M_e(t.txn_time,n,s);switch(e.operation){case cc.OPERATIONS_ENUM.INSERT:try{await Tp(e,t.inserted_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for insert."),eo.error(a)}break;case cc.OPERATIONS_ENUM.DELETE:try{await Tp(e,t.deleted_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for delete."),eo.error(a)}break;case cc.OPERATIONS_ENUM.UPDATE:try{await Tp(e,t.update_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for update."),eo.error(a)}break;case cc.OPERATIONS_ENUM.UPSERT:try{await Tp(e,t.upserted_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for upsert."),eo.error(a)}break;default:break}return t}o(x_e,"postOperationHandler")});var J,mW=ce(()=>{J=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 QO={};we(QO,{chooseOperation:()=>DW,executeJob:()=>Bs,getOperationFunction:()=>MW,operation:()=>iP,processLocalTransaction:()=>LW});async function LW(e,t){try{if(e.body.operation!=="read_log"&&(bp.default.log_level===$f.INFO||bp.default.log_level===$f.DEBUG||bp.default.log_level===$f.TRACE)){let{hdb_user:n,hdbAuthHeader:s,password:i,payload:a,...c}=e.body;gn.info(c)}}catch(n){gn.error(n)}let r=await CW.default.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return H_e[e.body.operation]&&IW.default.setSchemaDataToGlobal(n=>{n&&gn.error(n)}),r}function DW(e){let t;try{t=MW(e)}catch(s){throw gn.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=PT.default.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let a=PT.default.checkASTPermissions(e,i);if(a)throw gn.error(`${hW.FORBIDDEN} from operation ${e.operation}`),gn.warn(`User '${e.hdb_user?.username}' is not permitted to ${e.operation}`),(0,Fs.handleHDBError)(new Error,a,Fs.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.LOGIN&&e.operation!==q.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=bW.default.verifyPerms(i,s);if(a)throw gn.error(`${hW.FORBIDDEN} from operation ${e.operation}`),gn.warn(`User '${i.hdb_user?.username}' is not permitted to ${i.operation}`),(0,Fs.handleHDBError)(new Error,a,Fs.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw(0,Fs.handleHDBError)(s,"There was an error when trying to choose an operation path")}return r}function MW(e){if(gn.trace(`getOperationFunction with operation: ${e.operation}`),pW.has(e.operation))return pW.get(e.operation);throw(0,Fs.handleHDBError)(new Error,Fs.hdbErrors.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Fs.hdbErrors.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}function iP(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=DW(e);return LW({body:e},n)}async function k_e(e){gn.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[Qy]=!0;let a;switch(i.operation){case q.INSERT:a=await Wl.default.insert(i);break;case q.UPDATE:a=await Wl.default.update(i);break;case q.UPSERT:a=await Wl.default.upsert(i);break;case q.DELETE:a=await Xd.default.deleteRecord(i);break;default:gn.warn("invalid operation in catchup");break}await PW.transactToClusteringUtils.postOperationHandler(i,a,e)}catch(a){gn.info("Invalid operation in transaction"),gn.error(a)}}async function Bs(e){(0,OW.transformReq)(e);let t,r;try{if(r=await LT.default.addJob(e),r){t=r.createdJob,gn.info("addJob result",r);let n=new eP.default.RunnerMessage(t,e);return{message:await eP.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 gn.error(i),(0,Fs.handleHDBError)(n,i)}}function G_e(){let e=new Map;return e.set(q.INSERT,new J(Wl.default.insert)),e.set(q.UPDATE,new J(Wl.default.update)),e.set(q.UPSERT,new J(Wl.default.upsert)),e.set(q.SEARCH_BY_CONDITIONS,new J(Jd.default.searchByConditions)),e.set(q.SEARCH_BY_HASH,new J(Jd.default.searchByHash)),e.set(q.SEARCH_BY_ID,new J(Jd.default.searchByHash)),e.set(q.SEARCH_BY_VALUE,new J(Jd.default.searchByValue)),e.set(q.SEARCH,new J(B_e)),e.set(q.SQL,new J(F_e)),e.set(q.CSV_DATA_LOAD,new J(Bs,Rp.default.csvDataLoad)),e.set(q.CSV_FILE_LOAD,new J(Bs,Rp.default.csvFileLoad)),e.set(q.CSV_URL_LOAD,new J(Bs,Rp.default.csvURLLoad)),e.set(q.IMPORT_FROM_S3,new J(Bs,Rp.default.importFromS3)),e.set(q.CREATE_SCHEMA,new J(Ai.default.createSchema)),e.set(q.CREATE_DATABASE,new J(Ai.default.createSchema)),e.set(q.CREATE_TABLE,new J(Ai.default.createTable)),e.set(q.CREATE_ATTRIBUTE,new J(Ai.default.createAttribute)),e.set(q.DROP_SCHEMA,new J(Ai.default.dropSchema)),e.set(q.DROP_DATABASE,new J(Ai.default.dropSchema)),e.set(q.DROP_TABLE,new J(Ai.default.dropTable)),e.set(q.DROP_ATTRIBUTE,new J(Ai.default.dropAttribute)),e.set(q.DESCRIBE_SCHEMA,new J(yp.default.describeSchema)),e.set(q.DESCRIBE_DATABASE,new J(yp.default.describeSchema)),e.set(q.DESCRIBE_TABLE,new J(yp.default.describeTable)),e.set(q.DESCRIBE_ALL,new J(yp.default.describeAll)),e.set(q.DELETE,new J(Xd.default.deleteRecord)),e.set(q.ADD_USER,new J(Qd.default.addUser)),e.set(q.ALTER_USER,new J(Qd.default.alterUser)),e.set(q.DROP_USER,new J(Qd.default.dropUser)),e.set(q.LIST_USERS,new J(Qd.default.listUsersExternal)),e.set(q.LIST_ROLES,new J(Ap.default.listRoles)),e.set(q.ADD_ROLE,new J(Ap.default.addRole)),e.set(q.ALTER_ROLE,new J(Ap.default.alterRole)),e.set(q.DROP_ROLE,new J(Ap.default.dropRole)),e.set(q.USER_INFO,new J(Qd.default.userInfo)),e.set(q.READ_LOG,new J(_W.default)),e.set(q.ADD_NODE,new J(gW.default)),e.set(q.UPDATE_NODE,new J(JC.default)),e.set(q.SET_NODE_REPLICATION,new J(JC.default)),e.set(q.REMOVE_NODE,new J(SW.default)),e.set(q.CONFIGURE_CLUSTER,new J(TW.default)),e.set(q.PURGE_STREAM,new J(RW.default)),e.set(q.SET_CONFIGURATION,new J(tP.default.setConfiguration)),e.set(q.CLUSTER_STATUS,new J(yW.default.clusterStatus)),e.set(q.CLUSTER_NETWORK,new J(AW.default)),e.set(q.CLUSTER_SET_ROUTES,new J(OT.default.setRoutes)),e.set(q.CLUSTER_GET_ROUTES,new J(OT.default.getRoutes)),e.set(q.CLUSTER_DELETE_ROUTES,new J(OT.default.deleteRoutes)),e.set(q.EXPORT_TO_S3,new J(Bs,XC.default.export_to_s3)),e.set(q.CREATE_CSR,new J(Yl.default.createCsr)),e.set(q.SIGN_CERTIFICATE,new J(Yl.default.signCertificate)),e.set(q.LIST_CERTIFICATES,new J(Yl.default.listCertificates)),e.set(q.ADD_CERTIFICATES,new J(Yl.default.addCertificate)),e.set(q.REMOVE_CERTIFICATE,new J(Yl.default.removeCertificate)),e.set(q.GET_KEY,new J(Yl.default.getKey)),e.set(q.ADD_NODE_BACK,new J(Vw)),e.set(q.REMOVE_NODE_BACK,new J(Kw)),e.set(q.DELETE_FILES_BEFORE,new J(Bs,Xd.default.deleteFilesBefore)),e.set(q.DELETE_RECORDS_BEFORE,new J(Bs,Xd.default.deleteFilesBefore)),e.set(q.EXPORT_LOCAL,new J(Bs,XC.default.export_local)),e.set(q.SEARCH_JOBS_BY_START_DATE,new J(LT.default.handleGetJobsByStartDate)),e.set(q.GET_JOB,new J(LT.default.handleGetJob)),e.set(q.GET_FINGERPRINT,new J(CT.default.getFingerprint)),e.set(q.SET_LICENSE,new J(CT.default.setLicense)),e.set(q.GET_REGISTRATION_INFO,new J(CT.default.getRegistrationInfo)),e.set(q.RESTART,new J(ZC.default.restart)),e.set(q.RESTART_SERVICE,new J(Bs,ZC.default.restartService)),e.set(q.CATCHUP,new J(k_e)),e.set(q.SYSTEM_INFORMATION,new J(NW.default.systemInformation)),e.set(q.DELETE_AUDIT_LOGS_BEFORE,new J(Bs,Xd.default.deleteAuditLogsBefore)),e.set(q.READ_AUDIT_LOG,new J(EW.default)),e.set(q.CREATE_AUTHENTICATION_TOKENS,new J(_N)),e.set(q.REFRESH_OPERATION_TOKEN,new J(gN)),e.set(q.LOGIN,new J(qO)),e.set(q.LOGOUT,new J($O)),e.set(q.GET_CONFIGURATION,new J(tP.default.getConfiguration)),e.set(q.CUSTOM_FUNCTIONS_STATUS,new J(Mt.default.customFunctionsStatus)),e.set(q.GET_CUSTOM_FUNCTIONS,new J(Mt.default.getCustomFunctions)),e.set(q.GET_COMPONENT_FILE,new J(Mt.default.getComponentFile)),e.set(q.GET_COMPONENTS,new J(Mt.default.getComponents)),e.set(q.SET_COMPONENT_FILE,new J(Mt.default.setComponentFile)),e.set(q.DROP_COMPONENT,new J(Mt.default.dropComponent)),e.set(q.GET_CUSTOM_FUNCTION,new J(Mt.default.getCustomFunction)),e.set(q.SET_CUSTOM_FUNCTION,new J(Mt.default.setCustomFunction)),e.set(q.DROP_CUSTOM_FUNCTION,new J(Mt.default.dropCustomFunction)),e.set(q.ADD_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.addComponent)),e.set(q.ADD_COMPONENT,new J(Mt.default.addComponent)),e.set(q.DROP_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.dropCustomFunctionProject)),e.set(q.PACKAGE_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.packageComponent)),e.set(q.PACKAGE_COMPONENT,new J(Mt.default.packageComponent)),e.set(q.DEPLOY_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.deployComponent)),e.set(q.DEPLOY_COMPONENT,new J(Mt.default.deployComponent)),e.set(q.READ_TRANSACTION_LOG,new J(rP.default.readTransactionLog)),e.set(q.DELETE_TRANSACTION_LOGS_BEFORE,new J(Bs,rP.default.deleteTransactionLogsBefore)),e.set(q.INSTALL_NODE_MODULES,new J(nP.default.installModules)),e.set(q.AUDIT_NODE_MODULES,new J(nP.default.auditModules)),e.set(q.GET_BACKUP,new J(Ai.default.getBackup)),e.set(q.CLEANUP_ORPHAN_BLOBS,new J(Ai.default.cleanupOrphanBlobs)),e.set(q.ADD_SSH_KEY,new J(Mt.default.addSSHKey)),e.set(q.UPDATE_SSH_KEY,new J(Mt.default.updateSSHKey)),e.set(q.DELETE_SSH_KEY,new J(Mt.default.deleteSSHKey)),e.set(q.LIST_SSH_KEYS,new J(Mt.default.listSSHKeys)),e.set(q.SET_SSH_KNOWN_HOSTS,new J(Mt.default.setSSHKnownHosts)),e.set(q.GET_SSH_KNOWN_HOSTS,new J(Mt.default.getSSHKnownHosts)),e.set(q.GET_ANALYTICS,new J(eC)),e.set(q.LIST_METRICS,new J(tC)),e.set(q.DESCRIBE_METRIC,new J(rC)),e.set(q.GET_STATUS,new J(aC)),e.set(q.SET_STATUS,new J(cC)),e.set(q.CLEAR_STATUS,new J(oC)),e}var Jd,PT,Rp,Ai,yp,Xd,EW,Qd,Ap,Mt,bp,_W,gW,JC,SW,TW,RW,yW,AW,OT,XC,bW,LT,Fs,CT,ZC,sP,Wl,IW,NW,eP,tP,rP,nP,wW,OW,Yl,CW,PW,hW,gn,B_e,F_e,H_e,pW,JO=ce(()=>{Jd=w(nn()),PT=w(mT()),Rp=w(qC()),Ai=w(wh()),yp=w(Ca()),Xd=w(Xc()),EW=w(gw()),Qd=w(Xn()),Ap=w(jm()),Mt=w(jO()),bp=w(Q()),_W=w(Aw()),gW=w(RS()),JC=w(Qw()),SW=w(AS()),TW=w(Zw()),RW=w(eO()),yW=w(nO()),AW=w(iO()),OT=w(OS()),XC=w(KC()),bW=w(dT()),LT=w(zC());k();Fs=w(ge()),CT=w(gO()),ZC=w(kd()),sP=w(require("util")),Wl=w(Cn()),IW=w(ni()),NW=w(bd()),eP=w(uW());ed();jS();tP=w(wt()),rP=w(nT()),nP=w(tp()),wW=w(Zs()),OW=w(ie());Dr();Yl=w(ss());Nd();sC();CW=w(LC()),PW=w(fW());dp();mW();({HTTP_STATUS_CODES:hW}=Fs.hdbErrors),gn=bp.default.loggerWithTag("operation"),B_e=sP.promisify(Jd.default.search),F_e=sP.promisify(PT.default.evaluateSQL),H_e={[q.CREATE_ATTRIBUTE]:!0,[q.CREATE_TABLE]:!0,[q.CREATE_SCHEMA]:!0,[q.DROP_ATTRIBUTE]:!0,[q.DROP_TABLE]:!0,[q.DROP_SCHEMA]:!0};o(LW,"processLocalTransaction");pW=G_e();Le.operation=iP;o(DW,"chooseOperation");o(MW,"getOperationFunction");(0,wW._assignPackageExport)("operation",iP);o(iP,"operation");o(k_e,"catchup");o(Bs,"executeJob");o(G_e,"initializeOperationFunctionMap")});var vT=M((k0e,xW)=>{"use strict";var DT=(k(),v(W)),q_e=ie(),Ip=Q(),{handleHDBError:oP,hdbErrors:MT}=ge(),{isMainThread:$_e}=require("worker_threads"),{Readable:V_e}=require("stream"),vW=require("os"),K_e=require("util"),Y_e=TN(),W_e=K_e.promisify(Y_e.authorize),UW=(JO(),v(QO)),{createGzip:z_e,constants:j_e}=require("zlib"),Q_e=[DT.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,DT.OPERATIONS_ENUM.LOGIN,DT.OPERATIONS_ENUM.LOGOUT];function J_e(e){let t=`Found an uncaught exception with message: ${e.message}. ${vW.EOL}Stack: ${e.stack} ${vW.EOL}Terminating ${$_e?"HDB":"thread"}.`;console.error(t),Ip.fatal(t),process.exit(1)}o(J_e,"handleServerUncaughtException");function X_e(e,t,r){if(Ip[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:MT.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(X_e,"serverErrorHandler");function Z_e(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=oP(new Error,"Invalid JSON.",MT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(q_e.isEmpty(e.body.operation)){let n=oP(new Error,"Request body must include an 'operation' property.",MT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}o(Z_e,"reqBodyValidationHandler");function ege(e,t,r){let n;!Q_e.includes(e.body.operation)||e.body.operation===DT.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&!e.body.username&&!e.body.password?W_e(e,t).then(i=>{n=i,e.body.hdb_user=n,r()}).catch(i=>{Ip.warn(i),Ip.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${i.stack}"`);let a=typeof i=="string"?{error:i}:{error:i.message};r(oP(i,a,MT.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(ege,"authHandler");async function tge(e,t,r=!1){let n;try{e.body.bypass_auth&&delete e.body.bypass_auth,n=UW.chooseOperation(e.body);let s=await UW.processLocalTransaction(e,n);if(s instanceof V_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(z_e({level:j_e.Z_BEST_SPEED})))}return s}catch(s){throw Ip.error(s),s}}o(tge,"handlePostRequest");xW.exports={authHandler:ege,handlePostRequest:tge,handleServerUncaughtException:J_e,serverErrorHandler:X_e,reqBodyValidationHandler:Z_e}});var kW=M((q0e,HW)=>{"use strict";var rge=require("fastify-plugin"),{handlePostRequest:BW,authHandler:nge,reqBodyValidationHandler:sge}=vT();async function ige(e){e.decorate("hdbCore",{preValidation:[sge,nge],request:o((t,r)=>FW(BW(t,r)),"request"),requestWithoutAuthentication:o((t,r)=>FW(BW(t,r,!0)),"requestWithoutAuthentication")})}o(ige,"hdbCore");async function FW(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(FW,"convertAsyncIterators");HW.exports=rge(ige)});var qW=M((K0e,GW)=>{"use strict";var V0e=require("fs"),UT=oe();UT.initSync();var{CONFIG_PARAMS:aP}=(k(),v(W)),oge=1024*1024*1024;function age(e){let t=UT.get(aP.HTTP_TIMEOUT),r=UT.get(aP.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:oge,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,maxParamLength:UT.get(aP.HTTP_MAXPARAMLENGTH)??1e3,https:e}}o(age,"getServerOptions");GW.exports=age});var KW=M((W0e,VW)=>{"use strict";var cP=oe();cP.initSync();var{CONFIG_PARAMS:$W}=(k(),v(W));function cge(){let e=cP.get($W.HTTP_CORSACCESSLIST),t=cP.get($W.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(cge,"getCORSOptions");VW.exports=cge});var zW=M((j0e,WW)=>{"use strict";var YW=oe();YW.initSync();var lge=(k(),v(W));function uge(){return YW.get(lge.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}o(uge,"getHeaderTimeoutConfig");WW.exports=uge});var uP={};we(uP,{customFunctionsServer:()=>mge,ready:()=>cz,start:()=>fge});function fge(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Qo||(Qo=az(t),Le.http((await Qo).server));let a=await Qo,c=(0,lP.dirname)(s),l=(0,lP.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!jW.has(c)){jW.add(c);try{a.register(pge(c,l))}catch(u){if(u.message==="Root plugin has already booted")yt.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw u}}},ready:cz}}async function mge(){try{yt.info("In Custom Functions Fastify server"+process.cwd()),yt.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),yt.debug(`Custom Functions server process ${process.pid} starting up.`),await hge();let e=tz.get(U.HTTP_SECUREPORT)>0,t;try{t=Qo=await az(e)}catch(r){throw yt.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw yt.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){yt.error(`Custom Functions ${process.pid} Error: ${e}`),yt.error(e),process.exit(1)}}async function hge(){try{yt.info("Custom Functions starting configuration."),await rz.setUsersWithRolesCache(),yt.info("Custom Functions completed configuration.")}catch(e){yt.error(e)}}function pge(e,t){return async function(r){try{yt.info("Custom Functions starting buildRoutes"),yt.trace("Loading fastify routes folder "+e),(0,QW.existsSync)(e)&&r.register(ez.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:yt.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,a)=>{s?.message?yt.error(s.message):s&&yt.error(s),a()})}catch(n){yt.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function az(e){yt.info("Custom Functions starting buildServer.");let t=(0,nz.default)(e),r=(0,JW.default)(t);r.server.headersTimeout=(0,iz.default)(),r.setErrorHandler(oz.serverErrorHandler);let n=(0,sz.default)();return n&&r.register(XW.default,n),r.register(function(s,i,a){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),a()}),r.register(ZW.default),await r.register(dge),await r.after(),dm(r),yt.info("Custom Functions completed buildServer."),r}function cz(){if(Qo)return Qo.then?Qo.then(e=>e.ready()):Qo.ready()}var lP,QW,JW,XW,ZW,ez,tz,yt,dge,rz,nz,sz,iz,oz,Qo,jW,lz=ce(()=>{lP=require("path"),QW=require("fs"),JW=w(require("fastify")),XW=w(require("@fastify/cors")),ZW=w(mN()),ez=w(require("@fastify/autoload")),tz=w(oe());k();yt=w(Q()),dge=w(kW()),rz=w(Xn()),nz=w(qW()),sz=w(KW()),iz=w(zW()),oz=w(vT());To();Dr();jW=new Set;o(fge,"start");o(mge,"customFunctionsServer");o(hge,"setUp");o(pge,"buildRouteFolder");o(az,"buildServer");o(cz,"ready")});var dP={};we(dP,{start:()=>Ege});function Ege(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,hz.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){dz||(dz=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let a=uz.get(s.pathname);if(a)return{handlesHeaders:!0,body:(0,fz.default)(s,(0,mz.realpathSync)(a))}}return i(s)},{runFirst:!0})),uz.set(r,n)}}}var fz,mz,hz,uz,dz,pz=ce(()=>{fz=w(require("send")),mz=require("fs"),hz=w(require("serve-static")),uz=new Map;o(Ege,"start")});var fP={};we(fP,{start:()=>_ge});function _ge({override:e}){return{handleFile:o((t,r,n)=>{xT.default.debug(`Loading env file: ${n}`);for(let[s,i]of Object.entries((0,Ez.parse)(t))){if(process.env[s]!==void 0)if(xT.default.warn(`Environment variable conflict: ${s} from ${n} is already set on process.env`),e)xT.default.debug(`override option enabled. overriding environment variable: ${s}`);else continue;process.env[s]=i}},"handleFile")}}var Ez,xT,_z=ce(()=>{Ez=require("dotenv"),xT=w(Q());o(_ge,"start")});var pP={};we(pP,{DataLoaderError:()=>us,DataLoaderResult:()=>Zd,EmptyFileError:()=>kT,FileParseError:()=>HT,InvalidPropertyTypeError:()=>GT,MissingRequiredPropertyError:()=>Np,RecordProcessingError:()=>wp,SystemDatabaseError:()=>qT,UnsupportedFileExtensionError:()=>FT,computeRecordHash:()=>hP,handleApplication:()=>Tge,loadDataFile:()=>Iz,suppressHandleApplicationWarning:()=>Sge});function hP(e){let t=Object.keys(e).sort(),r={};for(let s of t)r[s]=e[s];let n=JSON.stringify(r);return(0,Sz.createHash)("sha256").update(n).digest("hex")}function bz(e){return e.system&&e.system[mP]?e.system[mP]:BT||(BT=ze({database:"system",table:mP,attributes:[{name:"id",type:"string",isPrimaryKey:!0},{name:"hash",type:"string"}]}),BT)}async function gge(e,t,r,n){try{let s=bz(n),i=e?`${e}:${t}:${r}`:`${t}:${r}`;return(await s.get(i))?.hash||null}catch(s){return Hs.error?.(`Failed to get stored hash: ${s.message}`),null}}async function gz(e,t,r,n,s){try{let i=bz(s),a=e?`${e}:${t}:${r}`:`${t}:${r}`;await i.put({id:a,hash:n})}catch(i){Hs.error?.(`Failed to store hash: ${i.message}`)}}function Tge(e){if((0,Rz.getWorkerIndex)()!==0){Hs.debug?.("Skipping data loader initialization on non-primary worker");return}e.handleEntry(t=>{t.entryType!=="file"||t.eventType==="unlink"||Iz(t,ln,He).then(r=>{Hs.debug?.("Data loader processed file: %s: %s",(0,Jo.basename)(t.absolutePath),r.message)})})}async function Iz({contents:e,absolutePath:t,stats:r},n,s){let i=(0,Jo.extname)(t)||"unknown",a;try{if(i===".yaml"||i===".yml")a=(0,Tz.parseDocument)(e.toString()).toJSON();else if(i===".json")a=JSON.parse(e.toString());else throw new FT(t,i)}catch(f){throw f instanceof us?f:new HT(t,f)}if(!a)throw new kT(t);let{database:c,table:l,records:u}=a;if(!l)throw new Np(t,"table");if(!u)throw new Np(t,"records");if(!Array.isArray(u))throw new GT(t,"records","array");let d=c?`${c}.${l}`:l;if(c?.toLowerCase()==="system")throw new qT(c,l);try{let f;if(c&&s[c]&&s[c][l])Hs.debug?.(`Using existing table ${d} from database tables`),f=s[c][l];else if(n&&n[l])Hs.debug?.(`Using existing table ${d} from global tables`),f=n[l];else{Hs.debug?.(`Table ${d} not found, creating new table`);let R=[];if(u.length>0){let T=u[0];Object.keys(T).map(y=>{let N={name:y,type:typeof T[y]};return y==="id"&&(N.isPrimaryKey=!0),N}).forEach(y=>{R.push(y)})}f=await ze({database:c,table:l,attributes:R})}let m=u.length,h=0,p=0,_=0,g=100;for(let R=0;R<u.length;R+=g){let T=u.slice(R,R+g),y=[];for(let N of T)y.push(async()=>{try{let O=null,F=N.id;F!==void 0&&(O=await f.get(F));let Z=hP(N);if(!O){h++;let $=await f.put(N);return await gz(c,l,F,Z,s),$}let G=await gge(c,l,F,s);if(!G)return _++,Promise.resolve({inserted:0,updated:0});let Y={};for(let $ of Object.keys(N))$ in O&&(Y[$]=O[$]);return hP(Y)!==G?(_++,Promise.resolve({inserted:0,updated:0})):Z!==G?(p++,await f.patch(F,N),await gz(c,l,F,Z,s),{updated:1}):(_++,Promise.resolve({inserted:0,updated:0}))}catch(O){if(O instanceof us)Hs.error?.(`Record processing error: ${O.message}`);else{let F=new wp(d,O);Hs.error?.(`Record processing error: ${F.message}`)}return Promise.resolve({inserted:0,updated:0,error:O.message})}});await Promise.all(y.map(N=>N()))}if(h>0||p>0){let R=`Loaded ${h} new and updated ${p} records in ${d}`;return _>0&&(R+=` (${_} records skipped)`),Hs.info?.(R),new Zd(t,c,l,"success",h+p,R)}else if(_>0){let R=`All ${_} records in ${d} already up-to-date`;return Hs.info?.(R),new Zd(t,c,l,"skipped",m,R)}else{let R=`No records to process in ${d}`;return Hs.info?.(R),new Zd(t,c,l,"success",0,R)}}catch(f){throw f instanceof us?f:new wp(d,f)}}var Jo,Sz,Tz,Rz,Xo,yz,Az,Hs,mP,BT,Sge,us,FT,HT,kT,Np,GT,qT,wp,Zd,Nz=ce(()=>{Jo=require("node:path"),Sz=require("node:crypto"),Tz=require("yaml");Me();Rz=w(nt()),Xo=w(tn()),yz=w(ge()),Az=w(Q()),Hs=Az.default.forComponent("dataLoader"),mP="hdb_dataloader_hash";o(hP,"computeRecordHash");o(bz,"getHashTrackingTable");o(gge,"getStoredHash");o(gz,"storeHash");Sge=!0;o(Tge,"handleApplication");o(Iz,"loadDataFile");us=class extends yz.ClientError{static{o(this,"DataLoaderError")}constructor(t,r=Xo.HTTP_STATUS_CODES.BAD_REQUEST){super(t,r),this.name="DataLoaderError"}},FT=class extends us{static{o(this,"UnsupportedFileExtensionError")}constructor(t,r){super(`Unsupported file extension in ${(0,Jo.basename)(t)}: ${r}. Only YAML and JSON files are supported.`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="UnsupportedFileExtensionError"}},HT=class extends us{static{o(this,"FileParseError")}constructor(t,r){super(`Failed to parse data file ${(0,Jo.basename)(t)}: ${r.message}`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="FileParseError"}},kT=class extends us{static{o(this,"EmptyFileError")}constructor(t){super(`Data file ${(0,Jo.basename)(t)} is empty or invalid`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="EmptyFileError"}},Np=class extends us{static{o(this,"MissingRequiredPropertyError")}constructor(t,r){super(`Data file ${(0,Jo.basename)(t)} is missing required "${r}" property`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="MissingRequiredPropertyError"}},GT=class extends us{static{o(this,"InvalidPropertyTypeError")}constructor(t,r,n){super(`Data file ${(0,Jo.basename)(t)} has invalid "${r}" property, expected ${n}`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="InvalidPropertyTypeError"}},qT=class extends us{static{o(this,"SystemDatabaseError")}constructor(t,r){super(`Cannot load data into system database: ${t}.${r}`,Xo.HTTP_STATUS_CODES.FORBIDDEN),this.name="SystemDatabaseError"}},wp=class extends us{static{o(this,"RecordProcessingError")}constructor(t,r){super(`Failed to process record in ${t}: ${r.message}`,Xo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="RecordProcessingError"}},Zd=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 xz={};we(xz,{startHTTPThreads:()=>yge,startSocketServer:()=>TP,updateWorkerIdleness:()=>Uz});async function yge(e=2,t){tN().catch(r=>sf.error?.("Error recording hostname for analytics:",r));try{if(t)gP(0,1,!0);else{let{loadRootComponents:r}=YT();if(e===0)return(0,ks.setMainIsWorker)(!0),await AP().startServers(),Promise.resolve([]);await r()}vz();for(let r=0;r<e;r++)gP(r,e);return Promise.all(Mz)}finally{(0,ks.threadsHaveStarted)()}}function vz(){let e=(0,Pz.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),_P=setInterval(()=>{sf.notify(e)},Rge).unref())}function gP(e,t=1,r){if(EP++,(0,ks.startWorker)("server/threads/threadServer.js",{name:Zy.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((a,c)=>{function l(u){u.type===jy.CHILD_STARTED&&(n.removeListener("message",l),a(n))}o(l,"onMessage"),n.on("message",l),n.on("error",c)});Mz.push(s),await s,ef.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",a=>{if(a.requestId){let c=VT.get(a.requestId);c&&c(a)}}),n.on("exit",i),n.on("shutdown",i);function i(){let a=ef.indexOf(n);a>-1&&ef.splice(a,1)}if(o(i,"removeWorker"),tf){let a=tf;tf=[];for(let c of a)Dz[c.localPort](null,c)}}}),r){let n=setInterval(()=>{SP?SP=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ks.shutdownWorkers)(),EP=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function TP(e=0,t){if(typeof e=="string")try{(0,KT.existsSync)(e)&&(0,KT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Age:r=bge(t):r=RP;let n=(0,rf.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=Dz[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),SP=!0,r(i,(a,c)=>{if(!a){if(wz){let u=i._socket||new rf.Socket({handle:i,writable:!0,readable:!0});wz.deliverSocket(u,e,c),u.resume()}else EP>0?(tf.length===0&&setTimeout(()=>{tf.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,tf.push(i)):(console.log("start up a dynamic thread to handle request"),gP(0));it(!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 rf.Socket({handle:i,writable:!0,readable:!0});wge(u,a,e)}it(!0,"socket-routed")})},sf.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 RP(e,t){let r,n=0;for(let s of ef){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=$T)return $T=i,t(r);n=i}$T=0,t(r)}function Age(e,t){let r={};e.getpeername(r);let n=r.address,s=nf.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);RP(e,a=>{nf.set(n,{worker:a,lastUsed:i}),t(a)})}function bge(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new rf.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=nf.get(l),d=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=d,s(u.worker);RP(n,f=>{nf.set(l,{worker:f,lastUsed:d}),s(f,a)})})}o(r,"findByHeaderAffinity")}function Uz(){$T=0;for(let e of ef)e.expectedIdle=e.recentELU.idle+Ige,e.requests=1;ef.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function wge(e,t,r){let n=Nge++;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(),VT.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")),VT.delete(n)),s.event=="destroy"&&(e.destroy(),VT.delete(n))})}var ks,rf,sf,KT,Cz,Pz,Lz,ef,tf,Dz,wz,EP,Mz,_P,Rge,SP,$T,Oz,nf,Ige,VT,Nge,yP=ce(()=>{ks=w(nt()),rf=require("net");k();sf=w(Q()),KT=require("fs");Yi();Cz=require("worker_threads"),Pz=w(Dd()),Lz=w(bt()),ef=[],tf=[],Dz=[],EP=0,Mz=[];Cz.isMainThread&&(process.on("uncaughtException",e=>{e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ks.onMessageFromWorkers)(e=>{e.type===Xy.RESTART&&_P&&(clearInterval(_P),vz())}));Rge=6e5;o(yge,"startHTTPThreads");o(vz,"licenseWarning");o(gP,"startHTTPWorker");o(TP,"startSocketServer");$T=0;o(RP,"findMostIdleWorker");Oz=36e5,nf=new Map;o(Age,"findByRemoteAddressAffinity");o(bge,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of nf)r.lastUsed+Oz<e&&nf.delete(t)},Oz).unref();Ige=1e3;o(Uz,"updateWorkerIdleness");(0,ks.setMonitorListener)(Uz);VT=new Map,Nge=1;o(wge,"proxySocket")});var bP={};we(bP,{hdbServer:()=>Lge,start:()=>Lge});async function Lge(e){try{to.default.debug("In Fastify server"+process.cwd()),to.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),to.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Bz.default.isMaster,await Dge();let t=e.securePort>0;of=Mge(t),await of.ready(),e||(e={}),e.isOperationsServer=!0;try{Le.http(of.server,e),of.server.closeIdleConnections||await of.listen({port:0,host:"::"})}catch(r){throw of.close(),to.default.error(r),to.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),to.default.fatal(t),process.exit(1)}}async function Dge(){to.default.trace("Configuring HarperDB process."),Kz.default.setSchemaDataToGlobal(),await Wz.default.setUsersWithRolesCache(),await zz.default.getLicense()}function Mge(e){to.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=vge(e),r=(0,Fz.default)(t);r.server.headersTimeout=xge(),r.setErrorHandler(uc.serverErrorHandler);let n=Uge();n&&r.register(Hz.default,n),r.register(function(i,a,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(qz.default),r.register(kz.default),r.register(Gz.default,{root:$z.default.join(Vz.PACKAGE_ROOT,"studio/build-local")}),dm(r);let s=lc.default.get(zy.LOCAL_STUDIO_ON);return r.get("/",function(i,a){return!Yz.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?a.sendFile("index.html"):a.sendFile("running.html")}),r.post("/",{preValidation:[uc.reqBodyValidationHandler,uc.authHandler],config:{isOperation:!0}},async function(i,a){return i.body?.operation?.startsWith("restart")&&a.header("Connection","close"),(0,uc.handlePostRequest)(i,a)}),r.get("/health",()=>"HarperDB is running."),to.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}function vge(e){let t=lc.default.get(Op.OPERATIONSAPI_NETWORK_TIMEOUT),r=lc.default.get(Op.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Cge,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}function Uge(){let e=lc.default.get(Op.OPERATIONSAPI_NETWORK_CORS),t=lc.default.get(Op.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Pge)&&(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 xge(){return lc.default.get(Op.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Oge}var Bz,lc,to,Fz,Hz,kz,Gz,qz,$z,Vz,Kz,Yz,Wz,zz,uc,Oge,Cge,Pge,Op,of,jz=ce(()=>{Bz=w(require("cluster")),lc=w(oe());k();to=w(Q()),Fz=w(require("fastify")),Hz=w(require("@fastify/cors")),kz=w(require("@fastify/compress")),Gz=w(require("@fastify/static")),qz=w(mN()),$z=w(require("path")),Vz=w(bt()),Kz=w(ni()),Yz=w(ie()),Wz=w(Xn()),zz=w(Dd());Dr();uc=w(vT());To();lc.default.initSync();Oge=6e4,Cge=1024*1024*1024,Pge="TRUE",{CONFIG_PARAMS:Op}=W;o(Lge,"operationsServer");o(Dge,"setUp");o(Mge,"buildServer");o(vge,"getServerOptions");o(Uge,"getCORSOpts");o(xge,"getHeaderTimeoutConfig")});var PP={};we(PP,{disableNATS:()=>Fge,publishToStream:()=>jT,setNATSReplicator:()=>IP,setPublishToStream:()=>Hge,setSubscription:()=>CP,start:()=>Bge});function Bge(){Cp.default.get(U.CLUSTERING_ENABLED)&&Gge()}function Fge(e=!0){ej=e}function Hge(e,t){jT=e,CP=t}function Gge(){if(ej||process.env._DISABLE_NATS)return;let e=st(),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];IP(s,r,i)}}Nl((r,n)=>{IP(r.tableName,r.databaseName,r),n&&rj(r)}),!Qz&&(Qz=!0)}function IP(e,t,r){if(t==="system"&&qge.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 Br{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){rj(i)}static subscribe(){let i=new Vn;return CP(t,e,i),i}static subscribeOnThisThread(i){return i<(Cp.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??kge)}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 WT(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=tj;return i}o(n,"getNATSTransaction")}function rj(e){let t=Cp.default.get(U.CLUSTERING_NODENAME);jT(`${wP.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,OP.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 Jz,wP,OP,Xz,Zz,Cp,zT,ej,jT,CP,kge,tj,Qz,qge,WT,NP,nj=ce(()=>{Me();xa();Jz=w(mr()),wP=w(Ot()),OP=w(ki());Ru();Xz=w(CN()),Zz=w(yn()),Cp=w(oe());k();zT=w(Q());o(Bge,"start");o(Fge,"disableNATS");jT=Jz.publishToStream,CP=Xz.setSubscription;o(Hge,"setPublishToStream");kge=2;o(Gge,"assignReplicationSource");qge=["hdb_job","hdb_raw_analytics","hdb_info","hdb_license"];o(IP,"setNATSReplicator");o(rj,"publishSchema");WT=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=Cp.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||(zT.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(jT(`${wP.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,OP.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(d=>{throw zT.error("An error has occurred trying to replicate transaction",l,d),d.statusCode=504,d}))}return Promise.all(n)}},NP=class extends WT{static{o(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,Zz.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};tj=new NP});async function cj({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let a=await LP.get(e,{returnNonexistent:!0});i=new vP(e,t,a),a&&(i.sessionWasPresent=!0)}else{if(e){let a=await LP.get(e);a&&a.delete()}i=new JT(e,t)}return n&&(n.id=e,n.user={username:t?.username},Pp.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function DP(){return QT++,QT>65500&&(QT=1),QT}function MP(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=ys.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 ui(i.relativeURL);a.checkPermission=r.user?.role?.permission??{};let c=i.Resource;return Ft(r,()=>s?t===void 0?c.delete(a,r):c.put(a,e.data,r):c.publish(a,e.data,r))}var ij,dc,oj,aj,sj,LP,Pp,QT,JT,vP,lj=ce(()=>{Me();Ou();ij=w(yn()),dc=w(Q());Bc();oj=w(nt()),aj=w(AP());Dr();lg();sj=100,LP=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"}]}}]}),Pp=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,oj.getWorkerIndex)()===0&&(async()=>{await aj.whenComponentsLoaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Pp.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Le.getUser(r.user.username));try{await MP(r,t,r)}catch{(0,dc.warn)("Failed to publish will",t)}Pp.delete(e.id)}})();o(cj,"getSession");QT=1;o(DP,"getNextMessageId");JT=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,dc.trace)("Resuming subscription from",s,"from",a);let h=ys.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 y=T.split("/"),N;for(let Z=0;Z<y.length;Z++)if(y[Z].indexOf("+")>-1)if(y[Z]==="+")N=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&N)throw new Error("Filters can not be combined");let O=!0;y[y.length-1]==="#"&&(y.length--,O=!1),N&&(n=o(Z=>{let G=Z.id;if(!Array.isArray(G))if(G?.indexOf?.("/")>-1)G=G.split("/");else return!1;if(O&&G.length!==y.length)return!1;for(let Y=0;Y<y.length;Y++)if(y[Y]!=="+"&&y[Y]!==G[Y])return!1;return!0},"filter"));let F=y.indexOf("+");m.url="/"+(F>-1?y.slice(0,F):y).concat("").join("/")}}else m.isCollection=!1;let _=h.path,g=h.Resource,R=await Ft(m,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i,T.isCollection=m.isCollection;let y=await g.subscribe(m,T);if(!y)return;if(!y[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let N=(async()=>{for await(let O of y)try{let F;if(O.type&&O.type!=="put"&&O.type!=="delete"&&O.type!=="message"&&O.type!=="patch"||n&&!n(O))continue;r?(O.topic=s,F=this.needsAcknowledge(O)):(O.acknowledge?.(),F=DP());let Z=O.id;if(Array.isArray(Z)&&(Z=wu(Z)),Z==null&&(Z=""),await this.listener(_+"/"+Z,O.value,F,t)===!1)break;this.awaitingAcks?.size>sj?await new Promise(Y=>setTimeout(Y,this.awaitingAcks.size-sj)):await new Promise(setImmediate)}catch(F){(0,dc.warn)(F)}})();return y});if(R)return R.topic=s,R.qos=t.qos,this.subscriptions.push(R),R}resume(){}needsAcknowledge(t){let r=DP();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 MP(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();Ft(r,async()=>{try{if(!t){let n=await Pp.get(this.sessionId);n?.doesExist()&&await MP(n,n.data,r)}}finally{await Pp.delete(this.sessionId)}}).catch(n=>{(0,dc.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(MP,"publish");vP=class extends JT{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=DP(),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,dc.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,ij.getNextMonotonicTime)()),(0,dc.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),LP.put(this.sessionRecord)}}});var UP={};we(UP,{bypassAuth:()=>$ge,start:()=>Kge});function $ge(){Ej=!0}function Kge({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new pj.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),ir.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:p}=dj(u,_=>{u.send(_)},d,Promise.resolve(f).then(()=>d?.user),a);u.on("message",h),u.on("close",p),u.on("error",_=>{ir.info?.("WebSocket error",_)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let d;if(a.events.emit("connection",u),ir.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,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ZT.notify?.({username:d?.username,status:Xs.SUCCESS,type:ya.AUTHENTICATION,authStrategy:"MQTT mTLS",remoteAddress:u.remoteAddress})}catch(p){throw(0,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ZT.error?.({username:h,status:Xs.FAILURE,type:ya.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:u.remoteAddress}),p}}else ir.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){a.events.emit("error",h,u),ir.error?.(h)}else if(l.required)return ir.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!d&&Vge(u.remoteAddress)&&(d=await(0,fj.getSuperUser)(),ir.debug?.("Auto-authorizing local connection",d?.username));let{onMessage:f,onClose:m}=dj(u,h=>u.write(h),null,d,a);u.on("data",f),u.on("close",m),u.on("error",h=>{ir.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function dj(e,t,r,n,s){uj||(uj=!0,Zm(f=>{XT>0&&f.push({metric:"mqtt-connections",connections:XT,byThread:!0})}));let i;XT++;let a,c={protocolVersion:4},l=(0,eR.parser)({protocolVersion:5});function u(f){l.parse(f)}o(u,"onMessage");function d(){XT--,i||(i=!0,a?.disconnect?.(),s.events.emit("disconnected",a,e),s.sessions.delete(a),Yr(!1,"connection","mqtt","disconnect"),ir.debug?.("MQTT connection was closed",e.remoteAddress))}return o(d,"onClose"),l.on("packet",async f=>{try{n?.then&&(n=await n)}catch(y){e.close?.(1008,"Unauthorized"),ir.info?.(y);return}let m=f.cmd;if(a)a.then&&await a;else if(m!=="connect"){ir.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;it(f.length,"bytes-received",_,R(f),"mqtt");try{switch(a?.receivedPacket?.(),m){case"connect":if(c.protocolVersion=f.protocolVersion,f.username)try{n=await Le.getUser(f.username,f.password.toString(),r),(0,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ZT.notify?.({username:n?.username,status:Xs.SUCCESS,type:ya.AUTHENTICATION,authStrategy:"MQTT",remoteAddress:e.remoteAddress})}catch(K){return(0,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ZT.error?.({username:f.username,status:Xs.FAILURE,type:ya.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:e.remoteAddress}),s.events.emit("auth-failed",f,e,K),Yr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",f,e),Yr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(f,n),f.will){let K=e.deserialize||(e.deserialize=Ao(r?.headers.get?.("content-type")));f.will.data=f.will.payload?.length>0?K(f.will.payload):void 0,delete f.will.payload}a=cj({user:n,...f}),a=await a,a.socket=e,r&&(a.request=r),s.sessions.add(a)}catch(K){return ir.error?.(K),s.events.emit("auth-failed",f,e,K),Yr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:K.code||5,returnCode:K.code||128})}s.events.emit("connected",a,e),Yr(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:a.sessionWasPresent,reasonCode:0,returnCode:0});let y=o(async(K,$,le,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",K);let se=K.indexOf("/",1),me=se>0?K.slice(0,se):K;g({cmd:"publish",topic:K,payload:await T($),messageId:le||Math.floor(Math.random()*1e8),qos:ue.qos},me);let Pe=e._socket??e;return Pe.writableNeedDrain?new Promise(De=>Pe.once("drain",De)):!Pe.closed}catch(se){return ir.error?.(se),a?.disconnect(),s.sessions.delete(a),!1}},"listener");a.setListener(y),a.sessionWasPresent&&await a.resume();break;case"subscribe":let N=[];for(let K of f.subscriptions){let $;try{let le=await a.addSubscription(K,K.qos>=1);$=le?le.qos||0:c.protocolVersion<5?128:143}catch(le){s.events.emit("error",le,e,K,a),le.statusCode?le.statusCode===500?ir.warn?.(le):ir.info?.(le):ir.error?.(le),$=c.protocolVersion<5?128:le.statusCode===403?135:le.statusCode===404?143:128}N.push($)}await a.committed,g({cmd:"suback",granted:N,messageId:f.messageId});break;case"unsubscribe":{let K=[];for(let $ of f.unsubscriptions)K.push(a.removeSubscription($)?0:17);g({cmd:"unsuback",granted:K,messageId:f.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:f.messageId,reasonCode:0});return;case"publish":let O=f.qos===2?"pubrec":"puback",F=e.deserialize||(e.deserialize=Ao(r?.headers.get?.("content-type"))),G=(f.payload?.length||0)>0?F(f.payload):void 0,Y;try{Y=await a.publish(f,G)}catch(K){s.events.emit("error",K,e,f,a),ir.warn?.(K),f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:128},f.topic);break}f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:Y===!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),Yr(!0,"connection","mqtt","disconnect"),ir.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(y){s.events.emit("error",y,e,f,a),ir.error?.(y),g({cmd:"disconnect"})}function g(y,N){let O=(0,eR.generate)(y,c);t(O),it(O.length,"bytes-sent",N,R(y),"mqtt")}o(g,"sendPacket");function R(y){return y.qos>0?y.cmd+",qos="+y.qos:y.cmd}o(R,"packetMethodName");function T(y){return Na(y,r)}o(T,"serialize")}),l.on("error",f=>{ir.warn("MQTT parsing error, closing connection:",f.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:d}}var eR,fj,af,mj,hj,pj,ZT,ir,Ej,Vge,uj,XT,_j=ce(()=>{eR=require("mqtt-packet");lj();fj=w(Xn());To();Yi();Dr();af=w(oe());k();mj=w(ei()),hj=w(Q()),pj=require("events"),ZT=(0,mj.loggerWithTag)("auth-event"),ir=(0,hj.forComponent)("mqtt"),Ej=(0,af.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;o($ge,"bypassAuth");Vge=o(e=>Ej&&(e.includes("127.0.0.")||e==="::1"),"authorizeLocal");o(Kge,"start");XT=0;o(dj,"onSocket")});function tR(e,t){if(t?.includes(".."))throw new xP(t);let r=t||"/";return(r==="."||r.startsWith("./"))&&(r=`/${e}${r.slice(1)}`),r.startsWith("/")||(r=`/${r}`),r.endsWith("/")||(r=`${r}/`),r}var xP,BP=ce(()=>{xP=class extends Error{static{o(this,"InvalidBaseURLPathError")}constructor(t){super(`urlPath must not contain '..'. Received: '${t}'`)}};o(tR,"resolveBaseURLPath")});function gj(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 Sj=ce(()=>{o(gj,"deriveCommonPatternBase")});function rR(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 FP=ce(()=>{o(rR,"deriveGlobOptions")});var Tj,HP,Lp,Rj=ce(()=>{BP();Sj();FP();Tj=require("micromatch"),HP=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"}},Lp=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=tR(this.name,this.config.urlPath),this.globOptions=rR(this.config.files),this.globOptions.source=this.globOptions.source.map(s=>{if(s.includes("..")||s.startsWith("/"))throw new HP(s);return s==="."||s==="./"?"**/*":s}),this.patternBases=this.globOptions.source.map(s=>(0,Tj.scan)(s).base),this.commonPatternBase=gj(this.patternBases)}}});function yj(e,t){return new RegExp(`^${e}(/|$)`).test(t)}function zl(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(yj(n,t)){t=t.slice(n.length+1);break}}if(r==="directory"){if(t===n){t="";break}else if(yj(n,t)){t=t.slice(n.length+1);break}}}return(0,Aj.join)(e.baseURLPath,t)}var Aj,kP=ce(()=>{Aj=require("node:path");o(yj,"pathStartsWithBase");o(zl,"deriveURLPath")});function bj(e){return typeof e=="string"||Array.isArray(e)||!("files"in e)?{files:e}:e}var sR,Ij,Nj,GP,wj,Oj,nR,Cj=ce(()=>{sR=require("node:events");Rj();Ij=w(Q()),Nj=w(require("chokidar")),GP=require("node:path"),wj=require("node:fs/promises");kP();Oj=require("micromatch"),nR=class extends sR.EventEmitter{static{o(this,"EntryHandler")}#e;#t;#r;ready;constructor(t,r,n,s){super(),this.#e=new Lp(t,r,bj(n)),this.#r=s||Ij.default.loggerWithTag(t),this.ready=(0,sR.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,GP.join)(this.directory,r);switch(t){case"add":case"change":{let i=zl(this.#e,r,"file");(0,wj.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=zl(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=zl(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,GP.join)(this.#e.directory,r));return this.#t=Nj.default.watch(this.#e.commonPatternBase,{cwd:this.#e.directory,persistent:!1,ignored:o(r=>{let n=r.replace(/\\/g,"/"),s=t.map(i=>i.replace(/\\/g,"/"));return n!==this.#e.directory.replace(/\\/g,"/")&&s.every(i=>!n.startsWith(i))},"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 Lp(this.name,this.directory,bj(t)),this.#a()}};o(bj,"castConfig")});var iR,qP=ce(()=>{iR={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js"},static:{files:"web/**"}}});var aR,Pj,Lj,Dj,Mj,vj,$P,VP,KP,YP,WP,oR,Uj=ce(()=>{aR=require("events"),Pj=w(require("yaml")),Lj=w(require("chokidar")),Dj=require("node:fs/promises"),Mj=require("util"),vj=w(Q());qP();$P=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"}},VP=class extends Error{static{o(this,"InvariantUninitializedOptionsWatcherError")}constructor(){super("Invariant: OptionsWatcher has not been initialized yet. This should never happen."),this.name="InvariantUninitializedOptionsWatcherError"}},KP=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"}},YP=class extends Error{static{o(this,"KeyDoesNotExistError")}constructor(t,r){super(`Cannot set property ${t.join(".")} as ${r} does not exist.`),this.name="KeyDoesNotExistError"}},WP=class extends Error{static{o(this,"CannotSetPropertyError")}constructor(t){super(`Cannot set property ${t.join(".")} as parent is not an object.`),this.name="CannotSetPropertyError"}},oR=class extends aR.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||vj.default.loggerWithTag(t),this.ready=(0,aR.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,Dj.readFile)(this.#e,"utf-8").then(t=>{this.#n=Pj.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 $P(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=iR,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,Mj.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 VP;if(!["object","string","array","number","boolean","undefined"].includes(typeof r))throw new KP(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 YP(t,s);n=n[s]}if(n==null||typeof n!="object")throw new WP(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 xj(){Wge[0]=1}var Yge,Wge,Bj=ce(()=>{dp();Yge=zo.primaryStore.getUserSharedBuffer("restart-needed",new ArrayBuffer(1)),Wge=new Uint8Array(Yge);o(xj,"requestRestart")});var uR,Fj,cR,lR,Hj=ce(()=>{uR=require("node:events");Cj();Uj();Fj=w(Q());Bj();cR=class extends Error{static{o(this,"MissingDefaultFilesOptionError")}constructor(){super("No default files option exists. Ensure `files` is specified in config.yaml"),this.name="MissingDefaultFilesOptionError"}},lR=class extends uR.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=Fj.default.forComponent(this.#r),this.resources=s,this.server=i,this.#s=[],this.ready=(0,uR.once)(this,"ready"),this.options=new oR(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 nR(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{files:t.files,urlPath:t.urlPath}}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 cR);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 cR);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}`),xj()}}});function jl(e){return typeof e=="string"&&e.trim()!==""}function zP(e){return Array.isArray(e)&&e.length!==0&&e.every(t=>jl(t))}function $j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function zge(e){e.config.root&&Dp.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 tL(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($j(e.config.files)&&e.config.files.only==="files")return!1;t=e.patternBases}let s=!1;for(let i of t){let a=(0,Mp.join)(e.directory,i);dR.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 Vj(e){let t=!1;if(t=await zge(e),t)return t;let r=await(0,kj.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,Mp.join)(e.directory,n.path);if(n.dirent.isDirectory()){let i=zl(e,n.path,"directory");dR.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=zl(e,n.path,"file"),a=await(0,Gj.readFile)(s);dR.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 Dp.default.error(`Entry received from glob pattern match for component ${e.name} is neither a file nor a directory:`,n)}return t}var dR,kj,Dp,Mp,Gj,qj,fR,bi,jP,QP,JP,XP,ZP,eL,tL,rL,nL,Kj=ce(()=>{dR=require("node:worker_threads"),kj=w(require("fast-glob")),Dp=w(Q());BP();FP();Mp=require("node:path"),Gj=require("node:fs/promises");kP();qj=require("micromatch"),fR=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,!jl(this.config.files)&&!zP(this.config.files)&&!$j(this.config.files))throw new jP(this);if(typeof this.config.files=="object"&&!Array.isArray(this.config.files)){if(this.config.files.source===void 0||!zP(this.config.files.source)&&!jl(this.config.files.source))throw new QP(this);if(this.config.files.only!==void 0&&(typeof this.config.files.only!="string"||!["all","files","directories"].includes(this.config.files.only)))throw new JP(this);if(this.config.files.ignore!==void 0&&!zP(this.config.files.ignore)&&!jl(this.config.files.ignore))throw new XP(this)}if(this.config.root!==void 0&&!jl(this.config.root))throw new eL(this);if(this.config.path!==void 0&&!jl(this.config.path))throw new rL(this);if(this.config.path&&(Dp.default.warn("Resource extension 'path' option is deprecated. Please replace with 'urlPath'."),this.config.urlPath=this.config.path),this.config.urlPath!==void 0&&(!jl(this.config.urlPath)||typeof this.config.urlPath=="string"&&this.config.urlPath.includes("..")))throw new nL(this);this.globOptions=rR(this.config.files),this.globOptions.source=this.globOptions.source.map(r=>{if(r.includes(".."))throw new ZP(this,r);return r.startsWith("/")&&(Dp.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,qj.scan)(r).base),this.baseURLPath=tR(this.name,this.config.urlPath)}},bi=class extends Error{static{o(this,"ComponentV1ProcessingError")}constructor(t,r){super(`Component ${r.name} (from ${(0,Mp.basename)(r.directory)}) ${t}`)}},jP=class extends bi{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)}},QP=class extends bi{static{o(this,"InvalidFilesSourceOptionError")}constructor(t){super("'files' object must have a non-empty 'source' property.",t)}},JP=class extends bi{static{o(this,"InvalidFilesOnlyOptionError")}constructor(t){super("'files.only' option must be one of 'all', 'files', or 'directories'.",t)}},XP=class extends bi{static{o(this,"InvalidFileIgnoreOptionError")}constructor(t){super("'files.ignore' option must be a non-empty string or an array of non-empty strings.",t)}},ZP=class extends bi{static{o(this,"InvalidGlobPattern")}constructor(t,r){super(`'files' glob pattern must not contain '..'. Received: '${r}'`,t)}},eL=class extends bi{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)}},tL=class extends bi{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)}},rL=class extends bi{static{o(this,"InvalidPathOptionError")}constructor(t){super("deprecated 'path' option must be a non-empty string. Consider replacing with 'urlPath'.",t)}},nL=class extends bi{static{o(this,"InvalidURLPathOptionError")}constructor(t){super("'urlPath' option must be a non-empty string that must not contain '..'.",t)}};o(jl,"isNonEmptyString");o(zP,"isArrayOfNonEmptyStrings");o($j,"isObject");o(zge,"handleRoots");o(Vj,"processResourceExtensionComponent")});var Yj={};we(Yj,{SERVERS:()=>cf,portServer:()=>sL,setPortServerMap:()=>mR});function mR(e,t){let r=sL.get(e)??[];sL.set(e,[...r,t])}var cf,sL,iL=ce(()=>{cf={},sL=new Map;o(mR,"setPortServerMap")});function hR(e,t,r=Qge){let n;return function(...i){return n?n.length*oL>r?t(...i):new Promise((a,c)=>{n.push({args:i,fn(){try{let l=e(...i);a(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,a){setImmediate(()=>{let c=performance.now();oL=(oL*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var jj,jge,Qge,Wj,Jge,aL,zj,oL,cL=ce(()=>{jj=w(ei()),jge=3e3,Qge=2e4,Wj=0,Jge=3e4,aL=3e3,zj=performance.now()+aL,oL=0;o(hR,"throttle");setInterval(()=>{let e=performance.now();e-zj-aL>jge&&Wj+Jge<e&&(jj.default.warn?.("JavaScript execution has taken too long and is not allowing proper event queue cycling, consider using 'await new Promise(setImmediate)' in code that will execute for a long duration"),Wj=e),zj=e},aL).unref()});var TR={};we(TR,{deliverSocket:()=>c2,getHttpOptions:()=>tSe,getRequestId:()=>f2,handleApplication:()=>eSe,httpServer:()=>EL,logRequest:()=>xp,proxyRequest:()=>rSe,registerServer:()=>hL,suppressHandleApplicationWarning:()=>Zge});function eSe(e){Bp=e.options.getAll(),e.options.on("change",t=>{Bp=e.options.getAll()})}function tSe(){return Bp}function c2(e,t,r){let n=e?.read?e:new e2.Socket({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=cf[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=cf[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):a<5?i(a+1):(Zo.default.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}function rSe(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=Qj.get(s),r){case"connection":i=c2(void 0,t),Qj.set(s,i),i.write=(c,l,u)=>(ER.parentPort.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(ER.parentPort.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let a=i.destroy;i.destroy=()=>{a.call(i),ER.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 hL(e,t,r=!0){t||(t=wr.default.get(U.HTTP_PORT));let n=cf[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",Zj),s.on("unhandled",(i,a)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,a)}),n.lastServer=e}else cf[t]=e;e.on("unhandled",Zj)}function pL(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=[],wr.default.get(U.HTTP_PORT)!=null&&t.push({port:wr.default.get(U.HTTP_PORT),secure:wr.default.get(U.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),wr.default.get(U.HTTP_SECUREPORT)!=null&&t.push({port:wr.default.get(U.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&wr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:(0,t2.resolvePath)(wr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}function EL(e,t){let r=[];for(let{port:n,secure:s}of pL(t))r.push(l2(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?fL[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,hL(e,n,!1)),_R[n]=gR(fL,n);return r}function l2(e,t,r,n){if(mR(e,{protocol_name:t?"HTTPS":"HTTP",name:RR()}),!pR[e]){let s=r?"operationsApi_network":"http",i=wr.default.get(s+"_keepAliveTimeout"),a=wr.default.get(s+"_timeout"),c=wr.default.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:a,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:wr.default.get(U.HTTP_MAXHEADERSIZE)},u=wr.default.get(s+"_mtls"),d=wr.default.get(s+"_mtls_required"),f;if(t){let g=wr.default.get("tls");f=wr.default.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!d,requestCert:!!(u||n),ticketKeys:(0,r2.getTicketKeys)(),SNICallback:(0,n2.createTLSSelector)(r?"operations-api":"server",u),ciphers:g.ciphers??g[0]?.ciphers})}let m=(0,s2.checkMemoryLimit)(),h=o(async(g,R)=>{let T=performance.now(),y=0;try{let O=new Ha(g,R);r&&(O.isOperationsServer=!0),Bp.logging?.id&&(O.requestId=y=f2());let F=await _R[e](O);if(!F){if(O._nodeResponse.statusCode){xp(g,O._nodeResponse.statusCode,y,performance.now()-T);return}F=u2(O)}if(F.headers?.set||(F.headers=new Ns(F.headers)),m?F.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):F.headers?.set?.("Server","HarperDB"),F.status===-1){for(let me of F.headers||[])R.setHeader(me[0],me[1]);return g.baseRequest=O,R.baseResponse=F,pR[e].emit("unhandled",g,R)}let Z=F.status||200,G=performance.now(),Y=G-T,K=F.body,$,le=!1;if(!F.handlesHeaders){let me=F.headers||new Ns;K?K.length>=0?(typeof K=="string"?me.set("Content-Length",Buffer.byteLength(K)):me.set("Content-Length",K.length),$=!0):K instanceof Rs&&(K.size?me.set("Content-Length",K.size):K.on&&(le=!0,K.on("size",De=>{R.headersSent||R.setHeader("Content-Length",De)})),K=K.stream()):(me.set("Content-Length","0"),$=!0);let Pe=`hdb;dur=${Y.toFixed(2)}`;if(F.wasCacheMiss&&(Pe+=", miss"),eh(me,"Server-Timing",Pe,!0),!R.headersSent)if(le){if(R.statusCode=Z,me)if(me[Symbol.iterator])for(let[De,dt]of me)R.setHeader(De,dt);else for(let De in me)R.setHeader(De,me[De])}else R.writeHead(Z,me&&(me[Symbol.iterator]?Array.from(me):me));$&&R.end(K)}let ue=O.handlerPath,se=O.method;if(it(Y,"duration",ue,se,F.wasCacheMiss==null?void 0:F.wasCacheMiss?"cache-miss":"cache-hit"),Yr(Z<400,"success",ue,se),Yr(1,"response_"+Z,ue,se),xp(g,Z,y,Y),!$)if(K instanceof ReadableStream&&(K=dL.Readable.fromWeb(K)),(K[Symbol.iterator]||K[Symbol.asyncIterator])&&(K=dL.Readable.from(K)),K?.pipe){K.pipe(R),K.destroy&&R.on("close",()=>{K.destroy()});let me=0;K.on("data",Pe=>{me+=Pe.length}),K.on("end",()=>{it(performance.now()-G,"transfer",ue,se),it(me,"bytes-sent",ue,se)})}else K?.then?K.then(me=>{R.end(me)},N):R.end(K)}catch(O){N(O)}function N(O){let F=O.headers,Z=O.statusCode||500;R.writeHead(Z,F&&(F[Symbol.iterator]?Array.from(F):F)),R.end(Xge(O)),xp(g,Z,y,performance.now()-T),O.statusCode?O.statusCode===500?Zo.default.warn(O):Zo.default.info(O):Zo.default.error(O)}o(N,"onError")},"requestHandler"),p=hR(h,(g,R)=>{R.statusCode=503,R.end("Service unavailable, exceeded request queue limit"),it(!0,"service-unavailable",e)},wr.default.get(s+"_requestQueueLimit")),_=pR[e]=(t?f?i2.createSecureServer:o2.createServer:SR.createServer)(l,(g,R)=>{let T=g.method;T==="GET"||T==="OPTIONS"||T==="HEAD"?h(g,R):p(g,R)});i>=0&&(_.keepAliveTimeout=i),c>=0&&(_.headersTimeout=c),t&&(_.ports||(_.ports=[]),_.ports.push(e),l.SNICallback.initialize(_),u&&(_.mtlsConfig=u),_.on("secureConnection",g=>{g._parent.startTime&&it(performance.now()-g._parent.startTime,"tls-handshake",e),it(g.isSessionReused(),"tls-reused",e)}),_.isSecure=!0),hL(_,e)}return pR[e]}function gR(e,t){let r=u2;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 u2(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new Ns}}function nSe(e,t){EL(e,{requestOnly:!0,...t})}function d2(e,t){for(let{port:r}of pL(t))Jj[t?.runFirst?"unshift":"push"]({listener:e,port:r}),mL[r]=gR(Jj,r)}function sSe(e,t){let r=[];for(let{port:n,secure:s}of pL(t)){mR(n,{protocol_name:s?"WSS":"WS",name:RR()});let i=l2(n,s,t?.isOperationsServer,t?.mtls);vp[n]||(vp[n]=new a2.WebSocketServer({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),vp[n].on("connection",(a,c)=>{try{let l=new Ha(c);l.isWebSocket=!0;let u=_R[n](l);Zo.default.debug("Received WS connection, calling listeners",lL),Xj[n](a,l,u)}catch(l){Zo.default.warn("Error in handling WS connection",l)}}),d2((a,c,l,u)=>a.__harperdbRequestUpgraded?u(a,c,l):vp[n].handleUpgrade(a,c,l,d=>{a.__harperdbRequestUpgraded=!0,u(a,c,l),vp[n].emit("connection",d,a)}),{port:n}),i.on("upgrade",(a,c,l)=>{mL[n]&&mL[n](a,c,l)})),r.push(i),lL[t?.runFirst?"unshift":"push"]({listener:e,port:n}),Xj[n]=gR(lL,n),_R[n]=gR(fL,n)}return r}function Zj(e,t){t.writeHead(404),t.end(`Not found
34
- `),xp(e,404,0,e.requestId)}function xp(e,t,r,n){let s=Bp.logging;if(s){uL||(uL=Zo.default.forComponent("http"));let i=t<400?"info":t===500?"error":"warn";uL[i]?.(`${e.method} ${e.url} ${e.socket.encrypted?"HTTPS":"HTTP"}/${e.httpVersion}${s.headers?" "+iSe(e.headers):""} ${t}${s.timing&&n?" "+n.toFixed(2)+"ms":""}${r?" id: "+r:""}`)}}function iSe(e){let t=[];for(let r in e)t.push(`${r}: ${e[r]}`);return t.join(", ")}function f2(){return Up||(Up=new BigInt64Array([1n]),Up=new BigInt64Array(databases.system.hdb_analytics.primaryStore.getUserSharedBuffer("next-request-id",Up.buffer))),Number(Atomics.add(Up,0,1n))}var e2,Zo,ER,wr,t2,r2,n2,s2,i2,o2,SR,dL,a2,Xge,vp,pR,_R,fL,Bp,Zge,Qj,Jj,mL,lL,Xj,uL,Up,_L=ce(()=>{e2=require("node:net"),Zo=w(Q()),ER=require("node:worker_threads"),wr=w(oe());k();t2=w(wt()),r2=w(nt()),n2=w(ss()),s2=w(Dd()),i2=require("node:http2"),o2=require("node:https"),SR=require("node:http");rh();th();Kn();Yi();dL=require("node:stream");Dr();iL();Vd();cL();a2=require("ws"),{errorToString:Xge}=Zo.default;Le.http=EL;Le.request=nSe;Le.ws=sSe;Le.upgrade=d2;vp={},pR={},_R={},fL=[],Bp={},Zge=!0;o(eSe,"handleApplication");o(tSe,"getHttpOptions");o(c2,"deliverSocket");Qj=new Map;o(rSe,"proxyRequest");o(hL,"registerServer");o(pL,"getPorts");o(EL,"httpServer");o(l2,"getHTTPServer");o(gR,"makeCallbackChain");o(u2,"unhandled");o(nSe,"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){}});Jj=[],mL={};o(d2,"onUpgrade");lL=[],Xj={};o(sSe,"onWebSocket");o(Zj,"defaultNotFound");o(xp,"logRequest");o(iSe,"headersToString");o(f2,"getRequestId")});var sp={};we(sp,{componentErrors:()=>Fp,getComponentName:()=>RR,loadComponent:()=>IR,loadComponentDirectories:()=>p2,setErrorReporter:()=>aSe});function p2(e,t){t&&(SL=t),e&&(AL=e);let r=[];if((0,vt.existsSync)(gL)){let s=(0,vt.readdirSync)(gL,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,Hr.join)(gL,a);r.push(IR(c,SL,Vy,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(IR(n,SL,n,!1,void 0,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{h2=!0})}function aSe(e){AR=e}function cSe(e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{zo.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(zo.primaryStore.attemptLock(e,0,()=>{clearTimeout(s),r()}))try{(0,vt.rmSync)(t,{recursive:!0,force:!0}),(0,vt.existsSync)((0,Hr.join)(e,"node_modules"))||(0,vt.mkdirSync)((0,Hr.join)(e,"node_modules")),(0,vt.symlinkSync)(IL.PACKAGE_ROOT,t,"dir"),r()}finally{zo.primaryStore.unlock(e,0)}})}function E2(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;if(!zo.primaryStore.attemptLock(e.name,0,()=>{clearTimeout(s),n(E2(e,t))}))return new Promise((a,c)=>{n=a,s=setTimeout(()=>{c(new Error(`Timeout waiting for lock on ${e.name}`))},r+5e3)});let i;return Promise.race([t.handleApplication(e),new Promise((a,c)=>i=setTimeout(()=>c(new Error(`handleApplication timed out after ${r}ms for ${e.name}`)),r))]).finally(()=>{zo.primaryStore.unlock(e.name,0),clearTimeout(i)})})}async function IR(e,t,r,n,s,i){let a=(0,vt.realpathSync)(e);if(yR.has(a))return yR.get(a);yR.set(a,!0),s&&(AL=s);try{let c;n&&(Fp=new Map);let l=(0,Hr.join)(e,"harperdb-config.yaml");(0,vt.existsSync)(l)?c=n?(0,NR.getConfigObj)():(0,RL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():!n&&(0,vt.existsSync)(l=(0,Hr.join)(e,"config.yaml"))?c=(0,RL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():c=iR;try{let m=(0,Hr.join)(e,"node_modules","harperdb");(n||((0,vt.existsSync)(m)||!e.startsWith((0,yL.getHdbBasePath)()))&&(!(0,vt.existsSync)(m)||(0,vt.realpathSync)(IL.PACKAGE_ROOT)!==(0,vt.realpathSync)(m)))&&await cSe(e,m)}catch(m){ea.default.error("Error symlinking harperdb module",m),m.code=="EPERM"&&process.platform==="win32"&&ea.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=bR,d={};for(let m in c){bR=m;let h=c[m];if(Fp.set(n?m:(0,Hr.basename)(e),!1),!h)continue;let p,_=h.package;try{if(_){let N=e,O;for(;!(0,vt.existsSync)(O=(0,Hr.join)(N,"node_modules",m));)if(N=(0,Hr.dirname)(N),N.length<(0,yL.getHdbBasePath)().length){O=null;break}if(O)p=await IR(O,t,r,!1),d[m]=!0;else throw new Error(`Unable to find package ${m}:${_}`)}else p=oSe[m];if(!p)continue;let g=o(N=>(N.origin=r,ze(N)),"ensureTable"),R=h.network||(h.port||h.securePort)&&h,T=R?.securePort||R?.https&&R.port,y=!R?.https&&R?.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&&ea.default.warn(`Plugin ${m} is using the experimental handleApplication API`);let N=new lR(m,e,l,t,Le);await E2(N,p);continue}if(TL.isMainThread&&(p=await p.startOnMainThread?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p,n&&R))for(let N of[y,T])try{if(+N&&!m2.includes(N)){let O=bL.get(U.HTTP_SESSIONAFFINITY);O&&ea.default.warn("Session affinity is not recommended and may cause memory leaks"),(O||!cg)&&(m2.push(N),TP(N,O))}}catch(O){console.error("Error listening on socket",N,O,m)}if(t.isWorker&&(p=await p.start?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p),AL.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&h.files!=null){let N=new fR({config:h,name:m,directory:e,module:p,resources:t});d[m]=await Vj(N)}}catch(g){g.message=`Could not load component '${m}' for application '${(0,Hr.basename)(e)}' due to: ${g.message}`,AR?.(g),((0,Hp.getWorkerIndex)()===0?console:ea.default).error(g),t.set(h.path||"/",new $c(g),null,!0),Fp.set(n?m:(0,Hr.basename)(e),g.message)}}if(bR=u,TL.isMainThread&&!h2&&i&&(0,Hp.watchDir)(e,async()=>p2()),c.extensionModule||c.pluginModule){let m=await tg((0,Hr.join)(e,c.extensionModule||c.pluginModule));return yR.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?`;AR?.(new Error(m)),((0,Hp.getWorkerIndex)()===0?console:ea.default).error(m),Fp.set((0,Hr.basename)(e),m)}for(let[m,h]of Object.entries(d))h||ea.default.warn(`Component ${m} from (${(0,Hr.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}`,AR?.(c),t.set("",new $c(c))}}var vt,Hr,TL,RL,bL,IL,ea,Hp,yL,NR,gL,AL,h2,SL,Fp,oSe,m2,yR,AR,bR,RR,Vd=ce(()=>{vt=require("node:fs"),Hr=require("node:path"),TL=require("node:worker_threads"),RL=require("yaml"),bL=w(oe()),IL=w(bt());k();iv();Kv();pH();yH();AH();uk();lz();pz();_z();ea=w(Q());Nz();Hp=w(nt());VI();Dr();Me();yP();yL=w(oe());jz();jS();nj();rs();_j();NR=w(wt());rh();CA();Hj();Kj();_L();dp();qP();gL=(0,NR.resolvePath)(bL.get(U.COMPONENTSROOT)),AL=new Map,Fp=new Map;o(p2,"loadComponentDirectories");oSe={REST:dg,rest:dg,graphql:LA,graphqlSchema:fA,roles:$I,jsResource:KI,fastifyRoutes:uP,login:WI,static:dP,operationsApi:bP,customFunctions:{},http:TR,clustering:PP,replication:Uo,authentication:Jh,mqtt:UP,loadEnv:fP,logging:ea.default,dataLoader:pP},m2=[],yR=new Map;o(aSe,"setErrorReporter");RR=o(()=>bR,"getComponentName");o(cSe,"symlinkHarperModule");o(E2,"sequentiallyHandleApplication");o(IR,"loadComponent")});var YT=M((WBe,g2)=>{var{isMainThread:_2}=require("worker_threads"),{getTables:lSe,getDatabases:KBe,table:YBe}=(Me(),v(Et)),{loadComponentDirectories:uSe,loadComponent:dSe}=(Vd(),v(sp)),{resetResources:fSe}=(Ou(),v(Uv)),mSe=YO(),hSe=wt(),{dirname:pSe}=require("path"),{getConnection:ESe}=mr(),_Se=oe(),{CONFIG_PARAMS:gSe}=(k(),v(W)),{loadCertificates:SSe}=ss(),NL=new Map;async function TSe(e=!1){!_2&&_Se.get(gSe.CLUSTERING_ENABLED)&&ESe();try{_2&&await mSe()}catch(n){console.error(n)}let t=fSe();lSe(),t.isWorker=e,await SSe(),await dSe(pSe(hSe.getConfigFilePath()),t,"hdb",!0,NL),await uSe(NL,t);let r=[];for(let[n]of NL)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}o(TSe,"loadRootComponents");g2.exports.loadRootComponents=TSe});var nt=M((jBe,Ni)=>{"use strict";qy();var{Worker:RSe,MessageChannel:ySe,parentPort:ro,isMainThread:LL,threadId:ASe,workerData:no}=require("worker_threads"),{PACKAGE_ROOT:bSe}=bt(),{join:y2,isAbsolute:ISe,extname:NSe}=require("path"),{server:A2}=(Dr(),v(rm)),{watch:wSe,readdir:OSe}=require("fs/promises"),{totalmem:S2}=require("os"),{setHeapSnapshotNearHeapLimit:CSe}=require("v8"),fc=(k(),v(W)),CR=oe(),Ii=Q(),{randomBytes:PSe}=require("crypto"),{_assignPackageExport:LSe}=Zs(),T2=1024*1024,mc=[],Gs=[],DSe=50,DL=1e4,MSe="restart",b2="request_thread_info",I2="resource_report",N2="thread_info",w2="added-port",vSe="ack",wL;LSe("threads",Gs);Ni.exports={startWorker:OL,restartWorkers:vL,shutdownWorkers:HSe,workers:mc,setMonitorListener:WSe,onMessageFromWorkers:kSe,onMessageByType:v2,broadcast:qSe,broadcastWithAcknowledgement:VSe,setChildListenerByType:FSe,getWorkerIndex:O2,getWorkerCount:C2,getTicketKeys:L2,setMainIsWorker:xSe,setTerminateTimeout:USe,restartNumber:no?.restartNumber||1};Gs.onMessageByType=v2;Gs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Gs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Ni.exports.whenThreadsStarted=new Promise(e=>{Ni.exports.threadsHaveStarted=e});CR.get(fc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&CSe(1);var ML;function USe(e){DL=e}o(USe,"setTerminateTimeout");function O2(){return no?no.workerIndex:ML?0:void 0}o(O2,"getWorkerIndex");function C2(){return no?no.workerCount:ML?1:void 0}o(C2,"getWorkerCount");function xSe(e){ML=e,Ni.exports.threadsHaveStarted()}o(xSe,"setMainIsWorker");var P2=1,wR;function L2(){return wR||(wR=LL?PSe(48):no.ticketKeys,wR)}o(L2,"getTicketKeys");Object.defineProperty(A2,"workerIndex",{get(){return O2()}});Object.defineProperty(A2,"workerCount",{get(){return C2()}});var D2={[b2](e,t){KSe(t)},[I2](e,t){YSe(t,e)}};function OL(e,t={}){let r=process.constrainedMemory?.()||S2();r=Math.min(r,S2(),2e4*T2);let n=CR.get(fc.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/T2/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],a=[];for(let u of Gs){let d=new ySe;d.existingPort=u,i.push(d),a.push(d.port2)}NSe(e)||(e+=".js");let c=["--enable-source-maps","--expose-internals"];CR.get(fc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&c.push("--heapsnapshot-near-heap-limit=1");let l=new RSe(ISe(e)?e:y2(bSe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:c,argv:process.argv.slice(2),workerData:{addPorts:a,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:P2=t.threadCount,name:t.name,restartNumber:Ni.exports.restartNumber,ticketKeys:L2()},transferList:a,...t});for(let{port1:u,existingPort:d}of i)d.postMessage({type:w2,port:u,threadId:l.threadId},[u]);return PR(l,!0),l.unexpectedRestarts=t.unexpectedRestarts||0,l.startCopy=()=>OL(e,t),l.on("error",u=>{Ii.error(`Worker index ${t.workerIndex} error:`,u)}),l.on("exit",u=>{mc.splice(mc.indexOf(l),1),!l.wasShutdown&&t.autoRestart!==!1&&(l.unexpectedRestarts<DSe?(t.unexpectedRestarts=l.unexpectedRestarts+1,OL(e,t)):Ii.error(`Thread has been restarted ${l.restarts} times and will not be restarted`))}),l.on("message",u=>{D2[u.type]?.(u,l)}),mc.push(l),jSe(),t.onStarted&&t.onStarted(l),l.name=t.name,l}o(OL,"startWorker");var BSe=[fc.THREAD_TYPES.HTTP];async function vL(e=null,t=Math.max(P2>3,1),r=!0){if(LL){try{process.chdir(process.cwd())}catch(a){Ii.error("Unable to reestablish current working directory",a)}if(r){let{loadRootComponents:a}=YT();await a()}Ni.exports.restartNumber++,t<1&&(t=t*mc.length);let n=[],s=[];for(let a of mc.slice(0)){if(e&&a.name!==e||a.wasShutdown)continue;Ii.trace("sending shutdown request to ",a.threadId),a.postMessage({restartNumber:Ni.exports.restartNumber,type:fc.ITC_EVENT_TYPES.SHUTDOWN}),a.wasShutdown=!0,a.emit("shutdown",{});let c=BSe.indexOf(a.name)>-1,l=new Promise(u=>{let d=setTimeout(()=>{Ii.warn("Thread did not voluntarily terminate, terminating from the outside",a.threadId),a.terminate()},DL*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===fc.ITC_EVENT_TYPES.CHILD_STARTED&&(Ii.trace("Worker has started",u.threadId),f(),s.splice(s.indexOf(d)),u.off("message",m))},"startListener");Ii.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}=kd();r&&(e==="http"||!e)&&CR.get(fc.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ro.postMessage({type:MSe,workerType:e})}o(vL,"restartWorkers");function FSe(e,t){D2[e]=t}o(FSe,"setChildListenerByType");function HSe(e){return vL(e,1/0,!1)}o(HSe,"shutdownWorkers");var M2=[];function kSe(e){M2.push(e)}o(kSe,"onMessageFromWorkers");var CL=new Map;function v2(e,t){let r=CL.get(e);r||CL.set(e,r=[]),r.push(t)}o(v2,"onMessageByType");var GSe=10;async function qSe(e,t){let r=0;for(let n of Gs)try{n.postMessage(e),r++>GSe&&(r=0,await new Promise(setImmediate))}catch(s){Ii.error("Unable to send message to worker",s)}t&&x2(e,null)}o(qSe,"broadcast");var OR=new Map,$Se=1;function VSe(e){return new Promise(t=>{let r=0;for(let n of Gs)try{let s=$Se++,i=o(()=>{OR.delete(s),--r===0&&t(),n!==ro&&--n.refCount===0&&n.unref()},"ackHandler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,OR.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,a]of OR)a.port===n&&a()})),n.postMessage(e),r++}catch(s){Ii.error("Unable to send message to worker",s)}r===0&&t()})}o(VSe,"broadcastWithAcknowledgement");function KSe(e){e.postMessage({type:N2,workers:U2()})}o(KSe,"sendThreadInfo");function U2(){let e=Date.now();return mc.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(U2,"getChildWorkerInfo");function YSe(e,t){e.resources=t,e.resources.updated=Date.now()}o(YSe,"recordResourceReport");var PL;function WSe(e){PL=e}o(WSe,"setMonitorListener");var zSe=1e3,R2=!1;function jSe(){R2||(R2=!0,setInterval(()=>{for(let e of mc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}PL&&PL()},zSe).unref())}o(jSe,"startMonitoring");var QSe=1e3;if(ro&&no?.addPorts){PR(ro);for(let e=0,t=no.addPorts.length;e<t;e++){let r=no.addPorts[e];r.threadId=no.addThreadIds[e],PR(r)}setInterval(()=>{let e=process.memoryUsage();ro.postMessage({type:I2,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},QSe).unref(),wL=o(()=>new Promise((e,t)=>{ro.on("message",r),ro.postMessage({type:b2});function r(n){n.type===N2&&(ro.off("message",r),e(n.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else wL=U2;Ni.exports.getThreadInfo=wL;function PR(e,t){Gs.push(e),e.on("message",r=>{if(r.type===w2)r.port.threadId=r.threadId,PR(r.port);else if(r.type===vSe){let n=OR.get(r.id);n&&n()}else x2(r,e)}).on("close",()=>{Gs.splice(Gs.indexOf(e),1)}).on("exit",()=>{Gs.splice(Gs.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(PR,"addPort");function x2(e,t){for(let n of M2)n(e,t);let r=CL.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){Ii.error(s)}}o(x2,"notifyMessageListeners");if(LL){let e,t,r=new Set,n=o(async(s,i)=>{i&&(e=i);for(let a of await OSe(s,{withFileTypes:!0}))a.isDirectory()&&a.name!=="node_modules"&&n(y2(s,a.name));try{for await(let{filename:a}of wSe(s,{persistent:!1}))r.add(a),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await vL(),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");Ni.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ro.on("message",async e=>{let{type:t}=e;t===fc.ITC_EVENT_TYPES.SHUTDOWN&&(Ni.exports.restartNumber=e.restartNumber,ro.unref(),setTimeout(()=>{Ii.warn("Thread did not voluntarily terminate",ASe),process.exit(0)},DL).unref())})});var G2={};we(G2,{onStorageReclamation:()=>kp,runReclamationHandlers:()=>FL,setAvailableSpaceRatioGetter:()=>XSe});function kp(e,t,r){(r||(0,DR.getWorkerIndex)()===(0,DR.getWorkerCount)()-1)&&(LR.has(e)||LR.set(e,[]),LR.get(e).push({priority:0,handler:t}),BL||(BL=setTimeout(FL,F2).unref()))}async function FL(){for(let[e,t]of LR)try{let r=await k2(e),n=JSe/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&&(xL.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){xL.default.error?.("Error running storage reclamation handlers",r)}BL=setTimeout(FL,F2).unref()}function XSe(e){k2=e??H2}var UL,DR,xL,MR,B2,LR,JSe,F2,BL,H2,k2,vR=ce(()=>{UL=require("node:fs/promises"),DR=w(nt()),xL=w(ei());k();MR=w(oe()),B2=w(ie());MR.default.initSync();LR=new Map,JSe=MR.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,F2=(0,B2.convertToMS)(MR.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;o(kp,"onStorageReclamation");H2=o(async e=>{if(UL.statfs){let t=await(0,UL.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"),k2=H2;o(FL,"runReclamationHandlers");o(XSe,"setAvailableSpaceRatioGetter")});var DF={};we(DF,{ACTION_32_BIT:()=>HR,ACTION_64_BIT:()=>rTe,AUDIT_STORE_OPTIONS:()=>Yh,Decoder:()=>Il,HAS_BLOBS:()=>$r,HAS_CURRENT_RESIDENCY_ID:()=>Al,HAS_EXPIRATION_EXTENDED_TYPE:()=>Kp,HAS_ORIGINATING_OPERATION:()=>Vp,HAS_PREVIOUS_RESIDENCY_ID:()=>bl,REMOTE_SEQUENCE_UPDATE:()=>Qg,createAuditEntry:()=>Rl,getLastRemoved:()=>eTe,openAuditStore:()=>BR,readAuditEntry:()=>Nt,removeAuditEntry:()=>FR,setAuditRetention:()=>tTe,transactionKeyEncoder:()=>Q2});function BR(e){let t=e.auditStore=e.openDB(HL.AUDIT_STORE_NAME,{create:!1,...Yh});t||(t=e.auditStore=e.openDB(HL.AUDIT_STORE_NAME,Yh),$2(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=GL;kp(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()-kL/(1+i*i)})){try{m=FR(t,p,_)}catch(g){lf.warn("Error removing audit entry",g)}if(h=p,await new Promise(setImmediate),++f>=ZSe){a=10;break}}await m}finally{f===0?a=Math.min(a<<1,kL/10):($2(t,h),a>100&&(a=a>>1)),d(void 0),c()}},a).unref()});return u}if(o(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,qp.getWorkerIndex)()===(0,qp.getWorkerCount)()-1&&c(),(0,qp.getWorkerIndex)()===0&&!q2)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(q2=!0,lf.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 FR(e,t,r){let n=nTe(r),s;if(n&$r){s=Nt(r);let i=e.tableStores[s.tableId];if(i){let a=s.type==="message"?null:i?.getEntry(s.recordId);(!a||a.version!==s.version||!a.value)&&So(()=>Ia(s.getValue(i)),i.rootStore)}}if((n&15)===qL){s=s||Nt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId)?.version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function $2(e,t){$L[0]=t,e.put(Symbol.for("last-removed"),J2)}function eTe(e){let t=e.get(Symbol.for("last-removed"));if(t)return J2.set(t),$L[0]}function tTe(e,t=GL){kL=e,GL=t}function Rl(e,t,r,n,s,i,a,c,l,u,d,f,m){let h=X2[a];if(!h)throw new Error(`Invalid audit entry type ${a}`);let p=1;if(n&&(n>1?hc.setFloat64(0,n):qs.set(VL),p=9),l){if(l&255)throw new Error("Illegal extended type");p+=3}R(s),R(t),g(r),hc.setFloat64(p,e),p+=8,l&Al&&R(u),l&bl&&R(d),l&Kp&&(hc.setFloat64(p,f),p+=8),l&Vp&&R(Z2[m]),i?g(i):qs[p++]=0,l?hc.setUint32(n?8:0,h|l|3221225472):qs[n?8:0]=h;let _=qs.subarray(0,p);if(c)return Buffer.concat([_,c]);return _;function g(T){let y=p;p+=1,p=(0,Ql.writeKey)(T,qs,p);let N=p-y-1;N>127?N>16383?(lf.error("Key or username was too large for audit entry",T),p=y+1,qs[y]=0):(qs.copyWithin(y+2,y+1,p),hc.setUint16(y,N|32768),p++):qs[y]=N}function R(T){T<128?qs[p++]=T:T<16384?(hc.setUint16(p,T|32768),p+=2):T<1056964608?(hc.setUint32(p,T|3221225472),p+=4):(qs[p]=255,hc.setUint32(p+1,T),p+=5)}}function nTe(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 Il(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Il(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&Al&&(m=n.readInt()),i&bl&&(h=n.readInt()),i&Kp&&(p=n.readFloat64()),i&Vp){let y=n.readInt();_=Z2[y]}l=n.readInt();let g=n.position,R=n.position+=l,T;return{type:X2[i&7],tableId:c,nodeId:a,get recordId(){return(0,Ql.readKey)(e,u,d)},getBinaryRecordId(){return e.subarray(u,d)},version:f,previousLocalTime:s,get user(){return R>g?(0,Ql.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(y,N,O){if(i&UR||i&Gp&&!N)return T||(T=So(()=>y.decoder.decode(e.subarray(n.position,r)),y.rootStore)),T;if(i&Gp&&O)return OI(y.getEntry(this.recordId),O,y)},getBinaryValue(){return i&(UR|Gp)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:m,previousResidencyId:h,expiresAt:p,originatingOperation:_}}catch(n){return lf.error("Reading audit entry error",n,e),{}}}var Ql,xR,HL,qp,j2,lf,qs,hc,Q2,Yh,kL,ZSe,$L,J2,GL,q2,UR,Gp,V2,qL,K2,Y2,W2,z2,HR,rTe,Qg,Al,bl,Vp,Kp,$r,X2,Z2,Il,Mi=ce(()=>{Ql=require("ordered-binary"),xR=w(oe()),HL=w(Vt());k();qp=w(nt()),j2=w(ie());Vc();lf=w(Q());V_();Kn();vR();(0,xR.initSync)();qs=Buffer.alloc(2816),hc=new DataView(qs.buffer,qs.byteOffset,2816),Q2={writeKey(e,t,r){return e===$p?(t.set($p,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Ql.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,Ql.readKey)(e,t,r)}},Yh={encoding:"binary",keyEncoder:Q2},kL=(0,j2.convertToMS)((0,xR.get)(U.LOGGING_AUDITRETENTION))||86400*3,ZSe=1e3,$L=new Float64Array(1),J2=new Uint8Array($L.buffer),GL=1e4,q2=!1;o(BR,"openAuditStore");o(FR,"removeAuditEntry");o($2,"updateLastRemoved");o(eTe,"getLastRemoved");o(tTe,"setAuditRetention");UR=16,Gp=32,V2=1,qL=2,K2=3,Y2=4,W2=5,z2=6,HR=14,rTe=15,Qg=11,Al=512,bl=1024,Vp=2048,Kp=4096,$r=8192,X2={put:V2|UR,[V2]:"put",delete:qL,[qL]:"delete",message:K2|UR,[K2]:"message",invalidate:Y2|Gp,[Y2]:"invalidate",patch:W2|Gp,[W2]:"patch",relocate:z2,[z2]:"relocate"},Z2={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};o(Rl,"createAuditEntry");o(nTe,"readAction");o(Nt,"readAuditEntry");Il=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 sU={};we(sU,{ENTRY:()=>iTe,HAS_EXPIRATION:()=>$R,HAS_RESIDENCY_ID:()=>jL,HAS_STRUCTURE_UPDATE:()=>eS,LAST_TIMESTAMP_PLACEHOLDER:()=>$p,LOCAL_TIMESTAMP:()=>sTe,METADATA:()=>Ed,NEW_TIMESTAMP_PLACEHOLDER:()=>tQ,NO_TIMESTAMP:()=>GR,PENDING_LOCAL_TIME:()=>QL,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>VL,RecordEncoder:()=>zL,TIMESTAMP_ASSIGN_LAST:()=>aTe,TIMESTAMP_ASSIGN_NEW:()=>rQ,TIMESTAMP_ASSIGN_PREVIOUS:()=>nQ,TIMESTAMP_PLACEHOLDER:()=>kR,TIMESTAMP_RECORD_PREVIOUS:()=>KL,entryMap:()=>pc,handleLocalTimeForGets:()=>VR,lastMetadata:()=>ut,recordUpdater:()=>JL,removeEntry:()=>Zl});function lTe(){return zp[0]=zp[0]^64,oTe.getFloat64(0)}function VR(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++,ut=null;let l=r.call(this,a,c);return l&&(ut&&(l.metadataFlags=ut[Ed],l.localTime=ut.localTime,l.residencyId=ut.residencyId,ut.expiresAt>=0&&(l.expiresAt=ut.expiresAt),ut=null),l.value&&pc.set(l.value,l),l.key=a),l};let n=e.get;e.get=function(a,c){ut=null;let l=n.call(this,a,c);return ut&&l&&(pc.set(l,ut),ut=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=>(ut&&(l.metadataFlags=ut[Ed],l.localTime=ut.localTime,l.residencyId=ut.residencyId,ut.expiresAt>=0&&(l.expiresAt=ut.expiresAt),ut=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,Xl.push(new WeakRef(this))),c.call(this)},a.prototype.done=function(){if(l.call(this),this.isDone)for(let u=0;u<Xl.length;u++){let d=Xl[u].deref();(!d||d.isDone||d.isCommitted)&&Xl.splice(u--,1)}},a.prototype.done.isTracked=!0}return e}function JL(e,t,r){return function(n,s,i,a,c=-1,l,u,d="put",f,m){l==null?Jl=GR:f?Jl=i?.localTime?KL|nQ:GR:Jl=l?i?.localTime?KL|16384:rQ|16384:GR;let h=u?.expiresAt;if(h>=0&&(c|=$R),Wp=c,YL=h,i?.version===a&&l===!1)throw new Error("Must retain local time if version is not changed");let p={version:a,instructedWrite:Jl>0},_,g=0;try{let R=i?.residencyId,T=u?.residencyId;T&&(WL=T,Wp|=jL,g|=Al),R!==T&&(g|=bl,R||(R=0)),c&$R&&(g|=Kp),u?.originatingOperation&&(g|=Vp),f&&(p.ifVersion=_=i?.version??null),i&&i.value&&d!=="message"&&i.metadataFlags&$r&&(!i.localTime||!r.getBinaryFast(i.localTime))&&Ia(i.value);let y;if(s!==void 0&&(y=XE(()=>e.put(n,s,p),n,e.rootStore),kc&&(g|=$r)),l){let N=u?.user?.username;if(m&&(XE(()=>e.encoder.encode(m),n,e.rootStore),kc&&(g|=$r)),e.encoder.hasStructureUpdate&&(g|=eS,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let O=i?.localTime,F=r.get(O);if(F){let Z=Nt(F).previousLocalTime;return y=r.put(O,Rl(a,t,n,Z,u?.nodeId??server.replication.getThisNodeId(r)??0,N,d,Yp,g,T,R,h),{ifVersion:_}),y}}y=r.put(s===void 0?tQ:$p,Rl(a,t,n,i?.localTime?1:0,u?.nodeId??server.replication?.getThisNodeId(r)??0,N,d,Yp,g,T,R,h,u?.originatingOperation),{instructedWrite:!0,ifVersion:_})}return y}catch(R){throw R.message+=" id: "+n+" options: "+p,R}}}function Zl(e,t,r){if(t)return t.value&&t.metadataFlags&$r&&!e.auditStore?.getBinaryFast(t.localTime)&&Ia(t.value),e.remove(t.key,r)}var eQ,qR,kR,$p,VL,tQ,sTe,Ed,iTe,zp,oTe,GR,rQ,aTe,nQ,KL,$R,jL,QL,eS,pc,cTe,Yp,Jl,Wp,YL,WL,ut,zL,Xl,Vc=ce(()=>{eQ=require("msgpackr");Mi();qR=w(Q());Kn();Kn();kR=new Uint8Array([1,1,1,1,4,64,0,0]),$p=new Uint8Array([1,1,1,1,1,0,0,0]),VL=new Uint8Array([1,1,1,1,3,64,0,0]),tQ=new Uint8Array([1,1,1,1,0,64,0,0]),sTe=Symbol("local-timestamp"),Ed=Symbol("metadata"),iTe=Symbol("entry"),zp=new Uint8Array(8),oTe=new DataView(zp.buffer,0,8),GR=0,rQ=0,aTe=1,nQ=3,KL=4,$R=16,jL=32,QL=1,eS=256,pc=new WeakMap,Jl=0,Wp=-1,YL=-1,WL=0,ut=null,zL=class extends eQ.Encoder{static{o(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0;class r{static{o(this,"RecordObject")}getUpdatedTime(){return pc.get(this)?.version}getExpiresAt(){return pc.get(this)?.expiresAt}}t.structPrototype=r.prototype,super(t);let n=this.encode;this.encode=function(i,a){if(Jl||Wp>=0){let c=0,l=Jl;l&&(c+=8,Jl=0);let u=Wp,d=YL,f=WL;u>=0&&(c+=4,Wp=-1,d>=0&&(c+=8,YL=-1),f&&(c+=4,WL=0));let m=cTe=n.call(this,i,a|2048|c);Yp=m.subarray((m.start||0)+c,m.end);let h=m.start||0;return l&&(kR[4]=l,kR[5]=l>>8,m.set(kR,h),h+=8),kc&&(u|=$r),u>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,u|HR<<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 Yp=n.call(this,i,a),Yp};let s=this.saveStructures;this.saveStructures=function(i,a){let c=s.call(this,i,a);return this.hasStructureUpdate=!0,c}}decode(t,r){ut=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(zp,0,c),c+=8;else for(let m=0;m<8;m++)zp[m]=t[c++];l=lTe(),i=t[c]}let u,d;i<32&&(i===HR?(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&$R&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),a&jL&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=So(()=>r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c),this.rootStore);return ut={localTime:l,[Ed]:a,expiresAt:u,residencyId:d},f}return r?.valueAsBuffer?t:So(()=>super.decode(t,r),this.rootStore)}catch(c){return qR.error("Error decoding record",c,"data: "+t.slice(0,40).toString("hex")),null}}};o(lTe,"getTimestamp");o(VR,"handleLocalTimeForGets");Xl=[];setInterval(()=>{for(let e=0;e<Xl.length;e++){let t=Xl[e].deref();!t||t.isDone||t.isCommitted?Xl.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(qR.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):qR.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(JL,"recordUpdater");o(Zl,"removeEntry")});function eD(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?eD(f.conditions,f.operator,r,n,s,i,a,c):mf(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",y=d(p.conditions,!T,h);return T?(N,O)=>y.some(F=>F(N,O)):(N,O)=>y.every(F=>F(N,O))}let g=(p.attribute||p[0])===r.primaryKey,R=Qp(p,r,i,c,g,h);return m&&_<f.length-1&&h&&(h=gTe(r.primaryStore,p.estimated_count,h)),R}).filter(Boolean)}o(d,"mapConditionsToFilters")}function mf(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 Xr.ClientError(`Search condition for ${c} must have a value`);if(Array.isArray(c)){let y=c[0],N=io(n.attributes,y);if(N.relationship){if(c.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let O=N.definition?.tableClass||N.elements?.definition?.tableClass,F=new Map,Z=mf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:u},t,r,O,s,F);if(N.relationship.to){i[c[0]]=F;let G=!!io(O.attributes,N.relationship.to)?.elements;Z=hTe(Z,N,O.primaryStore,G,F)}if(N.relationship.from){let G=o(Y=>(Y?.key!==void 0&&(Y=Y.key),mf({attribute:N.relationship.from,value:Y},t,r,n,s,F)),"searchEntry");N.elements?(i[c[0]]=F,Z=pTe(Z,N,O.primaryStore,F,G)):Z=Z.flatMap(G)}return Z}else if(c.length===1)c=c[0];else throw new Xr.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(tD[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]=so.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 Xr.ClientError(`Unknown query comparator "${u}"`)}let R;if(typeof m=="string"&&m.length>$s.MAX_SEARCH_KEY_LENGTH&&(m=m.slice(0,$s.MAX_SEARCH_KEY_LENGTH)+$s.OVERFLOW_MARKER,_=!1,R=Qp(e,n,null,i,d)),typeof h=="string"&&h.length>$s.MAX_SEARCH_KEY_LENGTH&&(h=h.slice(0,$s.MAX_SEARCH_KEY_LENGTH)+$s.OVERFLOW_MARKER,p=!0,R=R??Qp(e,n,null,i,d)),r){let y=m;m=h,h=y,y=!_,_=!p,p=y}if(!f||f.isIndexing||g||l===null&&!f.indexNulls){if(s===!1&&!f)throw new Xr.ClientError(`"${c}" is not indexed, can not search for this attribute`,404);if(s===!1&&g)throw new Xr.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 Xr.ServerError(`"${c}" is not indexed yet, can not search for this attribute`,503);if(l===null&&f&&!f.indexNulls)throw new Xr.ClientError(`"${c}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(R=R??Qp(e,n,null,i,d),!R)throw new Xr.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 y=f.getRange(T).map(R?function({key:N,value:O}){return this?.isSync?O&&R(O)?N:Ec.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(O&&R(O)?N:Ec.SKIP)}catch(G){Z(G)}}))}:N=>N.value==null&&!(N.metadataFlags&(Fn|eu))?Ec.SKIP:(a?._freezeRecords&&Object.freeze(N.value),N));return y.hasEntries=!0,y}else return f?f.customIndex?f.customIndex.search(e,a).map(y=>{if(typeof y=="object"&&y){let{key:N,...O}=y,F=n.primaryStore.getEntry(N);return a?._freezeRecords&&Object.freeze(F?.value),{...O,...F}}return y}):f.getRange(T).map(R?function({key:y,value:N}){let O;return typeof y=="string"&&y.length>$s.MAX_SEARCH_KEY_LENGTH?O=n.primaryStore.get(N):O={[c]:y},this.isSync?R(O)?N:Ec.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(R(O)?N:Ec.SKIP)}catch(G){Z(G)}}))}:({value:y})=>y):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:y,value:N}){return this.isSync?N&&R(N)?y:Ec.SKIP:new Promise((O,F)=>setImmediate(()=>{try{O(N&&R(N)?y:Ec.SKIP)}catch(Z){F(Z)}}))})}function io(e,t){if(Array.isArray(t))if(t.length>1){let r=io(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?io(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 hTe(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 pTe(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 Qp(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=io(t.attributes,d),m=f.definition?.tableClass||f.elements.definition?.tableClass,h=n?.[d],p=Qp({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,R=o((y,N)=>{let O,F;return _?_.returnDirect?(O=_(y,r,N),F=ut):(F=_(y,r,N,!0),Array.isArray(F)?(O=F.map(Z=>Z.value),F=null):O=F?.value):O=y[d],{subObject:O,subEntry:F}},"getSubObject"),T=o((y,N)=>{if(_&&p.idFilter){if(!g)if(p.idFilter.idSet?.size===1){for(let Y of p.idFilter.idSet)e={attribute:_.from??t.primaryKey,value:Y};g=u(_.from??t.primaryKey,p.idFilter,!0,!0)}else g=u(_.from??t.primaryKey,p.idFilter,!1,!0);let G=g(y);return g.idFilter&&(T.idFilter=g.idFilter),G}let{subObject:O,subEntry:F}=R(y,N);return O?Array.isArray(O)?(!n?.[d]&&n&&(n[d]={fromRecord(G){let Y=R(G).subObject;return Array.isArray(Y)?Y.filter(p).map(K=>K[m.primaryKey]):Y}}),O.some(p)):p(O,F):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),tD[a]||a){case $s.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,so.compareKeys)(d,l[0])>=0&&(0,so.compareKeys)(d,l[1])<=0,!0);case"gt":return u(c,d=>(0,so.compareKeys)(d,l)>0);case"ge":return u(c,d=>(0,so.compareKeys)(d,l)>=0);case"lt":return u(c,d=>(0,so.compareKeys)(d,l)<0);case"le":return u(c,d=>(0,so.compareKeys)(d,l)<=0);case"ne":return u(c,d=>(0,so.compareKeys)(d,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new Xr.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&&YR(t)(e),p=e.estimated_count>>4,(isNaN(p)||p>=i)&&(m=!1));let _=0,g=3;function R(T){let y=T[d],N;if(typeof y!="object"||!y||h?N=f(y):Array.isArray(y)?N=y.some(f):y instanceof Date&&(N=f(y.getTime())),m&&(g++,!N&&!R.idFilter&&++_/g*i>p)){let O=mf(e,r.transaction.getReadTxn(),!1,t),F;R.to?F=O.flatMap(G=>t.primaryStore.get(G)[R.to]):F=O.map(hf);let Z=new Set(F);R.idFilter=G=>Z.has(hf(G)),R.idFilter.idSet=Z}return N}return o(R,"recordFilter"),s&&(R.idFilter=f),R}o(u,"attributeComparator")}function YR(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/ta(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=tD[n]||n,n===$s.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=io(e.attributes,s[0]),a=i.definition?.tableClass||i.elements.definition?.tableClass,c=YR(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*ta(e.indices[i.relationship.from])/(ta(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=ta(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else if(n==="starts_with"||n==="prefix")r.estimated_count=fTe*ta(e.primaryStore)+1;else if(n==="between")r.estimated_count=dTe*ta(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=ta(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=uTe*ta(e.primaryStore)+1}typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return o(t,"estimateConditionForTable"),t}function fg(e,t){if(e)if(ra=e,uf.lastIndex=0,ETe.test(e))try{if(t&&(t.conditions=[]),wi=t??new ff,jp(wi,""),kr!==ra.length&&Jt("Unable to parse query, unexpected end of query"),wi.parseErrorMessage&&(wi.parseError=new XL(t.parseErrorMessage),!t))throw wi.parseError;return wi}catch(r){if(r.statusCode=400,r.message=`Unable to parse query, ${r.message} at position ${kr} in '${ra}'`,wi.parseErrorMessage&&(r.message+=", "+wi.parseErrorMessage),t)t.parseError=r;else throw r}else return t??new URLSearchParams(e)}function Jt(e){let t=`${e} at position ${kr}`;wi.parseErrorMessage=wi.parseErrorMessage?wi.parseErrorMessage+", "+t:t}function jp(e,t){let r=uf,n,s,i,a,c,l=decodeURIComponent,u;for(;n=r.exec(ra);){kr=r.lastIndex;let[,d,f]=n;a?(d&&Jt(`expected operator, but encountered '${d}'`),a=!1,c=!1):c=!0;let m;switch(f){case"=":s!=null?(d.length<=2?i=d:Jt(`invalid FIQL operator ${d}`),l=sQ):(l=decodeURIComponent,i="equals",d||Jt("attribute must be specified before equality comparator"),s=df(d));break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":i=mTe[f],l=ZL[i]?sQ:decodeURIComponent,d||Jt(`attribute must be specified before comparator ${f}`),s=df(d);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null)s===void 0&&(t&&Jt(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`),Jt(`no comparison specified before ${f?"'"+f+"'":"end of string"}`));else{e.conditions||Jt("conditions/comparisons are not allowed in a property list");let p={comparator:i,attribute:s||null,value:l(d)};if(i==="eq"&&iQ(p,d),s===""){let _=e.conditions[e.conditions.length-1];_.chainedConditions=_.chainedConditions||[],_.chainedConditions.push(p),_.operator=u}else KR(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?Jt("conditions/comparisons are not allowed in a property list"):e.push(df(d)),s=void 0;break;case"(":uf.lastIndex=kr;let h=jp(d?[]:new ff,")");switch(d){case"":KR(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:Jt("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":Jt("group by is not implemented yet");case"sort":e.sort=oQ(h);break;default:Jt(`unknown query function call ${d}`)}ra[kr]===","?r.lastIndex=++kr:a=!0,s=null;break;case"{":e.conditions&&Jt("property sets are not allowed in a queries"),d||Jt("property sets must have a defined parent property name"),uf.lastIndex=kr,m=jp([],"}"),m.name=d,e.push(m),ra[kr]===","?r.lastIndex=++kr:a=!0;break;case"[":if(uf.lastIndex=kr,d?(m=jp(new ff,"]"),m.name=d):m=jp(e.conditions?new ff:[],"]"),e.conditions)if(KR(e,u),ra[kr]==="="){l=decodeURIComponent,i="equals",s=df(d),r.lastIndex=++kr;break}else e.conditions.push(m),s=null;else e.push(m);ra[kr]===","?r.lastIndex=++kr: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"&&iQ(p,d),KR(e,u),e.conditions.push(p)}else d&&Jt("no attribute or comparison specified");else(d||e.length>0&&c)&&e.push(df(d));return e}else Jt(t?`expected '${t}', but encountered '${f[0]}'`:`unexpected token '${f[0]}'`);default:Jt(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?_Te:uf,r.lastIndex=kr),kr===ra.length)return e}t&&Jt(`expected '${t}', but encountered end of string`)}function KR(e,t){e.conditions.length>0&&(e.operator?e.operator!==t&&Jt("Can not mix operators within a condition grouping"):e.operator=t)}function df(e){return e.indexOf(".")>-1?e.split(".").map(df):decodeURIComponent(e)}function sQ(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 Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function iQ(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function oQ(e){let t=aQ(e[0]);return e.length>1&&(t.next=oQ(e.slice(1))),t}function aQ(e){if(Array.isArray(e)){let t=aQ(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}}Jt(`Unknown sort type ${e}`)}function hf(e){return Array.isArray(e)?e.join("\0"):e}function ta(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function gTe(e,t,r){return t*r/ta(e)}var Xr,$s,so,Ec,uTe,dTe,fTe,mTe,ZL,tD,XL,ETe,uf,_Te,kr,wi,ra,ff,mg=ce(()=>{Xr=w(ge()),$s=w(Vt()),so=require("ordered-binary"),Ec=require("lmdb");bT();Vc();uTe=.3,dTe=.1,fTe=.05,mTe={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},ZL={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};o(eD,"executeConditions");o(mf,"searchByIndex");o(io,"findAttribute");o(hTe,"joinTo");o(pTe,"joinFrom");tD={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(Qp,"filterByType");o(YR,"estimateCondition");XL=class extends Xr.Violation{static{o(this,"SyntaxViolation")}},ETe=/[()[\]|!<>.]|(=\w*=)/,uf=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,_Te=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;o(fg,"parseQuery");o(Jt,"recordError");o(jp,"parseBlock");o(KR,"assignOperator");o(df,"decodeProperty");o(sQ,"typedDecoding");o(iQ,"wildcardDecoding");o(oQ,"toSortObject");o(aQ,"toSortEntry");ff=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(hf,"flattenKey");o(ta,"estimatedEntryCount");o(gTe,"intersectionEstimate")});var xB={};we(xB,{MultiPartId:()=>WR,Resource:()=>Br,contextStorage:()=>Ef,snakeCase:()=>TTe,transformForSelect:()=>_f});function TTe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function cQ(e,t){if(tu=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(tu=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new WR;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){tu=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return tu=!0,null;e[e.length-1]==="/"&&(tu=!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 _o?a=i:d=i;else if(s&&typeof s=="object")d=s,s=void 0,c=d.getId?.()??d[this.primaryKey];else throw new pf.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 ui,l.id=c,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new ui,l.id=c,c==null&&(u=!0);l||(l=new ui,l.id=c),u&&(l.isCollection=!0);let f;a||(a=Ef.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(_=>Ef.run(a,()=>p(_)),"runAction")),a?.transaction){let _=this.getResource(c,a,f);return _.then?_.then(h):h(_)}else return Ft(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(R=>{if(!R)throw new pf.AccessViolation(a.user);return typeof d?.then=="function"?d.then(T=>e(_,l,a,T)):e(_,l,a,d)});if(!g)throw new pf.AccessViolation(a.user)}return typeof d?.then=="function"?d.then(g=>e(_,l,a,g)):e(_,l,a,d)}o(p,"authorizeActionOnResource")}}function ds(e,t){let r=new pf.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 rD(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 _f(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):rD(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(rD(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(rD(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]=_f(c.select||c,d)}let u=a(c.name);return l(u)}else return a(c);else return c}}o(i,"handleProperty")}var lQ,uQ,pf,dQ,Ef,STe,Br,tu,WR,xa=ce(()=>{lQ=require("crypto");tm();Ru();uQ=w(Zs()),pf=w(ge());Bc();mg();dQ=require("async_hooks");lg();Ef=new dQ.AsyncLocalStorage,STe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Br=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(t.constructor.loadAsInstance===!1)return i;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=_f(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):ds(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):ds(t,"patch")},{hasContent:!0,type:"update"});static delete=Hn(function(t,r,n,s){return t.delete?t.delete(r):ds(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,lQ.randomUUID)()}static create(t,r,n){n?n.getContext&&(n=n.getContext()):n=Ef.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),Ft(n,async()=>{let i=new this(s,n),a=await i.create?i.create(s,r):ds(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):ds(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):ds(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Hn(function(t,r,n,s){return t.subscribe?t.subscribe(r):ds(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):ds(t,"publish")},{hasContent:!0,type:"create"});static search=Hn(function(t,r,n){let s=t.search?t.search(r):ds(t,"search"),i=n.select;if(i&&n.hasOwnProperty("select")&&s!=null&&!s.selectApplied){let a=_f(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):ds(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):ds(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):ds(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#r)return(await this.constructor.create(this.#e,t,this.#t)).#e;ds(this,"post")}static isCollection(t){return t&&t.#r}get isCollection(){return this.#r}static coerceId(t){return t}static parseQuery(t,r){return fg(t,r)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let a=t.slice(s+1),c=r?.headers&&STe[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:cQ(t,this),isCollection:tu}}let i=cQ(t,this);return tu?{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 Vn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Vn}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,uQ._assignPackageExport)("Resource",Br);o(TTe,"snakeCase");o(cQ,"pathToId");WR=class extends Array{static{o(this,"MultiPartId")}toString(){return this.join("/")}};o(Hn,"transactional");o(ds,"missingMethod");o(rD,"selectFromObject");o(_f,"transformForSelect")});var UY={};we(UY,{EVICTED:()=>eu,INVALIDATED:()=>Fn,coerceType:()=>jR,makeTable:()=>JR});function JR(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:R}=e;_??=0;let{attributes:T}=e;T||(T=[]);let y=JL(i,n,l),N,O,F={},Z=Promise.resolve(),G,Y,K;for(let V of T)(V.assignCreatedTime||V.name==="__createdtime__")&&(G=V),(V.assignUpdatedTime||V.name==="__updatedtime__")&&(Y=V),V.expiresAt&&(K=V),V.isPrimaryKey&&(F=V);let $,le=[],ue=[],se=1,me=2,Pe={},De={},dt=864e5,Ye=0,qn,rt,ht,Cc=!1,Pc,$t,vf,Uf=nu.get(U.REPLICATION_DATABASES);if(Array.isArray(Uf)){for(let V of Uf)if(V.name===c&&V.replicateTo>=0){vf=V.replicateTo;break}}let IE=i.getRange({start:!1,end:!1}).constructor,NE=10,xy=6;g&&Hf(),kp(i.env.path,V=>{if(O)return Ta(V)});class xf extends al{static{o(this,"Updatable")}getUpdatedTime(){return pc.get(this.getRecord())?.version}getExpiresAt(){return pc.get(this.getRecord())?.expiresAt}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.set(E,new Ym(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(E,S){return this.addTo(E,-S)}}class Ce extends Br{#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=G;static updatedTimeProperty=Y;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(L=>!L.intermediateSource)){if(this.sources.some(L=>L.name===E.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(E)}O=O||E.get&&(!E.get.reliesOnPrototype||E.prototype.get),N=N||E.load;let A=o(L=>{let D=this.sources;if(D=D.filter(H=>H.intermediateSource&&H[L]&&(!H[L].reliesOnPrototype||H.prototype[L])),D.length>0)if(D.length===1){let H=D[0];return(C,x,z)=>{if(C?.source!==H)return H[L](x,z,C)}}else return(H,C,x)=>{let z=[];for(let ne of D){if(H?.source===ne)break;z.push(ne[L](C,x,H))}return Promise.all(z)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1];b.intermediateSource&&(b={});let I=o(L=>{if(b[L]&&(!b[L].reliesOnPrototype||b.prototype[L]))return(D,H,C)=>{if(!D?.source)return b[L](H,C,D)}},"getApplyToCanonicalSource");Pe={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},De={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let P=b.shouldRevalidateEvents;return(async()=>{let L=!1,D,H=o(async(C,x)=>{let z=C.value,ne=C.table?He[c][C.table]:Ce;if(c===Vf&&(C.table===gu.ROLE_TABLE_NAME||C.table===gu.USER_TABLE_NAME)&&(L=!0),C.id===void 0&&(C.id=z[ne.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));C.source=E;let re={residencyId:Mc(C.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:C.nodeId,async:!0},B=C.id,de=await ne.getResource(B,x,re);switch(C.finished&&await C.finished,C.type){case"put":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!0,re);case"patch":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!1,re);case"delete":return de._writeDelete(B,re);case"publish":case"message":return de._writePublish(B,z,re);case"invalidate":return de._writeInvalidate(B,z,re);case"relocate":return de._writeRelocate(B,re);default:ve.default.error?.("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=E.subscribe;C&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},z=E.subscribeOnThisThread?E.subscribeOnThisThread((0,ru.getWorkerIndex)(),x):(0,ru.getWorkerIndex)()===0,ne=C&&z&&await E.subscribe?.(x);if(ne){let re;for await(let B of ne)try{if(!(B.type==="transaction"?B.writes[0]:B)){ve.default.error?.("Bad subscription event",B);continue}if(B.source=E,B.type==="end_txn"){if(re?.resolve(),B.localTime&&D!==B.localTime){if(B.remoteNodeIds?.length>0){let Se=[Symbol.for("seq"),B.remoteNodeIds[0]],ee=d.get(Se),j=ee?.nodes;j||(j=[]);for(let Te of B.remoteNodeIds.slice(1)){let fe=j.find(We=>We.id===Te);j=j.filter(We=>We.id!==Te||We===fe),fe||(fe={id:Te,seqId:0},j.push(fe)),fe.seqId=Math.max(ee?.seqId??1,B.localTime),Te===re?.nodeId&&(fe.lastTxnTime=B.timestamp)}let pe=Math.max(ee?.seqId??1,B.localTime);ve.default.trace?.("Received txn",c,pe,new Date(pe),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(Se,{seqId:pe,nodes:j})}D=B.localTime}B.onCommit&&re?.committed.then(B.onCommit);continue}if(re)if(B.beginTxn)re.resolve();else{re.write_promises.push(H(B,re));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let he=Ft(B,()=>{if(B.type==="transaction"){let Se=[];for(let ee of B.writes)try{Se.push(H(ee,B))}catch(j){throw j.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(B),j}return Promise.all(Se)}else if(B.type==="define_schema"){let Se=this.attributes.slice(0),ee=!1;for(let j of B.attributes)Se.find(pe=>pe.name===j.name)||(Se.push(j),ee=!0);ee&&(ze({table:s,database:c,attributes:Se,origin:"cluster"}),Xp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,q.CREATE_TABLE,c,s)))}else return B.beginTxn?(re=B,re.write_promises=[H(B,B)],new Promise(Se=>{re.resolve=()=>Se(Promise.all(re.write_promises))})):H(B,B)});re&&(re.committed=he),L&&he&&!he?.waitingForUserChange&&(he.then(()=>Xp.signalUserChange(new Zp.UserEventMsg(process.pid))),he.waitingForUserChange=!0),B.onCommit&&(he?he.then(B.onCommit):B.onCommit())}catch(de){ve.default.error?.("error in subscription handler",de)}}}catch(C){ve.default.error?.(C)}})(),this}static get isCaching(){return O}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(E,S,A){let b=super.getResource(E,S,A);if(this.loadAsInstance===!1&&(S._freezeRecords=!0),E!=null&&this.loadAsInstance!==!1){Pr(E);try{if(b.getRecord?.())return b;if(typeof E=="object"&&E&&!Array.isArray(E))throw new Error(`Invalid id ${JSON.stringify(E)}`);let I=!A?.async||i.cache?.get?.(E),P=Lr(S),L=P.getReadTxn();if(L?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ea(E,S,{transaction:L,ensureLoaded:A?.ensureLoaded},I,D=>{if(D?Ce._updateResource(b,D):b.#e=null,S.onlyIfCached){if(!b.doesExist())throw new ct.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let H=Lc(E,D,S,b);if(H)return P?.disregardReadTxn(),b.#i=!0,S.loadedFromSource=!0,Vs(H,C=>(Ce._updateResource(b,C),b))}return b})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(E)),I}}return b}static _updateResource(E,S){E.#n=S,E.#e=S?.value??null,E.#r=S?.version}ensureLoaded(){let E=Lc(this.getId(),this.#n,this.getContext());if(E)return this.#i=!0,this.getContext().loadedFromSource=!0,Vs(E,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let E=F?.type;if(E==="String"||E==="ID")return super.getNewId();if(!$t){let I=i.getEntry(Symbol.for("id_allocation")),P=I?.value,L;if(P&&P.nodeName===server.hostname&&(!LTe(i)||P.pid===process.pid)){let D=P.start,H=P.end;L=D;for(let C of i.getKeys({start:H,end:D,limit:1,reverse:!0}))L=C}else P=b(I?.version??null),L=P.start;$t=new BigInt64Array([BigInt(L)+1n]),$t=new BigInt64Array(i.getUserSharedBuffer("id",$t.buffer)),$t.maxSafeId=P.end}let S=Number(Atomics.add($t,0,1n)),A=E==="Int"?512:1048576;if(S+A>=$t.maxSafeId){let I=o(P=>{$t.maxSafeId=S+(E==="Int"?1023:4194303);let L=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=P?void 0:i.useReadTransaction(),H=Number($t[0]);for(let z of i.getKeys({start:H+1,end:L,limit:1,transaction:D}))L=z;D?.done();let{value:C,version:x}=i.getEntry(Symbol.for("id_allocation"));if($t.maxSafeId<L){if(C.end>$t.maxSafeId-100)return;ve.default.info?.("New id allocation",S,$t.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:C.start,end:$t.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{ve.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${$t.maxSafeId}, but id of ${L} detected`);let z=b(x);z.alreadyUpdated||Atomics.store($t,0,BigInt(z.start+1)),$t.maxSafeId=z.end}},"updateEnd");S+A===$t.maxSafeId?setImmediate(I):S+100>=$t.maxSafeId&&(ve.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(()=>I(!0)))}return S;function b(I){let P=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=P/4,D,H,C=!1,x,z;do{x=Math.floor(Math.random()*P),z={start:x,end:x+(E==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},D=0;for(let ne of i.getKeys({start:x,limit:1,reverse:!0}))D=ne;H=P;for(let ne of i.getKeys({start:x+1,end:P,limit:1}))H=ne;L*=.875,L<1e3&&!C&&(C=!0,ve.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":""}`,x,D,H,L))}while(!(L<H-x&&(L<x-D||D===0)));return i.transactionSync(()=>{let ne=i.getEntry(Symbol.for("id_allocation"));return(ne?.version??null)==I?(ve.default.info?.("Allocated new id range",z),i.put(Symbol.for("id_allocation"),z,Date.now()),z):(ve.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ne.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,dt=E.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");dt=dt||(p+_)/4,Ta()}static getResidencyRecord(E){return d.get([Symbol.for("residency_by_id"),E])}static setResidency(E){Ce.getResidency=E&&((S,A)=>{try{return E(S,A)}catch(b){throw b.message+=` in residency function for table ${s}`,b}})}static setResidencyById(E){Ce.getResidencyById=E&&(S=>{try{return E(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(E,S){if(Ce.getResidencyById)return Ce.getResidencyById(E[t]);let A=vf;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 b=[server.hostname];if(S.previousResidency)b.push(...S.previousResidency.slice(0,A));else{let I=server.nodes.map(D=>D.name),P=Math.floor(I.length*Math.random());b.push(...I.slice(P,P+A));let L=P+A-I.length;L>0&&b.push(...I.slice(0,L))}return b}}static enableAuditing(E=!0){g=E,E&&Hf(),Ce.audit=E}static coerceId(E){return E===""?null:jR(E,F)}static async dropTable(){delete He[c][s];for(let E of i.getRange({versions:!0,snapshot:!1,lazy:!0}))E.metadataFlags&$r&&E.value&&Ia(E.value);if(c===a){for(let E of T)d.remove(Ce.tableName+"/"+E.name),r[E.name]?.drop();d.remove(Ce.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),sD.default.unlinkSync(i.env.path);Xp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,q.DROP_TABLE,c,s))}get(E){let S=this.constructor;if(typeof E=="string"&&S.loadAsInstance!==!1)return this.getProperty(E);if(Ff(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?Ce.getRecordCount().then(b=>(A.recordCount=b.recordCount,A.estimatedRecordRange=b.estimatedRange,A)):A}if(E!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),b=Lr(A),I=b.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let P=Rr(E);Pr(P);let L=!0;return E.checkPermission&&(L=this.allowRead(A.user,E)),Vs(Vs(L,D=>{if(!D)throw new ct.AccessViolation(A.user);let H=!0;return Ea(P,A,{transaction:I,ensureLoaded:H},!1,C=>{if(A.onlyIfCached){if(!C?.value)throw new ct.ServerError("Entry is not cached",504)}else if(H){let x=Lc(P,C,A);if(x)return b?.disregardReadTxn(),A.loadedFromSource=!0,x.then(z=>z?.value)}return C?.value})}),D=>{let H=E?.select;return H&&D!=null?_f(H,this.constructor)(D):D})}if(E?.property)return this.getProperty(E.property);if(this.doesExist()||E?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(E,S){let A=_a(E,S);if(A?.read){if(A.isSuperUser)return!0;let b=A.attribute_permissions,I=S?.select;if(b?.length>0||Cc&&I){if(S||(S={}),I){let P=Array.isArray(I)?I:[I],L=b?.length>0&&nD(b,"read");S.select=P.map(D=>{let H=D.name||D;if(!L||L[H]){let C=ht[H]?.definition?.tableClass;if(C){if(D.name||(D={name:D}),!D.checkPermission&&S.checkPermission&&(D.checkPermission=S.checkPermission),!C.prototype.allowRead.call(null,E,D))return!1;if(!D.select)return D.name}return D}}).filter(Boolean)}else S.select=b.filter(P=>P.read&&!ht[P.attribute_name]).map(P=>P.attribute_name);return S}else return!0}}allowUpdate(E,S,A){let b=_a(E,A);if(b?.update){let I=b.attribute_permissions;if(I?.length>0){let P=nD(I,"update");for(let L in S)if(!P[L])return!1;for(let L of I){let D=L.attribute_name;!L.update&&!(D in S)&&(S[D]=this.getProperty(D))}}return Sa(this.getContext())}}allowCreate(E,S,A){if(this.isCollection){let b=_a(E,A);if(b?.insert){let I=b.attribute_permissions;if(I?.length>0){let P=nD(I,"insert");for(let L in S)if(!P[L])return!1;return Sa(this.getContext())}else return Sa(this.getContext())}}else return this.allowUpdate(E,{})}allowDelete(E,S){return _a(E,S)?.delete&&Sa(this.getContext())}update(E,S){let A,b=typeof S=="boolean"||S===void 0&&(E==null||typeof E=="object"&&!(E instanceof URLSearchParams)),I=!1;b?(I=S,S=E,A=this.getId()):A=Rr(E);let P=this.getContext();if(!Lr(P))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(I)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(b){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(P.user,S,E)),Vs(D,H=>{if(!H)throw new ct.AccessViolation(P.user);return Vs(i.get(Rr(E)),C=>{let x=new xf(C);return x._setChanges(S),this._writeUpdate(A,x.getChanges(),!1),x})})}return this._writeUpdate(A,this.#t,I),this}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.#s===mQ?this.set(E,(+this.getProperty(E)||0)+S):(this.#s||this.update(),this.set(E,new Ym(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)),Vs(S,b=>{if(!b)throw new ct.AccessViolation(A.user);this._writeInvalidate(E?Rr(E):this.getId())})}_writeInvalidate(E,S,A){let b=this.getContext();Pr(E),Lr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Pe.invalidate?.bind(this,b,E),beforeIntermediate:Ra(S,De.invalidate?.bind(this,b,E)),commit:o((P,L)=>{if(!(ga(P,L,A?.nodeId)<=0)){S??=null;for(let D in r)S||(S={}),S[D]===void 0&&(S[D]=this.getProperty(D));ve.default.trace?.(`Invalidating entry in ${s} id: ${E}, timestamp: ${new Date(P).toISOString()}`),y(E,S,L,P,Fn,g,{user:b?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(E,S){let A=this.getContext();Pr(E),Lr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Pe.relocate?.bind(this,A,E),beforeIntermediate:De.relocate?.bind(this,A,E),commit:o((I,P)=>{if(ga(I,P,S?.nodeId)<=0)return;let L=Ce.getResidencyRecord(S.residencyId),D=0,H=null,C=P?.value;if(L&&!L.includes(server.hostname)){for(let x in r)H||(H={}),H[x]=C[x];D=Fn}else H=C;ve.default.trace?.(`Relocating entry id: ${E}, timestamp: ${new Date(I).toISOString()}`),y(E,H,P,I,D,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(E,S){if(this.getResidencyById)return!1;let A={previousResidency:this.getResidencyRecord(E.residencyId),isRelocation:!0},b=Dc(this.getResidency(S.value,A)),I;if(b){if(!b.includes(server.hostname))return!1;I=Mc(b)}let P=0;ve.default.debug?.("Performing a relocate of an entry",E.key,S.value,b);let L=y(E.key,S.value,E,E.version,P,!0,{residencyId:I,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(E,S,A){let b=this.Source,I;if(!((O||g)&&(!S||(I=i.getEntry(E),!I||!S)||I.version!==A))){if(O){if(i.hasLock(E,I.version))return;let P;for(let L in r)P||(P={}),P[L]=S[L];if(P)return y(E,P,I,A,eu,null,null,null,!0)}return i.ifVersion(E,A,()=>{po(E,S,null)}),Zl(i,I??i.getEntry(E),A)}}lock(){throw new Error("Not yet implemented")}static operation(E,S){return E.table||=s,E.schema||=c,global.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 b=this.getContext();return E.checkPermission&&(A=this.allowUpdate(b.user,S,E)),Vs(A,I=>{if(!I)throw new ct.AccessViolation(b.user);if(Array.isArray(S))for(let P of S){let L=P[t];this._writeUpdate(L,P,!0)}else{let P=Rr(E);this._writeUpdate(P,S,!0)}})}}create(E,S){let A=!0,b=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(b.user,S,E)),Vs(A,I=>{if(!I)throw new ct.AccessViolation(b.user);let P=Rr(E)??S[t];if(P===void 0)P=this.constructor.getNewId();else if(i.get(P))throw new ct.ClientError("Record already exists",409);return this._writeUpdate(P,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,b){let I=this.getContext(),P=Lr(I);Pr(E);let L=this.#n??i.getEntry(E);this.#s=A?mQ:wTe;let D=o(C=>A?C.put?()=>C.put(I,E,S):null:C.patch?()=>C.patch(I,E,S):C.put?()=>C.put(I,E,cl(this)):null,"writeToSources"),H={key:E,store:i,entry:L,nodeName:I?.nodeName,validate:o(C=>{S||(S=this.#t),A||S&&K_(this.#t===S?this:S)?I?.source||(P.checkOverloaded(),this.validate(S,!A),Y&&(S[Y.name]=Y.type==="Date"?new Date(C):Y.type==="String"?new Date(C).toISOString():C),A&&(t&&S[t]!==E&&(S[t]=E),G&&(L?.value?S[G.name]=L?.value[G.name]:S[G.name]=G.type==="Date"?new Date(C):G.type==="String"?new Date(C).toISOString():C),S=cl(S))):P.removeWrite(H)},"validate"),before:D(Pe),beforeIntermediate:Ra(S,D(De)),commit:o((C,x,z)=>{if(z){if(I&&x?.version>(I.lastModified||0)&&(I.lastModified=x.version),this.#n=x,x?.value&&x.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=x?.value??null)}this.#t=void 0,this.#r=C;let ne=x?.value,re=S;this.#s=0;let B=!1,de=ga(C,x,b?.nodeId),he,Se=A?"put":"patch",ee;b?.residencyId!=null&&(ee=b.residencyId);let j=I?.expiresAt??(p?p+Date.now():-1);if(de<=0){if(g){let fe=x.localTime,We=x.version;ve.default.trace?.("Applying CRDT update to record with id: ",E,"txn time",new Date(C),"applying later update from:",new Date(We),"local recorded time",new Date(fe));let St=[];for(;fe>C||We>=C&&fe>0;){let ft=l.get(fe);if(!ft)break;let Ee=Nt(ft);if(We=Ee.version,We>=C){if(We===C){if(de=ga(C,{version:We,localTime:fe},b?.nodeId),de===0)return Te(!1);if(de>0)continue}if(Ee.type==="patch")St.push(Ee),he=S;else if(Ee.type==="put"||Ee.type==="delete")return Te(!1)}fe=Ee.previousLocalTime}fe||ve.default.debug?.("No further audit history, applying incremental updates based on available history",E,"existing version preserved",x),St.sort((ft,Ee)=>ft.version-Ee.version);for(let ft of St){let Ee=ft.getValue(i);if(ve.default.debug?.("Rebuilding update with future patch:",new Date(ft.version),Ee,ft),re=$_(re,Ee,A),!re)return Te(!1)}}else{if(A)return Te(!1);re=$_(re,ne,A),ve.default.debug?.("Rebuilding update without audit:",re)}ve.default.trace?.("Rebuilt record to save:",re," is full update:",A)}let pe;if(A?pe=re:this.constructor.loadAsInstance===!1?pe=cl(ne,re):(this.#e=ne,pe=cl(this,re)),this.#e=pe,pe&&pe.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(ee==null){L?.residencyId&&(I.previousResidency=Ce.getResidencyRecord(L.residencyId));let fe=Dc(Ce.getResidency(pe,I));if(fe&&!fe.includes(server.hostname))if(he??=pe,B=!0,Ce.getResidencyById)pe=void 0;else{pe=null;for(let We in r)pe||(pe={}),pe[We]=he[We]}ee=Mc(fe)}A||(he=S),ve.default.trace?.(`Saving record with id: ${E}, timestamp: ${new Date(C).toISOString()}${j?", expires at: "+new Date(j).toISOString():""}${x?", replaces entry from: "+new Date(x.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(pe).slice(0,100)}catch{return""}})()),po(E,ne,pe),Te(!0),I.expiresAt&&Ta();function Te(fe){y(E,fe?pe:void 0,fe?x:{...x,value:void 0},C,B?Fn:0,g,{omitLocalRecord:B,user:I?.user,residencyId:ee,expiresAt:j,nodeId:b?.nodeId,originatingOperation:I?.originatingOperation},Se,!1,fe?he:he??S)}o(Te,"writeCommit")},"commit")};P.addWrite(H)}async delete(E){if(Ff(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)),Vs(S,b=>{if(!b)throw new ct.AccessViolation(A.user);let I=Rr(E);return this._writeDelete(I),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(E,S){let A=Lr(this.getContext());Pr(E);let b=this.getContext();return A.addWrite({key:E,store:i,entry:this.#n,nodeName:b?.nodeName,before:Pe.delete?.bind(this,b,E),beforeIntermediate:De.delete?.bind(this,b,E),commit:o((I,P,L)=>{let D=P?.value;L&&(b&&P?.version>(b.lastModified||0)&&(b.lastModified=P.version),Ce._updateResource(this,P)),!(ga(I,P,S?.nodeId)<=0)&&(po(this.getId(),D),ve.default.trace?.(`Deleting record with id: ${E}, txn timestamp: ${new Date(I).toISOString()}`),g||R?(y(E,null,P,I,0,g,{user:b?.user,nodeId:S?.nodeId},"delete"),g||Ta()):Zl(i,P))},"commit")}),!0}search(E){let S=this.getContext(),A=Lr(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 ct.AccessViolation(S.user);let b=E.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(E)?E:E[Symbol.iterator]?Array.from(E):[];let I=E.id??this.getId();I&&(b=[{attribute:null,comparator:Array.isArray(I)?"prefix":"starts_with",value:I}].concat(b));let P,L={};function D(j,pe){let Te;switch(pe){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Te=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}for(let fe of j){if(fe.conditions){fe.conditions=D(fe.conditions,fe.operator);continue}let We=fe[0]??fe.attribute,St=We==null?F:io(T,We);if(St)(St.type||ZL[fe.comparator])&&(fe[1]===void 0?fe.value=C(fe.value,St):fe[1]=C(fe[1],St));else if(We!=null&&!E.allowConditionsOnDynamicAttributes)throw(0,ct.handleHDBError)(new Error,`${We} is not a defined attribute`,404);if(fe.chainedConditions)if(fe.chainedConditions.length===1&&(!fe.operator||fe.operator=="and")){let ft=fe.chainedConditions[0],Ee,pt;if(ft.comparator==="gt"||ft.comparator==="greater_than"||ft.comparator==="ge"||ft.comparator==="greater_than_equal"?(Ee=fe,pt=ft):(Ee=ft,pt=fe),Ee.comparator!=="lt"&&Ee.comparator!=="less_than"&&Ee.comparator!=="le"&&Ee.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let tt=pt.comparator==="ge"||pt.comparator==="greater_than_equal",cr=Ee.comparator==="le"||Ee.comparator==="less_than_equal";fe.comparator=(tt?"ge":"gt")+(cr?"le":"lt"),fe.value=[pt.value,Ee.value]}else throw new Error("Multiple chained conditions are not currently supported")}return j}o(D,"prepareConditions");function H(j,pe){if(E.enforceExecutionOrder)return j;for(let Te of j)Te.conditions&&(Te.conditions=H(Te.conditions,Te.operator));return j.length>1&&pe!=="or"?RTe(j,YR(Ce)):j}o(H,"orderConditions");function C(j,pe){return Array.isArray(j)?j.map(Te=>jR(Te,pe)):jR(j,pe)}o(C,"coerceTypedValues");let x=E.operator;(b.length>0||x)&&(b=D(b,x));let z=typeof E.sort=="object"&&E.sort,ne;if(z&&x!=="or"){let j=z.attribute;if(j==null)throw new ct.ClientError("Sort requires an attribute");if(P=b.find(pe=>hf(pe.attribute)===hf(j)),!P){let pe=io(T,j);if(!pe)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);if(pe.indexed)P={...z,comparator:"sort"},b.push(P);else if(b.length===0&&!E.allowFullScan)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not indexed and not combined with any other conditions`,404)}P&&(P.descending=!!z.descending)}b=H(b,x),z&&(P&&b[0]===P?z.next&&(ne={dbOrderedAttribute:z.attribute,attribute:z.next.attribute,descending:z.next.descending,next:z.next.next}):(P&&b.splice(b.indexOf(P),1),ne=z));let re=E.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),E.explain)return{conditions:b,operator:x,postOrdering:ne,selectApplied:!!re};let B=A.useReadTxn(),de=eD(b,x,Ce,B,E,S,(j,pe)=>pu(j,re,S,B,pe),L),he=E.ensureLoaded!==!1,Se=Ce.transformEntryForSelect(re,S,B,L,he,!0),ee=Ce.transformToOrderedSelect(de,re,ne,S,B,Se);return(E.offset||E.limit!==void 0)&&(ee=ee.slice(E.offset,E.limit!==void 0?(E.offset||0)+E.limit:void 0)),ee.onDone=()=>{ee.onDone=null,A.doneReadTxn()},ee.selectApplied=!0,ee.getColumns=()=>{if(re){let j=[];for(let pe of re)pe==="*"?j.push(...T.map(Te=>Te.name)):j.push(pe.name||pe);return j}return T.filter(j=>!j.computed&&!j.relationship).map(j=>j.name)},ee}static transformToOrderedSelect(E,S,A,b,I,P){let L=new IE;if(A){E=pu(E,S,b,I,null);let D;L.iterate=function(){let C,x=E[Symbol.asyncIterator]?E[Symbol.asyncIterator]():E[Symbol.iterator](),z,ne=A.dbOrderedAttribute,re,B,de=!0;function he(ee){let j=ee.next&&he(ee.next),pe=ee.descending;return b.sort=ee,(Te,fe)=>{let We=hu(Te,ee.attribute,b),St=hu(fe,ee.attribute,b),ft=pe?(0,su.compareKeys)(St,We):(0,su.compareKeys)(We,St);return ft===0?j?.(Te,fe)||0:ft}}o(he,"createComparator");let Se=he(A);return{async next(){let ee;if(C)if(ee=C.next(),ee.done){if(z)return L.onDone&&L.onDone(),ee}else return{value:await P.call(this,ee.value)};D=[],re&&D.push(re);do if(ee=await x.next(),ee.done){if(z=!0,D.length)break;return L.onDone&&L.onDone(),ee}else{let j=ee.value;if(j?.then&&(j=await j),ne){let pe=hu(j,ne,b);if(de)de=!1,B=pe;else if(pe!==B){B=pe,re=j;break}}D.push(j)}while(!0);return A.isGrouped,D.sort(Se),C=D[Symbol.iterator](),ee=C.next(),ee.done?(L.onDone&&L.onDone(),ee):{value:await P.call(this,ee.value)}},return(){L.onDone&&L.onDone(),x.return()},throw(){L.onDone&&L.onDone(),x.throw()}}};let H=o(C=>{if(typeof S=="object"&&Array.isArray(C.attribute))for(let x=0;x<S.length;x++){let z=S[x],ne;if(z.name===C.attribute[0]){for(ne=z.sort||(z.sort={});ne.next;)ne=ne.next;ne.attribute=C.attribute.slice(1),ne.descending=C.descending}else z===C.attribute[0]&&(S[x]=ne={name:z,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&H(C.next)},"applySortingOnSelect");H(A)}else L.iterate=(E[Symbol.asyncIterator]||E[Symbol.iterator]).bind(E),L=L.map(function(D){try{let H=P.call(this,D);return typeof H?.catch=="function"?H.catch(C=>{throw C.partialObject={[t]:D.key},C}):H}catch(H){throw H.partialObject={[t]:D.key},H}});return L}static transformEntryForSelect(E,S,A,b,I,P){let L;I&&O&&!(typeof E=="string"?[E]:E)?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(L=!0);let D,H=o(function(C){let x;if(S?.transaction?.stale&&(S.transaction.stale=!1),C!=null){if(x=C.deref?C.deref():C.value,!x&&(C.key===void 0||C.deref)||C.metadataFlags&Fn){if(C.metadataFlags&Fn&&S.replicateFrom===!1&&P&&C.residencyId)return gc.SKIP;if(C=Ea(C.key??C,S,{transaction:A,lazy:E?.length<4,ensureLoaded:I},this?.isSync,z=>z),C?.then)return C.then(H.bind(this));x=C?.value}if(L&&C?.metadataFlags&(Fn|eu)||C?.expiresAt!=null&&C?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:C.key,message:"This entry has expired"};let z=Lc(C.key??C,C,S);if(z?.then)return z.then(H)}}if(x==null)return P?gc.SKIP:x;if(E&&!(E[0]==="*"&&E.length===1)){let z,ne=o((B,de)=>{let he;typeof B=="object"?he=B.name:he=B;let Se=ht?.[he],ee;if(Se){let j=b?.[he];if(j)if(j.hasMappings){let Te=Se.from?x[Se.from]:hf(C.key);ee=j.get(Te),ee||(ee=[])}else ee=j.fromRecord?.(x);else ee=Se(x,S,C,!0);let pe=o(Te=>{if(Se.directReturn)return de(Te,he);if(Te&&typeof Te=="object"){let fe=Se.definition?.tableClass||Ce;D||(D={});let We=D[he]||(D[he]=fe.transformEntryForSelect(he===B?null:B.select||(Array.isArray(B)?B:null),S,A,j,I));if(Array.isArray(Te)){let St=[],ft=fe.transformToOrderedSelect(Te,B.select,typeof B.sort=="object"&&B.sort,S,A,We)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ee=o(tt=>{for(;!tt.done;){if(tt?.then)return tt.then(Ee);St.push(tt.value),tt=ft.next()}de(St,he)},"nextValue"),pt=Ee(ft.next());pt&&(z||(z=[]),z.push(pt));return}else if(Te=We.call(this,Te),Te?.then){z||(z=[]),z.push(Te.then(St=>de(St,he)));return}}de(Te,he)},"handleResolvedValue");ee?.then?(z||(z=[]),z.push(ee.then(pe))):pe(ee);return}else ee=x[he],ee&&typeof ee=="object"&&he!==B&&(ee=Ce.transformEntryForSelect(B.select||B,S,A,null)({value:ee}));de(ee,he)},"selectAttribute"),re;if(typeof E=="string")ne(E,B=>{re=B});else if(Array.isArray(E))if(E.asArray)re=[],E.forEach((B,de)=>{B==="*"?E[de]=x:ne(B,he=>re[de]=he)});else{re={};let B=E.forceNulls;for(let de of E)if(de==="*")for(let he in x)re[he]=x[he];else ne(de,(he,Se)=>{he===void 0&&B&&(he=null),re[Se]=he})}else throw new ct.ClientError("Invalid select"+E);return z?Promise.all(z).then(()=>re):re}return x},"transform");return H}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=[],b=this,I=VN(Ce,this.getId()??null,function(L,D,H,C){try{let x=D.getValue?.(i,S),z=D.type;if(!x&&z==="patch"&&S){let re=i.getEntry(L);re?.version===D.version?x=re.value:x=D.getValue?.(i,!0,H),z="put"}let ne={id:L,localTime:H,value:x,version:D.version,type:z,beginTxn:C};A?A.push(ne):this.send(ne)}catch(x){ve.default.error?.(x)}},E.startTime||0,E),P=(async()=>{this.isCollection&&(I.includeDescendants=!0,E.onlyChildren&&(I.onlyChildren=!0)),E.supportsTransactions&&(I.supportsTransactions=!0);let L=this.getId(),D=E.previousCount;D>1e3&&(D=1e3);let H=E.startTime;if(this.isCollection){if(H){if(D)throw new ct.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:C,value:x}of l.getRange({start:H,exclusiveStart:!0,snapshot:!1})){let z=Nt(x);if(z.tableId!==n)continue;let ne=z.recordId;if(L==null||_Q(L,ne)){let re=z.getValue(i,S,C);if(I.send({id:ne,localTime:C,value:re,version:z.version,type:z.type}),I.queue?.length>pQ&&await I.waitForDrain()===!1)return}I.startTime=C}}else if(D){let C=[];for(let{key:x,value:z}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ne=Nt(z);if(ne.tableId!==n)continue;let re=ne.recordId;if(L==null||_Q(L,re)){let B=ne.getValue(i,S,x);if(C.push({id:re,localTime:x,value:B,version:ne.version,type:ne.type}),--D<=0)break}}catch(ne){ve.default.error("Error getting history entry",x,ne)}for(let x=C.length;x>0;)I.send(C[--x]);C[0]&&(I.startTime=C[0].localTime)}else if(!E.omitCurrent){for(let{key:C,value:x,version:z,localTime:ne}of i.getRange({start:L??!1,end:L==null?void 0:[L,su.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(I.send({id:C,localTime:ne,value:x,version:z,type:"put"}),I.queue?.length>pQ&&await I.waitForDrain()===!1))return}}else{D&&!H&&(H=0);let C=this.#n?.localTime;if(C===QL&&(i.cache?.delete(L),this.#n=i.getEntry(L),ve.default.trace?.("re-retrieved record",C,this.#n?.localTime),C=this.#n?.localTime),ve.default.trace?.("Subscription from",H,"from",L,C),H<C){let x=[],z=C;do{let ne=l.get(z);if(ne){E.omitCurrent=!0;let re=Nt(ne),B=re.getValue(i,S,z);S&&(re.type="put"),x.push({id:L,value:B,localTime:z,...re}),z=re.previousLocalTime}else break;D&&D--}while(z>H&&D!==0);for(let ne=x.length;ne>0;)I.send(x[--ne]);I.startTime=C}!E.omitCurrent&&this.doesExist()&&I.send({id:L,localTime:C,value:this.#e,version:this.#r,type:"put"})}for(let C of A)I.send(C);A=null})();return E.listener&&I.on("data",E.listener),I}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 b=!0,I=this.getContext();return E.checkPermission&&(b=this.allowCreate(I.user,E,I)),Vs(b,P=>{if(!P)throw new ct.AccessViolation(I.user);let L=Rr(E);this._writePublish(L,S,A)})}}_writePublish(E,S,A){let b=Lr(this.getContext());E??=null,E!==null&&Pr(E);let I=this.getContext();b.addWrite({key:E,store:i,entry:this.#n,nodeName:I?.nodeName,validate:o(()=>{I?.source||(b.checkOverloaded(),this.validate(S))},"validate"),before:Pe.publish?.bind(this,I,E,S),beforeIntermediate:Ra(S,De.publish?.bind(this,I,E,S)),commit:o((P,L,D)=>{L===void 0&&R&&!g&&Ta(),ve.default.trace?.(`Publishing message to id: ${E}, timestamp: ${new Date(P).toISOString()}`),y(E,L?.value??null,L,L?.version||P,0,!0,{user:I?.user,residencyId:A?.residencyId,expiresAt:I?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(E,S){let A,b=o((I,P,L)=>{if(P.type&&I!=null)if(S&&I.__op__&&(I=I.value),P.properties){typeof I!="object"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an object${P.type?" ("+P.type+")":""}`);let D=P.properties;for(let H=0,C=D.length;H<C;H++){let x=D[H];if(x.relationship||x.computed){E.hasOwnProperty(x.name)&&(A||(A=[])).push(`Computed property ${L}.${x.name} may not be directly assigned a value`);continue}let z=b(I[x.name],x,L+"."+x.name);z&&(I[x.name]=z)}if(P.sealed&&I!=null&&typeof I=="object")for(let H in I)D.find(C=>C.name===H)||(A||(A=[])).push(`Property ${H} is not allowed within object in property ${L}`)}else switch(P.type){case"Int":(typeof I!="number"||I>>0!==I)&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(D=>typeof D=="string")||(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a string`);break;case"Boolean":typeof I!="boolean"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a bigint`)}break;case"Bytes":if(!(I instanceof Uint8Array)){if(typeof I=="string")return Buffer.from(I);(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(I instanceof Rs)){if(typeof I=="string"&&(I=Buffer.from(I)),I instanceof Buffer)return createBlob(I,{type:"text/plain"});(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a Blob`)}break;case"array":if(Array.isArray(I)){if(P.elements)for(let D=0,H=I.length;D<H;D++){let C=I[D],x=b(C,P.elements,L+"[*]");x&&(I[D]=x)}}else(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an Array`);break}P.nullable===!1&&I==null&&(A||(A=[])).push(`Property ${L} is required (and not does not allow null values)`)},"validateValue");for(let I=0,P=T.length;I<P;I++){let L=T[I];if(L.relationship||L.computed){Object.hasOwn(E,L.name)&&(A||(A=[])).push(`Computed property ${L.name} may not be directly assigned a value`);continue}if(!S||L.name in E){let D=b(E[L.name],L,L.name);D!==void 0&&(E[L.name]=D)}}if(f)for(let I in E)T.find(P=>P.name===I)||(A||(A=[])).push(`Property ${I} is not allowed`);if(A)throw new ct.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return O?!!this.#i:void 0}static async addAttributes(E){let S=T.slice(0);for(let A of E){if(!A.name)throw new ct.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new ct.ClientError("Attribute names cannot include backticks or forward slashes");yTe(A.name),S.push(A)}return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.indexingOperation}static async removeAttributes(E){let S=T.filter(A=>!E.includes(A.name));return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.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=sD.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,b=performance.now(),I=Math.floor(S/2),P=E?.exactCount,L=0,D=0,H;for(let{value:C}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(C!=null&&L++,D++,await _c(),!P&&D<I&&performance.now()-b>A){H=D;break}if(H){let C=L;L=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:H,snapshot:!1}))ee!=null&&L++,await _c();let x=H*2,z=(L+C)/x,ne=Math.pow((L-C+1)/H/2,2)+z*(1-z)/x,re=Math.max(Math.sqrt(ne)*S,1),B=Math.round(z*S),de=Math.max(B-1.96*re,L+C),he=Math.min(B+1.96*re,S),Se=Math.pow(10,Math.round(Math.log10(re)));return Se>B&&(Se=Se/10),L=Math.round(B/Se)*Se,{recordCount:L,estimatedRange:[Math.round(de),Math.round(he)]}}return{recordCount:L}}static updatedAttributes(){ht=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&&(F=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)"),Cc=!0,S.to)E.elements?.definition?(ht[E.name]=E.resolve=(b,I,P,L)=>{let D=b[S.from?S.from:t],H=E.elements.definition.tableClass;return L?mf({attribute:S.to,value:D},Lr(I).getReadTxn(),!1,H,!1).map(C=>C&&C.key!==void 0?C:H.primaryStore.getEntry(C,{transaction:Lr(I).getReadTxn()})).asArray:H.search([{attribute:S.to,value:D}],I).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 b=E.definition||E.elements?.definition;b?(ht[E.name]=E.resolve=(I,P,L,D)=>{let H=I[S.from];if(H===void 0)return;if(E.elements){let x,z=H?.map(ne=>{let re=b.tableClass.primaryStore[D?"getEntry":"get"](ne,{transaction:Lr(P).getReadTxn()});return re?.then&&(x=!0),Ce.loadAsInstance===!1&&Object.freeze(D?re?.value:re),re});return S.filterMissing?x?Promise.all(z).then(ne=>ne.filter(gQ)):z.filter(gQ):x?Promise.all(z):z}let C=b.tableClass.primaryStore[D?"getEntry":"get"](H,{transaction:Lr(P).getReadTxn()});return Ce.loadAsInstance===!1&&Object.freeze(D?C?.value:C),C},E.set=(I,P)=>{if(Array.isArray(P)){let L=P.map(D=>D.getId?.()||D[b.tableClass.primaryKey]);I[S.from]=L}else{let L=P.getId?.()||P[b.tableClass.primaryKey];I[S.from]=L}},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),ht[E.name]=E.resolve=(b,I,P)=>{let L=typeof A.from=="string"?b[A.from]:b,D=this.userResolvers[E.name];if(D)return D(L,I,P);ve.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 b=r[E.name].customIndex;ht[E.name]=(I,P,L)=>{let D=I[E.name];return b.propertyResolver(D,P,L)},ht[E.name].directReturn=!0}}Wm(this,this),Wm(xf,this,!0);for(let E of T){let S=E.name;E.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return E.resolve(this,Ef.getStore())},set(A){return E.set(this,A)},configurable:!0})}}static setComputedAttribute(E,S){let A=io(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:b,value:I}of l.getRange({start:0,end:E}))await _c(),Nt(I).tableId===n&&(A=FR(l,b,I));if(S)for(let b of i.getRange({start:0,versions:!0})){let{key:I,value:P,localTime:L}=b;await _c(),P===null&&L<E&&(A=Zl(i,b))}await A}static async*getHistory(E=0,S=1/0){for(let{key:A,value:b}of l.getRange({start:E||1,end:S})){await _c();let I=Nt(b);I.tableId===n&&(yield{id:I.recordId,localTime:A,version:I.version,type:I.type,value:I.getValue(i,!0,A),user:I.user,operation:I.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 b=A.localTime;if(!b)throw new Error("The entry does not have a local audit time");let I=0;do{await _c();let P=l.get(b);if(P){let L=Nt(P);S.push({id:L.recordId,localTime:b,version:L.version,type:L.type,value:L.getValue(i,!0,b),user:L.user}),b=L.previousLocalTime}else break}while(I<1e3&&b);return S.reverse()}static cleanup(){$?.remove()}}let wE=hR(async(V,E,S)=>{for(let A of Ce.sources)if(A.get&&(!A.get.reliesOnPrototype||A.prototype.get)){if(A.available?.(S)===!1)continue;E.source=A;let b=await A.get(V,E);if(b)return b}},()=>{throw new ct.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});Ce.updatedAttributes();let Bf=Ce.prototype;return p&&Ce.setTTLExpiration(p/1e3),K&&Eu(),Ce;function po(V,E,S){let A;for(let b in r){let I=r[b],P=I.isIndexing,L=ht[b],D=S&&(L?L(S):S[b]),H=E&&(L?L(E):E[b]);if(D===H&&!P)continue;if(I.customIndex){I.customIndex.index(V,D,H);continue}A=!0;let C=I.indexNulls,x=(0,Jp.getIndexedValues)(D,C),z=(0,Jp.getIndexedValues)(H,C);if(s==="OrganizationRole"&&ve.default.error?.({tableName:s,id:V,key:b,valuesToAdd:x,valuesToRemove:z}),z?.length>0){let ne=new Set(z);if(x=x?x.filter(re=>{if(ne.has(re))ne.delete(re);else return!0}):[],z=Array.from(ne),(z.length>0||x.length>0)&&fQ){let re=z.concat(x).map(B=>({key:B,value:V}));I.prefetch(re,EQ)}for(let re=0,B=z.length;re<B;re++)I.remove(z[re],V)}else x?.length>0&&fQ&&I.prefetch(x.map(ne=>({key:ne,value:V})),EQ);if(x)for(let ne=0,re=x.length;ne<re;ne++)I.put(x[ne],V)}return A}o(po,"updateIndices");function Pr(V){switch(typeof V){case"number":return!0;case"string":if(V.length<659)return!0;if(V.length>hQ)throw new Error("Primary key size is too large: "+V.length);break;case"object":if(V===null)throw new Error("Invalid primary key of null");break;case"bigint":if(V<2n**64n&&V>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof V)}if((0,su.writeKey)(V,OTe,0)>hQ)throw new Error("Primary key size is too large: "+V.length);return!0}o(Pr,"checkValidId");function Rr(V){return typeof V=="object"&&V?V.id:V}o(Rr,"requestTargetToId");function Ff(V){return typeof V=="object"&&V&&V.isCollection}o(Ff,"isSearchTarget");function Ss(V){}o(Ss,"isRequestTarget");function Ea(V,E,S,A,b){if(Ce.getResidencyById&&S.ensureLoaded&&E?.replicateFrom!==!1){let P=Dc(Ce.getResidencyById(V));if(P&&!P.includes(server.hostname)&&N)return N({key:V,residency:P}).then(b)}let I=o(()=>{if(E?.transaction?.stale&&(E.transaction.stale=!1),S.transaction?.isDone)return b(null,V);let P=i.getEntry(V,S);return E?._freezeRecords&&Object.freeze(P?.value),P?.residencyId&&P.metadataFlags&Fn&&N&&S.ensureLoaded&&E?.replicateFrom!==!1?N(P).then(L=>b(L,V),L=>(ve.default.error?.("Error loading remote record",V,P,S,L),b(null,V))):(P&&E&&(P?.version>(E.lastModified||0)&&(E.lastModified=P.version),P?.localTime&&!E.lastRefreshed&&(E.lastRefreshed=P.localTime)),b(P,V))},"whenPrefetched");return A?I():se>0?(se--,I()):new Promise((P,L)=>{se===0?(se--,i.prefetch([V],()=>{D(),H()})):(le.push(V),ue.push(H),le.length>xy&&(se--,D()));function D(){if(le.length>0){let C=ue;i.prefetch(le,()=>{se===-1?D():se++;for(let x of C)x()}),le=[],ue=[],me>2&&me--}else se=me,me<NE&&me++}o(D,"prefetch");function H(){try{P(I())}catch(C){L(C)}}o(H,"load")})}o(Ea,"loadLocalRecord");function _a(V,E){let S=E?.checkPermission;if(typeof S!="object"){if(!V?.role)return;S=V.role.permission}if(S.super_user)return CTe;let A=S[c],b,I=A?.tables;if(I)return I[s];if(c==="data"&&(b=S[s])&&!b.tables)return b}o(_a,"getTablePermissions");function Lc(V,E,S,A){if(O){let b=!1;if(S.noCache?b=!0:(E?(!E.value||E.metadataFlags&(Fn|eu)||E.expiresAt!=null&&E.expiresAt<Date.now())&&(b=!0):b=!0,Yr(!b,"cache-hit",s)),b){let I=OE(V,E,S).then(P=>(P?.value&&P?.value.getRecord?.()&&ve.default.error?.("Can not assign a record that is already a resource"),S&&(P?.version>(S.lastModified||0)&&(S.lastModified=P.version),S.lastRefreshed=Date.now()),P));if(S?.onlyIfCached||E?.value&&A?.allowStaleWhileRevalidate?.(E,V)){if(I.catch(P=>ve.default.warn?.(P)),S?.onlyIfCached&&!A.doesExist())throw new ct.ServerError("Entry is not cached",504);return}else return I}}else if(E?.value&&E.expiresAt!=null&&E.expiresAt<Date.now())return Ce.evict(E.key,E.value,E.version),E.value=null,{then(b){return b(E)}}}o(Lc,"ensureLoadedFromSource");function Lr(V){let E=V?.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 _o,E.lmdbDb=i,E;E=S}while(!0)}else return new VE}o(Lr,"txnForContext");function hu(V,E,S){if(!V)return;let A=(V.deref?V.deref():V.value)??i.getEntry(V.key)?.value;if(typeof E=="object"){let I=ht,P=A;for(let L=0,D=E.length;L<D;L++){let H=E[L],C=I?.[H];P=C&&P?C(P,S,V):P?.[H],V=null,I=C?.definition?.tableClass?.propertyResolvers}return P}let b=ht[E];return b?b(A,S,V):A[E]}o(hu,"getAttributeValue");function pu(V,E,S,A,b){let I=b?.length,P={transaction:A,lazy:I>0||typeof E=="string"||E?.length<4,alwaysPrefetch:!0},L;function D(H,C){let x=H?.value;if(!x)return gc.SKIP;for(let z=0;z<I;z++)if(!L?.includes(z)&&!b[z](x,H))return gc.SKIP;return C!==void 0&&(H.key=C),H}if(o(D,"processEntry"),I>0||!V.hasEntries){let H=V.map(C=>{if(L=null,typeof C=="object"&&C?.key!==void 0)return I>0?D(C):C;if(C==null)return gc.SKIP;for(let x=0;x<I;x++){let ne=b[x].idFilter;if(ne){if(!ne(C))return gc.SKIP;L||(L=[]),L.push(x)}}return Ea(C,S,P,!1,D)});return Array.isArray(V)&&(H=H.filter(C=>C!==gc.SKIP)),H.hasEntries=!0,H}return V}o(pu,"transformToEntries");function ga(V,E,S=server.replication?.getThisNodeId(l)){if(V<=E?.version){if(E?.version===V&&S!==void 0){let A=server.replication?.exportIdMapping(l),b=E.localTime,I=b&&l.get(b);if(I){let P,L,D=Nt(I);for(let H in A)A[H]===S&&(P=H),A[H]===D.nodeId&&(L=H);if(P>L)return 1;if(P===L)return 0}}return-1}return 1}o(ga,"precedesExistingVersion");async function OE(V,E,S){let A=E?.metadataFlags,b=E?.version,I,P;if(!i.attemptLock(V,b,()=>{clearTimeout(P);let C=i.getEntry(V);!C||!C.value||C.metadataFlags&(Fn|eu)?I(OE(V,i.getEntry(V),S)):I(C)}))return new Promise(C=>{I=C,P=setTimeout(()=>{i.unlock(V,b)},NTe)});let L=E?.value,D={requestContext:S,replacingRecord:L,replacingEntry:E,replacingVersion:b,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},H=S?.responseHeaders;return new Promise((C,x)=>{let z;Vs(Ft(D,async ne=>{let re=performance.now(),B,de,he;try{B=await wE(V,D,E),he=A&Fn;let ee=D.lastModified||he&&b;ee||(ee=(0,Jp.getNextMonotonicTime)()),de=he||ee>b||!L;let j=performance.now()-re;if(it(j,"cache-resolution",s,null,"success"),H&&eh(H,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),ne.timestamp=ee,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=L,ee=b;else throw new ct.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==V&&(B[t]=V)}z=!0,C({key:V,version:ee,value:B})}catch(ee){ee.message+=` while resolving record ${V} for ${s}`,L&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(C({key:V,version:b,value:L}),ve.default.trace?.(ee.message,"(returned stale record)")):x(ee);let j=performance.now()-re;it(j,"cache-resolution",s,null,"fail"),H&&eh(H,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),D.transaction.abort();return}if(S?.noCacheStore||D.noCacheStore){D.transaction.abort();return}Lr(D).addWrite({key:V,store:i,entry:E,nodeName:"source",before:Ra(B),commit:o((ee,j)=>{if(j?.version!==b)return;let pe=po(V,L,B);if(B){De.put?.(D,V,B),j&&(S.previousResidency=Ce.getResidencyRecord(j.residencyId));let Te,fe=!1,We,St=Dc(Ce.getResidency(B,S));if(St){if(!St.includes(server.hostname))if(Te=B,fe=!0,Ce.getResidencyById)B=void 0;else{B=null;for(let ft in r)B||(B={}),B[ft]=Te[ft]}We=Mc(St)}ve.default.trace?.(`Writing resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),y(V,B,j,ee,fe?Fn:0,g&&(de||fe)||null,{user:D?.user,expiresAt:D.expiresAt,residencyId:We},"put",!!he,Te)}else j&&(De.delete?.(D,V),ve.default.trace?.(`Deleting resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),g||R?y(V,null,j,ee,0,g&&de||null,{user:D?.user},"delete",!!he):Zl(i,j,b))},"commit")})}),()=>{i.unlock(V,b)},ne=>{i.unlock(V,b),z&&ve.default.error?.("Error committing cache update",ne)})})}o(OE,"getFromSource");function Sa(V){if(!V||V.user?.role?.permission?.super_user)return!0;if(V.replicateTo)throw new ct.ClientError("Can not specify replication parameters without super user permissions",403);if(V.replicatedConfirmation)throw new ct.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Sa,"checkContextPermissions");function Ta(V){let E=!1;if(V&&(V-Ye>1&&(E=!0),Ye=V),!(dt===qn&&!E)&&(qn=dt,(0,ru.getWorkerIndex)()===(0,ru.getWorkerCount)()-1))return rt&&clearTimeout(rt),dt?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let b=dt/(1+Ye),I=E?Date.now():Math.ceil((Date.now()-A.getTime())/b)*b+A.getTime(),P=o(L=>{ve.default.trace?.(`Scheduled next cleanup scan at ${new Date(L)}`),rt=setTimeout(()=>Z=Z.then(async()=>{if(P(Math.max(L+dt,Date.now())),i.rootStore.status!=="open"){clearTimeout(rt);return}let D=50,H=new Array(D),C=0,x=Math.pow(Ye,8)*(nu.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),z=_/Math.pow(Math.max(Ye,1),4);ve.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${z}ms`);function ne(re,B,de,he){let Se=re+z-Date.now();if(Se<0)return!0;if(Ye){let ee=i.lastSize;return de&$r&&Hc(he,j=>{j.size&&(ee+=j.size)}),ve.default.trace?.(`shouldEvict adjusted ${Se} ${ee}, ${Se*(re-B)/ee} < ${x}`),Se*(re-B)/ee<x}return!1}o(ne,"shouldEvict");try{let re=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:de,value:he,version:Se,expiresAt:ee,metadataFlags:j}=B,pe;he===null&&!g&&Se+ITe<Date.now()?pe=Zl(i,B,Se):ee!=null&&ne(ee,Se,j,he)&&(pe=Ce.evict(de,he,Se),re++),pe&&(await H[C],H[C]=pe.catch(Te=>{ve.default.error?.("Cleanup error",Te)}),++C>=D&&(C=0)),await _c()}ve.default.info?.(`Finished cleanup scan for ${s}, evicted ${re} entries`)}catch(re){ve.default.warn?.(`Error in cleanup scan for ${s}:`,re)}S(void 0),Ye=0}),Math.min(L-Date.now(),2147483647)).unref()},"startNextTimer");P(I)}):void 0}o(Ta,"scheduleCleanup");function Hf(){$=l?.addDeleteRemovalCallback(n,i,(V,E)=>{i.remove(V,E)})}o(Hf,"addDeleteRemoval");function Eu(){(0,ru.getWorkerIndex)()===0&&setInterval(async()=>{if(!Pc){Pc=!0;try{let V=K.name,E=r[V];if(!E)throw new Error(`expiresAt attribute ${K} 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 b=i.getEntry(A);b?.value?b.value[V]<Date.now()&&Ce.evict(A,b.value,b.version):i.ifVersion(A,b?.version,()=>E.remove(S,A))}await _c()}}catch(V){ve.default.error?.("Error in evicting old records",V)}finally{Pc=!1}}},bTe).unref()}o(Eu,"runRecordExpirationEviction");function Dc(V){if(V!=null){if(Array.isArray(V))return V;if(typeof V=="number"){if(V>=65536)throw new Error(`Shard id ${V} must be below 65536`);let E=server.shards?.get?.(V);if(E)return ve.default.trace?.(`Shard ${V} mapped to ${E.map(S=>S.name).join(", ")}`),E.map(S=>S.name);throw new Error(`Shard ${V} is not defined`)}throw new Error(`Shard or residency list ${V} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(Dc,"residencyFromFunction");function Mc(V){if(V){let E=V.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],V),S)}}o(Mc,"getResidencyId");function Ra(V,E){let S=yA(V,i.rootStore);if(S){let A=E;return A?async()=>{await A(),await S()}:()=>S()}return E}o(Ra,"preCommitBlobsForRecordBefore")}function nD(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 EQ(){}function jR(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 zR(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return zR(+e);case"Float":return e==="null"?null:zR(+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;PTe.test(e)||(e+="Z");let n=new Date(e);return zR(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,QR.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function zR(e){if(isNaN(e))throw new SyntaxError;return e}function _Q(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 Vs(e,t,r){return e?.then?e.then(t,r):t(e)}function gQ(e){return e!=null}function Ks(e){try{return JSON.stringify(e)}catch{return e}}function LTe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var gc,Jp,SQ,TQ,nu,ct,Xp,Zp,ve,su,ru,QR,sD,RTe,yTe,ATe,bTe,ITe,fQ,NTe,mQ,wTe,Fn,eu,OTe,hQ,pQ,CTe,BFe,PTe,_c,bT=ce(()=>{k();gc=require("lmdb"),Jp=w(yn()),SQ=w(require("lodash")),TQ=w(Zf());xa();tm();nu=w(oe());KN();ct=w(ge()),Xp=w(Co()),Zp=w(ai());Me();mg();ve=w(ei());LI();Bc();su=require("ordered-binary"),ru=w(nt());Mi();QR=w(ie());Vc();Yi();V_();th();sD=w(require("node:fs"));Kn();vR();cL();({sortBy:RTe}=SQ.default),{validateAttribute:yTe}=TQ.default,ATe=new Uint8Array(9);ATe[8]=192;bTe=6e4,ITe=864e5;nu.initSync();fQ=nu.get(U.STORAGE_PREFETCHWRITES),NTe=1e4,mQ=1,wTe=2,Fn=1,eu=8,OTe=Buffer.allocUnsafeSlow(8192),hQ=1978,pQ=100,CTe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},BFe=(0,QR.convertToMS)(nu.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(JR,"makeTable");o(nD,"attributesAsObject");o(EQ,"noop");PTe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(jR,"coerceType");o(zR,"rejectNaN");o(_Q,"isDescendantId");_c=o(()=>new Promise(setImmediate),"rest");o(Vs,"when");o(gQ,"exists");o(Ks,"stringify");o(LTe,"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 ZR(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 RQ=ce(()=>{o(XR,"euclideanDistance");o(ZR,"cosineDistance")});var yQ,AQ,Sf,oo,gf,DTe,MTe,ey,bQ=ce(()=>{RQ();yQ=require("msgpackr"),AQ=w(ei()),Sf=w(ge()),oo=(0,AQ.loggerWithTag)("HNSW"),gf=Symbol.for("entryPoint"),DTe=Symbol.for("key"),MTe=10,ey=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=yQ.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?XR:ZR,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"?[DTe,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(gf);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 R=0;R<=_;R++)g[R]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);oo.debug?.("setting entry point to",i),this.indexStore.put(gf,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),MTe),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);oo.debug?.("setting entry point to",i),this.indexStore.put(gf,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&&oo.info?.("should not have zero connections for",l);let R=p[_];for(let T=0;T<g.length;T++){let{id:y,distance:N,node:O}=g[T];if(y===i)continue;let F=[];if(this.optimizeRouting){let Y=!1,K=O[_],$=1+this.optimizeRouting*(1+.5*T/this.M);for(let le=0;le<K.length;le++){let{id:ue,distance:se}=K[le],me=1+this.optimizeRouting*(1+.5*le/this.M);for(let Pe=0;Pe<R.length;Pe++){let{id:De,distance:dt}=R[Pe];if(De===ue){N*$>dt+se?Y=!0:se*me>N+dt&&(F.push({fromId:De,toId:y}),F.push({fromId:y,toId:De}));break}}if(Y)break}if(Y)continue}else if(T>=(_>0?this.M:this.M<<1))continue;R.push({id:y,distance:N});for(let{fromId:Y,toId:K}of F){let $=d(Y);$||($=d(Y,this.indexStore.get(Y)));for(let le=0;le<$[_].length;le++)if($[_][le].id===K){Object.isFrozen($[_])&&($[_]=$[_].slice()),$[_].splice(le,1);break}}let Z=c[_],G=Z?.find(({id:Y})=>Y===y);if(G){let Y=Z?.indexOf(G);Z.copied||(Z=[...Z],Z.copied=!0,c[_]=Z),Z.splice(Y,1)}else this.addConnection(y,d(y,O),i,_,N,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(gf);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);oo.debug?.("setting entry point to",l),this.indexStore.put(gf,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&&(oo.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(gf);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 Sf.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Sf.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=ZR;else if(s==="euclidean")c=XR;else{if(s)throw new Sf.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Sf.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Sf.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){oo.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||oo.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)){oo.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&&oo.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?oo.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:ZR);let c=a(s.target,t);return i.set(n,c),c}return t}}});var iD,IQ=ce(()=>{bQ();iD={HNSW:ey}});var Et={};we(Et,{database:()=>Vu,databaseEnvs:()=>na,databases:()=>He,dropDatabase:()=>xI,dropTableMeta:()=>FTe,getDatabases:()=>st,getDefaultCompression:()=>$S,getTables:()=>vTe,onRemovedDB:()=>bh,onUpdatedTable:()=>Nl,readMetaDb:()=>eE,resetDatabases:()=>Fd,table:()=>ze,tables:()=>ln});function vTe(){return sy||st(),ln||{}}function st(){if(sy)return He;sy=!0,yf=new Map;let e=(0,Xt.getHdbBasePath)()&&(0,Gt.join)((0,Xt.getHdbBasePath)(),Uc),t=(0,Xt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Xt.get)(U.STORAGE_PATH)||e&&((0,fs.existsSync)(e)?e:(0,Gt.join)((0,Xt.getHdbBasePath)(),ME)),!e)return;if((0,fs.existsSync)(e))for(let n of(0,fs.readdirSync)(e,{withFileTypes:!0})){let s=(0,Gt.basename)(n.name,".mdb");n.isFile()&&(0,Gt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&eE((0,Gt.join)(e,n.name),null,s)}if((0,fs.existsSync)((0,Rf.getBaseSchemaPath)())){for(let n of(0,fs.readdirSync)((0,Rf.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Gt.join)((0,Rf.getBaseSchemaPath)(),n.name),i=(0,Gt.join)((0,Rf.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,fs.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,Gt.extname)(a.name).toLowerCase()===".mdb"){let c=(0,Gt.join)(i,a.name);eE((0,Gt.join)(s,a.name),(0,Gt.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,fs.existsSync)(i))for(let c of(0,fs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Gt.extname)(c.name).toLowerCase()===".mdb"&&eE((0,Gt.join)(i,c.name),(0,Gt.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,Gt.join)(l.path,(0,Gt.basename)(c+".mdb"));(0,fs.existsSync)(u)&&eE(u,c,n,null,!0)}}for(let n in He){let s=yf.get(n);if(s){let i=He[n];n.includes("delete")&&Or.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Or.trace(`delete table class ${a}`),delete i[a])}else if(delete He[n],n==="data"){for(let i in ln)delete ln[i];delete ln[iy]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,Xt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(He.system?.hdb_analytics?.enableAuditing(),He.system?.hdb_analytics_hostname?.enableAuditing()),He.system)for(let n of r)He.system[n]&&(He.system[n].replicate=!1);return yf=null,He}function Fd(){sy=!1;for(let[,e]of na)e.needsDeletion=!0;st();for(let[e,t]of na)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),na.delete(e);let r=He[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete He[t.databaseName],rE.forEach(i=>i(t.databaseName));break}}return He}function eE(e,t,r=cD,n,s){let i=new oD.default(e,!1);try{let a=na.get(e);a?a.needsDeletion=!1:(a=(0,Af.open)(i),na.set(e,a));let c=new bf.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(ty.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,fs.existsSync)(n)&&(i.path=n,u=(0,Af.open)(i),u.isLegacy=!0):u=BR(a));let d=PQ(r),f=d[iy],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 R=m.get(_);R||m.set(_,R={attributes:[]}),(g==null||p.is_hash_attribute)&&(R.primary=p),g!=null&&R.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){Or.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(_)}`);continue}}let R=d[h],T={},y=[],N,O,F=typeof g.audit=="boolean"?g.audit:(0,Xt.get)(U.LOGGING_AUDITLOG),Z=g.trackDeletes,G=g.expiration,Y=g.eviction,K=g.sealed,$=g.splitSegments,le=g.replicate;if(R)T=R.indices,y=R.attributes,R.schemaVersion++;else{N=g.tableId,N?N>=(l.get(Tf)||0)&&(l.putSync(Tf,N+1),Or.info(`Updating next table id (it was out of sync) to ${N+1} for ${h}`)):(g.tableId=N=l.get(Tf),N||(N=1),Or.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Tf,N+1),l.putSync(g.key,g));let se=new bf.default(!g.is_hash_attribute,g.is_hash_attribute);if(se.compression=g.compression,se.compression){let me=(0,Xt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||CQ;se.compression.threshold=me}O=VR(a.openDB(g.key,se),a),a.databaseName=r,O.tableId=N}let ue;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 Pe=DQ(se.key,a,se);T[se.name]=Pe,T[se.name].indexNulls=se.indexNulls}let me=y.find(Pe=>Pe.name===se.name);me?y.splice(y.indexOf(me),1,se):y.push(se),ue=!0}}catch(me){Or.error("Error trying to update attribute",se,y,T,me)}}for(let se of y)if(!_.find(Pe=>Pe.name===se.name)){if(se.is_hash_attribute){Or.error("Unable to remove existing primary key attribute",se);continue}se.indexed&&(y.splice(y.indexOf(se),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=LQ(d,h,JR({primaryStore:O,auditStore:u,audit:F,sealed:K,splitSegments:$,replicate:le,expirationMS:G&&G*1e3,evictionMS:Y&&Y*1e3,trackDeletes:Z,tableName:h,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:_,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let se of tE)se(R)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function PQ(e){let t=He[e];if(t||(e==="data"?t=He[e]=ln:e==="system"?Object.defineProperty(He,"system",{value:t=Object.create(null),configurable:!0}):t=He[e]=Object.create(null)),yf&&!yf.has(e)){let r=new Set;t[iy]=r,yf.set(e,r)}return t}function LQ(e,t,r){return e[t]=r,r}function Vu({database:e,table:t}){e||(e=cD),st();let r=PQ(e),n=(0,Gt.join)((0,Xt.getHdbBasePath)(),Uc),s=(0,Xt.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,Xt.get)(U.STORAGE_PATH)||((0,fs.existsSync)(n)?n:(0,Gt.join)((0,Xt.getHdbBasePath)(),ME));let a=(0,Gt.join)(n,(i?t:e)+".mdb"),c=na.get(a);if(!c||c.status==="closed"){let l=new oD.default(a,!1);c=(0,Af.open)(l),na.set(a,c)}return c.auditStore||(c.auditStore=BR(c)),c}async function xI(e){if(!He[e])throw new Error("Schema does not exist");let t=He[e],r;for(let n in t)r=t[n].primaryStore.rootStore,na.delete(r.path),r.status==="open"&&(await r.close(),await nE.remove(r.path));if(r||(r=Vu({database:e,table:null}),r.status==="open"&&(await r.close(),await nE.remove(r.path))),e==="data"){for(let n in ln)delete ln[n];delete ln[iy]}delete He[e],rE.forEach(n=>n(e)),await RA(r)}function DQ(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&iD[r.indexed.type]?.useObjectStore,s=new bf.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=iD[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Or.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=cD);let p=Vu({database:r,table:t}),_=He[r];Or.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 R,T,y;m==null&&(m=!0);let N=new bf.default(!1);for(let $ of a)$.attribute&&!$.name?($.name=$.attribute,$.indexed=!0):$.attribute=$.name,$.expiresAt&&($.indexed=!0);let O,F;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...a)}else{let $=p.auditStore;T=a.find(me=>me.isPrimaryKey)||{},R=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=$S(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,Xt.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]),Or.trace(`${t} table loading, opening primary store`);let le=new bf.default(!1,!0);le.compression=T.compression;let ue=t+"/";if(y=p.dbisDb=p.openDB(ty.INTERNAL_DBIS_NAME,N),K(),y.get(ue))return F&&F(),Fd(),ze(e);let se=VR(p.openDB(ue,le),p);p.databaseName=r,se.tableId=y.get(Tf),Or.trace(`Assigning new table id ${se.tableId} for ${t}`),se.tableId||(se.tableId=1),y.put(Tf,se.tableId+1),T.tableId=se.tableId,g=LQ(_,t,JR({primaryStore:se,auditStore:$,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:se.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:y})),g.schemaVersion=1,O=!0,y.put(ue,T)}let Z=g.indices;y=y||(p.dbisDb=p.openDB(ty.INTERNAL_DBIS_NAME,N)),g.dbisDB=y;let G=[];for(let{key:$,value:le}of y.getRange({start:!0})){let[ue,se]=$.toString().split("/");if(se===""&&(se=le.name),se){if(ue!==t)continue}else continue;let me=a.find(De=>De.name===se),Pe=!me?.indexed&&le.indexed&&!le.isPrimaryKey;if((!me||Pe)&&(K(),O=!0,me||y.remove($),Pe)){let De=g.indices[ue];De&&G.push(De)}}let Y=[];try{for(let $ of a||[]){if(($.relationship||$.computed)&&(O=!0,$.relationship))continue;let le=t+"/"+($.name||"");Object.defineProperty($,"key",{value:le,configurable:!0});let ue=y.get(le);if($.isPrimaryKey){if(ue=ue||y.get(le=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||$.type!==ue.type){let me={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),me.audit=c),n&&(me.expiration=+n),s&&(me.eviction=+s),l!==void 0&&(me.sealed=l),d!==void 0&&(me.replicate=d),$.type&&(me.type=$.type),O=!0,K(),y.put(le,me)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let se=!ue||ue.type!==$.type||JSON.stringify(ue.indexed)!==JSON.stringify($.indexed)||ue.nullable!==$.nullable||ue.version!==$.version||JSON.stringify(ue.properties)!==JSON.stringify($.properties)||JSON.stringify(ue.elements)!==JSON.stringify($.elements);if($.indexed){let me=DQ(le,p,$);(se||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<sE.workerData?.restartNumber)&&(O=!0,K(),ue=y.get(le),(se||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<sE.workerData?.restartNumber)&&(O=!0,$.indexNulls===void 0&&($.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&($.lastIndexedKey=ue?.lastIndexedKey??void 0,$.indexingPID=process.pid,me.isIndexing=!0,Object.defineProperty($,"dbi",{value:me}),Y.push($))),y.put(le,$)),ue?.indexNulls&&$.indexNulls===void 0&&($.indexNulls=!0),me.indexNulls=$.indexNulls,Z[$.name]=me}else se&&(O=!0,K(),y.put(le,$))}}finally{F&&F()}if(O&&(g.schemaVersion++,g.updatedAttributes()),Or.trace(`${t} table loading, running index`),Y.length>0||G.length>0?g.indexingOperation=BTe(g,Y,G):O&&ry.signalSchemaChange(new ny.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,O)for(let $ of tE)$(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Or.trace(`${t} table loaded`),g;function K(){F||p.transactionSync(()=>({then($){F=$}}))}o(K,"startTxn")}async function BTe(e,t,r){try{Or.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await ry.signalSchemaChange(new ny.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,Af.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,R=_.dbi;try{let T=_.resolve,y=m&&(T?T(m):m[g]);if(R.customIndex){R.customIndex.index(f,y);continue}let N=(0,NQ.getIndexedValues)(y);if(N)for(let O=0,F=N.length;O<F;O++)R.put(N[O],f)}catch(T){a[g]||(a[g]=!0,Or.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Or.error(p)}),sE.workerData&&sE.workerData.restartNumber!==OQ.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>UTe?await s:d>xTe&&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 ry.signalSchemaChange(new ny.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Or.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Or.error("Error in indexing",n)}}function FTe({table:e,database:t}){let r=Vu({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 Nl(e){return tE.push(e),{remove(){let t=tE.indexOf(e);t>-1&&tE.splice(t,1)}}}function bh(e){return rE.push(e),{remove(){let t=rE.indexOf(e);t>-1&&rE.splice(t,1)}}}function $S(){let e=(0,Xt.get)(U.STORAGE_COMPRESSION),t=(0,Xt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Xt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||CQ,n={startingOffset:32};return t&&(n.dictionary=nE.readFileSync(t)),r&&(n.threshold=r),e&&n}var Xt,ty,Af,Gt,fs,Rf,bf,oD,nE,aD,NQ,ry,ny,sE,wQ,OQ,Or,cD,iy,CQ,ln,He,Tf,tE,rE,sy,na,yf,UTe,xTe,Me=ce(()=>{Xt=w(oe()),ty=w(Vt()),Af=require("lmdb"),Gt=require("path"),fs=require("fs"),Rf=w(It());bT();bf=w(mm()),oD=w(hm());k();nE=w(require("fs-extra")),aD=w(Zs()),NQ=w(yn()),ry=w(Co()),ny=w(ai()),sE=require("worker_threads"),wQ=w(Q()),OQ=w(nt());Mi();Vc();Kn();IQ();Or=(0,wQ.forComponent)("storage"),cD="data",iy=Symbol("defined-tables"),CQ=((0,Xt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Xt.initSync)();ln=Object.create(null),He=Object.create(null);(0,aD._assignPackageExport)("databases",He);(0,aD._assignPackageExport)("tables",ln);Tf=Symbol.for("next-table-id"),tE=[],rE=[],na=new Map;o(vTe,"getTables");o(st,"getDatabases");o(Fd,"resetDatabases");o(eE,"readMetaDb");o(PQ,"ensureDB");o(LQ,"setTable");o(Vu,"database");o(xI,"dropDatabase");o(DQ,"openIndex");o(ze,"table");UTe=1e3,xTe=10;o(BTe,"runIndexing");o(FTe,"dropTableMeta");o(Nl,"onUpdatedTable");o(bh,"onRemovedDB");o($S,"getDefaultCompression")});var ie=M(be=>{"use strict";var Sc=require("path"),BQ=require("fs-extra"),kn=Q(),MQ=require("fs-extra"),oy=require("os"),HTe=require("net"),kTe=require("recursive-iterator"),Cr=(k(),v(W)),{PACKAGE_ROOT:GTe}=bt(),qTe=eA(),vQ=require("papaparse"),ay=require("moment"),{inspect:$Te}=require("util"),UQ=require("is-number"),VTe=require("minimist"),KTe=require("https"),YTe=require("http"),WTe=/^((\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)))$/,FQ=require("util").promisify(setTimeout),zTe=100,jTe=5,QTe="",JTe=4,xQ={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};be.isEmpty=ms;be.isEmptyOrZeroLength=ao;be.arrayHasEmptyValues=eRe;be.arrayHasEmptyOrZeroLengthValues=tRe;be.buildFolderPath=rRe;be.isBoolean=HQ;be.errorizeMessage=XTe;be.stripFileExtension=sRe;be.autoCast=iRe;be.autoCastJSON=kQ;be.autoCastJSONDeep=uD;be.removeDir=oRe;be.compareVersions=aRe;be.isCompatibleDataVersion=cRe;be.escapeRawValue=lRe;be.unescapeValue=uRe;be.stringifyProps=dRe;be.timeoutPromise=mRe;be.isClusterOperation=pRe;be.getClusterUser=_Re;be.checkGlobalSchemaTable=ERe;be.getHomeDir=qQ;be.getPropsFilePath=fRe;be.promisifyPapaParse=gRe;be.removeBOM=$Q;be.createEventPromise=SRe;be.checkProcessRunning=TRe;be.checkSchemaTableExist=RRe;be.checkSchemaExists=VQ;be.checkTableExists=KQ;be.getStartOfTomorrowInSeconds=yRe;be.getLimitKey=ARe;be.isObject=nRe;be.isNotEmptyAndHasValue=ZTe;be.autoCasterIsNumberCheck=GQ;be.backtickASTSchemaItems=bRe;be.isPortTaken=hRe;be.createForkArgs=IRe;be.autoCastBoolean=NRe;be.asyncSetTimeout=FQ;be.getTableHashAttribute=wRe;be.doesSchemaExist=ORe;be.doesTableExist=CRe;be.stringifyObj=PRe;be.ms_to_time=LRe;be.changeExtension=DRe;be.getEnvCliRootPath=dD;be.noBootFile=MRe;be.httpRequest=vRe;be.transformReq=URe;be.convertToMS=xRe;be.PACKAGE_ROOT=GTe;function XTe(e){return e instanceof Error?e:new Error(e)}o(XTe,"errorizeMessage");function ms(e){return e==null}o(ms,"isEmpty");function ZTe(e){return!ms(e)&&(e||e===0||e===""||HQ(e))}o(ZTe,"isNotEmptyAndHasValue");function ao(e){return ms(e)||e.length===0||e.size===0}o(ao,"isEmptyOrZeroLength");function eRe(e){if(ms(e))return!0;for(let t=0;t<e.length;t++)if(ms(e[t]))return!0;return!1}o(eRe,"arrayHasEmptyValues");function tRe(e){if(ao(e))return!0;for(let t=0;t<e.length;t++)if(ao(e[t]))return!0;return!1}o(tRe,"arrayHasEmptyOrZeroLengthValues");function rRe(...e){try{return e.join(Sc.sep)}catch{console.error(e)}}o(rRe,"buildFolderPath");function HQ(e){return ms(e)?!1:e===!0||e===!1}o(HQ,"isBoolean");function nRe(e){return ms(e)?!1:typeof e=="object"}o(nRe,"isObject");function sRe(e){return ao(e)?QTe:e.slice(0,-JTe)}o(sRe,"stripFileExtension");function iRe(e){return ms(e)||e===""||typeof e!="string"?e:xQ[e]!==void 0?xQ[e]:GQ(e)===!0?Number(e):WTe.test(e)?new Date(e):e}o(iRe,"autoCast");function kQ(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(kQ,"autoCastJSON");function uD(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=uD(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=uD(r);n!==r&&(e[t]=n)}return e}else return kQ(e)}o(uD,"autoCastJSONDeep");function GQ(e){if(e.startsWith("0.")&&UQ(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&UQ(e))}o(GQ,"autoCasterIsNumberCheck");async function oRe(e){if(ao(e))throw new Error(`Directory path: ${e} does not exist`);try{await MQ.emptyDir(e),await MQ.remove(e)}catch(t){throw kn.error(`Error removing files in ${e} -- ${t}`),t}}o(oRe,"removeDir");function aRe(e,t){if(ao(e)){kn.info("Invalid current version sent as parameter.");return}if(ao(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(aRe,"compareVersions");function cRe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}o(cRe,"isCompatibleDataVersion");function lRe(e){if(ms(e))return e;let t=String(e);return t==="."?Cr.UNICODE_PERIOD:t===".."?Cr.UNICODE_PERIOD+Cr.UNICODE_PERIOD:t.replace(Cr.FORWARD_SLASH_REGEX,Cr.UNICODE_FORWARD_SLASH)}o(lRe,"escapeRawValue");function uRe(e){if(ms(e))return e;let t=String(e);return t===Cr.UNICODE_PERIOD?".":t===Cr.UNICODE_PERIOD+Cr.UNICODE_PERIOD?"..":String(e).replace(Cr.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(uRe,"unescapeValue");function dRe(e,t){if(ms(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+oy.EOL}!ao(n)&&n[0]===";"?r+=" "+n+s+oy.EOL:ao(n)||(r+=n+"="+s+oy.EOL)}catch{kn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}o(dRe,"stringifyProps");function qQ(){let e;try{e=oy.homedir()}catch{e=process.env.HOME}return e}o(qQ,"getHomeDir");function fRe(){let e=Sc.join(qQ(),Cr.HDB_HOME_DIR_NAME,Cr.BOOT_PROPS_FILE_NAME);return BQ.existsSync(e)||(e=Sc.join(__dirname,"../","hdb_boot_properties.file")),e}o(fRe,"getPropsFilePath");function mRe(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(mRe,"timeoutPromise");async function hRe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=HTe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}o(hRe,"isPortTaken");function pRe(e){try{return Cr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){kn.error(`Error checking operation against cluster ops ${t}`)}return!1}o(pRe,"isClusterOperation");function ERe(e,t){let r=(Me(),v(Et)).getDatabases();if(!r[e])return cy.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return cy.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(ERe,"checkGlobalSchemaTable");function _Re(e,t){if(ms(t)){kn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ms(e)||ao(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(_Re,"getClusterUser");function gRe(){vQ.parsePromise=function(e,t,r){return new Promise(function(n,s){vQ.parse(e,{header:!0,transformHeader:$Q,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}o(gRe,"promisifyPapaParse");function $Q(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o($Q,"removeBOM");function SRe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;kn.info(`Got cluster status event response: ${$Te(s)}`);try{i.cancel()}catch{kn.error("Error trying to cancel timeout.")}n(s)})})}o(SRe,"createEventPromise");async function TRe(e){let t=!0,r=0;do await FQ(zTe*r++),(await qTe.findPs(e)).length>0&&(t=!1);while(t&&r<jTe);if(t)throw new Error(`process ${e} was not started`)}o(TRe,"checkProcessRunning");function RRe(e,t){let r=VQ(e);if(r)return r;let n=KQ(e,t);if(n)return n}o(RRe,"checkSchemaTableExist");function VQ(e){let{getDatabases:t}=(Me(),v(Et));if(!t()[e])return cy.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(VQ,"checkSchemaExists");function KQ(e,t){let{getDatabases:r}=(Me(),v(Et));if(!r()[e][t])return cy.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(KQ,"checkTableExists");function yRe(){let e=ay().utc().add(1,"d").startOf("d").unix(),t=ay().utc().unix();return e-t}o(yRe,"getStartOfTomorrowInSeconds");function ARe(){return ay().utc().format("DD-MM-YYYY")}o(ARe,"getLimitKey");function bRe(e){try{let t=new kTe(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(bRe,"backtickASTSchemaItems");function IRe(e){return[e]}o(IRe,"createForkArgs");function NRe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(NRe,"autoCastBoolean");function wRe(e,t){let{getDatabases:r}=(Me(),v(Et)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}o(wRe,"getTableHashAttribute");function ORe(e){let{getDatabases:t}=(Me(),v(Et));return t()[e]!==void 0}o(ORe,"doesSchemaExist");function CRe(e,t){let{getDatabases:r}=(Me(),v(Et));return r()[e]?.[t]!==void 0}o(CRe,"doesTableExist");function PRe(e){try{return JSON.stringify(e)}catch{return e}}o(PRe,"stringifyObj");function LRe(e){let t=ay.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(LRe,"ms_to_time");function DRe(e,t){let r=Sc.basename(e,Sc.extname(e));return Sc.join(Sc.dirname(e),r+t)}o(DRe,"changeExtension");function dD(){if(process.env[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=VTe(process.argv);if(e[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(dD,"getEnvCliRootPath");var lD;function MRe(){if(lD)return lD;let e=dD();if(dD()&&BQ.pathExistsSync(Sc.join(e,Cr.HDB_CONFIG_FILE)))return lD=!0,!0}o(MRe,"noBootFile");function vRe(e,t){let r;return e.protocol==="http:"?r=YTe:r=KTe,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(vRe,"httpRequest");function URe(e){if(!e.schema&&!e.database){e.schema=Cr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(URe,"transformReq");function xRe(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(xRe,"convertToMS");var cy=tn()});var oe=M((jQ,QQ)=>{"use strict";var fD=require("fs-extra"),iu=require("path"),YQ=require("os"),BRe=require("properties-reader"),oE=Q(),iE=ie(),Be=(k(),v(W)),ly=wt(),FRe="Error initializing environment manager",uy="BOOT_PROPS_FILE_PATH",WQ=!1,HRe={[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},sa={};Object.assign(jQ,QQ.exports={BOOT_PROPS_FILE_PATH:uy,getHdbBasePath:kRe,setHdbBasePath:GRe,get:zQ,initSync:$Re,setProperty:Je,initTestEnvironment:VRe});function kRe(){return sa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(kRe,"getHdbBasePath");function GRe(e){sa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(GRe,"setHdbBasePath");function zQ(e){let t=ly.getConfigValue(e);return t===void 0?sa[e]:t}o(zQ,"get");function Je(e,t){HRe[e]&&(sa[e]=t),ly.updateConfigObject(e,t)}o(Je,"setProperty");function qRe(){let e;try{e=iE.getPropsFilePath(),fD.accessSync(e,fD.constants.F_OK|fD.constants.R_OK),WQ=!0;let t=BRe(e);return sa[Be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Be.HDB_SETTINGS_NAMES.INSTALL_USER),sa[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),sa[uy]=e,!0}catch{return oE.trace(`Environment manager found no properties file at ${e}`),!1}}o(qRe,"doesPropFileExist");function $Re(e=!1){try{(WQ||qRe()||iE.noBootFile()||e)&&(ly.initConfig(e),sa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=ly.getConfigValue(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){oE.error(FRe),oE.error(t),console.error(t),process.exit(1)}}o($Re,"initSync");function VRe(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=iu.join(__dirname,"../../","unitTests");sa[uy]=iu.join(l,"hdb_boot_properties.file"),Je(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,iu.join(l,"settings.test")),Je(Be.HDB_SETTINGS_NAMES.INSTALL_USER,YQ.userInfo()?YQ.userInfo().username:void 0),Je(Be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Je(Be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,iu.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,iu.join(l,"envDir")),Je(Be.CONFIG_PARAMS.STORAGE_PATH,iu.join(l,"envDir")),s&&(Je(Be.CONFIG_PARAMS.HTTP_SECUREPORT,zQ(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,iE.isEmpty(i)?!1:i),Je(Be.CONFIG_PARAMS.HTTP_CORS,iE.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,iu.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Je(Be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,iE.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 ${uy}. Please check your boot props and settings files`;oE.fatal(r),oE.error(t)}}o(VRe,"initTestEnvironment")});var rJ=M((oHe,tJ)=>{"use strict";var{promises:If,createReadStream:KRe,createWriteStream:YRe}=require("fs"),{createGzip:WRe}=require("zlib"),{promisify:zRe}=require("util"),{pipeline:jRe}=require("stream"),QRe=zRe(jRe),hD=require("path"),eJ=oe();eJ.initSync();var dy=Q(),{CONFIG_PARAMS:JRe,ITC_EVENT_TYPES:sHe}=(k(),v(W)),{onMessageFromWorkers:iHe}=nt(),{convertToMS:JQ}=ie(),{onStorageReclamation:XRe}=(vR(),v(G2)),ZRe=6e4,eye="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",tye="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",mD,XQ;tJ.exports=rye;function rye({logger:e,maxSize:t,interval:r,retention:n,enabled:s,path:i,auditInterval:a}){if(s===!1)return;let c=0;if(XRe(e.path,f=>{c=f},!0),!t&&!r)throw new Error(eye);if(!i)throw new Error(tye);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=JQ(r));let d;return mD=Date.now(),dy.trace("Log rotate enabled, maxSize:",t,"interval:",r),XQ=setInterval(async()=>{if(l){let f;f=await If.stat(e.path),f.size>=l&&(d=await ZQ(e.path,i))}if(u&&Date.now()-mD>=u&&(d=await ZQ(e.path,i),mD=Date.now()),n||c){let f=JQ(n??"1M")/(1+c);c=0;let m=await If.readdir(i);for(let h of m)try{let p=await If.stat(hD.join(i,h));Date.now()-p.mtimeMs>f&&await If.unlink(hD.join(i,h))}catch(p){dy.error("Error trying to remove log",h,p)}}},a??ZRe).unref(),{end(){clearInterval(XQ)},getLastRotatedLogPath(){return d}}}o(rye,"logRotator");async function ZQ(e,t){let r=eJ.get(JRe.LOGGING_ROTATION_COMPRESS),n=hD.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.log`);return await If.rename(e,n),r&&(e=n,n+=".gz",await QRe(KRe(e),WRe(),YRe(n)),await If.unlink(e)),dy.closeLogFile(),dy.notify(`hdb.log rotated, old log moved to ${n}`),n}o(ZQ,"moveLogFile")});var aJ={};we(aJ,{RootConfigWatcher:()=>pD});var nJ,sJ,iJ,fy,oJ,pD,cJ=ce(()=>{nJ=w(require("chokidar")),sJ=require("node:fs/promises"),iJ=w(wt()),fy=require("node:stream"),oJ=require("yaml"),pD=class extends fy.EventEmitter{static{o(this,"RootConfigWatcher")}#e;#t;#r;constructor(){super(),this.#e=(0,iJ.getConfigFilePath)(),this.#t=nJ.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,sJ.readFile)(this.#e,"utf-8").then(t=>{if(!t)return;let r=(0,oJ.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,fy.once)(this,"ready")}close(){return this.#t.close(),this.#r=void 0,this.emit("close"),this.removeAllListeners(),this}get config(){return this.#r}}});var Q=M((dHe,Ty)=>{"use strict";var ia=require("fs-extra"),{workerData:nye,threadId:sye,isMainThread:pJ}=require("worker_threads"),lE=require("path"),EJ=require("yaml"),_J=require("properties-reader"),Gr=(k(),v(W)),lJ=xc(),iye=require("os"),{PACKAGE_ROOT:yD}=bt(),{_assignPackageExport:oye}=Zs(),{Console:aye}=require("console"),uJ=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),dJ=new Map,{join:oa}=lE,fJ=1e4,or={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},cye={STDOUT:"stdOut",STDERR:"stdErr"},uHe=oa(yD,"logs"),lye=oa(yD,"config/yaml/",Gr.HDB_DEFAULT_CONFIG_FILE),uye=1e4,uE,dE,my,co,_D,ED,py,Ut,Gn,Ey,_y,Nf,cE,aE;function hy(e,t,r){e.rotation=t.rotation;let n=t.path;n?t.root||(t.root=lE.dirname(n)):t.root?n=oa(t.root,_D):(n=Ut.path,t.root||(t.root=lE.dirname(n))),n?e.path=n:console.error("No path for logger",t),e.level=or[t.level]??Ut?.level??or.info,gJ(e),e.logToStdstreams=t.stdStreams??!1,e.tag=t.tag??(Ut.path===e.path&&r)}o(hy,"updateLogger");function gJ(e){let t=e.conditional??(e.conditional={});t.notify=or.notify>=e.level?e.notify.bind(e):void 0,t.fatal=or.fatal>=e.level?e.fatal.bind(e):void 0,t.error=or.error>=e.level?e.error.bind(e):void 0,t.warn=or.warn>=e.level?e.warn.bind(e):void 0,t.info=or.info>=e.level?e.info.bind(e):void 0,t.debug=or.debug>=e.level?e.debug.bind(e):void 0,t.trace=or.trace>=e.level?e.trace.bind(e):void 0}o(gJ,"updateConditional");async function gD(){aE||(aE=new Cye,await aE.ready(),aE.on("change",gD));let e=aE.config,t=e.logging??{};hy(Ut,t),py=Ut.path,uE=t.console??!1,t.external&&hy(Gn,t.external);for(let r in e){let n=e[r];n.logging?hy(Ut.forComponent(r),n.logging,r):Ut.hasComponent(r)&&hy(Ut.forComponent(r),t,r)}}o(gD,"updateLogSettings");var SD=class extends aye{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){Sn="trace",this.level<=or.trace&&super.info(...t),Sn="info"}debug(...t){Sn="debug",this.level<=or.debug&&super.info(...t),Sn="info"}info(...t){Sn="info",this.level<=or.info&&super.info(...t),Sn="info"}warn(...t){Sn="warn",this.level<=or.warn&&super.warn(...t),Sn="info"}error(...t){Sn="error",this.level<=or.error&&super.error(...t),Sn="info"}fatal(...t){Nf=!0;try{Sn="fatal",this.level<=or.fatal&&super.error(...t),Sn="info"}finally{Nf=!1}}notify(...t){Nf=!0;try{Sn="notify",this.level<=or.notify&&super.info(...t),Sn="info"}finally{Nf=!1}}withTag(t){return TJ(t,!0,this)}forComponent(t){return this}hasComponent(t){return!1}};cE===void 0&&SJ();Ty.exports={notify:gye,fatal:Sye,error:RD,warn:Tye,info:pye,debug:_ye,trace:Eye,logLevel:co,loggerWithTag:TJ,suppressLogging:mye,initLogSettings:SJ,logCustomLevel:Rye,closeLogFile:RJ,createLogger:Sy,logsAtLevel:dye,getLogFilePath:o(()=>py,"getLogFilePath"),forComponent:o(e=>Ut.forComponent(e),"forComponent"),setMainLogger:wye,setLogLevel:Aye,OUTPUTS:cye,AuthAuditLog:Oye,start:gD,startOnMainThread:gD,errorToString:Nye};Ty.exports.externalLogger={notify(...e){Gn.notify(...e)},fatal(...e){Gn.fatal(...e)},error(...e){Gn.error(...e)},warn(...e){Gn.warn(...e)},info(...e){Gn.info(...e)},debug(...e){Gn.debug(...e)},trace(...e){Gn.trace(...e)},withTag(e){return Gn.withTag(e)},loggerWithTag(e){return Gn.withTag(e)}};oye("logger",Ty.exports.externalLogger);function dye(e){return or[co]<=or[e]}o(dye,"logsAtLevel");function SJ(e=!1){try{if(cE===void 0||e){RJ();let t=yye(),r=lJ(["ROOTPATH"]);try{cE=_J(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!ia.pathExistsSync(oa(r.ROOTPATH,Gr.HDB_CONFIG_FILE)))throw s}let n;if({level:co,configLogPath:ED,toFile:dE,logConsole:uE,rotation:n,toStream:my}=bye(r.ROOTPATH?oa(r.ROOTPATH,Gr.HDB_CONFIG_FILE):cE.get("settings_path")),_D=Gr.LOG_NAMES.HDB,py=oa(ED,_D),Ut=Sy({path:py,level:co,stdStreams:my,rotation:n}),Gn=Ut.forComponent("external"),Gn.tag=null,pJ)try{require("segfault-handler").registerHandler(oa(ED,"crash.log"))}catch{}}}catch(t){if(cE=void 0,t.code===Gr.NODE_ERROR_CODES.ENOENT||t.code===Gr.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=lJ(Object.keys(Gr.CONFIG_PARAM_MAP),!0);for(let s in r){let i=Gr.CONFIG_PARAM_MAP[s];i&&i.toLowerCase();let a=r[s];if(i===Gr.CONFIG_PARAMS.LOGGING_LEVEL){co=a;continue}i===Gr.CONFIG_PARAMS.LOGGING_CONSOLE&&(uE=i)}let{defaultLevel:n}=Iye();dE=!1,my=!0,co=co===void 0?n:co,Ut=Sy({level:co}),Gn=Ut.forComponent("external"),Gn.tag=null;return}throw RD("Error initializing log settings"),RD(t),t}process.env.DEV_MODE&&(my=!0),fye()}o(SJ,"initLogSettings");var Tc=!0;function fye(){dE&&(process.stdout.write=function(e){return typeof e=="string"&&Tc&&uE&&(e=e.toString(),e[e.length-1]===`
33
+ `);throw n[1]?yC(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,AC.BAD_REQUEST):yC(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",AC.BAD_REQUEST)}return t}o(iY,"convertSQLToAST");function oY(e,t,r){try{let n=zpe;if(!e.bypass_auth&&!t.permissions_checked){let i=sY(e,t);if(i&&i.length>0)return r(Kpe,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Ep.VALID_SQL_OPS_ENUM.SELECT:n=Bpe,s=t.ast.statements[0];break;case Ep.VALID_SQL_OPS_ENUM.INSERT:n=jpe;break;case Ep.VALID_SQL_OPS_ENUM.UPDATE:n=Hpe;break;case Ep.VALID_SQL_OPS_ENUM.DELETE:n=kpe;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(oY,"processAST");function zpe(e,t){fT.info(e),t("unknown sql statement")}o(zpe,"nullFunction");function jpe({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=Qpe(i,e.values)}catch(a){return r(a)}xpe(s,(a,c)=>{if(a)return r(a);try{delete c.new_attributes,delete c.txn_time}catch(l){fT.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}o(jpe,"convertInsert");function Qpe(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]]=ac.compile(`SELECT ${s.toString()} AS [${Ep.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw fT.error(r),new Error(Ype)}}o(Qpe,"createDataObjects")});var PC=M((a0e,dY)=>{var _T=require("clone"),gT=lt(),Jpe=ie(),pT=(k(),v(W)),i0e=Q(),IC=require("fs"),wC=require("joi"),{string:ET}=wC.types(),{hdbErrors:Xpe,handleHDBError:hT}=ge(),{HDB_ERROR_MSGS:o0e,HTTP_STATUS_CODES:NC}=Xpe,{commonValidators:Yd}=Bi(),cY=" is required",Zpe=["insert","update","upsert"],OC={database:{presence:!1,format:Yd.schema_format,length:Yd.schema_length},schema:{presence:!1,format:Yd.schema_format,length:Yd.schema_length},table:{presence:!0,format:Yd.schema_format,length:Yd.schema_length},action:{inclusion:{within:Zpe,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},eEe={schema:ET.required(),table:ET.required(),action:ET.valid("insert","update","upsert")},{AWS_ACCESS_KEY:tEe,AWS_SECRET:rEe,AWS_BUCKET:nEe,AWS_FILE_KEY:sEe,REGION:iEe}=pT.S3_BUCKET_AUTH_KEYS,oEe={s3:{presence:!0},[`s3.${tEe}`]:{presence:!0,type:"String"},[`s3.${rEe}`]:{presence:!0,type:"String"},[`s3.${nEe}`]:{presence:!0,type:"String"},[`s3.${sEe}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${iEe}`]:{presence:!0,type:"String"}},lY=_T(OC);lY.data.presence={message:cY};var uY=_T(OC);uY.file_path.presence={message:cY};var aEe=Object.assign(_T(OC),oEe),CC=_T(eEe);CC.csv_url=ET.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();CC.passthrough_headers=wC.object();function cEe(e){let t=gT.validateObject(e,lY);return ST(e,t)}o(cEe,"dataObject");function lEe(e){let t=gT.validateBySchema(e,wC.object(CC));return ST(e,t)}o(lEe,"urlObject");function uEe(e){let t=gT.validateObject(e,uY);return ST(e,t)}o(uEe,"fileObject");function dEe(e){let t=gT.validateObject(e,aEe);return ST(e,t)}o(dEe,"s3FileObject");function ST(e,t){if(!t){let r=Jpe.checkGlobalSchemaTable(e.schema,e.table);if(r)return hT(new Error,r,NC.BAD_REQUEST);if(e.operation===pT.OPERATIONS_ENUM.CSV_FILE_LOAD)try{IC.accessSync(e.file_path,IC.constants.R_OK|IC.constants.F_OK)}catch(n){return n.code===pT.NODE_ERROR_CODES.ENOENT?hT(n,`No such file or directory ${n.path}`,NC.BAD_REQUEST):n.code===pT.NODE_ERROR_CODES.EACCES?hT(n,`Permission denied ${n.path}`,NC.BAD_REQUEST):hT(n)}}return t}o(ST,"postValidateChecks");dY.exports={dataObject:cEe,urlObject:lEe,fileObject:uEe,s3FileObject:dEe}});var LC=M((l0e,fY)=>{"use strict";var _p=Q(),TT=(k(),v(W));async function fEe(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===TT.OPERATIONS_ENUM.INSERT||t.operation===TT.OPERATIONS_ENUM.UPDATE||t.operation===TT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===TT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(_p.info(i.message),i):i.http_resp_msg?(_p.error(`Error calling operation: ${e.name}`),_p.error(i.http_resp_msg),i):(_p.error(`Error calling operation: ${e.name}`),_p.error(i),i)}}o(fEe,"callOperationFunctionAsAwait");fY.exports={callOperationFunctionAsAwait:fEe}});var DC=M((d0e,hY)=>{"use strict";var{S3:mEe,GetObjectCommand:hEe}=require("@aws-sdk/client-s3");hY.exports={getFileStreamFromS3:pEe,getS3AuthObj:mY};async function pEe(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await mY(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new hEe(r))).Body}o(pEe,"getFileStreamFromS3");function mY(e,t,r){return new mEe({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}o(mY,"getS3AuthObj")});var EY=M((m0e,pY)=>{"use strict";var MC=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}},vC=class{static{o(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};pY.exports={BulkLoadFileObject:MC,BulkLoadDataObject:vC}});var xC=M((p0e,_Y)=>{"use strict";var UC=class{static{o(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};_Y.exports=UC});var qC=M((R0e,vY)=>{"use strict";var RT=Cn(),AT=PC(),EEe=require("needle"),Ti=(k(),v(W)),_0e=Ot(),Wd=ie(),{handleHDBError:Qt,hdbErrors:NY}=ge(),{HTTP_STATUS_CODES:Jr,HDB_ERROR_MSGS:Ir,CHECK_LOGS_WRAPPER:$l}=NY,zd=Q(),BC=require("papaparse");Wd.promisifyPapaParse();var Ri=require("fs-extra"),_Ee=require("path"),{chain:gY}=require("stream-chain"),SY=require("stream-json/streamers/StreamArray"),TY=require("stream-json/utils/Batch"),RY=require("stream-chain/utils/comp"),{finished:yY}=require("stream"),gEe=oe(),wY=LC(),SEe=DC(),{BulkLoadFileObject:HC,BulkLoadDataObject:TEe}=EY(),kC=mC(),{verifyBulkLoadAttributePerms:OY}=dT(),g0e=xC(),S0e=mr(),T0e=ki(),{databases:REe}=(Me(),v(Et)),{coerceType:yEe}=(bT(),v(UY)),AY="No records parsed from csv file.",ql=`${gEe.get("HDB_ROOT")}/tmp`,{schemaRegex:AEe}=Bi(),bY=1024*1024*2,IY=5e3,bEe={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};vY.exports={csvDataLoad:IEe,csvURLLoad:NEe,csvFileLoad:wEe,importFromS3:OEe};async function IEe(e,t){let r=AT.dataObject(e);if(r)throw Qt(r,r.message,Jr.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=LY(e.schema,e.table),i=BC.parse(e.data,{header:!0,skipEmptyLines:!0,transform:FC.bind(null,s),dynamicTyping:!1}),a=new kC;e.hdb_user&&e.hdb_user?.role&&e.hdb_user?.role?.permission&&e.hdb_user?.role?.permission?.super_user!==!0&&OY(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 Qt(new Error,c,Jr.BAD_REQUEST,void 0,void 0,!0);let l=new TEe(e.action,e.schema,e.table,i.data);return n=await wY.callOperationFunctionAsAwait(DY,l,null),n.message===AY?AY:MY(n.records,n.number_written)}catch(s){throw Vl(s)}}o(IEe,"csvDataLoad");async function NEe(e){let t=AT.urlObject(e);if(t)throw Qt(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${ql}/${r}`;try{await CEe(e,r)}catch(s){throw zd.error(Ir.DOWNLOAD_FILE_ERR(r)+" - "+s),Qt(s,$l(Ir.DOWNLOAD_FILE_ERR(r)))}try{let s=new HC(this.job_operation_function.name,e.action,e.schema,e.table,n,Ti.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission),i=await GC(s);return await yT(n),i}catch(s){throw await yT(n),Vl(s)}}o(NEe,"csvURLLoad");async function wEe(e){let t=AT.fileObject(e);if(t)throw Qt(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=new HC(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Ti.VALID_S3_FILE_TYPES.CSV,e.hdb_user?.role?.permission);try{return await GC(r)}catch(n){throw Vl(n)}}o(wEe,"csvFileLoad");async function OEe(e){let t=AT.s3FileObject(e);if(t)throw Qt(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=_Ee.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${ql}/${s}`;let i=new HC(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user?.role?.permission);await PEe(s,e);let a=await GC(i);return await yT(r),a}catch(n){throw await yT(r),Vl(n)}}o(OEe,"importFromS3");async function CEe(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await EEe("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 Qt(n,s,n.statusCode,Ti.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}DEe(r,e.csv_url),await LEe(t,r.raw)}o(CEe,"downloadCSVFile");async function PEe(e,t){try{let r=`${ql}/${e}`;await Ri.mkdirp(ql),await Ri.writeFile(`${ql}/${e}`,"",{flag:"a+"});let n=await Ri.createWriteStream(r),s=await SEe.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(){zd.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw zd.error(Ir.S3_DOWNLOAD_ERR+" - "+r),Qt(r,$l(Ir.S3_DOWNLOAD_ERR))}}o(PEe,"downloadFileFromS3");async function LEe(e,t){try{await Ri.mkdirp(ql),await Ri.writeFile(`${ql}/${e}`,t)}catch(r){throw zd.error(Ir.WRITE_TEMP_FILE_ERR),Qt(r,$l(Ir.DEFAULT_BULK_LOAD_ERR))}}o(LEe,"writeFileToTempFolder");async function yT(e){if(e)try{await Ri.access(e),await Ri.unlink(e)}catch{zd.warn(`could not delete temp csv file at ${e}, file does not exist`)}}o(yT,"deleteTempFile");function DEe(e,t){if(e.statusCode!==NY.HTTP_STATUS_CODES.OK)throw Qt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Jr.BAD_REQUEST);if(!bEe[e.headers["content-type"]])throw Qt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Jr.BAD_REQUEST);if(!e.raw)throw Qt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Jr.BAD_REQUEST)}o(DEe,"validateURLResponse");async function GC(e){try{let t;switch(e.file_type){case Ti.VALID_S3_FILE_TYPES.CSV:t=await MEe(e);break;case Ti.VALID_S3_FILE_TYPES.JSON:t=await vEe(e);break;default:throw Qt(new Error,Ir.DEFAULT_BULK_LOAD_ERR,Jr.BAD_REQUEST,Ti.LOG_LEVELS.ERROR,Ir.INVALID_FILE_EXT_ERR(e))}return MY(t.records,t.number_written)}catch(t){throw Vl(t)}}o(GC,"fileLoad");async function CY(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 RT.validation(a);e.role_perms&&e.role_perms.super_user!==!0&&OY(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=Qt(c);r(l)}}o(CY,"validateChunk");async function PY(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Wd.autoCastJSONDeep(i),s&&s.pause();let a=n.meta?n.meta.fields:null;if(a)i.forEach(c=>{!Wd.isEmpty(c)&&!Wd.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 wY.callOperationFunctionAsAwait(DY,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=Qt(c,$l(Ir.INSERT_CSV_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.INSERT_CSV_ERR+" - "+c);r(l)}}o(PY,"insertChunk");async function MEe(e){let t={records:0,number_written:0},r=LY(e.schema,e.table);try{let n=new kC,s=Ri.createReadStream(e.file_path,{highWaterMark:bY});s.setEncoding("utf8"),await BC.parsePromise(s,CY.bind(null,e,n),FC.bind(null,r));let i=n.getPermsResponse();if(i)throw Qt(new Error,i,Jr.BAD_REQUEST);return s=Ri.createReadStream(e.file_path,{highWaterMark:bY}),s.setEncoding("utf8"),await BC.parsePromise(s,PY.bind(null,e,t),FC.bind(null,r)),s.destroy(),t}catch(n){throw Qt(n,$l(Ir.PAPA_PARSE_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.PAPA_PARSE_ERR+n)}}o(MEe,"callPapaParse");function LY(e,t){let r=REe[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>yEe(i,s));return n}o(LY,"createTransformMap");function FC(e,t,r){let n=e.get(r);return n?n(t):Wd.autoCast(t)}o(FC,"typeFunction");async function vEe(e){let t={records:0,number_written:0},r=o(n=>{throw n},"throwErr");try{let n=new kC,s=gY([Ri.createReadStream(e.file_path,{encoding:"utf-8"}),SY.withParser(),c=>c.value,new TY({batchSize:IY}),RY(async c=>{await CY(e,n,r,c)})]);await new Promise((c,l)=>{yY(s,u=>{u?l(u):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw Qt(new Error,i,Jr.BAD_REQUEST);let a=gY([Ri.createReadStream(e.file_path,{encoding:"utf-8"}),SY.withParser(),c=>c.value,new TY({batchSize:IY}),RY(async c=>{await PY(e,t,r,c)})]);return await new Promise((c,l)=>{yY(a,u=>{u?l(u):c()}),a.resume()}),t}catch(n){throw Qt(n,$l(Ir.INSERT_JSON_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.INSERT_JSON_ERR+n)}}o(vEe,"insertJson");async function DY(e){let t={};try{e.data&&e.data.length>0&&UEe(e.data[0])?t=await xEe(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",zd.info(t.message))}catch(r){throw Vl(r)}return t}o(DY,"callBulkFileLoad");function UEe(e){let t=Object.keys(e);for(let r of t)if(!AEe.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}o(UEe,"validateColumnNames");async function xEe(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=RT.insert;break;case"update":i=RT.update;break;case"upsert":i=RT.upsert;break;default:throw Qt(new Error,Ir.INVALID_ACTION_PARAM_ERR(n),Jr.BAD_REQUEST,Ti.LOG_LEVELS.ERROR,Ir.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=Wd.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:a.new_attributes}}catch(a){throw Vl(a)}}o(xEe,"bulkFileLoad");function MY(e,t){return`successfully loaded ${t} of ${e} records`}o(MY,"buildResponseMsg");function Vl(e){return Qt(e,$l(Ir.DEFAULT_BULK_LOAD_ERR),Jr.INTERNAL_SERVER_ERROR,Ti.LOG_LEVELS.ERROR,Ir.DEFAULT_BULK_LOAD_ERR+" - "+e)}o(Vl,"buildTopLevelErrMsg")});var KC=M((A0e,$Y)=>{"use strict";var VC=nn(),BEe=DC(),{AsyncParser:FEe}=require("json2csv"),IT=require("stream"),ls=ie(),$C=require("fs-extra"),HEe=require("path"),xs=Q(),{promisify:FY}=require("util"),gp=ie(),{handleHDBError:_r,hdbErrors:kEe}=ge(),{HDB_ERROR_MSGS:Bn,HTTP_STATUS_CODES:gr}=kEe,{streamAsJSON:GEe}=(EA(),v(fv)),{Upload:qEe}=require("@aws-sdk/lib-storage"),{toCsvStream:$Ee}=(To(),v(Dv)),xY=["search_by_value","search_by_hash","sql","search_by_conditions"],BY=["json","csv"],HY="json",kY="csv",VEe="Successfully exported JSON locally.",KEe="Successfully exported CSV locally.",YEe=1e3,WEe=VC.searchByHash,zEe=VC.searchByValue,jEe=FY(IT.finished);$Y.exports={export_to_s3:ZEe,export_local:QEe};async function QEe(e){xs.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=GY(e);if(!ls.isEmpty(t))throw xs.error(t),_r(new Error,t,gr.BAD_REQUEST,void 0,void 0,!0);if(ls.isEmpty(e.path))throw xs.error(Bn.MISSING_VALUE("path")),_r(new Error,Bn.MISSING_VALUE("path"),gr.BAD_REQUEST,void 0,void 0,!0);let r=(ls.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(HEe.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=ls.buildFolderPath(e.path,r);await JEe(e.path);let s=await qY(e);return await XEe(n,e.format,s)}o(QEe,"export_local");async function JEe(e){if(xs.trace("in confirmPath"),ls.isEmptyOrZeroLength(e))throw _r(new Error,`Invalid path: ${e}`,gr.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await $C.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,xs.error(n),_r(new Error,n,gr.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw xs.error(r),_r(new Error,r,gr.BAD_REQUEST,void 0,void 0,!0)}return!0}o(JEe,"confirmPath");async function XEe(e,t,r){if(xs.trace("in saveToLocal"),gp.isEmptyOrZeroLength(e))throw _r(new Error,Bn.INVALID_VALUE("file_path"),gr.BAD_REQUEST,void 0,void 0,!0);if(gp.isEmptyOrZeroLength(t))throw _r(new Error,Bn.INVALID_VALUE("Source format"),gr.BAD_REQUEST,void 0,void 0,!0);if(gp.isEmpty(r))throw _r(new Error,Bn.NOT_FOUND("Data"),gr.BAD_REQUEST,void 0,void 0,!0);if(t===HY){let n=$C.createWriteStream(e);return GEe(r).pipe(n),await jEe(n),{message:VEe,path:e}}else if(t===kY){let n=$C.createWriteStream(e),s=IT.Readable.from(r),i={},a=r.getColumns?.();a&&(i.fields=a.map(d=>({label:d,value:d})));let c={objectMode:!0};return await new FEe(i,c).fromInput(s).toOutput(n).promise(!1),{message:KEe,path:e}}throw _r(new Error,Bn.INVALID_VALUE("format"),gr.BAD_REQUEST)}o(XEe,"saveToLocal");async function ZEe(e){if(!e.s3||Object.keys(e.s3).length===0)throw _r(new Error,Bn.MISSING_VALUE("S3 object"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw _r(new Error,Bn.MISSING_VALUE("aws_access_key_id"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw _r(new Error,Bn.MISSING_VALUE("aws_secret_access_key"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.bucket))throw _r(new Error,Bn.MISSING_VALUE("bucket"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.key))throw _r(new Error,Bn.MISSING_VALUE("key"),gr.BAD_REQUEST);if(ls.isEmptyOrZeroLength(e.s3.region))throw _r(new Error,Bn.MISSING_VALUE("region"),gr.BAD_REQUEST);let t=GY(e);if(!ls.isEmpty(t))throw _r(new Error,t,gr.BAD_REQUEST);xs.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await qY(e)}catch(l){throw xs.error(l),l}let n,s=await BEe.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,a=new IT.PassThrough;if(e.format===kY){i=e.s3.key+".csv";let l=$Ee(r,r.getColumns?.());l.on("error",u=>{throw u}),l.pipe(a)}else if(e.format===HY){i=e.s3.key+".json";let l=new IT.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%YEe===0&&(l.push(d),d="")}d.length!==0&&l.push(d),l.push("]"),l.push(null)}else throw _r(new Error,Bn.INVALID_VALUE("format"),gr.BAD_REQUEST);return new qEe({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:a}}).done()}o(ZEe,"export_to_s3");function GY(e){if(xs.trace("in exportCoreValidation"),ls.isEmpty(e.format))return"format missing";if(BY.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${BY.join(", ")}`;let t=e.search_operation.operation;if(ls.isEmpty(t))return"search_operation.operation missing";if(xY.indexOf(t)<0)return`searchOperation.operation must be one of the following values: ${xY.join(", ")}`}o(GY,"exportCoreValidation");async function qY(e){xs.trace("in getRecords");let t,r;if(gp.isEmpty(e.search_operation)||gp.isEmptyOrZeroLength(e.search_operation.operation))throw _r(new Error,Bn.INVALID_VALUE("Search operation"),gr.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=zEe;break;case"search_by_hash":t=WEe;break;case"search_by_conditions":t=VC.searchByConditions;break;case"sql":{let n=mT();t=FY(n.evaluateSQL);break}default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,xs.error(r),_r(new Error,r,gr.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}o(qY,"getRecords")});var KY=M((I0e,VY)=>{"use strict";var YC=class{static{o(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};VY.exports=YC});var zY=M((w0e,WY)=>{"use strict";var e_e=(k(),v(W)),YY=require("moment"),t_e=require("uuid").v4,WC=class{static{o(this,"JobObject")}constructor(){this.id=t_e(),this.type=void 0,this.start_datetime=YY().valueOf(),this.created_datetime=YY().valueOf(),this.end_datetime=void 0,this.status=e_e.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};WY.exports=WC});var zC=M((C0e,rW)=>{"use strict";var r_e=require("uuid").v4,ZY=Cn(),eW=nn(),n_e=ci(),s_e=qu(),i_e=KY(),Dt=(k(),v(W)),o_e=zY(),a_e=pg(),yi=Q(),c_e=Xf(),jd=ie(),{promisify:l_e}=require("util"),Kl=require("moment"),u_e=mT(),NT=PC(),jY=hb(),{deleteTransactionLogsBeforeValidator:d_e}=XO(),{handleHDBError:QY,hdbErrors:f_e,ClientError:m_e}=ge(),{HTTP_STATUS_CODES:JY}=f_e,XY=eW.searchByValue,h_e=eW.searchByHash,p_e=ZY.insert,E_e=l_e(u_e.evaluateSQL),__e=ZY.update;rW.exports={addJob:T_e,updateJob:y_e,handleGetJob:g_e,handleGetJobsByStartDate:S_e,getJobById:tW};async function g_e(e){if(e.id===void 0)throw new m_e("'id' is required");let t=await tW(e.id);return jd.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(g_e,"handleGetJob");async function S_e(e){try{let t=await R_e(e);if(yi.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=Kl(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Kl(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 yi.error(r),new Error(r)}}o(S_e,"handleGetJobsByStartDate");async function T_e(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||jd.isEmptyOrZeroLength(e.operation)){let d="job parameter is invalid";return yi.info(d),t.error=d,t}if(!Dt.JOB_TYPE_ENUM[e.operation])return yi.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Dt.OPERATIONS_ENUM.CSV_FILE_LOAD:n=NT.fileObject(e);break;case Dt.OPERATIONS_ENUM.CSV_URL_LOAD:n=NT.urlObject(e);break;case Dt.OPERATIONS_ENUM.CSV_DATA_LOAD:n=NT.dataObject(e);break;case Dt.OPERATIONS_ENUM.IMPORT_FROM_S3:n=NT.s3FileObject(e);break;case Dt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Dt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=jY(e,"date");break;case Dt.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=jY(e,"timestamp");break;case Dt.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=d_e(e);break;case Dt.OPERATIONS_ENUM.RESTART_SERVICE:if(Dt.HDB_PROCESS_SERVICES[e.service]===void 0)throw QY(new Error,"Invalid service",JY.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw QY(n,n.message,JY.BAD_REQUEST,void 0,void 0,!0);let s=new o_e;s.type=e.operation===Dt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Dt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user?.username;let i=new n_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),a;try{a=Array.from(await XY(i))}catch(d){let f=`There was an error inserting a new job: ${d}`;return yi.error(f),t}let c=Array.isArray(a)?a:Object.keys(a);if(c&&c.length>0){s.id=r_e();try{a=await XY(i)}catch(d){let f=`There was an error inserting a new job: ${d}`;return yi.error(f),t}if(c=Array.isArray(a)?a:Object.keys(a),c&&c.length>0)return yi.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new c_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),u;try{u=await p_e(l)}catch(d){return yi.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,yi.trace(d)}return t}o(T_e,"addJob");async function R_e(e){let t=Kl(e.from_date,Kl.ISO_8601),r=Kl(e.to_date,Kl.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 i_e(n,e.hdb_user);try{return await E_e(s)}catch(i){throw yi.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(R_e,"getJobsInDateRange");async function tW(e){if(jd.isEmptyOrZeroLength(e))return jd.errorizeMessage("Invalid job ID specified.");let t=new s_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await h_e(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return yi.error(n),jd.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}o(tW,"getJobById");async function y_e(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(jd.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Dt.JOB_STATUS_ENUM.COMPLETE||e.status===Dt.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Kl().valueOf());let t=new a_e(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await __e(t),r}o(y_e,"updateJob")});var uW=M((L0e,lW)=>{"use strict";var nW=ie(),Nr=(k(),v(W)),A_e=require("moment"),wT=qC(),Sp=Q(),sW=zC(),iW=KC(),oW=Xc(),aW=nt(),b_e=nT(),I_e=kd(),{parentPort:N_e,isMainThread:cW}=require("worker_threads"),{onMessageByType:w_e}=nt(),jC=class{static{o(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function O_e(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(nW.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(nW.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nr.JOB_TYPE_ENUM.csv_file_load:await Zi(e,wT.csvFileLoad);break;case Nr.JOB_TYPE_ENUM.csv_url_load:await Zi(e,wT.csvURLLoad);break;case Nr.JOB_TYPE_ENUM.csv_data_load:await Zi(e,wT.csvDataLoad);break;case Nr.JOB_TYPE_ENUM.import_from_s3:await Zi(e,wT.importFromS3);break;case Nr.JOB_TYPE_ENUM.empty_trash:break;case Nr.JOB_TYPE_ENUM.export_local:await Zi(e,iW.export_local);break;case Nr.JOB_TYPE_ENUM.export_to_s3:await Zi(e,iW.export_to_s3);break;case Nr.JOB_TYPE_ENUM.delete_files_before:case Nr.JOB_TYPE_ENUM.delete_records_before:await Zi(e,oW.deleteFilesBefore);break;case Nr.JOB_TYPE_ENUM.delete_audit_logs_before:await Zi(e,oW.deleteAuditLogsBefore);break;case Nr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Zi(e,b_e.deleteTransactionLogsBefore);break;case Nr.JOB_TYPE_ENUM.restart_service:return await Zi(e,I_e.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}o(O_e,"parseMessage");async function Zi(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=A_e().valueOf(),await sW.updateJob(e.job),await C_e(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):Sp.error(`There was an error running ${t.name} job with id ${e.job.id}`),Sp.error(n),e.job.message=n,e.job.status=Nr.JOB_STATUS_ENUM.ERROR;try{await sW.updateJob(e.job)}catch(s){throw Sp.error(`Unable to update job with id ${e.job.id}`),s}throw r}}o(Zi,"runJob");async function C_e(e){Sp.trace("launching job thread:",e),cW?aW.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):N_e.postMessage({type:Nr.ITC_EVENT_TYPES.START_JOB,jobId:e})}o(C_e,"launchJobThread");cW&&w_e(Nr.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{aW.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){Sp.error(r)}});lW.exports={parseMessage:O_e,RunnerMessage:jC}});var fW=M((M0e,dW)=>{"use strict";var P_e=ie(),QC=oe(),cc=(k(),v(W)),L_e=Ot(),D_e=mr(),eo=Q(),M_e=xC(),v_e=ki();QC.initSync();dW.exports={postOperationHandler:x_e,sendOperationTransaction:Tp};async function Tp(e,t,r,n){if(e.schema===cc.SYSTEM_SCHEMA_NAME)return;let s=U_e(e,t,r);s&&(eo.trace(`sendOperationTransaction publishing to schema ${e.schema} following transaction:`,s),await D_e.publishToStream(`${L_e.SUBJECT_PREFIXES.TXN}.${e.schema}`,v_e.createNatsTableStreamName(e.schema,e.table),n,s))}o(Tp,"sendOperationTransaction");function U_e(e,t,r){if(P_e.isEmptyOrZeroLength(t))return null;let n={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===cc.OPERATIONS_ENUM.DELETE?n.hash_values=t:n.records=e.records,n}o(U_e,"convertCRUDOperationToTransaction");async function x_e(e,t,r){if(!QC.get(cc.CONFIG_PARAMS.CLUSTERING_ENABLED))return;eo.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let n=e.hdb_user?.username,s=QC.get(cc.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new M_e(t.txn_time,n,s);switch(e.operation){case cc.OPERATIONS_ENUM.INSERT:try{await Tp(e,t.inserted_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for insert."),eo.error(a)}break;case cc.OPERATIONS_ENUM.DELETE:try{await Tp(e,t.deleted_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for delete."),eo.error(a)}break;case cc.OPERATIONS_ENUM.UPDATE:try{await Tp(e,t.update_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for update."),eo.error(a)}break;case cc.OPERATIONS_ENUM.UPSERT:try{await Tp(e,t.upserted_hashes,i,r)}catch(a){eo.error("There was an error calling clustering postOperationHandler for upsert."),eo.error(a)}break;default:break}return t}o(x_e,"postOperationHandler")});var J,mW=ce(()=>{J=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 QO={};we(QO,{chooseOperation:()=>DW,executeJob:()=>Bs,getOperationFunction:()=>MW,operation:()=>iP,processLocalTransaction:()=>LW});async function LW(e,t){try{if(e.body.operation!=="read_log"&&(bp.default.log_level===$f.INFO||bp.default.log_level===$f.DEBUG||bp.default.log_level===$f.TRACE)){let{hdb_user:n,hdbAuthHeader:s,password:i,payload:a,...c}=e.body;gn.info(c)}}catch(n){gn.error(n)}let r=await CW.default.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return H_e[e.body.operation]&&IW.default.setSchemaDataToGlobal(n=>{n&&gn.error(n)}),r}function DW(e){let t;try{t=MW(e)}catch(s){throw gn.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=PT.default.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let a=PT.default.checkASTPermissions(e,i);if(a)throw gn.error(`${hW.FORBIDDEN} from operation ${e.operation}`),gn.warn(`User '${e.hdb_user?.username}' is not permitted to ${e.operation}`),(0,Fs.handleHDBError)(new Error,a,Fs.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.LOGIN&&e.operation!==q.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=bW.default.verifyPerms(i,s);if(a)throw gn.error(`${hW.FORBIDDEN} from operation ${e.operation}`),gn.warn(`User '${i.hdb_user?.username}' is not permitted to ${i.operation}`),(0,Fs.handleHDBError)(new Error,a,Fs.hdbErrors.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw(0,Fs.handleHDBError)(s,"There was an error when trying to choose an operation path")}return r}function MW(e){if(gn.trace(`getOperationFunction with operation: ${e.operation}`),pW.has(e.operation))return pW.get(e.operation);throw(0,Fs.handleHDBError)(new Error,Fs.hdbErrors.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Fs.hdbErrors.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}function iP(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=DW(e);return LW({body:e},n)}async function k_e(e){gn.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[Qy]=!0;let a;switch(i.operation){case q.INSERT:a=await Wl.default.insert(i);break;case q.UPDATE:a=await Wl.default.update(i);break;case q.UPSERT:a=await Wl.default.upsert(i);break;case q.DELETE:a=await Xd.default.deleteRecord(i);break;default:gn.warn("invalid operation in catchup");break}await PW.transactToClusteringUtils.postOperationHandler(i,a,e)}catch(a){gn.info("Invalid operation in transaction"),gn.error(a)}}async function Bs(e){(0,OW.transformReq)(e);let t,r;try{if(r=await LT.default.addJob(e),r){t=r.createdJob,gn.info("addJob result",r);let n=new eP.default.RunnerMessage(t,e);return{message:await eP.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 gn.error(i),(0,Fs.handleHDBError)(n,i)}}function G_e(){let e=new Map;return e.set(q.INSERT,new J(Wl.default.insert)),e.set(q.UPDATE,new J(Wl.default.update)),e.set(q.UPSERT,new J(Wl.default.upsert)),e.set(q.SEARCH_BY_CONDITIONS,new J(Jd.default.searchByConditions)),e.set(q.SEARCH_BY_HASH,new J(Jd.default.searchByHash)),e.set(q.SEARCH_BY_ID,new J(Jd.default.searchByHash)),e.set(q.SEARCH_BY_VALUE,new J(Jd.default.searchByValue)),e.set(q.SEARCH,new J(B_e)),e.set(q.SQL,new J(F_e)),e.set(q.CSV_DATA_LOAD,new J(Bs,Rp.default.csvDataLoad)),e.set(q.CSV_FILE_LOAD,new J(Bs,Rp.default.csvFileLoad)),e.set(q.CSV_URL_LOAD,new J(Bs,Rp.default.csvURLLoad)),e.set(q.IMPORT_FROM_S3,new J(Bs,Rp.default.importFromS3)),e.set(q.CREATE_SCHEMA,new J(Ai.default.createSchema)),e.set(q.CREATE_DATABASE,new J(Ai.default.createSchema)),e.set(q.CREATE_TABLE,new J(Ai.default.createTable)),e.set(q.CREATE_ATTRIBUTE,new J(Ai.default.createAttribute)),e.set(q.DROP_SCHEMA,new J(Ai.default.dropSchema)),e.set(q.DROP_DATABASE,new J(Ai.default.dropSchema)),e.set(q.DROP_TABLE,new J(Ai.default.dropTable)),e.set(q.DROP_ATTRIBUTE,new J(Ai.default.dropAttribute)),e.set(q.DESCRIBE_SCHEMA,new J(yp.default.describeSchema)),e.set(q.DESCRIBE_DATABASE,new J(yp.default.describeSchema)),e.set(q.DESCRIBE_TABLE,new J(yp.default.describeTable)),e.set(q.DESCRIBE_ALL,new J(yp.default.describeAll)),e.set(q.DELETE,new J(Xd.default.deleteRecord)),e.set(q.ADD_USER,new J(Qd.default.addUser)),e.set(q.ALTER_USER,new J(Qd.default.alterUser)),e.set(q.DROP_USER,new J(Qd.default.dropUser)),e.set(q.LIST_USERS,new J(Qd.default.listUsersExternal)),e.set(q.LIST_ROLES,new J(Ap.default.listRoles)),e.set(q.ADD_ROLE,new J(Ap.default.addRole)),e.set(q.ALTER_ROLE,new J(Ap.default.alterRole)),e.set(q.DROP_ROLE,new J(Ap.default.dropRole)),e.set(q.USER_INFO,new J(Qd.default.userInfo)),e.set(q.READ_LOG,new J(_W.default)),e.set(q.ADD_NODE,new J(gW.default)),e.set(q.UPDATE_NODE,new J(JC.default)),e.set(q.SET_NODE_REPLICATION,new J(JC.default)),e.set(q.REMOVE_NODE,new J(SW.default)),e.set(q.CONFIGURE_CLUSTER,new J(TW.default)),e.set(q.PURGE_STREAM,new J(RW.default)),e.set(q.SET_CONFIGURATION,new J(tP.default.setConfiguration)),e.set(q.CLUSTER_STATUS,new J(yW.default.clusterStatus)),e.set(q.CLUSTER_NETWORK,new J(AW.default)),e.set(q.CLUSTER_SET_ROUTES,new J(OT.default.setRoutes)),e.set(q.CLUSTER_GET_ROUTES,new J(OT.default.getRoutes)),e.set(q.CLUSTER_DELETE_ROUTES,new J(OT.default.deleteRoutes)),e.set(q.EXPORT_TO_S3,new J(Bs,XC.default.export_to_s3)),e.set(q.CREATE_CSR,new J(Yl.default.createCsr)),e.set(q.SIGN_CERTIFICATE,new J(Yl.default.signCertificate)),e.set(q.LIST_CERTIFICATES,new J(Yl.default.listCertificates)),e.set(q.ADD_CERTIFICATES,new J(Yl.default.addCertificate)),e.set(q.REMOVE_CERTIFICATE,new J(Yl.default.removeCertificate)),e.set(q.GET_KEY,new J(Yl.default.getKey)),e.set(q.ADD_NODE_BACK,new J(Vw)),e.set(q.REMOVE_NODE_BACK,new J(Kw)),e.set(q.DELETE_FILES_BEFORE,new J(Bs,Xd.default.deleteFilesBefore)),e.set(q.DELETE_RECORDS_BEFORE,new J(Bs,Xd.default.deleteFilesBefore)),e.set(q.EXPORT_LOCAL,new J(Bs,XC.default.export_local)),e.set(q.SEARCH_JOBS_BY_START_DATE,new J(LT.default.handleGetJobsByStartDate)),e.set(q.GET_JOB,new J(LT.default.handleGetJob)),e.set(q.GET_FINGERPRINT,new J(CT.default.getFingerprint)),e.set(q.SET_LICENSE,new J(CT.default.setLicense)),e.set(q.GET_REGISTRATION_INFO,new J(CT.default.getRegistrationInfo)),e.set(q.RESTART,new J(ZC.default.restart)),e.set(q.RESTART_SERVICE,new J(Bs,ZC.default.restartService)),e.set(q.CATCHUP,new J(k_e)),e.set(q.SYSTEM_INFORMATION,new J(NW.default.systemInformation)),e.set(q.DELETE_AUDIT_LOGS_BEFORE,new J(Bs,Xd.default.deleteAuditLogsBefore)),e.set(q.READ_AUDIT_LOG,new J(EW.default)),e.set(q.CREATE_AUTHENTICATION_TOKENS,new J(_N)),e.set(q.REFRESH_OPERATION_TOKEN,new J(gN)),e.set(q.LOGIN,new J(qO)),e.set(q.LOGOUT,new J($O)),e.set(q.GET_CONFIGURATION,new J(tP.default.getConfiguration)),e.set(q.CUSTOM_FUNCTIONS_STATUS,new J(Mt.default.customFunctionsStatus)),e.set(q.GET_CUSTOM_FUNCTIONS,new J(Mt.default.getCustomFunctions)),e.set(q.GET_COMPONENT_FILE,new J(Mt.default.getComponentFile)),e.set(q.GET_COMPONENTS,new J(Mt.default.getComponents)),e.set(q.SET_COMPONENT_FILE,new J(Mt.default.setComponentFile)),e.set(q.DROP_COMPONENT,new J(Mt.default.dropComponent)),e.set(q.GET_CUSTOM_FUNCTION,new J(Mt.default.getCustomFunction)),e.set(q.SET_CUSTOM_FUNCTION,new J(Mt.default.setCustomFunction)),e.set(q.DROP_CUSTOM_FUNCTION,new J(Mt.default.dropCustomFunction)),e.set(q.ADD_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.addComponent)),e.set(q.ADD_COMPONENT,new J(Mt.default.addComponent)),e.set(q.DROP_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.dropCustomFunctionProject)),e.set(q.PACKAGE_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.packageComponent)),e.set(q.PACKAGE_COMPONENT,new J(Mt.default.packageComponent)),e.set(q.DEPLOY_CUSTOM_FUNCTION_PROJECT,new J(Mt.default.deployComponent)),e.set(q.DEPLOY_COMPONENT,new J(Mt.default.deployComponent)),e.set(q.READ_TRANSACTION_LOG,new J(rP.default.readTransactionLog)),e.set(q.DELETE_TRANSACTION_LOGS_BEFORE,new J(Bs,rP.default.deleteTransactionLogsBefore)),e.set(q.INSTALL_NODE_MODULES,new J(nP.default.installModules)),e.set(q.AUDIT_NODE_MODULES,new J(nP.default.auditModules)),e.set(q.GET_BACKUP,new J(Ai.default.getBackup)),e.set(q.CLEANUP_ORPHAN_BLOBS,new J(Ai.default.cleanupOrphanBlobs)),e.set(q.ADD_SSH_KEY,new J(Mt.default.addSSHKey)),e.set(q.UPDATE_SSH_KEY,new J(Mt.default.updateSSHKey)),e.set(q.DELETE_SSH_KEY,new J(Mt.default.deleteSSHKey)),e.set(q.LIST_SSH_KEYS,new J(Mt.default.listSSHKeys)),e.set(q.SET_SSH_KNOWN_HOSTS,new J(Mt.default.setSSHKnownHosts)),e.set(q.GET_SSH_KNOWN_HOSTS,new J(Mt.default.getSSHKnownHosts)),e.set(q.GET_ANALYTICS,new J(eC)),e.set(q.LIST_METRICS,new J(tC)),e.set(q.DESCRIBE_METRIC,new J(rC)),e.set(q.GET_STATUS,new J(aC)),e.set(q.SET_STATUS,new J(cC)),e.set(q.CLEAR_STATUS,new J(oC)),e}var Jd,PT,Rp,Ai,yp,Xd,EW,Qd,Ap,Mt,bp,_W,gW,JC,SW,TW,RW,yW,AW,OT,XC,bW,LT,Fs,CT,ZC,sP,Wl,IW,NW,eP,tP,rP,nP,wW,OW,Yl,CW,PW,hW,gn,B_e,F_e,H_e,pW,JO=ce(()=>{Jd=w(nn()),PT=w(mT()),Rp=w(qC()),Ai=w(wh()),yp=w(Ca()),Xd=w(Xc()),EW=w(gw()),Qd=w(Xn()),Ap=w(jm()),Mt=w(jO()),bp=w(Q()),_W=w(Aw()),gW=w(RS()),JC=w(Qw()),SW=w(AS()),TW=w(Zw()),RW=w(eO()),yW=w(nO()),AW=w(iO()),OT=w(OS()),XC=w(KC()),bW=w(dT()),LT=w(zC());k();Fs=w(ge()),CT=w(gO()),ZC=w(kd()),sP=w(require("util")),Wl=w(Cn()),IW=w(ni()),NW=w(bd()),eP=w(uW());ed();jS();tP=w(wt()),rP=w(nT()),nP=w(tp()),wW=w(Zs()),OW=w(ie());Dr();Yl=w(ss());Nd();sC();CW=w(LC()),PW=w(fW());dp();mW();({HTTP_STATUS_CODES:hW}=Fs.hdbErrors),gn=bp.default.loggerWithTag("operation"),B_e=sP.promisify(Jd.default.search),F_e=sP.promisify(PT.default.evaluateSQL),H_e={[q.CREATE_ATTRIBUTE]:!0,[q.CREATE_TABLE]:!0,[q.CREATE_SCHEMA]:!0,[q.DROP_ATTRIBUTE]:!0,[q.DROP_TABLE]:!0,[q.DROP_SCHEMA]:!0};o(LW,"processLocalTransaction");pW=G_e();Le.operation=iP;o(DW,"chooseOperation");o(MW,"getOperationFunction");(0,wW._assignPackageExport)("operation",iP);o(iP,"operation");o(k_e,"catchup");o(Bs,"executeJob");o(G_e,"initializeOperationFunctionMap")});var vT=M((k0e,xW)=>{"use strict";var DT=(k(),v(W)),q_e=ie(),Ip=Q(),{handleHDBError:oP,hdbErrors:MT}=ge(),{isMainThread:$_e}=require("worker_threads"),{Readable:V_e}=require("stream"),vW=require("os"),K_e=require("util"),Y_e=TN(),W_e=K_e.promisify(Y_e.authorize),UW=(JO(),v(QO)),{createGzip:z_e,constants:j_e}=require("zlib"),Q_e=[DT.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,DT.OPERATIONS_ENUM.LOGIN,DT.OPERATIONS_ENUM.LOGOUT];function J_e(e){let t=`Found an uncaught exception with message: ${e.message}. ${vW.EOL}Stack: ${e.stack} ${vW.EOL}Terminating ${$_e?"HDB":"thread"}.`;console.error(t),Ip.fatal(t),process.exit(1)}o(J_e,"handleServerUncaughtException");function X_e(e,t,r){if(Ip[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:MT.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(X_e,"serverErrorHandler");function Z_e(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=oP(new Error,"Invalid JSON.",MT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(q_e.isEmpty(e.body.operation)){let n=oP(new Error,"Request body must include an 'operation' property.",MT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}o(Z_e,"reqBodyValidationHandler");function ege(e,t,r){let n;!Q_e.includes(e.body.operation)||e.body.operation===DT.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&!e.body.username&&!e.body.password?W_e(e,t).then(i=>{n=i,e.body.hdb_user=n,r()}).catch(i=>{Ip.warn(i),Ip.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${i.stack}"`);let a=typeof i=="string"?{error:i}:{error:i.message};r(oP(i,a,MT.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(ege,"authHandler");async function tge(e,t,r=!1){let n;try{e.body.bypass_auth&&delete e.body.bypass_auth,n=UW.chooseOperation(e.body);let s=await UW.processLocalTransaction(e,n);if(s instanceof V_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(z_e({level:j_e.Z_BEST_SPEED})))}return s}catch(s){throw Ip.error(s),s}}o(tge,"handlePostRequest");xW.exports={authHandler:ege,handlePostRequest:tge,handleServerUncaughtException:J_e,serverErrorHandler:X_e,reqBodyValidationHandler:Z_e}});var kW=M((q0e,HW)=>{"use strict";var rge=require("fastify-plugin"),{handlePostRequest:BW,authHandler:nge,reqBodyValidationHandler:sge}=vT();async function ige(e){e.decorate("hdbCore",{preValidation:[sge,nge],request:o((t,r)=>FW(BW(t,r)),"request"),requestWithoutAuthentication:o((t,r)=>FW(BW(t,r,!0)),"requestWithoutAuthentication")})}o(ige,"hdbCore");async function FW(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(FW,"convertAsyncIterators");HW.exports=rge(ige)});var qW=M((K0e,GW)=>{"use strict";var V0e=require("fs"),UT=oe();UT.initSync();var{CONFIG_PARAMS:aP}=(k(),v(W)),oge=1024*1024*1024;function age(e){let t=UT.get(aP.HTTP_TIMEOUT),r=UT.get(aP.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:oge,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,maxParamLength:UT.get(aP.HTTP_MAXPARAMLENGTH)??1e3,https:e}}o(age,"getServerOptions");GW.exports=age});var KW=M((W0e,VW)=>{"use strict";var cP=oe();cP.initSync();var{CONFIG_PARAMS:$W}=(k(),v(W));function cge(){let e=cP.get($W.HTTP_CORSACCESSLIST),t=cP.get($W.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(cge,"getCORSOptions");VW.exports=cge});var zW=M((j0e,WW)=>{"use strict";var YW=oe();YW.initSync();var lge=(k(),v(W));function uge(){return YW.get(lge.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}o(uge,"getHeaderTimeoutConfig");WW.exports=uge});var uP={};we(uP,{customFunctionsServer:()=>mge,ready:()=>cz,start:()=>fge});function fge(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Qo||(Qo=az(t),Le.http((await Qo).server));let a=await Qo,c=(0,lP.dirname)(s),l=(0,lP.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!jW.has(c)){jW.add(c);try{a.register(pge(c,l))}catch(u){if(u.message==="Root plugin has already booted")yt.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw u}}},ready:cz}}async function mge(){try{yt.info("In Custom Functions Fastify server"+process.cwd()),yt.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),yt.debug(`Custom Functions server process ${process.pid} starting up.`),await hge();let e=tz.get(U.HTTP_SECUREPORT)>0,t;try{t=Qo=await az(e)}catch(r){throw yt.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw yt.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){yt.error(`Custom Functions ${process.pid} Error: ${e}`),yt.error(e),process.exit(1)}}async function hge(){try{yt.info("Custom Functions starting configuration."),await rz.setUsersWithRolesCache(),yt.info("Custom Functions completed configuration.")}catch(e){yt.error(e)}}function pge(e,t){return async function(r){try{yt.info("Custom Functions starting buildRoutes"),yt.trace("Loading fastify routes folder "+e),(0,QW.existsSync)(e)&&r.register(ez.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:yt.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,a)=>{s?.message?yt.error(s.message):s&&yt.error(s),a()})}catch(n){yt.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function az(e){yt.info("Custom Functions starting buildServer.");let t=(0,nz.default)(e),r=(0,JW.default)(t);r.server.headersTimeout=(0,iz.default)(),r.setErrorHandler(oz.serverErrorHandler);let n=(0,sz.default)();return n&&r.register(XW.default,n),r.register(function(s,i,a){s.setNotFoundHandler(function(c,l){l.sent||l.raw.headersSent||l.raw.writableEnded||r.server.emit("unhandled",c.raw,l.raw)}),a()}),r.register(ZW.default),await r.register(dge),await r.after(),dm(r),yt.info("Custom Functions completed buildServer."),r}function cz(){if(Qo)return Qo.then?Qo.then(e=>e.ready()):Qo.ready()}var lP,QW,JW,XW,ZW,ez,tz,yt,dge,rz,nz,sz,iz,oz,Qo,jW,lz=ce(()=>{lP=require("path"),QW=require("fs"),JW=w(require("fastify")),XW=w(require("@fastify/cors")),ZW=w(mN()),ez=w(require("@fastify/autoload")),tz=w(oe());k();yt=w(Q()),dge=w(kW()),rz=w(Xn()),nz=w(qW()),sz=w(KW()),iz=w(zW()),oz=w(vT());To();Dr();jW=new Set;o(fge,"start");o(mge,"customFunctionsServer");o(hge,"setUp");o(pge,"buildRouteFolder");o(az,"buildServer");o(cz,"ready")});var dP={};we(dP,{start:()=>Ege});function Ege(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,hz.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){dz||(dz=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let a=uz.get(s.pathname);if(a)return{handlesHeaders:!0,body:(0,fz.default)(s,(0,mz.realpathSync)(a))}}return i(s)},{runFirst:!0})),uz.set(r,n)}}}var fz,mz,hz,uz,dz,pz=ce(()=>{fz=w(require("send")),mz=require("fs"),hz=w(require("serve-static")),uz=new Map;o(Ege,"start")});var fP={};we(fP,{start:()=>_ge});function _ge({override:e}){return{handleFile:o((t,r,n)=>{xT.default.debug(`Loading env file: ${n}`);for(let[s,i]of Object.entries((0,Ez.parse)(t))){if(process.env[s]!==void 0)if(xT.default.warn(`Environment variable conflict: ${s} from ${n} is already set on process.env`),e)xT.default.debug(`override option enabled. overriding environment variable: ${s}`);else continue;process.env[s]=i}},"handleFile")}}var Ez,xT,_z=ce(()=>{Ez=require("dotenv"),xT=w(Q());o(_ge,"start")});var pP={};we(pP,{DataLoaderError:()=>us,DataLoaderResult:()=>Zd,EmptyFileError:()=>kT,FileParseError:()=>HT,InvalidPropertyTypeError:()=>GT,MissingRequiredPropertyError:()=>Np,RecordProcessingError:()=>wp,SystemDatabaseError:()=>qT,UnsupportedFileExtensionError:()=>FT,computeRecordHash:()=>hP,handleApplication:()=>Tge,loadDataFile:()=>Iz,suppressHandleApplicationWarning:()=>Sge});function hP(e){let t=Object.keys(e).sort(),r={};for(let s of t)r[s]=e[s];let n=JSON.stringify(r);return(0,Sz.createHash)("sha256").update(n).digest("hex")}function bz(e){return e.system&&e.system[mP]?e.system[mP]:BT||(BT=ze({database:"system",table:mP,attributes:[{name:"id",type:"string",isPrimaryKey:!0},{name:"hash",type:"string"}]}),BT)}async function gge(e,t,r,n){try{let s=bz(n),i=e?`${e}:${t}:${r}`:`${t}:${r}`;return(await s.get(i))?.hash||null}catch(s){return Hs.error?.(`Failed to get stored hash: ${s.message}`),null}}async function gz(e,t,r,n,s){try{let i=bz(s),a=e?`${e}:${t}:${r}`:`${t}:${r}`;await i.put({id:a,hash:n})}catch(i){Hs.error?.(`Failed to store hash: ${i.message}`)}}function Tge(e){if((0,Rz.getWorkerIndex)()!==0){Hs.debug?.("Skipping data loader initialization on non-primary worker");return}e.handleEntry(t=>{t.entryType!=="file"||t.eventType==="unlink"||Iz(t,ln,He).then(r=>{Hs.debug?.("Data loader processed file: %s: %s",(0,Jo.basename)(t.absolutePath),r.message)})})}async function Iz({contents:e,absolutePath:t,stats:r},n,s){let i=(0,Jo.extname)(t)||"unknown",a;try{if(i===".yaml"||i===".yml")a=(0,Tz.parseDocument)(e.toString()).toJSON();else if(i===".json")a=JSON.parse(e.toString());else throw new FT(t,i)}catch(f){throw f instanceof us?f:new HT(t,f)}if(!a)throw new kT(t);let{database:c,table:l,records:u}=a;if(!l)throw new Np(t,"table");if(!u)throw new Np(t,"records");if(!Array.isArray(u))throw new GT(t,"records","array");let d=c?`${c}.${l}`:l;if(c?.toLowerCase()==="system")throw new qT(c,l);try{let f;if(c&&s[c]&&s[c][l])Hs.debug?.(`Using existing table ${d} from database tables`),f=s[c][l];else if(n&&n[l])Hs.debug?.(`Using existing table ${d} from global tables`),f=n[l];else{Hs.debug?.(`Table ${d} not found, creating new table`);let R=[];if(u.length>0){let T=u[0];Object.keys(T).map(y=>{let N={name:y,type:typeof T[y]};return y==="id"&&(N.isPrimaryKey=!0),N}).forEach(y=>{R.push(y)})}f=await ze({database:c,table:l,attributes:R})}let m=u.length,h=0,p=0,_=0,g=100;for(let R=0;R<u.length;R+=g){let T=u.slice(R,R+g),y=[];for(let N of T)y.push(async()=>{try{let O=null,F=N.id;F!==void 0&&(O=await f.get(F));let Z=hP(N);if(!O){h++;let $=await f.put(N);return await gz(c,l,F,Z,s),$}let G=await gge(c,l,F,s);if(!G)return _++,Promise.resolve({inserted:0,updated:0});let Y={};for(let $ of Object.keys(N))$ in O&&(Y[$]=O[$]);return hP(Y)!==G?(_++,Promise.resolve({inserted:0,updated:0})):Z!==G?(p++,await f.patch(F,N),await gz(c,l,F,Z,s),{updated:1}):(_++,Promise.resolve({inserted:0,updated:0}))}catch(O){if(O instanceof us)Hs.error?.(`Record processing error: ${O.message}`);else{let F=new wp(d,O);Hs.error?.(`Record processing error: ${F.message}`)}return Promise.resolve({inserted:0,updated:0,error:O.message})}});await Promise.all(y.map(N=>N()))}if(h>0||p>0){let R=`Loaded ${h} new and updated ${p} records in ${d}`;return _>0&&(R+=` (${_} records skipped)`),Hs.info?.(R),new Zd(t,c,l,"success",h+p,R)}else if(_>0){let R=`All ${_} records in ${d} already up-to-date`;return Hs.info?.(R),new Zd(t,c,l,"skipped",m,R)}else{let R=`No records to process in ${d}`;return Hs.info?.(R),new Zd(t,c,l,"success",0,R)}}catch(f){throw f instanceof us?f:new wp(d,f)}}var Jo,Sz,Tz,Rz,Xo,yz,Az,Hs,mP,BT,Sge,us,FT,HT,kT,Np,GT,qT,wp,Zd,Nz=ce(()=>{Jo=require("node:path"),Sz=require("node:crypto"),Tz=require("yaml");Me();Rz=w(nt()),Xo=w(tn()),yz=w(ge()),Az=w(Q()),Hs=Az.default.forComponent("dataLoader"),mP="hdb_dataloader_hash";o(hP,"computeRecordHash");o(bz,"getHashTrackingTable");o(gge,"getStoredHash");o(gz,"storeHash");Sge=!0;o(Tge,"handleApplication");o(Iz,"loadDataFile");us=class extends yz.ClientError{static{o(this,"DataLoaderError")}constructor(t,r=Xo.HTTP_STATUS_CODES.BAD_REQUEST){super(t,r),this.name="DataLoaderError"}},FT=class extends us{static{o(this,"UnsupportedFileExtensionError")}constructor(t,r){super(`Unsupported file extension in ${(0,Jo.basename)(t)}: ${r}. Only YAML and JSON files are supported.`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="UnsupportedFileExtensionError"}},HT=class extends us{static{o(this,"FileParseError")}constructor(t,r){super(`Failed to parse data file ${(0,Jo.basename)(t)}: ${r.message}`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="FileParseError"}},kT=class extends us{static{o(this,"EmptyFileError")}constructor(t){super(`Data file ${(0,Jo.basename)(t)} is empty or invalid`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="EmptyFileError"}},Np=class extends us{static{o(this,"MissingRequiredPropertyError")}constructor(t,r){super(`Data file ${(0,Jo.basename)(t)} is missing required "${r}" property`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="MissingRequiredPropertyError"}},GT=class extends us{static{o(this,"InvalidPropertyTypeError")}constructor(t,r,n){super(`Data file ${(0,Jo.basename)(t)} has invalid "${r}" property, expected ${n}`,Xo.HTTP_STATUS_CODES.BAD_REQUEST),this.name="InvalidPropertyTypeError"}},qT=class extends us{static{o(this,"SystemDatabaseError")}constructor(t,r){super(`Cannot load data into system database: ${t}.${r}`,Xo.HTTP_STATUS_CODES.FORBIDDEN),this.name="SystemDatabaseError"}},wp=class extends us{static{o(this,"RecordProcessingError")}constructor(t,r){super(`Failed to process record in ${t}: ${r.message}`,Xo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="RecordProcessingError"}},Zd=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 xz={};we(xz,{startHTTPThreads:()=>yge,startSocketServer:()=>TP,updateWorkerIdleness:()=>Uz});async function yge(e=2,t){tN().catch(r=>sf.error?.("Error recording hostname for analytics:",r));try{if(t)gP(0,1,!0);else{let{loadRootComponents:r}=YT();if(e===0)return(0,ks.setMainIsWorker)(!0),await AP().startServers(),Promise.resolve([]);await r()}vz();for(let r=0;r<e;r++)gP(r,e);return Promise.all(Mz)}finally{(0,ks.threadsHaveStarted)()}}function vz(){let e=(0,Pz.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),_P=setInterval(()=>{sf.notify(e)},Rge).unref())}function gP(e,t=1,r){if(EP++,(0,ks.startWorker)("server/threads/threadServer.js",{name:Zy.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((a,c)=>{function l(u){u.type===jy.CHILD_STARTED&&(n.removeListener("message",l),a(n))}o(l,"onMessage"),n.on("message",l),n.on("error",c)});Mz.push(s),await s,ef.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",a=>{if(a.requestId){let c=VT.get(a.requestId);c&&c(a)}}),n.on("exit",i),n.on("shutdown",i);function i(){let a=ef.indexOf(n);a>-1&&ef.splice(a,1)}if(o(i,"removeWorker"),tf){let a=tf;tf=[];for(let c of a)Dz[c.localPort](null,c)}}}),r){let n=setInterval(()=>{SP?SP=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ks.shutdownWorkers)(),EP=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function TP(e=0,t){if(typeof e=="string")try{(0,KT.existsSync)(e)&&(0,KT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Age:r=bge(t):r=RP;let n=(0,rf.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=Dz[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),SP=!0,r(i,(a,c)=>{if(!a){if(wz){let u=i._socket||new rf.Socket({handle:i,writable:!0,readable:!0});wz.deliverSocket(u,e,c),u.resume()}else EP>0?(tf.length===0&&setTimeout(()=>{tf.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,tf.push(i)):(console.log("start up a dynamic thread to handle request"),gP(0));it(!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 rf.Socket({handle:i,writable:!0,readable:!0});wge(u,a,e)}it(!0,"socket-routed")})},sf.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 RP(e,t){let r,n=0;for(let s of ef){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=$T)return $T=i,t(r);n=i}$T=0,t(r)}function Age(e,t){let r={};e.getpeername(r);let n=r.address,s=nf.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);RP(e,a=>{nf.set(n,{worker:a,lastUsed:i}),t(a)})}function bge(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new rf.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=nf.get(l),d=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=d,s(u.worker);RP(n,f=>{nf.set(l,{worker:f,lastUsed:d}),s(f,a)})})}o(r,"findByHeaderAffinity")}function Uz(){$T=0;for(let e of ef)e.expectedIdle=e.recentELU.idle+Ige,e.requests=1;ef.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function wge(e,t,r){let n=Nge++;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(),VT.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")),VT.delete(n)),s.event=="destroy"&&(e.destroy(),VT.delete(n))})}var ks,rf,sf,KT,Cz,Pz,Lz,ef,tf,Dz,wz,EP,Mz,_P,Rge,SP,$T,Oz,nf,Ige,VT,Nge,yP=ce(()=>{ks=w(nt()),rf=require("net");k();sf=w(Q()),KT=require("fs");Yi();Cz=require("worker_threads"),Pz=w(Dd()),Lz=w(bt()),ef=[],tf=[],Dz=[],EP=0,Mz=[];Cz.isMainThread&&(process.on("uncaughtException",e=>{e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ks.onMessageFromWorkers)(e=>{e.type===Xy.RESTART&&_P&&(clearInterval(_P),vz())}));Rge=6e5;o(yge,"startHTTPThreads");o(vz,"licenseWarning");o(gP,"startHTTPWorker");o(TP,"startSocketServer");$T=0;o(RP,"findMostIdleWorker");Oz=36e5,nf=new Map;o(Age,"findByRemoteAddressAffinity");o(bge,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of nf)r.lastUsed+Oz<e&&nf.delete(t)},Oz).unref();Ige=1e3;o(Uz,"updateWorkerIdleness");(0,ks.setMonitorListener)(Uz);VT=new Map,Nge=1;o(wge,"proxySocket")});var bP={};we(bP,{hdbServer:()=>Lge,start:()=>Lge});async function Lge(e){try{to.default.debug("In Fastify server"+process.cwd()),to.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),to.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Bz.default.isMaster,await Dge();let t=e.securePort>0;of=Mge(t),await of.ready(),e||(e={}),e.isOperationsServer=!0;try{Le.http(of.server,e),of.server.closeIdleConnections||await of.listen({port:0,host:"::"})}catch(r){throw of.close(),to.default.error(r),to.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),to.default.fatal(t),process.exit(1)}}async function Dge(){to.default.trace("Configuring HarperDB process."),Kz.default.setSchemaDataToGlobal(),await Wz.default.setUsersWithRolesCache(),await zz.default.getLicense()}function Mge(e){to.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=vge(e),r=(0,Fz.default)(t);r.server.headersTimeout=xge(),r.setErrorHandler(uc.serverErrorHandler);let n=Uge();n&&r.register(Hz.default,n),r.register(function(i,a,c){i.setNotFoundHandler(function(l,u){u.sent||u.raw.headersSent||u.raw.writableEnded||r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(qz.default),r.register(kz.default),r.register(Gz.default,{root:$z.default.join(Vz.PACKAGE_ROOT,"studio/build-local")}),dm(r);let s=lc.default.get(zy.LOCAL_STUDIO_ON);return r.get("/",function(i,a){return!Yz.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?a.sendFile("index.html"):a.sendFile("running.html")}),r.post("/",{preValidation:[uc.reqBodyValidationHandler,uc.authHandler],config:{isOperation:!0}},async function(i,a){return i.body?.operation?.startsWith("restart")&&a.header("Connection","close"),(0,uc.handlePostRequest)(i,a)}),r.get("/health",()=>"HarperDB is running."),to.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}function vge(e){let t=lc.default.get(Op.OPERATIONSAPI_NETWORK_TIMEOUT),r=lc.default.get(Op.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Cge,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}function Uge(){let e=lc.default.get(Op.OPERATIONSAPI_NETWORK_CORS),t=lc.default.get(Op.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Pge)&&(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 xge(){return lc.default.get(Op.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Oge}var Bz,lc,to,Fz,Hz,kz,Gz,qz,$z,Vz,Kz,Yz,Wz,zz,uc,Oge,Cge,Pge,Op,of,jz=ce(()=>{Bz=w(require("cluster")),lc=w(oe());k();to=w(Q()),Fz=w(require("fastify")),Hz=w(require("@fastify/cors")),kz=w(require("@fastify/compress")),Gz=w(require("@fastify/static")),qz=w(mN()),$z=w(require("path")),Vz=w(bt()),Kz=w(ni()),Yz=w(ie()),Wz=w(Xn()),zz=w(Dd());Dr();uc=w(vT());To();lc.default.initSync();Oge=6e4,Cge=1024*1024*1024,Pge="TRUE",{CONFIG_PARAMS:Op}=W;o(Lge,"operationsServer");o(Dge,"setUp");o(Mge,"buildServer");o(vge,"getServerOptions");o(Uge,"getCORSOpts");o(xge,"getHeaderTimeoutConfig")});var PP={};we(PP,{disableNATS:()=>Fge,publishToStream:()=>jT,setNATSReplicator:()=>IP,setPublishToStream:()=>Hge,setSubscription:()=>CP,start:()=>Bge});function Bge(){Cp.default.get(U.CLUSTERING_ENABLED)&&Gge()}function Fge(e=!0){ej=e}function Hge(e,t){jT=e,CP=t}function Gge(){if(ej||process.env._DISABLE_NATS)return;let e=st(),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];IP(s,r,i)}}Nl((r,n)=>{IP(r.tableName,r.databaseName,r),n&&rj(r)}),!Qz&&(Qz=!0)}function IP(e,t,r){if(t==="system"&&qge.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 Br{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){rj(i)}static subscribe(){let i=new Vn;return CP(t,e,i),i}static subscribeOnThisThread(i){return i<(Cp.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??kge)}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 WT(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=tj;return i}o(n,"getNATSTransaction")}function rj(e){let t=Cp.default.get(U.CLUSTERING_NODENAME);jT(`${wP.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,OP.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 Jz,wP,OP,Xz,Zz,Cp,zT,ej,jT,CP,kge,tj,Qz,qge,WT,NP,nj=ce(()=>{Me();xa();Jz=w(mr()),wP=w(Ot()),OP=w(ki());Ru();Xz=w(CN()),Zz=w(yn()),Cp=w(oe());k();zT=w(Q());o(Bge,"start");o(Fge,"disableNATS");jT=Jz.publishToStream,CP=Xz.setSubscription;o(Hge,"setPublishToStream");kge=2;o(Gge,"assignReplicationSource");qge=["hdb_job","hdb_raw_analytics","hdb_info","hdb_license"];o(IP,"setNATSReplicator");o(rj,"publishSchema");WT=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=Cp.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||(zT.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(jT(`${wP.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,OP.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(d=>{throw zT.error("An error has occurred trying to replicate transaction",l,d),d.statusCode=504,d}))}return Promise.all(n)}},NP=class extends WT{static{o(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,Zz.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};tj=new NP});async function cj({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let a=await LP.get(e,{returnNonexistent:!0});i=new vP(e,t,a),a&&(i.sessionWasPresent=!0)}else{if(e){let a=await LP.get(e);a&&a.delete()}i=new JT(e,t)}return n&&(n.id=e,n.user={username:t?.username},Pp.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function DP(){return QT++,QT>65500&&(QT=1),QT}function MP(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=ys.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 ui(i.relativeURL);a.checkPermission=r.user?.role?.permission??{};let c=i.Resource;return Ft(r,()=>s?t===void 0?c.delete(a,r):c.put(a,e.data,r):c.publish(a,e.data,r))}var ij,dc,oj,aj,sj,LP,Pp,QT,JT,vP,lj=ce(()=>{Me();Ou();ij=w(yn()),dc=w(Q());Bc();oj=w(nt()),aj=w(AP());Dr();lg();sj=100,LP=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"}]}}]}),Pp=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,oj.getWorkerIndex)()===0&&(async()=>{await aj.whenComponentsLoaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Pp.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Le.getUser(r.user.username));try{await MP(r,t,r)}catch{(0,dc.warn)("Failed to publish will",t)}Pp.delete(e.id)}})();o(cj,"getSession");QT=1;o(DP,"getNextMessageId");JT=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,dc.trace)("Resuming subscription from",s,"from",a);let h=ys.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 y=T.split("/"),N;for(let Z=0;Z<y.length;Z++)if(y[Z].indexOf("+")>-1)if(y[Z]==="+")N=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&N)throw new Error("Filters can not be combined");let O=!0;y[y.length-1]==="#"&&(y.length--,O=!1),N&&(n=o(Z=>{let G=Z.id;if(!Array.isArray(G))if(G?.indexOf?.("/")>-1)G=G.split("/");else return!1;if(O&&G.length!==y.length)return!1;for(let Y=0;Y<y.length;Y++)if(y[Y]!=="+"&&y[Y]!==G[Y])return!1;return!0},"filter"));let F=y.indexOf("+");m.url="/"+(F>-1?y.slice(0,F):y).concat("").join("/")}}else m.isCollection=!1;let _=h.path,g=h.Resource,R=await Ft(m,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i,T.isCollection=m.isCollection;let y=await g.subscribe(m,T);if(!y)return;if(!y[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let N=(async()=>{for await(let O of y)try{let F;if(O.type&&O.type!=="put"&&O.type!=="delete"&&O.type!=="message"&&O.type!=="patch"||n&&!n(O))continue;r?(O.topic=s,F=this.needsAcknowledge(O)):(O.acknowledge?.(),F=DP());let Z=O.id;if(Array.isArray(Z)&&(Z=wu(Z)),Z==null&&(Z=""),await this.listener(_+"/"+Z,O.value,F,t)===!1)break;this.awaitingAcks?.size>sj?await new Promise(Y=>setTimeout(Y,this.awaitingAcks.size-sj)):await new Promise(setImmediate)}catch(F){(0,dc.warn)(F)}})();return y});if(R)return R.topic=s,R.qos=t.qos,this.subscriptions.push(R),R}resume(){}needsAcknowledge(t){let r=DP();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 MP(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();Ft(r,async()=>{try{if(!t){let n=await Pp.get(this.sessionId);n?.doesExist()&&await MP(n,n.data,r)}}finally{await Pp.delete(this.sessionId)}}).catch(n=>{(0,dc.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(MP,"publish");vP=class extends JT{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=DP(),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,dc.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,ij.getNextMonotonicTime)()),(0,dc.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),LP.put(this.sessionRecord)}}});var UP={};we(UP,{bypassAuth:()=>$ge,start:()=>Kge});function $ge(){Ej=!0}function Kge({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new pj.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),ir.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:p}=dj(u,_=>{u.send(_)},d,Promise.resolve(f).then(()=>d?.user),a);u.on("message",h),u.on("close",p),u.on("error",_=>{ir.info?.("WebSocket error",_)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let d;if(a.events.emit("connection",u),ir.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,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ZT.notify?.({username:d?.username,status:Xs.SUCCESS,type:ya.AUTHENTICATION,authStrategy:"MQTT mTLS",remoteAddress:u.remoteAddress})}catch(p){throw(0,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ZT.error?.({username:h,status:Xs.FAILURE,type:ya.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:u.remoteAddress}),p}}else ir.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){a.events.emit("error",h,u),ir.error?.(h)}else if(l.required)return ir.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!d&&Vge(u.remoteAddress)&&(d=await(0,fj.getSuperUser)(),ir.debug?.("Auto-authorizing local connection",d?.username));let{onMessage:f,onClose:m}=dj(u,h=>u.write(h),null,d,a);u.on("data",f),u.on("close",m),u.on("error",h=>{ir.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function dj(e,t,r,n,s){uj||(uj=!0,Zm(f=>{XT>0&&f.push({metric:"mqtt-connections",connections:XT,byThread:!0})}));let i;XT++;let a,c={protocolVersion:4},l=(0,eR.parser)({protocolVersion:5});function u(f){l.parse(f)}o(u,"onMessage");function d(){XT--,i||(i=!0,a?.disconnect?.(),s.events.emit("disconnected",a,e),s.sessions.delete(a),Yr(!1,"connection","mqtt","disconnect"),ir.debug?.("MQTT connection was closed",e.remoteAddress))}return o(d,"onClose"),l.on("packet",async f=>{try{n?.then&&(n=await n)}catch(y){e.close?.(1008,"Unauthorized"),ir.info?.(y);return}let m=f.cmd;if(a)a.then&&await a;else if(m!=="connect"){ir.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;it(f.length,"bytes-received",_,R(f),"mqtt");try{switch(a?.receivedPacket?.(),m){case"connect":if(c.protocolVersion=f.protocolVersion,f.username)try{n=await Le.getUser(f.username,f.password.toString(),r),(0,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ZT.notify?.({username:n?.username,status:Xs.SUCCESS,type:ya.AUTHENTICATION,authStrategy:"MQTT",remoteAddress:e.remoteAddress})}catch(K){return(0,af.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ZT.error?.({username:f.username,status:Xs.FAILURE,type:ya.AUTHENTICATION,authStrategy:"mqtt",remoteAddress:e.remoteAddress}),s.events.emit("auth-failed",f,e,K),Yr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",f,e),Yr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(f,n),f.will){let K=e.deserialize||(e.deserialize=Ao(r?.headers.get?.("content-type")));f.will.data=f.will.payload?.length>0?K(f.will.payload):void 0,delete f.will.payload}a=cj({user:n,...f}),a=await a,a.socket=e,r&&(a.request=r),s.sessions.add(a)}catch(K){return ir.error?.(K),s.events.emit("auth-failed",f,e,K),Yr(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:K.code||5,returnCode:K.code||128})}s.events.emit("connected",a,e),Yr(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:a.sessionWasPresent,reasonCode:0,returnCode:0});let y=o(async(K,$,le,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",K);let se=K.indexOf("/",1),me=se>0?K.slice(0,se):K;g({cmd:"publish",topic:K,payload:await T($),messageId:le||Math.floor(Math.random()*1e8),qos:ue.qos},me);let Pe=e._socket??e;return Pe.writableNeedDrain?new Promise(De=>Pe.once("drain",De)):!Pe.closed}catch(se){return ir.error?.(se),a?.disconnect(),s.sessions.delete(a),!1}},"listener");a.setListener(y),a.sessionWasPresent&&await a.resume();break;case"subscribe":let N=[];for(let K of f.subscriptions){let $;try{let le=await a.addSubscription(K,K.qos>=1);$=le?le.qos||0:c.protocolVersion<5?128:143}catch(le){s.events.emit("error",le,e,K,a),le.statusCode?le.statusCode===500?ir.warn?.(le):ir.info?.(le):ir.error?.(le),$=c.protocolVersion<5?128:le.statusCode===403?135:le.statusCode===404?143:128}N.push($)}await a.committed,g({cmd:"suback",granted:N,messageId:f.messageId});break;case"unsubscribe":{let K=[];for(let $ of f.unsubscriptions)K.push(a.removeSubscription($)?0:17);g({cmd:"unsuback",granted:K,messageId:f.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:f.messageId,reasonCode:0});return;case"publish":let O=f.qos===2?"pubrec":"puback",F=e.deserialize||(e.deserialize=Ao(r?.headers.get?.("content-type"))),G=(f.payload?.length||0)>0?F(f.payload):void 0,Y;try{Y=await a.publish(f,G)}catch(K){s.events.emit("error",K,e,f,a),ir.warn?.(K),f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:128},f.topic);break}f.qos>0&&g({cmd:O,messageId:f.messageId,reasonCode:Y===!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),Yr(!0,"connection","mqtt","disconnect"),ir.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(y){s.events.emit("error",y,e,f,a),ir.error?.(y),g({cmd:"disconnect"})}function g(y,N){let O=(0,eR.generate)(y,c);t(O),it(O.length,"bytes-sent",N,R(y),"mqtt")}o(g,"sendPacket");function R(y){return y.qos>0?y.cmd+",qos="+y.qos:y.cmd}o(R,"packetMethodName");function T(y){return Na(y,r)}o(T,"serialize")}),l.on("error",f=>{ir.warn("MQTT parsing error, closing connection:",f.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:d}}var eR,fj,af,mj,hj,pj,ZT,ir,Ej,Vge,uj,XT,_j=ce(()=>{eR=require("mqtt-packet");lj();fj=w(Xn());To();Yi();Dr();af=w(oe());k();mj=w(ei()),hj=w(Q()),pj=require("events"),ZT=(0,mj.loggerWithTag)("auth-event"),ir=(0,hj.forComponent)("mqtt"),Ej=(0,af.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;o($ge,"bypassAuth");Vge=o(e=>Ej&&(e.includes("127.0.0.")||e==="::1"),"authorizeLocal");o(Kge,"start");XT=0;o(dj,"onSocket")});function tR(e,t){if(t?.includes(".."))throw new xP(t);let r=t||"/";return(r==="."||r.startsWith("./"))&&(r=`/${e}${r.slice(1)}`),r.startsWith("/")||(r=`/${r}`),r.endsWith("/")||(r=`${r}/`),r}var xP,BP=ce(()=>{xP=class extends Error{static{o(this,"InvalidBaseURLPathError")}constructor(t){super(`urlPath must not contain '..'. Received: '${t}'`)}};o(tR,"resolveBaseURLPath")});function gj(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 Sj=ce(()=>{o(gj,"deriveCommonPatternBase")});function rR(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 FP=ce(()=>{o(rR,"deriveGlobOptions")});var Tj,HP,Lp,Rj=ce(()=>{BP();Sj();FP();Tj=require("micromatch"),HP=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"}},Lp=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=tR(this.name,this.config.urlPath),this.globOptions=rR(this.config.files),this.globOptions.source=this.globOptions.source.map(s=>{if(s.includes("..")||s.startsWith("/"))throw new HP(s);return s==="."||s==="./"?"**/*":s}),this.patternBases=this.globOptions.source.map(s=>(0,Tj.scan)(s).base),this.commonPatternBase=gj(this.patternBases)}}});function yj(e,t){return new RegExp(`^${e}(/|$)`).test(t)}function zl(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(yj(n,t)){t=t.slice(n.length+1);break}}if(r==="directory"){if(t===n){t="";break}else if(yj(n,t)){t=t.slice(n.length+1);break}}}return(0,Aj.join)(e.baseURLPath,t)}var Aj,kP=ce(()=>{Aj=require("node:path");o(yj,"pathStartsWithBase");o(zl,"deriveURLPath")});function bj(e){return typeof e=="string"||Array.isArray(e)||!("files"in e)?{files:e}:e}var sR,Ij,Nj,GP,wj,Oj,nR,Cj=ce(()=>{sR=require("node:events");Rj();Ij=w(Q()),Nj=w(require("chokidar")),GP=require("node:path"),wj=require("node:fs/promises");kP();Oj=require("micromatch"),nR=class extends sR.EventEmitter{static{o(this,"EntryHandler")}#e;#t;#r;ready;constructor(t,r,n,s){super(),this.#e=new Lp(t,r,bj(n)),this.#r=s||Ij.default.loggerWithTag(t),this.ready=(0,sR.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,GP.join)(this.directory,r);switch(t){case"add":case"change":{let i=zl(this.#e,r,"file");(0,wj.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=zl(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=zl(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,GP.join)(this.#e.directory,r));return this.#t=Nj.default.watch(this.#e.commonPatternBase,{cwd:this.#e.directory,persistent:!1,ignored:o(r=>{let n=r.replace(/\\/g,"/"),s=t.map(i=>i.replace(/\\/g,"/"));return n!==this.#e.directory.replace(/\\/g,"/")&&s.every(i=>!n.startsWith(i))},"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 Lp(this.name,this.directory,bj(t)),this.#a()}};o(bj,"castConfig")});var iR,qP=ce(()=>{iR={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js"},static:{files:"web/**"}}});var aR,Pj,Lj,Dj,Mj,vj,$P,VP,KP,YP,WP,oR,Uj=ce(()=>{aR=require("events"),Pj=w(require("yaml")),Lj=w(require("chokidar")),Dj=require("node:fs/promises"),Mj=require("util"),vj=w(Q());qP();$P=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"}},VP=class extends Error{static{o(this,"InvariantUninitializedOptionsWatcherError")}constructor(){super("Invariant: OptionsWatcher has not been initialized yet. This should never happen."),this.name="InvariantUninitializedOptionsWatcherError"}},KP=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"}},YP=class extends Error{static{o(this,"KeyDoesNotExistError")}constructor(t,r){super(`Cannot set property ${t.join(".")} as ${r} does not exist.`),this.name="KeyDoesNotExistError"}},WP=class extends Error{static{o(this,"CannotSetPropertyError")}constructor(t){super(`Cannot set property ${t.join(".")} as parent is not an object.`),this.name="CannotSetPropertyError"}},oR=class extends aR.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||vj.default.loggerWithTag(t),this.ready=(0,aR.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,Dj.readFile)(this.#e,"utf-8").then(t=>{this.#n=Pj.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 $P(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=iR,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,Mj.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 VP;if(!["object","string","array","number","boolean","undefined"].includes(typeof r))throw new KP(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 YP(t,s);n=n[s]}if(n==null||typeof n!="object")throw new WP(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 xj(){Wge[0]=1}var Yge,Wge,Bj=ce(()=>{dp();Yge=zo.primaryStore.getUserSharedBuffer("restart-needed",new ArrayBuffer(1)),Wge=new Uint8Array(Yge);o(xj,"requestRestart")});var uR,Fj,cR,lR,Hj=ce(()=>{uR=require("node:events");Cj();Uj();Fj=w(Q());Bj();cR=class extends Error{static{o(this,"MissingDefaultFilesOptionError")}constructor(){super("No default files option exists. Ensure `files` is specified in config.yaml"),this.name="MissingDefaultFilesOptionError"}},lR=class extends uR.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=Fj.default.forComponent(this.#r),this.resources=s,this.server=i,this.#s=[],this.ready=(0,uR.once)(this,"ready"),this.options=new oR(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 nR(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{files:t.files,urlPath:t.urlPath}}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 cR);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 cR);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}`),xj()}}});function jl(e){return typeof e=="string"&&e.trim()!==""}function zP(e){return Array.isArray(e)&&e.length!==0&&e.every(t=>jl(t))}function $j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function zge(e){e.config.root&&Dp.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 tL(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($j(e.config.files)&&e.config.files.only==="files")return!1;t=e.patternBases}let s=!1;for(let i of t){let a=(0,Mp.join)(e.directory,i);dR.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 Vj(e){let t=!1;if(t=await zge(e),t)return t;let r=await(0,kj.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,Mp.join)(e.directory,n.path);if(n.dirent.isDirectory()){let i=zl(e,n.path,"directory");dR.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=zl(e,n.path,"file"),a=await(0,Gj.readFile)(s);dR.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 Dp.default.error(`Entry received from glob pattern match for component ${e.name} is neither a file nor a directory:`,n)}return t}var dR,kj,Dp,Mp,Gj,qj,fR,bi,jP,QP,JP,XP,ZP,eL,tL,rL,nL,Kj=ce(()=>{dR=require("node:worker_threads"),kj=w(require("fast-glob")),Dp=w(Q());BP();FP();Mp=require("node:path"),Gj=require("node:fs/promises");kP();qj=require("micromatch"),fR=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,!jl(this.config.files)&&!zP(this.config.files)&&!$j(this.config.files))throw new jP(this);if(typeof this.config.files=="object"&&!Array.isArray(this.config.files)){if(this.config.files.source===void 0||!zP(this.config.files.source)&&!jl(this.config.files.source))throw new QP(this);if(this.config.files.only!==void 0&&(typeof this.config.files.only!="string"||!["all","files","directories"].includes(this.config.files.only)))throw new JP(this);if(this.config.files.ignore!==void 0&&!zP(this.config.files.ignore)&&!jl(this.config.files.ignore))throw new XP(this)}if(this.config.root!==void 0&&!jl(this.config.root))throw new eL(this);if(this.config.path!==void 0&&!jl(this.config.path))throw new rL(this);if(this.config.path&&(Dp.default.warn("Resource extension 'path' option is deprecated. Please replace with 'urlPath'."),this.config.urlPath=this.config.path),this.config.urlPath!==void 0&&(!jl(this.config.urlPath)||typeof this.config.urlPath=="string"&&this.config.urlPath.includes("..")))throw new nL(this);this.globOptions=rR(this.config.files),this.globOptions.source=this.globOptions.source.map(r=>{if(r.includes(".."))throw new ZP(this,r);return r.startsWith("/")&&(Dp.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,qj.scan)(r).base),this.baseURLPath=tR(this.name,this.config.urlPath)}},bi=class extends Error{static{o(this,"ComponentV1ProcessingError")}constructor(t,r){super(`Component ${r.name} (from ${(0,Mp.basename)(r.directory)}) ${t}`)}},jP=class extends bi{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)}},QP=class extends bi{static{o(this,"InvalidFilesSourceOptionError")}constructor(t){super("'files' object must have a non-empty 'source' property.",t)}},JP=class extends bi{static{o(this,"InvalidFilesOnlyOptionError")}constructor(t){super("'files.only' option must be one of 'all', 'files', or 'directories'.",t)}},XP=class extends bi{static{o(this,"InvalidFileIgnoreOptionError")}constructor(t){super("'files.ignore' option must be a non-empty string or an array of non-empty strings.",t)}},ZP=class extends bi{static{o(this,"InvalidGlobPattern")}constructor(t,r){super(`'files' glob pattern must not contain '..'. Received: '${r}'`,t)}},eL=class extends bi{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)}},tL=class extends bi{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)}},rL=class extends bi{static{o(this,"InvalidPathOptionError")}constructor(t){super("deprecated 'path' option must be a non-empty string. Consider replacing with 'urlPath'.",t)}},nL=class extends bi{static{o(this,"InvalidURLPathOptionError")}constructor(t){super("'urlPath' option must be a non-empty string that must not contain '..'.",t)}};o(jl,"isNonEmptyString");o(zP,"isArrayOfNonEmptyStrings");o($j,"isObject");o(zge,"handleRoots");o(Vj,"processResourceExtensionComponent")});var Yj={};we(Yj,{SERVERS:()=>cf,portServer:()=>sL,setPortServerMap:()=>mR});function mR(e,t){let r=sL.get(e)??[];sL.set(e,[...r,t])}var cf,sL,iL=ce(()=>{cf={},sL=new Map;o(mR,"setPortServerMap")});function hR(e,t,r=Qge){let n;return function(...i){return n?n.length*oL>r?t(...i):new Promise((a,c)=>{n.push({args:i,fn(){try{let l=e(...i);a(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,a){setImmediate(()=>{let c=performance.now();oL=(oL*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var jj,jge,Qge,Wj,Jge,aL,zj,oL,cL=ce(()=>{jj=w(ei()),jge=3e3,Qge=2e4,Wj=0,Jge=3e4,aL=3e3,zj=performance.now()+aL,oL=0;o(hR,"throttle");setInterval(()=>{let e=performance.now();e-zj-aL>jge&&Wj+Jge<e&&(jj.default.warn?.("JavaScript execution has taken too long and is not allowing proper event queue cycling, consider using 'await new Promise(setImmediate)' in code that will execute for a long duration"),Wj=e),zj=e},aL).unref()});var TR={};we(TR,{deliverSocket:()=>c2,getHttpOptions:()=>tSe,getRequestId:()=>f2,handleApplication:()=>eSe,httpServer:()=>EL,logRequest:()=>xp,proxyRequest:()=>rSe,registerServer:()=>hL,suppressHandleApplicationWarning:()=>Zge});function eSe(e){Bp=e.options.getAll(),e.options.on("change",t=>{Bp=e.options.getAll()})}function tSe(){return Bp}function c2(e,t,r){let n=e?.read?e:new e2.Socket({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=cf[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=cf[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):a<5?i(a+1):(Zo.default.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}function rSe(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=Qj.get(s),r){case"connection":i=c2(void 0,t),Qj.set(s,i),i.write=(c,l,u)=>(ER.parentPort.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(ER.parentPort.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let a=i.destroy;i.destroy=()=>{a.call(i),ER.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 hL(e,t,r=!0){t||(t=wr.default.get(U.HTTP_PORT));let n=cf[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",Zj),s.on("unhandled",(i,a)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,a)}),n.lastServer=e}else cf[t]=e;e.on("unhandled",Zj)}function pL(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=[],wr.default.get(U.HTTP_PORT)!=null&&t.push({port:wr.default.get(U.HTTP_PORT),secure:wr.default.get(U.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),wr.default.get(U.HTTP_SECUREPORT)!=null&&t.push({port:wr.default.get(U.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&wr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:(0,t2.resolvePath)(wr.default.get(U.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}function EL(e,t){let r=[];for(let{port:n,secure:s}of pL(t))r.push(l2(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?fL[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,hL(e,n,!1)),_R[n]=gR(fL,n);return r}function l2(e,t,r,n){if(mR(e,{protocol_name:t?"HTTPS":"HTTP",name:RR()}),!pR[e]){let s=r?"operationsApi_network":"http",i=wr.default.get(s+"_keepAliveTimeout"),a=wr.default.get(s+"_timeout"),c=wr.default.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:a,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:wr.default.get(U.HTTP_MAXHEADERSIZE)},u=wr.default.get(s+"_mtls"),d=wr.default.get(s+"_mtls_required"),f;if(t){let g=wr.default.get("tls");f=wr.default.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!d,requestCert:!!(u||n),ticketKeys:(0,r2.getTicketKeys)(),SNICallback:(0,n2.createTLSSelector)(r?"operations-api":"server",u),ciphers:g.ciphers??g[0]?.ciphers})}let m=(0,s2.checkMemoryLimit)(),h=o(async(g,R)=>{let T=performance.now(),y=0;try{let O=new Ha(g,R);r&&(O.isOperationsServer=!0),Bp.logging?.id&&(O.requestId=y=f2());let F=await _R[e](O);if(!F){if(O._nodeResponse.statusCode){xp(g,O._nodeResponse.statusCode,y,performance.now()-T);return}F=u2(O)}if(F.headers?.set||(F.headers=new Ns(F.headers)),m?F.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):F.headers?.set?.("Server","HarperDB"),F.status===-1){for(let me of F.headers||[])R.setHeader(me[0],me[1]);return g.baseRequest=O,R.baseResponse=F,pR[e].emit("unhandled",g,R)}let Z=F.status||200,G=performance.now(),Y=G-T,K=F.body,$,le=!1;if(!F.handlesHeaders){let me=F.headers||new Ns;K?K.length>=0?(typeof K=="string"?me.set("Content-Length",Buffer.byteLength(K)):me.set("Content-Length",K.length),$=!0):K instanceof Rs&&(K.size?me.set("Content-Length",K.size):K.on&&(le=!0,K.on("size",De=>{R.headersSent||R.setHeader("Content-Length",De)})),K=K.stream()):(me.set("Content-Length","0"),$=!0);let Pe=`hdb;dur=${Y.toFixed(2)}`;if(F.wasCacheMiss&&(Pe+=", miss"),eh(me,"Server-Timing",Pe,!0),!R.headersSent)if(le){if(R.statusCode=Z,me)if(me[Symbol.iterator])for(let[De,dt]of me)R.setHeader(De,dt);else for(let De in me)R.setHeader(De,me[De])}else R.writeHead(Z,me&&(me[Symbol.iterator]?Array.from(me):me));$&&R.end(K)}let ue=O.handlerPath,se=O.method;if(it(Y,"duration",ue,se,F.wasCacheMiss==null?void 0:F.wasCacheMiss?"cache-miss":"cache-hit"),Yr(Z<400,"success",ue,se),Yr(1,"response_"+Z,ue,se),xp(g,Z,y,Y),!$)if(K instanceof ReadableStream&&(K=dL.Readable.fromWeb(K)),(K[Symbol.iterator]||K[Symbol.asyncIterator])&&(K=dL.Readable.from(K)),K?.pipe){K.pipe(R),K.destroy&&R.on("close",()=>{K.destroy()});let me=0;K.on("data",Pe=>{me+=Pe.length}),K.on("end",()=>{it(performance.now()-G,"transfer",ue,se),it(me,"bytes-sent",ue,se)})}else K?.then?K.then(me=>{R.end(me)},N):R.end(K)}catch(O){N(O)}function N(O){let F=O.headers,Z=O.statusCode||500;R.writeHead(Z,F&&(F[Symbol.iterator]?Array.from(F):F)),R.end(Xge(O)),xp(g,Z,y,performance.now()-T),O.statusCode?O.statusCode===500?Zo.default.warn(O):Zo.default.info(O):Zo.default.error(O)}o(N,"onError")},"requestHandler"),p=hR(h,(g,R)=>{R.statusCode=503,R.end("Service unavailable, exceeded request queue limit"),it(!0,"service-unavailable",e)},wr.default.get(s+"_requestQueueLimit")),_=pR[e]=(t?f?i2.createSecureServer:o2.createServer:SR.createServer)(l,(g,R)=>{let T=g.method;T==="GET"||T==="OPTIONS"||T==="HEAD"?h(g,R):p(g,R)});i>=0&&(_.keepAliveTimeout=i),c>=0&&(_.headersTimeout=c),t&&(_.ports||(_.ports=[]),_.ports.push(e),l.SNICallback.initialize(_),u&&(_.mtlsConfig=u),_.on("secureConnection",g=>{g._parent.startTime&&it(performance.now()-g._parent.startTime,"tls-handshake",e),it(g.isSessionReused(),"tls-reused",e)}),_.isSecure=!0),hL(_,e)}return pR[e]}function gR(e,t){let r=u2;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 u2(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new Ns}}function nSe(e,t){EL(e,{requestOnly:!0,...t})}function d2(e,t){for(let{port:r}of pL(t))Jj[t?.runFirst?"unshift":"push"]({listener:e,port:r}),mL[r]=gR(Jj,r)}function sSe(e,t){let r=[];for(let{port:n,secure:s}of pL(t)){mR(n,{protocol_name:s?"WSS":"WS",name:RR()});let i=l2(n,s,t?.isOperationsServer,t?.mtls);vp[n]||(vp[n]=new a2.WebSocketServer({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),vp[n].on("connection",(a,c)=>{try{let l=new Ha(c);l.isWebSocket=!0;let u=_R[n](l);Zo.default.debug("Received WS connection, calling listeners",lL),Xj[n](a,l,u)}catch(l){Zo.default.warn("Error in handling WS connection",l)}}),d2((a,c,l,u)=>a.__harperdbRequestUpgraded?u(a,c,l):vp[n].handleUpgrade(a,c,l,d=>{a.__harperdbRequestUpgraded=!0,u(a,c,l),vp[n].emit("connection",d,a)}),{port:n}),i.on("upgrade",(a,c,l)=>{mL[n]&&mL[n](a,c,l)})),r.push(i),lL[t?.runFirst?"unshift":"push"]({listener:e,port:n}),Xj[n]=gR(lL,n),_R[n]=gR(fL,n)}return r}function Zj(e,t){t.headersSent||t.writableEnded||(t.writeHead(404),t.end(`Not found
34
+ `),xp(e,404,0,e.requestId))}function xp(e,t,r,n){let s=Bp.logging;if(s){uL||(uL=Zo.default.forComponent("http"));let i=t<400?"info":t===500?"error":"warn";uL[i]?.(`${e.method} ${e.url} ${e.socket.encrypted?"HTTPS":"HTTP"}/${e.httpVersion}${s.headers?" "+iSe(e.headers):""} ${t}${s.timing&&n?" "+n.toFixed(2)+"ms":""}${r?" id: "+r:""}`)}}function iSe(e){let t=[];for(let r in e)t.push(`${r}: ${e[r]}`);return t.join(", ")}function f2(){return Up||(Up=new BigInt64Array([1n]),Up=new BigInt64Array(databases.system.hdb_analytics.primaryStore.getUserSharedBuffer("next-request-id",Up.buffer))),Number(Atomics.add(Up,0,1n))}var e2,Zo,ER,wr,t2,r2,n2,s2,i2,o2,SR,dL,a2,Xge,vp,pR,_R,fL,Bp,Zge,Qj,Jj,mL,lL,Xj,uL,Up,_L=ce(()=>{e2=require("node:net"),Zo=w(Q()),ER=require("node:worker_threads"),wr=w(oe());k();t2=w(wt()),r2=w(nt()),n2=w(ss()),s2=w(Dd()),i2=require("node:http2"),o2=require("node:https"),SR=require("node:http");rh();th();Kn();Yi();dL=require("node:stream");Dr();iL();Vd();cL();a2=require("ws"),{errorToString:Xge}=Zo.default;Le.http=EL;Le.request=nSe;Le.ws=sSe;Le.upgrade=d2;vp={},pR={},_R={},fL=[],Bp={},Zge=!0;o(eSe,"handleApplication");o(tSe,"getHttpOptions");o(c2,"deliverSocket");Qj=new Map;o(rSe,"proxyRequest");o(hL,"registerServer");o(pL,"getPorts");o(EL,"httpServer");o(l2,"getHTTPServer");o(gR,"makeCallbackChain");o(u2,"unhandled");o(nSe,"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){}});Jj=[],mL={};o(d2,"onUpgrade");lL=[],Xj={};o(sSe,"onWebSocket");o(Zj,"defaultNotFound");o(xp,"logRequest");o(iSe,"headersToString");o(f2,"getRequestId")});var sp={};we(sp,{componentErrors:()=>Fp,getComponentName:()=>RR,loadComponent:()=>IR,loadComponentDirectories:()=>p2,setErrorReporter:()=>aSe});function p2(e,t){t&&(SL=t),e&&(AL=e);let r=[];if((0,vt.existsSync)(gL)){let s=(0,vt.readdirSync)(gL,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,Hr.join)(gL,a);r.push(IR(c,SL,Vy,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(IR(n,SL,n,!1,void 0,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{h2=!0})}function aSe(e){AR=e}function cSe(e,t){return new Promise((r,n)=>{let s=setTimeout(()=>{zo.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(zo.primaryStore.attemptLock(e,0,()=>{clearTimeout(s),r()}))try{(0,vt.rmSync)(t,{recursive:!0,force:!0}),(0,vt.existsSync)((0,Hr.join)(e,"node_modules"))||(0,vt.mkdirSync)((0,Hr.join)(e,"node_modules")),(0,vt.symlinkSync)(IL.PACKAGE_ROOT,t,"dir"),r()}finally{zo.primaryStore.unlock(e,0)}})}function E2(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;if(!zo.primaryStore.attemptLock(e.name,0,()=>{clearTimeout(s),n(E2(e,t))}))return new Promise((a,c)=>{n=a,s=setTimeout(()=>{c(new Error(`Timeout waiting for lock on ${e.name}`))},r+5e3)});let i;return Promise.race([t.handleApplication(e),new Promise((a,c)=>i=setTimeout(()=>c(new Error(`handleApplication timed out after ${r}ms for ${e.name}`)),r))]).finally(()=>{zo.primaryStore.unlock(e.name,0),clearTimeout(i)})})}async function IR(e,t,r,n,s,i){let a=(0,vt.realpathSync)(e);if(yR.has(a))return yR.get(a);yR.set(a,!0),s&&(AL=s);try{let c;n&&(Fp=new Map);let l=(0,Hr.join)(e,"harperdb-config.yaml");(0,vt.existsSync)(l)?c=n?(0,NR.getConfigObj)():(0,RL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():!n&&(0,vt.existsSync)(l=(0,Hr.join)(e,"config.yaml"))?c=(0,RL.parseDocument)((0,vt.readFileSync)(l,"utf8")).toJSON():c=iR;try{let m=(0,Hr.join)(e,"node_modules","harperdb");(n||((0,vt.existsSync)(m)||!e.startsWith((0,yL.getHdbBasePath)()))&&(!(0,vt.existsSync)(m)||(0,vt.realpathSync)(IL.PACKAGE_ROOT)!==(0,vt.realpathSync)(m)))&&await cSe(e,m)}catch(m){ea.default.error("Error symlinking harperdb module",m),m.code=="EPERM"&&process.platform==="win32"&&ea.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=bR,d={};for(let m in c){bR=m;let h=c[m];if(Fp.set(n?m:(0,Hr.basename)(e),!1),!h)continue;let p,_=h.package;try{if(_){let N=e,O;for(;!(0,vt.existsSync)(O=(0,Hr.join)(N,"node_modules",m));)if(N=(0,Hr.dirname)(N),N.length<(0,yL.getHdbBasePath)().length){O=null;break}if(O)p=await IR(O,t,r,!1),d[m]=!0;else throw new Error(`Unable to find package ${m}:${_}`)}else p=oSe[m];if(!p)continue;let g=o(N=>(N.origin=r,ze(N)),"ensureTable"),R=h.network||(h.port||h.securePort)&&h,T=R?.securePort||R?.https&&R.port,y=!R?.https&&R?.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&&ea.default.warn(`Plugin ${m} is using the experimental handleApplication API`);let N=new lR(m,e,l,t,Le);await E2(N,p);continue}if(TL.isMainThread&&(p=await p.startOnMainThread?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p,n&&R))for(let N of[y,T])try{if(+N&&!m2.includes(N)){let O=bL.get(U.HTTP_SESSIONAFFINITY);O&&ea.default.warn("Session affinity is not recommended and may cause memory leaks"),(O||!cg)&&(m2.push(N),TP(N,O))}}catch(O){console.error("Error listening on socket",N,O,m)}if(t.isWorker&&(p=await p.start?.({server:Le,ensureTable:g,port:y,securePort:T,resources:t,...h})||p),AL.set(p,!0),(p.handleFile||p.handleDirectory||p.setupFile||p.setupDirectory)&&h.files!=null){let N=new fR({config:h,name:m,directory:e,module:p,resources:t});d[m]=await Vj(N)}}catch(g){g.message=`Could not load component '${m}' for application '${(0,Hr.basename)(e)}' due to: ${g.message}`,AR?.(g),((0,Hp.getWorkerIndex)()===0?console:ea.default).error(g),t.set(h.path||"/",new $c(g),null,!0),Fp.set(n?m:(0,Hr.basename)(e),g.message)}}if(bR=u,TL.isMainThread&&!h2&&i&&(0,Hp.watchDir)(e,async()=>p2()),c.extensionModule||c.pluginModule){let m=await tg((0,Hr.join)(e,c.extensionModule||c.pluginModule));return yR.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?`;AR?.(new Error(m)),((0,Hp.getWorkerIndex)()===0?console:ea.default).error(m),Fp.set((0,Hr.basename)(e),m)}for(let[m,h]of Object.entries(d))h||ea.default.warn(`Component ${m} from (${(0,Hr.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}`,AR?.(c),t.set("",new $c(c))}}var vt,Hr,TL,RL,bL,IL,ea,Hp,yL,NR,gL,AL,h2,SL,Fp,oSe,m2,yR,AR,bR,RR,Vd=ce(()=>{vt=require("node:fs"),Hr=require("node:path"),TL=require("node:worker_threads"),RL=require("yaml"),bL=w(oe()),IL=w(bt());k();iv();Kv();pH();yH();AH();uk();lz();pz();_z();ea=w(Q());Nz();Hp=w(nt());VI();Dr();Me();yP();yL=w(oe());jz();jS();nj();rs();_j();NR=w(wt());rh();CA();Hj();Kj();_L();dp();qP();gL=(0,NR.resolvePath)(bL.get(U.COMPONENTSROOT)),AL=new Map,Fp=new Map;o(p2,"loadComponentDirectories");oSe={REST:dg,rest:dg,graphql:LA,graphqlSchema:fA,roles:$I,jsResource:KI,fastifyRoutes:uP,login:WI,static:dP,operationsApi:bP,customFunctions:{},http:TR,clustering:PP,replication:Uo,authentication:Jh,mqtt:UP,loadEnv:fP,logging:ea.default,dataLoader:pP},m2=[],yR=new Map;o(aSe,"setErrorReporter");RR=o(()=>bR,"getComponentName");o(cSe,"symlinkHarperModule");o(E2,"sequentiallyHandleApplication");o(IR,"loadComponent")});var YT=M((WBe,g2)=>{var{isMainThread:_2}=require("worker_threads"),{getTables:lSe,getDatabases:KBe,table:YBe}=(Me(),v(Et)),{loadComponentDirectories:uSe,loadComponent:dSe}=(Vd(),v(sp)),{resetResources:fSe}=(Ou(),v(Uv)),mSe=YO(),hSe=wt(),{dirname:pSe}=require("path"),{getConnection:ESe}=mr(),_Se=oe(),{CONFIG_PARAMS:gSe}=(k(),v(W)),{loadCertificates:SSe}=ss(),NL=new Map;async function TSe(e=!1){!_2&&_Se.get(gSe.CLUSTERING_ENABLED)&&ESe();try{_2&&await mSe()}catch(n){console.error(n)}let t=fSe();lSe(),t.isWorker=e,await SSe(),await dSe(pSe(hSe.getConfigFilePath()),t,"hdb",!0,NL),await uSe(NL,t);let r=[];for(let[n]of NL)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}o(TSe,"loadRootComponents");g2.exports.loadRootComponents=TSe});var nt=M((jBe,Ni)=>{"use strict";qy();var{Worker:RSe,MessageChannel:ySe,parentPort:ro,isMainThread:LL,threadId:ASe,workerData:no}=require("worker_threads"),{PACKAGE_ROOT:bSe}=bt(),{join:y2,isAbsolute:ISe,extname:NSe}=require("path"),{server:A2}=(Dr(),v(rm)),{watch:wSe,readdir:OSe}=require("fs/promises"),{totalmem:S2}=require("os"),{setHeapSnapshotNearHeapLimit:CSe}=require("v8"),fc=(k(),v(W)),CR=oe(),Ii=Q(),{randomBytes:PSe}=require("crypto"),{_assignPackageExport:LSe}=Zs(),T2=1024*1024,mc=[],Gs=[],DSe=50,DL=1e4,MSe="restart",b2="request_thread_info",I2="resource_report",N2="thread_info",w2="added-port",vSe="ack",wL;LSe("threads",Gs);Ni.exports={startWorker:OL,restartWorkers:vL,shutdownWorkers:HSe,workers:mc,setMonitorListener:WSe,onMessageFromWorkers:kSe,onMessageByType:v2,broadcast:qSe,broadcastWithAcknowledgement:VSe,setChildListenerByType:FSe,getWorkerIndex:O2,getWorkerCount:C2,getTicketKeys:L2,setMainIsWorker:xSe,setTerminateTimeout:USe,restartNumber:no?.restartNumber||1};Gs.onMessageByType=v2;Gs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Gs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Ni.exports.whenThreadsStarted=new Promise(e=>{Ni.exports.threadsHaveStarted=e});CR.get(fc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&CSe(1);var ML;function USe(e){DL=e}o(USe,"setTerminateTimeout");function O2(){return no?no.workerIndex:ML?0:void 0}o(O2,"getWorkerIndex");function C2(){return no?no.workerCount:ML?1:void 0}o(C2,"getWorkerCount");function xSe(e){ML=e,Ni.exports.threadsHaveStarted()}o(xSe,"setMainIsWorker");var P2=1,wR;function L2(){return wR||(wR=LL?PSe(48):no.ticketKeys,wR)}o(L2,"getTicketKeys");Object.defineProperty(A2,"workerIndex",{get(){return O2()}});Object.defineProperty(A2,"workerCount",{get(){return C2()}});var D2={[b2](e,t){KSe(t)},[I2](e,t){YSe(t,e)}};function OL(e,t={}){let r=process.constrainedMemory?.()||S2();r=Math.min(r,S2(),2e4*T2);let n=CR.get(fc.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/T2/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],a=[];for(let u of Gs){let d=new ySe;d.existingPort=u,i.push(d),a.push(d.port2)}NSe(e)||(e+=".js");let c=["--enable-source-maps","--expose-internals"];CR.get(fc.CONFIG_PARAMS.THREADS_HEAPSNAPSHOTNEARLIMIT)&&c.push("--heapsnapshot-near-heap-limit=1");let l=new RSe(ISe(e)?e:y2(bSe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:c,argv:process.argv.slice(2),workerData:{addPorts:a,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:P2=t.threadCount,name:t.name,restartNumber:Ni.exports.restartNumber,ticketKeys:L2()},transferList:a,...t});for(let{port1:u,existingPort:d}of i)d.postMessage({type:w2,port:u,threadId:l.threadId},[u]);return PR(l,!0),l.unexpectedRestarts=t.unexpectedRestarts||0,l.startCopy=()=>OL(e,t),l.on("error",u=>{Ii.error(`Worker index ${t.workerIndex} error:`,u)}),l.on("exit",u=>{mc.splice(mc.indexOf(l),1),!l.wasShutdown&&t.autoRestart!==!1&&(l.unexpectedRestarts<DSe?(t.unexpectedRestarts=l.unexpectedRestarts+1,OL(e,t)):Ii.error(`Thread has been restarted ${l.restarts} times and will not be restarted`))}),l.on("message",u=>{D2[u.type]?.(u,l)}),mc.push(l),jSe(),t.onStarted&&t.onStarted(l),l.name=t.name,l}o(OL,"startWorker");var BSe=[fc.THREAD_TYPES.HTTP];async function vL(e=null,t=Math.max(P2>3,1),r=!0){if(LL){try{process.chdir(process.cwd())}catch(a){Ii.error("Unable to reestablish current working directory",a)}if(r){let{loadRootComponents:a}=YT();await a()}Ni.exports.restartNumber++,t<1&&(t=t*mc.length);let n=[],s=[];for(let a of mc.slice(0)){if(e&&a.name!==e||a.wasShutdown)continue;Ii.trace("sending shutdown request to ",a.threadId),a.postMessage({restartNumber:Ni.exports.restartNumber,type:fc.ITC_EVENT_TYPES.SHUTDOWN}),a.wasShutdown=!0,a.emit("shutdown",{});let c=BSe.indexOf(a.name)>-1,l=new Promise(u=>{let d=setTimeout(()=>{Ii.warn("Thread did not voluntarily terminate, terminating from the outside",a.threadId),a.terminate()},DL*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===fc.ITC_EVENT_TYPES.CHILD_STARTED&&(Ii.trace("Worker has started",u.threadId),f(),s.splice(s.indexOf(d)),u.off("message",m))},"startListener");Ii.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}=kd();r&&(e==="http"||!e)&&CR.get(fc.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ro.postMessage({type:MSe,workerType:e})}o(vL,"restartWorkers");function FSe(e,t){D2[e]=t}o(FSe,"setChildListenerByType");function HSe(e){return vL(e,1/0,!1)}o(HSe,"shutdownWorkers");var M2=[];function kSe(e){M2.push(e)}o(kSe,"onMessageFromWorkers");var CL=new Map;function v2(e,t){let r=CL.get(e);r||CL.set(e,r=[]),r.push(t)}o(v2,"onMessageByType");var GSe=10;async function qSe(e,t){let r=0;for(let n of Gs)try{n.postMessage(e),r++>GSe&&(r=0,await new Promise(setImmediate))}catch(s){Ii.error("Unable to send message to worker",s)}t&&x2(e,null)}o(qSe,"broadcast");var OR=new Map,$Se=1;function VSe(e){return new Promise(t=>{let r=0;for(let n of Gs)try{let s=$Se++,i=o(()=>{OR.delete(s),--r===0&&t(),n!==ro&&--n.refCount===0&&n.unref()},"ackHandler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,OR.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,a]of OR)a.port===n&&a()})),n.postMessage(e),r++}catch(s){Ii.error("Unable to send message to worker",s)}r===0&&t()})}o(VSe,"broadcastWithAcknowledgement");function KSe(e){e.postMessage({type:N2,workers:U2()})}o(KSe,"sendThreadInfo");function U2(){let e=Date.now();return mc.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(U2,"getChildWorkerInfo");function YSe(e,t){e.resources=t,e.resources.updated=Date.now()}o(YSe,"recordResourceReport");var PL;function WSe(e){PL=e}o(WSe,"setMonitorListener");var zSe=1e3,R2=!1;function jSe(){R2||(R2=!0,setInterval(()=>{for(let e of mc){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}PL&&PL()},zSe).unref())}o(jSe,"startMonitoring");var QSe=1e3;if(ro&&no?.addPorts){PR(ro);for(let e=0,t=no.addPorts.length;e<t;e++){let r=no.addPorts[e];r.threadId=no.addThreadIds[e],PR(r)}setInterval(()=>{let e=process.memoryUsage();ro.postMessage({type:I2,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},QSe).unref(),wL=o(()=>new Promise((e,t)=>{ro.on("message",r),ro.postMessage({type:b2});function r(n){n.type===N2&&(ro.off("message",r),e(n.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else wL=U2;Ni.exports.getThreadInfo=wL;function PR(e,t){Gs.push(e),e.on("message",r=>{if(r.type===w2)r.port.threadId=r.threadId,PR(r.port);else if(r.type===vSe){let n=OR.get(r.id);n&&n()}else x2(r,e)}).on("close",()=>{Gs.splice(Gs.indexOf(e),1)}).on("exit",()=>{Gs.splice(Gs.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(PR,"addPort");function x2(e,t){for(let n of M2)n(e,t);let r=CL.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){Ii.error(s)}}o(x2,"notifyMessageListeners");if(LL){let e,t,r=new Set,n=o(async(s,i)=>{i&&(e=i);for(let a of await OSe(s,{withFileTypes:!0}))a.isDirectory()&&a.name!=="node_modules"&&n(y2(s,a.name));try{for await(let{filename:a}of wSe(s,{persistent:!1}))r.add(a),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await vL(),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");Ni.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ro.on("message",async e=>{let{type:t}=e;t===fc.ITC_EVENT_TYPES.SHUTDOWN&&(Ni.exports.restartNumber=e.restartNumber,ro.unref(),setTimeout(()=>{Ii.warn("Thread did not voluntarily terminate",ASe),process.exit(0)},DL).unref())})});var G2={};we(G2,{onStorageReclamation:()=>kp,runReclamationHandlers:()=>FL,setAvailableSpaceRatioGetter:()=>XSe});function kp(e,t,r){(r||(0,DR.getWorkerIndex)()===(0,DR.getWorkerCount)()-1)&&(LR.has(e)||LR.set(e,[]),LR.get(e).push({priority:0,handler:t}),BL||(BL=setTimeout(FL,F2).unref()))}async function FL(){for(let[e,t]of LR)try{let r=await k2(e),n=JSe/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&&(xL.default.info?.(`Running storage reclamation handler for ${e} with priority ${n}`),await c)}}}catch(r){xL.default.error?.("Error running storage reclamation handlers",r)}BL=setTimeout(FL,F2).unref()}function XSe(e){k2=e??H2}var UL,DR,xL,MR,B2,LR,JSe,F2,BL,H2,k2,vR=ce(()=>{UL=require("node:fs/promises"),DR=w(nt()),xL=w(ei());k();MR=w(oe()),B2=w(ie());MR.default.initSync();LR=new Map,JSe=MR.default.get(U.STORAGE_RECLAMATION_THRESHOLD)??.4,F2=(0,B2.convertToMS)(MR.default.get(U.STORAGE_RECLAMATION_INTERVAL))||36e5;o(kp,"onStorageReclamation");H2=o(async e=>{if(UL.statfs){let t=await(0,UL.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"),k2=H2;o(FL,"runReclamationHandlers");o(XSe,"setAvailableSpaceRatioGetter")});var DF={};we(DF,{ACTION_32_BIT:()=>HR,ACTION_64_BIT:()=>rTe,AUDIT_STORE_OPTIONS:()=>Yh,Decoder:()=>Il,HAS_BLOBS:()=>$r,HAS_CURRENT_RESIDENCY_ID:()=>Al,HAS_EXPIRATION_EXTENDED_TYPE:()=>Kp,HAS_ORIGINATING_OPERATION:()=>Vp,HAS_PREVIOUS_RESIDENCY_ID:()=>bl,REMOTE_SEQUENCE_UPDATE:()=>Qg,createAuditEntry:()=>Rl,getLastRemoved:()=>eTe,openAuditStore:()=>BR,readAuditEntry:()=>Nt,removeAuditEntry:()=>FR,setAuditRetention:()=>tTe,transactionKeyEncoder:()=>Q2});function BR(e){let t=e.auditStore=e.openDB(HL.AUDIT_STORE_NAME,{create:!1,...Yh});t||(t=e.auditStore=e.openDB(HL.AUDIT_STORE_NAME,Yh),$2(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=GL;kp(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()-kL/(1+i*i)})){try{m=FR(t,p,_)}catch(g){lf.warn("Error removing audit entry",g)}if(h=p,await new Promise(setImmediate),++f>=ZSe){a=10;break}}await m}finally{f===0?a=Math.min(a<<1,kL/10):($2(t,h),a>100&&(a=a>>1)),d(void 0),c()}},a).unref()});return u}if(o(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,qp.getWorkerIndex)()===(0,qp.getWorkerCount)()-1&&c(),(0,qp.getWorkerIndex)()===0&&!q2)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(q2=!0,lf.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 FR(e,t,r){let n=nTe(r),s;if(n&$r){s=Nt(r);let i=e.tableStores[s.tableId];if(i){let a=s.type==="message"?null:i?.getEntry(s.recordId);(!a||a.version!==s.version||!a.value)&&So(()=>Ia(s.getValue(i)),i.rootStore)}}if((n&15)===qL){s=s||Nt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId)?.version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function $2(e,t){$L[0]=t,e.put(Symbol.for("last-removed"),J2)}function eTe(e){let t=e.get(Symbol.for("last-removed"));if(t)return J2.set(t),$L[0]}function tTe(e,t=GL){kL=e,GL=t}function Rl(e,t,r,n,s,i,a,c,l,u,d,f,m){let h=X2[a];if(!h)throw new Error(`Invalid audit entry type ${a}`);let p=1;if(n&&(n>1?hc.setFloat64(0,n):qs.set(VL),p=9),l){if(l&255)throw new Error("Illegal extended type");p+=3}R(s),R(t),g(r),hc.setFloat64(p,e),p+=8,l&Al&&R(u),l&bl&&R(d),l&Kp&&(hc.setFloat64(p,f),p+=8),l&Vp&&R(Z2[m]),i?g(i):qs[p++]=0,l?hc.setUint32(n?8:0,h|l|3221225472):qs[n?8:0]=h;let _=qs.subarray(0,p);if(c)return Buffer.concat([_,c]);return _;function g(T){let y=p;p+=1,p=(0,Ql.writeKey)(T,qs,p);let N=p-y-1;N>127?N>16383?(lf.error("Key or username was too large for audit entry",T),p=y+1,qs[y]=0):(qs.copyWithin(y+2,y+1,p),hc.setUint16(y,N|32768),p++):qs[y]=N}function R(T){T<128?qs[p++]=T:T<16384?(hc.setUint16(p,T|32768),p+=2):T<1056964608?(hc.setUint32(p,T|3221225472),p+=4):(qs[p]=255,hc.setUint32(p+1,T),p+=5)}}function nTe(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 Il(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Il(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&Al&&(m=n.readInt()),i&bl&&(h=n.readInt()),i&Kp&&(p=n.readFloat64()),i&Vp){let y=n.readInt();_=Z2[y]}l=n.readInt();let g=n.position,R=n.position+=l,T;return{type:X2[i&7],tableId:c,nodeId:a,get recordId(){return(0,Ql.readKey)(e,u,d)},getBinaryRecordId(){return e.subarray(u,d)},version:f,previousLocalTime:s,get user(){return R>g?(0,Ql.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(y,N,O){if(i&UR||i&Gp&&!N)return T||(T=So(()=>y.decoder.decode(e.subarray(n.position,r)),y.rootStore)),T;if(i&Gp&&O)return OI(y.getEntry(this.recordId),O,y)},getBinaryValue(){return i&(UR|Gp)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:m,previousResidencyId:h,expiresAt:p,originatingOperation:_}}catch(n){return lf.error("Reading audit entry error",n,e),{}}}var Ql,xR,HL,qp,j2,lf,qs,hc,Q2,Yh,kL,ZSe,$L,J2,GL,q2,UR,Gp,V2,qL,K2,Y2,W2,z2,HR,rTe,Qg,Al,bl,Vp,Kp,$r,X2,Z2,Il,Mi=ce(()=>{Ql=require("ordered-binary"),xR=w(oe()),HL=w(Vt());k();qp=w(nt()),j2=w(ie());Vc();lf=w(Q());V_();Kn();vR();(0,xR.initSync)();qs=Buffer.alloc(2816),hc=new DataView(qs.buffer,qs.byteOffset,2816),Q2={writeKey(e,t,r){return e===$p?(t.set($p,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Ql.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,Ql.readKey)(e,t,r)}},Yh={encoding:"binary",keyEncoder:Q2},kL=(0,j2.convertToMS)((0,xR.get)(U.LOGGING_AUDITRETENTION))||86400*3,ZSe=1e3,$L=new Float64Array(1),J2=new Uint8Array($L.buffer),GL=1e4,q2=!1;o(BR,"openAuditStore");o(FR,"removeAuditEntry");o($2,"updateLastRemoved");o(eTe,"getLastRemoved");o(tTe,"setAuditRetention");UR=16,Gp=32,V2=1,qL=2,K2=3,Y2=4,W2=5,z2=6,HR=14,rTe=15,Qg=11,Al=512,bl=1024,Vp=2048,Kp=4096,$r=8192,X2={put:V2|UR,[V2]:"put",delete:qL,[qL]:"delete",message:K2|UR,[K2]:"message",invalidate:Y2|Gp,[Y2]:"invalidate",patch:W2|Gp,[W2]:"patch",relocate:z2,[z2]:"relocate"},Z2={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};o(Rl,"createAuditEntry");o(nTe,"readAction");o(Nt,"readAuditEntry");Il=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 sU={};we(sU,{ENTRY:()=>iTe,HAS_EXPIRATION:()=>$R,HAS_RESIDENCY_ID:()=>jL,HAS_STRUCTURE_UPDATE:()=>eS,LAST_TIMESTAMP_PLACEHOLDER:()=>$p,LOCAL_TIMESTAMP:()=>sTe,METADATA:()=>Ed,NEW_TIMESTAMP_PLACEHOLDER:()=>tQ,NO_TIMESTAMP:()=>GR,PENDING_LOCAL_TIME:()=>QL,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>VL,RecordEncoder:()=>zL,TIMESTAMP_ASSIGN_LAST:()=>aTe,TIMESTAMP_ASSIGN_NEW:()=>rQ,TIMESTAMP_ASSIGN_PREVIOUS:()=>nQ,TIMESTAMP_PLACEHOLDER:()=>kR,TIMESTAMP_RECORD_PREVIOUS:()=>KL,entryMap:()=>pc,handleLocalTimeForGets:()=>VR,lastMetadata:()=>ut,recordUpdater:()=>JL,removeEntry:()=>Zl});function lTe(){return zp[0]=zp[0]^64,oTe.getFloat64(0)}function VR(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++,ut=null;let l=r.call(this,a,c);return l&&(ut&&(l.metadataFlags=ut[Ed],l.localTime=ut.localTime,l.residencyId=ut.residencyId,ut.expiresAt>=0&&(l.expiresAt=ut.expiresAt),ut=null),l.value&&pc.set(l.value,l),l.key=a),l};let n=e.get;e.get=function(a,c){ut=null;let l=n.call(this,a,c);return ut&&l&&(pc.set(l,ut),ut=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=>(ut&&(l.metadataFlags=ut[Ed],l.localTime=ut.localTime,l.residencyId=ut.residencyId,ut.expiresAt>=0&&(l.expiresAt=ut.expiresAt),ut=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,Xl.push(new WeakRef(this))),c.call(this)},a.prototype.done=function(){if(l.call(this),this.isDone)for(let u=0;u<Xl.length;u++){let d=Xl[u].deref();(!d||d.isDone||d.isCommitted)&&Xl.splice(u--,1)}},a.prototype.done.isTracked=!0}return e}function JL(e,t,r){return function(n,s,i,a,c=-1,l,u,d="put",f,m){l==null?Jl=GR:f?Jl=i?.localTime?KL|nQ:GR:Jl=l?i?.localTime?KL|16384:rQ|16384:GR;let h=u?.expiresAt;if(h>=0&&(c|=$R),Wp=c,YL=h,i?.version===a&&l===!1)throw new Error("Must retain local time if version is not changed");let p={version:a,instructedWrite:Jl>0},_,g=0;try{let R=i?.residencyId,T=u?.residencyId;T&&(WL=T,Wp|=jL,g|=Al),R!==T&&(g|=bl,R||(R=0)),c&$R&&(g|=Kp),u?.originatingOperation&&(g|=Vp),f&&(p.ifVersion=_=i?.version??null),i&&i.value&&d!=="message"&&i.metadataFlags&$r&&(!i.localTime||!r.getBinaryFast(i.localTime))&&Ia(i.value);let y;if(s!==void 0&&(y=XE(()=>e.put(n,s,p),n,e.rootStore),kc&&(g|=$r)),l){let N=u?.user?.username;if(m&&(XE(()=>e.encoder.encode(m),n,e.rootStore),kc&&(g|=$r)),e.encoder.hasStructureUpdate&&(g|=eS,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let O=i?.localTime,F=r.get(O);if(F){let Z=Nt(F).previousLocalTime;return y=r.put(O,Rl(a,t,n,Z,u?.nodeId??server.replication.getThisNodeId(r)??0,N,d,Yp,g,T,R,h),{ifVersion:_}),y}}y=r.put(s===void 0?tQ:$p,Rl(a,t,n,i?.localTime?1:0,u?.nodeId??server.replication?.getThisNodeId(r)??0,N,d,Yp,g,T,R,h,u?.originatingOperation),{instructedWrite:!0,ifVersion:_})}return y}catch(R){throw R.message+=" id: "+n+" options: "+p,R}}}function Zl(e,t,r){if(t)return t.value&&t.metadataFlags&$r&&!e.auditStore?.getBinaryFast(t.localTime)&&Ia(t.value),e.remove(t.key,r)}var eQ,qR,kR,$p,VL,tQ,sTe,Ed,iTe,zp,oTe,GR,rQ,aTe,nQ,KL,$R,jL,QL,eS,pc,cTe,Yp,Jl,Wp,YL,WL,ut,zL,Xl,Vc=ce(()=>{eQ=require("msgpackr");Mi();qR=w(Q());Kn();Kn();kR=new Uint8Array([1,1,1,1,4,64,0,0]),$p=new Uint8Array([1,1,1,1,1,0,0,0]),VL=new Uint8Array([1,1,1,1,3,64,0,0]),tQ=new Uint8Array([1,1,1,1,0,64,0,0]),sTe=Symbol("local-timestamp"),Ed=Symbol("metadata"),iTe=Symbol("entry"),zp=new Uint8Array(8),oTe=new DataView(zp.buffer,0,8),GR=0,rQ=0,aTe=1,nQ=3,KL=4,$R=16,jL=32,QL=1,eS=256,pc=new WeakMap,Jl=0,Wp=-1,YL=-1,WL=0,ut=null,zL=class extends eQ.Encoder{static{o(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0;class r{static{o(this,"RecordObject")}getUpdatedTime(){return pc.get(this)?.version}getExpiresAt(){return pc.get(this)?.expiresAt}}t.structPrototype=r.prototype,super(t);let n=this.encode;this.encode=function(i,a){if(Jl||Wp>=0){let c=0,l=Jl;l&&(c+=8,Jl=0);let u=Wp,d=YL,f=WL;u>=0&&(c+=4,Wp=-1,d>=0&&(c+=8,YL=-1),f&&(c+=4,WL=0));let m=cTe=n.call(this,i,a|2048|c);Yp=m.subarray((m.start||0)+c,m.end);let h=m.start||0;return l&&(kR[4]=l,kR[5]=l>>8,m.set(kR,h),h+=8),kc&&(u|=$r),u>=0&&((m.dataView||(m.dataView=new DataView(m.buffer,m.byteOffset,m.byteLength))).setUint32(h,u|HR<<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 Yp=n.call(this,i,a),Yp};let s=this.saveStructures;this.saveStructures=function(i,a){let c=s.call(this,i,a);return this.hasStructureUpdate=!0,c}}decode(t,r){ut=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(zp,0,c),c+=8;else for(let m=0;m<8;m++)zp[m]=t[c++];l=lTe(),i=t[c]}let u,d;i<32&&(i===HR?(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&$R&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),a&jL&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=So(()=>r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c),this.rootStore);return ut={localTime:l,[Ed]:a,expiresAt:u,residencyId:d},f}return r?.valueAsBuffer?t:So(()=>super.decode(t,r),this.rootStore)}catch(c){return qR.error("Error decoding record",c,"data: "+t.slice(0,40).toString("hex")),null}}};o(lTe,"getTimestamp");o(VR,"handleLocalTimeForGets");Xl=[];setInterval(()=>{for(let e=0;e<Xl.length;e++){let t=Xl[e].deref();!t||t.isDone||t.isCommitted?Xl.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(qR.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):qR.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(JL,"recordUpdater");o(Zl,"removeEntry")});function eD(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?eD(f.conditions,f.operator,r,n,s,i,a,c):mf(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",y=d(p.conditions,!T,h);return T?(N,O)=>y.some(F=>F(N,O)):(N,O)=>y.every(F=>F(N,O))}let g=(p.attribute||p[0])===r.primaryKey,R=Qp(p,r,i,c,g,h);return m&&_<f.length-1&&h&&(h=gTe(r.primaryStore,p.estimated_count,h)),R}).filter(Boolean)}o(d,"mapConditionsToFilters")}function mf(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 Xr.ClientError(`Search condition for ${c} must have a value`);if(Array.isArray(c)){let y=c[0],N=io(n.attributes,y);if(N.relationship){if(c.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let O=N.definition?.tableClass||N.elements?.definition?.tableClass,F=new Map,Z=mf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:u},t,r,O,s,F);if(N.relationship.to){i[c[0]]=F;let G=!!io(O.attributes,N.relationship.to)?.elements;Z=hTe(Z,N,O.primaryStore,G,F)}if(N.relationship.from){let G=o(Y=>(Y?.key!==void 0&&(Y=Y.key),mf({attribute:N.relationship.from,value:Y},t,r,n,s,F)),"searchEntry");N.elements?(i[c[0]]=F,Z=pTe(Z,N,O.primaryStore,F,G)):Z=Z.flatMap(G)}return Z}else if(c.length===1)c=c[0];else throw new Xr.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(tD[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]=so.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 Xr.ClientError(`Unknown query comparator "${u}"`)}let R;if(typeof m=="string"&&m.length>$s.MAX_SEARCH_KEY_LENGTH&&(m=m.slice(0,$s.MAX_SEARCH_KEY_LENGTH)+$s.OVERFLOW_MARKER,_=!1,R=Qp(e,n,null,i,d)),typeof h=="string"&&h.length>$s.MAX_SEARCH_KEY_LENGTH&&(h=h.slice(0,$s.MAX_SEARCH_KEY_LENGTH)+$s.OVERFLOW_MARKER,p=!0,R=R??Qp(e,n,null,i,d)),r){let y=m;m=h,h=y,y=!_,_=!p,p=y}if(!f||f.isIndexing||g||l===null&&!f.indexNulls){if(s===!1&&!f)throw new Xr.ClientError(`"${c}" is not indexed, can not search for this attribute`,404);if(s===!1&&g)throw new Xr.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 Xr.ServerError(`"${c}" is not indexed yet, can not search for this attribute`,503);if(l===null&&f&&!f.indexNulls)throw new Xr.ClientError(`"${c}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(R=R??Qp(e,n,null,i,d),!R)throw new Xr.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 y=f.getRange(T).map(R?function({key:N,value:O}){return this?.isSync?O&&R(O)?N:Ec.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(O&&R(O)?N:Ec.SKIP)}catch(G){Z(G)}}))}:N=>N.value==null&&!(N.metadataFlags&(Fn|eu))?Ec.SKIP:(a?._freezeRecords&&Object.freeze(N.value),N));return y.hasEntries=!0,y}else return f?f.customIndex?f.customIndex.search(e,a).map(y=>{if(typeof y=="object"&&y){let{key:N,...O}=y,F=n.primaryStore.getEntry(N);return a?._freezeRecords&&Object.freeze(F?.value),{...O,...F}}return y}):f.getRange(T).map(R?function({key:y,value:N}){let O;return typeof y=="string"&&y.length>$s.MAX_SEARCH_KEY_LENGTH?O=n.primaryStore.get(N):O={[c]:y},this.isSync?R(O)?N:Ec.SKIP:new Promise((F,Z)=>setImmediate(()=>{try{F(R(O)?N:Ec.SKIP)}catch(G){Z(G)}}))}:({value:y})=>y):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:y,value:N}){return this.isSync?N&&R(N)?y:Ec.SKIP:new Promise((O,F)=>setImmediate(()=>{try{O(N&&R(N)?y:Ec.SKIP)}catch(Z){F(Z)}}))})}function io(e,t){if(Array.isArray(t))if(t.length>1){let r=io(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?io(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 hTe(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 pTe(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 Qp(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=io(t.attributes,d),m=f.definition?.tableClass||f.elements.definition?.tableClass,h=n?.[d],p=Qp({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,R=o((y,N)=>{let O,F;return _?_.returnDirect?(O=_(y,r,N),F=ut):(F=_(y,r,N,!0),Array.isArray(F)?(O=F.map(Z=>Z.value),F=null):O=F?.value):O=y[d],{subObject:O,subEntry:F}},"getSubObject"),T=o((y,N)=>{if(_&&p.idFilter){if(!g)if(p.idFilter.idSet?.size===1){for(let Y of p.idFilter.idSet)e={attribute:_.from??t.primaryKey,value:Y};g=u(_.from??t.primaryKey,p.idFilter,!0,!0)}else g=u(_.from??t.primaryKey,p.idFilter,!1,!0);let G=g(y);return g.idFilter&&(T.idFilter=g.idFilter),G}let{subObject:O,subEntry:F}=R(y,N);return O?Array.isArray(O)?(!n?.[d]&&n&&(n[d]={fromRecord(G){let Y=R(G).subObject;return Array.isArray(Y)?Y.filter(p).map(K=>K[m.primaryKey]):Y}}),O.some(p)):p(O,F):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),tD[a]||a){case $s.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,so.compareKeys)(d,l[0])>=0&&(0,so.compareKeys)(d,l[1])<=0,!0);case"gt":return u(c,d=>(0,so.compareKeys)(d,l)>0);case"ge":return u(c,d=>(0,so.compareKeys)(d,l)>=0);case"lt":return u(c,d=>(0,so.compareKeys)(d,l)<0);case"le":return u(c,d=>(0,so.compareKeys)(d,l)<=0);case"ne":return u(c,d=>(0,so.compareKeys)(d,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new Xr.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&&YR(t)(e),p=e.estimated_count>>4,(isNaN(p)||p>=i)&&(m=!1));let _=0,g=3;function R(T){let y=T[d],N;if(typeof y!="object"||!y||h?N=f(y):Array.isArray(y)?N=y.some(f):y instanceof Date&&(N=f(y.getTime())),m&&(g++,!N&&!R.idFilter&&++_/g*i>p)){let O=mf(e,r.transaction.getReadTxn(),!1,t),F;R.to?F=O.flatMap(G=>t.primaryStore.get(G)[R.to]):F=O.map(hf);let Z=new Set(F);R.idFilter=G=>Z.has(hf(G)),R.idFilter.idSet=Z}return N}return o(R,"recordFilter"),s&&(R.idFilter=f),R}o(u,"attributeComparator")}function YR(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/ta(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=tD[n]||n,n===$s.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=io(e.attributes,s[0]),a=i.definition?.tableClass||i.elements.definition?.tableClass,c=YR(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*ta(e.indices[i.relationship.from])/(ta(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=ta(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else if(n==="starts_with"||n==="prefix")r.estimated_count=fTe*ta(e.primaryStore)+1;else if(n==="between")r.estimated_count=dTe*ta(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=ta(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=uTe*ta(e.primaryStore)+1}typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return o(t,"estimateConditionForTable"),t}function fg(e,t){if(e)if(ra=e,uf.lastIndex=0,ETe.test(e))try{if(t&&(t.conditions=[]),wi=t??new ff,jp(wi,""),kr!==ra.length&&Jt("Unable to parse query, unexpected end of query"),wi.parseErrorMessage&&(wi.parseError=new XL(t.parseErrorMessage),!t))throw wi.parseError;return wi}catch(r){if(r.statusCode=400,r.message=`Unable to parse query, ${r.message} at position ${kr} in '${ra}'`,wi.parseErrorMessage&&(r.message+=", "+wi.parseErrorMessage),t)t.parseError=r;else throw r}else return t??new URLSearchParams(e)}function Jt(e){let t=`${e} at position ${kr}`;wi.parseErrorMessage=wi.parseErrorMessage?wi.parseErrorMessage+", "+t:t}function jp(e,t){let r=uf,n,s,i,a,c,l=decodeURIComponent,u;for(;n=r.exec(ra);){kr=r.lastIndex;let[,d,f]=n;a?(d&&Jt(`expected operator, but encountered '${d}'`),a=!1,c=!1):c=!0;let m;switch(f){case"=":s!=null?(d.length<=2?i=d:Jt(`invalid FIQL operator ${d}`),l=sQ):(l=decodeURIComponent,i="equals",d||Jt("attribute must be specified before equality comparator"),s=df(d));break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":i=mTe[f],l=ZL[i]?sQ:decodeURIComponent,d||Jt(`attribute must be specified before comparator ${f}`),s=df(d);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null)s===void 0&&(t&&Jt(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`),Jt(`no comparison specified before ${f?"'"+f+"'":"end of string"}`));else{e.conditions||Jt("conditions/comparisons are not allowed in a property list");let p={comparator:i,attribute:s||null,value:l(d)};if(i==="eq"&&iQ(p,d),s===""){let _=e.conditions[e.conditions.length-1];_.chainedConditions=_.chainedConditions||[],_.chainedConditions.push(p),_.operator=u}else KR(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?Jt("conditions/comparisons are not allowed in a property list"):e.push(df(d)),s=void 0;break;case"(":uf.lastIndex=kr;let h=jp(d?[]:new ff,")");switch(d){case"":KR(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:Jt("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":Jt("group by is not implemented yet");case"sort":e.sort=oQ(h);break;default:Jt(`unknown query function call ${d}`)}ra[kr]===","?r.lastIndex=++kr:a=!0,s=null;break;case"{":e.conditions&&Jt("property sets are not allowed in a queries"),d||Jt("property sets must have a defined parent property name"),uf.lastIndex=kr,m=jp([],"}"),m.name=d,e.push(m),ra[kr]===","?r.lastIndex=++kr:a=!0;break;case"[":if(uf.lastIndex=kr,d?(m=jp(new ff,"]"),m.name=d):m=jp(e.conditions?new ff:[],"]"),e.conditions)if(KR(e,u),ra[kr]==="="){l=decodeURIComponent,i="equals",s=df(d),r.lastIndex=++kr;break}else e.conditions.push(m),s=null;else e.push(m);ra[kr]===","?r.lastIndex=++kr: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"&&iQ(p,d),KR(e,u),e.conditions.push(p)}else d&&Jt("no attribute or comparison specified");else(d||e.length>0&&c)&&e.push(df(d));return e}else Jt(t?`expected '${t}', but encountered '${f[0]}'`:`unexpected token '${f[0]}'`);default:Jt(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?_Te:uf,r.lastIndex=kr),kr===ra.length)return e}t&&Jt(`expected '${t}', but encountered end of string`)}function KR(e,t){e.conditions.length>0&&(e.operator?e.operator!==t&&Jt("Can not mix operators within a condition grouping"):e.operator=t)}function df(e){return e.indexOf(".")>-1?e.split(".").map(df):decodeURIComponent(e)}function sQ(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 Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function iQ(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function oQ(e){let t=aQ(e[0]);return e.length>1&&(t.next=oQ(e.slice(1))),t}function aQ(e){if(Array.isArray(e)){let t=aQ(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}}Jt(`Unknown sort type ${e}`)}function hf(e){return Array.isArray(e)?e.join("\0"):e}function ta(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function gTe(e,t,r){return t*r/ta(e)}var Xr,$s,so,Ec,uTe,dTe,fTe,mTe,ZL,tD,XL,ETe,uf,_Te,kr,wi,ra,ff,mg=ce(()=>{Xr=w(ge()),$s=w(Vt()),so=require("ordered-binary"),Ec=require("lmdb");bT();Vc();uTe=.3,dTe=.1,fTe=.05,mTe={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},ZL={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};o(eD,"executeConditions");o(mf,"searchByIndex");o(io,"findAttribute");o(hTe,"joinTo");o(pTe,"joinFrom");tD={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(Qp,"filterByType");o(YR,"estimateCondition");XL=class extends Xr.Violation{static{o(this,"SyntaxViolation")}},ETe=/[()[\]|!<>.]|(=\w*=)/,uf=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,_Te=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;o(fg,"parseQuery");o(Jt,"recordError");o(jp,"parseBlock");o(KR,"assignOperator");o(df,"decodeProperty");o(sQ,"typedDecoding");o(iQ,"wildcardDecoding");o(oQ,"toSortObject");o(aQ,"toSortEntry");ff=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(hf,"flattenKey");o(ta,"estimatedEntryCount");o(gTe,"intersectionEstimate")});var xB={};we(xB,{MultiPartId:()=>WR,Resource:()=>Br,contextStorage:()=>Ef,snakeCase:()=>TTe,transformForSelect:()=>_f});function TTe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function cQ(e,t){if(tu=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(tu=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new WR;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){tu=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return tu=!0,null;e[e.length-1]==="/"&&(tu=!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 _o?a=i:d=i;else if(s&&typeof s=="object")d=s,s=void 0,c=d.getId?.()??d[this.primaryKey];else throw new pf.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 ui,l.id=c,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new ui,l.id=c,c==null&&(u=!0);l||(l=new ui,l.id=c),u&&(l.isCollection=!0);let f;a||(a=Ef.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(_=>Ef.run(a,()=>p(_)),"runAction")),a?.transaction){let _=this.getResource(c,a,f);return _.then?_.then(h):h(_)}else return Ft(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(R=>{if(!R)throw new pf.AccessViolation(a.user);return typeof d?.then=="function"?d.then(T=>e(_,l,a,T)):e(_,l,a,d)});if(!g)throw new pf.AccessViolation(a.user)}return typeof d?.then=="function"?d.then(g=>e(_,l,a,g)):e(_,l,a,d)}o(p,"authorizeActionOnResource")}}function ds(e,t){let r=new pf.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 rD(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 _f(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):rD(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(rD(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(rD(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]=_f(c.select||c,d)}let u=a(c.name);return l(u)}else return a(c);else return c}}o(i,"handleProperty")}var lQ,uQ,pf,dQ,Ef,STe,Br,tu,WR,xa=ce(()=>{lQ=require("crypto");tm();Ru();uQ=w(Zs()),pf=w(ge());Bc();mg();dQ=require("async_hooks");lg();Ef=new dQ.AsyncLocalStorage,STe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Br=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(t.constructor.loadAsInstance===!1)return i;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=_f(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):ds(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):ds(t,"patch")},{hasContent:!0,type:"update"});static delete=Hn(function(t,r,n,s){return t.delete?t.delete(r):ds(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,lQ.randomUUID)()}static create(t,r,n){n?n.getContext&&(n=n.getContext()):n=Ef.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),Ft(n,async()=>{let i=new this(s,n),a=await i.create?i.create(s,r):ds(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):ds(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):ds(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Hn(function(t,r,n,s){return t.subscribe?t.subscribe(r):ds(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):ds(t,"publish")},{hasContent:!0,type:"create"});static search=Hn(function(t,r,n){let s=t.search?t.search(r):ds(t,"search"),i=n.select;if(i&&n.hasOwnProperty("select")&&s!=null&&!s.selectApplied){let a=_f(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):ds(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):ds(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):ds(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#r)return(await this.constructor.create(this.#e,t,this.#t)).#e;ds(this,"post")}static isCollection(t){return t&&t.#r}get isCollection(){return this.#r}static coerceId(t){return t}static parseQuery(t,r){return fg(t,r)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let a=t.slice(s+1),c=r?.headers&&STe[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:cQ(t,this),isCollection:tu}}let i=cQ(t,this);return tu?{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 Vn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Vn}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,uQ._assignPackageExport)("Resource",Br);o(TTe,"snakeCase");o(cQ,"pathToId");WR=class extends Array{static{o(this,"MultiPartId")}toString(){return this.join("/")}};o(Hn,"transactional");o(ds,"missingMethod");o(rD,"selectFromObject");o(_f,"transformForSelect")});var UY={};we(UY,{EVICTED:()=>eu,INVALIDATED:()=>Fn,coerceType:()=>jR,makeTable:()=>JR});function JR(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:R}=e;_??=0;let{attributes:T}=e;T||(T=[]);let y=JL(i,n,l),N,O,F={},Z=Promise.resolve(),G,Y,K;for(let V of T)(V.assignCreatedTime||V.name==="__createdtime__")&&(G=V),(V.assignUpdatedTime||V.name==="__updatedtime__")&&(Y=V),V.expiresAt&&(K=V),V.isPrimaryKey&&(F=V);let $,le=[],ue=[],se=1,me=2,Pe={},De={},dt=864e5,Ye=0,qn,rt,ht,Cc=!1,Pc,$t,vf,Uf=nu.get(U.REPLICATION_DATABASES);if(Array.isArray(Uf)){for(let V of Uf)if(V.name===c&&V.replicateTo>=0){vf=V.replicateTo;break}}let IE=i.getRange({start:!1,end:!1}).constructor,NE=10,xy=6;g&&Hf(),kp(i.env.path,V=>{if(O)return Ta(V)});class xf extends al{static{o(this,"Updatable")}getUpdatedTime(){return pc.get(this.getRecord())?.version}getExpiresAt(){return pc.get(this.getRecord())?.expiresAt}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.set(E,new Ym(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(E,S){return this.addTo(E,-S)}}class Ce extends Br{#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=G;static updatedTimeProperty=Y;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(L=>!L.intermediateSource)){if(this.sources.some(L=>L.name===E.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(E)}O=O||E.get&&(!E.get.reliesOnPrototype||E.prototype.get),N=N||E.load;let A=o(L=>{let D=this.sources;if(D=D.filter(H=>H.intermediateSource&&H[L]&&(!H[L].reliesOnPrototype||H.prototype[L])),D.length>0)if(D.length===1){let H=D[0];return(C,x,z)=>{if(C?.source!==H)return H[L](x,z,C)}}else return(H,C,x)=>{let z=[];for(let ne of D){if(H?.source===ne)break;z.push(ne[L](C,x,H))}return Promise.all(z)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1];b.intermediateSource&&(b={});let I=o(L=>{if(b[L]&&(!b[L].reliesOnPrototype||b.prototype[L]))return(D,H,C)=>{if(!D?.source)return b[L](H,C,D)}},"getApplyToCanonicalSource");Pe={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},De={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let P=b.shouldRevalidateEvents;return(async()=>{let L=!1,D,H=o(async(C,x)=>{let z=C.value,ne=C.table?He[c][C.table]:Ce;if(c===Vf&&(C.table===gu.ROLE_TABLE_NAME||C.table===gu.USER_TABLE_NAME)&&(L=!0),C.id===void 0&&(C.id=z[ne.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));C.source=E;let re={residencyId:Mc(C.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:C.nodeId,async:!0},B=C.id,de=await ne.getResource(B,x,re);switch(C.finished&&await C.finished,C.type){case"put":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!0,re);case"patch":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!1,re);case"delete":return de._writeDelete(B,re);case"publish":case"message":return de._writePublish(B,z,re);case"invalidate":return de._writeInvalidate(B,z,re);case"relocate":return de._writeRelocate(B,re);default:ve.default.error?.("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=E.subscribe;C&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},z=E.subscribeOnThisThread?E.subscribeOnThisThread((0,ru.getWorkerIndex)(),x):(0,ru.getWorkerIndex)()===0,ne=C&&z&&await E.subscribe?.(x);if(ne){let re;for await(let B of ne)try{if(!(B.type==="transaction"?B.writes[0]:B)){ve.default.error?.("Bad subscription event",B);continue}if(B.source=E,B.type==="end_txn"){if(re?.resolve(),B.localTime&&D!==B.localTime){if(B.remoteNodeIds?.length>0){let Se=[Symbol.for("seq"),B.remoteNodeIds[0]],ee=d.get(Se),j=ee?.nodes;j||(j=[]);for(let Te of B.remoteNodeIds.slice(1)){let fe=j.find(We=>We.id===Te);j=j.filter(We=>We.id!==Te||We===fe),fe||(fe={id:Te,seqId:0},j.push(fe)),fe.seqId=Math.max(ee?.seqId??1,B.localTime),Te===re?.nodeId&&(fe.lastTxnTime=B.timestamp)}let pe=Math.max(ee?.seqId??1,B.localTime);ve.default.trace?.("Received txn",c,pe,new Date(pe),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(Se,{seqId:pe,nodes:j})}D=B.localTime}B.onCommit&&re?.committed.then(B.onCommit);continue}if(re)if(B.beginTxn)re.resolve();else{re.write_promises.push(H(B,re));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let he=Ft(B,()=>{if(B.type==="transaction"){let Se=[];for(let ee of B.writes)try{Se.push(H(ee,B))}catch(j){throw j.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(B),j}return Promise.all(Se)}else if(B.type==="define_schema"){let Se=this.attributes.slice(0),ee=!1;for(let j of B.attributes)Se.find(pe=>pe.name===j.name)||(Se.push(j),ee=!0);ee&&(ze({table:s,database:c,attributes:Se,origin:"cluster"}),Xp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,q.CREATE_TABLE,c,s)))}else return B.beginTxn?(re=B,re.write_promises=[H(B,B)],new Promise(Se=>{re.resolve=()=>Se(Promise.all(re.write_promises))})):H(B,B)});re&&(re.committed=he),L&&he&&!he?.waitingForUserChange&&(he.then(()=>Xp.signalUserChange(new Zp.UserEventMsg(process.pid))),he.waitingForUserChange=!0),B.onCommit&&(he?he.then(B.onCommit):B.onCommit())}catch(de){ve.default.error?.("error in subscription handler",de)}}}catch(C){ve.default.error?.(C)}})(),this}static get isCaching(){return O}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(E,S,A){let b=super.getResource(E,S,A);if(this.loadAsInstance===!1&&(S._freezeRecords=!0),E!=null&&this.loadAsInstance!==!1){Pr(E);try{if(b.getRecord?.())return b;if(typeof E=="object"&&E&&!Array.isArray(E))throw new Error(`Invalid id ${JSON.stringify(E)}`);let I=!A?.async||i.cache?.get?.(E),P=Lr(S),L=P.getReadTxn();if(L?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ea(E,S,{transaction:L,ensureLoaded:A?.ensureLoaded},I,D=>{if(D?Ce._updateResource(b,D):b.#e=null,S.onlyIfCached){if(!b.doesExist())throw new ct.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let H=Lc(E,D,S,b);if(H)return P?.disregardReadTxn(),b.#i=!0,S.loadedFromSource=!0,Vs(H,C=>(Ce._updateResource(b,C),b))}return b})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(E)),I}}return b}static _updateResource(E,S){E.#n=S,E.#e=S?.value??null,E.#r=S?.version}ensureLoaded(){let E=Lc(this.getId(),this.#n,this.getContext());if(E)return this.#i=!0,this.getContext().loadedFromSource=!0,Vs(E,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let E=F?.type;if(E==="String"||E==="ID")return super.getNewId();if(!$t){let I=i.getEntry(Symbol.for("id_allocation")),P=I?.value,L;if(P&&P.nodeName===server.hostname&&(!LTe(i)||P.pid===process.pid)){let D=P.start,H=P.end;L=D;for(let C of i.getKeys({start:H,end:D,limit:1,reverse:!0}))L=C}else P=b(I?.version??null),L=P.start;$t=new BigInt64Array([BigInt(L)+1n]),$t=new BigInt64Array(i.getUserSharedBuffer("id",$t.buffer)),$t.maxSafeId=P.end}let S=Number(Atomics.add($t,0,1n)),A=E==="Int"?512:1048576;if(S+A>=$t.maxSafeId){let I=o(P=>{$t.maxSafeId=S+(E==="Int"?1023:4194303);let L=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=P?void 0:i.useReadTransaction(),H=Number($t[0]);for(let z of i.getKeys({start:H+1,end:L,limit:1,transaction:D}))L=z;D?.done();let{value:C,version:x}=i.getEntry(Symbol.for("id_allocation"));if($t.maxSafeId<L){if(C.end>$t.maxSafeId-100)return;ve.default.info?.("New id allocation",S,$t.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:C.start,end:$t.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{ve.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${$t.maxSafeId}, but id of ${L} detected`);let z=b(x);z.alreadyUpdated||Atomics.store($t,0,BigInt(z.start+1)),$t.maxSafeId=z.end}},"updateEnd");S+A===$t.maxSafeId?setImmediate(I):S+100>=$t.maxSafeId&&(ve.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(()=>I(!0)))}return S;function b(I){let P=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=P/4,D,H,C=!1,x,z;do{x=Math.floor(Math.random()*P),z={start:x,end:x+(E==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},D=0;for(let ne of i.getKeys({start:x,limit:1,reverse:!0}))D=ne;H=P;for(let ne of i.getKeys({start:x+1,end:P,limit:1}))H=ne;L*=.875,L<1e3&&!C&&(C=!0,ve.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":""}`,x,D,H,L))}while(!(L<H-x&&(L<x-D||D===0)));return i.transactionSync(()=>{let ne=i.getEntry(Symbol.for("id_allocation"));return(ne?.version??null)==I?(ve.default.info?.("Allocated new id range",z),i.put(Symbol.for("id_allocation"),z,Date.now()),z):(ve.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ne.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,dt=E.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");dt=dt||(p+_)/4,Ta()}static getResidencyRecord(E){return d.get([Symbol.for("residency_by_id"),E])}static setResidency(E){Ce.getResidency=E&&((S,A)=>{try{return E(S,A)}catch(b){throw b.message+=` in residency function for table ${s}`,b}})}static setResidencyById(E){Ce.getResidencyById=E&&(S=>{try{return E(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(E,S){if(Ce.getResidencyById)return Ce.getResidencyById(E[t]);let A=vf;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 b=[server.hostname];if(S.previousResidency)b.push(...S.previousResidency.slice(0,A));else{let I=server.nodes.map(D=>D.name),P=Math.floor(I.length*Math.random());b.push(...I.slice(P,P+A));let L=P+A-I.length;L>0&&b.push(...I.slice(0,L))}return b}}static enableAuditing(E=!0){g=E,E&&Hf(),Ce.audit=E}static coerceId(E){return E===""?null:jR(E,F)}static async dropTable(){delete He[c][s];for(let E of i.getRange({versions:!0,snapshot:!1,lazy:!0}))E.metadataFlags&$r&&E.value&&Ia(E.value);if(c===a){for(let E of T)d.remove(Ce.tableName+"/"+E.name),r[E.name]?.drop();d.remove(Ce.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),sD.default.unlinkSync(i.env.path);Xp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,q.DROP_TABLE,c,s))}get(E){let S=this.constructor;if(typeof E=="string"&&S.loadAsInstance!==!1)return this.getProperty(E);if(Ff(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?Ce.getRecordCount().then(b=>(A.recordCount=b.recordCount,A.estimatedRecordRange=b.estimatedRange,A)):A}if(E!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),b=Lr(A),I=b.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let P=Rr(E);Pr(P);let L=!0;return E.checkPermission&&(L=this.allowRead(A.user,E)),Vs(Vs(L,D=>{if(!D)throw new ct.AccessViolation(A.user);let H=!0;return Ea(P,A,{transaction:I,ensureLoaded:H},!1,C=>{if(A.onlyIfCached){if(!C?.value)throw new ct.ServerError("Entry is not cached",504)}else if(H){let x=Lc(P,C,A);if(x)return b?.disregardReadTxn(),A.loadedFromSource=!0,x.then(z=>z?.value)}return C?.value})}),D=>{let H=E?.select;return H&&D!=null?_f(H,this.constructor)(D):D})}if(E?.property)return this.getProperty(E.property);if(this.doesExist()||E?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(E,S){let A=_a(E,S);if(A?.read){if(A.isSuperUser)return!0;let b=A.attribute_permissions,I=S?.select;if(b?.length>0||Cc&&I){if(S||(S={}),I){let P=Array.isArray(I)?I:[I],L=b?.length>0&&nD(b,"read");S.select=P.map(D=>{let H=D.name||D;if(!L||L[H]){let C=ht[H]?.definition?.tableClass;if(C){if(D.name||(D={name:D}),!D.checkPermission&&S.checkPermission&&(D.checkPermission=S.checkPermission),!C.prototype.allowRead.call(null,E,D))return!1;if(!D.select)return D.name}return D}}).filter(Boolean)}else S.select=b.filter(P=>P.read&&!ht[P.attribute_name]).map(P=>P.attribute_name);return S}else return!0}}allowUpdate(E,S,A){let b=_a(E,A);if(b?.update){let I=b.attribute_permissions;if(I?.length>0){let P=nD(I,"update");for(let L in S)if(!P[L])return!1;for(let L of I){let D=L.attribute_name;!L.update&&!(D in S)&&(S[D]=this.getProperty(D))}}return Sa(this.getContext())}}allowCreate(E,S,A){if(this.isCollection){let b=_a(E,A);if(b?.insert){let I=b.attribute_permissions;if(I?.length>0){let P=nD(I,"insert");for(let L in S)if(!P[L])return!1;return Sa(this.getContext())}else return Sa(this.getContext())}}else return this.allowUpdate(E,{})}allowDelete(E,S){return _a(E,S)?.delete&&Sa(this.getContext())}update(E,S){let A,b=typeof S=="boolean"||S===void 0&&(E==null||typeof E=="object"&&!(E instanceof URLSearchParams)),I=!1;b?(I=S,S=E,A=this.getId()):A=Rr(E);let P=this.getContext();if(!Lr(P))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(I)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(b){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(P.user,S,E)),Vs(D,H=>{if(!H)throw new ct.AccessViolation(P.user);return Vs(i.get(Rr(E)),C=>{let x=new xf(C);return x._setChanges(S),this._writeUpdate(A,x.getChanges(),!1),x})})}return this._writeUpdate(A,this.#t,I),this}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.#s===mQ?this.set(E,(+this.getProperty(E)||0)+S):(this.#s||this.update(),this.set(E,new Ym(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)),Vs(S,b=>{if(!b)throw new ct.AccessViolation(A.user);this._writeInvalidate(E?Rr(E):this.getId())})}_writeInvalidate(E,S,A){let b=this.getContext();Pr(E),Lr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Pe.invalidate?.bind(this,b,E),beforeIntermediate:Ra(S,De.invalidate?.bind(this,b,E)),commit:o((P,L)=>{if(!(ga(P,L,A?.nodeId)<=0)){S??=null;for(let D in r)S||(S={}),S[D]===void 0&&(S[D]=this.getProperty(D));ve.default.trace?.(`Invalidating entry in ${s} id: ${E}, timestamp: ${new Date(P).toISOString()}`),y(E,S,L,P,Fn,g,{user:b?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(E,S){let A=this.getContext();Pr(E),Lr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Pe.relocate?.bind(this,A,E),beforeIntermediate:De.relocate?.bind(this,A,E),commit:o((I,P)=>{if(ga(I,P,S?.nodeId)<=0)return;let L=Ce.getResidencyRecord(S.residencyId),D=0,H=null,C=P?.value;if(L&&!L.includes(server.hostname)){for(let x in r)H||(H={}),H[x]=C[x];D=Fn}else H=C;ve.default.trace?.(`Relocating entry id: ${E}, timestamp: ${new Date(I).toISOString()}`),y(E,H,P,I,D,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(E,S){if(this.getResidencyById)return!1;let A={previousResidency:this.getResidencyRecord(E.residencyId),isRelocation:!0},b=Dc(this.getResidency(S.value,A)),I;if(b){if(!b.includes(server.hostname))return!1;I=Mc(b)}let P=0;ve.default.debug?.("Performing a relocate of an entry",E.key,S.value,b);let L=y(E.key,S.value,E,E.version,P,!0,{residencyId:I,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(E,S,A){let b=this.Source,I;if(!((O||g)&&(!S||(I=i.getEntry(E),!I||!S)||I.version!==A))){if(O){if(i.hasLock(E,I.version))return;let P;for(let L in r)P||(P={}),P[L]=S[L];if(P)return y(E,P,I,A,eu,null,null,null,!0)}return i.ifVersion(E,A,()=>{po(E,S,null)}),Zl(i,I??i.getEntry(E),A)}}lock(){throw new Error("Not yet implemented")}static operation(E,S){return E.table||=s,E.schema||=c,global.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 b=this.getContext();return E.checkPermission&&(A=this.allowUpdate(b.user,S,E)),Vs(A,I=>{if(!I)throw new ct.AccessViolation(b.user);if(Array.isArray(S))for(let P of S){let L=P[t];this._writeUpdate(L,P,!0)}else{let P=Rr(E);this._writeUpdate(P,S,!0)}})}}create(E,S){let A=!0,b=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(b.user,S,E)),Vs(A,I=>{if(!I)throw new ct.AccessViolation(b.user);let P=Rr(E)??S[t];if(P===void 0)P=this.constructor.getNewId();else if(i.get(P))throw new ct.ClientError("Record already exists",409);return this._writeUpdate(P,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,b){let I=this.getContext(),P=Lr(I);Pr(E);let L=this.#n??i.getEntry(E);this.#s=A?mQ:wTe;let D=o(C=>A?C.put?()=>C.put(I,E,S):null:C.patch?()=>C.patch(I,E,S):C.put?()=>C.put(I,E,cl(this)):null,"writeToSources"),H={key:E,store:i,entry:L,nodeName:I?.nodeName,validate:o(C=>{S||(S=this.#t),A||S&&K_(this.#t===S?this:S)?I?.source||(P.checkOverloaded(),this.validate(S,!A),Y&&(S[Y.name]=Y.type==="Date"?new Date(C):Y.type==="String"?new Date(C).toISOString():C),A&&(t&&S[t]!==E&&(S[t]=E),G&&(L?.value?S[G.name]=L?.value[G.name]:S[G.name]=G.type==="Date"?new Date(C):G.type==="String"?new Date(C).toISOString():C),S=cl(S))):P.removeWrite(H)},"validate"),before:D(Pe),beforeIntermediate:Ra(S,D(De)),commit:o((C,x,z)=>{if(z){if(I&&x?.version>(I.lastModified||0)&&(I.lastModified=x.version),this.#n=x,x?.value&&x.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=x?.value??null)}this.#t=void 0,this.#r=C;let ne=x?.value,re=S;this.#s=0;let B=!1,de=ga(C,x,b?.nodeId),he,Se=A?"put":"patch",ee;b?.residencyId!=null&&(ee=b.residencyId);let j=I?.expiresAt??(p?p+Date.now():-1);if(de<=0){if(g){let fe=x.localTime,We=x.version;ve.default.trace?.("Applying CRDT update to record with id: ",E,"txn time",new Date(C),"applying later update from:",new Date(We),"local recorded time",new Date(fe));let St=[];for(;fe>C||We>=C&&fe>0;){let ft=l.get(fe);if(!ft)break;let Ee=Nt(ft);if(We=Ee.version,We>=C){if(We===C){if(de=ga(C,{version:We,localTime:fe},b?.nodeId),de===0)return Te(!1);if(de>0)continue}if(Ee.type==="patch")St.push(Ee),he=S;else if(Ee.type==="put"||Ee.type==="delete")return Te(!1)}fe=Ee.previousLocalTime}fe||ve.default.debug?.("No further audit history, applying incremental updates based on available history",E,"existing version preserved",x),St.sort((ft,Ee)=>ft.version-Ee.version);for(let ft of St){let Ee=ft.getValue(i);if(ve.default.debug?.("Rebuilding update with future patch:",new Date(ft.version),Ee,ft),re=$_(re,Ee,A),!re)return Te(!1)}}else{if(A)return Te(!1);re=$_(re,ne,A),ve.default.debug?.("Rebuilding update without audit:",re)}ve.default.trace?.("Rebuilt record to save:",re," is full update:",A)}let pe;if(A?pe=re:this.constructor.loadAsInstance===!1?pe=cl(ne,re):(this.#e=ne,pe=cl(this,re)),this.#e=pe,pe&&pe.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(ee==null){L?.residencyId&&(I.previousResidency=Ce.getResidencyRecord(L.residencyId));let fe=Dc(Ce.getResidency(pe,I));if(fe&&!fe.includes(server.hostname))if(he??=pe,B=!0,Ce.getResidencyById)pe=void 0;else{pe=null;for(let We in r)pe||(pe={}),pe[We]=he[We]}ee=Mc(fe)}A||(he=S),ve.default.trace?.(`Saving record with id: ${E}, timestamp: ${new Date(C).toISOString()}${j?", expires at: "+new Date(j).toISOString():""}${x?", replaces entry from: "+new Date(x.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(pe).slice(0,100)}catch{return""}})()),po(E,ne,pe),Te(!0),I.expiresAt&&Ta();function Te(fe){y(E,fe?pe:void 0,fe?x:{...x,value:void 0},C,B?Fn:0,g,{omitLocalRecord:B,user:I?.user,residencyId:ee,expiresAt:j,nodeId:b?.nodeId,originatingOperation:I?.originatingOperation},Se,!1,fe?he:he??S)}o(Te,"writeCommit")},"commit")};P.addWrite(H)}async delete(E){if(Ff(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)),Vs(S,b=>{if(!b)throw new ct.AccessViolation(A.user);let I=Rr(E);return this._writeDelete(I),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(E,S){let A=Lr(this.getContext());Pr(E);let b=this.getContext();return A.addWrite({key:E,store:i,entry:this.#n,nodeName:b?.nodeName,before:Pe.delete?.bind(this,b,E),beforeIntermediate:De.delete?.bind(this,b,E),commit:o((I,P,L)=>{let D=P?.value;L&&(b&&P?.version>(b.lastModified||0)&&(b.lastModified=P.version),Ce._updateResource(this,P)),!(ga(I,P,S?.nodeId)<=0)&&(po(this.getId(),D),ve.default.trace?.(`Deleting record with id: ${E}, txn timestamp: ${new Date(I).toISOString()}`),g||R?(y(E,null,P,I,0,g,{user:b?.user,nodeId:S?.nodeId},"delete"),g||Ta()):Zl(i,P))},"commit")}),!0}search(E){let S=this.getContext(),A=Lr(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 ct.AccessViolation(S.user);let b=E.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(E)?E:E[Symbol.iterator]?Array.from(E):[];let I=E.id??this.getId();I&&(b=[{attribute:null,comparator:Array.isArray(I)?"prefix":"starts_with",value:I}].concat(b));let P,L={};function D(j,pe){let Te;switch(pe){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Te=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}for(let fe of j){if(fe.conditions){fe.conditions=D(fe.conditions,fe.operator);continue}let We=fe[0]??fe.attribute,St=We==null?F:io(T,We);if(St)(St.type||ZL[fe.comparator])&&(fe[1]===void 0?fe.value=C(fe.value,St):fe[1]=C(fe[1],St));else if(We!=null&&!E.allowConditionsOnDynamicAttributes)throw(0,ct.handleHDBError)(new Error,`${We} is not a defined attribute`,404);if(fe.chainedConditions)if(fe.chainedConditions.length===1&&(!fe.operator||fe.operator=="and")){let ft=fe.chainedConditions[0],Ee,pt;if(ft.comparator==="gt"||ft.comparator==="greater_than"||ft.comparator==="ge"||ft.comparator==="greater_than_equal"?(Ee=fe,pt=ft):(Ee=ft,pt=fe),Ee.comparator!=="lt"&&Ee.comparator!=="less_than"&&Ee.comparator!=="le"&&Ee.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let tt=pt.comparator==="ge"||pt.comparator==="greater_than_equal",cr=Ee.comparator==="le"||Ee.comparator==="less_than_equal";fe.comparator=(tt?"ge":"gt")+(cr?"le":"lt"),fe.value=[pt.value,Ee.value]}else throw new Error("Multiple chained conditions are not currently supported")}return j}o(D,"prepareConditions");function H(j,pe){if(E.enforceExecutionOrder)return j;for(let Te of j)Te.conditions&&(Te.conditions=H(Te.conditions,Te.operator));return j.length>1&&pe!=="or"?RTe(j,YR(Ce)):j}o(H,"orderConditions");function C(j,pe){return Array.isArray(j)?j.map(Te=>jR(Te,pe)):jR(j,pe)}o(C,"coerceTypedValues");let x=E.operator;(b.length>0||x)&&(b=D(b,x));let z=typeof E.sort=="object"&&E.sort,ne;if(z&&x!=="or"){let j=z.attribute;if(j==null)throw new ct.ClientError("Sort requires an attribute");if(P=b.find(pe=>hf(pe.attribute)===hf(j)),!P){let pe=io(T,j);if(!pe)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);if(pe.indexed)P={...z,comparator:"sort"},b.push(P);else if(b.length===0&&!E.allowFullScan)throw(0,ct.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not indexed and not combined with any other conditions`,404)}P&&(P.descending=!!z.descending)}b=H(b,x),z&&(P&&b[0]===P?z.next&&(ne={dbOrderedAttribute:z.attribute,attribute:z.next.attribute,descending:z.next.descending,next:z.next.next}):(P&&b.splice(b.indexOf(P),1),ne=z));let re=E.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),E.explain)return{conditions:b,operator:x,postOrdering:ne,selectApplied:!!re};let B=A.useReadTxn(),de=eD(b,x,Ce,B,E,S,(j,pe)=>pu(j,re,S,B,pe),L),he=E.ensureLoaded!==!1,Se=Ce.transformEntryForSelect(re,S,B,L,he,!0),ee=Ce.transformToOrderedSelect(de,re,ne,S,B,Se);return(E.offset||E.limit!==void 0)&&(ee=ee.slice(E.offset,E.limit!==void 0?(E.offset||0)+E.limit:void 0)),ee.onDone=()=>{ee.onDone=null,A.doneReadTxn()},ee.selectApplied=!0,ee.getColumns=()=>{if(re){let j=[];for(let pe of re)pe==="*"?j.push(...T.map(Te=>Te.name)):j.push(pe.name||pe);return j}return T.filter(j=>!j.computed&&!j.relationship).map(j=>j.name)},ee}static transformToOrderedSelect(E,S,A,b,I,P){let L=new IE;if(A){E=pu(E,S,b,I,null);let D;L.iterate=function(){let C,x=E[Symbol.asyncIterator]?E[Symbol.asyncIterator]():E[Symbol.iterator](),z,ne=A.dbOrderedAttribute,re,B,de=!0;function he(ee){let j=ee.next&&he(ee.next),pe=ee.descending;return b.sort=ee,(Te,fe)=>{let We=hu(Te,ee.attribute,b),St=hu(fe,ee.attribute,b),ft=pe?(0,su.compareKeys)(St,We):(0,su.compareKeys)(We,St);return ft===0?j?.(Te,fe)||0:ft}}o(he,"createComparator");let Se=he(A);return{async next(){let ee;if(C)if(ee=C.next(),ee.done){if(z)return L.onDone&&L.onDone(),ee}else return{value:await P.call(this,ee.value)};D=[],re&&D.push(re);do if(ee=await x.next(),ee.done){if(z=!0,D.length)break;return L.onDone&&L.onDone(),ee}else{let j=ee.value;if(j?.then&&(j=await j),ne){let pe=hu(j,ne,b);if(de)de=!1,B=pe;else if(pe!==B){B=pe,re=j;break}}D.push(j)}while(!0);return A.isGrouped,D.sort(Se),C=D[Symbol.iterator](),ee=C.next(),ee.done?(L.onDone&&L.onDone(),ee):{value:await P.call(this,ee.value)}},return(){L.onDone&&L.onDone(),x.return()},throw(){L.onDone&&L.onDone(),x.throw()}}};let H=o(C=>{if(typeof S=="object"&&Array.isArray(C.attribute))for(let x=0;x<S.length;x++){let z=S[x],ne;if(z.name===C.attribute[0]){for(ne=z.sort||(z.sort={});ne.next;)ne=ne.next;ne.attribute=C.attribute.slice(1),ne.descending=C.descending}else z===C.attribute[0]&&(S[x]=ne={name:z,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&H(C.next)},"applySortingOnSelect");H(A)}else L.iterate=(E[Symbol.asyncIterator]||E[Symbol.iterator]).bind(E),L=L.map(function(D){try{let H=P.call(this,D);return typeof H?.catch=="function"?H.catch(C=>{throw C.partialObject={[t]:D.key},C}):H}catch(H){throw H.partialObject={[t]:D.key},H}});return L}static transformEntryForSelect(E,S,A,b,I,P){let L;I&&O&&!(typeof E=="string"?[E]:E)?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(L=!0);let D,H=o(function(C){let x;if(S?.transaction?.stale&&(S.transaction.stale=!1),C!=null){if(x=C.deref?C.deref():C.value,!x&&(C.key===void 0||C.deref)||C.metadataFlags&Fn){if(C.metadataFlags&Fn&&S.replicateFrom===!1&&P&&C.residencyId)return gc.SKIP;if(C=Ea(C.key??C,S,{transaction:A,lazy:E?.length<4,ensureLoaded:I},this?.isSync,z=>z),C?.then)return C.then(H.bind(this));x=C?.value}if(L&&C?.metadataFlags&(Fn|eu)||C?.expiresAt!=null&&C?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:C.key,message:"This entry has expired"};let z=Lc(C.key??C,C,S);if(z?.then)return z.then(H)}}if(x==null)return P?gc.SKIP:x;if(E&&!(E[0]==="*"&&E.length===1)){let z,ne=o((B,de)=>{let he;typeof B=="object"?he=B.name:he=B;let Se=ht?.[he],ee;if(Se){let j=b?.[he];if(j)if(j.hasMappings){let Te=Se.from?x[Se.from]:hf(C.key);ee=j.get(Te),ee||(ee=[])}else ee=j.fromRecord?.(x);else ee=Se(x,S,C,!0);let pe=o(Te=>{if(Se.directReturn)return de(Te,he);if(Te&&typeof Te=="object"){let fe=Se.definition?.tableClass||Ce;D||(D={});let We=D[he]||(D[he]=fe.transformEntryForSelect(he===B?null:B.select||(Array.isArray(B)?B:null),S,A,j,I));if(Array.isArray(Te)){let St=[],ft=fe.transformToOrderedSelect(Te,B.select,typeof B.sort=="object"&&B.sort,S,A,We)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ee=o(tt=>{for(;!tt.done;){if(tt?.then)return tt.then(Ee);St.push(tt.value),tt=ft.next()}de(St,he)},"nextValue"),pt=Ee(ft.next());pt&&(z||(z=[]),z.push(pt));return}else if(Te=We.call(this,Te),Te?.then){z||(z=[]),z.push(Te.then(St=>de(St,he)));return}}de(Te,he)},"handleResolvedValue");ee?.then?(z||(z=[]),z.push(ee.then(pe))):pe(ee);return}else ee=x[he],ee&&typeof ee=="object"&&he!==B&&(ee=Ce.transformEntryForSelect(B.select||B,S,A,null)({value:ee}));de(ee,he)},"selectAttribute"),re;if(typeof E=="string")ne(E,B=>{re=B});else if(Array.isArray(E))if(E.asArray)re=[],E.forEach((B,de)=>{B==="*"?E[de]=x:ne(B,he=>re[de]=he)});else{re={};let B=E.forceNulls;for(let de of E)if(de==="*")for(let he in x)re[he]=x[he];else ne(de,(he,Se)=>{he===void 0&&B&&(he=null),re[Se]=he})}else throw new ct.ClientError("Invalid select"+E);return z?Promise.all(z).then(()=>re):re}return x},"transform");return H}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=[],b=this,I=VN(Ce,this.getId()??null,function(L,D,H,C){try{let x=D.getValue?.(i,S),z=D.type;if(!x&&z==="patch"&&S){let re=i.getEntry(L);re?.version===D.version?x=re.value:x=D.getValue?.(i,!0,H),z="put"}let ne={id:L,localTime:H,value:x,version:D.version,type:z,beginTxn:C};A?A.push(ne):this.send(ne)}catch(x){ve.default.error?.(x)}},E.startTime||0,E),P=(async()=>{this.isCollection&&(I.includeDescendants=!0,E.onlyChildren&&(I.onlyChildren=!0)),E.supportsTransactions&&(I.supportsTransactions=!0);let L=this.getId(),D=E.previousCount;D>1e3&&(D=1e3);let H=E.startTime;if(this.isCollection){if(H){if(D)throw new ct.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:C,value:x}of l.getRange({start:H,exclusiveStart:!0,snapshot:!1})){let z=Nt(x);if(z.tableId!==n)continue;let ne=z.recordId;if(L==null||_Q(L,ne)){let re=z.getValue(i,S,C);if(I.send({id:ne,localTime:C,value:re,version:z.version,type:z.type}),I.queue?.length>pQ&&await I.waitForDrain()===!1)return}I.startTime=C}}else if(D){let C=[];for(let{key:x,value:z}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ne=Nt(z);if(ne.tableId!==n)continue;let re=ne.recordId;if(L==null||_Q(L,re)){let B=ne.getValue(i,S,x);if(C.push({id:re,localTime:x,value:B,version:ne.version,type:ne.type}),--D<=0)break}}catch(ne){ve.default.error("Error getting history entry",x,ne)}for(let x=C.length;x>0;)I.send(C[--x]);C[0]&&(I.startTime=C[0].localTime)}else if(!E.omitCurrent){for(let{key:C,value:x,version:z,localTime:ne}of i.getRange({start:L??!1,end:L==null?void 0:[L,su.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(I.send({id:C,localTime:ne,value:x,version:z,type:"put"}),I.queue?.length>pQ&&await I.waitForDrain()===!1))return}}else{D&&!H&&(H=0);let C=this.#n?.localTime;if(C===QL&&(i.cache?.delete(L),this.#n=i.getEntry(L),ve.default.trace?.("re-retrieved record",C,this.#n?.localTime),C=this.#n?.localTime),ve.default.trace?.("Subscription from",H,"from",L,C),H<C){let x=[],z=C;do{let ne=l.get(z);if(ne){E.omitCurrent=!0;let re=Nt(ne),B=re.getValue(i,S,z);S&&(re.type="put"),x.push({id:L,value:B,localTime:z,...re}),z=re.previousLocalTime}else break;D&&D--}while(z>H&&D!==0);for(let ne=x.length;ne>0;)I.send(x[--ne]);I.startTime=C}!E.omitCurrent&&this.doesExist()&&I.send({id:L,localTime:C,value:this.#e,version:this.#r,type:"put"})}for(let C of A)I.send(C);A=null})();return E.listener&&I.on("data",E.listener),I}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 b=!0,I=this.getContext();return E.checkPermission&&(b=this.allowCreate(I.user,E,I)),Vs(b,P=>{if(!P)throw new ct.AccessViolation(I.user);let L=Rr(E);this._writePublish(L,S,A)})}}_writePublish(E,S,A){let b=Lr(this.getContext());E??=null,E!==null&&Pr(E);let I=this.getContext();b.addWrite({key:E,store:i,entry:this.#n,nodeName:I?.nodeName,validate:o(()=>{I?.source||(b.checkOverloaded(),this.validate(S))},"validate"),before:Pe.publish?.bind(this,I,E,S),beforeIntermediate:Ra(S,De.publish?.bind(this,I,E,S)),commit:o((P,L,D)=>{L===void 0&&R&&!g&&Ta(),ve.default.trace?.(`Publishing message to id: ${E}, timestamp: ${new Date(P).toISOString()}`),y(E,L?.value??null,L,L?.version||P,0,!0,{user:I?.user,residencyId:A?.residencyId,expiresAt:I?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(E,S){let A,b=o((I,P,L)=>{if(P.type&&I!=null)if(S&&I.__op__&&(I=I.value),P.properties){typeof I!="object"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an object${P.type?" ("+P.type+")":""}`);let D=P.properties;for(let H=0,C=D.length;H<C;H++){let x=D[H];if(x.relationship||x.computed){E.hasOwnProperty(x.name)&&(A||(A=[])).push(`Computed property ${L}.${x.name} may not be directly assigned a value`);continue}let z=b(I[x.name],x,L+"."+x.name);z&&(I[x.name]=z)}if(P.sealed&&I!=null&&typeof I=="object")for(let H in I)D.find(C=>C.name===H)||(A||(A=[])).push(`Property ${H} is not allowed within object in property ${L}`)}else switch(P.type){case"Int":(typeof I!="number"||I>>0!==I)&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(D=>typeof D=="string")||(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a string`);break;case"Boolean":typeof I!="boolean"&&(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a bigint`)}break;case"Bytes":if(!(I instanceof Uint8Array)){if(typeof I=="string")return Buffer.from(I);(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(I instanceof Rs)){if(typeof I=="string"&&(I=Buffer.from(I)),I instanceof Buffer)return createBlob(I,{type:"text/plain"});(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be a Blob`)}break;case"array":if(Array.isArray(I)){if(P.elements)for(let D=0,H=I.length;D<H;D++){let C=I[D],x=b(C,P.elements,L+"[*]");x&&(I[D]=x)}}else(A||(A=[])).push(`Value ${Ks(I)} in property ${L} must be an Array`);break}P.nullable===!1&&I==null&&(A||(A=[])).push(`Property ${L} is required (and not does not allow null values)`)},"validateValue");for(let I=0,P=T.length;I<P;I++){let L=T[I];if(L.relationship||L.computed){Object.hasOwn(E,L.name)&&(A||(A=[])).push(`Computed property ${L.name} may not be directly assigned a value`);continue}if(!S||L.name in E){let D=b(E[L.name],L,L.name);D!==void 0&&(E[L.name]=D)}}if(f)for(let I in E)T.find(P=>P.name===I)||(A||(A=[])).push(`Property ${I} is not allowed`);if(A)throw new ct.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return O?!!this.#i:void 0}static async addAttributes(E){let S=T.slice(0);for(let A of E){if(!A.name)throw new ct.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new ct.ClientError("Attribute names cannot include backticks or forward slashes");yTe(A.name),S.push(A)}return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.indexingOperation}static async removeAttributes(E){let S=T.filter(A=>!E.includes(A.name));return ze({table:s,database:c,schemaDefined:u,attributes:S}),Ce.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=sD.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,b=performance.now(),I=Math.floor(S/2),P=E?.exactCount,L=0,D=0,H;for(let{value:C}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(C!=null&&L++,D++,await _c(),!P&&D<I&&performance.now()-b>A){H=D;break}if(H){let C=L;L=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:H,snapshot:!1}))ee!=null&&L++,await _c();let x=H*2,z=(L+C)/x,ne=Math.pow((L-C+1)/H/2,2)+z*(1-z)/x,re=Math.max(Math.sqrt(ne)*S,1),B=Math.round(z*S),de=Math.max(B-1.96*re,L+C),he=Math.min(B+1.96*re,S),Se=Math.pow(10,Math.round(Math.log10(re)));return Se>B&&(Se=Se/10),L=Math.round(B/Se)*Se,{recordCount:L,estimatedRange:[Math.round(de),Math.round(he)]}}return{recordCount:L}}static updatedAttributes(){ht=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&&(F=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)"),Cc=!0,S.to)E.elements?.definition?(ht[E.name]=E.resolve=(b,I,P,L)=>{let D=b[S.from?S.from:t],H=E.elements.definition.tableClass;return L?mf({attribute:S.to,value:D},Lr(I).getReadTxn(),!1,H,!1).map(C=>C&&C.key!==void 0?C:H.primaryStore.getEntry(C,{transaction:Lr(I).getReadTxn()})).asArray:H.search([{attribute:S.to,value:D}],I).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 b=E.definition||E.elements?.definition;b?(ht[E.name]=E.resolve=(I,P,L,D)=>{let H=I[S.from];if(H===void 0)return;if(E.elements){let x,z=H?.map(ne=>{let re=b.tableClass.primaryStore[D?"getEntry":"get"](ne,{transaction:Lr(P).getReadTxn()});return re?.then&&(x=!0),Ce.loadAsInstance===!1&&Object.freeze(D?re?.value:re),re});return S.filterMissing?x?Promise.all(z).then(ne=>ne.filter(gQ)):z.filter(gQ):x?Promise.all(z):z}let C=b.tableClass.primaryStore[D?"getEntry":"get"](H,{transaction:Lr(P).getReadTxn()});return Ce.loadAsInstance===!1&&Object.freeze(D?C?.value:C),C},E.set=(I,P)=>{if(Array.isArray(P)){let L=P.map(D=>D.getId?.()||D[b.tableClass.primaryKey]);I[S.from]=L}else{let L=P.getId?.()||P[b.tableClass.primaryKey];I[S.from]=L}},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),ht[E.name]=E.resolve=(b,I,P)=>{let L=typeof A.from=="string"?b[A.from]:b,D=this.userResolvers[E.name];if(D)return D(L,I,P);ve.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 b=r[E.name].customIndex;ht[E.name]=(I,P,L)=>{let D=I[E.name];return b.propertyResolver(D,P,L)},ht[E.name].directReturn=!0}}Wm(this,this),Wm(xf,this,!0);for(let E of T){let S=E.name;E.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return E.resolve(this,Ef.getStore())},set(A){return E.set(this,A)},configurable:!0})}}static setComputedAttribute(E,S){let A=io(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:b,value:I}of l.getRange({start:0,end:E}))await _c(),Nt(I).tableId===n&&(A=FR(l,b,I));if(S)for(let b of i.getRange({start:0,versions:!0})){let{key:I,value:P,localTime:L}=b;await _c(),P===null&&L<E&&(A=Zl(i,b))}await A}static async*getHistory(E=0,S=1/0){for(let{key:A,value:b}of l.getRange({start:E||1,end:S})){await _c();let I=Nt(b);I.tableId===n&&(yield{id:I.recordId,localTime:A,version:I.version,type:I.type,value:I.getValue(i,!0,A),user:I.user,operation:I.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 b=A.localTime;if(!b)throw new Error("The entry does not have a local audit time");let I=0;do{await _c();let P=l.get(b);if(P){let L=Nt(P);S.push({id:L.recordId,localTime:b,version:L.version,type:L.type,value:L.getValue(i,!0,b),user:L.user}),b=L.previousLocalTime}else break}while(I<1e3&&b);return S.reverse()}static cleanup(){$?.remove()}}let wE=hR(async(V,E,S)=>{for(let A of Ce.sources)if(A.get&&(!A.get.reliesOnPrototype||A.prototype.get)){if(A.available?.(S)===!1)continue;E.source=A;let b=await A.get(V,E);if(b)return b}},()=>{throw new ct.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});Ce.updatedAttributes();let Bf=Ce.prototype;return p&&Ce.setTTLExpiration(p/1e3),K&&Eu(),Ce;function po(V,E,S){let A;for(let b in r){let I=r[b],P=I.isIndexing,L=ht[b],D=S&&(L?L(S):S[b]),H=E&&(L?L(E):E[b]);if(D===H&&!P)continue;if(I.customIndex){I.customIndex.index(V,D,H);continue}A=!0;let C=I.indexNulls,x=(0,Jp.getIndexedValues)(D,C),z=(0,Jp.getIndexedValues)(H,C);if(s==="OrganizationRole"&&ve.default.error?.({tableName:s,id:V,key:b,valuesToAdd:x,valuesToRemove:z}),z?.length>0){let ne=new Set(z);if(x=x?x.filter(re=>{if(ne.has(re))ne.delete(re);else return!0}):[],z=Array.from(ne),(z.length>0||x.length>0)&&fQ){let re=z.concat(x).map(B=>({key:B,value:V}));I.prefetch(re,EQ)}for(let re=0,B=z.length;re<B;re++)I.remove(z[re],V)}else x?.length>0&&fQ&&I.prefetch(x.map(ne=>({key:ne,value:V})),EQ);if(x)for(let ne=0,re=x.length;ne<re;ne++)I.put(x[ne],V)}return A}o(po,"updateIndices");function Pr(V){switch(typeof V){case"number":return!0;case"string":if(V.length<659)return!0;if(V.length>hQ)throw new Error("Primary key size is too large: "+V.length);break;case"object":if(V===null)throw new Error("Invalid primary key of null");break;case"bigint":if(V<2n**64n&&V>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof V)}if((0,su.writeKey)(V,OTe,0)>hQ)throw new Error("Primary key size is too large: "+V.length);return!0}o(Pr,"checkValidId");function Rr(V){return typeof V=="object"&&V?V.id:V}o(Rr,"requestTargetToId");function Ff(V){return typeof V=="object"&&V&&V.isCollection}o(Ff,"isSearchTarget");function Ss(V){}o(Ss,"isRequestTarget");function Ea(V,E,S,A,b){if(Ce.getResidencyById&&S.ensureLoaded&&E?.replicateFrom!==!1){let P=Dc(Ce.getResidencyById(V));if(P&&!P.includes(server.hostname)&&N)return N({key:V,residency:P}).then(b)}let I=o(()=>{if(E?.transaction?.stale&&(E.transaction.stale=!1),S.transaction?.isDone)return b(null,V);let P=i.getEntry(V,S);return E?._freezeRecords&&Object.freeze(P?.value),P?.residencyId&&P.metadataFlags&Fn&&N&&S.ensureLoaded&&E?.replicateFrom!==!1?N(P).then(L=>b(L,V),L=>(ve.default.error?.("Error loading remote record",V,P,S,L),b(null,V))):(P&&E&&(P?.version>(E.lastModified||0)&&(E.lastModified=P.version),P?.localTime&&!E.lastRefreshed&&(E.lastRefreshed=P.localTime)),b(P,V))},"whenPrefetched");return A?I():se>0?(se--,I()):new Promise((P,L)=>{se===0?(se--,i.prefetch([V],()=>{D(),H()})):(le.push(V),ue.push(H),le.length>xy&&(se--,D()));function D(){if(le.length>0){let C=ue;i.prefetch(le,()=>{se===-1?D():se++;for(let x of C)x()}),le=[],ue=[],me>2&&me--}else se=me,me<NE&&me++}o(D,"prefetch");function H(){try{P(I())}catch(C){L(C)}}o(H,"load")})}o(Ea,"loadLocalRecord");function _a(V,E){let S=E?.checkPermission;if(typeof S!="object"){if(!V?.role)return;S=V.role.permission}if(S.super_user)return CTe;let A=S[c],b,I=A?.tables;if(I)return I[s];if(c==="data"&&(b=S[s])&&!b.tables)return b}o(_a,"getTablePermissions");function Lc(V,E,S,A){if(O){let b=!1;if(S.noCache?b=!0:(E?(!E.value||E.metadataFlags&(Fn|eu)||E.expiresAt!=null&&E.expiresAt<Date.now())&&(b=!0):b=!0,Yr(!b,"cache-hit",s)),b){let I=OE(V,E,S).then(P=>(P?.value&&P?.value.getRecord?.()&&ve.default.error?.("Can not assign a record that is already a resource"),S&&(P?.version>(S.lastModified||0)&&(S.lastModified=P.version),S.lastRefreshed=Date.now()),P));if(S?.onlyIfCached||E?.value&&A?.allowStaleWhileRevalidate?.(E,V)){if(I.catch(P=>ve.default.warn?.(P)),S?.onlyIfCached&&!A.doesExist())throw new ct.ServerError("Entry is not cached",504);return}else return I}}else if(E?.value&&E.expiresAt!=null&&E.expiresAt<Date.now())return Ce.evict(E.key,E.value,E.version),E.value=null,{then(b){return b(E)}}}o(Lc,"ensureLoadedFromSource");function Lr(V){let E=V?.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 _o,E.lmdbDb=i,E;E=S}while(!0)}else return new VE}o(Lr,"txnForContext");function hu(V,E,S){if(!V)return;let A=(V.deref?V.deref():V.value)??i.getEntry(V.key)?.value;if(typeof E=="object"){let I=ht,P=A;for(let L=0,D=E.length;L<D;L++){let H=E[L],C=I?.[H];P=C&&P?C(P,S,V):P?.[H],V=null,I=C?.definition?.tableClass?.propertyResolvers}return P}let b=ht[E];return b?b(A,S,V):A[E]}o(hu,"getAttributeValue");function pu(V,E,S,A,b){let I=b?.length,P={transaction:A,lazy:I>0||typeof E=="string"||E?.length<4,alwaysPrefetch:!0},L;function D(H,C){let x=H?.value;if(!x)return gc.SKIP;for(let z=0;z<I;z++)if(!L?.includes(z)&&!b[z](x,H))return gc.SKIP;return C!==void 0&&(H.key=C),H}if(o(D,"processEntry"),I>0||!V.hasEntries){let H=V.map(C=>{if(L=null,typeof C=="object"&&C?.key!==void 0)return I>0?D(C):C;if(C==null)return gc.SKIP;for(let x=0;x<I;x++){let ne=b[x].idFilter;if(ne){if(!ne(C))return gc.SKIP;L||(L=[]),L.push(x)}}return Ea(C,S,P,!1,D)});return Array.isArray(V)&&(H=H.filter(C=>C!==gc.SKIP)),H.hasEntries=!0,H}return V}o(pu,"transformToEntries");function ga(V,E,S=server.replication?.getThisNodeId(l)){if(V<=E?.version){if(E?.version===V&&S!==void 0){let A=server.replication?.exportIdMapping(l),b=E.localTime,I=b&&l.get(b);if(I){let P,L,D=Nt(I);for(let H in A)A[H]===S&&(P=H),A[H]===D.nodeId&&(L=H);if(P>L)return 1;if(P===L)return 0}}return-1}return 1}o(ga,"precedesExistingVersion");async function OE(V,E,S){let A=E?.metadataFlags,b=E?.version,I,P;if(!i.attemptLock(V,b,()=>{clearTimeout(P);let C=i.getEntry(V);!C||!C.value||C.metadataFlags&(Fn|eu)?I(OE(V,i.getEntry(V),S)):I(C)}))return new Promise(C=>{I=C,P=setTimeout(()=>{i.unlock(V,b)},NTe)});let L=E?.value,D={requestContext:S,replacingRecord:L,replacingEntry:E,replacingVersion:b,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},H=S?.responseHeaders;return new Promise((C,x)=>{let z;Vs(Ft(D,async ne=>{let re=performance.now(),B,de,he;try{B=await wE(V,D,E),he=A&Fn;let ee=D.lastModified||he&&b;ee||(ee=(0,Jp.getNextMonotonicTime)()),de=he||ee>b||!L;let j=performance.now()-re;if(it(j,"cache-resolution",s,null,"success"),H&&eh(H,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),ne.timestamp=ee,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=L,ee=b;else throw new ct.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==V&&(B[t]=V)}z=!0,C({key:V,version:ee,value:B})}catch(ee){ee.message+=` while resolving record ${V} for ${s}`,L&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(C({key:V,version:b,value:L}),ve.default.trace?.(ee.message,"(returned stale record)")):x(ee);let j=performance.now()-re;it(j,"cache-resolution",s,null,"fail"),H&&eh(H,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),D.transaction.abort();return}if(S?.noCacheStore||D.noCacheStore){D.transaction.abort();return}Lr(D).addWrite({key:V,store:i,entry:E,nodeName:"source",before:Ra(B),commit:o((ee,j)=>{if(j?.version!==b)return;let pe=po(V,L,B);if(B){De.put?.(D,V,B),j&&(S.previousResidency=Ce.getResidencyRecord(j.residencyId));let Te,fe=!1,We,St=Dc(Ce.getResidency(B,S));if(St){if(!St.includes(server.hostname))if(Te=B,fe=!0,Ce.getResidencyById)B=void 0;else{B=null;for(let ft in r)B||(B={}),B[ft]=Te[ft]}We=Mc(St)}ve.default.trace?.(`Writing resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),y(V,B,j,ee,fe?Fn:0,g&&(de||fe)||null,{user:D?.user,expiresAt:D.expiresAt,residencyId:We},"put",!!he,Te)}else j&&(De.delete?.(D,V),ve.default.trace?.(`Deleting resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),g||R?y(V,null,j,ee,0,g&&de||null,{user:D?.user},"delete",!!he):Zl(i,j,b))},"commit")})}),()=>{i.unlock(V,b)},ne=>{i.unlock(V,b),z&&ve.default.error?.("Error committing cache update",ne)})})}o(OE,"getFromSource");function Sa(V){if(!V||V.user?.role?.permission?.super_user)return!0;if(V.replicateTo)throw new ct.ClientError("Can not specify replication parameters without super user permissions",403);if(V.replicatedConfirmation)throw new ct.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Sa,"checkContextPermissions");function Ta(V){let E=!1;if(V&&(V-Ye>1&&(E=!0),Ye=V),!(dt===qn&&!E)&&(qn=dt,(0,ru.getWorkerIndex)()===(0,ru.getWorkerCount)()-1))return rt&&clearTimeout(rt),dt?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let b=dt/(1+Ye),I=E?Date.now():Math.ceil((Date.now()-A.getTime())/b)*b+A.getTime(),P=o(L=>{ve.default.trace?.(`Scheduled next cleanup scan at ${new Date(L)}`),rt=setTimeout(()=>Z=Z.then(async()=>{if(P(Math.max(L+dt,Date.now())),i.rootStore.status!=="open"){clearTimeout(rt);return}let D=50,H=new Array(D),C=0,x=Math.pow(Ye,8)*(nu.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),z=_/Math.pow(Math.max(Ye,1),4);ve.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${z}ms`);function ne(re,B,de,he){let Se=re+z-Date.now();if(Se<0)return!0;if(Ye){let ee=i.lastSize;return de&$r&&Hc(he,j=>{j.size&&(ee+=j.size)}),ve.default.trace?.(`shouldEvict adjusted ${Se} ${ee}, ${Se*(re-B)/ee} < ${x}`),Se*(re-B)/ee<x}return!1}o(ne,"shouldEvict");try{let re=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:de,value:he,version:Se,expiresAt:ee,metadataFlags:j}=B,pe;he===null&&!g&&Se+ITe<Date.now()?pe=Zl(i,B,Se):ee!=null&&ne(ee,Se,j,he)&&(pe=Ce.evict(de,he,Se),re++),pe&&(await H[C],H[C]=pe.catch(Te=>{ve.default.error?.("Cleanup error",Te)}),++C>=D&&(C=0)),await _c()}ve.default.info?.(`Finished cleanup scan for ${s}, evicted ${re} entries`)}catch(re){ve.default.warn?.(`Error in cleanup scan for ${s}:`,re)}S(void 0),Ye=0}),Math.min(L-Date.now(),2147483647)).unref()},"startNextTimer");P(I)}):void 0}o(Ta,"scheduleCleanup");function Hf(){$=l?.addDeleteRemovalCallback(n,i,(V,E)=>{i.remove(V,E)})}o(Hf,"addDeleteRemoval");function Eu(){(0,ru.getWorkerIndex)()===0&&setInterval(async()=>{if(!Pc){Pc=!0;try{let V=K.name,E=r[V];if(!E)throw new Error(`expiresAt attribute ${K} 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 b=i.getEntry(A);b?.value?b.value[V]<Date.now()&&Ce.evict(A,b.value,b.version):i.ifVersion(A,b?.version,()=>E.remove(S,A))}await _c()}}catch(V){ve.default.error?.("Error in evicting old records",V)}finally{Pc=!1}}},bTe).unref()}o(Eu,"runRecordExpirationEviction");function Dc(V){if(V!=null){if(Array.isArray(V))return V;if(typeof V=="number"){if(V>=65536)throw new Error(`Shard id ${V} must be below 65536`);let E=server.shards?.get?.(V);if(E)return ve.default.trace?.(`Shard ${V} mapped to ${E.map(S=>S.name).join(", ")}`),E.map(S=>S.name);throw new Error(`Shard ${V} is not defined`)}throw new Error(`Shard or residency list ${V} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(Dc,"residencyFromFunction");function Mc(V){if(V){let E=V.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],V),S)}}o(Mc,"getResidencyId");function Ra(V,E){let S=yA(V,i.rootStore);if(S){let A=E;return A?async()=>{await A(),await S()}:()=>S()}return E}o(Ra,"preCommitBlobsForRecordBefore")}function nD(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 EQ(){}function jR(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 zR(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return zR(+e);case"Float":return e==="null"?null:zR(+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;PTe.test(e)||(e+="Z");let n=new Date(e);return zR(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,QR.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function zR(e){if(isNaN(e))throw new SyntaxError;return e}function _Q(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 Vs(e,t,r){return e?.then?e.then(t,r):t(e)}function gQ(e){return e!=null}function Ks(e){try{return JSON.stringify(e)}catch{return e}}function LTe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var gc,Jp,SQ,TQ,nu,ct,Xp,Zp,ve,su,ru,QR,sD,RTe,yTe,ATe,bTe,ITe,fQ,NTe,mQ,wTe,Fn,eu,OTe,hQ,pQ,CTe,BFe,PTe,_c,bT=ce(()=>{k();gc=require("lmdb"),Jp=w(yn()),SQ=w(require("lodash")),TQ=w(Zf());xa();tm();nu=w(oe());KN();ct=w(ge()),Xp=w(Co()),Zp=w(ai());Me();mg();ve=w(ei());LI();Bc();su=require("ordered-binary"),ru=w(nt());Mi();QR=w(ie());Vc();Yi();V_();th();sD=w(require("node:fs"));Kn();vR();cL();({sortBy:RTe}=SQ.default),{validateAttribute:yTe}=TQ.default,ATe=new Uint8Array(9);ATe[8]=192;bTe=6e4,ITe=864e5;nu.initSync();fQ=nu.get(U.STORAGE_PREFETCHWRITES),NTe=1e4,mQ=1,wTe=2,Fn=1,eu=8,OTe=Buffer.allocUnsafeSlow(8192),hQ=1978,pQ=100,CTe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},BFe=(0,QR.convertToMS)(nu.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(JR,"makeTable");o(nD,"attributesAsObject");o(EQ,"noop");PTe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(jR,"coerceType");o(zR,"rejectNaN");o(_Q,"isDescendantId");_c=o(()=>new Promise(setImmediate),"rest");o(Vs,"when");o(gQ,"exists");o(Ks,"stringify");o(LTe,"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 ZR(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 RQ=ce(()=>{o(XR,"euclideanDistance");o(ZR,"cosineDistance")});var yQ,AQ,Sf,oo,gf,DTe,MTe,ey,bQ=ce(()=>{RQ();yQ=require("msgpackr"),AQ=w(ei()),Sf=w(ge()),oo=(0,AQ.loggerWithTag)("HNSW"),gf=Symbol.for("entryPoint"),DTe=Symbol.for("key"),MTe=10,ey=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=yQ.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?XR:ZR,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"?[DTe,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(gf);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 R=0;R<=_;R++)g[R]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);oo.debug?.("setting entry point to",i),this.indexStore.put(gf,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),MTe),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);oo.debug?.("setting entry point to",i),this.indexStore.put(gf,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&&oo.info?.("should not have zero connections for",l);let R=p[_];for(let T=0;T<g.length;T++){let{id:y,distance:N,node:O}=g[T];if(y===i)continue;let F=[];if(this.optimizeRouting){let Y=!1,K=O[_],$=1+this.optimizeRouting*(1+.5*T/this.M);for(let le=0;le<K.length;le++){let{id:ue,distance:se}=K[le],me=1+this.optimizeRouting*(1+.5*le/this.M);for(let Pe=0;Pe<R.length;Pe++){let{id:De,distance:dt}=R[Pe];if(De===ue){N*$>dt+se?Y=!0:se*me>N+dt&&(F.push({fromId:De,toId:y}),F.push({fromId:y,toId:De}));break}}if(Y)break}if(Y)continue}else if(T>=(_>0?this.M:this.M<<1))continue;R.push({id:y,distance:N});for(let{fromId:Y,toId:K}of F){let $=d(Y);$||($=d(Y,this.indexStore.get(Y)));for(let le=0;le<$[_].length;le++)if($[_][le].id===K){Object.isFrozen($[_])&&($[_]=$[_].slice()),$[_].splice(le,1);break}}let Z=c[_],G=Z?.find(({id:Y})=>Y===y);if(G){let Y=Z?.indexOf(G);Z.copied||(Z=[...Z],Z.copied=!0,c[_]=Z),Z.splice(Y,1)}else this.addConnection(y,d(y,O),i,_,N,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(gf);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);oo.debug?.("setting entry point to",l),this.indexStore.put(gf,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&&(oo.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(gf);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 Sf.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Sf.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=ZR;else if(s==="euclidean")c=XR;else{if(s)throw new Sf.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Sf.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Sf.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){oo.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||oo.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)){oo.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&&oo.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?oo.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:ZR);let c=a(s.target,t);return i.set(n,c),c}return t}}});var iD,IQ=ce(()=>{bQ();iD={HNSW:ey}});var Et={};we(Et,{database:()=>Vu,databaseEnvs:()=>na,databases:()=>He,dropDatabase:()=>xI,dropTableMeta:()=>FTe,getDatabases:()=>st,getDefaultCompression:()=>$S,getTables:()=>vTe,onRemovedDB:()=>bh,onUpdatedTable:()=>Nl,readMetaDb:()=>eE,resetDatabases:()=>Fd,table:()=>ze,tables:()=>ln});function vTe(){return sy||st(),ln||{}}function st(){if(sy)return He;sy=!0,yf=new Map;let e=(0,Xt.getHdbBasePath)()&&(0,Gt.join)((0,Xt.getHdbBasePath)(),Uc),t=(0,Xt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Xt.get)(U.STORAGE_PATH)||e&&((0,fs.existsSync)(e)?e:(0,Gt.join)((0,Xt.getHdbBasePath)(),ME)),!e)return;if((0,fs.existsSync)(e))for(let n of(0,fs.readdirSync)(e,{withFileTypes:!0})){let s=(0,Gt.basename)(n.name,".mdb");n.isFile()&&(0,Gt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&eE((0,Gt.join)(e,n.name),null,s)}if((0,fs.existsSync)((0,Rf.getBaseSchemaPath)())){for(let n of(0,fs.readdirSync)((0,Rf.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Gt.join)((0,Rf.getBaseSchemaPath)(),n.name),i=(0,Gt.join)((0,Rf.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,fs.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,Gt.extname)(a.name).toLowerCase()===".mdb"){let c=(0,Gt.join)(i,a.name);eE((0,Gt.join)(s,a.name),(0,Gt.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,fs.existsSync)(i))for(let c of(0,fs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Gt.extname)(c.name).toLowerCase()===".mdb"&&eE((0,Gt.join)(i,c.name),(0,Gt.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,Gt.join)(l.path,(0,Gt.basename)(c+".mdb"));(0,fs.existsSync)(u)&&eE(u,c,n,null,!0)}}for(let n in He){let s=yf.get(n);if(s){let i=He[n];n.includes("delete")&&Or.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Or.trace(`delete table class ${a}`),delete i[a])}else if(delete He[n],n==="data"){for(let i in ln)delete ln[i];delete ln[iy]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,Xt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(He.system?.hdb_analytics?.enableAuditing(),He.system?.hdb_analytics_hostname?.enableAuditing()),He.system)for(let n of r)He.system[n]&&(He.system[n].replicate=!1);return yf=null,He}function Fd(){sy=!1;for(let[,e]of na)e.needsDeletion=!0;st();for(let[e,t]of na)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),na.delete(e);let r=He[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete He[t.databaseName],rE.forEach(i=>i(t.databaseName));break}}return He}function eE(e,t,r=cD,n,s){let i=new oD.default(e,!1);try{let a=na.get(e);a?a.needsDeletion=!1:(a=(0,Af.open)(i),na.set(e,a));let c=new bf.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(ty.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,fs.existsSync)(n)&&(i.path=n,u=(0,Af.open)(i),u.isLegacy=!0):u=BR(a));let d=PQ(r),f=d[iy],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 R=m.get(_);R||m.set(_,R={attributes:[]}),(g==null||p.is_hash_attribute)&&(R.primary=p),g!=null&&R.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){Or.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(_)}`);continue}}let R=d[h],T={},y=[],N,O,F=typeof g.audit=="boolean"?g.audit:(0,Xt.get)(U.LOGGING_AUDITLOG),Z=g.trackDeletes,G=g.expiration,Y=g.eviction,K=g.sealed,$=g.splitSegments,le=g.replicate;if(R)T=R.indices,y=R.attributes,R.schemaVersion++;else{N=g.tableId,N?N>=(l.get(Tf)||0)&&(l.putSync(Tf,N+1),Or.info(`Updating next table id (it was out of sync) to ${N+1} for ${h}`)):(g.tableId=N=l.get(Tf),N||(N=1),Or.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Tf,N+1),l.putSync(g.key,g));let se=new bf.default(!g.is_hash_attribute,g.is_hash_attribute);if(se.compression=g.compression,se.compression){let me=(0,Xt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||CQ;se.compression.threshold=me}O=VR(a.openDB(g.key,se),a),a.databaseName=r,O.tableId=N}let ue;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 Pe=DQ(se.key,a,se);T[se.name]=Pe,T[se.name].indexNulls=se.indexNulls}let me=y.find(Pe=>Pe.name===se.name);me?y.splice(y.indexOf(me),1,se):y.push(se),ue=!0}}catch(me){Or.error("Error trying to update attribute",se,y,T,me)}}for(let se of y)if(!_.find(Pe=>Pe.name===se.name)){if(se.is_hash_attribute){Or.error("Unable to remove existing primary key attribute",se);continue}se.indexed&&(y.splice(y.indexOf(se),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=LQ(d,h,JR({primaryStore:O,auditStore:u,audit:F,sealed:K,splitSegments:$,replicate:le,expirationMS:G&&G*1e3,evictionMS:Y&&Y*1e3,trackDeletes:Z,tableName:h,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:_,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let se of tE)se(R)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function PQ(e){let t=He[e];if(t||(e==="data"?t=He[e]=ln:e==="system"?Object.defineProperty(He,"system",{value:t=Object.create(null),configurable:!0}):t=He[e]=Object.create(null)),yf&&!yf.has(e)){let r=new Set;t[iy]=r,yf.set(e,r)}return t}function LQ(e,t,r){return e[t]=r,r}function Vu({database:e,table:t}){e||(e=cD),st();let r=PQ(e),n=(0,Gt.join)((0,Xt.getHdbBasePath)(),Uc),s=(0,Xt.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,Xt.get)(U.STORAGE_PATH)||((0,fs.existsSync)(n)?n:(0,Gt.join)((0,Xt.getHdbBasePath)(),ME));let a=(0,Gt.join)(n,(i?t:e)+".mdb"),c=na.get(a);if(!c||c.status==="closed"){let l=new oD.default(a,!1);c=(0,Af.open)(l),na.set(a,c)}return c.auditStore||(c.auditStore=BR(c)),c}async function xI(e){if(!He[e])throw new Error("Schema does not exist");let t=He[e],r;for(let n in t)r=t[n].primaryStore.rootStore,na.delete(r.path),r.status==="open"&&(await r.close(),await nE.remove(r.path));if(r||(r=Vu({database:e,table:null}),r.status==="open"&&(await r.close(),await nE.remove(r.path))),e==="data"){for(let n in ln)delete ln[n];delete ln[iy]}delete He[e],rE.forEach(n=>n(e)),await RA(r)}function DQ(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&iD[r.indexed.type]?.useObjectStore,s=new bf.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=iD[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Or.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=cD);let p=Vu({database:r,table:t}),_=He[r];Or.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 R,T,y;m==null&&(m=!0);let N=new bf.default(!1);for(let $ of a)$.attribute&&!$.name?($.name=$.attribute,$.indexed=!0):$.attribute=$.name,$.expiresAt&&($.indexed=!0);let O,F;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...a)}else{let $=p.auditStore;T=a.find(me=>me.isPrimaryKey)||{},R=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=$S(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,Xt.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]),Or.trace(`${t} table loading, opening primary store`);let le=new bf.default(!1,!0);le.compression=T.compression;let ue=t+"/";if(y=p.dbisDb=p.openDB(ty.INTERNAL_DBIS_NAME,N),K(),y.get(ue))return F&&F(),Fd(),ze(e);let se=VR(p.openDB(ue,le),p);p.databaseName=r,se.tableId=y.get(Tf),Or.trace(`Assigning new table id ${se.tableId} for ${t}`),se.tableId||(se.tableId=1),y.put(Tf,se.tableId+1),T.tableId=se.tableId,g=LQ(_,t,JR({primaryStore:se,auditStore:$,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:se.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:y})),g.schemaVersion=1,O=!0,y.put(ue,T)}let Z=g.indices;y=y||(p.dbisDb=p.openDB(ty.INTERNAL_DBIS_NAME,N)),g.dbisDB=y;let G=[];for(let{key:$,value:le}of y.getRange({start:!0})){let[ue,se]=$.toString().split("/");if(se===""&&(se=le.name),se){if(ue!==t)continue}else continue;let me=a.find(De=>De.name===se),Pe=!me?.indexed&&le.indexed&&!le.isPrimaryKey;if((!me||Pe)&&(K(),O=!0,me||y.remove($),Pe)){let De=g.indices[ue];De&&G.push(De)}}let Y=[];try{for(let $ of a||[]){if(($.relationship||$.computed)&&(O=!0,$.relationship))continue;let le=t+"/"+($.name||"");Object.defineProperty($,"key",{value:le,configurable:!0});let ue=y.get(le);if($.isPrimaryKey){if(ue=ue||y.get(le=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||$.type!==ue.type){let me={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),me.audit=c),n&&(me.expiration=+n),s&&(me.eviction=+s),l!==void 0&&(me.sealed=l),d!==void 0&&(me.replicate=d),$.type&&(me.type=$.type),O=!0,K(),y.put(le,me)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let se=!ue||ue.type!==$.type||JSON.stringify(ue.indexed)!==JSON.stringify($.indexed)||ue.nullable!==$.nullable||ue.version!==$.version||JSON.stringify(ue.properties)!==JSON.stringify($.properties)||JSON.stringify(ue.elements)!==JSON.stringify($.elements);if($.indexed){let me=DQ(le,p,$);(se||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<sE.workerData?.restartNumber)&&(O=!0,K(),ue=y.get(le),(se||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<sE.workerData?.restartNumber)&&(O=!0,$.indexNulls===void 0&&($.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&($.lastIndexedKey=ue?.lastIndexedKey??void 0,$.indexingPID=process.pid,me.isIndexing=!0,Object.defineProperty($,"dbi",{value:me}),Y.push($))),y.put(le,$)),ue?.indexNulls&&$.indexNulls===void 0&&($.indexNulls=!0),me.indexNulls=$.indexNulls,Z[$.name]=me}else se&&(O=!0,K(),y.put(le,$))}}finally{F&&F()}if(O&&(g.schemaVersion++,g.updatedAttributes()),Or.trace(`${t} table loading, running index`),Y.length>0||G.length>0?g.indexingOperation=BTe(g,Y,G):O&&ry.signalSchemaChange(new ny.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,O)for(let $ of tE)$(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Or.trace(`${t} table loaded`),g;function K(){F||p.transactionSync(()=>({then($){F=$}}))}o(K,"startTxn")}async function BTe(e,t,r){try{Or.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await ry.signalSchemaChange(new ny.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,Af.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,R=_.dbi;try{let T=_.resolve,y=m&&(T?T(m):m[g]);if(R.customIndex){R.customIndex.index(f,y);continue}let N=(0,NQ.getIndexedValues)(y);if(N)for(let O=0,F=N.length;O<F;O++)R.put(N[O],f)}catch(T){a[g]||(a[g]=!0,Or.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Or.error(p)}),sE.workerData&&sE.workerData.restartNumber!==OQ.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>UTe?await s:d>xTe&&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 ry.signalSchemaChange(new ny.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Or.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Or.error("Error in indexing",n)}}function FTe({table:e,database:t}){let r=Vu({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 Nl(e){return tE.push(e),{remove(){let t=tE.indexOf(e);t>-1&&tE.splice(t,1)}}}function bh(e){return rE.push(e),{remove(){let t=rE.indexOf(e);t>-1&&rE.splice(t,1)}}}function $S(){let e=(0,Xt.get)(U.STORAGE_COMPRESSION),t=(0,Xt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Xt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||CQ,n={startingOffset:32};return t&&(n.dictionary=nE.readFileSync(t)),r&&(n.threshold=r),e&&n}var Xt,ty,Af,Gt,fs,Rf,bf,oD,nE,aD,NQ,ry,ny,sE,wQ,OQ,Or,cD,iy,CQ,ln,He,Tf,tE,rE,sy,na,yf,UTe,xTe,Me=ce(()=>{Xt=w(oe()),ty=w(Vt()),Af=require("lmdb"),Gt=require("path"),fs=require("fs"),Rf=w(It());bT();bf=w(mm()),oD=w(hm());k();nE=w(require("fs-extra")),aD=w(Zs()),NQ=w(yn()),ry=w(Co()),ny=w(ai()),sE=require("worker_threads"),wQ=w(Q()),OQ=w(nt());Mi();Vc();Kn();IQ();Or=(0,wQ.forComponent)("storage"),cD="data",iy=Symbol("defined-tables"),CQ=((0,Xt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Xt.initSync)();ln=Object.create(null),He=Object.create(null);(0,aD._assignPackageExport)("databases",He);(0,aD._assignPackageExport)("tables",ln);Tf=Symbol.for("next-table-id"),tE=[],rE=[],na=new Map;o(vTe,"getTables");o(st,"getDatabases");o(Fd,"resetDatabases");o(eE,"readMetaDb");o(PQ,"ensureDB");o(LQ,"setTable");o(Vu,"database");o(xI,"dropDatabase");o(DQ,"openIndex");o(ze,"table");UTe=1e3,xTe=10;o(BTe,"runIndexing");o(FTe,"dropTableMeta");o(Nl,"onUpdatedTable");o(bh,"onRemovedDB");o($S,"getDefaultCompression")});var ie=M(be=>{"use strict";var Sc=require("path"),BQ=require("fs-extra"),kn=Q(),MQ=require("fs-extra"),oy=require("os"),HTe=require("net"),kTe=require("recursive-iterator"),Cr=(k(),v(W)),{PACKAGE_ROOT:GTe}=bt(),qTe=eA(),vQ=require("papaparse"),ay=require("moment"),{inspect:$Te}=require("util"),UQ=require("is-number"),VTe=require("minimist"),KTe=require("https"),YTe=require("http"),WTe=/^((\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)))$/,FQ=require("util").promisify(setTimeout),zTe=100,jTe=5,QTe="",JTe=4,xQ={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};be.isEmpty=ms;be.isEmptyOrZeroLength=ao;be.arrayHasEmptyValues=eRe;be.arrayHasEmptyOrZeroLengthValues=tRe;be.buildFolderPath=rRe;be.isBoolean=HQ;be.errorizeMessage=XTe;be.stripFileExtension=sRe;be.autoCast=iRe;be.autoCastJSON=kQ;be.autoCastJSONDeep=uD;be.removeDir=oRe;be.compareVersions=aRe;be.isCompatibleDataVersion=cRe;be.escapeRawValue=lRe;be.unescapeValue=uRe;be.stringifyProps=dRe;be.timeoutPromise=mRe;be.isClusterOperation=pRe;be.getClusterUser=_Re;be.checkGlobalSchemaTable=ERe;be.getHomeDir=qQ;be.getPropsFilePath=fRe;be.promisifyPapaParse=gRe;be.removeBOM=$Q;be.createEventPromise=SRe;be.checkProcessRunning=TRe;be.checkSchemaTableExist=RRe;be.checkSchemaExists=VQ;be.checkTableExists=KQ;be.getStartOfTomorrowInSeconds=yRe;be.getLimitKey=ARe;be.isObject=nRe;be.isNotEmptyAndHasValue=ZTe;be.autoCasterIsNumberCheck=GQ;be.backtickASTSchemaItems=bRe;be.isPortTaken=hRe;be.createForkArgs=IRe;be.autoCastBoolean=NRe;be.asyncSetTimeout=FQ;be.getTableHashAttribute=wRe;be.doesSchemaExist=ORe;be.doesTableExist=CRe;be.stringifyObj=PRe;be.ms_to_time=LRe;be.changeExtension=DRe;be.getEnvCliRootPath=dD;be.noBootFile=MRe;be.httpRequest=vRe;be.transformReq=URe;be.convertToMS=xRe;be.PACKAGE_ROOT=GTe;function XTe(e){return e instanceof Error?e:new Error(e)}o(XTe,"errorizeMessage");function ms(e){return e==null}o(ms,"isEmpty");function ZTe(e){return!ms(e)&&(e||e===0||e===""||HQ(e))}o(ZTe,"isNotEmptyAndHasValue");function ao(e){return ms(e)||e.length===0||e.size===0}o(ao,"isEmptyOrZeroLength");function eRe(e){if(ms(e))return!0;for(let t=0;t<e.length;t++)if(ms(e[t]))return!0;return!1}o(eRe,"arrayHasEmptyValues");function tRe(e){if(ao(e))return!0;for(let t=0;t<e.length;t++)if(ao(e[t]))return!0;return!1}o(tRe,"arrayHasEmptyOrZeroLengthValues");function rRe(...e){try{return e.join(Sc.sep)}catch{console.error(e)}}o(rRe,"buildFolderPath");function HQ(e){return ms(e)?!1:e===!0||e===!1}o(HQ,"isBoolean");function nRe(e){return ms(e)?!1:typeof e=="object"}o(nRe,"isObject");function sRe(e){return ao(e)?QTe:e.slice(0,-JTe)}o(sRe,"stripFileExtension");function iRe(e){return ms(e)||e===""||typeof e!="string"?e:xQ[e]!==void 0?xQ[e]:GQ(e)===!0?Number(e):WTe.test(e)?new Date(e):e}o(iRe,"autoCast");function kQ(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(kQ,"autoCastJSON");function uD(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=uD(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=uD(r);n!==r&&(e[t]=n)}return e}else return kQ(e)}o(uD,"autoCastJSONDeep");function GQ(e){if(e.startsWith("0.")&&UQ(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&UQ(e))}o(GQ,"autoCasterIsNumberCheck");async function oRe(e){if(ao(e))throw new Error(`Directory path: ${e} does not exist`);try{await MQ.emptyDir(e),await MQ.remove(e)}catch(t){throw kn.error(`Error removing files in ${e} -- ${t}`),t}}o(oRe,"removeDir");function aRe(e,t){if(ao(e)){kn.info("Invalid current version sent as parameter.");return}if(ao(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(aRe,"compareVersions");function cRe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}o(cRe,"isCompatibleDataVersion");function lRe(e){if(ms(e))return e;let t=String(e);return t==="."?Cr.UNICODE_PERIOD:t===".."?Cr.UNICODE_PERIOD+Cr.UNICODE_PERIOD:t.replace(Cr.FORWARD_SLASH_REGEX,Cr.UNICODE_FORWARD_SLASH)}o(lRe,"escapeRawValue");function uRe(e){if(ms(e))return e;let t=String(e);return t===Cr.UNICODE_PERIOD?".":t===Cr.UNICODE_PERIOD+Cr.UNICODE_PERIOD?"..":String(e).replace(Cr.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(uRe,"unescapeValue");function dRe(e,t){if(ms(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+oy.EOL}!ao(n)&&n[0]===";"?r+=" "+n+s+oy.EOL:ao(n)||(r+=n+"="+s+oy.EOL)}catch{kn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}o(dRe,"stringifyProps");function qQ(){let e;try{e=oy.homedir()}catch{e=process.env.HOME}return e}o(qQ,"getHomeDir");function fRe(){let e=Sc.join(qQ(),Cr.HDB_HOME_DIR_NAME,Cr.BOOT_PROPS_FILE_NAME);return BQ.existsSync(e)||(e=Sc.join(__dirname,"../","hdb_boot_properties.file")),e}o(fRe,"getPropsFilePath");function mRe(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(mRe,"timeoutPromise");async function hRe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=HTe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}o(hRe,"isPortTaken");function pRe(e){try{return Cr.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){kn.error(`Error checking operation against cluster ops ${t}`)}return!1}o(pRe,"isClusterOperation");function ERe(e,t){let r=(Me(),v(Et)).getDatabases();if(!r[e])return cy.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return cy.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(ERe,"checkGlobalSchemaTable");function _Re(e,t){if(ms(t)){kn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ms(e)||ao(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(_Re,"getClusterUser");function gRe(){vQ.parsePromise=function(e,t,r){return new Promise(function(n,s){vQ.parse(e,{header:!0,transformHeader:$Q,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}o(gRe,"promisifyPapaParse");function $Q(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o($Q,"removeBOM");function SRe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;kn.info(`Got cluster status event response: ${$Te(s)}`);try{i.cancel()}catch{kn.error("Error trying to cancel timeout.")}n(s)})})}o(SRe,"createEventPromise");async function TRe(e){let t=!0,r=0;do await FQ(zTe*r++),(await qTe.findPs(e)).length>0&&(t=!1);while(t&&r<jTe);if(t)throw new Error(`process ${e} was not started`)}o(TRe,"checkProcessRunning");function RRe(e,t){let r=VQ(e);if(r)return r;let n=KQ(e,t);if(n)return n}o(RRe,"checkSchemaTableExist");function VQ(e){let{getDatabases:t}=(Me(),v(Et));if(!t()[e])return cy.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(VQ,"checkSchemaExists");function KQ(e,t){let{getDatabases:r}=(Me(),v(Et));if(!r()[e][t])return cy.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(KQ,"checkTableExists");function yRe(){let e=ay().utc().add(1,"d").startOf("d").unix(),t=ay().utc().unix();return e-t}o(yRe,"getStartOfTomorrowInSeconds");function ARe(){return ay().utc().format("DD-MM-YYYY")}o(ARe,"getLimitKey");function bRe(e){try{let t=new kTe(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(bRe,"backtickASTSchemaItems");function IRe(e){return[e]}o(IRe,"createForkArgs");function NRe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(NRe,"autoCastBoolean");function wRe(e,t){let{getDatabases:r}=(Me(),v(Et)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}o(wRe,"getTableHashAttribute");function ORe(e){let{getDatabases:t}=(Me(),v(Et));return t()[e]!==void 0}o(ORe,"doesSchemaExist");function CRe(e,t){let{getDatabases:r}=(Me(),v(Et));return r()[e]?.[t]!==void 0}o(CRe,"doesTableExist");function PRe(e){try{return JSON.stringify(e)}catch{return e}}o(PRe,"stringifyObj");function LRe(e){let t=ay.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(LRe,"ms_to_time");function DRe(e,t){let r=Sc.basename(e,Sc.extname(e));return Sc.join(Sc.dirname(e),r+t)}o(DRe,"changeExtension");function dD(){if(process.env[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=VTe(process.argv);if(e[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Cr.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(dD,"getEnvCliRootPath");var lD;function MRe(){if(lD)return lD;let e=dD();if(dD()&&BQ.pathExistsSync(Sc.join(e,Cr.HDB_CONFIG_FILE)))return lD=!0,!0}o(MRe,"noBootFile");function vRe(e,t){let r;return e.protocol==="http:"?r=YTe:r=KTe,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(vRe,"httpRequest");function URe(e){if(!e.schema&&!e.database){e.schema=Cr.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(URe,"transformReq");function xRe(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(xRe,"convertToMS");var cy=tn()});var oe=M((jQ,QQ)=>{"use strict";var fD=require("fs-extra"),iu=require("path"),YQ=require("os"),BRe=require("properties-reader"),oE=Q(),iE=ie(),Be=(k(),v(W)),ly=wt(),FRe="Error initializing environment manager",uy="BOOT_PROPS_FILE_PATH",WQ=!1,HRe={[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},sa={};Object.assign(jQ,QQ.exports={BOOT_PROPS_FILE_PATH:uy,getHdbBasePath:kRe,setHdbBasePath:GRe,get:zQ,initSync:$Re,setProperty:Je,initTestEnvironment:VRe});function kRe(){return sa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(kRe,"getHdbBasePath");function GRe(e){sa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(GRe,"setHdbBasePath");function zQ(e){let t=ly.getConfigValue(e);return t===void 0?sa[e]:t}o(zQ,"get");function Je(e,t){HRe[e]&&(sa[e]=t),ly.updateConfigObject(e,t)}o(Je,"setProperty");function qRe(){let e;try{e=iE.getPropsFilePath(),fD.accessSync(e,fD.constants.F_OK|fD.constants.R_OK),WQ=!0;let t=BRe(e);return sa[Be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Be.HDB_SETTINGS_NAMES.INSTALL_USER),sa[Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),sa[uy]=e,!0}catch{return oE.trace(`Environment manager found no properties file at ${e}`),!1}}o(qRe,"doesPropFileExist");function $Re(e=!1){try{(WQ||qRe()||iE.noBootFile()||e)&&(ly.initConfig(e),sa[Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=ly.getConfigValue(Be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){oE.error(FRe),oE.error(t),console.error(t),process.exit(1)}}o($Re,"initSync");function VRe(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=iu.join(__dirname,"../../","unitTests");sa[uy]=iu.join(l,"hdb_boot_properties.file"),Je(Be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,iu.join(l,"settings.test")),Je(Be.HDB_SETTINGS_NAMES.INSTALL_USER,YQ.userInfo()?YQ.userInfo().username:void 0),Je(Be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Je(Be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,iu.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,iu.join(l,"envDir")),Je(Be.CONFIG_PARAMS.STORAGE_PATH,iu.join(l,"envDir")),s&&(Je(Be.CONFIG_PARAMS.HTTP_SECUREPORT,zQ(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,iE.isEmpty(i)?!1:i),Je(Be.CONFIG_PARAMS.HTTP_CORS,iE.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,iu.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Je(Be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,iE.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 ${uy}. Please check your boot props and settings files`;oE.fatal(r),oE.error(t)}}o(VRe,"initTestEnvironment")});var rJ=M((oHe,tJ)=>{"use strict";var{promises:If,createReadStream:KRe,createWriteStream:YRe}=require("fs"),{createGzip:WRe}=require("zlib"),{promisify:zRe}=require("util"),{pipeline:jRe}=require("stream"),QRe=zRe(jRe),hD=require("path"),eJ=oe();eJ.initSync();var dy=Q(),{CONFIG_PARAMS:JRe,ITC_EVENT_TYPES:sHe}=(k(),v(W)),{onMessageFromWorkers:iHe}=nt(),{convertToMS:JQ}=ie(),{onStorageReclamation:XRe}=(vR(),v(G2)),ZRe=6e4,eye="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",tye="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",mD,XQ;tJ.exports=rye;function rye({logger:e,maxSize:t,interval:r,retention:n,enabled:s,path:i,auditInterval:a}){if(s===!1)return;let c=0;if(XRe(e.path,f=>{c=f},!0),!t&&!r)throw new Error(eye);if(!i)throw new Error(tye);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=JQ(r));let d;return mD=Date.now(),dy.trace("Log rotate enabled, maxSize:",t,"interval:",r),XQ=setInterval(async()=>{if(l){let f;f=await If.stat(e.path),f.size>=l&&(d=await ZQ(e.path,i))}if(u&&Date.now()-mD>=u&&(d=await ZQ(e.path,i),mD=Date.now()),n||c){let f=JQ(n??"1M")/(1+c);c=0;let m=await If.readdir(i);for(let h of m)try{let p=await If.stat(hD.join(i,h));Date.now()-p.mtimeMs>f&&await If.unlink(hD.join(i,h))}catch(p){dy.error("Error trying to remove log",h,p)}}},a??ZRe).unref(),{end(){clearInterval(XQ)},getLastRotatedLogPath(){return d}}}o(rye,"logRotator");async function ZQ(e,t){let r=eJ.get(JRe.LOGGING_ROTATION_COMPRESS),n=hD.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.log`);return await If.rename(e,n),r&&(e=n,n+=".gz",await QRe(KRe(e),WRe(),YRe(n)),await If.unlink(e)),dy.closeLogFile(),dy.notify(`hdb.log rotated, old log moved to ${n}`),n}o(ZQ,"moveLogFile")});var aJ={};we(aJ,{RootConfigWatcher:()=>pD});var nJ,sJ,iJ,fy,oJ,pD,cJ=ce(()=>{nJ=w(require("chokidar")),sJ=require("node:fs/promises"),iJ=w(wt()),fy=require("node:stream"),oJ=require("yaml"),pD=class extends fy.EventEmitter{static{o(this,"RootConfigWatcher")}#e;#t;#r;constructor(){super(),this.#e=(0,iJ.getConfigFilePath)(),this.#t=nJ.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,sJ.readFile)(this.#e,"utf-8").then(t=>{if(!t)return;let r=(0,oJ.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,fy.once)(this,"ready")}close(){return this.#t.close(),this.#r=void 0,this.emit("close"),this.removeAllListeners(),this}get config(){return this.#r}}});var Q=M((dHe,Ty)=>{"use strict";var ia=require("fs-extra"),{workerData:nye,threadId:sye,isMainThread:pJ}=require("worker_threads"),lE=require("path"),EJ=require("yaml"),_J=require("properties-reader"),Gr=(k(),v(W)),lJ=xc(),iye=require("os"),{PACKAGE_ROOT:yD}=bt(),{_assignPackageExport:oye}=Zs(),{Console:aye}=require("console"),uJ=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),dJ=new Map,{join:oa}=lE,fJ=1e4,or={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},cye={STDOUT:"stdOut",STDERR:"stdErr"},uHe=oa(yD,"logs"),lye=oa(yD,"config/yaml/",Gr.HDB_DEFAULT_CONFIG_FILE),uye=1e4,uE,dE,my,co,_D,ED,py,Ut,Gn,Ey,_y,Nf,cE,aE;function hy(e,t,r){e.rotation=t.rotation;let n=t.path;n?t.root||(t.root=lE.dirname(n)):t.root?n=oa(t.root,_D):(n=Ut.path,t.root||(t.root=lE.dirname(n))),n?e.path=n:console.error("No path for logger",t),e.level=or[t.level]??Ut?.level??or.info,gJ(e),e.logToStdstreams=t.stdStreams??!1,e.tag=t.tag??(Ut.path===e.path&&r)}o(hy,"updateLogger");function gJ(e){let t=e.conditional??(e.conditional={});t.notify=or.notify>=e.level?e.notify.bind(e):void 0,t.fatal=or.fatal>=e.level?e.fatal.bind(e):void 0,t.error=or.error>=e.level?e.error.bind(e):void 0,t.warn=or.warn>=e.level?e.warn.bind(e):void 0,t.info=or.info>=e.level?e.info.bind(e):void 0,t.debug=or.debug>=e.level?e.debug.bind(e):void 0,t.trace=or.trace>=e.level?e.trace.bind(e):void 0}o(gJ,"updateConditional");async function gD(){aE||(aE=new Cye,await aE.ready(),aE.on("change",gD));let e=aE.config,t=e.logging??{};hy(Ut,t),py=Ut.path,uE=t.console??!1,t.external&&hy(Gn,t.external);for(let r in e){let n=e[r];n.logging?hy(Ut.forComponent(r),n.logging,r):Ut.hasComponent(r)&&hy(Ut.forComponent(r),t,r)}}o(gD,"updateLogSettings");var SD=class extends aye{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){Sn="trace",this.level<=or.trace&&super.info(...t),Sn="info"}debug(...t){Sn="debug",this.level<=or.debug&&super.info(...t),Sn="info"}info(...t){Sn="info",this.level<=or.info&&super.info(...t),Sn="info"}warn(...t){Sn="warn",this.level<=or.warn&&super.warn(...t),Sn="info"}error(...t){Sn="error",this.level<=or.error&&super.error(...t),Sn="info"}fatal(...t){Nf=!0;try{Sn="fatal",this.level<=or.fatal&&super.error(...t),Sn="info"}finally{Nf=!1}}notify(...t){Nf=!0;try{Sn="notify",this.level<=or.notify&&super.info(...t),Sn="info"}finally{Nf=!1}}withTag(t){return TJ(t,!0,this)}forComponent(t){return this}hasComponent(t){return!1}};cE===void 0&&SJ();Ty.exports={notify:gye,fatal:Sye,error:RD,warn:Tye,info:pye,debug:_ye,trace:Eye,logLevel:co,loggerWithTag:TJ,suppressLogging:mye,initLogSettings:SJ,logCustomLevel:Rye,closeLogFile:RJ,createLogger:Sy,logsAtLevel:dye,getLogFilePath:o(()=>py,"getLogFilePath"),forComponent:o(e=>Ut.forComponent(e),"forComponent"),setMainLogger:wye,setLogLevel:Aye,OUTPUTS:cye,AuthAuditLog:Oye,start:gD,startOnMainThread:gD,errorToString:Nye};Ty.exports.externalLogger={notify(...e){Gn.notify(...e)},fatal(...e){Gn.fatal(...e)},error(...e){Gn.error(...e)},warn(...e){Gn.warn(...e)},info(...e){Gn.info(...e)},debug(...e){Gn.debug(...e)},trace(...e){Gn.trace(...e)},withTag(e){return Gn.withTag(e)},loggerWithTag(e){return Gn.withTag(e)}};oye("logger",Ty.exports.externalLogger);function dye(e){return or[co]<=or[e]}o(dye,"logsAtLevel");function SJ(e=!1){try{if(cE===void 0||e){RJ();let t=yye(),r=lJ(["ROOTPATH"]);try{cE=_J(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!ia.pathExistsSync(oa(r.ROOTPATH,Gr.HDB_CONFIG_FILE)))throw s}let n;if({level:co,configLogPath:ED,toFile:dE,logConsole:uE,rotation:n,toStream:my}=bye(r.ROOTPATH?oa(r.ROOTPATH,Gr.HDB_CONFIG_FILE):cE.get("settings_path")),_D=Gr.LOG_NAMES.HDB,py=oa(ED,_D),Ut=Sy({path:py,level:co,stdStreams:my,rotation:n}),Gn=Ut.forComponent("external"),Gn.tag=null,pJ)try{require("segfault-handler").registerHandler(oa(ED,"crash.log"))}catch{}}}catch(t){if(cE=void 0,t.code===Gr.NODE_ERROR_CODES.ENOENT||t.code===Gr.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=lJ(Object.keys(Gr.CONFIG_PARAM_MAP),!0);for(let s in r){let i=Gr.CONFIG_PARAM_MAP[s];i&&i.toLowerCase();let a=r[s];if(i===Gr.CONFIG_PARAMS.LOGGING_LEVEL){co=a;continue}i===Gr.CONFIG_PARAMS.LOGGING_CONSOLE&&(uE=i)}let{defaultLevel:n}=Iye();dE=!1,my=!0,co=co===void 0?n:co,Ut=Sy({level:co}),Gn=Ut.forComponent("external"),Gn.tag=null;return}throw RD("Error initializing log settings"),RD(t),t}process.env.DEV_MODE&&(my=!0),fye()}o(SJ,"initLogSettings");var Tc=!0;function fye(){dE&&(process.stdout.write=function(e){return typeof e=="string"&&Tc&&uE&&(e=e.toString(),e[e.length-1]===`
35
35
  `&&(e=e.slice(0,-1)),_y(e)),uJ.apply(process.stdout,arguments)},process.stderr.write=function(e){return typeof e=="string"&&Tc&&uE&&(e[e.length-1]===`
36
36
  `&&(e=e.slice(0,-1)),_y(e)),uJ.apply(process.stderr,arguments)})}o(fye,"stdioLogging");function TJ(e,t,r=Ut){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<=or[i]?function(...a){gy=e;try{return s.call(r,...a)}finally{gy=void 0}}:null}o(n,"logWithTag")}o(TJ,"loggerWithTag");function mye(e){try{Tc=!1,e()}finally{Tc=!0}}o(mye,"suppressLogging");var hye=nye?.name?.replace(/ /g,"-")||"main",Sn="info",TD,gy;function Sy({path:e,level:t,stdStreams:r,rotation:n,isExternalInstance:s,writeToLog:i,component:a}){t||(t="info");let c=or[t],l;function u(h){if(dE)if(l.logToStdstreams){f(h.replace(/\x1b\[[0-9;]*m/g,"")),Tc=!1;try{process.stdout.write(h)}finally{Tc=!0}}else f(h);else r&&process.stdout.write(h)}o(u,"logStdOut");function d(h){if(dE){if(f(h),r){Tc=!1;try{process.stderr.write(h)}finally{Tc=!0}}}else r&&process.stderr.write(h)}o(d,"logStdErr");let f=e&&hJ(e,n,s);function m(h){return{write(p){let _=[Sn];_.unshift(TD||hye+"/"+sye),gy&&_.push(gy),l.tag&&_.push(l.tag),h(`[${_.join("] [")}]: ${p}`)}}}if(o(m,"logPrepend"),s&&(_y=f),l=new SD({stdout:m(i??u),stderr:m(i??d),colorMode:r??!1},c),gJ(l),l.path=e,Object.defineProperty(l,"path",{get(){return e},set(h){e=h,f=hJ(e,l.rotation,s),s&&(_y=f)},enumerable:!0}),l.closeLogFile=f?.closeLogFile,l.logToStdstreams=r,!a){let h=new Map;l.forComponent=function(p){let _=h.get(p);return _||(_=Sy({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(Sy,"createLogger");var mJ=100;function hJ(e,t,r){let n=dJ.get(e),s,i,a,c,l=0;n||(n=d,n.closeLogFile=m,n.path=e,dJ.set(e,n)),pJ&&JSON.stringify(t)!==JSON.stringify(n.rotation)&&(n.rotation=t,setTimeout(()=>{if(n.rotator?.end(),!t)return;let p=rJ();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
  `)?"":`