s3db.js 7.2.1 → 7.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{customAlphabet as e,urlAlphabet as t}from"nanoid";import r from"zlib";import{PromisePool as i}from"@supercharge/promise-pool";import{ReadableStream as s}from"node:stream/web";import{chunk as n,merge as o,isString as a,isEmpty as c,invert as u,uniq as l,cloneDeep as h,get as f,set as d,isObject as p,isFunction as g,isPlainObject as m}from"lodash-es";import{createHash as y}from"crypto";import b from"json-stable-stringify";import{S3Client as w,PutObjectCommand as v,GetObjectCommand as O,HeadObjectCommand as k,CopyObjectCommand as S,DeleteObjectCommand as _,DeleteObjectsCommand as R,ListObjectsV2Command as j}from"@aws-sdk/client-s3";import{flatten as N,unflatten as I}from"flat";import E from"fastest-validator";const A="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",D=Object.fromEntries([...A].map((e,t)=>[e,t])),x=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";if(0===e)return A[0];if(e<0)return"-"+x(-Math.floor(e));e=Math.floor(e);let t="";for(;e;)t=A[e%62]+t,e=Math.floor(e/62);return t},P=e=>{if("string"!=typeof e)return NaN;if(""===e)return 0;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));let r=0;for(let t=0;t<e.length;t++){const i=D[e[t]];if(void 0===i)return NaN;r=62*r+i}return t?-r:r},C=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";const t=e<0;e=Math.abs(e);const[r,i]=e.toString().split("."),s=x(Number(r));return i?(t?"-":"")+s+"."+i:(t?"-":"")+s},T=e=>{if("string"!=typeof e)return NaN;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));const[r,i]=e.split("."),s=P(r);if(isNaN(s))return NaN;const n=i?Number(s+"."+i):s;return t?-n:n};function L(e){"string"!=typeof e&&(e=String(e));let t=0;for(let r=0;r<e.length;r++){const i=e.codePointAt(r);i<=127?t+=1:i<=2047?t+=2:i<=65535?t+=3:i<=1114111&&(t+=4,i>65535&&r++)}return t}function $(e){let t=0;for(const r of Object.keys(e))t+=L(r);return t}function M(e){return null==e?"":"boolean"==typeof e?e?"1":"0":"number"==typeof e?String(e):"string"==typeof e?e:Array.isArray(e)?0===e.length?"[]":e.map(e=>String(e)).join("|"):"object"==typeof e?JSON.stringify(e):String(e)}function U(e){const t={};for(const[r,i]of Object.entries(e)){const e=L(M(i));t[r]=e}return t}function q(e){const t=U(e);return Object.values(t).reduce((e,t)=>e+t,0)+$(e)}function B(e){const t=U(e),r=$(e),i=Object.values(t).reduce((e,t)=>e+t,0),s=i+r,n=Object.entries(t).sort(([,e],[,t])=>t-e).map(([e,t])=>({attribute:e,size:t,percentage:(t/s*100).toFixed(2)+"%"}));return{total:s,valueSizes:t,namesSize:r,valueTotal:i,breakdown:n,detailedBreakdown:{values:i,names:r,total:s}}}function F(e={}){const{version:t="1",timestamps:r=!1,id:i=""}=e,s={_v:String(t)};r&&(s.createdAt="2024-01-01T00:00:00.000Z",s.updatedAt="2024-01-01T00:00:00.000Z"),i&&(s.id=i);const n={};for(const[e,t]of Object.entries(s))n[e]=t;return q(n)}function z(e={}){const{s3Limit:t=2048,systemConfig:r={}}=e;return t-F(r)}class V extends Error{constructor({verbose:e,bucket:t,key:r,message:i,code:s,statusCode:n,requestId:o,awsMessage:a,original:c,commandName:u,commandInput:l,metadata:h,suggestion:f,...d}){e&&(i+=`\n\nVerbose:\n\n${JSON.stringify(d,null,2)}`),super(i),"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error(i).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=t,this.key=r,this.thrownAt=new Date,this.code=s,this.statusCode=n,this.requestId=o,this.awsMessage=a,this.original=c,this.commandName=u,this.commandInput=l,this.metadata=h,this.suggestion=f,this.data={bucket:t,key:r,...d,verbose:e,message:i}}toJson(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,awsMessage:this.awsMessage,bucket:this.bucket,key:this.key,thrownAt:this.thrownAt,commandName:this.commandName,commandInput:this.commandInput,metadata:this.metadata,suggestion:this.suggestion,data:this.data,original:this.original,stack:this.stack}}toString(){return`${this.name} | ${this.message}`}}class K extends V{constructor(e,t={}){let r,i,s,n,o,a;t.original&&(o=t.original,r=o.code||o.Code||o.name,i=o.statusCode||o.$metadata&&o.$metadata.httpStatusCode,s=o.requestId||o.$metadata&&o.$metadata.requestId,n=o.message,a=o.$metadata?{...o.$metadata}:void 0),super({message:e,...t,code:r,statusCode:i,requestId:s,awsMessage:n,original:o,metadata:a})}}class H extends K{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class W extends K{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class G extends K{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class J extends K{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class Y extends K{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class Q extends K{constructor({bucket:e,resourceName:t,id:r,original:i,...s}){if("string"!=typeof r)throw new Error("id must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");if("string"!=typeof t)throw new Error("resourceName must be a string");super(`Resource not found: ${t}/${r} [bucket:${e}]`,{bucket:e,resourceName:t,id:r,original:i,...s})}}class X extends K{constructor({bucket:e,original:t,...r}){if("string"!=typeof e)throw new Error("bucket must be a string");super(`Bucket does not exists [bucket:${e}]`,{bucket:e,original:t,...r})}}class Z extends K{constructor({bucket:e,key:t,resourceName:r,id:i,original:s,...n}){if("string"!=typeof t)throw new Error("key must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");if(void 0!==i&&"string"!=typeof i)throw new Error("id must be a string");super(`No such key: ${t} [bucket:${e}]`,{bucket:e,key:t,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class ee extends K{constructor({bucket:e,key:t,resourceName:r,id:i,original:s,...n}){if("string"!=typeof t)throw new Error("key must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");super(`Not found: ${t} [bucket:${e}]`,{bucket:e,key:t,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class te extends K{constructor({bucket:e,original:t,...r}){if("string"!=typeof e)throw new Error("bucket must be a string");super(`Missing metadata for bucket [bucket:${e}]`,{bucket:e,original:t,...r})}}class re extends K{constructor({bucket:e,resourceName:t,attributes:r,validation:i,message:s,original:n,...o}){if("string"!=typeof e)throw new Error("bucket must be a string");if("string"!=typeof t)throw new Error("resourceName must be a string");super(s||`Validation error: This item is not valid. Resource=${t} [bucket:${e}].\n${JSON.stringify(i,null,2)}`,{bucket:e,resourceName:t,attributes:r,validation:i,original:n,...o})}}class ie extends K{}const se={NotFound:ee,NoSuchKey:Z,UnknownError:ie,NoSuchBucket:X,MissingMetadata:te,InvalidResourceItem:re};function ne(e,t={}){const r=e.code||e.Code||e.name,i=e.$metadata?{...e.$metadata}:void 0,s=t.commandName,n=t.commandInput;let o;return"NoSuchKey"===r||"NotFound"===r?(o="Check if the key exists in the specified bucket and if your credentials have permission.",new Z({...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"NoSuchBucket"===r?(o="Check if the bucket exists and if your credentials have permission.",new X({...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"AccessDenied"===r||403===e.statusCode||"Forbidden"===r?(o="Check your credentials and bucket policy.",new J("Access denied",{...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"ValidationError"===r||400===e.statusCode?(o="Check the request parameters and payload.",new W("Validation error",{...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"MissingMetadata"===r?(o="Check if the object metadata is present and valid.",new te({...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):(o="Check the error details and AWS documentation.",new ie("Unknown error",{...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o}))}class oe extends K{constructor(e,t={}){super(e,{...t,suggestion:"Check the connection string format and credentials."})}}class ae extends K{constructor(e,t={}){super(e,{...t,suggestion:"Check if the crypto library is available and input is valid."})}}class ce extends K{constructor(e,t={}){super(e,{...t,suggestion:"Check schema definition and input data."})}}class ue extends K{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,t)}}class le extends K{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check partition definition, fields, and input values."})}}function he(e){if(null==e){const e=new Error("fnOrPromise cannot be null or undefined");return e.stack=(new Error).stack,[!1,e,void 0]}if("function"==typeof e)try{const t=e();return null==t?[!0,null,t]:"function"==typeof t.then?t.then(e=>[!0,null,e]).catch(e=>{if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}):[!0,null,t]}catch(e){if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}return"function"==typeof e.then?Promise.resolve(e).then(e=>[!0,null,e]).catch(e=>{if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}):[!0,null,e]}function fe(e){try{return[!0,null,e()]}catch(e){return[!1,e,null]}}var de=he;async function pe(){let e;if("undefined"!=typeof process){const[t,r,i]=await de(async()=>{const{webcrypto:e}=await import("crypto");return e});if(!t)throw new ae("Crypto API not available",{original:r,context:"dynamicCrypto"});e=i}else"undefined"!=typeof window&&(e=window.crypto);if(!e)throw new ae("Could not load any crypto library",{context:"dynamicCrypto"});return e}async function ge(e){const[t,r,i]=await de(pe);if(!t)throw new ae("Crypto API not available",{original:r});const s=(new TextEncoder).encode(e),[n,o,a]=await de(()=>i.subtle.digest("SHA-256",s));if(!n)throw new ae("SHA-256 digest failed",{original:o,input:e});return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function me(e,t){const[r,i,s]=await de(pe);if(!r)throw new ae("Crypto API not available",{original:i});const n=s.getRandomValues(new Uint8Array(16)),[o,a,c]=await de(()=>we(t,n));if(!o)throw new ae("Key derivation failed",{original:a,passphrase:t,salt:n});const u=s.getRandomValues(new Uint8Array(12)),l=(new TextEncoder).encode(e),[h,f,d]=await de(()=>s.subtle.encrypt({name:"AES-GCM",iv:u},c,l));if(!h)throw new ae("Encryption failed",{original:f,content:e});const p=new Uint8Array(n.length+u.length+d.byteLength);return p.set(n),p.set(u,n.length),p.set(new Uint8Array(d),n.length+u.length),function(e){if("undefined"!=typeof process)return Buffer.from(e).toString("base64");{const[t,r,i]=fe(()=>String.fromCharCode.apply(null,new Uint8Array(e)));if(!t)throw new ae("Failed to convert ArrayBuffer to base64 (browser)",{original:r});return window.btoa(i)}}(p)}async function ye(e,t){const[r,i,s]=await de(pe);if(!r)throw new ae("Crypto API not available",{original:i});const n=function(e){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(e,"base64"));{const[t,r,i]=fe(()=>window.atob(e));if(!t)throw new ae("Failed to decode base64 (browser)",{original:r});const s=i.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=i.charCodeAt(e);return n}}(e),o=n.slice(0,16),a=n.slice(16,28),c=n.slice(28),[u,l,h]=await de(()=>we(t,o));if(!u)throw new ae("Key derivation failed (decrypt)",{original:l,passphrase:t,salt:o});const[f,d,p]=await de(()=>s.subtle.decrypt({name:"AES-GCM",iv:a},h,c));if(!f)throw new ae("Decryption failed",{original:d,encryptedBase64:e});return(new TextDecoder).decode(p)}async function be(e){if("undefined"==typeof process)throw new ae("MD5 hashing is only available in Node.js environment",{context:"md5"});const[t,r,i]=await de(async()=>{const{createHash:t}=await import("crypto");return t("md5").update(e).digest("base64")});if(!t)throw new ae("MD5 hashing failed",{original:r,data:e});return i}async function we(e,t){const[r,i,s]=await de(pe);if(!r)throw new ae("Crypto API not available",{original:i});const n=(new TextEncoder).encode(e),[o,a,c]=await de(()=>s.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]));if(!o)throw new ae("importKey failed",{original:a,passphrase:e});const[u,l,h]=await de(()=>s.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]));if(!u)throw new ae("deriveKey failed",{original:l,passphrase:e,salt:t});return h}const ve=e(t,22),Oe=e("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var ke;function Se(){}function _e(){_e.init.call(this)}function Re(e){return void 0===e._maxListeners?_e.defaultMaxListeners:e._maxListeners}function je(e,t,r,i){var s,n,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=e._events)?(n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]):(n=e._events=new Se,e._eventsCount=0),o){if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(s=Re(e))&&s>0&&o.length>s){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=n[t]=r,++e._eventsCount;return e}function Ne(e,t,r){var i=!1;function s(){e.removeListener(t,s),i||(i=!0,r.apply(e,arguments))}return s.listener=r,s}function Ie(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Ee(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Se.prototype=Object.create(null),_e.EventEmitter=_e,_e.usingDomains=!1,_e.prototype.domain=void 0,_e.prototype._events=void 0,_e.prototype._maxListeners=void 0,_e.defaultMaxListeners=10,_e.init=function(){this.domain=null,_e.usingDomains&&(!ke.active||this instanceof ke.Domain||(this.domain=ke.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Se,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},_e.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},_e.prototype.getMaxListeners=function(){return Re(this)},_e.prototype.emit=function(e){var t,r,i,s,n,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,s=Ee(e,i),n=0;n<i;++n)s[n].call(r)}(r,l,this);break;case 2:!function(e,t,r,i){if(t)e.call(r,i);else for(var s=e.length,n=Ee(e,s),o=0;o<s;++o)n[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,i,s){if(t)e.call(r,i,s);else for(var n=e.length,o=Ee(e,n),a=0;a<n;++a)o[a].call(r,i,s)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,i,s,n){if(t)e.call(r,i,s,n);else for(var o=e.length,a=Ee(e,o),c=0;c<o;++c)a[c].call(r,i,s,n)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];!function(e,t,r,i){if(t)e.apply(r,i);else for(var s=e.length,n=Ee(e,s),o=0;o<s;++o)n[o].apply(r,i)}(r,l,this,s)}return!0},_e.prototype.addListener=function(e,t){return je(this,e,t,!1)},_e.prototype.on=_e.prototype.addListener,_e.prototype.prependListener=function(e,t){return je(this,e,t,!0)},_e.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Ne(this,e,t)),this},_e.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Ne(this,e,t)),this},_e.prototype.removeListener=function(e,t){var r,i,s,n,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new Se:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===t||r[n].listener&&r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Se,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,s=e.length;i<s;r+=1,i+=1)e[r]=e[i];e.pop()}(r,s);i.removeListener&&this.emit("removeListener",e,o||t)}return this},_e.prototype.off=function(e,t){return this.removeListener(e,t)},_e.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Se,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new Se:delete r[e]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new Se,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},_e.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},_e.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ie.call(e,t)},_e.prototype.listenerCount=Ie,_e.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var Ae=class extends _e{constructor(e={}){super(),this.name=this.constructor.name,this.options=e,this.hooks=new Map}async setup(e){this.database=e,this.beforeSetup(),await this.onSetup(),this.afterSetup()}async start(){this.beforeStart(),await this.onStart(),this.afterStart()}async stop(){this.beforeStop(),await this.onStop(),this.afterStop()}async onSetup(){}async onStart(){}async onStop(){}addHook(e,t,r){this.hooks.has(e)||this.hooks.set(e,new Map);const i=this.hooks.get(e);i.has(t)||i.set(t,[]),i.get(t).push(r)}removeHook(e,t,r){const i=this.hooks.get(e);if(i&&i.has(t)){const e=i.get(t),s=e.indexOf(r);s>-1&&e.splice(s,1)}}wrapResourceMethod(e,t,r){const i=e[t];if(e._pluginWrappers||(e._pluginWrappers=new Map),e._pluginWrappers.has(t)||e._pluginWrappers.set(t,[]),e._pluginWrappers.get(t).push(r),!e[`_wrapped_${t}`]){e[`_wrapped_${t}`]=i;const r=i&&i._isMockFunction;e[t]=async function(...r){let i=await e[`_wrapped_${t}`](...r);for(const s of e._pluginWrappers.get(t))i=await s.call(this,i,r,t);return i},r&&(Object.setPrototypeOf(e[t],Object.getPrototypeOf(i)),Object.assign(e[t],i))}}addMiddleware(e,t,r){if(e._pluginMiddlewares||(e._pluginMiddlewares={}),!e._pluginMiddlewares[t]){e._pluginMiddlewares[t]=[];const r=e[t].bind(e);e[t]=async function(...i){let s=-1;const n=async(...i)=>(s++,s<e._pluginMiddlewares[t].length?await e._pluginMiddlewares[t][s].call(this,n,...i):await r(...i));return await n(...i)}}e._pluginMiddlewares[t].push(r)}getPartitionValues(e,t){if(!t.config?.partitions)return{};const r={};for(const[i,s]of Object.entries(t.config.partitions))if(s.fields){r[i]={};for(const[n,o]of Object.entries(s.fields)){const s=this.getNestedFieldValue(e,n);null!=s&&(r[i][n]=t.applyPartitionRule(s,o))}}else r[i]={};return r}getNestedFieldValue(e,t){if(!t.includes("."))return e[t]??null;const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return null;i=i[e]}return i??null}beforeSetup(){this.emit("plugin.beforeSetup",new Date)}afterSetup(){this.emit("plugin.afterSetup",new Date)}beforeStart(){this.emit("plugin.beforeStart",new Date)}afterStart(){this.emit("plugin.afterStart",new Date)}beforeStop(){this.emit("plugin.beforeStop",new Date)}afterStop(){this.emit("plugin.afterStop",new Date)}};const De={setup(e){},start(){},stop(){}};class xe extends Ae{constructor(e={}){super(e),this.auditResource=null,this.config={includeData:!1!==e.includeData,includePartitions:!1!==e.includePartitions,maxDataSize:e.maxDataSize||1e4,...e}}async onSetup(){const[e,t,r]=await de(()=>this.database.createResource({name:"audits",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",recordId:"string|required",userId:"string|optional",timestamp:"string|required",oldData:"string|optional",newData:"string|optional",partition:"string|optional",partitionValues:"string|optional",metadata:"string|optional"},behavior:"body-overflow"}));this.auditResource=e?r:this.database.resources.audits||null,(e||this.auditResource)&&(this.installDatabaseProxy(),this.installEventListeners())}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const e=this.installEventListenersForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...t){const r=await this._originalCreateResource(...t);return"audits"!==r.name&&e(r),r},this.database._auditProxyInstalled=!0}installEventListeners(){for(const e of Object.values(this.database.resources))"audits"!==e.name&&this.installEventListenersForResource(e)}installEventListenersForResource(e){e.on("insert",async t=>{const r=t.id||"auto-generated",i=this.config.includePartitions?this.getPartitionValues(t,e):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"insert",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(t)),partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(s).catch(console.error)}),e.on("update",async t=>{const r=t.id;let i=t.$before;if(this.config.includeData&&!i){const[t,s,n]=await de(()=>e.get(r));t&&(i=n)}const s=this.config.includePartitions?this.getPartitionValues(t,e):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"update",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(t)),partition:this.config.includePartitions?this.getPrimaryPartition(s):null,partitionValues:this.config.includePartitions&&s&&Object.keys(s).length>0?JSON.stringify(s):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(console.error)}),e.on("delete",async t=>{const r=t.id;let i=t;if(this.config.includeData&&!i){const[t,s,n]=await de(()=>e.get(r));t&&(i=n)}const s=i&&this.config.includePartitions?this.getPartitionValues(i,e):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"delete",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(s):null,partitionValues:this.config.includePartitions&&s&&Object.keys(s).length>0?JSON.stringify(s):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(console.error)}),e.useMiddleware("deleteMany",async(t,r)=>{const i=t.args[0],s={};if(this.config.includeData)for(const t of i){const[r,i,n]=await de(()=>e.get(t));s[t]=r?n:null}const n=await r();if(n&&n.length>0&&this.config.includeData)for(const t of i){const r=s[t],i=r&&this.config.includePartitions?this.getPartitionValues(r,e):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"delete",recordId:t,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(r)),newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0",batchOperation:!0})};this.logAudit(n).catch(console.error)}return n})}getPartitionValues(e,t){if(!e)return null;const r=t.config?.partitions||{},i={};for(const[t,s]of Object.entries(r))if(s.fields){const r={};for(const[t,i]of Object.entries(s.fields)){const i=this.getNestedFieldValue(e,t);null!=i&&(r[t]=i)}Object.keys(r).length>0&&(i[t]=r)}return i}getNestedFieldValue(e,t){if(!t.includes("."))return e[t];const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return;i=i[e]}return i}getPrimaryPartition(e){if(!e)return null;const t=Object.keys(e);return t.length>0?t[0]:null}async logAudit(e){e.id||(e.id=`audit-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return await this.auditResource.insert(e)}truncateData(e){if(!e)return e;const t={};for(const[r,i]of Object.entries(e))r.startsWith("_")||"$overflow"===r||(t[r]=i);const r=JSON.stringify(t);if(r.length<=this.config.maxDataSize)return t;let i={...t},s=JSON.stringify(i).length;const n=JSON.stringify({_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}).length,o=this.config.maxDataSize-n;for(const[e,t]of Object.entries(i))if("string"==typeof t&&s>o){const r=s-o,n=Math.max(0,t.length-r-3);n<t.length&&(i[e]=t.substring(0,n)+"...",s=JSON.stringify(i).length)}return{...i,_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(e={}){if(!this.auditResource)return[];const[t,r,i]=await de(async()=>{const{resourceName:t,operation:r,recordId:i,userId:s,partition:n,startDate:o,endDate:a,limit:c=100,offset:u=0}=e;let l=(await this.auditResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&((!i||e.recordId===i)&&((!s||e.userId===s)&&((!n||e.partition===n)&&(!(o&&new Date(e.timestamp)<new Date(o))&&!(a&&new Date(e.timestamp)>new Date(a))))))));l.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp));return l.slice(u,u+c).map(e=>{const[t,,r]="string"==typeof e.oldData?fe(()=>JSON.parse(e.oldData)):[!0,null,e.oldData],[i,,s]="string"==typeof e.newData?fe(()=>JSON.parse(e.newData)):[!0,null,e.newData],[n,,o]=e.partitionValues&&"string"==typeof e.partitionValues?fe(()=>JSON.parse(e.partitionValues)):[!0,null,e.partitionValues],[a,,c]=e.metadata&&"string"==typeof e.metadata?fe(()=>JSON.parse(e.metadata)):[!0,null,e.metadata];return{...e,oldData:null===e.oldData||void 0===e.oldData||"null"===e.oldData?null:t?r:null,newData:null===e.newData||void 0===e.newData||"null"===e.newData?null:i?s:null,partitionValues:n?o:e.partitionValues,metadata:a?c:e.metadata}})});return t?i:[]}async getRecordHistory(e,t){return this.getAuditLogs({resourceName:e,recordId:t,limit:1e3})}async getPartitionHistory(e,t,r){return this.getAuditLogs({resourceName:e,partition:t,limit:1e3})}async getAuditStats(e={}){const{resourceName:t,startDate:r,endDate:i}=e,s=await this.getAuditLogs({resourceName:t,startDate:r,endDate:i,limit:1e4}),n={total:s.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const e of s)if(n.byOperation[e.operation]=(n.byOperation[e.operation]||0)+1,n.byResource[e.resourceName]=(n.byResource[e.resourceName]||0)+1,e.partition&&(n.byPartition[e.partition]=(n.byPartition[e.partition]||0)+1),n.byUser[e.userId]=(n.byUser[e.userId]||0)+1,e.timestamp){const t=e.timestamp.split("T")[0];n.timeline[t]=(n.timeline[t]||0)+1}return n}}function Pe(e,t){for(var r=0,i=e.length-1;i>=0;i--){var s=e[i];"."===s?e.splice(i,1):".."===s?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}var Ce=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,Te=function(e){return Ce.exec(e).slice(1)};function Le(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:"/";if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");i&&(e=i+"/"+e,t="/"===i.charAt(0))}return(t?"/":"")+(e=Pe(Be(e.split("/"),function(e){return!!e}),!t).join("/"))||"."}function $e(e){var t=Me(e),r="/"===Fe(e,-1);return(e=Pe(Be(e.split("/"),function(e){return!!e}),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function Me(e){return"/"===e.charAt(0)}function Ue(){return $e(Be(Array.prototype.slice.call(arguments,0),function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))}var qe={extname:function(e){return Te(e)[3]},basename:function(e,t){var r=Te(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},dirname:function(e){var t=Te(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},sep:"/",delimiter:":",relative:function(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=Le(e).substr(1),t=Le(t).substr(1);for(var i=r(e.split("/")),s=r(t.split("/")),n=Math.min(i.length,s.length),o=n,a=0;a<n;a++)if(i[a]!==s[a]){o=a;break}var c=[];for(a=o;a<i.length;a++)c.push("..");return(c=c.concat(s.slice(o))).join("/")},join:Ue,isAbsolute:Me,normalize:$e,resolve:Le};function Be(e,t){if(e.filter)return e.filter(t);for(var r=[],i=0;i<e.length;i++)t(e[i],i,e)&&r.push(e[i]);return r}var Fe="b"==="ab".substr(-1)?function(e,t,r){return e.substr(t,r)}:function(e,t,r){return t<0&&(t=e.length+t),e.substr(t,r)};class ze extends _e{constructor(e={}){super(),this.config=e}async _set(e,t){}async _get(e){}async _del(e){}async _clear(e){}validateKey(e){if(null==e||"string"!=typeof e||!e)throw new Error("Invalid key")}async set(e,t){return this.validateKey(e),await this._set(e,t),this.emit("set",t),t}async get(e){this.validateKey(e);const t=await this._get(e);return this.emit("get",t),t}async del(e){this.validateKey(e);const t=await this._del(e);return this.emit("delete",t),t}async delete(e){return this.del(e)}async clear(e){const t=await this._clear(e);return this.emit("clear",t),t}}function Ve(){throw new Error("setTimeout has not been defined")}function Ke(){throw new Error("clearTimeout has not been defined")}var He=Ve,We=Ke;function Ge(e){if(He===setTimeout)return setTimeout(e,0);if((He===Ve||!He)&&setTimeout)return He=setTimeout,setTimeout(e,0);try{return He(e,0)}catch(t){try{return He.call(null,e,0)}catch(t){return He.call(this,e,0)}}}"function"==typeof global.setTimeout&&(He=setTimeout),"function"==typeof global.clearTimeout&&(We=clearTimeout);var Je,Ye=[],Qe=!1,Xe=-1;function Ze(){Qe&&Je&&(Qe=!1,Je.length?Ye=Je.concat(Ye):Xe=-1,Ye.length&&et())}function et(){if(!Qe){var e=Ge(Ze);Qe=!0;for(var t=Ye.length;t;){for(Je=Ye,Ye=[];++Xe<t;)Je&&Je[Xe].run();Xe=-1,t=Ye.length}Je=null,Qe=!1,function(e){if(We===clearTimeout)return clearTimeout(e);if((We===Ke||!We)&&clearTimeout)return We=clearTimeout,clearTimeout(e);try{return We(e)}catch(t){try{return We.call(null,e)}catch(t){return We.call(this,e)}}}(e)}}function tt(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];Ye.push(new rt(e,t)),1!==Ye.length||Qe||Ge(et)}function rt(e,t){this.fun=e,this.array=t}rt.prototype.run=function(){this.fun.apply(null,this.array)};var it,st={env:{}};it="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e};var nt=/%[sdj%]/g;function ot(e){if(!bt(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(lt(arguments[r]));return t.join(" ")}r=1;for(var i=arguments,s=i.length,n=String(e).replace(nt,function(e){if("%%"===e)return"%";if(r>=s)return e;switch(e){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(e){return"[Circular]"}default:return e}}),o=i[r];r<s;o=i[++r])yt(o)||!Ot(o)?n+=" "+o:n+=" "+lt(o);return n}function at(e,t){if(wt(global.process))return function(){return at(e,t).apply(this,arguments)};if(!0===st.noDeprecation)return e;var r=!1;return function(){if(!r){if(st.throwDeprecation)throw new Error(t);st.traceDeprecation?console.trace(t):console.error(t),r=!0}return e.apply(this,arguments)}}var ct,ut={};function lt(e,t){var r={seen:[],stylize:ft};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),mt(t)?r.showHidden=t:t&&function(e,t){if(!t||!Ot(t))return e;var r=Object.keys(t),i=r.length;for(;i--;)e[r[i]]=t[r[i]]}(r,t),wt(r.showHidden)&&(r.showHidden=!1),wt(r.depth)&&(r.depth=2),wt(r.colors)&&(r.colors=!1),wt(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=ht),dt(r,e,r.depth)}function ht(e,t){var r=lt.styles[t];return r?"["+lt.colors[r][0]+"m"+e+"["+lt.colors[r][1]+"m":e}function ft(e,t){return e}function dt(e,t,r){if(e.customInspect&&t&&_t(t.inspect)&&t.inspect!==lt&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return bt(i)||(i=dt(e,i,r)),i}var s=function(e,t){if(wt(t))return e.stylize("undefined","undefined");if(bt(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(i=t,"number"==typeof i)return e.stylize(""+t,"number");var i;if(mt(t))return e.stylize(""+t,"boolean");if(yt(t))return e.stylize("null","null")}(e,t);if(s)return s;var n=Object.keys(t),o=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(n);if(e.showHidden&&(n=Object.getOwnPropertyNames(t)),St(t)&&(n.indexOf("message")>=0||n.indexOf("description")>=0))return pt(t);if(0===n.length){if(_t(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(vt(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(kt(t))return e.stylize(Date.prototype.toString.call(t),"date");if(St(t))return pt(t)}var c,u,l="",h=!1,f=["{","}"];(c=t,Array.isArray(c)&&(h=!0,f=["[","]"]),_t(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return vt(t)&&(l=" "+RegExp.prototype.toString.call(t)),kt(t)&&(l=" "+Date.prototype.toUTCString.call(t)),St(t)&&(l=" "+pt(t)),0!==n.length||h&&0!=t.length?r<0?vt(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=h?function(e,t,r,i,s){for(var n=[],o=0,a=t.length;o<a;++o)jt(t,String(o))?n.push(gt(e,t,r,i,String(o),!0)):n.push("");return s.forEach(function(s){s.match(/^\d+$/)||n.push(gt(e,t,r,i,s,!0))}),n}(e,t,r,o,n):n.map(function(i){return gt(e,t,r,o,i,h)}),e.seen.pop(),function(e,t,r){var i=e.reduce(function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(u,l,f)):f[0]+l+f[1]}function pt(e){return"["+Error.prototype.toString.call(e)+"]"}function gt(e,t,r,i,s,n){var o,a,c;if((c=Object.getOwnPropertyDescriptor(t,s)||{value:t[s]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),jt(i,s)||(o="["+s+"]"),a||(e.seen.indexOf(c.value)<0?(a=yt(r)?dt(e,c.value,null):dt(e,c.value,r-1)).indexOf("\n")>-1&&(a=n?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),wt(o)){if(n&&s.match(/^\d+$/))return a;(o=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function mt(e){return"boolean"==typeof e}function yt(e){return null===e}function bt(e){return"string"==typeof e}function wt(e){return void 0===e}function vt(e){return Ot(e)&&"[object RegExp]"===Rt(e)}function Ot(e){return"object"==typeof e&&null!==e}function kt(e){return Ot(e)&&"[object Date]"===Rt(e)}function St(e){return Ot(e)&&("[object Error]"===Rt(e)||e instanceof Error)}function _t(e){return"function"==typeof e}function Rt(e){return Object.prototype.toString.call(e)}function jt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}lt.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},lt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var Nt=[],It=[],Et="undefined"!=typeof Uint8Array?Uint8Array:Array,At=!1;function Dt(){At=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)Nt[t]=e[t],It[e.charCodeAt(t)]=t;It["-".charCodeAt(0)]=62,It["_".charCodeAt(0)]=63}function xt(e){return Nt[e>>18&63]+Nt[e>>12&63]+Nt[e>>6&63]+Nt[63&e]}function Pt(e,t,r){for(var i,s=[],n=t;n<r;n+=3)i=(e[n]<<16)+(e[n+1]<<8)+e[n+2],s.push(xt(i));return s.join("")}function Ct(e){var t;At||Dt();for(var r=e.length,i=r%3,s="",n=[],o=16383,a=0,c=r-i;a<c;a+=o)n.push(Pt(e,a,a+o>c?c:a+o));return 1===i?(t=e[r-1],s+=Nt[t>>2],s+=Nt[t<<4&63],s+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],s+=Nt[t>>10],s+=Nt[t>>4&63],s+=Nt[t<<2&63],s+="="),n.push(s),n.join("")}function Tt(e,t,r,i,s){var n,o,a=8*s-i-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?s-1:0,f=r?-1:1,d=e[t+h];for(h+=f,n=d&(1<<-l)-1,d>>=-l,l+=a;l>0;n=256*n+e[t+h],h+=f,l-=8);for(o=n&(1<<-l)-1,n>>=-l,l+=i;l>0;o=256*o+e[t+h],h+=f,l-=8);if(0===n)n=1-u;else{if(n===c)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,i),n-=u}return(d?-1:1)*o*Math.pow(2,n-i)}function Lt(e,t,r,i,s,n){var o,a,c,u=8*n-s-1,l=(1<<u)-1,h=l>>1,f=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,p=i?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*c-1)*Math.pow(2,s),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,s),o=0));s>=8;e[r+d]=255&a,d+=p,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;e[r+d]=255&o,d+=p,o/=256,u-=8);e[r+d-p]|=128*g}var $t={}.toString,Mt=Array.isArray||function(e){return"[object Array]"==$t.call(e)};function Ut(){return Bt.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function qt(e,t){if(Ut()<t)throw new RangeError("Invalid typed array length");return Bt.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=Bt.prototype:(null===e&&(e=new Bt(t)),e.length=t),e}function Bt(e,t,r){if(!(Bt.TYPED_ARRAY_SUPPORT||this instanceof Bt))return new Bt(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return Vt(this,e)}return Ft(this,e,t,r)}function Ft(e,t,r,i){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,i){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");t=void 0===r&&void 0===i?new Uint8Array(t):void 0===i?new Uint8Array(t,r):new Uint8Array(t,r,i);Bt.TYPED_ARRAY_SUPPORT?(e=t).__proto__=Bt.prototype:e=Kt(e,t);return e}(e,t,r,i):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!Bt.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|Gt(t,r);e=qt(e,i);var s=e.write(t,r);s!==i&&(e=e.slice(0,s));return e}(e,t,r):function(e,t){if(Wt(t)){var r=0|Ht(t.length);return 0===(e=qt(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(i=t.length)!=i?qt(e,0):Kt(e,t);if("Buffer"===t.type&&Mt(t.data))return Kt(e,t.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function zt(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function Vt(e,t){if(zt(t),e=qt(e,t<0?0:0|Ht(t)),!Bt.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function Kt(e,t){var r=t.length<0?0:0|Ht(t.length);e=qt(e,r);for(var i=0;i<r;i+=1)e[i]=255&t[i];return e}function Ht(e){if(e>=Ut())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ut().toString(16)+" bytes");return 0|e}function Wt(e){return!(null==e||!e._isBuffer)}function Gt(e,t){if(Wt(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Or(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return kr(e).length;default:if(i)return Or(e).length;t=(""+t).toLowerCase(),i=!0}}function Jt(e,t,r){var i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return lr(this,t,r);case"utf8":case"utf-8":return or(this,t,r);case"ascii":return cr(this,t,r);case"latin1":case"binary":return ur(this,t,r);case"base64":return nr(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return hr(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function Yt(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function Qt(e,t,r,i,s){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=s?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(s)return-1;r=e.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof t&&(t=Bt.from(t,i)),Wt(t))return 0===t.length?-1:Xt(e,t,r,i,s);if("number"==typeof t)return t&=255,Bt.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Xt(e,[t],r,i,s);throw new TypeError("val must be string, number or Buffer")}function Xt(e,t,r,i,s){var n,o=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,r/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){var l=-1;for(n=r;n<a;n++)if(u(e,n)===u(t,-1===l?0:n-l)){if(-1===l&&(l=n),n-l+1===c)return l*o}else-1!==l&&(n-=n-l),l=-1}else for(r+c>a&&(r=a-c),n=r;n>=0;n--){for(var h=!0,f=0;f<c;f++)if(u(e,n+f)!==u(t,f)){h=!1;break}if(h)return n}return-1}function Zt(e,t,r,i){r=Number(r)||0;var s=e.length-r;i?(i=Number(i))>s&&(i=s):i=s;var n=t.length;if(n%2!=0)throw new TypeError("Invalid hex string");i>n/2&&(i=n/2);for(var o=0;o<i;++o){var a=parseInt(t.substr(2*o,2),16);if(isNaN(a))return o;e[r+o]=a}return o}function er(e,t,r,i){return Sr(Or(t,e.length-r),e,r,i)}function tr(e,t,r,i){return Sr(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function rr(e,t,r,i){return tr(e,t,r,i)}function ir(e,t,r,i){return Sr(kr(t),e,r,i)}function sr(e,t,r,i){return Sr(function(e,t){for(var r,i,s,n=[],o=0;o<e.length&&!((t-=2)<0);++o)i=(r=e.charCodeAt(o))>>8,s=r%256,n.push(s),n.push(i);return n}(t,e.length-r),e,r,i)}function nr(e,t,r){return 0===t&&r===e.length?Ct(e):Ct(e.slice(t,r))}function or(e,t,r){r=Math.min(e.length,r);for(var i=[],s=t;s<r;){var n,o,a,c,u=e[s],l=null,h=u>239?4:u>223?3:u>191?2:1;if(s+h<=r)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(n=e[s+1]))&&(c=(31&u)<<6|63&n)>127&&(l=c);break;case 3:n=e[s+1],o=e[s+2],128==(192&n)&&128==(192&o)&&(c=(15&u)<<12|(63&n)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:n=e[s+1],o=e[s+2],a=e[s+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&(c=(15&u)<<18|(63&n)<<12|(63&o)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|1023&l),i.push(l),s+=h}return function(e){var t=e.length;if(t<=ar)return String.fromCharCode.apply(String,e);var r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=ar));return r}(i)}Bt.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT,Ut(),Bt.poolSize=8192,Bt._augment=function(e){return e.__proto__=Bt.prototype,e},Bt.from=function(e,t,r){return Ft(null,e,t,r)},Bt.TYPED_ARRAY_SUPPORT&&(Bt.prototype.__proto__=Uint8Array.prototype,Bt.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Bt[Symbol.species]),Bt.alloc=function(e,t,r){return function(e,t,r,i){return zt(t),t<=0?qt(e,t):void 0!==r?"string"==typeof i?qt(e,t).fill(r,i):qt(e,t).fill(r):qt(e,t)}(null,e,t,r)},Bt.allocUnsafe=function(e){return Vt(null,e)},Bt.allocUnsafeSlow=function(e){return Vt(null,e)},Bt.isBuffer=function(e){return null!=e&&(!!e._isBuffer||_r(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&_r(e.slice(0,0))}(e))},Bt.compare=function(e,t){if(!Wt(e)||!Wt(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,i=t.length,s=0,n=Math.min(r,i);s<n;++s)if(e[s]!==t[s]){r=e[s],i=t[s];break}return r<i?-1:i<r?1:0},Bt.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Bt.concat=function(e,t){if(!Mt(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return Bt.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=Bt.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var n=e[r];if(!Wt(n))throw new TypeError('"list" argument must be an Array of Buffers');n.copy(i,s),s+=n.length}return i},Bt.byteLength=Gt,Bt.prototype._isBuffer=!0,Bt.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Yt(this,t,t+1);return this},Bt.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Yt(this,t,t+3),Yt(this,t+1,t+2);return this},Bt.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Yt(this,t,t+7),Yt(this,t+1,t+6),Yt(this,t+2,t+5),Yt(this,t+3,t+4);return this},Bt.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?or(this,0,e):Jt.apply(this,arguments)},Bt.prototype.equals=function(e){if(!Wt(e))throw new TypeError("Argument must be a Buffer");return this===e||0===Bt.compare(this,e)},Bt.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},Bt.prototype.compare=function(e,t,r,i,s){if(!Wt(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),t<0||r>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=r)return 0;if(i>=s)return-1;if(t>=r)return 1;if(this===e)return 0;for(var n=(s>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),a=Math.min(n,o),c=this.slice(i,s),u=e.slice(t,r),l=0;l<a;++l)if(c[l]!==u[l]){n=c[l],o=u[l];break}return n<o?-1:o<n?1:0},Bt.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},Bt.prototype.indexOf=function(e,t,r){return Qt(this,e,t,r,!0)},Bt.prototype.lastIndexOf=function(e,t,r){return Qt(this,e,t,r,!1)},Bt.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var s=this.length-t;if((void 0===r||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var n=!1;;)switch(i){case"hex":return Zt(this,e,t,r);case"utf8":case"utf-8":return er(this,e,t,r);case"ascii":return tr(this,e,t,r);case"latin1":case"binary":return rr(this,e,t,r);case"base64":return ir(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sr(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},Bt.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ar=4096;function cr(e,t,r){var i="";r=Math.min(e.length,r);for(var s=t;s<r;++s)i+=String.fromCharCode(127&e[s]);return i}function ur(e,t,r){var i="";r=Math.min(e.length,r);for(var s=t;s<r;++s)i+=String.fromCharCode(e[s]);return i}function lr(e,t,r){var i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);for(var s="",n=t;n<r;++n)s+=vr(e[n]);return s}function hr(e,t,r){for(var i=e.slice(t,r),s="",n=0;n<i.length;n+=2)s+=String.fromCharCode(i[n]+256*i[n+1]);return s}function fr(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function dr(e,t,r,i,s,n){if(!Wt(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<n)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function pr(e,t,r,i){t<0&&(t=65535+t+1);for(var s=0,n=Math.min(e.length-r,2);s<n;++s)e[r+s]=(t&255<<8*(i?s:1-s))>>>8*(i?s:1-s)}function gr(e,t,r,i){t<0&&(t=4294967295+t+1);for(var s=0,n=Math.min(e.length-r,4);s<n;++s)e[r+s]=t>>>8*(i?s:3-s)&255}function mr(e,t,r,i,s,n){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function yr(e,t,r,i,s){return s||mr(e,0,r,4),Lt(e,t,r,i,23,4),r+4}function br(e,t,r,i,s){return s||mr(e,0,r,8),Lt(e,t,r,i,52,8),r+8}Bt.prototype.slice=function(e,t){var r,i=this.length;if((e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t<e&&(t=e),Bt.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=Bt.prototype;else{var s=t-e;r=new Bt(s,void 0);for(var n=0;n<s;++n)r[n]=this[n+e]}return r},Bt.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||fr(e,t,this.length);for(var i=this[e],s=1,n=0;++n<t&&(s*=256);)i+=this[e+n]*s;return i},Bt.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||fr(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i},Bt.prototype.readUInt8=function(e,t){return t||fr(e,1,this.length),this[e]},Bt.prototype.readUInt16LE=function(e,t){return t||fr(e,2,this.length),this[e]|this[e+1]<<8},Bt.prototype.readUInt16BE=function(e,t){return t||fr(e,2,this.length),this[e]<<8|this[e+1]},Bt.prototype.readUInt32LE=function(e,t){return t||fr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Bt.prototype.readUInt32BE=function(e,t){return t||fr(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Bt.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||fr(e,t,this.length);for(var i=this[e],s=1,n=0;++n<t&&(s*=256);)i+=this[e+n]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*t)),i},Bt.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||fr(e,t,this.length);for(var i=t,s=1,n=this[e+--i];i>0&&(s*=256);)n+=this[e+--i]*s;return n>=(s*=128)&&(n-=Math.pow(2,8*t)),n},Bt.prototype.readInt8=function(e,t){return t||fr(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Bt.prototype.readInt16LE=function(e,t){t||fr(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Bt.prototype.readInt16BE=function(e,t){t||fr(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Bt.prototype.readInt32LE=function(e,t){return t||fr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Bt.prototype.readInt32BE=function(e,t){return t||fr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Bt.prototype.readFloatLE=function(e,t){return t||fr(e,4,this.length),Tt(this,e,!0,23,4)},Bt.prototype.readFloatBE=function(e,t){return t||fr(e,4,this.length),Tt(this,e,!1,23,4)},Bt.prototype.readDoubleLE=function(e,t){return t||fr(e,8,this.length),Tt(this,e,!0,52,8)},Bt.prototype.readDoubleBE=function(e,t){return t||fr(e,8,this.length),Tt(this,e,!1,52,8)},Bt.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||dr(this,e,t,r,Math.pow(2,8*r)-1,0);var s=1,n=0;for(this[t]=255&e;++n<r&&(s*=256);)this[t+n]=e/s&255;return t+r},Bt.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||dr(this,e,t,r,Math.pow(2,8*r)-1,0);var s=r-1,n=1;for(this[t+s]=255&e;--s>=0&&(n*=256);)this[t+s]=e/n&255;return t+r},Bt.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,1,255,0),Bt.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Bt.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,2,65535,0),Bt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):pr(this,e,t,!0),t+2},Bt.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,2,65535,0),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):pr(this,e,t,!1),t+2},Bt.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,4,4294967295,0),Bt.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):gr(this,e,t,!0),t+4},Bt.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,4,4294967295,0),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):gr(this,e,t,!1),t+4},Bt.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t|=0,!i){var s=Math.pow(2,8*r-1);dr(this,e,t,r,s-1,-s)}var n=0,o=1,a=0;for(this[t]=255&e;++n<r&&(o*=256);)e<0&&0===a&&0!==this[t+n-1]&&(a=1),this[t+n]=(e/o|0)-a&255;return t+r},Bt.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t|=0,!i){var s=Math.pow(2,8*r-1);dr(this,e,t,r,s-1,-s)}var n=r-1,o=1,a=0;for(this[t+n]=255&e;--n>=0&&(o*=256);)e<0&&0===a&&0!==this[t+n+1]&&(a=1),this[t+n]=(e/o|0)-a&255;return t+r},Bt.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,1,127,-128),Bt.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Bt.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,2,32767,-32768),Bt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):pr(this,e,t,!0),t+2},Bt.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,2,32767,-32768),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):pr(this,e,t,!1),t+2},Bt.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,4,2147483647,-2147483648),Bt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):gr(this,e,t,!0),t+4},Bt.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||dr(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):gr(this,e,t,!1),t+4},Bt.prototype.writeFloatLE=function(e,t,r){return yr(this,e,t,!0,r)},Bt.prototype.writeFloatBE=function(e,t,r){return yr(this,e,t,!1,r)},Bt.prototype.writeDoubleLE=function(e,t,r){return br(this,e,t,!0,r)},Bt.prototype.writeDoubleBE=function(e,t,r){return br(this,e,t,!1,r)},Bt.prototype.copy=function(e,t,r,i){if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);var s,n=i-r;if(this===e&&r<t&&t<i)for(s=n-1;s>=0;--s)e[s+t]=this[s+r];else if(n<1e3||!Bt.TYPED_ARRAY_SUPPORT)for(s=0;s<n;++s)e[s+t]=this[s+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+n),t);return n},Bt.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),1===e.length){var s=e.charCodeAt(0);s<256&&(e=s)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!Bt.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{var o=Wt(e)?e:Or(new Bt(e,i).toString()),a=o.length;for(n=0;n<r-t;++n)this[n+t]=o[n%a]}return this};var wr=/[^+\/0-9A-Za-z-_]/g;function vr(e){return e<16?"0"+e.toString(16):e.toString(16)}function Or(e,t){var r;t=t||1/0;for(var i=e.length,s=null,n=[],o=0;o<i;++o){if((r=e.charCodeAt(o))>55295&&r<57344){if(!s){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function kr(e){return function(e){var t,r,i,s,n,o;At||Dt();var a=e.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");n="="===e[a-2]?2:"="===e[a-1]?1:0,o=new Et(3*a/4-n),i=n>0?a-4:a;var c=0;for(t=0,r=0;t<i;t+=4,r+=3)s=It[e.charCodeAt(t)]<<18|It[e.charCodeAt(t+1)]<<12|It[e.charCodeAt(t+2)]<<6|It[e.charCodeAt(t+3)],o[c++]=s>>16&255,o[c++]=s>>8&255,o[c++]=255&s;return 2===n?(s=It[e.charCodeAt(t)]<<2|It[e.charCodeAt(t+1)]>>4,o[c++]=255&s):1===n&&(s=It[e.charCodeAt(t)]<<10|It[e.charCodeAt(t+1)]<<4|It[e.charCodeAt(t+2)]>>2,o[c++]=s>>8&255,o[c++]=255&s),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(wr,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Sr(e,t,r,i){for(var s=0;s<i&&!(s+r>=t.length||s>=e.length);++s)t[s+r]=e[s];return s}function _r(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function Rr(){this.head=null,this.tail=null,this.length=0}Rr.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},Rr.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},Rr.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},Rr.prototype.clear=function(){this.head=this.tail=null,this.length=0},Rr.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},Rr.prototype.concat=function(e){if(0===this.length)return Bt.alloc(0);if(1===this.length)return this.head.data;for(var t=Bt.allocUnsafe(e>>>0),r=this.head,i=0;r;)r.data.copy(t,i),i+=r.data.length,r=r.next;return t};var jr=Bt.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Nr(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!jr(e))throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Er;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Ar;break;default:return void(this.write=Ir)}this.charBuffer=new Bt(6),this.charReceived=0,this.charLength=0}function Ir(e){return e.toString(this.encoding)}function Er(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Ar(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}Nr.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";if(e=e.slice(r,e.length),!((s=(t=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(t.length-1))>=55296&&s<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived);var s;i=(t+=e.toString(this.encoding,0,i)).length-1;if((s=t.charCodeAt(i))>=55296&&s<=56319){var n=this.surrogateSize;return this.charLength+=n,this.charReceived+=n,this.charBuffer.copy(this.charBuffer,n,0,n),e.copy(this.charBuffer,0,0,n),t.substring(0,i)}return t},Nr.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},Nr.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,i=this.charBuffer,s=this.encoding;t+=i.slice(0,r).toString(s)}return t},Pr.ReadableState=xr;var Dr=function(e){if(wt(ct)&&(ct=st.env.NODE_DEBUG||""),e=e.toUpperCase(),!ut[e])if(new RegExp("\\b"+e+"\\b","i").test(ct)){ut[e]=function(){var t=ot.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else ut[e]=function(){};return ut[e]}("stream");function xr(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof ai&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new Rr,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new Nr(e.encoding),this.encoding=e.encoding)}function Pr(e){if(!(this instanceof Pr))return new Pr(e);this._readableState=new xr(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),_e.call(this)}function Cr(e,t,r,i,s){var n=function(e,t){var r=null;Buffer.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(n)e.emit("error",n);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,$r(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!s){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&s){var a=new Error("stream.unshift() after end event");e.emit("error",a)}else{var c;!t.decoder||s||i||(r=t.decoder.write(r),c=!t.objectMode&&0===r.length),s||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,s?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&$r(e))),function(e,t){t.readingMore||(t.readingMore=!0,tt(Ur,e,t))}(e,t)}else s||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}(t)}it(Pr,_e),Pr.prototype.push=function(e,t){var r=this._readableState;return r.objectMode||"string"!=typeof e||(t=t||r.defaultEncoding)!==r.encoding&&(e=Buffer.from(e,t),t=""),Cr(this,r,e,t,!1)},Pr.prototype.unshift=function(e){return Cr(this,this._readableState,e,"",!0)},Pr.prototype.isPaused=function(){return!1===this._readableState.flowing},Pr.prototype.setEncoding=function(e){return this._readableState.decoder=new Nr(e),this._readableState.encoding=e,this};var Tr=8388608;function Lr(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=Tr?e=Tr:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function $r(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Dr("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?tt(Mr,e):Mr(e))}function Mr(e){Dr("emit readable"),e.emit("readable"),Fr(e)}function Ur(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(Dr("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=!1}function qr(e){Dr("readable nexttick read 0"),e.read(0)}function Br(e,t){t.reading||(Dr("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),Fr(e),t.flowing&&!t.reading&&e.read(0)}function Fr(e){var t=e._readableState;for(Dr("flow",t.flowing);t.flowing&&null!==e.read(););}function zr(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var i;e<t.head.data.length?(i=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):i=e===t.head.data.length?t.shift():r?function(e,t){var r=t.head,i=1,s=r.data;e-=s.length;for(;r=r.next;){var n=r.data,o=e>n.length?n.length:e;if(o===n.length?s+=n:s+=n.slice(0,e),0===(e-=o)){o===n.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=n.slice(o));break}++i}return t.length-=i,s}(e,t):function(e,t){var r=Buffer.allocUnsafe(e),i=t.head,s=1;i.data.copy(r),e-=i.data.length;for(;i=i.next;){var n=i.data,o=e>n.length?n.length:e;if(n.copy(r,r.length-e,0,o),0===(e-=o)){o===n.length?(++s,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=n.slice(o));break}++s}return t.length-=s,r}(e,t);return i}(e,t.buffer,t.decoder),r);var r}function Vr(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,tt(Kr,t,e))}function Kr(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function Hr(e,t){for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function Wr(){}function Gr(e,t,r){this.chunk=e,this.encoding=t,this.callback=r,this.next=null}function Jr(e,t){Object.defineProperty(this,"buffer",{get:at(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),e=e||{},this.objectMode=!!e.objectMode,t instanceof ai&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var r=e.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var s=!1===e.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,i=r.sync,s=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,s){--t.pendingcb,r?tt(s,i):s(i);e._writableState.errorEmitted=!0,e.emit("error",i)}(e,r,i,t,s);else{var n=ei(r);n||r.corked||r.bufferProcessing||!r.bufferedRequest||Zr(e,r),i?tt(Xr,e,r,n,s):Xr(e,r,n,s)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new ii(this)}function Yr(e){if(!(this instanceof Yr||this instanceof ai))return new Yr(e);this._writableState=new Jr(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev)),_e.call(this)}function Qr(e,t,r,i,s,n,o){t.writelen=i,t.writecb=o,t.writing=!0,t.sync=!0,r?e._writev(s,t.onwrite):e._write(s,n,t.onwrite),t.sync=!1}function Xr(e,t,r,i){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,i(),ri(e,t)}function Zr(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,s=new Array(i),n=t.corkedRequestsFree;n.entry=r;for(var o=0;r;)s[o]=r,r=r.next,o+=1;Qr(e,t,!0,t.length,s,"",n.finish),t.pendingcb++,t.lastBufferedRequest=null,n.next?(t.corkedRequestsFree=n.next,n.next=null):t.corkedRequestsFree=new ii(t)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(Qr(e,t,!1,t.objectMode?1:a.length,a,c,u),r=r.next,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequestCount=0,t.bufferedRequest=r,t.bufferProcessing=!1}function ei(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function ti(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function ri(e,t){var r=ei(t);return r&&(0===t.pendingcb?(ti(e,t),t.finished=!0,e.emit("finish")):ti(e,t)),r}function ii(e){var t=this;this.next=null,this.entry=null,this.finish=function(r){var i=t.entry;for(t.entry=null;i;){var s=i.callback;e.pendingcb--,s(r),i=i.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}}Pr.prototype.read=function(e){Dr("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return Dr("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?Vr(this):$r(this),null;if(0===(e=Lr(e,t))&&t.ended)return 0===t.length&&Vr(this),null;var i,s=t.needReadable;return Dr("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&Dr("length less than watermark",s=!0),t.ended||t.reading?Dr("reading or ended",s=!1):s&&(Dr("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=Lr(r,t))),null===(i=e>0?zr(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&Vr(this)),null!==i&&this.emit("data",i),i},Pr.prototype._read=function(e){this.emit("error",new Error("not implemented"))},Pr.prototype.pipe=function(e,t){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,Dr("pipe count=%d opts=%j",i.pipesCount,t);var s=!t||!1!==t.end?o:u;function n(e){Dr("onunpipe"),e===r&&u()}function o(){Dr("onend"),e.end()}i.endEmitted?tt(s):r.once("end",s),e.on("unpipe",n);var a=function(e){return function(){var t=e._readableState;Dr("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,Fr(e))}}(r);e.on("drain",a);var c=!1;function u(){Dr("cleanup"),e.removeListener("close",d),e.removeListener("finish",p),e.removeListener("drain",a),e.removeListener("error",f),e.removeListener("unpipe",n),r.removeListener("end",o),r.removeListener("end",u),r.removeListener("data",h),c=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||a()}var l=!1;function h(t){Dr("ondata"),l=!1,!1!==e.write(t)||l||((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==Hr(i.pipes,e))&&!c&&(Dr("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function f(t){var r;Dr("onerror",t),g(),e.removeListener("error",f),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function d(){e.removeListener("finish",p),g()}function p(){Dr("onfinish"),e.removeListener("close",d),g()}function g(){Dr("unpipe"),r.unpipe(e)}return r.on("data",h),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",f),e.once("close",d),e.once("finish",p),e.emit("pipe",r),i.flowing||(Dr("pipe resume"),r.resume()),e},Pr.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this);return this}var n=Hr(t.pipes,e);return-1===n||(t.pipes.splice(n,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this)),this},Pr.prototype.on=function(e,t){var r=_e.prototype.on.call(this,e,t);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&$r(this):tt(qr,this))}return r},Pr.prototype.addListener=Pr.prototype.on,Pr.prototype.resume=function(){var e=this._readableState;return e.flowing||(Dr("resume"),e.flowing=!0,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,tt(Br,e,t))}(this,e)),this},Pr.prototype.pause=function(){return Dr("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Dr("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Pr.prototype.wrap=function(e){var t=this._readableState,r=!1,i=this;for(var s in e.on("end",function(){if(Dr("wrapped end"),t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&i.push(e)}i.push(null)}),e.on("data",function(s){(Dr("wrapped data"),t.decoder&&(s=t.decoder.write(s)),t.objectMode&&null==s)||(t.objectMode||s&&s.length)&&(i.push(s)||(r=!0,e.pause()))}),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));return function(e,t){for(var r=0,i=e.length;r<i;r++)t(e[r],r)}(["error","close","destroy","pause","resume"],function(t){e.on(t,i.emit.bind(i,t))}),i._read=function(t){Dr("wrapped _read",t),r&&(r=!1,e.resume())},i},Pr._fromList=zr,Yr.WritableState=Jr,it(Yr,_e),Jr.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},Yr.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Yr.prototype.write=function(e,t,r){var i=this._writableState,s=!1;return"function"==typeof t&&(r=t,t=null),Bt.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=Wr),i.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),tt(t,r)}(this,r):function(e,t,r,i){var s=!0,n=!1;return null===r?n=new TypeError("May not write null values to stream"):Bt.isBuffer(r)||"string"==typeof r||void 0===r||t.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n&&(e.emit("error",n),tt(i,n),s=!1),s}(this,i,e,r)&&(i.pendingcb++,s=function(e,t,r,i,s){r=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=Bt.from(t,r));return t}(t,r,i),Bt.isBuffer(r)&&(i="buffer");var n=t.objectMode?1:r.length;t.length+=n;var o=t.length<t.highWaterMark;o||(t.needDrain=!0);if(t.writing||t.corked){var a=t.lastBufferedRequest;t.lastBufferedRequest=new Gr(r,i,s),a?a.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else Qr(e,t,!1,n,r,i,s);return o}(this,i,e,t,r)),s},Yr.prototype.cork=function(){this._writableState.corked++},Yr.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||Zr(this,e))},Yr.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Yr.prototype._write=function(e,t,r){r(new Error("not implemented"))},Yr.prototype._writev=null,Yr.prototype.end=function(e,t,r){var i=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(e,t,r){t.ending=!0,ri(e,t),r&&(t.finished?tt(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,i,r)},it(ai,Pr);for(var si=Object.keys(Yr.prototype),ni=0;ni<si.length;ni++){var oi=si[ni];ai.prototype[oi]||(ai.prototype[oi]=Yr.prototype[oi])}function ai(e){if(!(this instanceof ai))return new ai(e);Pr.call(this,e),Yr.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",ci)}function ci(){this.allowHalfOpen||this._writableState.ended||tt(ui,this)}function ui(e){e.end()}function li(e){this.afterTransform=function(t,r){return function(e,t,r){var i=e._transformState;i.transforming=!1;var s=i.writecb;if(!s)return e.emit("error",new Error("no writecb in Transform class"));i.writechunk=null,i.writecb=null,null!=r&&e.push(r);s(t);var n=e._readableState;n.reading=!1,(n.needReadable||n.length<n.highWaterMark)&&e._read(n.highWaterMark)}(e,t,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function hi(e){if(!(this instanceof hi))return new hi(e);ai.call(this,e),this._transformState=new li(this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(e){fi(t,e)}):fi(t)})}function fi(e,t){if(t)return e.emit("error",t);var r=e._writableState,i=e._transformState;if(r.length)throw new Error("Calling transform done when ws.length != 0");if(i.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}function di(e){if(!(this instanceof di))return new di(e);hi.call(this,e)}function pi(){_e.call(this)}it(hi,ai),hi.prototype.push=function(e,t){return this._transformState.needTransform=!1,ai.prototype.push.call(this,e,t)},hi.prototype._transform=function(e,t,r){throw new Error("Not implemented")},hi.prototype._write=function(e,t,r){var i=this._transformState;if(i.writecb=r,i.writechunk=e,i.writeencoding=t,!i.transforming){var s=this._readableState;(i.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},hi.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},it(di,hi),di.prototype._transform=function(e,t,r){r(null,e)},it(pi,_e),pi.Readable=Pr,pi.Writable=Yr,pi.Duplex=ai,pi.Transform=hi,pi.PassThrough=di,pi.Stream=pi,pi.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function s(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",s),e._isStdio||t&&!1===t.end||(r.on("end",o),r.on("close",a));var n=!1;function o(){n||(n=!0,e.end())}function a(){n||(n=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(u(),0===_e.listenerCount(this,"error"))throw e}function u(){r.removeListener("data",i),e.removeListener("drain",s),r.removeListener("end",o),r.removeListener("close",a),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",u),r.removeListener("close",u),e.removeListener("close",u)}return r.on("error",c),e.on("error",c),r.on("end",u),r.on("close",u),e.on("close",u),e.emit("pipe",r),e};class gi extends _e{constructor({resource:e}){super(),this.resource=e,this.client=e.client,this.stream=new s({highWaterMark:3*this.client.parallelism,start:this._start.bind(this),pull:this._pull.bind(this),cancel:this._cancel.bind(this)})}build(){return this.stream.getReader()}async _start(e){this.controller=e,this.continuationToken=null,this.closeNextIteration=!1}async _pull(e){if(this.closeNextIteration)return void e.close();const t=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),r=t?.Contents.map(e=>e.Key).map(e=>e.replace(this.client.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e).map(e=>e.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=t.NextContinuationToken,this.enqueue(r),t.IsTruncated||(this.closeNextIteration=!0)}enqueue(e){e.forEach(e=>{this.controller.enqueue(e),this.emit("id",e)})}_cancel(e){}}var mi=gi;class yi extends mi{enqueue(e){this.controller.enqueue(e),this.emit("page",e)}}class bi extends _e{constructor({resource:e,batchSize:t=10,concurrency:r=5}){if(super(),!e)throw new Error("Resource is required for ResourceReader");this.resource=e,this.client=e.client,this.batchSize=t,this.concurrency=r,this.input=new yi({resource:this.resource}),this.transform=new hi({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",e=>{this.transform.write(e)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",e=>{this.emit("error",e)}),this.transform.on("data",e=>{this.emit("data",e)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",e=>{this.emit("error",e)})}build(){return this}async _transform(e,t,r){const[s,n]=await de(async()=>{await i.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const t=await this.resource.get(e);return this.push(t),t})});r(n)}resume(){this.input.resume()}}class wi extends _e{constructor({resource:e,batchSize:t=10,concurrency:r=5}){super(),this.resource=e,this.client=e.client,this.batchSize=t,this.concurrency=r,this.buffer=[],this.writing=!1,this.writable=new Yr({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",e=>{this.emit("error",e)})}build(){return this}write(e){return this.buffer.push(e),this._maybeWrite().catch(e=>{this.emit("error",e)}),!0}end(){this.ended=!0,this._maybeWrite().catch(e=>{this.emit("error",e)})}async _maybeWrite(){if(!this.writing&&(0!==this.buffer.length||this.ended)){for(this.writing=!0;this.buffer.length>0;){const e=this.buffer.splice(0,this.batchSize),[t,r]=await de(async()=>{await i.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const[t,r,i]=await de(async()=>await this.resource.insert(e));return t?i:(this.emit("error",r,e),null)})});t||this.emit("error",r)}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(e,t,r){r()}}function vi(e){return new Promise((t,r)=>{if(!e)return r(new Error("streamToString: stream is undefined"));const i=[];e.on("data",e=>i.push(e)),e.on("error",r),e.on("end",()=>t(Buffer.concat(i).toString("utf-8")))})}var Oi=class extends ze{constructor({client:e,keyPrefix:t="cache",ttl:r=0,prefix:i}){super({client:e,keyPrefix:t,ttl:r,prefix:i}),this.client=e,this.keyPrefix=t,this.config.ttl=r,this.config.client=e,this.config.prefix=void 0!==i?i:t+(t.endsWith("/")?"":"/")}async _set(e,t){let i=JSON.stringify(t);const s=i.length;return i=r.gzipSync(i).toString("base64"),this.client.putObject({key:Ue(this.keyPrefix,e),body:i,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(s),"length-compressed":String(i.length),"compression-gain":(i.length/s).toFixed(2)}})}async _get(e){const[t,i,s]=await de(async()=>{const{Body:t}=await this.client.getObject(Ue(this.keyPrefix,e));let i=await vi(t);return i=Buffer.from(i,"base64"),i=r.unzipSync(i).toString(),JSON.parse(i)});if(t)return s;if("NoSuchKey"===i.name||"NotFound"===i.name)return null;throw i}async _del(e){return await this.client.deleteObject(Ue(this.keyPrefix,e)),!0}async _clear(){const e=await this.client.getAllKeys({prefix:this.keyPrefix});await this.client.deleteObjects(e)}async size(){return(await this.keys()).length}async keys(){const e=await this.client.getAllKeys({prefix:this.keyPrefix}),t=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return e.map(e=>e.startsWith(t)?e.slice(t.length):e)}};var ki=class extends ze{constructor(e={}){super(e),this.cache={},this.meta={},this.maxSize=e.maxSize||0,this.ttl=e.ttl||0}async _set(e,t){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const e=Object.entries(this.meta).sort((e,t)=>e[1].ts-t[1].ts)[0]?.[0];e&&(delete this.cache[e],delete this.meta[e])}return this.cache[e]=t,this.meta[e]={ts:Date.now()},t}async _get(e){if(!Object.prototype.hasOwnProperty.call(this.cache,e))return null;if(this.ttl>0){const t=Date.now(),r=this.meta[e];if(r&&t-r.ts>1e3*this.ttl)return delete this.cache[e],delete this.meta[e],null}return this.cache[e]}async _del(e){return delete this.cache[e],delete this.meta[e],!0}async _clear(e){if(!e)return this.cache={},this.meta={},!0;for(const t of Object.keys(this.cache))t.startsWith(e)&&(delete this.cache[t],delete this.meta[t]);return!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}};class Si extends Ae{constructor(e={}){super(e),this.driver=e.driver,this.config={includePartitions:!1!==e.includePartitions,...e}}async setup(e){await super.setup(e)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new ki(this.config.memoryOptions||{}):this.driver=new Oi({client:this.database.client,...this.config.s3Options||{}}),this.installDatabaseProxy(),this.installResourceHooks()}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._cacheProxyInstalled)return;const e=this.installResourceHooks.bind(this);this.database._originalCreateResourceForCache=this.database.createResource,this.database.createResource=async function(...t){const r=await this._originalCreateResourceForCache(...t);return e(r),r},this.database._cacheProxyInstalled=!0}installResourceHooks(){for(const e of Object.values(this.database.resources))this.installResourceHooksForResource(e)}installResourceHooksForResource(e){if(!this.driver)return;Object.defineProperty(e,"cache",{value:this.driver,writable:!0,configurable:!0,enumerable:!1}),e.cacheKeyFor=async(t={})=>{const{action:r,params:i={},partition:s,partitionValues:n}=t;return this.generateCacheKey(e,r,i,s,n)};const t=["count","listIds","getMany","getAll","page","list","get"];for(const r of t)e.useMiddleware(r,async(t,i)=>{let s;if("getMany"===r)s=await e.cacheKeyFor({action:r,params:{ids:t.args[0]}});else if("page"===r){const{offset:i,size:n,partition:o,partitionValues:a}=t.args[0]||{};s=await e.cacheKeyFor({action:r,params:{offset:i,size:n},partition:o,partitionValues:a})}else if("list"===r||"listIds"===r||"count"===r){const{partition:i,partitionValues:n}=t.args[0]||{};s=await e.cacheKeyFor({action:r,partition:i,partitionValues:n})}else"getAll"===r?s=await e.cacheKeyFor({action:r}):"get"===r&&(s=await e.cacheKeyFor({action:r,params:{id:t.args[0]}}));const[n,o,a]=await de(()=>e.cache.get(s));if(n&&null!=a)return a;if(!n&&"NoSuchKey"!==o.name)throw o;const c=await i();return await e.cache.set(s,c),c});const r=["insert","update","delete","deleteMany"];for(const t of r)e.useMiddleware(t,async(r,i)=>{const s=await i();if("insert"===t)await this.clearCacheForResource(e,r.args[0]);else if("update"===t)await this.clearCacheForResource(e,{id:r.args[0],...r.args[1]});else if("delete"===t){let t={id:r.args[0]};if("function"==typeof e.get){const[i,s,n]=await de(()=>e.get(r.args[0]));i&&n&&(t=n)}await this.clearCacheForResource(e,t)}else"deleteMany"===t&&await this.clearCacheForResource(e);return s})}async clearCacheForResource(e,t){if(!e.cache)return;const r=`resource=${e.name}`;if(await e.cache.clear(r),!0===this.config.includePartitions&&e.config?.partitions&&Object.keys(e.config.partitions).length>0)if(t){const i=this.getPartitionValues(t,e);for(const[t,s]of Object.entries(i))if(s&&Object.keys(s).length>0&&Object.values(s).some(e=>null!=e)){const i=Ue(r,`partition=${t}`);await e.cache.clear(i)}}else for(const t of Object.keys(e.config.partitions)){const i=Ue(r,`partition=${t}`);await e.cache.clear(i)}}async generateCacheKey(e,t,r={},i=null,s=null){const n=[`resource=${e.name}`,`action=${t}`];if(i&&s&&Object.keys(s).length>0){n.push(`partition:${i}`);for(const[e,t]of Object.entries(s))null!=t&&n.push(`${e}:${t}`)}if(Object.keys(r).length>0){const e=await this.hashParams(r);n.push(e)}return Ue(...n)+".json.gz"}async hashParams(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("|")||"empty";return await ge(t)}async getCacheStats(){return this.driver?{size:await this.driver.size(),keys:await this.driver.keys(),driver:this.driver.constructor.name}:null}async clearAllCache(){if(this.driver)for(const e of Object.values(this.database.resources))if(e.cache){const t=`resource=${e.name}`;await e.cache.clear(t)}}async warmCache(e,t={}){const r=this.database.resources[e];if(!r)throw new Error(`Resource '${e}' not found`);const{includePartitions:i=!0}=t;if(await r.getAll(),i&&r.config.partitions)for(const[e,t]of Object.entries(r.config.partitions))if(t.fields){const t=await r.getAll(),i=Array.isArray(t)?t:[],s=new Set;for(const t of i.slice(0,10)){const i=this.getPartitionValues(t,r);i[e]&&s.add(JSON.stringify(i[e]))}for(const t of s){const i=JSON.parse(t);await r.list({partition:e,partitionValues:i})}}}}const _i={async setup(e){e&&e.client&&(this.client=e.client,this.map={PutObjectCommand:"put",GetObjectCommand:"get",HeadObjectCommand:"head",DeleteObjectCommand:"delete",DeleteObjectsCommand:"delete",ListObjectsV2Command:"list"},this.costs={total:0,prices:{put:5e-6,copy:5e-6,list:5e-6,post:5e-6,get:4e-4/1e3,select:4e-4/1e3,delete:4e-4/1e3,head:4e-4/1e3},requests:{total:0,put:0,post:0,copy:0,list:0,get:0,select:0,delete:0,head:0},events:{total:0,PutObjectCommand:0,GetObjectCommand:0,HeadObjectCommand:0,DeleteObjectCommand:0,DeleteObjectsCommand:0,ListObjectsV2Command:0}},this.client.costs=JSON.parse(JSON.stringify(this.costs)))},async start(){this.client&&(this.client.on("command.response",e=>this.addRequest(e,this.map[e])),this.client.on("command.error",e=>this.addRequest(e,this.map[e])))},addRequest(e,t){t&&(this.costs.events[e]++,this.costs.events.total++,this.costs.requests.total++,this.costs.requests[t]++,this.costs.total+=this.costs.prices[t],this.client&&this.client.costs&&(this.client.costs.events[e]++,this.client.costs.events.total++,this.client.costs.requests.total++,this.client.costs.requests[t]++,this.client.costs.total+=this.client.costs.prices[t]))}};class Ri extends Ae{constructor(e={}){super(),this.indexResource=null,this.config={minWordLength:e.minWordLength||3,maxResults:e.maxResults||100,...e},this.indexes=new Map}async setup(e){this.database=e;const[t,r,i]=await de(()=>e.createResource({name:"fulltext_indexes",attributes:{id:"string|required",resourceName:"string|required",fieldName:"string|required",word:"string|required",recordIds:"json|required",count:"number|required",lastUpdated:"string|required"}}));this.indexResource=t?i:e.resources.fulltext_indexes,await this.loadIndexes(),this.installIndexingHooks()}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(!this.indexResource)return;const[e,t,r]=await de(()=>this.indexResource.getAll());if(e)for(const e of r){const t=`${e.resourceName}:${e.fieldName}:${e.word}`;this.indexes.set(t,{recordIds:e.recordIds||[],count:e.count||0})}}async saveIndexes(){if(!this.indexResource)return;const[e,t]=await de(async()=>{const e=await this.indexResource.getAll();for(const t of e)await this.indexResource.delete(t.id);for(const[e,t]of this.indexes.entries()){const[r,i,s]=e.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:i,word:s,recordIds:t.recordIds,count:t.count,lastUpdated:(new Date).toISOString()})}})}installIndexingHooks(){this.database.plugins||(this.database.plugins={}),this.database.plugins.fulltext=this;for(const e of Object.values(this.database.resources))"fulltext_indexes"!==e.name&&this.installResourceHooks(e);this.database._fulltextProxyInstalled||(this.database._previousCreateResourceForFullText=this.database.createResource,this.database.createResource=async function(...e){const t=await this._previousCreateResourceForFullText(...e);return this.plugins?.fulltext&&"fulltext_indexes"!==t.name&&this.plugins.fulltext.installResourceHooks(t),t},this.database._fulltextProxyInstalled=!0);for(const e of Object.values(this.database.resources))"fulltext_indexes"!==e.name&&this.installResourceHooks(e)}installResourceHooks(e){e._insert=e.insert,e._update=e.update,e._delete=e.delete,e._deleteMany=e.deleteMany,this.wrapResourceMethod(e,"insert",async(t,r,i)=>{const[s]=r;return this.indexRecord(e.name,t.id,s).catch(console.error),t}),this.wrapResourceMethod(e,"update",async(t,r,i)=>{const[s,n]=r;return this.removeRecordFromIndex(e.name,s).catch(console.error),this.indexRecord(e.name,s,t).catch(console.error),t}),this.wrapResourceMethod(e,"delete",async(t,r,i)=>{const[s]=r;return this.removeRecordFromIndex(e.name,s).catch(console.error),t}),this.wrapResourceMethod(e,"deleteMany",async(t,r,i)=>{const[s]=r;for(const t of s)this.removeRecordFromIndex(e.name,t).catch(console.error);return t})}async indexRecord(e,t,r){const i=this.getIndexedFields(e);if(i&&0!==i.length)for(const s of i){const i=this.getFieldValue(r,s);if(!i)continue;const n=this.tokenize(i);for(const r of n){if(r.length<this.config.minWordLength)continue;const i=`${e}:${s}:${r.toLowerCase()}`,n=this.indexes.get(i)||{recordIds:[],count:0};n.recordIds.includes(t)||(n.recordIds.push(t),n.count=n.recordIds.length),this.indexes.set(i,n)}}}async removeRecordFromIndex(e,t){for(const[r,i]of this.indexes.entries())if(r.startsWith(`${e}:`)){const e=i.recordIds.indexOf(t);e>-1&&(i.recordIds.splice(e,1),i.count=i.recordIds.length,0===i.recordIds.length?this.indexes.delete(r):this.indexes.set(r,i))}}getFieldValue(e,t){if(!t.includes("."))return e&&void 0!==e[t]?e[t]:null;const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return null;i=i[e]}return i}tokenize(e){if(!e)return[];return String(e).toLowerCase().replace(/[^\w\s\u00C0-\u017F]/g," ").split(/\s+/).filter(e=>e.length>0)}getIndexedFields(e){if(this.config.fields)return this.config.fields;return{users:["name","email"],products:["name","description"],articles:["title","content"]}[e]||[]}async search(e,t,r={}){const{fields:i=null,limit:s=this.config.maxResults,offset:n=0,exactMatch:o=!1}=r;if(!t||0===t.trim().length)return[];const a=this.tokenize(t),c=new Map,u=i||this.getIndexedFields(e);if(0===u.length)return[];for(const t of a)if(!(t.length<this.config.minWordLength))for(const r of u)if(o){const i=`${e}:${r}:${t.toLowerCase()}`,s=this.indexes.get(i);if(s)for(const e of s.recordIds){const t=c.get(e)||0;c.set(e,t+1)}}else for(const[i,s]of this.indexes.entries())if(i.startsWith(`${e}:${r}:${t.toLowerCase()}`))for(const e of s.recordIds){const t=c.get(e)||0;c.set(e,t+1)}return Array.from(c.entries()).map(([e,t])=>({recordId:e,score:t})).sort((e,t)=>t.score-e.score).slice(n,n+s)}async searchRecords(e,t,r={}){const i=await this.search(e,t,r);if(0===i.length)return[];const s=this.database.resources[e];if(!s)throw new Error(`Resource '${e}' not found`);const n=i.map(e=>e.recordId);return(await s.getMany(n)).filter(e=>e&&"object"==typeof e).map(e=>{const t=i.find(t=>t.recordId===e.id);return{...e,_searchScore:t?t.score:0}}).sort((e,t)=>t._searchScore-e._searchScore)}async rebuildIndex(e){const t=this.database.resources[e];if(!t)throw new Error(`Resource '${e}' not found`);for(const[t]of this.indexes.entries())t.startsWith(`${e}:`)&&this.indexes.delete(t);const r=await t.getAll();for(let t=0;t<r.length;t+=100){const i=r.slice(t,t+100);for(const t of i){const[r,i]=await de(()=>this.indexRecord(e,t.id,t))}}await this.saveIndexes()}async getIndexStats(){const e={totalIndexes:this.indexes.size,resources:{},totalWords:0};for(const[t,r]of this.indexes.entries()){const[i,s]=t.split(":");e.resources[i]||(e.resources[i]={fields:{},totalRecords:new Set,totalWords:0}),e.resources[i].fields[s]||(e.resources[i].fields[s]={words:0,totalOccurrences:0}),e.resources[i].fields[s].words++,e.resources[i].fields[s].totalOccurrences+=r.count,e.resources[i].totalWords++;for(const t of r.recordIds)e.resources[i].totalRecords.add(t);e.totalWords++}for(const t in e.resources)e.resources[t].totalRecords=e.resources[t].totalRecords.size;return e}async rebuildAllIndexes({timeout:e}={}){return e?Promise.race([this._rebuildAllIndexesInternal(),new Promise((t,r)=>setTimeout(()=>r(new Error("Timeout")),e))]):this._rebuildAllIndexesInternal()}async _rebuildAllIndexesInternal(){const e=Object.keys(this.database.resources).filter(e=>"fulltext_indexes"!==e);for(const t of e){const[e,r]=await de(()=>this.rebuildIndex(t))}}async clearIndex(e){for(const[t]of this.indexes.entries())t.startsWith(`${e}:`)&&this.indexes.delete(t);await this.saveIndexes()}async clearAllIndexes(){this.indexes.clear(),await this.saveIndexes()}}class ji extends Ae{constructor(e={}){super(),this.config={collectPerformance:!1!==e.collectPerformance,collectErrors:!1!==e.collectErrors,collectUsage:!1!==e.collectUsage,retentionDays:e.retentionDays||30,flushInterval:e.flushInterval||6e4,...e},this.metrics={operations:{insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}},resources:{},errors:[],performance:[],startTime:(new Date).toISOString()},this.flushTimer=null}async setup(e){if(this.database=e,"test"===process.env.NODE_ENV)return;const[t,r]=await de(async()=>{const[t,r,i]=await de(()=>e.createResource({name:"metrics",attributes:{id:"string|required",type:"string|required",resourceName:"string",operation:"string",count:"number|required",totalTime:"number|required",errors:"number|required",avgTime:"number|required",timestamp:"string|required",metadata:"json"}}));this.metricsResource=t?i:e.resources.metrics;const[s,n,o]=await de(()=>e.createResource({name:"error_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",error:"string|required",timestamp:"string|required",metadata:"json"}}));this.errorsResource=s?o:e.resources.error_logs;const[a,c,u]=await de(()=>e.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}}));this.performanceResource=a?u:e.resources.performance_logs});t||(this.metricsResource=e.resources.metrics,this.errorsResource=e.resources.error_logs,this.performanceResource=e.resources.performance_logs),this.installMetricsHooks(),"test"!==process.env.NODE_ENV&&this.startFlushTimer()}async start(){}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"test"!==process.env.NODE_ENV&&await this.flushMetrics()}installMetricsHooks(){for(const e of Object.values(this.database.resources))["metrics","error_logs","performance_logs"].includes(e.name)||this.installResourceHooks(e);this.database._createResource=this.database.createResource,this.database.createResource=async function(...e){const t=await this._createResource(...e);return this.plugins?.metrics&&!["metrics","error_logs","performance_logs"].includes(t.name)&&this.plugins.metrics.installResourceHooks(t),t}}installResourceHooks(e){e._insert=e.insert,e._update=e.update,e._delete=e.delete,e._deleteMany=e.deleteMany,e._get=e.get,e._getMany=e.getMany,e._getAll=e.getAll,e._list=e.list,e._listIds=e.listIds,e._count=e.count,e._page=e.page,e.insert=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._insert(...t));if(this.recordOperation(e.name,"insert",Date.now()-r,!i),i||this.recordError(e.name,"insert",s),!i)throw s;return n}.bind(this),e.update=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._update(...t));if(this.recordOperation(e.name,"update",Date.now()-r,!i),i||this.recordError(e.name,"update",s),!i)throw s;return n}.bind(this),e.delete=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._delete(...t));if(this.recordOperation(e.name,"delete",Date.now()-r,!i),i||this.recordError(e.name,"delete",s),!i)throw s;return n}.bind(this),e.deleteMany=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._deleteMany(...t));if(this.recordOperation(e.name,"delete",Date.now()-r,!i),i||this.recordError(e.name,"delete",s),!i)throw s;return n}.bind(this),e.get=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._get(...t));if(this.recordOperation(e.name,"get",Date.now()-r,!i),i||this.recordError(e.name,"get",s),!i)throw s;return n}.bind(this),e.getMany=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._getMany(...t));if(this.recordOperation(e.name,"get",Date.now()-r,!i),i||this.recordError(e.name,"get",s),!i)throw s;return n}.bind(this),e.getAll=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._getAll(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this),e.list=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._list(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this),e.listIds=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._listIds(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this),e.count=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._count(...t));if(this.recordOperation(e.name,"count",Date.now()-r,!i),i||this.recordError(e.name,"count",s),!i)throw s;return n}.bind(this),e.page=async function(...t){const r=Date.now(),[i,s,n]=await de(()=>e._page(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this)}recordOperation(e,t,r,i){this.metrics.operations[t]&&(this.metrics.operations[t].count++,this.metrics.operations[t].totalTime+=r,i&&this.metrics.operations[t].errors++),this.metrics.resources[e]||(this.metrics.resources[e]={insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}}),this.metrics.resources[e][t]&&(this.metrics.resources[e][t].count++,this.metrics.resources[e][t].totalTime+=r,i&&this.metrics.resources[e][t].errors++),this.config.collectPerformance&&this.metrics.performance.push({resourceName:e,operation:t,duration:r,timestamp:(new Date).toISOString()})}recordError(e,t,r){this.config.collectErrors&&this.metrics.errors.push({resourceName:e,operation:t,error:r.message,stack:r.stack,timestamp:(new Date).toISOString()})}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flushMetrics().catch(console.error)},this.config.flushInterval))}async flushMetrics(){if(!this.metricsResource)return;const[e,t]=await de(async()=>{const e="test"===process.env.NODE_ENV?{}:{global:"true"},t="test"===process.env.NODE_ENV?{}:{perf:"true"},r="test"===process.env.NODE_ENV?{}:{error:"true"},i="test"===process.env.NODE_ENV?{}:{resource:"true"};for(const[t,r]of Object.entries(this.metrics.operations))r.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:"global",operation:t,count:r.count,totalTime:r.totalTime,errors:r.errors,avgTime:r.count>0?r.totalTime/r.count:0,timestamp:(new Date).toISOString(),metadata:e});for(const[e,t]of Object.entries(this.metrics.resources))for(const[r,s]of Object.entries(t))s.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:e,operation:r,count:s.count,totalTime:s.totalTime,errors:s.errors,avgTime:s.count>0?s.totalTime/s.count:0,timestamp:(new Date).toISOString(),metadata:i});if(this.config.collectPerformance&&this.metrics.performance.length>0)for(const e of this.metrics.performance)await this.performanceResource.insert({id:`perf-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e.resourceName,operation:e.operation,duration:e.duration,timestamp:e.timestamp,metadata:t});if(this.config.collectErrors&&this.metrics.errors.length>0)for(const e of this.metrics.errors)await this.errorsResource.insert({id:`error-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e.resourceName,operation:e.operation,error:e.error,stack:e.stack,timestamp:e.timestamp,metadata:r});this.resetMetrics()});e||console.error("Failed to flush metrics:",t)}resetMetrics(){for(const e of Object.keys(this.metrics.operations))this.metrics.operations[e]={count:0,totalTime:0,errors:0};for(const e of Object.keys(this.metrics.resources))for(const t of Object.keys(this.metrics.resources[e]))this.metrics.resources[e][t]={count:0,totalTime:0,errors:0};this.metrics.performance=[],this.metrics.errors=[]}async getMetrics(e={}){const{type:t="operation",resourceName:r,operation:i,startDate:s,endDate:n,limit:o=100,offset:a=0}=e;if(!this.metricsResource)return[];let c=(await this.metricsResource.getAll()).filter(e=>(!t||e.type===t)&&((!r||e.resourceName===r)&&((!i||e.operation===i)&&(!(s&&new Date(e.timestamp)<new Date(s))&&!(n&&new Date(e.timestamp)>new Date(n))))));return c.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),c.slice(a,a+o)}async getErrorLogs(e={}){if(!this.errorsResource)return[];const{resourceName:t,operation:r,startDate:i,endDate:s,limit:n=100,offset:o=0}=e;let a=(await this.errorsResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&(!(i&&new Date(e.timestamp)<new Date(i))&&!(s&&new Date(e.timestamp)>new Date(s)))));return a.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),a.slice(o,o+n)}async getPerformanceLogs(e={}){if(!this.performanceResource)return[];const{resourceName:t,operation:r,startDate:i,endDate:s,limit:n=100,offset:o=0}=e;let a=(await this.performanceResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&(!(i&&new Date(e.timestamp)<new Date(i))&&!(s&&new Date(e.timestamp)>new Date(s)))));return a.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),a.slice(o,o+n)}async getStats(){const e=new Date,t=new Date(e.getTime()-864e5),[r,i,s]=await Promise.all([this.getMetrics({startDate:t.toISOString()}),this.getErrorLogs({startDate:t.toISOString()}),this.getPerformanceLogs({startDate:t.toISOString()})]),n={period:"24h",totalOperations:0,totalErrors:i.length,avgResponseTime:0,operationsByType:{},resources:{},uptime:{startTime:this.metrics.startTime,duration:e.getTime()-new Date(this.metrics.startTime).getTime()}};for(const e of r)if("operation"===e.type){n.totalOperations+=e.count,n.operationsByType[e.operation]||(n.operationsByType[e.operation]={count:0,errors:0,avgTime:0}),n.operationsByType[e.operation].count+=e.count,n.operationsByType[e.operation].errors+=e.errors;const t=n.operationsByType[e.operation],r=t.count,i=(t.avgTime*(r-e.count)+e.totalTime)/r;t.avgTime=i}const o=r.reduce((e,t)=>e+t.totalTime,0),a=r.reduce((e,t)=>e+t.count,0);return n.avgResponseTime=a>0?o/a:0,n}async cleanupOldData(){const e=new Date;if(e.setDate(e.getDate()-this.config.retentionDays),this.metricsResource){const t=await this.getMetrics({endDate:e.toISOString()});for(const e of t)await this.metricsResource.delete(e.id)}if(this.errorsResource){const t=await this.getErrorLogs({endDate:e.toISOString()});for(const e of t)await this.errorsResource.delete(e.id)}if(this.performanceResource){const t=await this.getPerformanceLogs({endDate:e.toISOString()});for(const e of t)await this.performanceResource.delete(e.id)}}}var Ni=class extends _e{constructor(e={}){super(),this.config=e,this.name=this.constructor.name,this.enabled=!1!==e.enabled}async initialize(e){this.database=e,this.emit("initialized",{replicator:this.name})}async replicate(e,t,r,i){throw new Error(`replicate() method must be implemented by ${this.name}`)}async replicateBatch(e,t){throw new Error(`replicateBatch() method must be implemented by ${this.name}`)}async testConnection(){throw new Error(`testConnection() method must be implemented by ${this.name}`)}async getStatus(){return{name:this.name,config:this.config,connected:!1}}async cleanup(){this.emit("cleanup",{replicator:this.name})}validateConfig(){return{isValid:!0,errors:[]}}};var Ii=class extends Ni{constructor(e={},t={}){super(e),this.projectId=e.projectId,this.datasetId=e.datasetId,this.bigqueryClient=null,this.credentials=e.credentials,this.location=e.location||"US",this.logTable=e.logTable,this.resources=this.parseResourcesConfig(t)}parseResourcesConfig(e){const t={};for(const[r,i]of Object.entries(e))"string"==typeof i?t[r]=[{table:i,actions:["insert"],transform:null}]:Array.isArray(i)?t[r]=i.map(e=>"string"==typeof e?{table:e,actions:["insert"],transform:null}:{table:e.table,actions:e.actions||["insert"],transform:e.transform||null}):"object"==typeof i&&(t[r]=[{table:i.table,actions:i.actions||["insert"],transform:i.transform||null}]);return t}validateConfig(){const e=[];this.projectId||e.push("projectId is required"),this.datasetId||e.push("datasetId is required"),0===Object.keys(this.resources).length&&e.push("At least one resource must be configured");for(const[t,r]of Object.entries(this.resources))for(const i of r){i.table||e.push(`Table name is required for resource '${t}'`),Array.isArray(i.actions)&&0!==i.actions.length||e.push(`Actions array is required for resource '${t}'`);const r=["insert","update","delete"],s=i.actions.filter(e=>!r.includes(e));s.length>0&&e.push(`Invalid actions for resource '${t}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`),i.transform&&"function"!=typeof i.transform&&e.push(`Transform must be a function for resource '${t}'`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,i]=await de(()=>import("@google-cloud/bigquery"));if(!t)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{BigQuery:s}=i;this.bigqueryClient=new s({projectId:this.projectId,credentials:this.credentials,location:this.location}),this.emit("initialized",{replicator:this.name,projectId:this.projectId,datasetId:this.datasetId,resources:Object.keys(this.resources)})}shouldReplicateResource(e){return this.resources.hasOwnProperty(e)}shouldReplicateAction(e,t){return!!this.resources[e]&&this.resources[e].some(e=>e.actions.includes(t))}getTablesForResource(e,t){return this.resources[e]?this.resources[e].filter(e=>e.actions.includes(t)).map(e=>({table:e.table,transform:e.transform})):[]}applyTransform(e,t){if(!t)return e;let r=JSON.parse(JSON.stringify(e));return r._length&&delete r._length,t(r)}async replicate(e,t,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(e,t))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(e,t);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const o=[],a=[],[c,u,l]=await de(async()=>{const s=this.bigqueryClient.dataset(this.datasetId);for(const e of n){const[n,c]=await de(async()=>{const n=s.table(e.table);let a;if("insert"===t){const t=this.applyTransform(r,e.transform);a=await n.insert([t])}else if("update"===t){const t=this.applyTransform(r,e.transform),s=Object.keys(t).filter(e=>"id"!==e).map(e=>`${e} = @${e}`).join(", "),n={id:i,...t},o=`UPDATE \`${this.projectId}.${this.datasetId}.${e.table}\` SET ${s} WHERE id = @id`,c=2;let u=null;for(let e=1;e<=c;e++)try{const[e]=await this.bigqueryClient.createQueryJob({query:o,params:n,location:this.location});await e.getQueryResults(),a=[e];break}catch(t){if(u=t,t?.message?.includes("streaming buffer")&&e<c){const e=30;await new Promise(t=>setTimeout(t,1e3*e));continue}throw t}if(!a)throw u}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM \`${this.projectId}.${this.datasetId}.${e.table}\` WHERE id = @id`,[r]=await this.bigqueryClient.createQueryJob({query:t,params:{id:i},location:this.location});await r.getQueryResults(),a=[r]}}o.push({table:e.table,success:!0,jobId:a[0]?.id})});n||a.push({table:e.table,error:c.message})}if(this.logTable){const[n,o]=await de(async()=>{const n=s.table(this.logTable);await n.insert([{resource_name:e,operation:t,record_id:i,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replicator"}])})}const c=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:e,operation:t,id:i,tables:n.map(e=>e.table),results:o,errors:a,success:c}),{success:c,results:o,errors:a,tables:n.map(e=>e.table)}});return c?l:(this.emit("replicator_error",{replicator:this.name,resourceName:e,operation:t,id:i,error:u.message}),{success:!1,error:u.message})}async replicateBatch(e,t){const r=[],i=[];for(const s of t){const[t,n,o]=await de(()=>this.replicate(e,s.operation,s.data,s.id,s.beforeData));t?r.push(o):i.push({id:s.id,error:n.message})}return{success:0===i.length,results:r,errors:i}}async testConnection(){const[e,t]=await de(async()=>{this.bigqueryClient||await this.initialize();const e=this.bigqueryClient.dataset(this.datasetId);return await e.getMetadata(),!0});return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async cleanup(){}getStatus(){return{...super.getStatus(),projectId:this.projectId,datasetId:this.datasetId,resources:this.resources,logTable:this.logTable}}};var Ei=class extends Ni{constructor(e={},t={}){super(e),this.connectionString=e.connectionString,this.host=e.host,this.port=e.port||5432,this.database=e.database,this.user=e.user,this.password=e.password,this.client=null,this.ssl=e.ssl,this.logTable=e.logTable,this.resources=this.parseResourcesConfig(t)}parseResourcesConfig(e){const t={};for(const[r,i]of Object.entries(e))"string"==typeof i?t[r]=[{table:i,actions:["insert"]}]:Array.isArray(i)?t[r]=i.map(e=>"string"==typeof e?{table:e,actions:["insert"]}:{table:e.table,actions:e.actions||["insert"]}):"object"==typeof i&&(t[r]=[{table:i.table,actions:i.actions||["insert"]}]);return t}validateConfig(){const e=[];this.connectionString||this.host&&this.database||e.push("Either connectionString or host+database must be provided"),0===Object.keys(this.resources).length&&e.push("At least one resource must be configured");for(const[t,r]of Object.entries(this.resources))for(const i of r){i.table||e.push(`Table name is required for resource '${t}'`),Array.isArray(i.actions)&&0!==i.actions.length||e.push(`Actions array is required for resource '${t}'`);const r=["insert","update","delete"],s=i.actions.filter(e=>!r.includes(e));s.length>0&&e.push(`Invalid actions for resource '${t}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,i]=await de(()=>import("pg"));if(!t)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{Client:s}=i,n=this.connectionString?{connectionString:this.connectionString,ssl:this.ssl}:{host:this.host,port:this.port,database:this.database,user:this.user,password:this.password,ssl:this.ssl};this.client=new s(n),await this.client.connect(),this.logTable&&await this.createLogTableIfNotExists(),this.emit("initialized",{replicator:this.name,database:this.database||"postgres",resources:Object.keys(this.resources)})}async createLogTableIfNotExists(){const e=`\n CREATE TABLE IF NOT EXISTS ${this.logTable} (\n id SERIAL PRIMARY KEY,\n resource_name VARCHAR(255) NOT NULL,\n operation VARCHAR(50) NOT NULL,\n record_id VARCHAR(255) NOT NULL,\n data JSONB,\n timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n source VARCHAR(100) DEFAULT 's3db-replicator',\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n );\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_resource_name ON ${this.logTable}(resource_name);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_operation ON ${this.logTable}(operation);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_record_id ON ${this.logTable}(record_id);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_timestamp ON ${this.logTable}(timestamp);\n `;await this.client.query(e)}shouldReplicateResource(e){return this.resources.hasOwnProperty(e)}shouldReplicateAction(e,t){return!!this.resources[e]&&this.resources[e].some(e=>e.actions.includes(t))}getTablesForResource(e,t){return this.resources[e]?this.resources[e].filter(e=>e.actions.includes(t)).map(e=>e.table):[]}async replicate(e,t,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(e,t))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(e,t);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const o=[],a=[],[c,u,l]=await de(async()=>{for(const e of n){const[s,n]=await de(async()=>{let s;if("insert"===t){const t=Object.keys(r),i=t.map(e=>r[e]),n=t.map(e=>`"${e}"`).join(", "),o=t.map((e,t)=>`$${t+1}`).join(", "),a=`INSERT INTO ${e} (${n}) VALUES (${o}) ON CONFLICT (id) DO NOTHING RETURNING *`;s=await this.client.query(a,i)}else if("update"===t){const t=Object.keys(r).filter(e=>"id"!==e),n=t.map((e,t)=>`"${e}"=$${t+1}`).join(", "),o=t.map(e=>r[e]);o.push(i);const a=`UPDATE ${e} SET ${n} WHERE id=$${t.length+1} RETURNING *`;s=await this.client.query(a,o)}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM ${e} WHERE id=$1 RETURNING *`;s=await this.client.query(t,[i])}}o.push({table:e,success:!0,rows:s.rows,rowCount:s.rowCount})});s||a.push({table:e,error:n.message})}if(this.logTable){const[s,n]=await de(async()=>{await this.client.query(`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,[e,t,i,JSON.stringify(r),(new Date).toISOString(),"s3db-replicator"])})}const s=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:e,operation:t,id:i,tables:n,results:o,errors:a,success:s}),{success:s,results:o,errors:a,tables:n}});return c?l:(this.emit("replicator_error",{replicator:this.name,resourceName:e,operation:t,id:i,error:u.message}),{success:!1,error:u.message})}async replicateBatch(e,t){const r=[],i=[];for(const s of t){const[t,n,o]=await de(()=>this.replicate(e,s.operation,s.data,s.id,s.beforeData));t?r.push(o):i.push({id:s.id,error:n.message})}return{success:0===i.length,results:r,errors:i}}async testConnection(){const[e,t]=await de(async()=>(this.client||await this.initialize(),await this.client.query("SELECT 1"),!0));return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async cleanup(){this.client&&await this.client.end()}getStatus(){return{...super.getStatus(),database:this.database||"postgres",resources:this.resources,logTable:this.logTable}}};class Ai{constructor(e){let t;const[r,i,s]=de(()=>new URL(e));if(!r)throw new oe("Invalid connection string: "+e,{original:i,input:e});t=s,this.region="us-east-1","s3:"===t.protocol?this.defineFromS3(t):this.defineFromCustomUri(t);for(const[e,r]of t.searchParams.entries())this[e]=r}defineFromS3(e){const[t,r,i]=fe(()=>decodeURIComponent(e.hostname));if(!t)throw new oe("Invalid bucket in connection string",{original:r,input:e.hostname});this.bucket=i||"s3db";const[s,n,o]=fe(()=>decodeURIComponent(e.username));if(!s)throw new oe("Invalid accessKeyId in connection string",{original:n,input:e.username});this.accessKeyId=o;const[a,c,u]=fe(()=>decodeURIComponent(e.password));if(!a)throw new oe("Invalid secretAccessKey in connection string",{original:c,input:e.password});if(this.secretAccessKey=u,this.endpoint="https://s3.us-east-1.amazonaws.com",["/","",null].includes(e.pathname))this.keyPrefix="";else{let[,...t]=e.pathname.split("/");this.keyPrefix=[...t||[]].join("/")}}defineFromCustomUri(e){this.forcePathStyle=!0,this.endpoint=e.origin;const[t,r,i]=fe(()=>decodeURIComponent(e.username));if(!t)throw new oe("Invalid accessKeyId in connection string",{original:r,input:e.username});this.accessKeyId=i;const[s,n,o]=fe(()=>decodeURIComponent(e.password));if(!s)throw new oe("Invalid secretAccessKey in connection string",{original:n,input:e.password});if(this.secretAccessKey=o,["/","",null].includes(e.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,t,...r]=e.pathname.split("/");if(t){const[e,r,i]=fe(()=>decodeURIComponent(t));if(!e)throw new oe("Invalid bucket in connection string",{original:r,input:t});this.bucket=i}else this.bucket="s3db";this.keyPrefix=[...r||[]].join("/")}}}class Di extends _e{constructor({verbose:e=!1,id:t=null,AwsS3Client:r,connectionString:i,parallelism:s=10}){super(),this.verbose=e,this.id=t??ve(),this.parallelism=s,this.config=new Ai(i),this.client=r||this.createClient()}createClient(){let e={region:this.config.region,endpoint:this.config.endpoint};this.config.forcePathStyle&&(e.forcePathStyle=!0),this.config.accessKeyId&&(e.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey});const t=new w(e);return t.middlewareStack.add((e,t)=>async r=>{if("DeleteObjectsCommand"===t.commandName){const e=r.request.body;if(e&&"string"==typeof e){const t=await be(e);r.request.headers["Content-MD5"]=t}}return e(r)},{step:"build",name:"addContentMd5ForDeleteObjects",priority:"high"}),t}async sendCommand(e){this.emit("command.request",e.constructor.name,e.input);const[t,r,i]=await de(()=>this.client.send(e));if(!t){throw ne(r,{bucket:this.config.bucket,key:e.input&&e.input.Key,commandName:e.constructor.name,commandInput:e.input})}return this.emit("command.response",e.constructor.name,i,e.input),i}async putObject({key:e,metadata:t,contentType:r,body:i,contentEncoding:s,contentLength:n}){const o="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";o&&qe.join(o,e);const a={};if(t)for(const[e,r]of Object.entries(t)){a[String(e).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const c={Bucket:this.config.bucket,Key:o?qe.join(o,e):e,Metadata:a,Body:i||Buffer.alloc(0)};let u,l;void 0!==r&&(c.ContentType=r),void 0!==s&&(c.ContentEncoding=s),void 0!==n&&(c.ContentLength=n);try{return u=await this.sendCommand(new v(c)),u}catch(t){throw l=t,ne(t,{bucket:this.config.bucket,key:e,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",l||u,{key:e,metadata:t,contentType:r,body:i,contentEncoding:s,contentLength:n})}}async getObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:t?qe.join(t,e):e};let i,s;try{return i=await this.sendCommand(new O(r)),i}catch(t){throw s=t,ne(t,{bucket:this.config.bucket,key:e,commandName:"GetObjectCommand",commandInput:r})}finally{this.emit("getObject",s||i,{key:e})}}async headObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:t?qe.join(t,e):e};let i,s;try{return i=await this.sendCommand(new k(r)),i}catch(t){throw s=t,ne(t,{bucket:this.config.bucket,key:e,commandName:"HeadObjectCommand",commandInput:r})}finally{this.emit("headObject",s||i,{key:e})}}async copyObject({from:e,to:t}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?qe.join(this.config.keyPrefix,t):t,CopySource:qe.join(this.config.bucket,this.config.keyPrefix?qe.join(this.config.keyPrefix,e):e)};let i,s;try{return i=await this.sendCommand(new S(r)),i}catch(e){throw s=e,ne(e,{bucket:this.config.bucket,key:t,commandName:"CopyObjectCommand",commandInput:r})}finally{this.emit("copyObject",s||i,{from:e,to:t})}}async exists(e){const[t,r]=await de(()=>this.headObject(e));if(t)return!0;if("NoSuchKey"===r.name||"NotFound"===r.name)return!1;throw r}async deleteObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";t&&qe.join(t,e);const r={Bucket:this.config.bucket,Key:t?qe.join(t,e):e};let i,s;try{return i=await this.sendCommand(new _(r)),i}catch(t){throw s=t,ne(t,{bucket:this.config.bucket,key:e,commandName:"DeleteObjectCommand",commandInput:r})}finally{this.emit("deleteObject",s||i,{key:e})}}async deleteObjects(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r=n(e,1e3),{results:s,errors:o}=await i.for(r).withConcurrency(this.parallelism).process(async e=>{for(const r of e)t&&qe.join(t,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:e.map(e=>({Key:t?qe.join(t,e):e}))}};let i;const[s,n,o]=await de(()=>this.sendCommand(new R(r)));if(!s)throw n;return i=o,i&&i.Errors&&i.Errors.length,i&&i.Deleted&&(i.Deleted.length,e.length),i}),a={deleted:s,notFound:o};return this.emit("deleteObjects",a,e),a}async deleteAll({prefix:e}={}){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,i=0;do{const s=new j({Bucket:this.config.bucket,Prefix:t?qe.join(t,e||""):e||"",ContinuationToken:r}),n=await this.client.send(s);if(n.Contents&&n.Contents.length>0){const t=new R({Bucket:this.config.bucket,Delete:{Objects:n.Contents.map(e=>({Key:e.Key}))}}),r=await this.client.send(t),s=r.Deleted?r.Deleted.length:0;i+=s,this.emit("deleteAll",{prefix:e,batch:s,total:i})}r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:e,totalDeleted:i}),i}async moveObject({from:e,to:t}){const[r,i]=await de(async()=>{await this.copyObject({from:e,to:t}),await this.deleteObject(e)});if(!r)throw new ie("Unknown error in moveObject",{bucket:this.config.bucket,from:e,to:t,original:i});return!0}async listObjects({prefix:e,maxKeys:t=1e3,continuationToken:r}={}){const i={Bucket:this.config.bucket,MaxKeys:t,ContinuationToken:r,Prefix:this.config.keyPrefix?qe.join(this.config.keyPrefix,e||""):e||""},[s,n,o]=await de(()=>this.sendCommand(new j(i)));if(!s)throw new ie("Unknown error in listObjects",{prefix:e,bucket:this.config.bucket,original:n});return this.emit("listObjects",o,i),o}async count({prefix:e}={}){let t,r=0,i=!0;for(;i;){const s={prefix:e,continuationToken:t},n=await this.listObjects(s);r+=n.KeyCount||0,i=n.IsTruncated||!1,t=n.NextContinuationToken}return this.emit("count",r,{prefix:e}),r}async getAllKeys({prefix:e}={}){let t,r=[],i=!0;for(;i;){const s={prefix:e,continuationToken:t},n=await this.listObjects(s);n.Contents&&(r=r.concat(n.Contents.map(e=>e.Key))),i=n.IsTruncated||!1,t=n.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(e=>e.replace(this.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e)),this.emit("getAllKeys",r,{prefix:e}),r}async getContinuationTokenAfterOffset(e={}){const{prefix:t,offset:r=1e3}=e;if(0===r)return null;let i,s=!0,n=0;for(;s;){const e={prefix:t,maxKeys:r<1e3?r:r-n>1e3?1e3:r-n,continuationToken:i},o=await this.listObjects(e);if(o.Contents&&(n+=o.Contents.length),s=o.IsTruncated||!1,i=o.NextContinuationToken,n>=r)break}return this.emit("getContinuationTokenAfterOffset",i||null,e),i||null}async getKeysPage(e={}){const{prefix:t,offset:r=0,amount:i=100}=e;let s,n=[],o=!0;if(r>0&&(s=await this.getContinuationTokenAfterOffset({prefix:t,offset:r}),!s))return this.emit("getKeysPage",[],e),[];for(;o;){const e={prefix:t,continuationToken:s},r=await this.listObjects(e);if(r.Contents&&(n=n.concat(r.Contents.map(e=>e.Key))),o=r.IsTruncated||!1,s=r.NextContinuationToken,n.length>=i){n=n.slice(0,i);break}}return this.config.keyPrefix&&(n=n.map(e=>e.replace(this.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e)),this.emit("getKeysPage",n,e),n}async moveAllObjects({prefixFrom:e,prefixTo:t}){const r=await this.getAllKeys({prefix:e}),{results:s,errors:n}=await i.for(r).withConcurrency(this.parallelism).process(async r=>{const i=r.replace(e,t),[s,n]=await de(async()=>{await this.moveObject({from:r,to:i})});if(!s)throw new ie("Unknown error in moveAllObjects",{bucket:this.config.bucket,from:r,to:i,original:n});return i});if(this.emit("moveAllObjects",{results:s,errors:n},{prefixFrom:e,prefixTo:t}),n.length>0)throw new Error("Some objects could not be moved");return s}}var xi=Di;async function Pi(e,t,r){if(!this.passphrase)return t.push(new W("Missing configuration for secrets encryption.",{actual:e,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),e;const[i,s,n]=await de(()=>me(String(e),this.passphrase));return i?n:(t.push(new W("Problem encrypting secret.",{actual:e,type:"encryptionProblem",error:s,suggestion:"Check the passphrase and input value."})),e)}async function Ci(e,t,r){if(a(e))return e;const[i,s,n]=fe(()=>JSON.stringify(e));if(!i)throw new W("Failed to stringify JSON",{original:s,input:e});return n}class Ti extends E{constructor({options:e,passphrase:t,autoEncrypt:r=!0}={}){super(o({},{useNewCustomCheckerFunction:!0,messages:{encryptionKeyMissing:"Missing configuration for secrets encryption.",encryptionProblem:"Problem encrypting secret. Actual: {actual}. Error: {error}"},defaults:{string:{trim:!0},object:{strict:"remove"},number:{convert:!0}}},e)),this.passphrase=t,this.autoEncrypt=r,this.alias("secret",{type:"string",custom:this.autoEncrypt?Pi:void 0,messages:{string:"The '{field}' field must be a string.",stringMin:"This secret '{field}' field length must be at least {expected} long."}}),this.alias("secretAny",{type:"any",custom:this.autoEncrypt?Pi:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Pi:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?Ci:void 0})}}const Li=new Proxy(Ti,{instance:null,construct(e,t){return this.instance||(this.instance=new e(...t)),this.instance}});const $i={trim:e=>null==e?e:e.trim(),encrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,i,s]=await he(()=>me(e,t));return r?s:e},decrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,i,s]=await he(()=>ye(e,t));return r?"null"===s?null:"undefined"!==s?s:void 0:e},toString:e=>null==e?e:String(e),fromArray:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>"string"==typeof e?e.replace(/\\/g,"\\\\").replace(new RegExp(`\\${t}`,"g"),`\\${t}`):String(e)).join(t)},toArray:(e,{separator:t})=>{if(Array.isArray(e))return e;if(null==e)return e;if(""===e)return[];const r=[];let i="",s=0;const n=String(e);for(;s<n.length;)"\\"===n[s]&&s+1<n.length?(i+=n[s+1],s+=2):n[s]===t?(r.push(i),i="",s++):(i+=n[s],s++);return r.push(i),r},toJSON:e=>{if(null===e)return null;if(void 0===e)return;if("string"==typeof e){const[t,r,i]=fe(()=>JSON.parse(e));return e}const[t,r,i]=fe(()=>JSON.stringify(e));return t?i:e},fromJSON:e=>{if(null===e)return null;if(void 0===e)return;if("string"!=typeof e)return e;if(""===e)return"";const[t,r,i]=fe(()=>JSON.parse(e));return t?i:e},toNumber:e=>a(e)?e.includes(".")?parseFloat(e):parseInt(e):e,toBool:e=>[!0,1,"true","1","yes","y"].includes(e),fromBool:e=>[!0,1,"true","1","yes","y"].includes(e)?"1":"0",fromBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=P(e);return isNaN(t)?void 0:t}},toBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return x(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:x(t)}return e},fromBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=T(e);return isNaN(t)?void 0:t}},toBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return C(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:C(t)}return e},fromArrayOfNumbers:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>{if("number"==typeof e&&!isNaN(e))return x(e);const t=Number(e);return isNaN(t)?"":x(t)}).join(t)},toArrayOfNumbers:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:P(e));if(null==e)return e;if(""===e)return[];const r=String(e),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===t?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e){const t=P(e);return isNaN(t)?NaN:t}return NaN})},fromArrayOfDecimals:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>{if("number"==typeof e&&!isNaN(e))return C(e);const t=Number(e);return isNaN(t)?"":C(t)}).join(t)},toArrayOfDecimals:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:T(e));if(null==e)return e;if(""===e)return[];const r=String(e),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===t?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e){const t=T(e);return isNaN(t)?NaN:t}return NaN})}};class Mi{constructor(e){const{map:t,name:r,attributes:i,passphrase:s,version:n=1,options:a={}}=e;this.name=r,this.version=n,this.attributes=i||{},this.passphrase=s??"secret",this.options=o({},this.defaultOptions(),a),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const l=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Li({autoEncrypt:!1}).compile(o({$$async:!0},l)),this.options.generateAutoHooks&&this.generateAutoHooks(),c(t)){const e=N(this.attributes,{safe:!0}),t=Object.keys(e).filter(e=>!e.includes("$$")),r=this.extractObjectKeys(this.attributes),i=[...new Set([...t,...r])],{mapping:s,reversedMapping:n}=function(e){const t={},r={};return e.forEach((e,i)=>{const s=x(i);t[e]=s,r[s]=e}),{mapping:t,reversedMapping:r}}(i);this.map=s,this.reversedMap=n}else this.map=t,this.reversedMap=u(t)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(e,t,r){this.options.hooks[e][t]||(this.options.hooks[e][t]=[]),this.options.hooks[e][t]=l([...this.options.hooks[e][t],r])}extractObjectKeys(e,t=""){const r=[];for(const[i,s]of Object.entries(e)){if(i.startsWith("$$"))continue;const e=t?`${t}.${i}`:i;"object"!=typeof s||null===s||Array.isArray(s)||(r.push(e),"object"===s.$$type&&r.push(...this.extractObjectKeys(s,e)))}return r}generateAutoHooks(){const e=N(h(this.attributes),{safe:!0});for(const[t,r]of Object.entries(e))if(r.includes("array")){if(r.includes("items:string"))this.addHook("beforeMap",t,"fromArray"),this.addHook("afterUnmap",t,"toArray");else if(r.includes("items:number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",t,"fromArrayOfNumbers"),this.addHook("afterUnmap",t,"toArrayOfNumbers")):(this.addHook("beforeMap",t,"fromArrayOfDecimals"),this.addHook("afterUnmap",t,"toArrayOfDecimals"))}}else if(r.includes("secret"))this.options.autoEncrypt&&this.addHook("beforeMap",t,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",t,"decrypt");else{if(r.includes("number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",t,"toBase62"),this.addHook("afterUnmap",t,"fromBase62")):(this.addHook("beforeMap",t,"toBase62Decimal"),this.addHook("afterUnmap",t,"fromBase62Decimal"));continue}r.includes("boolean")?(this.addHook("beforeMap",t,"fromBool"),this.addHook("afterUnmap",t,"toBool")):(r.includes("json")||"object"===r||r.includes("object"))&&(this.addHook("beforeMap",t,"toJSON"),this.addHook("afterUnmap",t,"fromJSON"))}}static import(e){let{map:t,name:r,options:i,version:s,attributes:n}=a(e)?JSON.parse(e):e;const[o,c,u]=fe(()=>Mi._importAttributes(n));if(!o)throw new ce("Failed to import schema attributes",{original:c,input:n});n=u;return new Mi({map:t,name:r,options:i,version:s,attributes:n})}static _importAttributes(e){if("string"==typeof e){const[t,r,i]=fe(()=>JSON.parse(e));if(t&&"object"==typeof i&&null!==i){const[t,r,s]=fe(()=>Mi._importAttributes(i));if(!t)throw new ce("Failed to parse nested schema attribute",{original:r,input:e});return s}return e}if(Array.isArray(e)){const[t,r,i]=fe(()=>e.map(e=>Mi._importAttributes(e)));if(!t)throw new ce("Failed to import array schema attributes",{original:r,input:e});return i}if("object"==typeof e&&null!==e){const t={};for(const[r,i]of Object.entries(e)){const[e,s,n]=fe(()=>Mi._importAttributes(i));if(!e)throw new ce("Failed to import object schema attribute",{original:s,key:r,input:i});t[r]=n}return t}return e}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(e){if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>this._exportAttributes(e));if("object"==typeof e&&null!==e){const t={};for(const[r,i]of Object.entries(e))t[r]=this._exportAttributes(i);return t}return e}async applyHooksActions(e,t){const r=h(e);for(const[e,i]of Object.entries(this.options.hooks[t]))for(const t of i){const i=f(r,e);void 0!==i&&"function"==typeof $i[t]&&d(r,e,await $i[t](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(e,{mutateOriginal:t=!1}={}){let r=t?e:h(e);return await this.validator(r)}async mapper(e){let t=h(e);t=await this.applyHooksActions(t,"beforeMap");const r=N(t,{safe:!0}),i={_v:this.version+""};for(const[e,t]of Object.entries(r)){const r=this.map[e]||e,s=this.getAttributeDefinition(e);"number"==typeof t&&"string"==typeof s&&s.includes("number")?i[r]=x(t):"string"==typeof t?"[object Object]"===t?i[r]="{}":(t.startsWith("{")||t.startsWith("["),i[r]=t):Array.isArray(t)||"object"==typeof t&&null!==t?i[r]=JSON.stringify(t):i[r]=t}return await this.applyHooksActions(i,"afterMap"),i}async unmapper(e,t){let r=h(e);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const i=t?u(t):this.reversedMap,s={};for(const[e,t]of Object.entries(r)){const r=i&&i[e]?i[e]:e;let n=t;const o=this.getAttributeDefinition(r);if("string"!=typeof o||!o.includes("number")||o.includes("array")||o.includes("decimal")){if("string"==typeof t)if("[object Object]"===t)n={};else if(t.startsWith("{")||t.startsWith("[")){const[e,r,i]=fe(()=>JSON.parse(t));e&&(n=i)}}else"string"==typeof n&&""!==n?n=P(n):"number"==typeof n||(n=void 0);if(this.attributes&&"string"==typeof o&&o.includes("array"))if(Array.isArray(n));else if("string"==typeof n&&n.trim().startsWith("[")){const[e,t,r]=fe(()=>JSON.parse(n));e&&Array.isArray(r)&&(n=r)}else n=$i.toArray(n,{separator:this.options.arraySeparator});if(this.options.hooks&&this.options.hooks.afterUnmap&&this.options.hooks.afterUnmap[r])for(const e of this.options.hooks.afterUnmap[r])"function"==typeof $i[e]&&(n=await $i[e](n,{passphrase:this.passphrase,separator:this.options.arraySeparator}));s[r]=n}await this.applyHooksActions(s,"afterUnmap");const n=I(s);for(const[t,r]of Object.entries(e))t.startsWith("$")&&(n[t]=r);return n}getAttributeDefinition(e){const t=e.split(".");let r=this.attributes;for(const e of t){if(!r)return;r=r[e]}return r}preprocessAttributesForValidation(e){const t={};for(const[r,i]of Object.entries(e))if("object"!=typeof i||null===i||Array.isArray(i))t[r]=i;else{const e=i.$$type&&i.$$type.includes("required"),s=i.$$type&&i.$$type.includes("optional"),n={type:"object",properties:this.preprocessAttributesForValidation(i),strict:!1};e||(s||this.allNestedObjectsOptional)&&(n.optional=!0),t[r]=n}return t}}var Ui=Mi;const qi=2047;var Bi=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:qi,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:async function({resource:e,data:t,mappedData:r,originalData:i}){const s=q(r),n=z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}});if(s>n)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${n} bytes, absolute limit: 2047 bytes`);return{mappedData:r,body:JSON.stringify(r)}},handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){const n=q(i),o=z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}});if(n>o)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, effective limit: ${o} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:JSON.stringify(i)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){const s=q(i),n=z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}});if(s>n)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${n} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:""}}});var Fi=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:async function({resource:e,data:t,mappedData:r,originalData:i}){const s=q(r);return s>z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}})&&e.emit("exceedsLimit",{operation:"insert",totalSize:s,limit:2047,excess:s-2047,data:i||t}),{mappedData:r,body:JSON.stringify(t)}},handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){const n=q(i);return n>z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}})&&e.emit("exceedsLimit",{operation:"update",id:t,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){const n=q(i);return n>z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}})&&e.emit("exceedsLimit",{operation:"upsert",id:t,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}}});const zi="$truncated",Vi="true",Ki=L(zi)+L(Vi);async function Hi({resource:e,data:t,mappedData:r,originalData:i}){const s=z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),n=U(r),o=Object.entries(n).sort(([,e],[,t])=>e-t),a={};let c=0,u=!1;r._v&&(a._v=r._v,c+=n._v);for(const[e,t]of o){if("_v"===e)continue;const i=r[e];if(!(c+(t+(u?0:Ki))<=s)){const t=s-c-(u?0:Ki);if(t>0){const r=Wi(i,t);a[e]=r,u=!0,c+=L(r)}else a[e]="",u=!0;break}a[e]=i,c+=t}let l=q(a)+(u?Ki:0);for(;l>s;){const e=Object.keys(a).filter(e=>"_v"!==e&&"$truncated"!==e);if(0===e.length)break;a[e[e.length-1]]="",l=q(a)+Ki,u=!0}return u&&(a[zi]=Vi),{mappedData:a,body:JSON.stringify(r)}}function Wi(e,t){if("string"==typeof e)return Gi(e,t);if("object"==typeof e&&null!==e){return Gi(JSON.stringify(e),t)}return Gi(String(e),t)}function Gi(e,t){const r=new TextEncoder;let i=r.encode(e);if(i.length<=t)return e;let s=e.length;for(;s>0;){const n=e.substring(0,s);if(i=r.encode(n),i.length<=t)return n;s--}return""}var Ji=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:Hi,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){return Hi({resource:e,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return Hi({resource:e,data:r,mappedData:i})}});const Yi="$overflow",Qi="true",Xi=L(Yi)+L(Qi);async function Zi({resource:e,data:t,mappedData:r,originalData:i}){const s=z({s3Limit:qi,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),n=U(r),o=Object.entries(n).sort(([,e],[,t])=>e-t),a={},c={};let u=0,l=!1;r._v&&(a._v=r._v,u+=n._v);let h=s;for(const[e,t]of o)"_v"!==e&&(!l&&u+t>s&&(h-=Xi,l=!0),!l&&u+t<=h?(a[e]=r[e],u+=t):(c[e]=r[e],l=!0));l&&(a[Yi]=Qi);const f=Object.keys(c).length>0;let d=f?JSON.stringify(c):"";return f||(d="{}"),{mappedData:a,body:d}}async function es({resource:e,data:t,mappedData:r}){const i={_v:r._v||String(e.version)};i._map=JSON.stringify(e.schema.map);return{mappedData:i,body:JSON.stringify(r)}}const ts={"user-managed":Fi,"enforce-limits":Bi,"truncate-data":Ji,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){let i={};if(r&&""!==r.trim()){const[e,t,s]=fe(()=>JSON.parse(r));i=e?s:{}}const s={...i,...t};return delete s.$overflow,{metadata:s,body:r}},handleInsert:Zi,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){return Zi({resource:e,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return Zi({resource:e,data:r,mappedData:i})}}),"body-only":Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){let i={};if(r&&""!==r.trim()){const[e,t,s]=fe(()=>JSON.parse(r));i=e?s:{}}return{metadata:{...i,...t},body:r}},handleInsert:es,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i}){const s={_v:i._v||String(e.version)};return s._map=JSON.stringify(e.schema.map),{mappedData:s,body:JSON.stringify(i)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return es({resource:e,data:r,mappedData:i})}})};function rs(e){const t=ts[e];if(!t)throw new Error(`Unknown behavior: ${e}. Available behaviors: ${Object.keys(ts).join(", ")}`);return t}const is=Object.keys(ts),ss="user-managed";class ns extends _e{constructor(e={}){super(),this._instanceId=Math.random().toString(36).slice(2,8);const t=function(e){const t=[];e.name?"string"!=typeof e.name?t.push("Resource 'name' must be a string"):""===e.name.trim()&&t.push("Resource 'name' cannot be empty"):t.push("Resource 'name' is required");e.client||t.push("S3 'client' is required");e.attributes?"object"!=typeof e.attributes||Array.isArray(e.attributes)?t.push("Resource 'attributes' must be an object"):0===Object.keys(e.attributes).length&&t.push("Resource 'attributes' cannot be empty"):t.push("Resource 'attributes' are required");void 0!==e.version&&"string"!=typeof e.version&&t.push("Resource 'version' must be a string");void 0!==e.behavior&&"string"!=typeof e.behavior&&t.push("Resource 'behavior' must be a string");void 0!==e.passphrase&&"string"!=typeof e.passphrase&&t.push("Resource 'passphrase' must be a string");void 0!==e.parallelism&&("number"==typeof e.parallelism&&Number.isInteger(e.parallelism)?e.parallelism<1&&t.push("Resource 'parallelism' must be greater than 0"):t.push("Resource 'parallelism' must be an integer"));void 0===e.observers||Array.isArray(e.observers)||t.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const i of r)void 0!==e[i]&&"boolean"!=typeof e[i]&&t.push(`Resource '${i}' must be a boolean`);void 0!==e.idGenerator&&("function"!=typeof e.idGenerator&&"number"!=typeof e.idGenerator?t.push("Resource 'idGenerator' must be a function or a number (size)"):"number"==typeof e.idGenerator&&e.idGenerator<=0&&t.push("Resource 'idGenerator' size must be greater than 0"));void 0!==e.idSize&&("number"==typeof e.idSize&&Number.isInteger(e.idSize)?e.idSize<=0&&t.push("Resource 'idSize' must be greater than 0"):t.push("Resource 'idSize' must be an integer"));if(void 0!==e.partitions)if("object"!=typeof e.partitions||Array.isArray(e.partitions))t.push("Resource 'partitions' must be an object");else for(const[r,i]of Object.entries(e.partitions))if("object"!=typeof i||Array.isArray(i))t.push(`Partition '${r}' must be an object`);else if(i.fields)if("object"!=typeof i.fields||Array.isArray(i.fields))t.push(`Partition '${r}.fields' must be an object`);else for(const[e,s]of Object.entries(i.fields))"string"!=typeof s&&t.push(`Partition '${r}.fields.${e}' must be a string`);else t.push(`Partition '${r}' must have a 'fields' property`);if(void 0!==e.hooks)if("object"!=typeof e.hooks||Array.isArray(e.hooks))t.push("Resource 'hooks' must be an object");else{const r=["beforeInsert","afterInsert","beforeUpdate","afterUpdate","beforeDelete","afterDelete"];for(const[i,s]of Object.entries(e.hooks))if(r.includes(i))if(Array.isArray(s))for(let e=0;e<s.length;e++){const t=s[e];if("function"==typeof t);else if("string"==typeof t)continue}else t.push(`Resource 'hooks.${i}' must be an array`);else t.push(`Invalid hook event '${i}'. Valid events: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}(e);if(!t.isValid)throw new ue(`Invalid Resource ${e.name} configuration`,{resourceName:e.name,validation:t.errors,operation:"constructor",suggestion:"Check resource config and attributes."});const{name:r,client:i,version:s="1",attributes:n={},behavior:o=ss,passphrase:a="secret",parallelism:c=10,observers:u=[],cache:l=!1,autoDecrypt:h=!0,timestamps:f=!1,partitions:d={},paranoid:p=!0,allNestedObjectsOptional:g=!0,hooks:m={},idGenerator:y,idSize:b=22,versioningEnabled:w=!1}=e;if(this.name=r,this.client=i,this.version=s,this.behavior=o,this.observers=u,this.parallelism=c,this.passphrase=a??"secret",this.versioningEnabled=w,this.idGenerator=this.configureIdGenerator(y,b),this.config={cache:l,hooks:m,paranoid:p,timestamps:f,partitions:d,autoDecrypt:h,allNestedObjectsOptional:g},this.hooks={beforeInsert:[],afterInsert:[],beforeUpdate:[],afterUpdate:[],beforeDelete:[],afterDelete:[]},this.attributes=n||{},this.map=e.map,this.applyConfiguration({map:this.map}),m)for(const[e,t]of Object.entries(m))if(Array.isArray(t)&&this.hooks[e])for(const r of t)"function"==typeof r&&this.hooks[e].push(r.bind(this));this._initMiddleware()}configureIdGenerator(r,i){return"function"==typeof r?r:"number"==typeof r&&r>0?e(t,r):"number"==typeof i&&i>0&&22!==i?e(t,i):ve}get options(){return{timestamps:this.config.timestamps,partitions:this.config.partitions||{},cache:this.config.cache,autoDecrypt:this.config.autoDecrypt,paranoid:this.config.paranoid,allNestedObjectsOptional:this.config.allNestedObjectsOptional}}export(){const e=this.schema.export();return e.behavior=this.behavior,e.timestamps=this.config.timestamps,e.partitions=this.config.partitions||{},e.paranoid=this.config.paranoid,e.allNestedObjectsOptional=this.config.allNestedObjectsOptional,e.autoDecrypt=this.config.autoDecrypt,e.cache=this.config.cache,e.hooks=this.hooks,e.map=this.map,e}applyConfiguration({map:e}={}){this.config.timestamps&&(this.attributes.createdAt||(this.attributes.createdAt="string|optional"),this.attributes.updatedAt||(this.attributes.updatedAt="string|optional"),this.config.partitions||(this.config.partitions={}),this.config.partitions.byCreatedDate||(this.config.partitions.byCreatedDate={fields:{createdAt:"date|maxlength:10"}}),this.config.partitions.byUpdatedDate||(this.config.partitions.byUpdatedDate={fields:{updatedAt:"date|maxlength:10"}})),this.setupPartitionHooks(),this.versioningEnabled&&(this.config.partitions.byVersion||(this.config.partitions.byVersion={fields:{_v:"string"}})),this.schema=new Ui({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional},map:e||this.map}),this.validatePartitions()}updateAttributes(e){const t=this.attributes;return this.attributes=e,this.applyConfiguration({map:this.schema?.map}),{oldAttributes:t,newAttributes:e}}addHook(e,t){this.hooks[e]&&this.hooks[e].push(t.bind(this))}async executeHooks(e,t){if(!this.hooks[e])return t;let r=t;for(const t of this.hooks[e])r=await t(r);return r}setupPartitionHooks(){if(!this.config.partitions)return;const e=this.config.partitions;0!==Object.keys(e).length&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async e=>(await this.createPartitionReferences(e),e)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async e=>(await this.deletePartitionReferences(e),e)))}async validate(e){const t={original:h(e),isValid:!1,errors:[]},r=await this.schema.validate(e,{mutateOriginal:!1});return!0===r?t.isValid=!0:t.errors=r,t.data=e,t}validatePartitions(){if(!this.config.partitions)return;const e=this.config.partitions;if(0===Object.keys(e).length)return;const t=Object.keys(this.attributes||{});for(const[r,i]of Object.entries(e))if(i.fields)for(const e of Object.keys(i.fields))if(!this.fieldExistsInAttributes(e))throw new le(`Partition '${r}' uses field '${e}' which does not exist in resource attributes. Available fields: ${t.join(", ")}.`,{resourceName:this.name,partitionName:r,fieldName:e,availableFields:t,operation:"validatePartitions"})}fieldExistsInAttributes(e){if(e.startsWith("_"))return!0;if(!e.includes("."))return Object.keys(this.attributes||{}).includes(e);const t=e.split(".");let r=this.attributes||{};for(const e of t){if(!r||"object"!=typeof r||!(e in r))return!1;r=r[e]}return!0}applyPartitionRule(e,t){if(null==e)return e;let r=e;if("string"==typeof t&&t.includes("maxlength:")){const e=t.match(/maxlength:(\d+)/);if(e){const t=parseInt(e[1]);"string"==typeof r&&r.length>t&&(r=r.substring(0,t))}}if(t.includes("date"))if(r instanceof Date)r=r.toISOString().split("T")[0];else if("string"==typeof r)if(r.includes("T")&&r.includes("Z"))r=r.split("T")[0];else{const e=new Date(r);isNaN(e.getTime())||(r=e.toISOString().split("T")[0])}return r}getResourceKey(e){return Ue("resource="+this.name,"data",`id=${e}`)}getPartitionKey({partitionName:e,id:t,data:r}){if(!this.config.partitions||!this.config.partitions[e])throw new le(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"getPartitionKey"});const i=this.config.partitions[e],s=[],n=Object.entries(i.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of n){const i=this.getNestedFieldValue(r,e),n=this.applyPartitionRule(i,t);if(null==n)return null;s.push(`${e}=${n}`)}if(0===s.length)return null;const o=t||r?.id;return o?Ue(`resource=${this.name}`,`partition=${e}`,...s,`id=${o}`):null}getNestedFieldValue(e,t){if(!t.includes("."))return e[t];const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return;i=i[e]}return i}calculateContentLength(e){return e?Buffer.isBuffer(e)?e.length:"string"==typeof e?Buffer.byteLength(e,"utf8"):"object"==typeof e?Buffer.byteLength(JSON.stringify(e),"utf8"):Buffer.byteLength(String(e),"utf8"):0}async insert({id:e,...t}){if(await this.exists(e))throw new Error(`Resource with id '${e}' already exists`);this.getResourceKey(e||"(auto)"),this.options.timestamps&&(t.createdAt=(new Date).toISOString(),t.updatedAt=(new Date).toISOString());const r={id:e,...this.applyDefaults(t)},i=await this.executeHooks("beforeInsert",r),s=Object.keys(i).filter(e=>!(e in r)||i[e]!==r[e]),n={};for(const e of s)n[e]=i[e];const{errors:o,isValid:a,data:c}=await this.validate(i);if(!a){const e=o&&o.length&&o[0].message?o[0].message:"Insert failed";throw new re({bucket:this.client.config.bucket,resourceName:this.name,attributes:i,validation:o,message:e})}const{id:u,...l}=c;Object.assign(l,n);const h=u||e||this.idGenerator(),f=await this.schema.mapper(l);f._v=String(this.version);const d=rs(this.behavior),{mappedData:p,body:g}=await d.handleInsert({resource:this,data:l,mappedData:f,originalData:r}),m=p,y=this.getResourceKey(h);let b;if(g&&""!==g){const[e,t]=await de(()=>Promise.resolve(JSON.parse(g)));e&&(b="application/json")}if("body-only"===this.behavior&&(!g||""===g))throw new Error(`[Resource.insert] Tentativa de gravar objeto sem body! Dados: id=${h}, resource=${this.name}`);const[w,v,O]=await de(()=>this.client.putObject({key:y,body:g,contentType:b,metadata:m}));if(!w){const e=v&&v.message?v.message:"";if(e.includes("metadata headers exceed")||e.includes("Insert failed")){const e=q(m),t=z({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=e-t;throw v.totalSize=e,v.limit=2047,v.effectiveLimit=t,v.excess=r,new ue("metadata headers exceed",{resourceName:this.name,operation:"insert",id:h,totalSize:e,effectiveLimit:t,excess:r,suggestion:"Reduce metadata size or number of fields."})}throw ne(v,{bucket:this.client.config.bucket,key:y,resourceName:this.name,operation:"insert",id:h})}let k=await this.composeFullObjectFromWrite({id:h,metadata:m,body:g,behavior:this.behavior});const S=await this.executeHooks("afterInsert",k);return this.emit("insert",{...k,$before:{...r},$after:{...S}}),S}async get(e){if(p(e))throw new Error("id cannot be an object");if(c(e))throw new Error("id cannot be empty");const t=this.getResourceKey(e),[r,i,s]=await de(()=>this.client.getObject(t));if(!r)throw ne(i,{bucket:this.client.config.bucket,key:t,resourceName:this.name,operation:"get",id:e});if(0===s.ContentLength){const r=new Error(`No such key: ${t} [bucket:${this.client.config.bucket}]`);throw r.name="NoSuchKey",ne(r,{bucket:this.client.config.bucket,key:t,resourceName:this.name,operation:"get",id:e})}const n=s.Metadata?._v||this.version,o="string"==typeof n&&n.startsWith("v")?n.slice(1):n,a=await this.getSchemaForVersion(o);let u=await a.unmapper(s.Metadata);const l=rs(this.behavior);let h="";if(s.ContentLength>0){const[e,r,i]=await de(()=>this.client.getObject(t));h=e?await vi(i.Body):""}const{metadata:f}=await l.handleGet({resource:this,metadata:u,body:h});let d=await this.composeFullObjectFromWrite({id:e,metadata:f,body:h,behavior:this.behavior});d._contentLength=s.ContentLength,d._lastModified=s.LastModified,d._hasContent=s.ContentLength>0,d._mimeType=s.ContentType||null,d._v=o,s.VersionId&&(d._versionId=s.VersionId),s.Expiration&&(d._expiresAt=s.Expiration),d._definitionHash=this.getDefinitionHash(),o!==this.version&&(d=await this.applyVersionMapping(d,o,this.version)),this.emit("get",d);return d}async exists(e){const t=this.getResourceKey(e),[r,i]=await de(()=>this.client.headObject(t));return r}async update(e,t){if(c(e))throw new Error("id cannot be empty");if(!await this.exists(e))throw new Error(`Resource with id '${e}' does not exist`);const r=await this.get(e),i=h(t);let s=h(r);for(const[e,t]of Object.entries(i))if(e.includes(".")){let r=s;const i=e.split(".");for(let e=0;e<i.length-1;e++)"object"==typeof r[i[e]]&&null!==r[i[e]]||(r[i[e]]={}),r=r[i[e]];r[i[i.length-1]]=h(t)}else"object"!=typeof t||null===t||Array.isArray(t)?s[e]=h(t):s[e]=o({},s[e],t);if(this.config.timestamps){const e=(new Date).toISOString();s.updatedAt=e,s.metadata||(s.metadata={}),s.metadata.updatedAt=e}const n=await this.executeHooks("beforeUpdate",h(s)),a={...r,...n,id:e},{isValid:u,errors:l,data:f}=await this.validate(h(a));if(!u)throw new re({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:l,message:"validation: "+(l&&l.length?JSON.stringify(l):"unknown")});await this.schema.mapper(f);const d=rs(this.behavior),p=await this.schema.mapper({...r,...n});p._v=String(this.version),await d.handleUpdate({resource:this,id:e,data:{...r,...n},mappedData:p,originalData:{...i,id:e}});const{id:g,...m}=f,y={...r,id:e},b={...m,id:e};await this.handlePartitionReferenceUpdates(y,b);const w=await this.schema.mapper(m);w._v=String(this.version);const v=rs(this.behavior),{mappedData:O,body:k}=await v.handleUpdate({resource:this,id:e,data:m,mappedData:w,originalData:{...i,id:e}}),S=O,_=this.getResourceKey(e);let R,j=k;if(""===k&&"body-overflow"!==this.behavior){const[e,t,r]=await de(()=>this.client.getObject(_));if(e&&r.ContentLength>0){const e=Buffer.from(await r.Body.transformToByteArray()),t=e.toString(),[i,s]=await de(()=>Promise.resolve(JSON.parse(t)));i||(j=e,R=r.ContentType)}}let N=R;if(j&&""!==j&&!N){const[e,t]=await de(()=>Promise.resolve(JSON.parse(j)));e&&(N="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(e,r);const[I,E]=await de(()=>this.client.putObject({key:_,body:j,contentType:N,metadata:S}));if(!I&&E&&E.message&&E.message.includes("metadata headers exceed")){const t=q(S),r=z({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:e}}),i=t-r;throw E.totalSize=t,E.limit=2047,E.effectiveLimit=r,E.excess=i,this.emit("exceedsLimit",{operation:"update",totalSize:t,limit:2047,effectiveLimit:r,excess:i,data:m}),new ue("metadata headers exceed",{resourceName:this.name,operation:"update",id:e,totalSize:t,effectiveLimit:r,excess:i,suggestion:"Reduce metadata size or number of fields."})}if(!I)throw ne(E,{bucket:this.client.config.bucket,key:_,resourceName:this.name,operation:"update",id:e});const A=await this.composeFullObjectFromWrite({id:e,metadata:S,body:j,behavior:this.behavior}),D=await this.executeHooks("afterUpdate",A);return this.emit("update",{...A,$before:{...r},$after:{...D}}),D}async delete(e){if(c(e))throw new Error("id cannot be empty");let t,r=null;const[i,s,n]=await de(()=>this.get(e));i?t=n:(t={id:e},r=s),await this.executeHooks("beforeDelete",t);const o=this.getResourceKey(e),[a,u,l]=await de(()=>this.client.deleteObject(o));if(this.emit("delete",{...t,$before:{...t},$after:null}),r)throw ne(r,{bucket:this.client.config.bucket,key:o,resourceName:this.name,operation:"delete",id:e});if(!a)throw ne(u,{key:o,resourceName:this.name,operation:"delete",id:e});return await this.executeHooks("afterDelete",t),l}async upsert({id:e,...t}){return await this.exists(e)?this.update(e,t):this.insert({id:e,...t})}async count({partition:e=null,partitionValues:t={}}={}){let r;if(e&&Object.keys(t).length>0){const i=this.config.partitions[e];if(!i)throw new le(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"count"});const s=[],n=Object.entries(i.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,r]of n){const i=t[e];if(null!=i){const t=this.applyPartitionRule(i,r);s.push(`${e}=${t}`)}}r=s.length>0?`resource=${this.name}/partition=${e}/${s.join("/")}`:`resource=${this.name}/partition=${e}`}else r=`resource=${this.name}/data`;const i=await this.client.count({prefix:r});return this.emit("count",i),i}async insertMany(e){const{results:t}=await i.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,t),this.observers.map(r=>r.emit("error",this.name,e,t))}).process(async e=>await this.insert(e));return this.emit("insertMany",e.length),t}async deleteMany(e){const t=n(e.map(e=>this.getResourceKey(e)),1e3);e.map(e=>this.getResourceKey(e));const{results:r}=await i.for(t).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,t),this.observers.map(r=>r.emit("error",this.name,e,t))}).process(async e=>{const t=await this.client.deleteObjects(e);return e.forEach(e=>{const t=e.split("/").find(e=>e.startsWith("id=")),r=t?t.replace("id=",""):null;r&&(this.emit("deleted",r),this.observers.map(e=>e.emit("deleted",this.name,r)))}),t});return this.emit("deleteMany",e.length),r}async deleteAll(){if(!1!==this.config.paranoid)throw new ue("deleteAll() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAll",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAll."});const e=`resource=${this.name}/data`,t=await this.client.deleteAll({prefix:e});return this.emit("deleteAll",{version:this.version,prefix:e,deletedCount:t}),{deletedCount:t,version:this.version}}async deleteAllData(){if(!1!==this.config.paranoid)throw new ue("deleteAllData() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAllData",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAllData."});const e=`resource=${this.name}`,t=await this.client.deleteAll({prefix:e});return this.emit("deleteAllData",{resource:this.name,prefix:e,deletedCount:t}),{deletedCount:t,resource:this.name}}async listIds({partition:e=null,partitionValues:t={},limit:r,offset:i=0}={}){let s;if(e&&Object.keys(t).length>0){if(!this.config.partitions||!this.config.partitions[e])throw new le(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"listIds"});const r=this.config.partitions[e],i=[],n=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,r]of n){const s=t[e];if(null!=s){const t=this.applyPartitionRule(s,r);i.push(`${e}=${t}`)}}s=i.length>0?`resource=${this.name}/partition=${e}/${i.join("/")}`:`resource=${this.name}/partition=${e}`}else s=`resource=${this.name}/data`;const n=(await this.client.getKeysPage({prefix:s,offset:i,amount:r||1e3})).map(e=>{const t=e.split("/").find(e=>e.startsWith("id="));return t?t.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",n.length),n}async list({partition:e=null,partitionValues:t={},limit:r,offset:i=0}={}){const[s,n,o]=await de(async()=>e?await this.listPartition({partition:e,partitionValues:t,limit:r,offset:i}):await this.listMain({limit:r,offset:i}));return s?o:this.handleListError(n,{partition:e,partitionValues:t})}async listMain({limit:e,offset:t=0}){const[r,i,s]=await de(()=>this.listIds({limit:e,offset:t}));if(!r)throw i;const n=await this.processListResults(s,"main");return this.emit("list",{count:n.length,errors:0}),n}async listPartition({partition:e,partitionValues:t,limit:r,offset:i=0}){if(!this.config.partitions?.[e])return this.emit("list",{partition:e,partitionValues:t,count:0,errors:0}),[];const s=this.config.partitions[e],n=this.buildPartitionPrefix(e,s,t),[o,a,c]=await de(()=>this.client.getAllKeys({prefix:n}));if(!o)throw a;const u=this.extractIdsFromKeys(c).slice(i),l=r?u.slice(0,r):u,h=await this.processPartitionResults(l,e,s,c);return this.emit("list",{partition:e,partitionValues:t,count:h.length,errors:0}),h}buildPartitionPrefix(e,t,r){const i=[],s=Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of s){const s=r[e];if(null!=s){const r=this.applyPartitionRule(s,t);i.push(`${e}=${r}`)}}return i.length>0?`resource=${this.name}/partition=${e}/${i.join("/")}`:`resource=${this.name}/partition=${e}`}extractIdsFromKeys(e){return e.map(e=>{const t=e.split("/").find(e=>e.startsWith("id="));return t?t.replace("id=",""):null}).filter(Boolean)}async processListResults(e,t="main"){const{results:r,errors:s}=await i.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content))}).process(async e=>{const[r,i,s]=await de(()=>this.get(e));return r?s:this.handleResourceError(i,e,t)});return this.emit("list",{count:r.length,errors:0}),r}async processPartitionResults(e,t,r,s){const n=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t)),{results:o,errors:a}=await i.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content))}).process(async e=>{const[r,i,o]=await de(async()=>{const r=this.extractPartitionValuesFromKey(e,s,n);return await this.getFromPartition({id:e,partitionName:t,partitionValues:r})});return r?o:this.handleResourceError(i,e,"partition")});return o.filter(e=>null!==e)}extractPartitionValuesFromKey(e,t,r){const i=t.find(t=>t.includes(`id=${e}`));if(!i)throw new le(`Partition key not found for ID ${e}`,{resourceName:this.name,id:e,operation:"extractPartitionValuesFromKey"});const s=i.split("/"),n={};for(const[e]of r){const t=s.find(t=>t.startsWith(`${e}=`));if(t){const r=t.replace(`${e}=`,"");n[e]=r}}return n}handleResourceError(e,t,r){if(e.message.includes("Cipher job failed")||e.message.includes("OperationError"))return{id:t,_decryptionFailed:!0,_error:e.message,..."partition"===r&&{_partition:r}};throw e}handleListError(e,{partition:t,partitionValues:r}){return e.message.includes("Partition '")&&e.message.includes("' not found"),this.emit("list",{partition:t,partitionValues:r,count:0,errors:1}),[]}async getMany(e){const{results:t,errors:r}=await i.for(e).withConcurrency(this.client.parallelism).handleError(async(e,t)=>(this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content)),{id:t,_error:e.message,_decryptionFailed:e.message.includes("Cipher job failed")||e.message.includes("OperationError")})).process(async e=>{const[t,r,i]=await de(()=>this.get(e));if(t)return i;if(r.message.includes("Cipher job failed")||r.message.includes("OperationError"))return{id:e,_decryptionFailed:!0,_error:r.message};throw r});return this.emit("getMany",e.length),t}async getAll(){const[e,t,r]=await de(()=>this.listIds());if(!e)throw t;const i=[];for(const e of r){const[t,r,s]=await de(()=>this.get(e));t&&i.push(s)}return i}async page({offset:e=0,size:t=100,partition:r=null,partitionValues:i={},skipCount:s=!1}={}){const[n,o,a]=await de(async()=>{let n=null,o=null;if(!s){const[e,s,a]=await de(()=>this.count({partition:r,partitionValues:i}));e?(n=a,o=Math.ceil(n/t)):(n=null,o=null)}const a=Math.floor(e/t);let c=[];if(t<=0)c=[];else{const[s,n,o]=await de(()=>this.list({partition:r,partitionValues:i,limit:t,offset:e}));c=s?o:[]}const u={items:c,totalItems:n,page:a,pageSize:t,totalPages:o,hasMore:c.length===t&&e+t<(n||1/0),_debug:{requestedSize:t,requestedOffset:e,actualItemsReturned:c.length,skipCount:s,hasTotalItems:null!==n}};return this.emit("page",u),u});return n?a:{items:[],totalItems:null,page:Math.floor(e/t),pageSize:t,totalPages:null,_debug:{requestedSize:t,requestedOffset:e,actualItemsReturned:0,skipCount:s,hasTotalItems:!1,error:o.message}}}readable(){return new bi({resource:this}).build()}writable(){return new wi({resource:this}).build()}async setContent({id:e,buffer:t,contentType:r="application/octet-stream"}){const[i,s,n]=await de(()=>this.get(e));if(!i||!n)throw new ue(`Resource with id '${e}' not found`,{resourceName:this.name,id:e,operation:"setContent"});const o={...n,_hasContent:!0,_contentLength:t.length,_mimeType:r},a=await this.schema.mapper(o),[c,u]=await de(()=>this.client.putObject({key:this.getResourceKey(e),metadata:a,body:t,contentType:r}));if(!c)throw u;return this.emit("setContent",{id:e,contentType:r,contentLength:t.length}),o}async content(e){const t=this.getResourceKey(e),[r,i,s]=await de(()=>this.client.getObject(t));if(!r){if("NoSuchKey"===i.name)return{buffer:null,contentType:null};throw i}const n=Buffer.from(await s.Body.transformToByteArray()),o=s.ContentType||null;return this.emit("content",e,n.length,o),{buffer:n,contentType:o}}async hasContent(e){const t=this.getResourceKey(e),[r,i,s]=await de(()=>this.client.headObject(t));return!!r&&s.ContentLength>0}async deleteContent(e){const t=this.getResourceKey(e),[r,i,s]=await de(()=>this.client.headObject(t));if(!r)throw i;const n=s.Metadata||{},[o,a,c]=await de(()=>this.client.putObject({key:t,body:"",metadata:n}));if(!o)throw a;return this.emit("deleteContent",e),c}getDefinitionHash(){const e={attributes:this.attributes,behavior:this.behavior},t=b(e);return`sha256:${y("sha256").update(t).digest("hex")}`}extractVersionFromKey(e){const t=e.split("/").find(e=>e.startsWith("v="));return t?t.replace("v=",""):null}async getSchemaForVersion(e){if(e===this.version)return this.schema;const[t,r,i]=await de(()=>Promise.resolve(new Ui({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:e,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})));return t?i:this.schema}async createPartitionReferences(e){const t=this.config.partitions;if(t&&0!==Object.keys(t).length)for(const[r,i]of Object.entries(t)){const t=this.getPartitionKey({partitionName:r,id:e.id,data:e});if(t){const e={_v:String(this.version)};await this.client.putObject({key:t,metadata:e,body:"",contentType:void 0})}}}async deletePartitionReferences(e){const t=this.config.partitions;if(!t||0===Object.keys(t).length)return;const r=[];for(const[i,s]of Object.entries(t)){const t=this.getPartitionKey({partitionName:i,id:e.id,data:e});t&&r.push(t)}if(r.length>0){const[e,t]=await de(()=>this.client.deleteObjects(r))}}async query(e={},{limit:t=100,offset:r=0,partition:i=null,partitionValues:s={}}={}){if(0===Object.keys(e).length)return await this.list({partition:i,partitionValues:s,limit:t,offset:r});const n=[];let o=r;const a=Math.min(t,50);for(;n.length<t;){const t=await this.list({partition:i,partitionValues:s,limit:a,offset:o});if(0===t.length)break;const r=t.filter(t=>Object.entries(e).every(([e,r])=>t[e]===r));if(n.push(...r),o+=a,t.length<a)break}return n.slice(0,t)}async handlePartitionReferenceUpdates(e,t){const r=this.config.partitions;if(!r||0===Object.keys(r).length)return;for(const[i,s]of Object.entries(r)){const[r,n]=await de(()=>this.handlePartitionReferenceUpdate(i,s,e,t))}const i=t.id||e.id;for(const[e,s]of Object.entries(r)){const r=`resource=${this.name}/partition=${e}`;let s=[];const[n,o,a]=await de(()=>this.client.getAllKeys({prefix:r}));if(!n)continue;s=a;const c=this.getPartitionKey({partitionName:e,id:i,data:t});for(const e of s)if(e.endsWith(`/id=${i}`)&&e!==c){const[t,r]=await de(()=>this.client.deleteObject(e))}}}async handlePartitionReferenceUpdate(e,t,r,i){const s=i.id||r.id,n=this.getPartitionKey({partitionName:e,id:s,data:r}),o=this.getPartitionKey({partitionName:e,id:s,data:i});if(n!==o){if(n){const[e,t]=await de(async()=>{await this.client.deleteObject(n)})}if(o){const[e,t]=await de(async()=>{const e={_v:String(this.version)};await this.client.putObject({key:o,metadata:e,body:"",contentType:void 0})})}}else if(o){const[e,t]=await de(async()=>{const e={_v:String(this.version)};await this.client.putObject({key:o,metadata:e,body:"",contentType:void 0})})}}async updatePartitionReferences(e){const t=this.config.partitions;if(t&&0!==Object.keys(t).length)for(const[r,i]of Object.entries(t)){if(!i||!i.fields||"object"!=typeof i.fields)continue;const t=this.getPartitionKey({partitionName:r,id:e.id,data:e});if(t){const e={_v:String(this.version)},[r,i]=await de(async()=>{await this.client.putObject({key:t,metadata:e,body:"",contentType:void 0})})}}}async getFromPartition({id:e,partitionName:t,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[t])throw new le(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"getFromPartition"});const i=this.config.partitions[t],s=[],n=Object.entries(i.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of n){const i=r[e];if(null!=i){const r=this.applyPartitionRule(i,t);s.push(`${e}=${r}`)}}if(0===s.length)throw new le(`No partition values provided for partition '${t}'`,{resourceName:this.name,partitionName:t,operation:"getFromPartition"});const o=Ue(`resource=${this.name}`,`partition=${t}`,...s,`id=${e}`),[a,c]=await de(async()=>{await this.client.headObject(o)});if(!a)throw new ue(`Resource with id '${e}' not found in partition '${t}'`,{resourceName:this.name,id:e,partitionName:t,operation:"getFromPartition"});const u=await this.get(e);return u._partition=t,u._partitionValues=r,this.emit("getFromPartition",u),u}async createHistoricalVersion(e,t){const r=Ue(`resource=${this.name}`,"historical",`id=${e}`),i={...t,_v:t._v||this.version,_historicalTimestamp:(new Date).toISOString()},s=await this.schema.mapper(i),n=rs(this.behavior),{mappedData:o,body:a}=await n.handleInsert({resource:this,data:i,mappedData:s}),c={...o,_v:t._v||this.version,_historicalTimestamp:i._historicalTimestamp};let u;if(a&&""!==a){const[e,t]=await de(()=>Promise.resolve(JSON.parse(a)));e&&(u="application/json")}await this.client.putObject({key:r,metadata:c,body:a,contentType:u})}async applyVersionMapping(e,t,r){if(t===r)return e;return{...e,_v:r,_originalVersion:t,_versionMapped:!0}}async composeFullObjectFromWrite({id:e,metadata:t,body:r,behavior:i}){const s={};t&&"true"===t.$truncated&&(s.$truncated="true"),t&&"true"===t.$overflow&&(s.$overflow="true");let n={};const[o,a,c]=await de(()=>this.schema.unmapper(t));n=o?c:t;const u=e=>{if(!e||"object"!=typeof e)return e;const t={};for(const[r,i]of Object.entries(e))r.startsWith("_")||(t[r]=i);return t},l=e=>{if("object"==typeof e&&null!==e)return e;if("string"==typeof e){if("[object Object]"===e)return{};if(e.startsWith("{")||e.startsWith("[")){const[t,r,i]=fe(()=>JSON.parse(e));return t?i:e}return e}return e};if("body-overflow"===i){const i=t&&"true"===t.$overflow;let s={};if(i&&r){const[e,t,i]=await de(()=>Promise.resolve(JSON.parse(r)));if(e){const[e,t,r]=await de(()=>this.schema.unmapper(i));s=e?r:{}}}const o={...n,...s,id:e};Object.keys(o).forEach(e=>{o[e]=l(o[e])});const a=u(o);return i&&(a.$overflow="true"),a}if("body-only"===i){const[i,s,n]=await de(()=>Promise.resolve(r?JSON.parse(r):{}));let o=this.schema.map;if(t&&t._map){const[e,r,i]=await de(()=>Promise.resolve("string"==typeof t._map?JSON.parse(t._map):t._map));o=e?i:this.schema.map}const[a,c,u]=await de(()=>this.schema.unmapper(n,o)),h=a?{...u,id:e}:{id:e};return Object.keys(h).forEach(e=>{h[e]=l(h[e])}),h}const h={...n,id:e};Object.keys(h).forEach(e=>{h[e]=l(h[e])});const f=u(h);return s.$truncated&&(f.$truncated=s.$truncated),s.$overflow&&(f.$overflow=s.$overflow),f}emit(e,...t){return super.emit(e,...t)}async replace(e,t){await this.delete(e),await new Promise(e=>setTimeout(e,100));const r=Date.now();for(;Date.now()-r<5e3;){if(!await this.exists(e))break;await new Promise(e=>setTimeout(e,50))}try{return await this.insert({...t,id:e})}catch(r){if(r&&r.message&&r.message.includes("already exists")){return await this.update(e,t)}throw r}}_initMiddleware(){this._middlewares=new Map,this._middlewareMethods=["get","list","listIds","getAll","count","page","insert","update","delete","deleteMany","exists","getMany"];for(const e of this._middlewareMethods)this._middlewares.set(e,[]),this[`_original_${e}`]||(this[`_original_${e}`]=this[e].bind(this),this[e]=async(...t)=>{const r={resource:this,args:t,method:e};let i=-1;const s=this._middlewares.get(e),n=async t=>{if(t<=i)throw new Error("next() called multiple times");return i=t,t<s.length?await s[t](r,()=>n(t+1)):await this[`_original_${e}`](...r.args)};return await n(0)})}useMiddleware(e,t){if(this._middlewares||this._initMiddleware(),!this._middlewares.has(e))throw new ue(`No such method for middleware: ${e}`,{operation:"useMiddleware",method:e});this._middlewares.get(e).push(t)}applyDefaults(e){const t={...e};for(const[e,r]of Object.entries(this.attributes))if(void 0===t[e]&&"string"==typeof r&&r.includes("default:")){const i=r.match(/default:([^|]+)/);if(i){let s=i[1];r.includes("boolean")?s="true"===s:r.includes("number")&&(s=Number(s)),t[e]=s}}return t}}var os=ns;class as extends _e{constructor(e){super(),this.version="1",this.s3dbVersion=(()=>{const[e,t,r]=de(()=>"7.2.0");return e?r:"latest"})(),this.resources={},this.savedMetadata=null,this.options=e,this.verbose=e.verbose||!1,this.parallelism=parseInt(e.parallelism+"")||10,this.plugins=e.plugins||[],this.pluginList=e.plugins||[],this.cache=e.cache,this.passphrase=e.passphrase||"secret",this.versioningEnabled=e.versioningEnabled||!1;let t=e.connectionString;if(!t&&(e.bucket||e.accessKeyId||e.secretAccessKey)){const{bucket:r,region:i,accessKeyId:s,secretAccessKey:n,endpoint:o,forcePathStyle:a}=e;if(o){const e=new URL(o);s&&(e.username=encodeURIComponent(s)),n&&(e.password=encodeURIComponent(n)),e.pathname=`/${r||"s3db"}`,a&&e.searchParams.set("forcePathStyle","true"),t=e.toString()}else if(s&&n){const e=new URLSearchParams;e.set("region",i||"us-east-1"),a&&e.set("forcePathStyle","true"),t=`s3://${encodeURIComponent(s)}:${encodeURIComponent(n)}@${r||"s3db"}?${e.toString()}`}}this.client=e.client||new xi({verbose:this.verbose,parallelism:this.parallelism,connectionString:t}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix,this._exitListenerRegistered||(this._exitListenerRegistered=!0,process.on("exit",async()=>{if(this.isConnected())try{await this.disconnect()}catch(e){}}))}async connect(){await this.startPlugins();let e=null;if(await this.client.exists("s3db.json")){const t=await this.client.getObject("s3db.json");e=JSON.parse(await vi(t?.Body))}else e=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=e;const t=this.detectDefinitionChanges(e);for(const[t,r]of Object.entries(e.resources||{})){const e=r.currentVersion||"v0",i=r.versions?.[e];i&&(this.resources[t]=new os({name:t,client:this.client,database:this,version:e,attributes:i.attributes,behavior:i.behavior||"user-managed",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:void 0!==i.timestamps&&i.timestamps,partitions:r.partitions||i.partitions||{},paranoid:void 0===i.paranoid||i.paranoid,allNestedObjectsOptional:void 0===i.allNestedObjectsOptional||i.allNestedObjectsOptional,autoDecrypt:void 0===i.autoDecrypt||i.autoDecrypt,hooks:i.hooks||{},versioningEnabled:this.versioningEnabled,map:i.map}))}t.length>0&&this.emit("resourceDefinitionsChanged",{changes:t,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(e){const t=[];for(const[r,i]of Object.entries(this.resources)){const s=this.generateDefinitionHash(i.export()),n=e.resources?.[r];if(n){const e=n.currentVersion||"v0",i=n.versions?.[e],o=i?.hash;o!==s&&t.push({type:"changed",resourceName:r,currentHash:s,savedHash:o,fromVersion:e,toVersion:this.getNextVersion(n.versions)})}else t.push({type:"new",resourceName:r,currentHash:s,savedHash:null})}for(const[r,i]of Object.entries(e.resources||{}))if(!this.resources[r]){const e=i.currentVersion||"v0",s=i.versions?.[e];t.push({type:"deleted",resourceName:r,currentHash:null,savedHash:s?.hash,deletedVersion:e})}return t}generateDefinitionHash(e,t=void 0){const r={...e.attributes};e.timestamps&&(delete r.createdAt,delete r.updatedAt);const i={attributes:r,behavior:t||e.behavior||"user-managed",partitions:e.partitions||{}},s=b(i);return`sha256:${y("sha256").update(s).digest("hex")}`}getNextVersion(e={}){const t=Object.keys(e).filter(e=>e.startsWith("v")).map(e=>parseInt(e.substring(1))).filter(e=>!isNaN(e));return`v${(t.length>0?Math.max(...t):-1)+1}`}async startPlugins(){const e=this;if(!c(this.pluginList)){const t=this.pluginList.map(e=>g(e)?new e(this):e),r=t.map(async t=>{t.beforeSetup&&await t.beforeSetup(),await t.setup(e),t.afterSetup&&await t.afterSetup()});await Promise.all(r);const i=t.map(async e=>{e.beforeStart&&await e.beforeStart(),await e.start(),e.afterStart&&await e.afterStart()});await Promise.all(i)}}async usePlugin(e,t=null){const r=t||e.constructor.name.replace("Plugin","").toLowerCase();return this.plugins[r]=e,this.isConnected()&&(await e.setup(this),await e.start()),e}async uploadMetadataFile(){const e={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:(new Date).toISOString(),resources:{}};Object.entries(this.resources).forEach(([t,r])=>{const i=r.export(),s=this.generateDefinitionHash(i),n=this.savedMetadata?.resources?.[t],o=n?.currentVersion||"v0",a=n?.versions?.[o];let c,u;a&&a.hash===s?(c=o,u=!1):(c=this.getNextVersion(n?.versions),u=!0),e.resources[t]={currentVersion:c,partitions:r.config.partitions||{},versions:{...n?.versions,[c]:{hash:s,attributes:i.attributes,behavior:i.behavior||"user-managed",timestamps:r.config.timestamps,partitions:r.config.partitions,paranoid:r.config.paranoid,allNestedObjectsOptional:r.config.allNestedObjectsOptional,autoDecrypt:r.config.autoDecrypt,cache:r.config.cache,hooks:r.config.hooks,createdAt:u?(new Date).toISOString():a?.createdAt}}},r.version!==c&&(r.version=c,r.emit("versionUpdated",{oldVersion:o,newVersion:c}))}),await this.client.putObject({key:"s3db.json",body:JSON.stringify(e,null,2),contentType:"application/json"}),this.savedMetadata=e,this.emit("metadataUploaded",e)}blankMetadataStructure(){return{version:"1",s3dbVersion:this.s3dbVersion,resources:{}}}resourceExists(e){return!!this.resources[e]}resourceExistsWithSameHash({name:e,attributes:t,behavior:r="user-managed",partitions:i={},options:s={}}){if(!this.resources[e])return{exists:!1,sameHash:!1,hash:null};const n=this.resources[e],o=this.generateDefinitionHash(n.export()),a=new os({name:e,attributes:t,behavior:r,partitions:i,client:this.client,version:n.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...s}),c=this.generateDefinitionHash(a.export());return{exists:!0,sameHash:o===c,hash:c,existingHash:o}}async createResource({name:e,attributes:t,behavior:r="user-managed",hooks:i,...s}){if(this.resources[e]){const n=this.resources[e];if(Object.assign(n.config,{cache:this.cache,...s}),r&&(n.behavior=r),n.versioningEnabled=this.versioningEnabled,n.updateAttributes(t),i)for(const[e,t]of Object.entries(i))if(Array.isArray(t)&&n.hooks[e])for(const r of t)"function"==typeof r&&n.hooks[e].push(r.bind(n));const o=this.generateDefinitionHash(n.export(),n.behavior),a=this.savedMetadata?.resources?.[e],c=a?.currentVersion||"v0",u=a?.versions?.[c];return u&&u.hash===o||await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",e),n}const n=this.savedMetadata?.resources?.[e],o=n?.currentVersion||"v0",a=new os({name:e,client:this.client,version:void 0!==s.version?s.version:o,attributes:t,behavior:r,parallelism:this.parallelism,passphrase:void 0!==s.passphrase?s.passphrase:this.passphrase,observers:[this],cache:void 0!==s.cache?s.cache:this.cache,timestamps:void 0!==s.timestamps&&s.timestamps,partitions:s.partitions||{},paranoid:void 0===s.paranoid||s.paranoid,allNestedObjectsOptional:void 0===s.allNestedObjectsOptional||s.allNestedObjectsOptional,autoDecrypt:void 0===s.autoDecrypt||s.autoDecrypt,hooks:i||{},versioningEnabled:this.versioningEnabled,map:s.map,idGenerator:s.idGenerator,idSize:s.idSize});return a.database=this,this.resources[e]=a,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",e),a}resource(e){return this.resources[e]?this.resources[e]:Promise.reject(`resource ${e} does not exist`)}async listResources(){return Object.keys(this.resources).map(e=>({name:e}))}async getResource(e){if(!this.resources[e])throw new Q({bucket:this.client.config.bucket,resourceName:e,id:e});return this.resources[e]}get config(){return{version:this.version,s3dbVersion:this.s3dbVersion,bucket:this.bucket,keyPrefix:this.keyPrefix,parallelism:this.parallelism,verbose:this.verbose}}isConnected(){return!!this.savedMetadata}async disconnect(){try{if(this.pluginList&&this.pluginList.length>0){for(const e of this.pluginList)e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners();const e=this.pluginList.map(async e=>{try{e&&"function"==typeof e.stop&&await e.stop()}catch(e){}});await Promise.all(e)}if(this.resources&&Object.keys(this.resources).length>0){for(const[e,t]of Object.entries(this.resources))try{t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners(),t._pluginWrappers&&t._pluginWrappers.clear(),t._pluginMiddlewares&&(t._pluginMiddlewares={}),t.observers&&Array.isArray(t.observers)&&(t.observers=[])}catch(e){}Object.keys(this.resources).forEach(e=>delete this.resources[e])}this.client&&"function"==typeof this.client.removeAllListeners&&this.client.removeAllListeners(),this.removeAllListeners(),this.savedMetadata=null,this.plugins={},this.pluginList=[],this.emit("disconnected",new Date)}catch(e){}}}class cs extends as{}function us(e){return"string"==typeof e?e.trim().toLowerCase():e}var ls=class extends Ni{constructor(e={},t=[],r=null){super(e),this.instanceId=Math.random().toString(36).slice(2,10),this.client=r,this.connectionString=e.connectionString;let i=t;if(t)if(Array.isArray(t)){i={};for(const e of t)"string"==typeof e&&(i[us(e)]=e)}else"string"==typeof t&&(i[us(t)]=t);else i={};this.resourcesMap=this._normalizeResources(i)}_normalizeResources(e){if(!e)return{};if(Array.isArray(e)){const t={};for(const r of e)"string"==typeof r?t[us(r)]=r:Array.isArray(r)&&"string"==typeof r[0]?t[us(r[0])]=r:"object"==typeof r&&r.resource&&(t[us(r.resource)]={...r});return t}if("object"==typeof e){const t={};for(const[r,i]of Object.entries(e)){const e=us(r);"string"==typeof i?t[e]=i:Array.isArray(i)?t[e]=i.map(e=>"string"==typeof e||"function"==typeof e?e:"object"==typeof e&&e.resource?{...e}:e):"function"==typeof i?t[e]=i:"object"==typeof i&&i.resource&&(t[e]={...i})}return t}if("function"==typeof e)return e;if("string"==typeof e){return{[us(e)]:e}}return{}}validateConfig(){const e=[];return this.client||this.connectionString||e.push("You must provide a client or a connectionString"),(!this.resourcesMap||"object"==typeof this.resourcesMap&&0===Object.keys(this.resourcesMap).length)&&e.push("You must provide a resources map or array"),{isValid:0===e.length,errors:e}}async initialize(e){try{if(await super.initialize(e),this.client)this.targetDatabase=this.client;else{if(!this.connectionString)throw new Error("S3dbReplicator: No client or connectionString provided");{const e={connectionString:this.connectionString,region:this.region,keyPrefix:this.keyPrefix,verbose:this.config.verbose||!1};this.targetDatabase=new cs(e),await this.targetDatabase.connect()}}this.emit("connected",{replicator:this.name,target:this.connectionString||"client-provided"})}catch(e){throw e}}async replicate({resource:e,operation:t,data:r,id:i}){const s=us(e),n=this._resolveDestResource(s,r),o=this._getDestResourceObj(n),a=this._applyTransformer(s,r);let c;if("insert"===t)c=await o.insert(a);else if("update"===t)c=await o.update(i,a);else{if("delete"!==t)throw new Error(`Invalid operation: ${t}. Supported operations are: insert, update, delete`);c=await o.delete(i)}return c}_applyTransformer(e,t){const r=us(e),i=this.resourcesMap[r];let s;return i?(Array.isArray(i)&&"function"==typeof i[1]?s=i[1](t):"function"==typeof i?s=i(t):"object"==typeof i?"function"==typeof i.transform?s=i.transform(t):"function"==typeof i.transformer&&(s=i.transformer(t)):s=t,s&&t&&t.id&&!s.id&&(s.id=t.id),!s&&t&&(s=t),s):t}_resolveDestResource(e,t){const r=us(e),i=this.resourcesMap[r];if(!i)return e;if(Array.isArray(i)){if("string"==typeof i[0])return i[0];if("object"==typeof i[0]&&i[0].resource)return i[0].resource;if("function"==typeof i[0])return e}return"string"==typeof i?i:"function"==typeof i?e:"object"==typeof i&&i.resource?i.resource:e}_getDestResourceObj(e){if(!this.client||!this.client.resources)return null;const t=Object.keys(this.client.resources),r=us(e),i=t.find(e=>us(e)===r);if(!i)throw new Error(`[S3dbReplicator] Destination resource not found: ${e}. Available: ${t.join(", ")}`);return this.client.resources[i]}async replicateBatch(e,t){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const r=[],i=[];for(const s of t){const[t,n,o]=await de(()=>this.replicate({resource:e,operation:s.operation,id:s.id,data:s.data,beforeData:s.beforeData}));t?r.push(o):i.push({id:s.id,error:n.message})}return this.emit("batch_replicated",{replicator:this.name,resourceName:e,total:t.length,successful:r.length,errors:i.length}),{success:0===i.length,results:r,errors:i,total:t.length}}async testConnection(){const[e,t]=await de(async()=>(this.targetDatabase||await this.initialize(this.database),await this.targetDatabase.listResources(),!0));return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.targetDatabase,targetDatabase:this.connectionString||"client-provided",resources:Object.keys(this.resourcesMap||{}),totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.targetDatabase&&this.targetDatabase.removeAllListeners(),await super.cleanup()}shouldReplicateResource(e,t){const r=us(e),i=this.resourcesMap[r];if(!i)return!1;if(!t)return!0;if(Array.isArray(i)){for(const e of i)if("object"==typeof e&&e.resource){if(!e.actions||!Array.isArray(e.actions))return!0;if(e.actions.includes(t))return!0}else if("string"==typeof e||"function"==typeof e)return!0;return!1}return"object"==typeof i&&i.resource?!i.actions||!Array.isArray(i.actions)||i.actions.includes(t):"string"==typeof i||"function"==typeof i}};const hs={s3db:ls,sqs:class extends Ni{constructor(e={},t=[],r=null){if(super(e),this.resources=t,this.client=r,this.queueUrl=e.queueUrl,this.queues=e.queues||{},this.defaultQueue=e.defaultQueue||e.defaultQueueUrl||e.queueUrlDefault,this.region=e.region||"us-east-1",this.sqsClient=r||null,this.messageGroupId=e.messageGroupId,this.deduplicationId=e.deduplicationId,t&&"object"==typeof t)for(const[e,r]of Object.entries(t))r.queueUrl&&(this.queues[e]=r.queueUrl)}validateConfig(){const e=[];return this.queueUrl||0!==Object.keys(this.queues).length||this.defaultQueue||this.resourceQueueMap||e.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided"),{isValid:0===e.length,errors:e}}getQueueUrlsForResource(e){if(this.resourceQueueMap&&this.resourceQueueMap[e])return this.resourceQueueMap[e];if(this.queues[e])return[this.queues[e]];if(this.queueUrl)return[this.queueUrl];if(this.defaultQueue)return[this.defaultQueue];throw new Error(`No queue URL found for resource '${e}'`)}_applyTransformer(e,t){const r=this.resources[e];let i=t;return r?("function"==typeof r.transform?i=r.transform(t):"function"==typeof r.transformer&&(i=r.transformer(t)),i||t):t}createMessage(e,t,r,i,s=null){const n={resource:e,action:t,timestamp:(new Date).toISOString(),source:"s3db-replicator"};switch(t){case"insert":case"delete":default:return{...n,data:r};case"update":return{...n,before:s,data:r}}}async initialize(e,t){if(await super.initialize(e),!this.sqsClient){const[e,r,i]=await de(()=>import("@aws-sdk/client-sqs"));if(!e)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{SQSClient:s}=i;this.sqsClient=t||new s({region:this.region,credentials:this.config.credentials}),this.emit("initialized",{replicator:this.name,queueUrl:this.queueUrl,queues:this.queues,defaultQueue:this.defaultQueue})}}async replicate(e,t,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const[n,o,a]=await de(async()=>{const{SendMessageCommand:n}=await import("@aws-sdk/client-sqs"),o=this.getQueueUrlsForResource(e),a=this._applyTransformer(e,r),c=this.createMessage(e,t,a,i,s),u=[];for(const r of o){const s=new n({QueueUrl:r,MessageBody:JSON.stringify(c),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${e}:${t}:${i}`:void 0}),o=await this.sqsClient.send(s);u.push({queueUrl:r,messageId:o.MessageId}),this.emit("replicated",{replicator:this.name,resource:e,operation:t,id:i,queueUrl:r,messageId:o.MessageId,success:!0})}return{success:!0,results:u}});return n?a:(this.emit("replicator_error",{replicator:this.name,resource:e,operation:t,id:i,error:o.message}),{success:!1,error:o.message})}async replicateBatch(e,t){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const[r,i,s]=await de(async()=>{const{SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs"),i=this.getQueueUrlsForResource(e),s=[];for(let e=0;e<t.length;e+=10)s.push(t.slice(e,e+10));const n=[],o=[];for(const t of s){const[s,a]=await de(async()=>{const s=t.map((t,r)=>({Id:`${t.id}-${r}`,MessageBody:JSON.stringify(this.createMessage(e,t.operation,t.data,t.id,t.beforeData)),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${e}:${t.operation}:${t.id}`:void 0})),o=new r({QueueUrl:i[0],Entries:s}),a=await this.sqsClient.send(o);n.push(a)});if(!s&&(o.push({batch:t.length,error:a.message}),a.message&&(a.message.includes("Batch error")||a.message.includes("Connection")||a.message.includes("Network"))))throw a}return this.emit("batch_replicated",{replicator:this.name,resource:e,queueUrl:i[0],total:t.length,successful:n.length,errors:o.length}),{success:0===o.length,results:n,errors:o,total:t.length,queueUrl:i[0]}});if(r)return s;const n=i?.message||i||"Unknown error";return this.emit("batch_replicator_error",{replicator:this.name,resource:e,error:n}),{success:!1,error:n}}async testConnection(){const[e,t]=await de(async()=>{this.sqsClient||await this.initialize(this.database);const{GetQueueAttributesCommand:e}=await import("@aws-sdk/client-sqs"),t=new e({QueueUrl:this.queueUrl,AttributeNames:["QueueArn"]});return await this.sqsClient.send(t),!0});return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.sqsClient,queueUrl:this.queueUrl,region:this.region,resources:this.resources,totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.sqsClient&&this.sqsClient.destroy(),await super.cleanup()}shouldReplicateResource(e){return this.resourceQueueMap&&Object.keys(this.resourceQueueMap).includes(e)||this.queues&&Object.keys(this.queues).includes(e)||!(!this.defaultQueue&&!this.queueUrl)||this.resources&&Object.keys(this.resources).includes(e)||!1}},bigquery:Ii,postgres:Ei};function fs(e,t={},r=[],i=null){const s=hs[e];if(!s)throw new Error(`Unknown replicator driver: ${e}. Available drivers: ${Object.keys(hs).join(", ")}`);return new s(t,r,i)}function ds(e){return"string"==typeof e?e.trim().toLowerCase():e}class ps extends Ae{constructor(e={}){if(super(),e.verbose&&console.log("[PLUGIN][CONSTRUCTOR] ReplicatorPlugin constructor called"),e.verbose&&console.log("[PLUGIN][constructor] New ReplicatorPlugin instance created with config:",e),!e.replicators||!Array.isArray(e.replicators))throw new Error("ReplicatorPlugin: replicators array is required");for(const t of e.replicators)if(!t.driver)throw new Error("ReplicatorPlugin: each replicator must have a driver");this.config={verbose:e.verbose??!1,persistReplicatorLog:e.persistReplicatorLog??!1,replicatorLogResource:e.replicatorLogResource??"replicator_logs",replicators:e.replicators||[]},this.replicators=[],this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,totalErrors:0,lastError:null},this._installedListeners=[]}async decompressData(e){return e}filterInternalFields(e){if(!e||"object"!=typeof e)return e;const t={};for(const[r,i]of Object.entries(e))r.startsWith("_")||"$overflow"===r||"$before"===r||"$after"===r||(t[r]=i);return t}installEventListeners(e){const t=this;t.config.verbose&&console.log("[PLUGIN] installEventListeners called for:",e&&e.name,{hasDatabase:!!e.database,sameDatabase:e.database===t.database,alreadyInstalled:e._replicatorListenersInstalled,resourceObj:e,resourceObjId:e&&e.id,resourceObjType:typeof e,resourceObjIs:e&&Object.is(e,t.database.resources&&t.database.resources[e.name]),resourceObjEq:e===(t.database.resources&&t.database.resources[e.name])}),e&&e.name!==t.config.replicatorLogResource&&e.database&&e.database===t.database&&(e._replicatorListenersInstalled||(e._replicatorListenersInstalled=!0,this._installedListeners.push(e),t.config.verbose&&console.log(`[PLUGIN] installEventListeners INSTALLED for resource: ${e&&e.name}`),e.on("insert",async r=>{t.config.verbose&&console.log("[PLUGIN] Listener INSERT on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})));try{const i=await t.getCompleteData(e,r);t.config.verbose&&console.log(`[PLUGIN] Listener INSERT completeData for ${e.name} id=${r&&r.id}:`,i),await t.processReplicatorEvent(e.name,"insert",r.id,i,null)}catch(i){t.config.verbose&&console.error(`[PLUGIN] Listener INSERT error on ${e.name} id=${r&&r.id}:`,i)}}),e.on("update",async r=>{console.log("[PLUGIN][Listener][UPDATE][START] triggered for resource:",e.name,"data:",r);const i=r&&r.$before;t.config.verbose&&console.log("[PLUGIN] Listener UPDATE on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})),"data:",r,"beforeData:",i);try{let s;const[n,o,a]=await de(()=>e.get(r.id));s=n&&a?a:r,await t.processReplicatorEvent(e.name,"update",r.id,s,i)}catch(i){t.config.verbose&&console.error(`[PLUGIN] Listener UPDATE erro em ${e.name} id=${r&&r.id}:`,i)}}),e.on("delete",async(r,i)=>{t.config.verbose&&console.log("[PLUGIN] Listener DELETE on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})));try{await t.processReplicatorEvent(e.name,"delete",r.id,null,i)}catch(i){t.config.verbose&&console.error(`[PLUGIN] Listener DELETE erro em ${e.name} id=${r&&r.id}:`,i)}}),t.config.verbose&&console.log(`[PLUGIN] Listeners instalados para resource: ${e&&e.name} (insert: ${e.listenerCount("insert")}, update: ${e.listenerCount("update")}, delete: ${e.listenerCount("delete")})`)))}async getCompleteData(e,t){const[r,i,s]=await de(()=>e.get(t.id));return r?s:t}async setup(e){if(console.log("[PLUGIN][SETUP] setup called"),this.config.verbose&&console.log("[PLUGIN][setup] called with database:",e&&e.name),this.database=e,this.config.persistReplicatorLog){let t=e.resources[ds(this.config.replicatorLogResource)];t||(t=await e.createResource({name:this.config.replicatorLogResource,behavior:"truncate-data",attributes:{id:"string|required",resource:"string|required",action:"string|required",data:"object",timestamp:"number|required",createdAt:"string|required"},partitions:{byDate:{fields:{createdAt:"string|maxlength:10"}}}}),this.config.verbose&&console.log("[PLUGIN] Log resource created:",this.config.replicatorLogResource,!!t)),e.resources[ds(this.config.replicatorLogResource)]=t,this.replicatorLog=t,this.config.verbose&&console.log("[PLUGIN] Log resource created and registered:",this.config.replicatorLogResource,!!e.resources[ds(this.config.replicatorLogResource)]),"function"==typeof e.uploadMetadataFile&&(await e.uploadMetadataFile(),this.config.verbose&&console.log("[PLUGIN] uploadMetadataFile called. database.resources keys:",Object.keys(e.resources)))}this.config.replicators&&this.config.replicators.length>0&&0===this.replicators.length&&(await this.initializeReplicators(),console.log("[PLUGIN][SETUP] after initializeReplicators, replicators.length:",this.replicators.length),this.config.verbose&&console.log("[PLUGIN][setup] After initializeReplicators, replicators.length:",this.replicators.length,this.replicators.map(e=>({id:e.id,driver:e.driver}))));for(const t in e.resources)ds(t)!==ds(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t]);e.on("connected",()=>{for(const t in e.resources)ds(t)!==ds(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t])});const t=e.createResource.bind(e);e.createResource=async e=>{this.config.verbose&&console.log("[PLUGIN] createResource proxy called for:",e&&e.name);const r=await t(e);return r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r),r},e.on("s3db.resourceCreated",t=>{const r=e.resources[t];r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r)}),e.on("s3db.resourceUpdated",t=>{const r=e.resources[t];r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r)})}async initializeReplicators(){console.log("[PLUGIN][INIT] initializeReplicators called");for(const e of this.config.replicators)try{console.log("[PLUGIN][INIT] processing replicatorConfig:",e);const t=e.driver,r=e.resources,i=fs(t,e,r,e.client);i?(await i.initialize(this.database),this.replicators.push({id:Math.random().toString(36).slice(2),driver:t,config:e,resources:r,instance:i}),console.log("[PLUGIN][INIT] pushed replicator:",t,r)):console.log("[PLUGIN][INIT] createReplicator returned null/undefined for driver:",t)}catch(e){console.error("[PLUGIN][INIT] Error creating replicator:",e)}}async start(){}async stop(){}async processReplicatorEvent(e,t,r,i,s=null){if(this.config.verbose&&(console.log("[PLUGIN][processReplicatorEvent] replicators.length:",this.replicators.length,this.replicators.map(e=>({id:e.id,driver:e.driver}))),console.log(`[PLUGIN][processReplicatorEvent] operation: ${t}, resource: ${e}, recordId: ${r}, data:`,i,"beforeData:",s)),this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: resource=${e} op=${t} id=${r} data=`,i),this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: resource=${e} op=${t} replicators=${this.replicators.length}`),0===this.replicators.length)return void(this.config.verbose&&console.log("[PLUGIN] No replicators registered"));const n=this.replicators.filter(r=>{const i=r.instance.shouldReplicateResource(e,t);return this.config.verbose&&console.log(`[PLUGIN] Replicator ${r.driver} shouldReplicateResource(${e}, ${t}):`,i),i});if(this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: applicableReplicators for resource=${e}:`,n.map(e=>e.driver)),0===n.length)return void(this.config.verbose&&console.log("[PLUGIN] No applicable replicators for resource",e));const o=this.filterInternalFields(m(i)?i:{raw:i}),a=s?this.filterInternalFields(m(s)?s:{raw:s}):null,c={id:`repl-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e,operation:t,recordId:r,data:o,beforeData:a,timestamp:(new Date).toISOString(),attempts:0},u=await this.logreplicator(c),[l,h,f]=await de(async()=>this.processreplicatorItem(c));l?(u&&await this.updatereplicatorLog(u,{status:f.success?"success":"failed",attempts:1,error:f.success?"":JSON.stringify(f.results)}),this.stats.totalOperations++,f.success?this.stats.successfulOperations++:this.stats.failedOperations++):(u&&await this.updatereplicatorLog(u,{status:"failed",attempts:1,error:h.message}),this.stats.failedOperations++)}async processreplicatorItem(e){this.config.verbose&&console.log("[PLUGIN][processreplicatorItem] called with item:",e);const t=this.replicators.filter(t=>{const r=t.instance.shouldReplicateResource(e.resourceName,e.operation);return this.config.verbose&&console.log(`[PLUGIN] processreplicatorItem: Replicator ${t.driver} shouldReplicateResource(${e.resourceName}, ${e.operation}):`,r),r});if(this.config.verbose&&console.log(`[PLUGIN] processreplicatorItem: applicableReplicators for resource=${e.resourceName}:`,t.map(e=>e.driver)),0===t.length)return this.config.verbose&&console.log("[PLUGIN] processreplicatorItem: No applicable replicators for resource",e.resourceName),{success:!0,skipped:!0,reason:"no_applicable_replicators"};const r=[];for(const i of t){let t,s,n;this.config.verbose&&console.log("[PLUGIN] processReplicatorItem",{resource:e.resourceName,operation:e.operation,data:e.data,beforeData:e.beforeData,replicator:i.instance?.constructor?.name}),i.instance&&i.instance.constructor&&"S3dbReplicator"===i.instance.constructor.name?[s,n,t]=await de(()=>i.instance.replicate({resource:e.resourceName,operation:e.operation,data:e.data,id:e.recordId,beforeData:e.beforeData})):[s,n,t]=await de(()=>i.instance.replicate(e.resourceName,e.operation,e.data,e.recordId,e.beforeData)),r.push({replicatorId:i.id,driver:i.driver,success:t&&t.success,error:t&&t.error,skipped:t&&t.skipped})}return{success:r.every(e=>e.success||e.skipped),results:r}}async logreplicator(e){const t=this.replicatorLog||this.database.resources[ds(this.config.replicatorLogResource)];if(!t)return this.config.verbose&&console.error("[PLUGIN] replicator log resource not found!"),this.database&&(this.config.verbose&&console.warn("[PLUGIN] database.resources keys:",Object.keys(this.database.resources)),this.database.options&&this.database.options.connectionString&&this.config.verbose&&console.warn("[PLUGIN] database connectionString:",this.database.options.connectionString)),void this.emit("replicator.log.failed",{error:"replicator log resource not found",item:e});const r={id:e.id||`repl-${Date.now()}-${Math.random().toString(36).slice(2)}`,resource:e.resource||e.resourceName||"",action:e.operation||e.action||"",data:e.data||{},timestamp:"number"==typeof e.timestamp?e.timestamp:Date.now(),createdAt:e.createdAt||(new Date).toISOString().slice(0,10)};try{await t.insert(r)}catch(t){this.config.verbose&&console.error("[PLUGIN] Error writing to replicator log:",t),this.emit("replicator.log.failed",{error:t,item:e})}}async updatereplicatorLog(e,t){if(!this.replicatorLog)return;const[r,i]=await de(async()=>{await this.replicatorLog.update(e,{...t,lastAttempt:(new Date).toISOString()})});r||this.emit("replicator.updateLog.failed",{error:i.message,logId:e,updates:t})}async getreplicatorStats(){return{replicators:await Promise.all(this.replicators.map(async e=>{const t=await e.instance.getStatus();return{id:e.id,driver:e.driver,config:e.config,status:t}})),queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getreplicatorLogs(e={}){if(!this.replicatorLog)return[];const{resourceName:t,operation:r,status:i,limit:s=100,offset:n=0}=e;let o={};t&&(o.resourceName=t),r&&(o.operation=r),i&&(o.status=i);return(await this.replicatorLog.list(o)).slice(n,n+s)}async retryFailedreplicators(){if(!this.replicatorLog)return{retried:0};const e=await this.replicatorLog.list({status:"failed"});let t=0;for(const r of e){const[e,i]=await de(async()=>{await this.processReplicatorEvent(r.resourceName,r.operation,r.recordId,r.data)});e?t++:this.config.verbose&&console.error("Failed to retry replicator:",i)}return{retried:t}}async syncAllData(e){const t=this.replicators.find(t=>t.id===e);if(!t)throw new Error(`Replicator not found: ${e}`);this.stats.lastSync=(new Date).toISOString();for(const r in this.database.resources)if(ds(r)!==ds("replicator_logs")&&t.instance.shouldReplicateResource(r)){this.emit("replicator.sync.resource",{resourceName:r,replicatorId:e});const i=this.database.resources[r],s=await i.getAll();for(const e of s)await t.instance.replicate(r,"insert",e,e.id)}this.emit("replicator.sync.completed",{replicatorId:e,stats:this.stats})}async cleanup(){if(this.config.verbose&&console.log("[PLUGIN][CLEANUP] Cleaning up ReplicatorPlugin"),this._installedListeners&&Array.isArray(this._installedListeners)){for(const e of this._installedListeners)e&&"function"==typeof e.removeAllListeners&&(e.removeAllListeners("insert"),e.removeAllListeners("update"),e.removeAllListeners("delete")),e._replicatorListenersInstalled=!1;this._installedListeners=[]}if(this.database&&"function"==typeof this.database.removeAllListeners&&this.database.removeAllListeners(),this.replicators&&Array.isArray(this.replicators)){for(const e of this.replicators)e.instance&&"function"==typeof e.instance.cleanup&&await e.instance.cleanup();this.replicators=[]}this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,totalErrors:0,lastError:null},this.config.verbose&&console.log("[PLUGIN][CLEANUP] ReplicatorPlugin cleanup complete")}}export{is as AVAILABLE_BEHAVIORS,xe as AuditPlugin,G as AuthenticationError,V as BaseError,Si as CachePlugin,Di as Client,Ai as ConnectionString,oe as ConnectionStringError,_i as CostsPlugin,ae as CryptoError,ss as DEFAULT_BEHAVIOR,as as Database,H as DatabaseError,Y as EncryptionError,se as ErrorMap,Ri as FullTextPlugin,re as InvalidResourceItem,ji as MetricsPlugin,te as MissingMetadata,X as NoSuchBucket,Z as NoSuchKey,ee as NotFound,le as PartitionError,J as PermissionError,Ae as Plugin,De as PluginObject,ps as ReplicatorPlugin,ns as Resource,ue as ResourceError,yi as ResourceIdsPageReader,gi as ResourceIdsReader,Q as ResourceNotFound,bi as ResourceReader,wi as ResourceWriter,as as S3db,K as S3dbError,Mi as Schema,ce as SchemaError,ie as UnknownError,W as ValidationError,Ti as Validator,ts as behaviors,$ as calculateAttributeNamesSize,U as calculateAttributeSizes,z as calculateEffectiveLimit,F as calculateSystemOverhead,q as calculateTotalSize,L as calculateUTF8Bytes,P as decode,T as decodeDecimal,ye as decrypt,cs as default,x as encode,C as encodeDecimal,me as encrypt,rs as getBehavior,B as getSizeBreakdown,ve as idGenerator,ne as mapAwsError,be as md5,Oe as passwordGenerator,ge as sha256,vi as streamToString,M as transformValue,he as tryFn,fe as tryFnSync};
1
+ import{customAlphabet as t,urlAlphabet as e}from"nanoid";import r from"zlib";import{PromisePool as i}from"@supercharge/promise-pool";import{ReadableStream as n}from"node:stream/web";import{chunk as s,merge as o,isString as a,isEmpty as c,invert as u,uniq as l,cloneDeep as h,get as f,set as d,isObject as p,isFunction as m}from"lodash-es";import{createHash as g}from"crypto";import y from"json-stable-stringify";import{S3Client as b,PutObjectCommand as w,GetObjectCommand as v,HeadObjectCommand as k,CopyObjectCommand as O,DeleteObjectCommand as S,DeleteObjectsCommand as _,ListObjectsV2Command as x}from"@aws-sdk/client-s3";import{flatten as j,unflatten as R}from"flat";import D from"fastest-validator";const A="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",N=Object.fromEntries([...A].map((t,e)=>[t,e])),E=t=>{if("number"!=typeof t||isNaN(t))return"undefined";if(!isFinite(t))return"undefined";if(0===t)return A[0];if(t<0)return"-"+E(-Math.floor(t));t=Math.floor(t);let e="";for(;t;)e=A[t%62]+e,t=Math.floor(t/62);return e},P=t=>{if("string"!=typeof t)return NaN;if(""===t)return 0;let e=!1;"-"===t[0]&&(e=!0,t=t.slice(1));let r=0;for(let e=0;e<t.length;e++){const i=N[t[e]];if(void 0===i)return NaN;r=62*r+i}return e?-r:r},I=t=>{if("number"!=typeof t||isNaN(t))return"undefined";if(!isFinite(t))return"undefined";const e=t<0;t=Math.abs(t);const[r,i]=t.toString().split("."),n=E(Number(r));return i?(e?"-":"")+n+"."+i:(e?"-":"")+n},C=t=>{if("string"!=typeof t)return NaN;let e=!1;"-"===t[0]&&(e=!0,t=t.slice(1));const[r,i]=t.split("."),n=P(r);if(isNaN(n))return NaN;const s=i?Number(n+"."+i):n;return e?-s:s};function M(t){"string"!=typeof t&&(t=String(t));let e=0;for(let r=0;r<t.length;r++){const i=t.codePointAt(r);i<=127?e+=1:i<=2047?e+=2:i<=65535?e+=3:i<=1114111&&(e+=4,i>65535&&r++)}return e}function T(t){let e=0;for(const r of Object.keys(t))e+=M(r);return e}function $(t){return null==t?"":"boolean"==typeof t?t?"1":"0":"number"==typeof t?String(t):"string"==typeof t?t:Array.isArray(t)?0===t.length?"[]":t.map(t=>String(t)).join("|"):"object"==typeof t?JSON.stringify(t):String(t)}function L(t){const e={};for(const[r,i]of Object.entries(t)){const t=M($(i));e[r]=t}return e}function U(t){const e=L(t);return Object.values(e).reduce((t,e)=>t+e,0)+T(t)}function B(t){const e=L(t),r=T(t),i=Object.values(e).reduce((t,e)=>t+e,0),n=i+r,s=Object.entries(e).sort(([,t],[,e])=>e-t).map(([t,e])=>({attribute:t,size:e,percentage:(e/n*100).toFixed(2)+"%"}));return{total:n,valueSizes:e,namesSize:r,valueTotal:i,breakdown:s,detailedBreakdown:{values:i,names:r,total:n}}}function F(t={}){const{version:e="1",timestamps:r=!1,id:i=""}=t,n={_v:String(e)};r&&(n.createdAt="2024-01-01T00:00:00.000Z",n.updatedAt="2024-01-01T00:00:00.000Z"),i&&(n.id=i);const s={};for(const[t,e]of Object.entries(n))s[t]=e;return U(s)}function V(t={}){const{s3Limit:e=2048,systemConfig:r={}}=t;return e-F(r)}class z extends Error{constructor({verbose:t,bucket:e,key:r,message:i,code:n,statusCode:s,requestId:o,awsMessage:a,original:c,commandName:u,commandInput:l,metadata:h,suggestion:f,...d}){t&&(i+=`\n\nVerbose:\n\n${JSON.stringify(d,null,2)}`),super(i),"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error(i).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=e,this.key=r,this.thrownAt=new Date,this.code=n,this.statusCode=s,this.requestId=o,this.awsMessage=a,this.original=c,this.commandName=u,this.commandInput=l,this.metadata=h,this.suggestion=f,this.data={bucket:e,key:r,...d,verbose:t,message:i}}toJson(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,awsMessage:this.awsMessage,bucket:this.bucket,key:this.key,thrownAt:this.thrownAt,commandName:this.commandName,commandInput:this.commandInput,metadata:this.metadata,suggestion:this.suggestion,data:this.data,original:this.original,stack:this.stack}}toString(){return`${this.name} | ${this.message}`}}class K extends z{constructor(t,e={}){let r,i,n,s,o,a;e.original&&(o=e.original,r=o.code||o.Code||o.name,i=o.statusCode||o.$metadata&&o.$metadata.httpStatusCode,n=o.requestId||o.$metadata&&o.$metadata.requestId,s=o.message,a=o.$metadata?{...o.$metadata}:void 0),super({message:t,...e,code:r,statusCode:i,requestId:n,awsMessage:s,original:o,metadata:a})}}class q extends K{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class H extends K{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class W extends K{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class J extends K{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class Y extends K{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class G extends K{constructor({bucket:t,resourceName:e,id:r,original:i,...n}){if("string"!=typeof r)throw new Error("id must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");if("string"!=typeof e)throw new Error("resourceName must be a string");super(`Resource not found: ${e}/${r} [bucket:${t}]`,{bucket:t,resourceName:e,id:r,original:i,...n})}}class Z extends K{constructor({bucket:t,original:e,...r}){if("string"!=typeof t)throw new Error("bucket must be a string");super(`Bucket does not exists [bucket:${t}]`,{bucket:t,original:e,...r})}}class Q extends K{constructor({bucket:t,key:e,resourceName:r,id:i,original:n,...s}){if("string"!=typeof e)throw new Error("key must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");if(void 0!==i&&"string"!=typeof i)throw new Error("id must be a string");super(`No such key: ${e} [bucket:${t}]`,{bucket:t,key:e,resourceName:r,id:i,original:n,...s}),this.resourceName=r,this.id=i}}class X extends K{constructor({bucket:t,key:e,resourceName:r,id:i,original:n,...s}){if("string"!=typeof e)throw new Error("key must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");super(`Not found: ${e} [bucket:${t}]`,{bucket:t,key:e,resourceName:r,id:i,original:n,...s}),this.resourceName=r,this.id=i}}class tt extends K{constructor({bucket:t,original:e,...r}){if("string"!=typeof t)throw new Error("bucket must be a string");super(`Missing metadata for bucket [bucket:${t}]`,{bucket:t,original:e,...r})}}class et extends K{constructor({bucket:t,resourceName:e,attributes:r,validation:i,message:n,original:s,...o}){if("string"!=typeof t)throw new Error("bucket must be a string");if("string"!=typeof e)throw new Error("resourceName must be a string");super(n||`Validation error: This item is not valid. Resource=${e} [bucket:${t}].\n${JSON.stringify(i,null,2)}`,{bucket:t,resourceName:e,attributes:r,validation:i,original:s,...o})}}class rt extends K{}const it={NotFound:X,NoSuchKey:Q,UnknownError:rt,NoSuchBucket:Z,MissingMetadata:tt,InvalidResourceItem:et};function nt(t,e={}){const r=t.code||t.Code||t.name,i=t.$metadata?{...t.$metadata}:void 0,n=e.commandName,s=e.commandInput;let o;return"NoSuchKey"===r||"NotFound"===r?(o="Check if the key exists in the specified bucket and if your credentials have permission.",new Q({...e,original:t,metadata:i,commandName:n,commandInput:s,suggestion:o})):"NoSuchBucket"===r?(o="Check if the bucket exists and if your credentials have permission.",new Z({...e,original:t,metadata:i,commandName:n,commandInput:s,suggestion:o})):"AccessDenied"===r||403===t.statusCode||"Forbidden"===r?(o="Check your credentials and bucket policy.",new J("Access denied",{...e,original:t,metadata:i,commandName:n,commandInput:s,suggestion:o})):"ValidationError"===r||400===t.statusCode?(o="Check the request parameters and payload.",new H("Validation error",{...e,original:t,metadata:i,commandName:n,commandInput:s,suggestion:o})):"MissingMetadata"===r?(o="Check if the object metadata is present and valid.",new tt({...e,original:t,metadata:i,commandName:n,commandInput:s,suggestion:o})):(o="Check the error details and AWS documentation.",new rt("Unknown error",{...e,original:t,metadata:i,commandName:n,commandInput:s,suggestion:o}))}class st extends K{constructor(t,e={}){super(t,{...e,suggestion:"Check the connection string format and credentials."})}}class ot extends K{constructor(t,e={}){super(t,{...e,suggestion:"Check if the crypto library is available and input is valid."})}}class at extends K{constructor(t,e={}){super(t,{...e,suggestion:"Check schema definition and input data."})}}class ct extends K{constructor(t,e={}){super(t,{...e,suggestion:e.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,e)}}class ut extends K{constructor(t,e={}){super(t,{...e,suggestion:e.suggestion||"Check partition definition, fields, and input values."})}}function lt(t){if(null==t){const t=new Error("fnOrPromise cannot be null or undefined");return t.stack=(new Error).stack,[!1,t,void 0]}if("function"==typeof t)try{const e=t();return null==e?[!0,null,e]:"function"==typeof e.then?e.then(t=>[!0,null,t]).catch(t=>{if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}):[!0,null,e]}catch(t){if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}return"function"==typeof t.then?Promise.resolve(t).then(t=>[!0,null,t]).catch(t=>{if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}):[!0,null,t]}function ht(t){try{return[!0,null,t()]}catch(t){return[!1,t,null]}}var ft=lt;async function dt(){let t;if("undefined"!=typeof process){const[e,r,i]=await ft(async()=>{const{webcrypto:t}=await import("crypto");return t});if(!e)throw new ot("Crypto API not available",{original:r,context:"dynamicCrypto"});t=i}else"undefined"!=typeof window&&(t=window.crypto);if(!t)throw new ot("Could not load any crypto library",{context:"dynamicCrypto"});return t}async function pt(t){const[e,r,i]=await ft(dt);if(!e)throw new ot("Crypto API not available",{original:r});const n=(new TextEncoder).encode(t),[s,o,a]=await ft(()=>i.subtle.digest("SHA-256",n));if(!s)throw new ot("SHA-256 digest failed",{original:o,input:t});return Array.from(new Uint8Array(a)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function mt(t,e){const[r,i,n]=await ft(dt);if(!r)throw new ot("Crypto API not available",{original:i});const s=n.getRandomValues(new Uint8Array(16)),[o,a,c]=await ft(()=>bt(e,s));if(!o)throw new ot("Key derivation failed",{original:a,passphrase:e,salt:s});const u=n.getRandomValues(new Uint8Array(12)),l=(new TextEncoder).encode(t),[h,f,d]=await ft(()=>n.subtle.encrypt({name:"AES-GCM",iv:u},c,l));if(!h)throw new ot("Encryption failed",{original:f,content:t});const p=new Uint8Array(s.length+u.length+d.byteLength);return p.set(s),p.set(u,s.length),p.set(new Uint8Array(d),s.length+u.length),function(t){if("undefined"!=typeof process)return Buffer.from(t).toString("base64");{const[e,r,i]=ht(()=>String.fromCharCode.apply(null,new Uint8Array(t)));if(!e)throw new ot("Failed to convert ArrayBuffer to base64 (browser)",{original:r});return window.btoa(i)}}(p)}async function gt(t,e){const[r,i,n]=await ft(dt);if(!r)throw new ot("Crypto API not available",{original:i});const s=function(t){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(t,"base64"));{const[e,r,i]=ht(()=>window.atob(t));if(!e)throw new ot("Failed to decode base64 (browser)",{original:r});const n=i.length,s=new Uint8Array(n);for(let t=0;t<n;t++)s[t]=i.charCodeAt(t);return s}}(t),o=s.slice(0,16),a=s.slice(16,28),c=s.slice(28),[u,l,h]=await ft(()=>bt(e,o));if(!u)throw new ot("Key derivation failed (decrypt)",{original:l,passphrase:e,salt:o});const[f,d,p]=await ft(()=>n.subtle.decrypt({name:"AES-GCM",iv:a},h,c));if(!f)throw new ot("Decryption failed",{original:d,encryptedBase64:t});return(new TextDecoder).decode(p)}async function yt(t){if("undefined"==typeof process)throw new ot("MD5 hashing is only available in Node.js environment",{context:"md5"});const[e,r,i]=await ft(async()=>{const{createHash:e}=await import("crypto");return e("md5").update(t).digest("base64")});if(!e)throw new ot("MD5 hashing failed",{original:r,data:t});return i}async function bt(t,e){const[r,i,n]=await ft(dt);if(!r)throw new ot("Crypto API not available",{original:i});const s=(new TextEncoder).encode(t),[o,a,c]=await ft(()=>n.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveKey"]));if(!o)throw new ot("importKey failed",{original:a,passphrase:t});const[u,l,h]=await ft(()=>n.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]));if(!u)throw new ot("deriveKey failed",{original:l,passphrase:t,salt:e});return h}const wt=t(e,22),vt=t("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var kt;function Ot(){}function St(){St.init.call(this)}function _t(t){return void 0===t._maxListeners?St.defaultMaxListeners:t._maxListeners}function xt(t,e,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=t._events)?(s.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]):(s=t._events=new Ot,t._eventsCount=0),o){if("function"==typeof o?o=s[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(n=_t(t))&&n>0&&o.length>n){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[e]=r,++t._eventsCount;return t}function jt(t,e,r){var i=!1;function n(){t.removeListener(e,n),i||(i=!0,r.apply(t,arguments))}return n.listener=r,n}function Rt(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Dt(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}Ot.prototype=Object.create(null),St.EventEmitter=St,St.usingDomains=!1,St.prototype.domain=void 0,St.prototype._events=void 0,St.prototype._maxListeners=void 0,St.defaultMaxListeners=10,St.init=function(){this.domain=null,St.usingDomains&&(!kt.active||this instanceof kt.Domain||(this.domain=kt.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Ot,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},St.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},St.prototype.getMaxListeners=function(){return _t(this)},St.prototype.emit=function(t){var e,r,i,n,s,o,a,c="error"===t;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(e=arguments[1],!a){if(e instanceof Error)throw e;var u=new Error('Uncaught, unspecified "error" event. ('+e+")");throw u.context=e,u}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=a,e.domainThrown=!1,a.emit("error",e),!1}if(!(r=o[t]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var i=t.length,n=Dt(t,i),s=0;s<i;++s)n[s].call(r)}(r,l,this);break;case 2:!function(t,e,r,i){if(e)t.call(r,i);else for(var n=t.length,s=Dt(t,n),o=0;o<n;++o)s[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(t,e,r,i,n){if(e)t.call(r,i,n);else for(var s=t.length,o=Dt(t,s),a=0;a<s;++a)o[a].call(r,i,n)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(t,e,r,i,n,s){if(e)t.call(r,i,n,s);else for(var o=t.length,a=Dt(t,o),c=0;c<o;++c)a[c].call(r,i,n,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];!function(t,e,r,i){if(e)t.apply(r,i);else for(var n=t.length,s=Dt(t,n),o=0;o<n;++o)s[o].apply(r,i)}(r,l,this,n)}return!0},St.prototype.addListener=function(t,e){return xt(this,t,e,!1)},St.prototype.on=St.prototype.addListener,St.prototype.prependListener=function(t,e){return xt(this,t,e,!0)},St.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,jt(this,t,e)),this},St.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,jt(this,t,e)),this},St.prototype.removeListener=function(t,e){var r,i,n,s,o;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[t]))return this;if(r===e||r.listener&&r.listener===e)0===--this._eventsCount?this._events=new Ot:(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if("function"!=typeof r){for(n=-1,s=r.length;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){o=r[s].listener,n=s;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Ot,this;delete i[t]}else!function(t,e){for(var r=e,i=r+1,n=t.length;i<n;r+=1,i+=1)t[r]=t[i];t.pop()}(r,n);i.removeListener&&this.emit("removeListener",t,o||e)}return this},St.prototype.off=function(t,e){return this.removeListener(t,e)},St.prototype.removeAllListeners=function(t){var e,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Ot,this._eventsCount=0):r[t]&&(0===--this._eventsCount?this._events=new Ot:delete r[t]),this;if(0===arguments.length){for(var i,n=Object.keys(r),s=0;s<n.length;++s)"removeListener"!==(i=n[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new Ot,this._eventsCount=0,this}if("function"==typeof(e=r[t]))this.removeListener(t,e);else if(e)do{this.removeListener(t,e[e.length-1])}while(e[0]);return this},St.prototype.listeners=function(t){var e,r=this._events;return r&&(e=r[t])?"function"==typeof e?[e.listener||e]:function(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}(e):[]},St.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):Rt.call(t,e)},St.prototype.listenerCount=Rt,St.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var At=class extends St{constructor(t={}){super(),this.name=this.constructor.name,this.options=t,this.hooks=new Map}async setup(t){this.database=t,this.beforeSetup(),await this.onSetup(),this.afterSetup()}async start(){this.beforeStart(),await this.onStart(),this.afterStart()}async stop(){this.beforeStop(),await this.onStop(),this.afterStop()}async onSetup(){}async onStart(){}async onStop(){}addHook(t,e,r){this.hooks.has(t)||this.hooks.set(t,new Map);const i=this.hooks.get(t);i.has(e)||i.set(e,[]),i.get(e).push(r)}removeHook(t,e,r){const i=this.hooks.get(t);if(i&&i.has(e)){const t=i.get(e),n=t.indexOf(r);n>-1&&t.splice(n,1)}}wrapResourceMethod(t,e,r){const i=t[e];if(t._pluginWrappers||(t._pluginWrappers=new Map),t._pluginWrappers.has(e)||t._pluginWrappers.set(e,[]),t._pluginWrappers.get(e).push(r),!t[`_wrapped_${e}`]){t[`_wrapped_${e}`]=i;const r=i&&i._isMockFunction;t[e]=async function(...r){let i=await t[`_wrapped_${e}`](...r);for(const n of t._pluginWrappers.get(e))i=await n.call(this,i,r,e);return i},r&&(Object.setPrototypeOf(t[e],Object.getPrototypeOf(i)),Object.assign(t[e],i))}}addMiddleware(t,e,r){if(t._pluginMiddlewares||(t._pluginMiddlewares={}),!t._pluginMiddlewares[e]){t._pluginMiddlewares[e]=[];const r=t[e].bind(t);t[e]=async function(...i){let n=-1;const s=async(...i)=>(n++,n<t._pluginMiddlewares[e].length?await t._pluginMiddlewares[e][n].call(this,s,...i):await r(...i));return await s(...i)}}t._pluginMiddlewares[e].push(r)}getPartitionValues(t,e){if(!e.config?.partitions)return{};const r={};for(const[i,n]of Object.entries(e.config.partitions))if(n.fields){r[i]={};for(const[s,o]of Object.entries(n.fields)){const n=this.getNestedFieldValue(t,s);null!=n&&(r[i][s]=e.applyPartitionRule(n,o))}}else r[i]={};return r}getNestedFieldValue(t,e){if(!e.includes("."))return t[e]??null;const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return null;i=i[t]}return i??null}beforeSetup(){this.emit("plugin.beforeSetup",new Date)}afterSetup(){this.emit("plugin.afterSetup",new Date)}beforeStart(){this.emit("plugin.beforeStart",new Date)}afterStart(){this.emit("plugin.afterStart",new Date)}beforeStop(){this.emit("plugin.beforeStop",new Date)}afterStop(){this.emit("plugin.afterStop",new Date)}};const Nt={setup(t){},start(){},stop(){}};class Et extends At{constructor(t={}){super(t),this.auditResource=null,this.config={includeData:!1!==t.includeData,includePartitions:!1!==t.includePartitions,maxDataSize:t.maxDataSize||1e4,...t}}async onSetup(){const[t,e,r]=await ft(()=>this.database.createResource({name:"audits",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",recordId:"string|required",userId:"string|optional",timestamp:"string|required",oldData:"string|optional",newData:"string|optional",partition:"string|optional",partitionValues:"string|optional",metadata:"string|optional"},behavior:"body-overflow"}));this.auditResource=t?r:this.database.resources.audits||null,(t||this.auditResource)&&(this.installDatabaseProxy(),this.installEventListeners())}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const t=this.installEventListenersForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResource(...e);return"audits"!==r.name&&t(r),r},this.database._auditProxyInstalled=!0}installEventListeners(){for(const t of Object.values(this.database.resources))"audits"!==t.name&&this.installEventListenersForResource(t)}installEventListenersForResource(t){t.on("insert",async e=>{const r=e.id||"auto-generated",i=this.config.includePartitions?this.getPartitionValues(e,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"insert",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(console.error)}),t.on("update",async e=>{const r=e.id;let i=e.$before;if(this.config.includeData&&!i){const[e,n,s]=await ft(()=>t.get(r));e&&(i=s)}const n=this.config.includePartitions?this.getPartitionValues(e,t):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"update",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(n):null,partitionValues:this.config.includePartitions&&n&&Object.keys(n).length>0?JSON.stringify(n):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(s).catch(console.error)}),t.on("delete",async e=>{const r=e.id;let i=e;if(this.config.includeData&&!i){const[e,n,s]=await ft(()=>t.get(r));e&&(i=s)}const n=i&&this.config.includePartitions?this.getPartitionValues(i,t):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"delete",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(n):null,partitionValues:this.config.includePartitions&&n&&Object.keys(n).length>0?JSON.stringify(n):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(s).catch(console.error)}),t.useMiddleware("deleteMany",async(e,r)=>{const i=e.args[0],n={};if(this.config.includeData)for(const e of i){const[r,i,s]=await ft(()=>t.get(e));n[e]=r?s:null}const s=await r();if(s&&s.length>0&&this.config.includeData)for(const e of i){const r=n[e],i=r&&this.config.includePartitions?this.getPartitionValues(r,t):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"delete",recordId:e,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(r)),newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0",batchOperation:!0})};this.logAudit(s).catch(console.error)}return s})}getPartitionValues(t,e){if(!t)return null;const r=e.config?.partitions||{},i={};for(const[e,n]of Object.entries(r))if(n.fields){const r={};for(const[e,i]of Object.entries(n.fields)){const i=this.getNestedFieldValue(t,e);null!=i&&(r[e]=i)}Object.keys(r).length>0&&(i[e]=r)}return i}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return;i=i[t]}return i}getPrimaryPartition(t){if(!t)return null;const e=Object.keys(t);return e.length>0?e[0]:null}async logAudit(t){t.id||(t.id=`audit-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return await this.auditResource.insert(t)}truncateData(t){if(!t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||"$overflow"===r||(e[r]=i);const r=JSON.stringify(e);if(r.length<=this.config.maxDataSize)return e;let i={...e},n=JSON.stringify(i).length;const s=JSON.stringify({_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}).length,o=this.config.maxDataSize-s;for(const[t,e]of Object.entries(i))if("string"==typeof e&&n>o){const r=n-o,s=Math.max(0,e.length-r-3);s<e.length&&(i[t]=e.substring(0,s)+"...",n=JSON.stringify(i).length)}return{...i,_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(t={}){if(!this.auditResource)return[];const[e,r,i]=await ft(async()=>{const{resourceName:e,operation:r,recordId:i,userId:n,partition:s,startDate:o,endDate:a,limit:c=100,offset:u=0}=t;let l=(await this.auditResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&((!i||t.recordId===i)&&((!n||t.userId===n)&&((!s||t.partition===s)&&(!(o&&new Date(t.timestamp)<new Date(o))&&!(a&&new Date(t.timestamp)>new Date(a))))))));l.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp));return l.slice(u,u+c).map(t=>{const[e,,r]="string"==typeof t.oldData?ht(()=>JSON.parse(t.oldData)):[!0,null,t.oldData],[i,,n]="string"==typeof t.newData?ht(()=>JSON.parse(t.newData)):[!0,null,t.newData],[s,,o]=t.partitionValues&&"string"==typeof t.partitionValues?ht(()=>JSON.parse(t.partitionValues)):[!0,null,t.partitionValues],[a,,c]=t.metadata&&"string"==typeof t.metadata?ht(()=>JSON.parse(t.metadata)):[!0,null,t.metadata];return{...t,oldData:null===t.oldData||void 0===t.oldData||"null"===t.oldData?null:e?r:null,newData:null===t.newData||void 0===t.newData||"null"===t.newData?null:i?n:null,partitionValues:s?o:t.partitionValues,metadata:a?c:t.metadata}})});return e?i:[]}async getRecordHistory(t,e){return this.getAuditLogs({resourceName:t,recordId:e,limit:1e3})}async getPartitionHistory(t,e,r){return this.getAuditLogs({resourceName:t,partition:e,limit:1e3})}async getAuditStats(t={}){const{resourceName:e,startDate:r,endDate:i}=t,n=await this.getAuditLogs({resourceName:e,startDate:r,endDate:i,limit:1e4}),s={total:n.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const t of n)if(s.byOperation[t.operation]=(s.byOperation[t.operation]||0)+1,s.byResource[t.resourceName]=(s.byResource[t.resourceName]||0)+1,t.partition&&(s.byPartition[t.partition]=(s.byPartition[t.partition]||0)+1),s.byUser[t.userId]=(s.byUser[t.userId]||0)+1,t.timestamp){const e=t.timestamp.split("T")[0];s.timeline[e]=(s.timeline[e]||0)+1}return s}}function Pt(t,e){for(var r=0,i=t.length-1;i>=0;i--){var n=t[i];"."===n?t.splice(i,1):".."===n?(t.splice(i,1),r++):r&&(t.splice(i,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}var It=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,Ct=function(t){return It.exec(t).slice(1)};function Mt(){for(var t="",e=!1,r=arguments.length-1;r>=-1&&!e;r--){var i=r>=0?arguments[r]:"/";if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");i&&(t=i+"/"+t,e="/"===i.charAt(0))}return(e?"/":"")+(t=Pt(Bt(t.split("/"),function(t){return!!t}),!e).join("/"))||"."}function Tt(t){var e=$t(t),r="/"===Ft(t,-1);return(t=Pt(Bt(t.split("/"),function(t){return!!t}),!e).join("/"))||e||(t="."),t&&r&&(t+="/"),(e?"/":"")+t}function $t(t){return"/"===t.charAt(0)}function Lt(){return Tt(Bt(Array.prototype.slice.call(arguments,0),function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))}var Ut={extname:function(t){return Ct(t)[3]},basename:function(t,e){var r=Ct(t)[2];return e&&r.substr(-1*e.length)===e&&(r=r.substr(0,r.length-e.length)),r},dirname:function(t){var e=Ct(t),r=e[0],i=e[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},sep:"/",delimiter:":",relative:function(t,e){function r(t){for(var e=0;e<t.length&&""===t[e];e++);for(var r=t.length-1;r>=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=Mt(t).substr(1),e=Mt(e).substr(1);for(var i=r(t.split("/")),n=r(e.split("/")),s=Math.min(i.length,n.length),o=s,a=0;a<s;a++)if(i[a]!==n[a]){o=a;break}var c=[];for(a=o;a<i.length;a++)c.push("..");return(c=c.concat(n.slice(o))).join("/")},join:Lt,isAbsolute:$t,normalize:Tt,resolve:Mt};function Bt(t,e){if(t.filter)return t.filter(e);for(var r=[],i=0;i<t.length;i++)e(t[i],i,t)&&r.push(t[i]);return r}var Ft="b"==="ab".substr(-1)?function(t,e,r){return t.substr(e,r)}:function(t,e,r){return e<0&&(e=t.length+e),t.substr(e,r)};class Vt extends St{constructor(t={}){super(),this.config=t}async _set(t,e){}async _get(t){}async _del(t){}async _clear(t){}validateKey(t){if(null==t||"string"!=typeof t||!t)throw new Error("Invalid key")}async set(t,e){return this.validateKey(t),await this._set(t,e),this.emit("set",e),e}async get(t){this.validateKey(t);const e=await this._get(t);return this.emit("get",e),e}async del(t){this.validateKey(t);const e=await this._del(t);return this.emit("delete",e),e}async delete(t){return this.del(t)}async clear(t){const e=await this._clear(t);return this.emit("clear",e),e}}function zt(){throw new Error("setTimeout has not been defined")}function Kt(){throw new Error("clearTimeout has not been defined")}var qt=zt,Ht=Kt;function Wt(t){if(qt===setTimeout)return setTimeout(t,0);if((qt===zt||!qt)&&setTimeout)return qt=setTimeout,setTimeout(t,0);try{return qt(t,0)}catch(e){try{return qt.call(null,t,0)}catch(e){return qt.call(this,t,0)}}}"function"==typeof global.setTimeout&&(qt=setTimeout),"function"==typeof global.clearTimeout&&(Ht=clearTimeout);var Jt,Yt=[],Gt=!1,Zt=-1;function Qt(){Gt&&Jt&&(Gt=!1,Jt.length?Yt=Jt.concat(Yt):Zt=-1,Yt.length&&Xt())}function Xt(){if(!Gt){var t=Wt(Qt);Gt=!0;for(var e=Yt.length;e;){for(Jt=Yt,Yt=[];++Zt<e;)Jt&&Jt[Zt].run();Zt=-1,e=Yt.length}Jt=null,Gt=!1,function(t){if(Ht===clearTimeout)return clearTimeout(t);if((Ht===Kt||!Ht)&&clearTimeout)return Ht=clearTimeout,clearTimeout(t);try{return Ht(t)}catch(e){try{return Ht.call(null,t)}catch(e){return Ht.call(this,t)}}}(t)}}function te(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];Yt.push(new ee(t,e)),1!==Yt.length||Gt||Wt(Xt)}function ee(t,e){this.fun=t,this.array=e}ee.prototype.run=function(){this.fun.apply(null,this.array)};var re,ie={env:{}};re="function"==typeof Object.create?function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t};var ne=/%[sdj%]/g;function se(t){if(!ye(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(ue(arguments[r]));return e.join(" ")}r=1;for(var i=arguments,n=i.length,s=String(t).replace(ne,function(t){if("%%"===t)return"%";if(r>=n)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),o=i[r];r<n;o=i[++r])ge(o)||!ve(o)?s+=" "+o:s+=" "+ue(o);return s}function oe(t,e){if(be(global.process))return function(){return oe(t,e).apply(this,arguments)};if(!0===ie.noDeprecation)return t;var r=!1;return function(){if(!r){if(ie.throwDeprecation)throw new Error(e);ie.traceDeprecation?console.trace(e):console.error(e),r=!0}return t.apply(this,arguments)}}var ae,ce={};function ue(t,e){var r={seen:[],stylize:he};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),me(e)?r.showHidden=e:e&&function(t,e){if(!e||!ve(e))return t;var r=Object.keys(e),i=r.length;for(;i--;)t[r[i]]=e[r[i]]}(r,e),be(r.showHidden)&&(r.showHidden=!1),be(r.depth)&&(r.depth=2),be(r.colors)&&(r.colors=!1),be(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=le),fe(r,t,r.depth)}function le(t,e){var r=ue.styles[e];return r?"["+ue.colors[r][0]+"m"+t+"["+ue.colors[r][1]+"m":t}function he(t,e){return t}function fe(t,e,r){if(t.customInspect&&e&&Se(e.inspect)&&e.inspect!==ue&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(r,t);return ye(i)||(i=fe(t,i,r)),i}var n=function(t,e){if(be(e))return t.stylize("undefined","undefined");if(ye(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(i=e,"number"==typeof i)return t.stylize(""+e,"number");var i;if(me(e))return t.stylize(""+e,"boolean");if(ge(e))return t.stylize("null","null")}(t,e);if(n)return n;var s=Object.keys(e),o=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(e)),Oe(e)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return de(e);if(0===s.length){if(Se(e)){var a=e.name?": "+e.name:"";return t.stylize("[Function"+a+"]","special")}if(we(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(ke(e))return t.stylize(Date.prototype.toString.call(e),"date");if(Oe(e))return de(e)}var c,u,l="",h=!1,f=["{","}"];(c=e,Array.isArray(c)&&(h=!0,f=["[","]"]),Se(e))&&(l=" [Function"+(e.name?": "+e.name:"")+"]");return we(e)&&(l=" "+RegExp.prototype.toString.call(e)),ke(e)&&(l=" "+Date.prototype.toUTCString.call(e)),Oe(e)&&(l=" "+de(e)),0!==s.length||h&&0!=e.length?r<0?we(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),u=h?function(t,e,r,i,n){for(var s=[],o=0,a=e.length;o<a;++o)xe(e,String(o))?s.push(pe(t,e,r,i,String(o),!0)):s.push("");return n.forEach(function(n){n.match(/^\d+$/)||s.push(pe(t,e,r,i,n,!0))}),s}(t,e,r,o,s):s.map(function(i){return pe(t,e,r,o,i,h)}),t.seen.pop(),function(t,e,r){var i=t.reduce(function(t,e){return e.indexOf("\n"),t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(u,l,f)):f[0]+l+f[1]}function de(t){return"["+Error.prototype.toString.call(t)+"]"}function pe(t,e,r,i,n,s){var o,a,c;if((c=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]}).get?a=c.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):c.set&&(a=t.stylize("[Setter]","special")),xe(i,n)||(o="["+n+"]"),a||(t.seen.indexOf(c.value)<0?(a=ge(r)?fe(t,c.value,null):fe(t,c.value,r-1)).indexOf("\n")>-1&&(a=s?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n")):a=t.stylize("[Circular]","special")),be(o)){if(s&&n.match(/^\d+$/))return a;(o=JSON.stringify(""+n)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+a}function me(t){return"boolean"==typeof t}function ge(t){return null===t}function ye(t){return"string"==typeof t}function be(t){return void 0===t}function we(t){return ve(t)&&"[object RegExp]"===_e(t)}function ve(t){return"object"==typeof t&&null!==t}function ke(t){return ve(t)&&"[object Date]"===_e(t)}function Oe(t){return ve(t)&&("[object Error]"===_e(t)||t instanceof Error)}function Se(t){return"function"==typeof t}function _e(t){return Object.prototype.toString.call(t)}function xe(t,e){return Object.prototype.hasOwnProperty.call(t,e)}ue.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},ue.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var je=[],Re=[],De="undefined"!=typeof Uint8Array?Uint8Array:Array,Ae=!1;function Ne(){Ae=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0;e<64;++e)je[e]=t[e],Re[t.charCodeAt(e)]=e;Re["-".charCodeAt(0)]=62,Re["_".charCodeAt(0)]=63}function Ee(t){return je[t>>18&63]+je[t>>12&63]+je[t>>6&63]+je[63&t]}function Pe(t,e,r){for(var i,n=[],s=e;s<r;s+=3)i=(t[s]<<16)+(t[s+1]<<8)+t[s+2],n.push(Ee(i));return n.join("")}function Ie(t){var e;Ae||Ne();for(var r=t.length,i=r%3,n="",s=[],o=16383,a=0,c=r-i;a<c;a+=o)s.push(Pe(t,a,a+o>c?c:a+o));return 1===i?(e=t[r-1],n+=je[e>>2],n+=je[e<<4&63],n+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],n+=je[e>>10],n+=je[e>>4&63],n+=je[e<<2&63],n+="="),s.push(n),s.join("")}function Ce(t,e,r,i,n){var s,o,a=8*n-i-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?n-1:0,f=r?-1:1,d=t[e+h];for(h+=f,s=d&(1<<-l)-1,d>>=-l,l+=a;l>0;s=256*s+t[e+h],h+=f,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=i;l>0;o=256*o+t[e+h],h+=f,l-=8);if(0===s)s=1-u;else{if(s===c)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,i),s-=u}return(d?-1:1)*o*Math.pow(2,s-i)}function Me(t,e,r,i,n,s){var o,a,c,u=8*s-n-1,l=(1<<u)-1,h=l>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:s-1,p=i?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=l):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),(e+=o+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(e*c-1)*Math.pow(2,n),o+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,n),o=0));n>=8;t[r+d]=255&a,d+=p,a/=256,n-=8);for(o=o<<n|a,u+=n;u>0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*m}var Te={}.toString,$e=Array.isArray||function(t){return"[object Array]"==Te.call(t)};function Le(){return Be.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Ue(t,e){if(Le()<e)throw new RangeError("Invalid typed array length");return Be.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Be.prototype:(null===t&&(t=new Be(e)),t.length=e),t}function Be(t,e,r){if(!(Be.TYPED_ARRAY_SUPPORT||this instanceof Be))return new Be(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return ze(this,t)}return Fe(this,t,e,r)}function Fe(t,e,r,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,r,i){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");e=void 0===r&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,r):new Uint8Array(e,r,i);Be.TYPED_ARRAY_SUPPORT?(t=e).__proto__=Be.prototype:t=Ke(t,e);return t}(t,e,r,i):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!Be.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|We(e,r);t=Ue(t,i);var n=t.write(e,r);n!==i&&(t=t.slice(0,n));return t}(t,e,r):function(t,e){if(He(e)){var r=0|qe(e.length);return 0===(t=Ue(t,r)).length||e.copy(t,0,0,r),t}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(i=e.length)!=i?Ue(t,0):Ke(t,e);if("Buffer"===e.type&&$e(e.data))return Ke(t,e.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function Ve(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function ze(t,e){if(Ve(e),t=Ue(t,e<0?0:0|qe(e)),!Be.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function Ke(t,e){var r=e.length<0?0:0|qe(e.length);t=Ue(t,r);for(var i=0;i<r;i+=1)t[i]=255&e[i];return t}function qe(t){if(t>=Le())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Le().toString(16)+" bytes");return 0|t}function He(t){return!(null==t||!t._isBuffer)}function We(t,e){if(He(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return vr(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return kr(t).length;default:if(i)return vr(t).length;e=(""+e).toLowerCase(),i=!0}}function Je(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return ur(this,e,r);case"utf8":case"utf-8":return sr(this,e,r);case"ascii":return ar(this,e,r);case"latin1":case"binary":return cr(this,e,r);case"base64":return nr(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return lr(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function Ye(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function Ge(t,e,r,i,n){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(n)return-1;r=t.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof e&&(e=Be.from(e,i)),He(e))return 0===e.length?-1:Ze(t,e,r,i,n);if("number"==typeof e)return e&=255,Be.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Ze(t,[e],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Ze(t,e,r,i,n){var s,o=1,a=t.length,c=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;o=2,a/=2,c/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(n){var l=-1;for(s=r;s<a;s++)if(u(t,s)===u(e,-1===l?0:s-l)){if(-1===l&&(l=s),s-l+1===c)return l*o}else-1!==l&&(s-=s-l),l=-1}else for(r+c>a&&(r=a-c),s=r;s>=0;s--){for(var h=!0,f=0;f<c;f++)if(u(t,s+f)!==u(e,f)){h=!1;break}if(h)return s}return-1}function Qe(t,e,r,i){r=Number(r)||0;var n=t.length-r;i?(i=Number(i))>n&&(i=n):i=n;var s=e.length;if(s%2!=0)throw new TypeError("Invalid hex string");i>s/2&&(i=s/2);for(var o=0;o<i;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[r+o]=a}return o}function Xe(t,e,r,i){return Or(vr(e,t.length-r),t,r,i)}function tr(t,e,r,i){return Or(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,i)}function er(t,e,r,i){return tr(t,e,r,i)}function rr(t,e,r,i){return Or(kr(e),t,r,i)}function ir(t,e,r,i){return Or(function(t,e){for(var r,i,n,s=[],o=0;o<t.length&&!((e-=2)<0);++o)i=(r=t.charCodeAt(o))>>8,n=r%256,s.push(n),s.push(i);return s}(e,t.length-r),t,r,i)}function nr(t,e,r){return 0===e&&r===t.length?Ie(t):Ie(t.slice(e,r))}function sr(t,e,r){r=Math.min(t.length,r);for(var i=[],n=e;n<r;){var s,o,a,c,u=t[n],l=null,h=u>239?4:u>223?3:u>191?2:1;if(n+h<=r)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(s=t[n+1]))&&(c=(31&u)<<6|63&s)>127&&(l=c);break;case 3:s=t[n+1],o=t[n+2],128==(192&s)&&128==(192&o)&&(c=(15&u)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:s=t[n+1],o=t[n+2],a=t[n+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(c=(15&u)<<18|(63&s)<<12|(63&o)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|1023&l),i.push(l),n+=h}return function(t){var e=t.length;if(e<=or)return String.fromCharCode.apply(String,t);var r="",i=0;for(;i<e;)r+=String.fromCharCode.apply(String,t.slice(i,i+=or));return r}(i)}Be.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT,Le(),Be.poolSize=8192,Be._augment=function(t){return t.__proto__=Be.prototype,t},Be.from=function(t,e,r){return Fe(null,t,e,r)},Be.TYPED_ARRAY_SUPPORT&&(Be.prototype.__proto__=Uint8Array.prototype,Be.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Be[Symbol.species]),Be.alloc=function(t,e,r){return function(t,e,r,i){return Ve(e),e<=0?Ue(t,e):void 0!==r?"string"==typeof i?Ue(t,e).fill(r,i):Ue(t,e).fill(r):Ue(t,e)}(null,t,e,r)},Be.allocUnsafe=function(t){return ze(null,t)},Be.allocUnsafeSlow=function(t){return ze(null,t)},Be.isBuffer=function(t){return null!=t&&(!!t._isBuffer||Sr(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&Sr(t.slice(0,0))}(t))},Be.compare=function(t,e){if(!He(t)||!He(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,i=e.length,n=0,s=Math.min(r,i);n<s;++n)if(t[n]!==e[n]){r=t[n],i=e[n];break}return r<i?-1:i<r?1:0},Be.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Be.concat=function(t,e){if(!$e(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Be.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var i=Be.allocUnsafe(e),n=0;for(r=0;r<t.length;++r){var s=t[r];if(!He(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(i,n),n+=s.length}return i},Be.byteLength=We,Be.prototype._isBuffer=!0,Be.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)Ye(this,e,e+1);return this},Be.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)Ye(this,e,e+3),Ye(this,e+1,e+2);return this},Be.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)Ye(this,e,e+7),Ye(this,e+1,e+6),Ye(this,e+2,e+5),Ye(this,e+3,e+4);return this},Be.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?sr(this,0,t):Je.apply(this,arguments)},Be.prototype.equals=function(t){if(!He(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Be.compare(this,t)},Be.prototype.inspect=function(){var t="";return this.length>0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),"<Buffer "+t+">"},Be.prototype.compare=function(t,e,r,i,n){if(!He(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),e<0||r>t.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&e>=r)return 0;if(i>=n)return-1;if(e>=r)return 1;if(this===t)return 0;for(var s=(n>>>=0)-(i>>>=0),o=(r>>>=0)-(e>>>=0),a=Math.min(s,o),c=this.slice(i,n),u=t.slice(e,r),l=0;l<a;++l)if(c[l]!==u[l]){s=c[l],o=u[l];break}return s<o?-1:o<s?1:0},Be.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},Be.prototype.indexOf=function(t,e,r){return Ge(this,t,e,r,!0)},Be.prototype.lastIndexOf=function(t,e,r){return Ge(this,t,e,r,!1)},Be.prototype.write=function(t,e,r,i){if(void 0===e)i="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)i=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(r)?(r|=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var n=this.length-e;if((void 0===r||r>n)&&(r=n),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return Qe(this,t,e,r);case"utf8":case"utf-8":return Xe(this,t,e,r);case"ascii":return tr(this,t,e,r);case"latin1":case"binary":return er(this,t,e,r);case"base64":return rr(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ir(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}},Be.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var or=4096;function ar(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;n<r;++n)i+=String.fromCharCode(127&t[n]);return i}function cr(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;n<r;++n)i+=String.fromCharCode(t[n]);return i}function ur(t,e,r){var i=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>i)&&(r=i);for(var n="",s=e;s<r;++s)n+=wr(t[s]);return n}function lr(t,e,r){for(var i=t.slice(e,r),n="",s=0;s<i.length;s+=2)n+=String.fromCharCode(i[s]+256*i[s+1]);return n}function hr(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function fr(t,e,r,i,n,s){if(!He(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<s)throw new RangeError('"value" argument is out of bounds');if(r+i>t.length)throw new RangeError("Index out of range")}function dr(t,e,r,i){e<0&&(e=65535+e+1);for(var n=0,s=Math.min(t.length-r,2);n<s;++n)t[r+n]=(e&255<<8*(i?n:1-n))>>>8*(i?n:1-n)}function pr(t,e,r,i){e<0&&(e=4294967295+e+1);for(var n=0,s=Math.min(t.length-r,4);n<s;++n)t[r+n]=e>>>8*(i?n:3-n)&255}function mr(t,e,r,i,n,s){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function gr(t,e,r,i,n){return n||mr(t,0,r,4),Me(t,e,r,i,23,4),r+4}function yr(t,e,r,i,n){return n||mr(t,0,r,8),Me(t,e,r,i,52,8),r+8}Be.prototype.slice=function(t,e){var r,i=this.length;if((t=~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),(e=void 0===e?i:~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t),Be.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=Be.prototype;else{var n=e-t;r=new Be(n,void 0);for(var s=0;s<n;++s)r[s]=this[s+t]}return r},Be.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||hr(t,e,this.length);for(var i=this[t],n=1,s=0;++s<e&&(n*=256);)i+=this[t+s]*n;return i},Be.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||hr(t,e,this.length);for(var i=this[t+--e],n=1;e>0&&(n*=256);)i+=this[t+--e]*n;return i},Be.prototype.readUInt8=function(t,e){return e||hr(t,1,this.length),this[t]},Be.prototype.readUInt16LE=function(t,e){return e||hr(t,2,this.length),this[t]|this[t+1]<<8},Be.prototype.readUInt16BE=function(t,e){return e||hr(t,2,this.length),this[t]<<8|this[t+1]},Be.prototype.readUInt32LE=function(t,e){return e||hr(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Be.prototype.readUInt32BE=function(t,e){return e||hr(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Be.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||hr(t,e,this.length);for(var i=this[t],n=1,s=0;++s<e&&(n*=256);)i+=this[t+s]*n;return i>=(n*=128)&&(i-=Math.pow(2,8*e)),i},Be.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||hr(t,e,this.length);for(var i=e,n=1,s=this[t+--i];i>0&&(n*=256);)s+=this[t+--i]*n;return s>=(n*=128)&&(s-=Math.pow(2,8*e)),s},Be.prototype.readInt8=function(t,e){return e||hr(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Be.prototype.readInt16LE=function(t,e){e||hr(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Be.prototype.readInt16BE=function(t,e){e||hr(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Be.prototype.readInt32LE=function(t,e){return e||hr(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Be.prototype.readInt32BE=function(t,e){return e||hr(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Be.prototype.readFloatLE=function(t,e){return e||hr(t,4,this.length),Ce(this,t,!0,23,4)},Be.prototype.readFloatBE=function(t,e){return e||hr(t,4,this.length),Ce(this,t,!1,23,4)},Be.prototype.readDoubleLE=function(t,e){return e||hr(t,8,this.length),Ce(this,t,!0,52,8)},Be.prototype.readDoubleBE=function(t,e){return e||hr(t,8,this.length),Ce(this,t,!1,52,8)},Be.prototype.writeUIntLE=function(t,e,r,i){(t=+t,e|=0,r|=0,i)||fr(this,t,e,r,Math.pow(2,8*r)-1,0);var n=1,s=0;for(this[e]=255&t;++s<r&&(n*=256);)this[e+s]=t/n&255;return e+r},Be.prototype.writeUIntBE=function(t,e,r,i){(t=+t,e|=0,r|=0,i)||fr(this,t,e,r,Math.pow(2,8*r)-1,0);var n=r-1,s=1;for(this[e+n]=255&t;--n>=0&&(s*=256);)this[e+n]=t/s&255;return e+r},Be.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,1,255,0),Be.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Be.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,2,65535,0),Be.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):dr(this,t,e,!0),e+2},Be.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,2,65535,0),Be.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):dr(this,t,e,!1),e+2},Be.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,4,4294967295,0),Be.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):pr(this,t,e,!0),e+4},Be.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,4,4294967295,0),Be.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):pr(this,t,e,!1),e+4},Be.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e|=0,!i){var n=Math.pow(2,8*r-1);fr(this,t,e,r,n-1,-n)}var s=0,o=1,a=0;for(this[e]=255&t;++s<r&&(o*=256);)t<0&&0===a&&0!==this[e+s-1]&&(a=1),this[e+s]=(t/o|0)-a&255;return e+r},Be.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e|=0,!i){var n=Math.pow(2,8*r-1);fr(this,t,e,r,n-1,-n)}var s=r-1,o=1,a=0;for(this[e+s]=255&t;--s>=0&&(o*=256);)t<0&&0===a&&0!==this[e+s+1]&&(a=1),this[e+s]=(t/o|0)-a&255;return e+r},Be.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,1,127,-128),Be.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Be.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,2,32767,-32768),Be.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):dr(this,t,e,!0),e+2},Be.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,2,32767,-32768),Be.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):dr(this,t,e,!1),e+2},Be.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,4,2147483647,-2147483648),Be.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):pr(this,t,e,!0),e+4},Be.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||fr(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Be.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):pr(this,t,e,!1),e+4},Be.prototype.writeFloatLE=function(t,e,r){return gr(this,t,e,!0,r)},Be.prototype.writeFloatBE=function(t,e,r){return gr(this,t,e,!1,r)},Be.prototype.writeDoubleLE=function(t,e,r){return yr(this,t,e,!0,r)},Be.prototype.writeDoubleBE=function(t,e,r){return yr(this,t,e,!1,r)},Be.prototype.copy=function(t,e,r,i){if(r||(r=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e<i-r&&(i=t.length-e+r);var n,s=i-r;if(this===t&&r<e&&e<i)for(n=s-1;n>=0;--n)t[n+e]=this[n+r];else if(s<1e3||!Be.TYPED_ARRAY_SUPPORT)for(n=0;n<s;++n)t[n+e]=this[n+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+s),e);return s},Be.prototype.fill=function(t,e,r,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),1===t.length){var n=t.charCodeAt(0);n<256&&(t=n)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!Be.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;var s;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(s=e;s<r;++s)this[s]=t;else{var o=He(t)?t:vr(new Be(t,i).toString()),a=o.length;for(s=0;s<r-e;++s)this[s+e]=o[s%a]}return this};var br=/[^+\/0-9A-Za-z-_]/g;function wr(t){return t<16?"0"+t.toString(16):t.toString(16)}function vr(t,e){var r;e=e||1/0;for(var i=t.length,n=null,s=[],o=0;o<i;++o){if((r=t.charCodeAt(o))>55295&&r<57344){if(!n){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===i){(e-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(e-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function kr(t){return function(t){var e,r,i,n,s,o;Ae||Ne();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===t[a-2]?2:"="===t[a-1]?1:0,o=new De(3*a/4-s),i=s>0?a-4:a;var c=0;for(e=0,r=0;e<i;e+=4,r+=3)n=Re[t.charCodeAt(e)]<<18|Re[t.charCodeAt(e+1)]<<12|Re[t.charCodeAt(e+2)]<<6|Re[t.charCodeAt(e+3)],o[c++]=n>>16&255,o[c++]=n>>8&255,o[c++]=255&n;return 2===s?(n=Re[t.charCodeAt(e)]<<2|Re[t.charCodeAt(e+1)]>>4,o[c++]=255&n):1===s&&(n=Re[t.charCodeAt(e)]<<10|Re[t.charCodeAt(e+1)]<<4|Re[t.charCodeAt(e+2)]>>2,o[c++]=n>>8&255,o[c++]=255&n),o}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(br,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Or(t,e,r,i){for(var n=0;n<i&&!(n+r>=e.length||n>=t.length);++n)e[n+r]=t[n];return n}function Sr(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function _r(){this.head=null,this.tail=null,this.length=0}_r.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},_r.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},_r.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},_r.prototype.clear=function(){this.head=this.tail=null,this.length=0},_r.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},_r.prototype.concat=function(t){if(0===this.length)return Be.alloc(0);if(1===this.length)return this.head.data;for(var e=Be.allocUnsafe(t>>>0),r=this.head,i=0;r;)r.data.copy(e,i),i+=r.data.length,r=r.next;return e};var xr=Be.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function jr(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!xr(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Dr;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Ar;break;default:return void(this.write=Rr)}this.charBuffer=new Be(6),this.charReceived=0,this.charLength=0}function Rr(t){return t.toString(this.encoding)}function Dr(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function Ar(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}jr.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";if(t=t.slice(r,t.length),!((n=(e=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(e.length-1))>=55296&&n<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var i=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,i),i-=this.charReceived);var n;i=(e+=t.toString(this.encoding,0,i)).length-1;if((n=e.charCodeAt(i))>=55296&&n<=56319){var s=this.surrogateSize;return this.charLength+=s,this.charReceived+=s,this.charBuffer.copy(this.charBuffer,s,0,s),t.copy(this.charBuffer,0,0,s),e.substring(0,i)}return e},jr.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},jr.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,n=this.encoding;e+=i.slice(0,r).toString(n)}return e},Pr.ReadableState=Er;var Nr=function(t){if(be(ae)&&(ae=ie.env.NODE_DEBUG||""),t=t.toUpperCase(),!ce[t])if(new RegExp("\\b"+t+"\\b","i").test(ae)){ce[t]=function(){var e=se.apply(null,arguments);console.error("%s %d: %s",t,0,e)}}else ce[t]=function(){};return ce[t]}("stream");function Er(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof oi&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new _r,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new jr(t.encoding),this.encoding=t.encoding)}function Pr(t){if(!(this instanceof Pr))return new Pr(t);this._readableState=new Er(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),St.call(this)}function Ir(t,e,r,i,n){var s=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(s)t.emit("error",s);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,Tr(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!n){var o=new Error("stream.push() after EOF");t.emit("error",o)}else if(e.endEmitted&&n){var a=new Error("stream.unshift() after end event");t.emit("error",a)}else{var c;!e.decoder||n||i||(r=e.decoder.write(r),c=!e.objectMode&&0===r.length),n||(e.reading=!1),c||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&Tr(t))),function(t,e){e.readingMore||(e.readingMore=!0,te(Lr,t,e))}(t,e)}else n||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(e)}re(Pr,St),Pr.prototype.push=function(t,e){var r=this._readableState;return r.objectMode||"string"!=typeof t||(e=e||r.defaultEncoding)!==r.encoding&&(t=Buffer.from(t,e),e=""),Ir(this,r,t,e,!1)},Pr.prototype.unshift=function(t){return Ir(this,this._readableState,t,"",!0)},Pr.prototype.isPaused=function(){return!1===this._readableState.flowing},Pr.prototype.setEncoding=function(t){return this._readableState.decoder=new jr(t),this._readableState.encoding=t,this};var Cr=8388608;function Mr(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=Cr?t=Cr:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Tr(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Nr("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?te($r,t):$r(t))}function $r(t){Nr("emit readable"),t.emit("readable"),Fr(t)}function Lr(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(Nr("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function Ur(t){Nr("readable nexttick read 0"),t.read(0)}function Br(t,e){e.reading||(Nr("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),Fr(t),e.flowing&&!e.reading&&t.read(0)}function Fr(t){var e=t._readableState;for(Nr("flow",e.flowing);e.flowing&&null!==t.read(););}function Vr(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var i;t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,i=1,n=r.data;t-=n.length;for(;r=r.next;){var s=r.data,o=t>s.length?s.length:t;if(o===s.length?n+=s:n+=s.slice(0,t),0===(t-=o)){o===s.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=s.slice(o));break}++i}return e.length-=i,n}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),i=e.head,n=1;i.data.copy(r),t-=i.data.length;for(;i=i.next;){var s=i.data,o=t>s.length?s.length:t;if(s.copy(r,r.length-t,0,o),0===(t-=o)){o===s.length?(++n,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=s.slice(o));break}++n}return e.length-=n,r}(t,e);return i}(t,e.buffer,e.decoder),r);var r}function zr(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,te(Kr,e,t))}function Kr(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function qr(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}function Hr(){}function Wr(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function Jr(t,e){Object.defineProperty(this,"buffer",{get:oe(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),t=t||{},this.objectMode=!!t.objectMode,e instanceof oi&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,i=r.sync,n=r.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,i,n){--e.pendingcb,r?te(n,i):n(i);t._writableState.errorEmitted=!0,t.emit("error",i)}(t,r,i,e,n);else{var s=Xr(r);s||r.corked||r.bufferProcessing||!r.bufferedRequest||Qr(t,r),i?te(Zr,t,r,s,n):Zr(t,r,s,n)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new ri(this)}function Yr(t){if(!(this instanceof Yr||this instanceof oi))return new Yr(t);this._writableState=new Jr(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev)),St.call(this)}function Gr(t,e,r,i,n,s,o){e.writelen=i,e.writecb=o,e.writing=!0,e.sync=!0,r?t._writev(n,e.onwrite):t._write(n,s,e.onwrite),e.sync=!1}function Zr(t,e,r,i){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,i(),ei(t,e)}function Qr(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,n=new Array(i),s=e.corkedRequestsFree;s.entry=r;for(var o=0;r;)n[o]=r,r=r.next,o+=1;Gr(t,e,!0,e.length,n,"",s.finish),e.pendingcb++,e.lastBufferedRequest=null,s.next?(e.corkedRequestsFree=s.next,s.next=null):e.corkedRequestsFree=new ri(e)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(Gr(t,e,!1,e.objectMode?1:a.length,a,c,u),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function Xr(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function ti(t,e){e.prefinished||(e.prefinished=!0,t.emit("prefinish"))}function ei(t,e){var r=Xr(e);return r&&(0===e.pendingcb?(ti(t,e),e.finished=!0,t.emit("finish")):ti(t,e)),r}function ri(t){var e=this;this.next=null,this.entry=null,this.finish=function(r){var i=e.entry;for(e.entry=null;i;){var n=i.callback;t.pendingcb--,n(r),i=i.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}}Pr.prototype.read=function(t){Nr("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return Nr("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?zr(this):Tr(this),null;if(0===(t=Mr(t,e))&&e.ended)return 0===e.length&&zr(this),null;var i,n=e.needReadable;return Nr("need readable",n),(0===e.length||e.length-t<e.highWaterMark)&&Nr("length less than watermark",n=!0),e.ended||e.reading?Nr("reading or ended",n=!1):n&&(Nr("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=Mr(r,e))),null===(i=t>0?Vr(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&zr(this)),null!==i&&this.emit("data",i),i},Pr.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Pr.prototype.pipe=function(t,e){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=t;break;case 1:i.pipes=[i.pipes,t];break;default:i.pipes.push(t)}i.pipesCount+=1,Nr("pipe count=%d opts=%j",i.pipesCount,e);var n=!e||!1!==e.end?o:u;function s(t){Nr("onunpipe"),t===r&&u()}function o(){Nr("onend"),t.end()}i.endEmitted?te(n):r.once("end",n),t.on("unpipe",s);var a=function(t){return function(){var e=t._readableState;Nr("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Fr(t))}}(r);t.on("drain",a);var c=!1;function u(){Nr("cleanup"),t.removeListener("close",d),t.removeListener("finish",p),t.removeListener("drain",a),t.removeListener("error",f),t.removeListener("unpipe",s),r.removeListener("end",o),r.removeListener("end",u),r.removeListener("data",h),c=!0,!i.awaitDrain||t._writableState&&!t._writableState.needDrain||a()}var l=!1;function h(e){Nr("ondata"),l=!1,!1!==t.write(e)||l||((1===i.pipesCount&&i.pipes===t||i.pipesCount>1&&-1!==qr(i.pipes,t))&&!c&&(Nr("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function f(e){var r;Nr("onerror",e),m(),t.removeListener("error",f),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function d(){t.removeListener("finish",p),m()}function p(){Nr("onfinish"),t.removeListener("close",d),m()}function m(){Nr("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",d),t.once("finish",p),t.emit("pipe",r),i.flowing||(Nr("pipe resume"),r.resume()),t},Pr.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var n=0;n<i;n++)r[n].emit("unpipe",this);return this}var s=qr(e.pipes,t);return-1===s||(e.pipes.splice(s,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this)),this},Pr.prototype.on=function(t,e){var r=St.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&Tr(this):te(Ur,this))}return r},Pr.prototype.addListener=Pr.prototype.on,Pr.prototype.resume=function(){var t=this._readableState;return t.flowing||(Nr("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,te(Br,t,e))}(this,t)),this},Pr.prototype.pause=function(){return Nr("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Nr("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Pr.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;for(var n in t.on("end",function(){if(Nr("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(n){(Nr("wrapped data"),e.decoder&&(n=e.decoder.write(n)),e.objectMode&&null==n)||(e.objectMode||n&&n.length)&&(i.push(n)||(r=!0,t.pause()))}),t)void 0===this[n]&&"function"==typeof t[n]&&(this[n]=function(e){return function(){return t[e].apply(t,arguments)}}(n));return function(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}(["error","close","destroy","pause","resume"],function(e){t.on(e,i.emit.bind(i,e))}),i._read=function(e){Nr("wrapped _read",e),r&&(r=!1,t.resume())},i},Pr._fromList=Vr,Yr.WritableState=Jr,re(Yr,St),Jr.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},Yr.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Yr.prototype.write=function(t,e,r){var i=this._writableState,n=!1;return"function"==typeof e&&(r=e,e=null),Be.isBuffer(t)?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=Hr),i.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),te(e,r)}(this,r):function(t,e,r,i){var n=!0,s=!1;return null===r?s=new TypeError("May not write null values to stream"):Be.isBuffer(r)||"string"==typeof r||void 0===r||e.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(t.emit("error",s),te(i,s),n=!1),n}(this,i,t,r)&&(i.pendingcb++,n=function(t,e,r,i,n){r=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Be.from(e,r));return e}(e,r,i),Be.isBuffer(r)&&(i="buffer");var s=e.objectMode?1:r.length;e.length+=s;var o=e.length<e.highWaterMark;o||(e.needDrain=!0);if(e.writing||e.corked){var a=e.lastBufferedRequest;e.lastBufferedRequest=new Wr(r,i,n),a?a.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else Gr(t,e,!1,s,r,i,n);return o}(this,i,t,e,r)),n},Yr.prototype.cork=function(){this._writableState.corked++},Yr.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||Qr(this,t))},Yr.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Yr.prototype._write=function(t,e,r){r(new Error("not implemented"))},Yr.prototype._writev=null,Yr.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(t,e,r){e.ending=!0,ei(t,e),r&&(e.finished?te(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,i,r)},re(oi,Pr);for(var ii=Object.keys(Yr.prototype),ni=0;ni<ii.length;ni++){var si=ii[ni];oi.prototype[si]||(oi.prototype[si]=Yr.prototype[si])}function oi(t){if(!(this instanceof oi))return new oi(t);Pr.call(this,t),Yr.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",ai)}function ai(){this.allowHalfOpen||this._writableState.ended||te(ci,this)}function ci(t){t.end()}function ui(t){this.afterTransform=function(e,r){return function(t,e,r){var i=t._transformState;i.transforming=!1;var n=i.writecb;if(!n)return t.emit("error",new Error("no writecb in Transform class"));i.writechunk=null,i.writecb=null,null!=r&&t.push(r);n(e);var s=t._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&t._read(s.highWaterMark)}(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function li(t){if(!(this instanceof li))return new li(t);oi.call(this,t),this._transformState=new ui(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t){hi(e,t)}):hi(e)})}function hi(t,e){if(e)return t.emit("error",e);var r=t._writableState,i=t._transformState;if(r.length)throw new Error("Calling transform done when ws.length != 0");if(i.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}function fi(t){if(!(this instanceof fi))return new fi(t);li.call(this,t)}function di(){St.call(this)}re(li,oi),li.prototype.push=function(t,e){return this._transformState.needTransform=!1,oi.prototype.push.call(this,t,e)},li.prototype._transform=function(t,e,r){throw new Error("Not implemented")},li.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}},li.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},re(fi,li),fi.prototype._transform=function(t,e,r){r(null,t)},re(di,St),di.Readable=Pr,di.Writable=Yr,di.Duplex=oi,di.Transform=li,di.PassThrough=fi,di.Stream=di,di.prototype.pipe=function(t,e){var r=this;function i(e){t.writable&&!1===t.write(e)&&r.pause&&r.pause()}function n(){r.readable&&r.resume&&r.resume()}r.on("data",i),t.on("drain",n),t._isStdio||e&&!1===e.end||(r.on("end",o),r.on("close",a));var s=!1;function o(){s||(s=!0,t.end())}function a(){s||(s=!0,"function"==typeof t.destroy&&t.destroy())}function c(t){if(u(),0===St.listenerCount(this,"error"))throw t}function u(){r.removeListener("data",i),t.removeListener("drain",n),r.removeListener("end",o),r.removeListener("close",a),r.removeListener("error",c),t.removeListener("error",c),r.removeListener("end",u),r.removeListener("close",u),t.removeListener("close",u)}return r.on("error",c),t.on("error",c),r.on("end",u),r.on("close",u),t.on("close",u),t.emit("pipe",r),t};class pi extends St{constructor({resource:t}){super(),this.resource=t,this.client=t.client,this.stream=new n({highWaterMark:3*this.client.parallelism,start:this._start.bind(this),pull:this._pull.bind(this),cancel:this._cancel.bind(this)})}build(){return this.stream.getReader()}async _start(t){this.controller=t,this.continuationToken=null,this.closeNextIteration=!1}async _pull(t){if(this.closeNextIteration)return void t.close();const e=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),r=e?.Contents.map(t=>t.Key).map(t=>t.replace(this.client.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t).map(t=>t.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=e.NextContinuationToken,this.enqueue(r),e.IsTruncated||(this.closeNextIteration=!0)}enqueue(t){t.forEach(t=>{this.controller.enqueue(t),this.emit("id",t)})}_cancel(t){}}var mi=pi;class gi extends mi{enqueue(t){this.controller.enqueue(t),this.emit("page",t)}}class yi extends St{constructor({resource:t,batchSize:e=10,concurrency:r=5}){if(super(),!t)throw new Error("Resource is required for ResourceReader");this.resource=t,this.client=t.client,this.batchSize=e,this.concurrency=r,this.input=new gi({resource:this.resource}),this.transform=new li({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",t=>{this.transform.write(t)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",t=>{this.emit("error",t)}),this.transform.on("data",t=>{this.emit("data",t)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",t=>{this.emit("error",t)})}build(){return this}async _transform(t,e,r){const[n,s]=await ft(async()=>{await i.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{const e=await this.resource.get(t);return this.push(e),e})});r(s)}resume(){this.input.resume()}}class bi extends St{constructor({resource:t,batchSize:e=10,concurrency:r=5}){super(),this.resource=t,this.client=t.client,this.batchSize=e,this.concurrency=r,this.buffer=[],this.writing=!1,this.writable=new Yr({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",t=>{this.emit("error",t)})}build(){return this}write(t){return this.buffer.push(t),this._maybeWrite().catch(t=>{this.emit("error",t)}),!0}end(){this.ended=!0,this._maybeWrite().catch(t=>{this.emit("error",t)})}async _maybeWrite(){if(!this.writing&&(0!==this.buffer.length||this.ended)){for(this.writing=!0;this.buffer.length>0;){const t=this.buffer.splice(0,this.batchSize),[e,r]=await ft(async()=>{await i.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{const[e,r,i]=await ft(async()=>await this.resource.insert(t));return e?i:(this.emit("error",r,t),null)})});e||this.emit("error",r)}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(t,e,r){r()}}function wi(t){return new Promise((e,r)=>{if(!t)return r(new Error("streamToString: stream is undefined"));const i=[];t.on("data",t=>i.push(t)),t.on("error",r),t.on("end",()=>e(Buffer.concat(i).toString("utf-8")))})}var vi=class extends Vt{constructor({client:t,keyPrefix:e="cache",ttl:r=0,prefix:i}){super({client:t,keyPrefix:e,ttl:r,prefix:i}),this.client=t,this.keyPrefix=e,this.config.ttl=r,this.config.client=t,this.config.prefix=void 0!==i?i:e+(e.endsWith("/")?"":"/")}async _set(t,e){let i=JSON.stringify(e);const n=i.length;return i=r.gzipSync(i).toString("base64"),this.client.putObject({key:Lt(this.keyPrefix,t),body:i,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(n),"length-compressed":String(i.length),"compression-gain":(i.length/n).toFixed(2)}})}async _get(t){const[e,i,n]=await ft(async()=>{const{Body:e}=await this.client.getObject(Lt(this.keyPrefix,t));let i=await wi(e);return i=Buffer.from(i,"base64"),i=r.unzipSync(i).toString(),JSON.parse(i)});if(e)return n;if("NoSuchKey"===i.name||"NotFound"===i.name)return null;throw i}async _del(t){return await this.client.deleteObject(Lt(this.keyPrefix,t)),!0}async _clear(){const t=await this.client.getAllKeys({prefix:this.keyPrefix});await this.client.deleteObjects(t)}async size(){return(await this.keys()).length}async keys(){const t=await this.client.getAllKeys({prefix:this.keyPrefix}),e=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return t.map(t=>t.startsWith(e)?t.slice(e.length):t)}};var ki=class extends Vt{constructor(t={}){super(t),this.cache={},this.meta={},this.maxSize=t.maxSize||0,this.ttl=t.ttl||0}async _set(t,e){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const t=Object.entries(this.meta).sort((t,e)=>t[1].ts-e[1].ts)[0]?.[0];t&&(delete this.cache[t],delete this.meta[t])}return this.cache[t]=e,this.meta[t]={ts:Date.now()},e}async _get(t){if(!Object.prototype.hasOwnProperty.call(this.cache,t))return null;if(this.ttl>0){const e=Date.now(),r=this.meta[t];if(r&&e-r.ts>1e3*this.ttl)return delete this.cache[t],delete this.meta[t],null}return this.cache[t]}async _del(t){return delete this.cache[t],delete this.meta[t],!0}async _clear(t){if(!t)return this.cache={},this.meta={},!0;for(const e of Object.keys(this.cache))e.startsWith(t)&&(delete this.cache[e],delete this.meta[e]);return!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}};class Oi extends At{constructor(t={}){super(t),this.driver=t.driver,this.config={includePartitions:!1!==t.includePartitions,...t}}async setup(t){await super.setup(t)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new ki(this.config.memoryOptions||{}):this.driver=new vi({client:this.database.client,...this.config.s3Options||{}}),this.installDatabaseProxy(),this.installResourceHooks()}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._cacheProxyInstalled)return;const t=this.installResourceHooks.bind(this);this.database._originalCreateResourceForCache=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResourceForCache(...e);return t(r),r},this.database._cacheProxyInstalled=!0}installResourceHooks(){for(const t of Object.values(this.database.resources))this.installResourceHooksForResource(t)}installResourceHooksForResource(t){if(!this.driver)return;Object.defineProperty(t,"cache",{value:this.driver,writable:!0,configurable:!0,enumerable:!1}),t.cacheKeyFor=async(e={})=>{const{action:r,params:i={},partition:n,partitionValues:s}=e;return this.generateCacheKey(t,r,i,n,s)};const e=["count","listIds","getMany","getAll","page","list","get"];for(const r of e)t.useMiddleware(r,async(e,i)=>{let n;if("getMany"===r)n=await t.cacheKeyFor({action:r,params:{ids:e.args[0]}});else if("page"===r){const{offset:i,size:s,partition:o,partitionValues:a}=e.args[0]||{};n=await t.cacheKeyFor({action:r,params:{offset:i,size:s},partition:o,partitionValues:a})}else if("list"===r||"listIds"===r||"count"===r){const{partition:i,partitionValues:s}=e.args[0]||{};n=await t.cacheKeyFor({action:r,partition:i,partitionValues:s})}else"getAll"===r?n=await t.cacheKeyFor({action:r}):"get"===r&&(n=await t.cacheKeyFor({action:r,params:{id:e.args[0]}}));const[s,o,a]=await ft(()=>t.cache.get(n));if(s&&null!=a)return a;if(!s&&"NoSuchKey"!==o.name)throw o;const c=await i();return await t.cache.set(n,c),c});const r=["insert","update","delete","deleteMany"];for(const e of r)t.useMiddleware(e,async(r,i)=>{const n=await i();if("insert"===e)await this.clearCacheForResource(t,r.args[0]);else if("update"===e)await this.clearCacheForResource(t,{id:r.args[0],...r.args[1]});else if("delete"===e){let e={id:r.args[0]};if("function"==typeof t.get){const[i,n,s]=await ft(()=>t.get(r.args[0]));i&&s&&(e=s)}await this.clearCacheForResource(t,e)}else"deleteMany"===e&&await this.clearCacheForResource(t);return n})}async clearCacheForResource(t,e){if(!t.cache)return;const r=`resource=${t.name}`;if(await t.cache.clear(r),!0===this.config.includePartitions&&t.config?.partitions&&Object.keys(t.config.partitions).length>0)if(e){const i=this.getPartitionValues(e,t);for(const[e,n]of Object.entries(i))if(n&&Object.keys(n).length>0&&Object.values(n).some(t=>null!=t)){const i=Lt(r,`partition=${e}`);await t.cache.clear(i)}}else for(const e of Object.keys(t.config.partitions)){const i=Lt(r,`partition=${e}`);await t.cache.clear(i)}}async generateCacheKey(t,e,r={},i=null,n=null){const s=[`resource=${t.name}`,`action=${e}`];if(i&&n&&Object.keys(n).length>0){s.push(`partition:${i}`);for(const[t,e]of Object.entries(n))null!=e&&s.push(`${t}:${e}`)}if(Object.keys(r).length>0){const t=await this.hashParams(r);s.push(t)}return Lt(...s)+".json.gz"}async hashParams(t){const e=Object.keys(t).sort().map(e=>`${e}:${t[e]}`).join("|")||"empty";return await pt(e)}async getCacheStats(){return this.driver?{size:await this.driver.size(),keys:await this.driver.keys(),driver:this.driver.constructor.name}:null}async clearAllCache(){if(this.driver)for(const t of Object.values(this.database.resources))if(t.cache){const e=`resource=${t.name}`;await t.cache.clear(e)}}async warmCache(t,e={}){const r=this.database.resources[t];if(!r)throw new Error(`Resource '${t}' not found`);const{includePartitions:i=!0}=e;if(await r.getAll(),i&&r.config.partitions)for(const[t,e]of Object.entries(r.config.partitions))if(e.fields){const e=await r.getAll(),i=Array.isArray(e)?e:[],n=new Set;for(const e of i.slice(0,10)){const i=this.getPartitionValues(e,r);i[t]&&n.add(JSON.stringify(i[t]))}for(const e of n){const i=JSON.parse(e);await r.list({partition:t,partitionValues:i})}}}}const Si={async setup(t){t&&t.client&&(this.client=t.client,this.map={PutObjectCommand:"put",GetObjectCommand:"get",HeadObjectCommand:"head",DeleteObjectCommand:"delete",DeleteObjectsCommand:"delete",ListObjectsV2Command:"list"},this.costs={total:0,prices:{put:5e-6,copy:5e-6,list:5e-6,post:5e-6,get:4e-4/1e3,select:4e-4/1e3,delete:4e-4/1e3,head:4e-4/1e3},requests:{total:0,put:0,post:0,copy:0,list:0,get:0,select:0,delete:0,head:0},events:{total:0,PutObjectCommand:0,GetObjectCommand:0,HeadObjectCommand:0,DeleteObjectCommand:0,DeleteObjectsCommand:0,ListObjectsV2Command:0}},this.client.costs=JSON.parse(JSON.stringify(this.costs)))},async start(){this.client&&(this.client.on("command.response",t=>this.addRequest(t,this.map[t])),this.client.on("command.error",t=>this.addRequest(t,this.map[t])))},addRequest(t,e){e&&(this.costs.events[t]++,this.costs.events.total++,this.costs.requests.total++,this.costs.requests[e]++,this.costs.total+=this.costs.prices[e],this.client&&this.client.costs&&(this.client.costs.events[t]++,this.client.costs.events.total++,this.client.costs.requests.total++,this.client.costs.requests[e]++,this.client.costs.total+=this.client.costs.prices[e]))}};class _i extends At{constructor(t={}){super(),this.indexResource=null,this.config={minWordLength:t.minWordLength||3,maxResults:t.maxResults||100,...t},this.indexes=new Map}async setup(t){this.database=t;const[e,r,i]=await ft(()=>t.createResource({name:"fulltext_indexes",attributes:{id:"string|required",resourceName:"string|required",fieldName:"string|required",word:"string|required",recordIds:"json|required",count:"number|required",lastUpdated:"string|required"}}));this.indexResource=e?i:t.resources.fulltext_indexes,await this.loadIndexes(),this.installIndexingHooks()}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(!this.indexResource)return;const[t,e,r]=await ft(()=>this.indexResource.getAll());if(t)for(const t of r){const e=`${t.resourceName}:${t.fieldName}:${t.word}`;this.indexes.set(e,{recordIds:t.recordIds||[],count:t.count||0})}}async saveIndexes(){if(!this.indexResource)return;const[t,e]=await ft(async()=>{const t=await this.indexResource.getAll();for(const e of t)await this.indexResource.delete(e.id);for(const[t,e]of this.indexes.entries()){const[r,i,n]=t.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:i,word:n,recordIds:e.recordIds,count:e.count,lastUpdated:(new Date).toISOString()})}})}installIndexingHooks(){this.database.plugins||(this.database.plugins={}),this.database.plugins.fulltext=this;for(const t of Object.values(this.database.resources))"fulltext_indexes"!==t.name&&this.installResourceHooks(t);this.database._fulltextProxyInstalled||(this.database._previousCreateResourceForFullText=this.database.createResource,this.database.createResource=async function(...t){const e=await this._previousCreateResourceForFullText(...t);return this.plugins?.fulltext&&"fulltext_indexes"!==e.name&&this.plugins.fulltext.installResourceHooks(e),e},this.database._fulltextProxyInstalled=!0);for(const t of Object.values(this.database.resources))"fulltext_indexes"!==t.name&&this.installResourceHooks(t)}installResourceHooks(t){t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,this.wrapResourceMethod(t,"insert",async(e,r,i)=>{const[n]=r;return this.indexRecord(t.name,e.id,n).catch(console.error),e}),this.wrapResourceMethod(t,"update",async(e,r,i)=>{const[n,s]=r;return this.removeRecordFromIndex(t.name,n).catch(console.error),this.indexRecord(t.name,n,e).catch(console.error),e}),this.wrapResourceMethod(t,"delete",async(e,r,i)=>{const[n]=r;return this.removeRecordFromIndex(t.name,n).catch(console.error),e}),this.wrapResourceMethod(t,"deleteMany",async(e,r,i)=>{const[n]=r;for(const e of n)this.removeRecordFromIndex(t.name,e).catch(console.error);return e})}async indexRecord(t,e,r){const i=this.getIndexedFields(t);if(i&&0!==i.length)for(const n of i){const i=this.getFieldValue(r,n);if(!i)continue;const s=this.tokenize(i);for(const r of s){if(r.length<this.config.minWordLength)continue;const i=`${t}:${n}:${r.toLowerCase()}`,s=this.indexes.get(i)||{recordIds:[],count:0};s.recordIds.includes(e)||(s.recordIds.push(e),s.count=s.recordIds.length),this.indexes.set(i,s)}}}async removeRecordFromIndex(t,e){for(const[r,i]of this.indexes.entries())if(r.startsWith(`${t}:`)){const t=i.recordIds.indexOf(e);t>-1&&(i.recordIds.splice(t,1),i.count=i.recordIds.length,0===i.recordIds.length?this.indexes.delete(r):this.indexes.set(r,i))}}getFieldValue(t,e){if(!e.includes("."))return t&&void 0!==t[e]?t[e]:null;const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return null;i=i[t]}return i}tokenize(t){if(!t)return[];return String(t).toLowerCase().replace(/[^\w\s\u00C0-\u017F]/g," ").split(/\s+/).filter(t=>t.length>0)}getIndexedFields(t){if(this.config.fields)return this.config.fields;return{users:["name","email"],products:["name","description"],articles:["title","content"]}[t]||[]}async search(t,e,r={}){const{fields:i=null,limit:n=this.config.maxResults,offset:s=0,exactMatch:o=!1}=r;if(!e||0===e.trim().length)return[];const a=this.tokenize(e),c=new Map,u=i||this.getIndexedFields(t);if(0===u.length)return[];for(const e of a)if(!(e.length<this.config.minWordLength))for(const r of u)if(o){const i=`${t}:${r}:${e.toLowerCase()}`,n=this.indexes.get(i);if(n)for(const t of n.recordIds){const e=c.get(t)||0;c.set(t,e+1)}}else for(const[i,n]of this.indexes.entries())if(i.startsWith(`${t}:${r}:${e.toLowerCase()}`))for(const t of n.recordIds){const e=c.get(t)||0;c.set(t,e+1)}return Array.from(c.entries()).map(([t,e])=>({recordId:t,score:e})).sort((t,e)=>e.score-t.score).slice(s,s+n)}async searchRecords(t,e,r={}){const i=await this.search(t,e,r);if(0===i.length)return[];const n=this.database.resources[t];if(!n)throw new Error(`Resource '${t}' not found`);const s=i.map(t=>t.recordId);return(await n.getMany(s)).filter(t=>t&&"object"==typeof t).map(t=>{const e=i.find(e=>e.recordId===t.id);return{...t,_searchScore:e?e.score:0}}).sort((t,e)=>e._searchScore-t._searchScore)}async rebuildIndex(t){const e=this.database.resources[t];if(!e)throw new Error(`Resource '${t}' not found`);for(const[e]of this.indexes.entries())e.startsWith(`${t}:`)&&this.indexes.delete(e);const r=await e.getAll();for(let e=0;e<r.length;e+=100){const i=r.slice(e,e+100);for(const e of i){const[r,i]=await ft(()=>this.indexRecord(t,e.id,e))}}await this.saveIndexes()}async getIndexStats(){const t={totalIndexes:this.indexes.size,resources:{},totalWords:0};for(const[e,r]of this.indexes.entries()){const[i,n]=e.split(":");t.resources[i]||(t.resources[i]={fields:{},totalRecords:new Set,totalWords:0}),t.resources[i].fields[n]||(t.resources[i].fields[n]={words:0,totalOccurrences:0}),t.resources[i].fields[n].words++,t.resources[i].fields[n].totalOccurrences+=r.count,t.resources[i].totalWords++;for(const e of r.recordIds)t.resources[i].totalRecords.add(e);t.totalWords++}for(const e in t.resources)t.resources[e].totalRecords=t.resources[e].totalRecords.size;return t}async rebuildAllIndexes({timeout:t}={}){return t?Promise.race([this._rebuildAllIndexesInternal(),new Promise((e,r)=>setTimeout(()=>r(new Error("Timeout")),t))]):this._rebuildAllIndexesInternal()}async _rebuildAllIndexesInternal(){const t=Object.keys(this.database.resources).filter(t=>"fulltext_indexes"!==t);for(const e of t){const[t,r]=await ft(()=>this.rebuildIndex(e))}}async clearIndex(t){for(const[e]of this.indexes.entries())e.startsWith(`${t}:`)&&this.indexes.delete(e);await this.saveIndexes()}async clearAllIndexes(){this.indexes.clear(),await this.saveIndexes()}}class xi extends At{constructor(t={}){super(),this.config={collectPerformance:!1!==t.collectPerformance,collectErrors:!1!==t.collectErrors,collectUsage:!1!==t.collectUsage,retentionDays:t.retentionDays||30,flushInterval:t.flushInterval||6e4,...t},this.metrics={operations:{insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}},resources:{},errors:[],performance:[],startTime:(new Date).toISOString()},this.flushTimer=null}async setup(t){if(this.database=t,"test"===process.env.NODE_ENV)return;const[e,r]=await ft(async()=>{const[e,r,i]=await ft(()=>t.createResource({name:"metrics",attributes:{id:"string|required",type:"string|required",resourceName:"string",operation:"string",count:"number|required",totalTime:"number|required",errors:"number|required",avgTime:"number|required",timestamp:"string|required",metadata:"json"}}));this.metricsResource=e?i:t.resources.metrics;const[n,s,o]=await ft(()=>t.createResource({name:"error_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",error:"string|required",timestamp:"string|required",metadata:"json"}}));this.errorsResource=n?o:t.resources.error_logs;const[a,c,u]=await ft(()=>t.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}}));this.performanceResource=a?u:t.resources.performance_logs});e||(this.metricsResource=t.resources.metrics,this.errorsResource=t.resources.error_logs,this.performanceResource=t.resources.performance_logs),this.installMetricsHooks(),"test"!==process.env.NODE_ENV&&this.startFlushTimer()}async start(){}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"test"!==process.env.NODE_ENV&&await this.flushMetrics()}installMetricsHooks(){for(const t of Object.values(this.database.resources))["metrics","error_logs","performance_logs"].includes(t.name)||this.installResourceHooks(t);this.database._createResource=this.database.createResource,this.database.createResource=async function(...t){const e=await this._createResource(...t);return this.plugins?.metrics&&!["metrics","error_logs","performance_logs"].includes(e.name)&&this.plugins.metrics.installResourceHooks(e),e}}installResourceHooks(t){t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,t._get=t.get,t._getMany=t.getMany,t._getAll=t.getAll,t._list=t.list,t._listIds=t.listIds,t._count=t.count,t._page=t.page,t.insert=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._insert(...e));if(this.recordOperation(t.name,"insert",Date.now()-r,!i),i||this.recordError(t.name,"insert",n),!i)throw n;return s}.bind(this),t.update=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._update(...e));if(this.recordOperation(t.name,"update",Date.now()-r,!i),i||this.recordError(t.name,"update",n),!i)throw n;return s}.bind(this),t.delete=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._delete(...e));if(this.recordOperation(t.name,"delete",Date.now()-r,!i),i||this.recordError(t.name,"delete",n),!i)throw n;return s}.bind(this),t.deleteMany=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._deleteMany(...e));if(this.recordOperation(t.name,"delete",Date.now()-r,!i),i||this.recordError(t.name,"delete",n),!i)throw n;return s}.bind(this),t.get=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._get(...e));if(this.recordOperation(t.name,"get",Date.now()-r,!i),i||this.recordError(t.name,"get",n),!i)throw n;return s}.bind(this),t.getMany=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._getMany(...e));if(this.recordOperation(t.name,"get",Date.now()-r,!i),i||this.recordError(t.name,"get",n),!i)throw n;return s}.bind(this),t.getAll=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._getAll(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",n),!i)throw n;return s}.bind(this),t.list=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._list(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",n),!i)throw n;return s}.bind(this),t.listIds=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._listIds(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",n),!i)throw n;return s}.bind(this),t.count=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._count(...e));if(this.recordOperation(t.name,"count",Date.now()-r,!i),i||this.recordError(t.name,"count",n),!i)throw n;return s}.bind(this),t.page=async function(...e){const r=Date.now(),[i,n,s]=await ft(()=>t._page(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",n),!i)throw n;return s}.bind(this)}recordOperation(t,e,r,i){this.metrics.operations[e]&&(this.metrics.operations[e].count++,this.metrics.operations[e].totalTime+=r,i&&this.metrics.operations[e].errors++),this.metrics.resources[t]||(this.metrics.resources[t]={insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}}),this.metrics.resources[t][e]&&(this.metrics.resources[t][e].count++,this.metrics.resources[t][e].totalTime+=r,i&&this.metrics.resources[t][e].errors++),this.config.collectPerformance&&this.metrics.performance.push({resourceName:t,operation:e,duration:r,timestamp:(new Date).toISOString()})}recordError(t,e,r){this.config.collectErrors&&this.metrics.errors.push({resourceName:t,operation:e,error:r.message,stack:r.stack,timestamp:(new Date).toISOString()})}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flushMetrics().catch(console.error)},this.config.flushInterval))}async flushMetrics(){if(!this.metricsResource)return;const[t,e]=await ft(async()=>{const t="test"===process.env.NODE_ENV?{}:{global:"true"},e="test"===process.env.NODE_ENV?{}:{perf:"true"},r="test"===process.env.NODE_ENV?{}:{error:"true"},i="test"===process.env.NODE_ENV?{}:{resource:"true"};for(const[e,r]of Object.entries(this.metrics.operations))r.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:"global",operation:e,count:r.count,totalTime:r.totalTime,errors:r.errors,avgTime:r.count>0?r.totalTime/r.count:0,timestamp:(new Date).toISOString(),metadata:t});for(const[t,e]of Object.entries(this.metrics.resources))for(const[r,n]of Object.entries(e))n.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:t,operation:r,count:n.count,totalTime:n.totalTime,errors:n.errors,avgTime:n.count>0?n.totalTime/n.count:0,timestamp:(new Date).toISOString(),metadata:i});if(this.config.collectPerformance&&this.metrics.performance.length>0)for(const t of this.metrics.performance)await this.performanceResource.insert({id:`perf-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.resourceName,operation:t.operation,duration:t.duration,timestamp:t.timestamp,metadata:e});if(this.config.collectErrors&&this.metrics.errors.length>0)for(const t of this.metrics.errors)await this.errorsResource.insert({id:`error-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.resourceName,operation:t.operation,error:t.error,stack:t.stack,timestamp:t.timestamp,metadata:r});this.resetMetrics()});t||console.error("Failed to flush metrics:",e)}resetMetrics(){for(const t of Object.keys(this.metrics.operations))this.metrics.operations[t]={count:0,totalTime:0,errors:0};for(const t of Object.keys(this.metrics.resources))for(const e of Object.keys(this.metrics.resources[t]))this.metrics.resources[t][e]={count:0,totalTime:0,errors:0};this.metrics.performance=[],this.metrics.errors=[]}async getMetrics(t={}){const{type:e="operation",resourceName:r,operation:i,startDate:n,endDate:s,limit:o=100,offset:a=0}=t;if(!this.metricsResource)return[];let c=(await this.metricsResource.getAll()).filter(t=>(!e||t.type===e)&&((!r||t.resourceName===r)&&((!i||t.operation===i)&&(!(n&&new Date(t.timestamp)<new Date(n))&&!(s&&new Date(t.timestamp)>new Date(s))))));return c.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),c.slice(a,a+o)}async getErrorLogs(t={}){if(!this.errorsResource)return[];const{resourceName:e,operation:r,startDate:i,endDate:n,limit:s=100,offset:o=0}=t;let a=(await this.errorsResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(n&&new Date(t.timestamp)>new Date(n)))));return a.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),a.slice(o,o+s)}async getPerformanceLogs(t={}){if(!this.performanceResource)return[];const{resourceName:e,operation:r,startDate:i,endDate:n,limit:s=100,offset:o=0}=t;let a=(await this.performanceResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(n&&new Date(t.timestamp)>new Date(n)))));return a.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),a.slice(o,o+s)}async getStats(){const t=new Date,e=new Date(t.getTime()-864e5),[r,i,n]=await Promise.all([this.getMetrics({startDate:e.toISOString()}),this.getErrorLogs({startDate:e.toISOString()}),this.getPerformanceLogs({startDate:e.toISOString()})]),s={period:"24h",totalOperations:0,totalErrors:i.length,avgResponseTime:0,operationsByType:{},resources:{},uptime:{startTime:this.metrics.startTime,duration:t.getTime()-new Date(this.metrics.startTime).getTime()}};for(const t of r)if("operation"===t.type){s.totalOperations+=t.count,s.operationsByType[t.operation]||(s.operationsByType[t.operation]={count:0,errors:0,avgTime:0}),s.operationsByType[t.operation].count+=t.count,s.operationsByType[t.operation].errors+=t.errors;const e=s.operationsByType[t.operation],r=e.count,i=(e.avgTime*(r-t.count)+t.totalTime)/r;e.avgTime=i}const o=r.reduce((t,e)=>t+e.totalTime,0),a=r.reduce((t,e)=>t+e.count,0);return s.avgResponseTime=a>0?o/a:0,s}async cleanupOldData(){const t=new Date;if(t.setDate(t.getDate()-this.config.retentionDays),this.metricsResource){const e=await this.getMetrics({endDate:t.toISOString()});for(const t of e)await this.metricsResource.delete(t.id)}if(this.errorsResource){const e=await this.getErrorLogs({endDate:t.toISOString()});for(const t of e)await this.errorsResource.delete(t.id)}if(this.performanceResource){const e=await this.getPerformanceLogs({endDate:t.toISOString()});for(const t of e)await this.performanceResource.delete(t.id)}}}class ji{constructor(t){let e;const[r,i,n]=ft(()=>new URL(t));if(!r)throw new st("Invalid connection string: "+t,{original:i,input:t});e=n,this.region="us-east-1","s3:"===e.protocol?this.defineFromS3(e):this.defineFromCustomUri(e);for(const[t,r]of e.searchParams.entries())this[t]=r}defineFromS3(t){const[e,r,i]=ht(()=>decodeURIComponent(t.hostname));if(!e)throw new st("Invalid bucket in connection string",{original:r,input:t.hostname});this.bucket=i||"s3db";const[n,s,o]=ht(()=>decodeURIComponent(t.username));if(!n)throw new st("Invalid accessKeyId in connection string",{original:s,input:t.username});this.accessKeyId=o;const[a,c,u]=ht(()=>decodeURIComponent(t.password));if(!a)throw new st("Invalid secretAccessKey in connection string",{original:c,input:t.password});if(this.secretAccessKey=u,this.endpoint="https://s3.us-east-1.amazonaws.com",["/","",null].includes(t.pathname))this.keyPrefix="";else{let[,...e]=t.pathname.split("/");this.keyPrefix=[...e||[]].join("/")}}defineFromCustomUri(t){this.forcePathStyle=!0,this.endpoint=t.origin;const[e,r,i]=ht(()=>decodeURIComponent(t.username));if(!e)throw new st("Invalid accessKeyId in connection string",{original:r,input:t.username});this.accessKeyId=i;const[n,s,o]=ht(()=>decodeURIComponent(t.password));if(!n)throw new st("Invalid secretAccessKey in connection string",{original:s,input:t.password});if(this.secretAccessKey=o,["/","",null].includes(t.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,e,...r]=t.pathname.split("/");if(e){const[t,r,i]=ht(()=>decodeURIComponent(e));if(!t)throw new st("Invalid bucket in connection string",{original:r,input:e});this.bucket=i}else this.bucket="s3db";this.keyPrefix=[...r||[]].join("/")}}}class Ri extends St{constructor({verbose:t=!1,id:e=null,AwsS3Client:r,connectionString:i,parallelism:n=10}){super(),this.verbose=t,this.id=e??wt(),this.parallelism=n,this.config=new ji(i),this.client=r||this.createClient()}createClient(){let t={region:this.config.region,endpoint:this.config.endpoint};this.config.forcePathStyle&&(t.forcePathStyle=!0),this.config.accessKeyId&&(t.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey});const e=new b(t);return e.middlewareStack.add((t,e)=>async r=>{if("DeleteObjectsCommand"===e.commandName){const t=r.request.body;if(t&&"string"==typeof t){const e=await yt(t);r.request.headers["Content-MD5"]=e}}return t(r)},{step:"build",name:"addContentMd5ForDeleteObjects",priority:"high"}),e}async sendCommand(t){this.emit("command.request",t.constructor.name,t.input);const[e,r,i]=await ft(()=>this.client.send(t));if(!e){throw nt(r,{bucket:this.config.bucket,key:t.input&&t.input.Key,commandName:t.constructor.name,commandInput:t.input})}return this.emit("command.response",t.constructor.name,i,t.input),i}async putObject({key:t,metadata:e,contentType:r,body:i,contentEncoding:n,contentLength:s}){const o="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";o&&Ut.join(o,t);const a={};if(e)for(const[t,r]of Object.entries(e)){a[String(t).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const c={Bucket:this.config.bucket,Key:o?Ut.join(o,t):t,Metadata:a,Body:i||Buffer.alloc(0)};let u,l;void 0!==r&&(c.ContentType=r),void 0!==n&&(c.ContentEncoding=n),void 0!==s&&(c.ContentLength=s);try{return u=await this.sendCommand(new w(c)),u}catch(e){throw l=e,nt(e,{bucket:this.config.bucket,key:t,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",l||u,{key:t,metadata:e,contentType:r,body:i,contentEncoding:n,contentLength:s})}}async getObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?Ut.join(e,t):t};let i,n;try{return i=await this.sendCommand(new v(r)),i}catch(e){throw n=e,nt(e,{bucket:this.config.bucket,key:t,commandName:"GetObjectCommand",commandInput:r})}finally{this.emit("getObject",n||i,{key:t})}}async headObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?Ut.join(e,t):t};let i,n;try{return i=await this.sendCommand(new k(r)),i}catch(e){throw n=e,nt(e,{bucket:this.config.bucket,key:t,commandName:"HeadObjectCommand",commandInput:r})}finally{this.emit("headObject",n||i,{key:t})}}async copyObject({from:t,to:e}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?Ut.join(this.config.keyPrefix,e):e,CopySource:Ut.join(this.config.bucket,this.config.keyPrefix?Ut.join(this.config.keyPrefix,t):t)};let i,n;try{return i=await this.sendCommand(new O(r)),i}catch(t){throw n=t,nt(t,{bucket:this.config.bucket,key:e,commandName:"CopyObjectCommand",commandInput:r})}finally{this.emit("copyObject",n||i,{from:t,to:e})}}async exists(t){const[e,r]=await ft(()=>this.headObject(t));if(e)return!0;if("NoSuchKey"===r.name||"NotFound"===r.name)return!1;throw r}async deleteObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";e&&Ut.join(e,t);const r={Bucket:this.config.bucket,Key:e?Ut.join(e,t):t};let i,n;try{return i=await this.sendCommand(new S(r)),i}catch(e){throw n=e,nt(e,{bucket:this.config.bucket,key:t,commandName:"DeleteObjectCommand",commandInput:r})}finally{this.emit("deleteObject",n||i,{key:t})}}async deleteObjects(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r=s(t,1e3),{results:n,errors:o}=await i.for(r).withConcurrency(this.parallelism).process(async t=>{for(const r of t)e&&Ut.join(e,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:t.map(t=>({Key:e?Ut.join(e,t):t}))}};let i;const[n,s,o]=await ft(()=>this.sendCommand(new _(r)));if(!n)throw s;return i=o,i&&i.Errors&&i.Errors.length,i&&i.Deleted&&(i.Deleted.length,t.length),i}),a={deleted:n,notFound:o};return this.emit("deleteObjects",a,t),a}async deleteAll({prefix:t}={}){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,i=0;do{const n=new x({Bucket:this.config.bucket,Prefix:e?Ut.join(e,t||""):t||"",ContinuationToken:r}),s=await this.client.send(n);if(s.Contents&&s.Contents.length>0){const e=new _({Bucket:this.config.bucket,Delete:{Objects:s.Contents.map(t=>({Key:t.Key}))}}),r=await this.client.send(e),n=r.Deleted?r.Deleted.length:0;i+=n,this.emit("deleteAll",{prefix:t,batch:n,total:i})}r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:t,totalDeleted:i}),i}async moveObject({from:t,to:e}){const[r,i]=await ft(async()=>{await this.copyObject({from:t,to:e}),await this.deleteObject(t)});if(!r)throw new rt("Unknown error in moveObject",{bucket:this.config.bucket,from:t,to:e,original:i});return!0}async listObjects({prefix:t,maxKeys:e=1e3,continuationToken:r}={}){const i={Bucket:this.config.bucket,MaxKeys:e,ContinuationToken:r,Prefix:this.config.keyPrefix?Ut.join(this.config.keyPrefix,t||""):t||""},[n,s,o]=await ft(()=>this.sendCommand(new x(i)));if(!n)throw new rt("Unknown error in listObjects",{prefix:t,bucket:this.config.bucket,original:s});return this.emit("listObjects",o,i),o}async count({prefix:t}={}){let e,r=0,i=!0;for(;i;){const n={prefix:t,continuationToken:e},s=await this.listObjects(n);r+=s.KeyCount||0,i=s.IsTruncated||!1,e=s.NextContinuationToken}return this.emit("count",r,{prefix:t}),r}async getAllKeys({prefix:t}={}){let e,r=[],i=!0;for(;i;){const n={prefix:t,continuationToken:e},s=await this.listObjects(n);s.Contents&&(r=r.concat(s.Contents.map(t=>t.Key))),i=s.IsTruncated||!1,e=s.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(t=>t.replace(this.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t)),this.emit("getAllKeys",r,{prefix:t}),r}async getContinuationTokenAfterOffset(t={}){const{prefix:e,offset:r=1e3}=t;if(0===r)return null;let i,n=!0,s=0;for(;n;){const t={prefix:e,maxKeys:r<1e3?r:r-s>1e3?1e3:r-s,continuationToken:i},o=await this.listObjects(t);if(o.Contents&&(s+=o.Contents.length),n=o.IsTruncated||!1,i=o.NextContinuationToken,s>=r)break}return this.emit("getContinuationTokenAfterOffset",i||null,t),i||null}async getKeysPage(t={}){const{prefix:e,offset:r=0,amount:i=100}=t;let n,s=[],o=!0;if(r>0&&(n=await this.getContinuationTokenAfterOffset({prefix:e,offset:r}),!n))return this.emit("getKeysPage",[],t),[];for(;o;){const t={prefix:e,continuationToken:n},r=await this.listObjects(t);if(r.Contents&&(s=s.concat(r.Contents.map(t=>t.Key))),o=r.IsTruncated||!1,n=r.NextContinuationToken,s.length>=i){s=s.slice(0,i);break}}return this.config.keyPrefix&&(s=s.map(t=>t.replace(this.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t)),this.emit("getKeysPage",s,t),s}async moveAllObjects({prefixFrom:t,prefixTo:e}){const r=await this.getAllKeys({prefix:t}),{results:n,errors:s}=await i.for(r).withConcurrency(this.parallelism).process(async r=>{const i=r.replace(t,e),[n,s]=await ft(async()=>{await this.moveObject({from:r,to:i})});if(!n)throw new rt("Unknown error in moveAllObjects",{bucket:this.config.bucket,from:r,to:i,original:s});return i});if(this.emit("moveAllObjects",{results:n,errors:s},{prefixFrom:t,prefixTo:e}),s.length>0)throw new Error("Some objects could not be moved");return n}}var Di=Ri;async function Ai(t,e,r){if(!this.passphrase)return e.push(new H("Missing configuration for secrets encryption.",{actual:t,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),t;const[i,n,s]=await ft(()=>mt(String(t),this.passphrase));return i?s:(e.push(new H("Problem encrypting secret.",{actual:t,type:"encryptionProblem",error:n,suggestion:"Check the passphrase and input value."})),t)}async function Ni(t,e,r){if(a(t))return t;const[i,n,s]=ht(()=>JSON.stringify(t));if(!i)throw new H("Failed to stringify JSON",{original:n,input:t});return s}class Ei extends D{constructor({options:t,passphrase:e,autoEncrypt:r=!0}={}){super(o({},{useNewCustomCheckerFunction:!0,messages:{encryptionKeyMissing:"Missing configuration for secrets encryption.",encryptionProblem:"Problem encrypting secret. Actual: {actual}. Error: {error}"},defaults:{string:{trim:!0},object:{strict:"remove"},number:{convert:!0}}},t)),this.passphrase=e,this.autoEncrypt=r,this.alias("secret",{type:"string",custom:this.autoEncrypt?Ai:void 0,messages:{string:"The '{field}' field must be a string.",stringMin:"This secret '{field}' field length must be at least {expected} long."}}),this.alias("secretAny",{type:"any",custom:this.autoEncrypt?Ai:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Ai:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?Ni:void 0})}}const Pi=new Proxy(Ei,{instance:null,construct(t,e){return this.instance||(this.instance=new t(...e)),this.instance}});const Ii={trim:t=>null==t?t:t.trim(),encrypt:async(t,{passphrase:e})=>{if(null==t)return t;const[r,i,n]=await lt(()=>mt(t,e));return r?n:t},decrypt:async(t,{passphrase:e})=>{if(null==t)return t;const[r,i,n]=await lt(()=>gt(t,e));return r?"null"===n?null:"undefined"!==n?n:void 0:t},toString:t=>null==t?t:String(t),fromArray:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>"string"==typeof t?t.replace(/\\/g,"\\\\").replace(new RegExp(`\\${e}`,"g"),`\\${e}`):String(t)).join(e)},toArray:(t,{separator:e})=>{if(Array.isArray(t))return t;if(null==t)return t;if(""===t)return[];const r=[];let i="",n=0;const s=String(t);for(;n<s.length;)"\\"===s[n]&&n+1<s.length?(i+=s[n+1],n+=2):s[n]===e?(r.push(i),i="",n++):(i+=s[n],n++);return r.push(i),r},toJSON:t=>{if(null===t)return null;if(void 0===t)return;if("string"==typeof t){const[e,r,i]=ht(()=>JSON.parse(t));return t}const[e,r,i]=ht(()=>JSON.stringify(t));return e?i:t},fromJSON:t=>{if(null===t)return null;if(void 0===t)return;if("string"!=typeof t)return t;if(""===t)return"";const[e,r,i]=ht(()=>JSON.parse(t));return e?i:t},toNumber:t=>a(t)?t.includes(".")?parseFloat(t):parseInt(t):t,toBool:t=>[!0,1,"true","1","yes","y"].includes(t),fromBool:t=>[!0,1,"true","1","yes","y"].includes(t)?"1":"0",fromBase62:t=>{if(null==t||""===t)return t;if("number"==typeof t)return t;if("string"==typeof t){const e=P(t);return isNaN(e)?void 0:e}},toBase62:t=>{if(null==t||""===t)return t;if("number"==typeof t)return E(t);if("string"==typeof t){const e=Number(t);return isNaN(e)?t:E(e)}return t},fromBase62Decimal:t=>{if(null==t||""===t)return t;if("number"==typeof t)return t;if("string"==typeof t){const e=C(t);return isNaN(e)?void 0:e}},toBase62Decimal:t=>{if(null==t||""===t)return t;if("number"==typeof t)return I(t);if("string"==typeof t){const e=Number(t);return isNaN(e)?t:I(e)}return t},fromArrayOfNumbers:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>{if("number"==typeof t&&!isNaN(t))return E(t);const e=Number(t);return isNaN(e)?"":E(e)}).join(e)},toArrayOfNumbers:(t,{separator:e})=>{if(Array.isArray(t))return t.map(t=>"number"==typeof t?t:P(t));if(null==t)return t;if(""===t)return[];const r=String(t),i=[];let n="",s=0;for(;s<r.length;)"\\"===r[s]&&s+1<r.length?(n+=r[s+1],s+=2):r[s]===e?(i.push(n),n="",s++):(n+=r[s],s++);return i.push(n),i.map(t=>{if("number"==typeof t)return t;if("string"==typeof t&&""!==t){const e=P(t);return isNaN(e)?NaN:e}return NaN})},fromArrayOfDecimals:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>{if("number"==typeof t&&!isNaN(t))return I(t);const e=Number(t);return isNaN(e)?"":I(e)}).join(e)},toArrayOfDecimals:(t,{separator:e})=>{if(Array.isArray(t))return t.map(t=>"number"==typeof t?t:C(t));if(null==t)return t;if(""===t)return[];const r=String(t),i=[];let n="",s=0;for(;s<r.length;)"\\"===r[s]&&s+1<r.length?(n+=r[s+1],s+=2):r[s]===e?(i.push(n),n="",s++):(n+=r[s],s++);return i.push(n),i.map(t=>{if("number"==typeof t)return t;if("string"==typeof t&&""!==t){const e=C(t);return isNaN(e)?NaN:e}return NaN})}};class Ci{constructor(t){const{map:e,name:r,attributes:i,passphrase:n,version:s=1,options:a={}}=t;this.name=r,this.version=s,this.attributes=i||{},this.passphrase=n??"secret",this.options=o({},this.defaultOptions(),a),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const l=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Pi({autoEncrypt:!1}).compile(o({$$async:!0},l)),this.options.generateAutoHooks&&this.generateAutoHooks(),c(e)){const t=j(this.attributes,{safe:!0}),e=Object.keys(t).filter(t=>!t.includes("$$")),r=this.extractObjectKeys(this.attributes),i=[...new Set([...e,...r])],{mapping:n,reversedMapping:s}=function(t){const e={},r={};return t.forEach((t,i)=>{const n=E(i);e[t]=n,r[n]=t}),{mapping:e,reversedMapping:r}}(i);this.map=n,this.reversedMap=s}else this.map=e,this.reversedMap=u(e)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(t,e,r){this.options.hooks[t][e]||(this.options.hooks[t][e]=[]),this.options.hooks[t][e]=l([...this.options.hooks[t][e],r])}extractObjectKeys(t,e=""){const r=[];for(const[i,n]of Object.entries(t)){if(i.startsWith("$$"))continue;const t=e?`${e}.${i}`:i;"object"!=typeof n||null===n||Array.isArray(n)||(r.push(t),"object"===n.$$type&&r.push(...this.extractObjectKeys(n,t)))}return r}generateAutoHooks(){const t=j(h(this.attributes),{safe:!0});for(const[e,r]of Object.entries(t))if(r.includes("array")){if(r.includes("items:string"))this.addHook("beforeMap",e,"fromArray"),this.addHook("afterUnmap",e,"toArray");else if(r.includes("items:number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",e,"fromArrayOfNumbers"),this.addHook("afterUnmap",e,"toArrayOfNumbers")):(this.addHook("beforeMap",e,"fromArrayOfDecimals"),this.addHook("afterUnmap",e,"toArrayOfDecimals"))}}else if(r.includes("secret"))this.options.autoEncrypt&&this.addHook("beforeMap",e,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",e,"decrypt");else{if(r.includes("number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",e,"toBase62"),this.addHook("afterUnmap",e,"fromBase62")):(this.addHook("beforeMap",e,"toBase62Decimal"),this.addHook("afterUnmap",e,"fromBase62Decimal"));continue}r.includes("boolean")?(this.addHook("beforeMap",e,"fromBool"),this.addHook("afterUnmap",e,"toBool")):(r.includes("json")||"object"===r||r.includes("object"))&&(this.addHook("beforeMap",e,"toJSON"),this.addHook("afterUnmap",e,"fromJSON"))}}static import(t){let{map:e,name:r,options:i,version:n,attributes:s}=a(t)?JSON.parse(t):t;const[o,c,u]=ht(()=>Ci._importAttributes(s));if(!o)throw new at("Failed to import schema attributes",{original:c,input:s});s=u;return new Ci({map:e,name:r,options:i,version:n,attributes:s})}static _importAttributes(t){if("string"==typeof t){const[e,r,i]=ht(()=>JSON.parse(t));if(e&&"object"==typeof i&&null!==i){const[e,r,n]=ht(()=>Ci._importAttributes(i));if(!e)throw new at("Failed to parse nested schema attribute",{original:r,input:t});return n}return t}if(Array.isArray(t)){const[e,r,i]=ht(()=>t.map(t=>Ci._importAttributes(t)));if(!e)throw new at("Failed to import array schema attributes",{original:r,input:t});return i}if("object"==typeof t&&null!==t){const e={};for(const[r,i]of Object.entries(t)){const[t,n,s]=ht(()=>Ci._importAttributes(i));if(!t)throw new at("Failed to import object schema attribute",{original:n,key:r,input:i});e[r]=s}return e}return t}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(t){if("string"==typeof t)return t;if(Array.isArray(t))return t.map(t=>this._exportAttributes(t));if("object"==typeof t&&null!==t){const e={};for(const[r,i]of Object.entries(t))e[r]=this._exportAttributes(i);return e}return t}async applyHooksActions(t,e){const r=h(t);for(const[t,i]of Object.entries(this.options.hooks[e]))for(const e of i){const i=f(r,t);void 0!==i&&"function"==typeof Ii[e]&&d(r,t,await Ii[e](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(t,{mutateOriginal:e=!1}={}){let r=e?t:h(t);return await this.validator(r)}async mapper(t){let e=h(t);e=await this.applyHooksActions(e,"beforeMap");const r=j(e,{safe:!0}),i={_v:this.version+""};for(const[t,e]of Object.entries(r)){const r=this.map[t]||t,n=this.getAttributeDefinition(t);"number"==typeof e&&"string"==typeof n&&n.includes("number")?i[r]=E(e):"string"==typeof e?"[object Object]"===e?i[r]="{}":(e.startsWith("{")||e.startsWith("["),i[r]=e):Array.isArray(e)||"object"==typeof e&&null!==e?i[r]=JSON.stringify(e):i[r]=e}return await this.applyHooksActions(i,"afterMap"),i}async unmapper(t,e){let r=h(t);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const i=e?u(e):this.reversedMap,n={};for(const[t,e]of Object.entries(r)){const r=i&&i[t]?i[t]:t;let s=e;const o=this.getAttributeDefinition(r);if("string"!=typeof o||!o.includes("number")||o.includes("array")||o.includes("decimal")){if("string"==typeof e)if("[object Object]"===e)s={};else if(e.startsWith("{")||e.startsWith("[")){const[t,r,i]=ht(()=>JSON.parse(e));t&&(s=i)}}else"string"==typeof s&&""!==s?s=P(s):"number"==typeof s||(s=void 0);if(this.attributes&&"string"==typeof o&&o.includes("array"))if(Array.isArray(s));else if("string"==typeof s&&s.trim().startsWith("[")){const[t,e,r]=ht(()=>JSON.parse(s));t&&Array.isArray(r)&&(s=r)}else s=Ii.toArray(s,{separator:this.options.arraySeparator});if(this.options.hooks&&this.options.hooks.afterUnmap&&this.options.hooks.afterUnmap[r])for(const t of this.options.hooks.afterUnmap[r])"function"==typeof Ii[t]&&(s=await Ii[t](s,{passphrase:this.passphrase,separator:this.options.arraySeparator}));n[r]=s}await this.applyHooksActions(n,"afterUnmap");const s=R(n);for(const[e,r]of Object.entries(t))e.startsWith("$")&&(s[e]=r);return s}getAttributeDefinition(t){const e=t.split(".");let r=this.attributes;for(const t of e){if(!r)return;r=r[t]}return r}preprocessAttributesForValidation(t){const e={};for(const[r,i]of Object.entries(t))if("object"!=typeof i||null===i||Array.isArray(i))e[r]=i;else{const t=i.$$type&&i.$$type.includes("required"),n=i.$$type&&i.$$type.includes("optional"),s={type:"object",properties:this.preprocessAttributesForValidation(i),strict:!1};t||(n||this.allNestedObjectsOptional)&&(s.optional=!0),e[r]=s}return e}}var Mi=Ci;const Ti=2047;var $i=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:Ti,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r,originalData:i}){const n=U(r),s=V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}});if(n>s)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, effective limit: ${s} bytes, absolute limit: 2047 bytes`);return{mappedData:r,body:JSON.stringify(r)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:n}){const s=U(i),o=V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}});if(s>o)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${o} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:JSON.stringify(i)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){const n=U(i),s=V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}});if(n>s)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, effective limit: ${s} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:""}}});var Li=Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r,originalData:i}){const n=U(r);return n>V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}})&&t.emit("exceedsLimit",{operation:"insert",totalSize:n,limit:2047,excess:n-2047,data:i||e}),{mappedData:r,body:JSON.stringify(e)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:n}){const s=U(i);return s>V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}})&&t.emit("exceedsLimit",{operation:"update",id:e,totalSize:s,limit:2047,excess:s-2047,data:n||r}),{mappedData:i,body:JSON.stringify(r)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i,originalData:n}){const s=U(i);return s>V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}})&&t.emit("exceedsLimit",{operation:"upsert",id:e,totalSize:s,limit:2047,excess:s-2047,data:n||r}),{mappedData:i,body:JSON.stringify(r)}}});const Ui="$truncated",Bi="true",Fi=M(Ui)+M(Bi);async function Vi({resource:t,data:e,mappedData:r,originalData:i}){const n=V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}}),s=L(r),o=Object.entries(s).sort(([,t],[,e])=>t-e),a={};let c=0,u=!1;r._v&&(a._v=r._v,c+=s._v);for(const[t,e]of o){if("_v"===t)continue;const i=r[t];if(!(c+(e+(u?0:Fi))<=n)){const e=n-c-(u?0:Fi);if(e>0){const r=zi(i,e);a[t]=r,u=!0,c+=M(r)}else a[t]="",u=!0;break}a[t]=i,c+=e}let l=U(a)+(u?Fi:0);for(;l>n;){const t=Object.keys(a).filter(t=>"_v"!==t&&"$truncated"!==t);if(0===t.length)break;a[t[t.length-1]]="",l=U(a)+Fi,u=!0}return u&&(a[Ui]=Bi),{mappedData:a,body:JSON.stringify(r)}}function zi(t,e){if("string"==typeof t)return Ki(t,e);if("object"==typeof t&&null!==t){return Ki(JSON.stringify(t),e)}return Ki(String(t),e)}function Ki(t,e){const r=new TextEncoder;let i=r.encode(t);if(i.length<=e)return t;let n=t.length;for(;n>0;){const s=t.substring(0,n);if(i=r.encode(s),i.length<=e)return s;n--}return""}var qi=Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:Vi,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:n}){return Vi({resource:t,data:r,mappedData:i,originalData:n})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return Vi({resource:t,data:r,mappedData:i})}});const Hi="$overflow",Wi="true",Ji=M(Hi)+M(Wi);async function Yi({resource:t,data:e,mappedData:r,originalData:i}){const n=V({s3Limit:Ti,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}}),s=L(r),o=Object.entries(s).sort(([,t],[,e])=>t-e),a={},c={};let u=0,l=!1;r._v&&(a._v=r._v,u+=s._v);let h=n;for(const[t,e]of o)"_v"!==t&&(!l&&u+e>n&&(h-=Ji,l=!0),!l&&u+e<=h?(a[t]=r[t],u+=e):(c[t]=r[t],l=!0));l&&(a[Hi]=Wi);const f=Object.keys(c).length>0;let d=f?JSON.stringify(c):"";return f||(d="{}"),{mappedData:a,body:d}}async function Gi({resource:t,data:e,mappedData:r}){const i={_v:r._v||String(t.version)};i._map=JSON.stringify(t.schema.map);return{mappedData:i,body:JSON.stringify(r)}}const Zi={"user-managed":Li,"enforce-limits":$i,"truncate-data":qi,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){let i={};if(r&&""!==r.trim()){const[t,e,n]=ht(()=>JSON.parse(r));i=t?n:{}}const n={...i,...e};return delete n.$overflow,{metadata:n,body:r}},handleInsert:Yi,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:n}){return Yi({resource:t,data:r,mappedData:i,originalData:n})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return Yi({resource:t,data:r,mappedData:i})}}),"body-only":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){let i={};if(r&&""!==r.trim()){const[t,e,n]=ht(()=>JSON.parse(r));i=t?n:{}}return{metadata:{...i,...e},body:r}},handleInsert:Gi,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i}){const n={_v:i._v||String(t.version)};return n._map=JSON.stringify(t.schema.map),{mappedData:n,body:JSON.stringify(i)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return Gi({resource:t,data:r,mappedData:i})}})};function Qi(t){const e=Zi[t];if(!e)throw new Error(`Unknown behavior: ${t}. Available behaviors: ${Object.keys(Zi).join(", ")}`);return e}const Xi=Object.keys(Zi),tn="user-managed";class en extends St{constructor(t={}){super(),this._instanceId=Math.random().toString(36).slice(2,8);const e=function(t){const e=[];t.name?"string"!=typeof t.name?e.push("Resource 'name' must be a string"):""===t.name.trim()&&e.push("Resource 'name' cannot be empty"):e.push("Resource 'name' is required");t.client||e.push("S3 'client' is required");t.attributes?"object"!=typeof t.attributes||Array.isArray(t.attributes)?e.push("Resource 'attributes' must be an object"):0===Object.keys(t.attributes).length&&e.push("Resource 'attributes' cannot be empty"):e.push("Resource 'attributes' are required");void 0!==t.version&&"string"!=typeof t.version&&e.push("Resource 'version' must be a string");void 0!==t.behavior&&"string"!=typeof t.behavior&&e.push("Resource 'behavior' must be a string");void 0!==t.passphrase&&"string"!=typeof t.passphrase&&e.push("Resource 'passphrase' must be a string");void 0!==t.parallelism&&("number"==typeof t.parallelism&&Number.isInteger(t.parallelism)?t.parallelism<1&&e.push("Resource 'parallelism' must be greater than 0"):e.push("Resource 'parallelism' must be an integer"));void 0===t.observers||Array.isArray(t.observers)||e.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const i of r)void 0!==t[i]&&"boolean"!=typeof t[i]&&e.push(`Resource '${i}' must be a boolean`);void 0!==t.idGenerator&&("function"!=typeof t.idGenerator&&"number"!=typeof t.idGenerator?e.push("Resource 'idGenerator' must be a function or a number (size)"):"number"==typeof t.idGenerator&&t.idGenerator<=0&&e.push("Resource 'idGenerator' size must be greater than 0"));void 0!==t.idSize&&("number"==typeof t.idSize&&Number.isInteger(t.idSize)?t.idSize<=0&&e.push("Resource 'idSize' must be greater than 0"):e.push("Resource 'idSize' must be an integer"));if(void 0!==t.partitions)if("object"!=typeof t.partitions||Array.isArray(t.partitions))e.push("Resource 'partitions' must be an object");else for(const[r,i]of Object.entries(t.partitions))if("object"!=typeof i||Array.isArray(i))e.push(`Partition '${r}' must be an object`);else if(i.fields)if("object"!=typeof i.fields||Array.isArray(i.fields))e.push(`Partition '${r}.fields' must be an object`);else for(const[t,n]of Object.entries(i.fields))"string"!=typeof n&&e.push(`Partition '${r}.fields.${t}' must be a string`);else e.push(`Partition '${r}' must have a 'fields' property`);if(void 0!==t.hooks)if("object"!=typeof t.hooks||Array.isArray(t.hooks))e.push("Resource 'hooks' must be an object");else{const r=["beforeInsert","afterInsert","beforeUpdate","afterUpdate","beforeDelete","afterDelete"];for(const[i,n]of Object.entries(t.hooks))if(r.includes(i))if(Array.isArray(n))for(let t=0;t<n.length;t++){const e=n[t];if("function"==typeof e);else if("string"==typeof e)continue}else e.push(`Resource 'hooks.${i}' must be an array`);else e.push(`Invalid hook event '${i}'. Valid events: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}(t);if(!e.isValid)throw new ct(`Invalid Resource ${t.name} configuration`,{resourceName:t.name,validation:e.errors,operation:"constructor",suggestion:"Check resource config and attributes."});const{name:r,client:i,version:n="1",attributes:s={},behavior:o=tn,passphrase:a="secret",parallelism:c=10,observers:u=[],cache:l=!1,autoDecrypt:h=!0,timestamps:f=!1,partitions:d={},paranoid:p=!0,allNestedObjectsOptional:m=!0,hooks:g={},idGenerator:y,idSize:b=22,versioningEnabled:w=!1}=t;if(this.name=r,this.client=i,this.version=n,this.behavior=o,this.observers=u,this.parallelism=c,this.passphrase=a??"secret",this.versioningEnabled=w,this.idGenerator=this.configureIdGenerator(y,b),this.config={cache:l,hooks:g,paranoid:p,timestamps:f,partitions:d,autoDecrypt:h,allNestedObjectsOptional:m},this.hooks={beforeInsert:[],afterInsert:[],beforeUpdate:[],afterUpdate:[],beforeDelete:[],afterDelete:[]},this.attributes=s||{},this.map=t.map,this.applyConfiguration({map:this.map}),g)for(const[t,e]of Object.entries(g))if(Array.isArray(e)&&this.hooks[t])for(const r of e)"function"==typeof r&&this.hooks[t].push(r.bind(this));this._initMiddleware()}configureIdGenerator(r,i){return"function"==typeof r?r:"number"==typeof r&&r>0?t(e,r):"number"==typeof i&&i>0&&22!==i?t(e,i):wt}get options(){return{timestamps:this.config.timestamps,partitions:this.config.partitions||{},cache:this.config.cache,autoDecrypt:this.config.autoDecrypt,paranoid:this.config.paranoid,allNestedObjectsOptional:this.config.allNestedObjectsOptional}}export(){const t=this.schema.export();return t.behavior=this.behavior,t.timestamps=this.config.timestamps,t.partitions=this.config.partitions||{},t.paranoid=this.config.paranoid,t.allNestedObjectsOptional=this.config.allNestedObjectsOptional,t.autoDecrypt=this.config.autoDecrypt,t.cache=this.config.cache,t.hooks=this.hooks,t.map=this.map,t}applyConfiguration({map:t}={}){this.config.timestamps&&(this.attributes.createdAt||(this.attributes.createdAt="string|optional"),this.attributes.updatedAt||(this.attributes.updatedAt="string|optional"),this.config.partitions||(this.config.partitions={}),this.config.partitions.byCreatedDate||(this.config.partitions.byCreatedDate={fields:{createdAt:"date|maxlength:10"}}),this.config.partitions.byUpdatedDate||(this.config.partitions.byUpdatedDate={fields:{updatedAt:"date|maxlength:10"}})),this.setupPartitionHooks(),this.versioningEnabled&&(this.config.partitions.byVersion||(this.config.partitions.byVersion={fields:{_v:"string"}})),this.schema=new Mi({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional},map:t||this.map}),this.validatePartitions()}updateAttributes(t){const e=this.attributes;return this.attributes=t,this.applyConfiguration({map:this.schema?.map}),{oldAttributes:e,newAttributes:t}}addHook(t,e){this.hooks[t]&&this.hooks[t].push(e.bind(this))}async executeHooks(t,e){if(!this.hooks[t])return e;let r=e;for(const e of this.hooks[t])r=await e(r);return r}setupPartitionHooks(){if(!this.config.partitions)return;const t=this.config.partitions;0!==Object.keys(t).length&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async t=>(await this.createPartitionReferences(t),t)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async t=>(await this.deletePartitionReferences(t),t)))}async validate(t){const e={original:h(t),isValid:!1,errors:[]},r=await this.schema.validate(t,{mutateOriginal:!1});return!0===r?e.isValid=!0:e.errors=r,e.data=t,e}validatePartitions(){if(!this.config.partitions)return;const t=this.config.partitions;if(0===Object.keys(t).length)return;const e=Object.keys(this.attributes||{});for(const[r,i]of Object.entries(t))if(i.fields)for(const t of Object.keys(i.fields))if(!this.fieldExistsInAttributes(t))throw new ut(`Partition '${r}' uses field '${t}' which does not exist in resource attributes. Available fields: ${e.join(", ")}.`,{resourceName:this.name,partitionName:r,fieldName:t,availableFields:e,operation:"validatePartitions"})}fieldExistsInAttributes(t){if(t.startsWith("_"))return!0;if(!t.includes("."))return Object.keys(this.attributes||{}).includes(t);const e=t.split(".");let r=this.attributes||{};for(const t of e){if(!r||"object"!=typeof r||!(t in r))return!1;r=r[t]}return!0}applyPartitionRule(t,e){if(null==t)return t;let r=t;if("string"==typeof e&&e.includes("maxlength:")){const t=e.match(/maxlength:(\d+)/);if(t){const e=parseInt(t[1]);"string"==typeof r&&r.length>e&&(r=r.substring(0,e))}}if(e.includes("date"))if(r instanceof Date)r=r.toISOString().split("T")[0];else if("string"==typeof r)if(r.includes("T")&&r.includes("Z"))r=r.split("T")[0];else{const t=new Date(r);isNaN(t.getTime())||(r=t.toISOString().split("T")[0])}return r}getResourceKey(t){return Lt("resource="+this.name,"data",`id=${t}`)}getPartitionKey({partitionName:t,id:e,data:r}){if(!this.config.partitions||!this.config.partitions[t])throw new ut(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"getPartitionKey"});const i=this.config.partitions[t],n=[],s=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of s){const i=this.getNestedFieldValue(r,t),s=this.applyPartitionRule(i,e);if(null==s)return null;n.push(`${t}=${s}`)}if(0===n.length)return null;const o=e||r?.id;return o?Lt(`resource=${this.name}`,`partition=${t}`,...n,`id=${o}`):null}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return;i=i[t]}return i}calculateContentLength(t){return t?Buffer.isBuffer(t)?t.length:"string"==typeof t?Buffer.byteLength(t,"utf8"):"object"==typeof t?Buffer.byteLength(JSON.stringify(t),"utf8"):Buffer.byteLength(String(t),"utf8"):0}async insert({id:t,...e}){if(await this.exists(t))throw new Error(`Resource with id '${t}' already exists`);this.getResourceKey(t||"(auto)"),this.options.timestamps&&(e.createdAt=(new Date).toISOString(),e.updatedAt=(new Date).toISOString());const r={id:t,...this.applyDefaults(e)},i=await this.executeHooks("beforeInsert",r),n=Object.keys(i).filter(t=>!(t in r)||i[t]!==r[t]),s={};for(const t of n)s[t]=i[t];const{errors:o,isValid:a,data:c}=await this.validate(i);if(!a){const t=o&&o.length&&o[0].message?o[0].message:"Insert failed";throw new et({bucket:this.client.config.bucket,resourceName:this.name,attributes:i,validation:o,message:t})}const{id:u,...l}=c;Object.assign(l,s);const h=u||t||this.idGenerator(),f=await this.schema.mapper(l);f._v=String(this.version);const d=Qi(this.behavior),{mappedData:p,body:m}=await d.handleInsert({resource:this,data:l,mappedData:f,originalData:r}),g=p,y=this.getResourceKey(h);let b;if(m&&""!==m){const[t,e]=await ft(()=>Promise.resolve(JSON.parse(m)));t&&(b="application/json")}if("body-only"===this.behavior&&(!m||""===m))throw new Error(`[Resource.insert] Tentativa de gravar objeto sem body! Dados: id=${h}, resource=${this.name}`);const[w,v,k]=await ft(()=>this.client.putObject({key:y,body:m,contentType:b,metadata:g}));if(!w){const t=v&&v.message?v.message:"";if(t.includes("metadata headers exceed")||t.includes("Insert failed")){const t=U(g),e=V({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=t-e;throw v.totalSize=t,v.limit=2047,v.effectiveLimit=e,v.excess=r,new ct("metadata headers exceed",{resourceName:this.name,operation:"insert",id:h,totalSize:t,effectiveLimit:e,excess:r,suggestion:"Reduce metadata size or number of fields."})}throw nt(v,{bucket:this.client.config.bucket,key:y,resourceName:this.name,operation:"insert",id:h})}let O=await this.composeFullObjectFromWrite({id:h,metadata:g,body:m,behavior:this.behavior});const S=await this.executeHooks("afterInsert",O);return this.emit("insert",{...O,$before:{...r},$after:{...S}}),S}async get(t){if(p(t))throw new Error("id cannot be an object");if(c(t))throw new Error("id cannot be empty");const e=this.getResourceKey(t),[r,i,n]=await ft(()=>this.client.getObject(e));if(!r)throw nt(i,{bucket:this.client.config.bucket,key:e,resourceName:this.name,operation:"get",id:t});if(0===n.ContentLength){const r=new Error(`No such key: ${e} [bucket:${this.client.config.bucket}]`);throw r.name="NoSuchKey",nt(r,{bucket:this.client.config.bucket,key:e,resourceName:this.name,operation:"get",id:t})}const s=n.Metadata?._v||this.version,o="string"==typeof s&&s.startsWith("v")?s.slice(1):s,a=await this.getSchemaForVersion(o);let u=await a.unmapper(n.Metadata);const l=Qi(this.behavior);let h="";if(n.ContentLength>0){const[t,r,i]=await ft(()=>this.client.getObject(e));h=t?await wi(i.Body):""}const{metadata:f}=await l.handleGet({resource:this,metadata:u,body:h});let d=await this.composeFullObjectFromWrite({id:t,metadata:f,body:h,behavior:this.behavior});d._contentLength=n.ContentLength,d._lastModified=n.LastModified,d._hasContent=n.ContentLength>0,d._mimeType=n.ContentType||null,d._v=o,n.VersionId&&(d._versionId=n.VersionId),n.Expiration&&(d._expiresAt=n.Expiration),d._definitionHash=this.getDefinitionHash(),o!==this.version&&(d=await this.applyVersionMapping(d,o,this.version)),this.emit("get",d);return d}async exists(t){const e=this.getResourceKey(t),[r,i]=await ft(()=>this.client.headObject(e));return r}async update(t,e){if(c(t))throw new Error("id cannot be empty");if(!await this.exists(t))throw new Error(`Resource with id '${t}' does not exist`);const r=await this.get(t),i=h(e);let n=h(r);for(const[t,e]of Object.entries(i))if(t.includes(".")){let r=n;const i=t.split(".");for(let t=0;t<i.length-1;t++)"object"==typeof r[i[t]]&&null!==r[i[t]]||(r[i[t]]={}),r=r[i[t]];r[i[i.length-1]]=h(e)}else"object"!=typeof e||null===e||Array.isArray(e)?n[t]=h(e):n[t]=o({},n[t],e);if(this.config.timestamps){const t=(new Date).toISOString();n.updatedAt=t,n.metadata||(n.metadata={}),n.metadata.updatedAt=t}const s=await this.executeHooks("beforeUpdate",h(n)),a={...r,...s,id:t},{isValid:u,errors:l,data:f}=await this.validate(h(a));if(!u)throw new et({bucket:this.client.config.bucket,resourceName:this.name,attributes:s,validation:l,message:"validation: "+(l&&l.length?JSON.stringify(l):"unknown")});await this.schema.mapper(f);const d=Qi(this.behavior),p=await this.schema.mapper({...r,...s});p._v=String(this.version),await d.handleUpdate({resource:this,id:t,data:{...r,...s},mappedData:p,originalData:{...i,id:t}});const{id:m,...g}=f,y={...r,id:t},b={...g,id:t};await this.handlePartitionReferenceUpdates(y,b);const w=await this.schema.mapper(g);w._v=String(this.version);const v=Qi(this.behavior),{mappedData:k,body:O}=await v.handleUpdate({resource:this,id:t,data:g,mappedData:w,originalData:{...i,id:t}}),S=k,_=this.getResourceKey(t);let x,j=O;if(""===O&&"body-overflow"!==this.behavior){const[t,e,r]=await ft(()=>this.client.getObject(_));if(t&&r.ContentLength>0){const t=Buffer.from(await r.Body.transformToByteArray()),e=t.toString(),[i,n]=await ft(()=>Promise.resolve(JSON.parse(e)));i||(j=t,x=r.ContentType)}}let R=x;if(j&&""!==j&&!R){const[t,e]=await ft(()=>Promise.resolve(JSON.parse(j)));t&&(R="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(t,r);const[D,A]=await ft(()=>this.client.putObject({key:_,body:j,contentType:R,metadata:S}));if(!D&&A&&A.message&&A.message.includes("metadata headers exceed")){const e=U(S),r=V({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:t}}),i=e-r;throw A.totalSize=e,A.limit=2047,A.effectiveLimit=r,A.excess=i,this.emit("exceedsLimit",{operation:"update",totalSize:e,limit:2047,effectiveLimit:r,excess:i,data:g}),new ct("metadata headers exceed",{resourceName:this.name,operation:"update",id:t,totalSize:e,effectiveLimit:r,excess:i,suggestion:"Reduce metadata size or number of fields."})}if(!D)throw nt(A,{bucket:this.client.config.bucket,key:_,resourceName:this.name,operation:"update",id:t});const N=await this.composeFullObjectFromWrite({id:t,metadata:S,body:j,behavior:this.behavior}),E=await this.executeHooks("afterUpdate",N);return this.emit("update",{...N,$before:{...r},$after:{...E}}),E}async delete(t){if(c(t))throw new Error("id cannot be empty");let e,r=null;const[i,n,s]=await ft(()=>this.get(t));i?e=s:(e={id:t},r=n),await this.executeHooks("beforeDelete",e);const o=this.getResourceKey(t),[a,u,l]=await ft(()=>this.client.deleteObject(o));if(this.emit("delete",{...e,$before:{...e},$after:null}),r)throw nt(r,{bucket:this.client.config.bucket,key:o,resourceName:this.name,operation:"delete",id:t});if(!a)throw nt(u,{key:o,resourceName:this.name,operation:"delete",id:t});return await this.executeHooks("afterDelete",e),l}async upsert({id:t,...e}){return await this.exists(t)?this.update(t,e):this.insert({id:t,...e})}async count({partition:t=null,partitionValues:e={}}={}){let r;if(t&&Object.keys(e).length>0){const i=this.config.partitions[t];if(!i)throw new ut(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"count"});const n=[],s=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,r]of s){const i=e[t];if(null!=i){const e=this.applyPartitionRule(i,r);n.push(`${t}=${e}`)}}r=n.length>0?`resource=${this.name}/partition=${t}/${n.join("/")}`:`resource=${this.name}/partition=${t}`}else r=`resource=${this.name}/data`;const i=await this.client.count({prefix:r});return this.emit("count",i),i}async insertMany(t){const{results:e}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,e),this.observers.map(r=>r.emit("error",this.name,t,e))}).process(async t=>await this.insert(t));return this.emit("insertMany",t.length),e}async deleteMany(t){const e=s(t.map(t=>this.getResourceKey(t)),1e3);t.map(t=>this.getResourceKey(t));const{results:r}=await i.for(e).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,e),this.observers.map(r=>r.emit("error",this.name,t,e))}).process(async t=>{const e=await this.client.deleteObjects(t);return t.forEach(t=>{const e=t.split("/").find(t=>t.startsWith("id=")),r=e?e.replace("id=",""):null;r&&(this.emit("deleted",r),this.observers.map(t=>t.emit("deleted",this.name,r)))}),e});return this.emit("deleteMany",t.length),r}async deleteAll(){if(!1!==this.config.paranoid)throw new ct("deleteAll() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAll",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAll."});const t=`resource=${this.name}/data`,e=await this.client.deleteAll({prefix:t});return this.emit("deleteAll",{version:this.version,prefix:t,deletedCount:e}),{deletedCount:e,version:this.version}}async deleteAllData(){if(!1!==this.config.paranoid)throw new ct("deleteAllData() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAllData",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAllData."});const t=`resource=${this.name}`,e=await this.client.deleteAll({prefix:t});return this.emit("deleteAllData",{resource:this.name,prefix:t,deletedCount:e}),{deletedCount:e,resource:this.name}}async listIds({partition:t=null,partitionValues:e={},limit:r,offset:i=0}={}){let n;if(t&&Object.keys(e).length>0){if(!this.config.partitions||!this.config.partitions[t])throw new ut(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"listIds"});const r=this.config.partitions[t],i=[],s=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,r]of s){const n=e[t];if(null!=n){const e=this.applyPartitionRule(n,r);i.push(`${t}=${e}`)}}n=i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}else n=`resource=${this.name}/data`;const s=(await this.client.getKeysPage({prefix:n,offset:i,amount:r||1e3})).map(t=>{const e=t.split("/").find(t=>t.startsWith("id="));return e?e.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",s.length),s}async list({partition:t=null,partitionValues:e={},limit:r,offset:i=0}={}){const[n,s,o]=await ft(async()=>t?await this.listPartition({partition:t,partitionValues:e,limit:r,offset:i}):await this.listMain({limit:r,offset:i}));return n?o:this.handleListError(s,{partition:t,partitionValues:e})}async listMain({limit:t,offset:e=0}){const[r,i,n]=await ft(()=>this.listIds({limit:t,offset:e}));if(!r)throw i;const s=await this.processListResults(n,"main");return this.emit("list",{count:s.length,errors:0}),s}async listPartition({partition:t,partitionValues:e,limit:r,offset:i=0}){if(!this.config.partitions?.[t])return this.emit("list",{partition:t,partitionValues:e,count:0,errors:0}),[];const n=this.config.partitions[t],s=this.buildPartitionPrefix(t,n,e),[o,a,c]=await ft(()=>this.client.getAllKeys({prefix:s}));if(!o)throw a;const u=this.extractIdsFromKeys(c).slice(i),l=r?u.slice(0,r):u,h=await this.processPartitionResults(l,t,n,c);return this.emit("list",{partition:t,partitionValues:e,count:h.length,errors:0}),h}buildPartitionPrefix(t,e,r){const i=[],n=Object.entries(e.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n){const n=r[t];if(null!=n){const r=this.applyPartitionRule(n,e);i.push(`${t}=${r}`)}}return i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}extractIdsFromKeys(t){return t.map(t=>{const e=t.split("/").find(t=>t.startsWith("id="));return e?e.replace("id=",""):null}).filter(Boolean)}async processListResults(t,e="main"){const{results:r,errors:n}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content))}).process(async t=>{const[r,i,n]=await ft(()=>this.get(t));return r?n:this.handleResourceError(i,t,e)});return this.emit("list",{count:r.length,errors:0}),r}async processPartitionResults(t,e,r,n){const s=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e)),{results:o,errors:a}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content))}).process(async t=>{const[r,i,o]=await ft(async()=>{const r=this.extractPartitionValuesFromKey(t,n,s);return await this.getFromPartition({id:t,partitionName:e,partitionValues:r})});return r?o:this.handleResourceError(i,t,"partition")});return o.filter(t=>null!==t)}extractPartitionValuesFromKey(t,e,r){const i=e.find(e=>e.includes(`id=${t}`));if(!i)throw new ut(`Partition key not found for ID ${t}`,{resourceName:this.name,id:t,operation:"extractPartitionValuesFromKey"});const n=i.split("/"),s={};for(const[t]of r){const e=n.find(e=>e.startsWith(`${t}=`));if(e){const r=e.replace(`${t}=`,"");s[t]=r}}return s}handleResourceError(t,e,r){if(t.message.includes("Cipher job failed")||t.message.includes("OperationError"))return{id:e,_decryptionFailed:!0,_error:t.message,..."partition"===r&&{_partition:r}};throw t}handleListError(t,{partition:e,partitionValues:r}){return t.message.includes("Partition '")&&t.message.includes("' not found"),this.emit("list",{partition:e,partitionValues:r,count:0,errors:1}),[]}async getMany(t){const{results:e,errors:r}=await i.for(t).withConcurrency(this.client.parallelism).handleError(async(t,e)=>(this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content)),{id:e,_error:t.message,_decryptionFailed:t.message.includes("Cipher job failed")||t.message.includes("OperationError")})).process(async t=>{const[e,r,i]=await ft(()=>this.get(t));if(e)return i;if(r.message.includes("Cipher job failed")||r.message.includes("OperationError"))return{id:t,_decryptionFailed:!0,_error:r.message};throw r});return this.emit("getMany",t.length),e}async getAll(){const[t,e,r]=await ft(()=>this.listIds());if(!t)throw e;const i=[];for(const t of r){const[e,r,n]=await ft(()=>this.get(t));e&&i.push(n)}return i}async page({offset:t=0,size:e=100,partition:r=null,partitionValues:i={},skipCount:n=!1}={}){const[s,o,a]=await ft(async()=>{let s=null,o=null;if(!n){const[t,n,a]=await ft(()=>this.count({partition:r,partitionValues:i}));t?(s=a,o=Math.ceil(s/e)):(s=null,o=null)}const a=Math.floor(t/e);let c=[];if(e<=0)c=[];else{const[n,s,o]=await ft(()=>this.list({partition:r,partitionValues:i,limit:e,offset:t}));c=n?o:[]}const u={items:c,totalItems:s,page:a,pageSize:e,totalPages:o,hasMore:c.length===e&&t+e<(s||1/0),_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:c.length,skipCount:n,hasTotalItems:null!==s}};return this.emit("page",u),u});return s?a:{items:[],totalItems:null,page:Math.floor(t/e),pageSize:e,totalPages:null,_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:0,skipCount:n,hasTotalItems:!1,error:o.message}}}readable(){return new yi({resource:this}).build()}writable(){return new bi({resource:this}).build()}async setContent({id:t,buffer:e,contentType:r="application/octet-stream"}){const[i,n,s]=await ft(()=>this.get(t));if(!i||!s)throw new ct(`Resource with id '${t}' not found`,{resourceName:this.name,id:t,operation:"setContent"});const o={...s,_hasContent:!0,_contentLength:e.length,_mimeType:r},a=await this.schema.mapper(o),[c,u]=await ft(()=>this.client.putObject({key:this.getResourceKey(t),metadata:a,body:e,contentType:r}));if(!c)throw u;return this.emit("setContent",{id:t,contentType:r,contentLength:e.length}),o}async content(t){const e=this.getResourceKey(t),[r,i,n]=await ft(()=>this.client.getObject(e));if(!r){if("NoSuchKey"===i.name)return{buffer:null,contentType:null};throw i}const s=Buffer.from(await n.Body.transformToByteArray()),o=n.ContentType||null;return this.emit("content",t,s.length,o),{buffer:s,contentType:o}}async hasContent(t){const e=this.getResourceKey(t),[r,i,n]=await ft(()=>this.client.headObject(e));return!!r&&n.ContentLength>0}async deleteContent(t){const e=this.getResourceKey(t),[r,i,n]=await ft(()=>this.client.headObject(e));if(!r)throw i;const s=n.Metadata||{},[o,a,c]=await ft(()=>this.client.putObject({key:e,body:"",metadata:s}));if(!o)throw a;return this.emit("deleteContent",t),c}getDefinitionHash(){const t={attributes:this.attributes,behavior:this.behavior},e=y(t);return`sha256:${g("sha256").update(e).digest("hex")}`}extractVersionFromKey(t){const e=t.split("/").find(t=>t.startsWith("v="));return e?e.replace("v=",""):null}async getSchemaForVersion(t){if(t===this.version)return this.schema;const[e,r,i]=await ft(()=>Promise.resolve(new Mi({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:t,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})));return e?i:this.schema}async createPartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,i]of Object.entries(e)){const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)};await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})}}}async deletePartitionReferences(t){const e=this.config.partitions;if(!e||0===Object.keys(e).length)return;const r=[];for(const[i,n]of Object.entries(e)){const e=this.getPartitionKey({partitionName:i,id:t.id,data:t});e&&r.push(e)}if(r.length>0){const[t,e]=await ft(()=>this.client.deleteObjects(r))}}async query(t={},{limit:e=100,offset:r=0,partition:i=null,partitionValues:n={}}={}){if(0===Object.keys(t).length)return await this.list({partition:i,partitionValues:n,limit:e,offset:r});const s=[];let o=r;const a=Math.min(e,50);for(;s.length<e;){const e=await this.list({partition:i,partitionValues:n,limit:a,offset:o});if(0===e.length)break;const r=e.filter(e=>Object.entries(t).every(([t,r])=>e[t]===r));if(s.push(...r),o+=a,e.length<a)break}return s.slice(0,e)}async handlePartitionReferenceUpdates(t,e){const r=this.config.partitions;if(!r||0===Object.keys(r).length)return;for(const[i,n]of Object.entries(r)){const[r,s]=await ft(()=>this.handlePartitionReferenceUpdate(i,n,t,e))}const i=e.id||t.id;for(const[t,n]of Object.entries(r)){const r=`resource=${this.name}/partition=${t}`;let n=[];const[s,o,a]=await ft(()=>this.client.getAllKeys({prefix:r}));if(!s)continue;n=a;const c=this.getPartitionKey({partitionName:t,id:i,data:e});for(const t of n)if(t.endsWith(`/id=${i}`)&&t!==c){const[e,r]=await ft(()=>this.client.deleteObject(t))}}}async handlePartitionReferenceUpdate(t,e,r,i){const n=i.id||r.id,s=this.getPartitionKey({partitionName:t,id:n,data:r}),o=this.getPartitionKey({partitionName:t,id:n,data:i});if(s!==o){if(s){const[t,e]=await ft(async()=>{await this.client.deleteObject(s)})}if(o){const[t,e]=await ft(async()=>{const t={_v:String(this.version)};await this.client.putObject({key:o,metadata:t,body:"",contentType:void 0})})}}else if(o){const[t,e]=await ft(async()=>{const t={_v:String(this.version)};await this.client.putObject({key:o,metadata:t,body:"",contentType:void 0})})}}async updatePartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,i]of Object.entries(e)){if(!i||!i.fields||"object"!=typeof i.fields)continue;const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)},[r,i]=await ft(async()=>{await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})})}}}async getFromPartition({id:t,partitionName:e,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[e])throw new ut(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"getFromPartition"});const i=this.config.partitions[e],n=[],s=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of s){const i=r[t];if(null!=i){const r=this.applyPartitionRule(i,e);n.push(`${t}=${r}`)}}if(0===n.length)throw new ut(`No partition values provided for partition '${e}'`,{resourceName:this.name,partitionName:e,operation:"getFromPartition"});const o=Lt(`resource=${this.name}`,`partition=${e}`,...n,`id=${t}`),[a,c]=await ft(async()=>{await this.client.headObject(o)});if(!a)throw new ct(`Resource with id '${t}' not found in partition '${e}'`,{resourceName:this.name,id:t,partitionName:e,operation:"getFromPartition"});const u=await this.get(t);return u._partition=e,u._partitionValues=r,this.emit("getFromPartition",u),u}async createHistoricalVersion(t,e){const r=Lt(`resource=${this.name}`,"historical",`id=${t}`),i={...e,_v:e._v||this.version,_historicalTimestamp:(new Date).toISOString()},n=await this.schema.mapper(i),s=Qi(this.behavior),{mappedData:o,body:a}=await s.handleInsert({resource:this,data:i,mappedData:n}),c={...o,_v:e._v||this.version,_historicalTimestamp:i._historicalTimestamp};let u;if(a&&""!==a){const[t,e]=await ft(()=>Promise.resolve(JSON.parse(a)));t&&(u="application/json")}await this.client.putObject({key:r,metadata:c,body:a,contentType:u})}async applyVersionMapping(t,e,r){if(e===r)return t;return{...t,_v:r,_originalVersion:e,_versionMapped:!0}}async composeFullObjectFromWrite({id:t,metadata:e,body:r,behavior:i}){const n={};e&&"true"===e.$truncated&&(n.$truncated="true"),e&&"true"===e.$overflow&&(n.$overflow="true");let s={};const[o,a,c]=await ft(()=>this.schema.unmapper(e));s=o?c:e;const u=t=>{if(!t||"object"!=typeof t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||(e[r]=i);return e},l=t=>{if("object"==typeof t&&null!==t)return t;if("string"==typeof t){if("[object Object]"===t)return{};if(t.startsWith("{")||t.startsWith("[")){const[e,r,i]=ht(()=>JSON.parse(t));return e?i:t}return t}return t};if("body-overflow"===i){const i=e&&"true"===e.$overflow;let n={};if(i&&r){const[t,e,i]=await ft(()=>Promise.resolve(JSON.parse(r)));if(t){const[t,e,r]=await ft(()=>this.schema.unmapper(i));n=t?r:{}}}const o={...s,...n,id:t};Object.keys(o).forEach(t=>{o[t]=l(o[t])});const a=u(o);return i&&(a.$overflow="true"),a}if("body-only"===i){const[i,n,s]=await ft(()=>Promise.resolve(r?JSON.parse(r):{}));let o=this.schema.map;if(e&&e._map){const[t,r,i]=await ft(()=>Promise.resolve("string"==typeof e._map?JSON.parse(e._map):e._map));o=t?i:this.schema.map}const[a,c,u]=await ft(()=>this.schema.unmapper(s,o)),h=a?{...u,id:t}:{id:t};return Object.keys(h).forEach(t=>{h[t]=l(h[t])}),h}const h={...s,id:t};Object.keys(h).forEach(t=>{h[t]=l(h[t])});const f=u(h);return n.$truncated&&(f.$truncated=n.$truncated),n.$overflow&&(f.$overflow=n.$overflow),f}emit(t,...e){return super.emit(t,...e)}async replace(t,e){await this.delete(t),await new Promise(t=>setTimeout(t,100));const r=Date.now();for(;Date.now()-r<5e3;){if(!await this.exists(t))break;await new Promise(t=>setTimeout(t,50))}try{return await this.insert({...e,id:t})}catch(r){if(r&&r.message&&r.message.includes("already exists")){return await this.update(t,e)}throw r}}_initMiddleware(){this._middlewares=new Map,this._middlewareMethods=["get","list","listIds","getAll","count","page","insert","update","delete","deleteMany","exists","getMany"];for(const t of this._middlewareMethods)this._middlewares.set(t,[]),this[`_original_${t}`]||(this[`_original_${t}`]=this[t].bind(this),this[t]=async(...e)=>{const r={resource:this,args:e,method:t};let i=-1;const n=this._middlewares.get(t),s=async e=>{if(e<=i)throw new Error("next() called multiple times");return i=e,e<n.length?await n[e](r,()=>s(e+1)):await this[`_original_${t}`](...r.args)};return await s(0)})}useMiddleware(t,e){if(this._middlewares||this._initMiddleware(),!this._middlewares.has(t))throw new ct(`No such method for middleware: ${t}`,{operation:"useMiddleware",method:t});this._middlewares.get(t).push(e)}applyDefaults(t){const e={...t};for(const[t,r]of Object.entries(this.attributes))if(void 0===e[t]&&"string"==typeof r&&r.includes("default:")){const i=r.match(/default:([^|]+)/);if(i){let n=i[1];r.includes("boolean")?n="true"===n:r.includes("number")&&(n=Number(n)),e[t]=n}}return e}}var rn=en;class nn extends St{constructor(t){super(),this.version="1",this.s3dbVersion=(()=>{const[t,e,r]=ft(()=>"7.2.1");return t?r:"latest"})(),this.resources={},this.savedMetadata=null,this.options=t,this.verbose=t.verbose||!1,this.parallelism=parseInt(t.parallelism+"")||10,this.plugins=t.plugins||[],this.pluginList=t.plugins||[],this.cache=t.cache,this.passphrase=t.passphrase||"secret",this.versioningEnabled=t.versioningEnabled||!1;let e=t.connectionString;if(!e&&(t.bucket||t.accessKeyId||t.secretAccessKey)){const{bucket:r,region:i,accessKeyId:n,secretAccessKey:s,endpoint:o,forcePathStyle:a}=t;if(o){const t=new URL(o);n&&(t.username=encodeURIComponent(n)),s&&(t.password=encodeURIComponent(s)),t.pathname=`/${r||"s3db"}`,a&&t.searchParams.set("forcePathStyle","true"),e=t.toString()}else if(n&&s){const t=new URLSearchParams;t.set("region",i||"us-east-1"),a&&t.set("forcePathStyle","true"),e=`s3://${encodeURIComponent(n)}:${encodeURIComponent(s)}@${r||"s3db"}?${t.toString()}`}}this.client=t.client||new Di({verbose:this.verbose,parallelism:this.parallelism,connectionString:e}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix,this._exitListenerRegistered||(this._exitListenerRegistered=!0,process.on("exit",async()=>{if(this.isConnected())try{await this.disconnect()}catch(t){}}))}async connect(){await this.startPlugins();let t=null;if(await this.client.exists("s3db.json")){const e=await this.client.getObject("s3db.json");t=JSON.parse(await wi(e?.Body))}else t=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=t;const e=this.detectDefinitionChanges(t);for(const[e,r]of Object.entries(t.resources||{})){const t=r.currentVersion||"v0",i=r.versions?.[t];i&&(this.resources[e]=new rn({name:e,client:this.client,database:this,version:t,attributes:i.attributes,behavior:i.behavior||"user-managed",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:void 0!==i.timestamps&&i.timestamps,partitions:r.partitions||i.partitions||{},paranoid:void 0===i.paranoid||i.paranoid,allNestedObjectsOptional:void 0===i.allNestedObjectsOptional||i.allNestedObjectsOptional,autoDecrypt:void 0===i.autoDecrypt||i.autoDecrypt,hooks:i.hooks||{},versioningEnabled:this.versioningEnabled,map:i.map}))}e.length>0&&this.emit("resourceDefinitionsChanged",{changes:e,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(t){const e=[];for(const[r,i]of Object.entries(this.resources)){const n=this.generateDefinitionHash(i.export()),s=t.resources?.[r];if(s){const t=s.currentVersion||"v0",i=s.versions?.[t],o=i?.hash;o!==n&&e.push({type:"changed",resourceName:r,currentHash:n,savedHash:o,fromVersion:t,toVersion:this.getNextVersion(s.versions)})}else e.push({type:"new",resourceName:r,currentHash:n,savedHash:null})}for(const[r,i]of Object.entries(t.resources||{}))if(!this.resources[r]){const t=i.currentVersion||"v0",n=i.versions?.[t];e.push({type:"deleted",resourceName:r,currentHash:null,savedHash:n?.hash,deletedVersion:t})}return e}generateDefinitionHash(t,e=void 0){const r={...t.attributes};t.timestamps&&(delete r.createdAt,delete r.updatedAt);const i={attributes:r,behavior:e||t.behavior||"user-managed",partitions:t.partitions||{}},n=y(i);return`sha256:${g("sha256").update(n).digest("hex")}`}getNextVersion(t={}){const e=Object.keys(t).filter(t=>t.startsWith("v")).map(t=>parseInt(t.substring(1))).filter(t=>!isNaN(t));return`v${(e.length>0?Math.max(...e):-1)+1}`}async startPlugins(){const t=this;if(!c(this.pluginList)){const e=this.pluginList.map(t=>m(t)?new t(this):t),r=e.map(async e=>{e.beforeSetup&&await e.beforeSetup(),await e.setup(t),e.afterSetup&&await e.afterSetup()});await Promise.all(r);const i=e.map(async t=>{t.beforeStart&&await t.beforeStart(),await t.start(),t.afterStart&&await t.afterStart()});await Promise.all(i)}}async usePlugin(t,e=null){const r=e||t.constructor.name.replace("Plugin","").toLowerCase();return this.plugins[r]=t,this.isConnected()&&(await t.setup(this),await t.start()),t}async uploadMetadataFile(){const t={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:(new Date).toISOString(),resources:{}};Object.entries(this.resources).forEach(([e,r])=>{const i=r.export(),n=this.generateDefinitionHash(i),s=this.savedMetadata?.resources?.[e],o=s?.currentVersion||"v0",a=s?.versions?.[o];let c,u;a&&a.hash===n?(c=o,u=!1):(c=this.getNextVersion(s?.versions),u=!0),t.resources[e]={currentVersion:c,partitions:r.config.partitions||{},versions:{...s?.versions,[c]:{hash:n,attributes:i.attributes,behavior:i.behavior||"user-managed",timestamps:r.config.timestamps,partitions:r.config.partitions,paranoid:r.config.paranoid,allNestedObjectsOptional:r.config.allNestedObjectsOptional,autoDecrypt:r.config.autoDecrypt,cache:r.config.cache,hooks:r.config.hooks,createdAt:u?(new Date).toISOString():a?.createdAt}}},r.version!==c&&(r.version=c,r.emit("versionUpdated",{oldVersion:o,newVersion:c}))}),await this.client.putObject({key:"s3db.json",body:JSON.stringify(t,null,2),contentType:"application/json"}),this.savedMetadata=t,this.emit("metadataUploaded",t)}blankMetadataStructure(){return{version:"1",s3dbVersion:this.s3dbVersion,resources:{}}}resourceExists(t){return!!this.resources[t]}resourceExistsWithSameHash({name:t,attributes:e,behavior:r="user-managed",partitions:i={},options:n={}}){if(!this.resources[t])return{exists:!1,sameHash:!1,hash:null};const s=this.resources[t],o=this.generateDefinitionHash(s.export()),a=new rn({name:t,attributes:e,behavior:r,partitions:i,client:this.client,version:s.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...n}),c=this.generateDefinitionHash(a.export());return{exists:!0,sameHash:o===c,hash:c,existingHash:o}}async createResource({name:t,attributes:e,behavior:r="user-managed",hooks:i,...n}){if(this.resources[t]){const s=this.resources[t];if(Object.assign(s.config,{cache:this.cache,...n}),r&&(s.behavior=r),s.versioningEnabled=this.versioningEnabled,s.updateAttributes(e),i)for(const[t,e]of Object.entries(i))if(Array.isArray(e)&&s.hooks[t])for(const r of e)"function"==typeof r&&s.hooks[t].push(r.bind(s));const o=this.generateDefinitionHash(s.export(),s.behavior),a=this.savedMetadata?.resources?.[t],c=a?.currentVersion||"v0",u=a?.versions?.[c];return u&&u.hash===o||await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",t),s}const s=this.savedMetadata?.resources?.[t],o=s?.currentVersion||"v0",a=new rn({name:t,client:this.client,version:void 0!==n.version?n.version:o,attributes:e,behavior:r,parallelism:this.parallelism,passphrase:void 0!==n.passphrase?n.passphrase:this.passphrase,observers:[this],cache:void 0!==n.cache?n.cache:this.cache,timestamps:void 0!==n.timestamps&&n.timestamps,partitions:n.partitions||{},paranoid:void 0===n.paranoid||n.paranoid,allNestedObjectsOptional:void 0===n.allNestedObjectsOptional||n.allNestedObjectsOptional,autoDecrypt:void 0===n.autoDecrypt||n.autoDecrypt,hooks:i||{},versioningEnabled:this.versioningEnabled,map:n.map,idGenerator:n.idGenerator,idSize:n.idSize});return a.database=this,this.resources[t]=a,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",t),a}resource(t){return this.resources[t]?this.resources[t]:Promise.reject(`resource ${t} does not exist`)}async listResources(){return Object.keys(this.resources).map(t=>({name:t}))}async getResource(t){if(!this.resources[t])throw new G({bucket:this.client.config.bucket,resourceName:t,id:t});return this.resources[t]}get config(){return{version:this.version,s3dbVersion:this.s3dbVersion,bucket:this.bucket,keyPrefix:this.keyPrefix,parallelism:this.parallelism,verbose:this.verbose}}isConnected(){return!!this.savedMetadata}async disconnect(){try{if(this.pluginList&&this.pluginList.length>0){for(const t of this.pluginList)t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners();const t=this.pluginList.map(async t=>{try{t&&"function"==typeof t.stop&&await t.stop()}catch(t){}});await Promise.all(t)}if(this.resources&&Object.keys(this.resources).length>0){for(const[t,e]of Object.entries(this.resources))try{e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners(),e._pluginWrappers&&e._pluginWrappers.clear(),e._pluginMiddlewares&&(e._pluginMiddlewares={}),e.observers&&Array.isArray(e.observers)&&(e.observers=[])}catch(t){}Object.keys(this.resources).forEach(t=>delete this.resources[t])}this.client&&"function"==typeof this.client.removeAllListeners&&this.client.removeAllListeners(),this.removeAllListeners(),this.savedMetadata=null,this.plugins={},this.pluginList=[],this.emit("disconnected",new Date)}catch(t){}}}class sn extends nn{}function on(t){return"string"==typeof t?t.trim().toLowerCase():t}class an extends At{constructor(t={}){if(super(),!t.replicators||!Array.isArray(t.replicators))throw new Error("ReplicatorPlugin: replicators array is required");for(const e of t.replicators){if(!e.driver)throw new Error("ReplicatorPlugin: each replicator must have a driver");if(!e.resources||"object"!=typeof e.resources)throw new Error("ReplicatorPlugin: each replicator must have resources config");if(0===Object.keys(e.resources).length)throw new Error("ReplicatorPlugin: each replicator must have at least one resource configured")}this.config={replicators:t.replicators||[],logErrors:!1!==t.logErrors,replicatorLogResource:t.replicatorLogResource||"replicator_log",enabled:!1!==t.enabled,batchSize:t.batchSize||100,maxRetries:t.maxRetries||3,timeout:t.timeout||3e4,verbose:t.verbose||!1,...t},this.replicators=[],this.database=null,this.eventListenersInstalled=new Set}async decompressData(t){return t}filterInternalFields(t){if(!t||"object"!=typeof t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||"$overflow"===r||"$before"===r||"$after"===r||(e[r]=i);return e}installEventListeners(t,e,r){t&&!this.eventListenersInstalled.has(t.name)&&(t.on("insert",async e=>{try{const i={...e,createdAt:(new Date).toISOString()};await r.processReplicatorEvent("insert",t.name,i.id,i)}catch(e){this.emit("error",{operation:"insert",error:e.message,resource:t.name})}}),t.on("update",async(e,i)=>{try{const n={...e,updatedAt:(new Date).toISOString()};await r.processReplicatorEvent("update",t.name,n.id,n,i)}catch(e){this.emit("error",{operation:"update",error:e.message,resource:t.name})}}),t.on("delete",async e=>{try{await r.processReplicatorEvent("delete",t.name,e.id,e)}catch(e){this.emit("error",{operation:"delete",error:e.message,resource:t.name})}}),this.eventListenersInstalled.add(t.name))}async getCompleteData(t,e){const[r,i,n]=await ft(()=>t.get(e.id));return r?n:e}async setup(t){this.database=t;try{await this.initializeReplicators(t)}catch(t){throw this.emit("error",{operation:"setup",error:t.message}),t}try{if(this.config.replicatorLogResource){await t.createResource({name:this.config.replicatorLogResource,behavior:"body-overflow",attributes:{operation:"string",resourceName:"string",recordId:"string",data:"string",error:"string|optional",replicator:"string",timestamp:"string",status:"string"}})}}catch(t){}await this.uploadMetadataFile(t);const e=t.createResource.bind(t);t.createResource=async r=>{const i=await e(r);return i&&this.installEventListeners(i,t,this),i};for(const e in t.resources){const r=t.resources[e];this.installEventListeners(r,t,this)}}async initializeReplicators(t){for(const e of this.config.replicators){const{driver:r,config:i,resources:n}=e,s=this.createReplicator(r,i,n);s&&(await s.initialize(t),this.replicators.push(s))}}async start(){}async stop(){}async processReplicatorEvent(t,e,r,i,n=null){if(!this.config.enabled)return;const s=this.replicators.filter(r=>r.shouldReplicateResource&&r.shouldReplicateResource(e,t));if(0===s.length)return;const o=s.map(async s=>{try{const o=await this.retryWithBackoff(()=>s.replicate(e,t,i,r,n),this.config.maxRetries);return this.emit("replicated",{replicator:s.name||s.id,resourceName:e,operation:t,recordId:r,result:o,success:!0}),o}catch(n){throw this.emit("replicator_error",{replicator:s.name||s.id,resourceName:e,operation:t,recordId:r,error:n.message}),this.config.logErrors&&this.database&&await this.logError(s,e,t,r,i,n),n}});return Promise.allSettled(o)}async processreplicatorItem(t){const e=this.replicators.filter(e=>e.shouldReplicateResource&&e.shouldReplicateResource(t.resourceName,t.operation));if(0===e.length)return;const r=e.map(async e=>{try{const[r,i,n]=await ft(()=>e.replicate(t.resourceName,t.operation,t.data,t.recordId,t.beforeData));return r?(this.emit("replicated",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,result:n,success:!0}),{success:!0,result:n}):(this.emit("replicator_error",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,error:i.message}),this.config.logErrors&&this.database&&await this.logError(e,t.resourceName,t.operation,t.recordId,t.data,i),{success:!1,error:i.message})}catch(r){return this.emit("replicator_error",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,error:r.message}),this.config.logErrors&&this.database&&await this.logError(e,t.resourceName,t.operation,t.recordId,t.data,r),{success:!1,error:r.message}}});return Promise.allSettled(r)}async logreplicator(t){const e=this.replicatorLog||this.database.resources[on(this.config.replicatorLogResource)];if(!e)return this.database&&this.database.options&&this.database.options.connectionString,void this.emit("replicator.log.failed",{error:"replicator log resource not found",item:t});const r={id:t.id||`repl-${Date.now()}-${Math.random().toString(36).slice(2)}`,resource:t.resource||t.resourceName||"",action:t.operation||t.action||"",data:t.data||{},timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now(),createdAt:t.createdAt||(new Date).toISOString().slice(0,10)};try{await e.insert(r)}catch(e){this.emit("replicator.log.failed",{error:e,item:t})}}async updatereplicatorLog(t,e){if(!this.replicatorLog)return;const[r,i]=await ft(async()=>{await this.replicatorLog.update(t,{...e,lastAttempt:(new Date).toISOString()})});r||this.emit("replicator.updateLog.failed",{error:i.message,logId:t,updates:e})}async getreplicatorStats(){return{replicators:await Promise.all(this.replicators.map(async t=>{const e=await t.instance.getStatus();return{id:t.id,driver:t.driver,config:t.config,status:e}})),queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getreplicatorLogs(t={}){if(!this.replicatorLog)return[];const{resourceName:e,operation:r,status:i,limit:n=100,offset:s=0}=t;let o={};e&&(o.resourceName=e),r&&(o.operation=r),i&&(o.status=i);return(await this.replicatorLog.list(o)).slice(s,s+n)}async retryFailedreplicators(){if(!this.replicatorLog)return{retried:0};const t=await this.replicatorLog.list({status:"failed"});let e=0;for(const r of t){const[t,i]=await ft(async()=>{await this.processReplicatorEvent(r.resourceName,r.operation,r.recordId,r.data)});t&&e++}return{retried:e}}async syncAllData(t){const e=this.replicators.find(e=>e.id===t);if(!e)throw new Error(`Replicator not found: ${t}`);this.stats.lastSync=(new Date).toISOString();for(const r in this.database.resources)if(on(r)!==on("replicator_logs")&&e.instance.shouldReplicateResource(r)){this.emit("replicator.sync.resource",{resourceName:r,replicatorId:t});const i=this.database.resources[r],n=await i.getAll();for(const t of n)await e.instance.replicate(r,"insert",t,t.id)}this.emit("replicator.sync.completed",{replicatorId:t,stats:this.stats})}async cleanup(){try{if(this.replicators&&this.replicators.length>0){const t=this.replicators.map(async t=>{try{t&&"function"==typeof t.cleanup&&await t.cleanup()}catch(t){}});await Promise.allSettled(t)}this.replicators=[],this.database=null,this.eventListenersInstalled.clear(),this.removeAllListeners()}catch(t){}}}export{Xi as AVAILABLE_BEHAVIORS,Et as AuditPlugin,W as AuthenticationError,z as BaseError,Oi as CachePlugin,Ri as Client,ji as ConnectionString,st as ConnectionStringError,Si as CostsPlugin,ot as CryptoError,tn as DEFAULT_BEHAVIOR,nn as Database,q as DatabaseError,Y as EncryptionError,it as ErrorMap,_i as FullTextPlugin,et as InvalidResourceItem,xi as MetricsPlugin,tt as MissingMetadata,Z as NoSuchBucket,Q as NoSuchKey,X as NotFound,ut as PartitionError,J as PermissionError,At as Plugin,Nt as PluginObject,an as ReplicatorPlugin,en as Resource,ct as ResourceError,gi as ResourceIdsPageReader,pi as ResourceIdsReader,G as ResourceNotFound,yi as ResourceReader,bi as ResourceWriter,nn as S3db,K as S3dbError,Ci as Schema,at as SchemaError,rt as UnknownError,H as ValidationError,Ei as Validator,Zi as behaviors,T as calculateAttributeNamesSize,L as calculateAttributeSizes,V as calculateEffectiveLimit,F as calculateSystemOverhead,U as calculateTotalSize,M as calculateUTF8Bytes,P as decode,C as decodeDecimal,gt as decrypt,sn as default,E as encode,I as encodeDecimal,mt as encrypt,Qi as getBehavior,B as getSizeBreakdown,wt as idGenerator,nt as mapAwsError,yt as md5,vt as passwordGenerator,pt as sha256,wi as streamToString,$ as transformValue,lt as tryFn,ht as tryFnSync};