s3db.js 6.2.0 → 7.0.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.
- package/PLUGINS.md +2724 -0
- package/README.md +372 -469
- package/UNLICENSE +24 -0
- package/dist/s3db.cjs.js +12105 -19396
- package/dist/s3db.cjs.min.js +1 -1
- package/dist/s3db.d.ts +373 -72
- package/dist/s3db.es.js +12090 -19393
- package/dist/s3db.es.min.js +1 -1
- package/dist/s3db.iife.js +12103 -19398
- package/dist/s3db.iife.min.js +1 -1
- package/package.json +44 -38
- package/src/behaviors/body-only.js +110 -0
- package/src/behaviors/body-overflow.js +153 -0
- package/src/behaviors/enforce-limits.js +195 -0
- package/src/behaviors/index.js +39 -0
- package/src/behaviors/truncate-data.js +204 -0
- package/src/behaviors/user-managed.js +147 -0
- package/src/client.class.js +515 -0
- package/src/concerns/base62.js +61 -0
- package/src/concerns/calculator.js +204 -0
- package/src/concerns/crypto.js +159 -0
- package/src/concerns/id.js +8 -0
- package/src/concerns/index.js +5 -0
- package/src/concerns/try-fn.js +151 -0
- package/src/connection-string.class.js +75 -0
- package/src/database.class.js +599 -0
- package/src/errors.js +261 -0
- package/src/index.js +17 -0
- package/src/plugins/audit.plugin.js +442 -0
- package/src/plugins/cache/cache.class.js +53 -0
- package/src/plugins/cache/index.js +6 -0
- package/src/plugins/cache/memory-cache.class.js +164 -0
- package/src/plugins/cache/s3-cache.class.js +189 -0
- package/src/plugins/cache.plugin.js +275 -0
- package/src/plugins/consumers/index.js +24 -0
- package/src/plugins/consumers/rabbitmq-consumer.js +56 -0
- package/src/plugins/consumers/sqs-consumer.js +102 -0
- package/src/plugins/costs.plugin.js +81 -0
- package/src/plugins/fulltext.plugin.js +473 -0
- package/src/plugins/index.js +12 -0
- package/src/plugins/metrics.plugin.js +603 -0
- package/src/plugins/plugin.class.js +210 -0
- package/src/plugins/plugin.obj.js +13 -0
- package/src/plugins/queue-consumer.plugin.js +134 -0
- package/src/plugins/replicator.plugin.js +769 -0
- package/src/plugins/replicators/base-replicator.class.js +85 -0
- package/src/plugins/replicators/bigquery-replicator.class.js +328 -0
- package/src/plugins/replicators/index.js +44 -0
- package/src/plugins/replicators/postgres-replicator.class.js +427 -0
- package/src/plugins/replicators/s3db-replicator.class.js +352 -0
- package/src/plugins/replicators/sqs-replicator.class.js +427 -0
- package/src/resource.class.js +2626 -0
- package/src/s3db.d.ts +1263 -0
- package/src/schema.class.js +706 -0
- package/src/stream/index.js +16 -0
- package/src/stream/resource-ids-page-reader.class.js +10 -0
- package/src/stream/resource-ids-reader.class.js +63 -0
- package/src/stream/resource-reader.class.js +81 -0
- package/src/stream/resource-writer.class.js +92 -0
- package/src/validator.class.js +97 -0
package/dist/s3db.iife.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var S3DB=function(t,e,r,n,i,s,o,a,c){"use strict";function u(t,e){for(var r=0,n=t.length-1;n>=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}var l=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,h=function(t){return l.exec(t).slice(1)};function f(){for(var t="",e=!1,r=arguments.length-1;r>=-1&&!e;r--){var n=r>=0?arguments[r]:"/";if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");n&&(t=n+"/"+t,e="/"===n.charAt(0))}return(e?"/":"")+(t=u(y(t.split("/"),function(t){return!!t}),!e).join("/"))||"."}function d(t){var e=p(t),r="/"===b(t,-1);return(t=u(y(t.split("/"),function(t){return!!t}),!e).join("/"))||e||(t="."),t&&r&&(t+="/"),(e?"/":"")+t}function p(t){return"/"===t.charAt(0)}function g(){return d(y(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 m={extname:function(t){return h(t)[3]},basename:function(t,e){var r=h(t)[2];return e&&r.substr(-1*e.length)===e&&(r=r.substr(0,r.length-e.length)),r},dirname:function(t){var e=h(t),r=e[0],n=e[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},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=f(t).substr(1),e=f(e).substr(1);for(var n=r(t.split("/")),i=r(e.split("/")),s=Math.min(n.length,i.length),o=s,a=0;a<s;a++)if(n[a]!==i[a]){o=a;break}var c=[];for(a=o;a<n.length;a++)c.push("..");return(c=c.concat(i.slice(o))).join("/")},join:g,isAbsolute:p,normalize:d,resolve:f};function y(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n<t.length;n++)e(t[n],n,t)&&r.push(t[n]);return r}var b="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)};const w=e.customAlphabet(e.urlAlphabet,22),_=e.customAlphabet("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",12);var v;function k(){}function S(){S.init.call(this)}function O(t){return void 0===t._maxListeners?S.defaultMaxListeners:t._maxListeners}function E(t,e,r,n){var i,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 k,t._eventsCount=0),o){if("function"==typeof o?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=O(t))&&i>0&&o.length>i){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 R(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function x(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 A(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}k.prototype=Object.create(null),S.EventEmitter=S,S.usingDomains=!1,S.prototype.domain=void 0,S.prototype._events=void 0,S.prototype._maxListeners=void 0,S.defaultMaxListeners=10,S.init=function(){this.domain=null,S.usingDomains&&(!v.active||this instanceof v.Domain||(this.domain=v.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new k,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},S.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},S.prototype.getMaxListeners=function(){return O(this)},S.prototype.emit=function(t){var e,r,n,i,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(n=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var n=t.length,i=A(t,n),s=0;s<n;++s)i[s].call(r)}(r,l,this);break;case 2:!function(t,e,r,n){if(e)t.call(r,n);else for(var i=t.length,s=A(t,i),o=0;o<i;++o)s[o].call(r,n)}(r,l,this,arguments[1]);break;case 3:!function(t,e,r,n,i){if(e)t.call(r,n,i);else for(var s=t.length,o=A(t,s),a=0;a<s;++a)o[a].call(r,n,i)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(t,e,r,n,i,s){if(e)t.call(r,n,i,s);else for(var o=t.length,a=A(t,o),c=0;c<o;++c)a[c].call(r,n,i,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];!function(t,e,r,n){if(e)t.apply(r,n);else for(var i=t.length,s=A(t,i),o=0;o<i;++o)s[o].apply(r,n)}(r,l,this,i)}return!0},S.prototype.addListener=function(t,e){return E(this,t,e,!1)},S.prototype.on=S.prototype.addListener,S.prototype.prependListener=function(t,e){return E(this,t,e,!0)},S.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,R(this,t,e)),this},S.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,R(this,t,e)),this},S.prototype.removeListener=function(t,e){var r,n,i,s,o;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[t]))return this;if(r===e||r.listener&&r.listener===e)0===--this._eventsCount?this._events=new k:(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new k,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n<i;r+=1,n+=1)t[r]=t[n];t.pop()}(r,i);n.removeListener&&this.emit("removeListener",t,o||e)}return this},S.prototype.off=function(t,e){return this.removeListener(t,e)},S.prototype.removeAllListeners=function(t){var e,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new k,this._eventsCount=0):r[t]&&(0===--this._eventsCount?this._events=new k:delete r[t]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new k,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},S.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):[]},S.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):x.call(t,e)},S.prototype.listenerCount=x,S.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class j extends Error{constructor({verbose:t,bucket:e,message:r,...n}){t&&(r+=`\n\nVerbose:\n\n${JSON.stringify(n,null,2)}`),super(r),"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error(r).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=e,this.thrownAt=new Date}toJson(){return{...this}}toString(){return`${this.name} | ${this.message}`}}class I extends j{constructor(t,e={}){super({message:t,...e})}}class D extends I{constructor({bucket:t,...e}){super(`Bucket does not exists [bucket:${t}]`,{bucket:t,...e})}}class P extends I{constructor({bucket:t,key:e,...r}){super(`Key [${e}] does not exists [bucket:${t}/${e}]`,{bucket:t,key:e,...r})}}class T extends P{}class N extends I{constructor({bucket:t,...e}){super(`Missing metadata for bucket [bucket:${t}]`,{bucket:t,...e})}}class C extends I{constructor({bucket:t,resourceName:e,attributes:r,validation:n}){super(`This item is not valid. Resource=${e} [bucket:${t}].\n${JSON.stringify(n,null,2)}`,{bucket:t,resourceName:e,attributes:r,validation:n})}}class M extends I{}const L={NotFound:T,NoSuchKey:P,UnknownError:M,NoSuchBucket:D,MissingMetadata:N,InvalidResourceItem:C},$="us-east-1",U="https://s3.us-east-1.amazonaws.com";class z{constructor(t){let e;try{e=new URL(t)}catch(e){throw new Error("Invalid connection string: "+t)}this.region=$,"s3:"===e.protocol?this.defineS3(e):this.defineMinio(e);for(const[t,r]of e.searchParams.entries())this[t]=r}defineS3(t){if(this.bucket=decodeURIComponent(t.hostname),this.accessKeyId=decodeURIComponent(t.username),this.secretAccessKey=decodeURIComponent(t.password),this.endpoint=U,["/","",null].includes(t.pathname))this.keyPrefix="";else{let[,...e]=t.pathname.split("/");this.keyPrefix=[...e||[]].join("/")}}defineMinio(t){if(this.forcePathStyle=!0,this.endpoint=t.origin,this.accessKeyId=decodeURIComponent(t.username),this.secretAccessKey=decodeURIComponent(t.password),["/","",null].includes(t.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,e,...r]=t.pathname.split("/");this.bucket=decodeURIComponent(e),this.keyPrefix=[...r||[]].join("/")}}}class F extends S{constructor({verbose:t=!1,id:e=null,AwsS3Client:r,connectionString:n,parallelism:i=10}){super(),this.verbose=t,this.id=e??w(),this.parallelism=i,this.config=new z(n),this.client=r||this.createClient()}createClient(){let t={region:this.config.region,endpoint:this.config.endpoint};return this.config.forcePathStyle&&(t.forcePathStyle=!0),this.config.accessKeyId&&(t.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey}),new i.S3Client(t)}async sendCommand(t){this.emit("command.request",t.constructor.name,t.input);const e=console.warn;try{console.warn=t=>{t.includes("Stream of unknown length")||e(t)}}catch(t){console.error(t)}const r=await this.client.send(t);this.emit("command.response",t.constructor.name,r,t.input);try{console.warn=e}catch(t){console.error(t)}return r}errorProxy(t,e){this.verbose&&(e.bucket=this.config.bucket,e.config=this.config,e.verbose=this.verbose),t.data=e;const r=L[t.name];return r?new r(e):t}async putObject({key:t,metadata:e,contentType:r,body:n,contentEncoding:s,contentLength:o}){const a="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",c={};if(e)for(const[t,r]of Object.entries(e)){c[String(t).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const u={Bucket:this.config.bucket,Key:a?m.join(a,t):t,Metadata:c,Body:n||Buffer.alloc(0)};void 0!==r&&(u.ContentType=r),void 0!==s&&(u.ContentEncoding=s),void 0!==o&&(u.ContentLength=o);try{const t=await this.sendCommand(new i.PutObjectCommand(u));return this.emit("putObject",t,u),t}catch(e){throw this.errorProxy(e,{key:t,command:u})}}async getObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?m.join(e,t):t};try{const t=await this.sendCommand(new i.GetObjectCommand(r));return this.emit("getObject",t,r),t}catch(e){throw this.errorProxy(e,{key:t,command:r})}}async headObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?m.join(e,t):t};try{const t=await this.sendCommand(new i.HeadObjectCommand(r));return this.emit("headObject",t,r),t}catch(e){throw this.errorProxy(e,{key:t,command:r})}}async copyObject({from:t,to:e}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?m.join(this.config.keyPrefix,e):e,CopySource:m.join(this.config.bucket,this.config.keyPrefix?m.join(this.config.keyPrefix,t):t)};try{const t=await this.client.send(new i.CopyObjectCommand(r));return this.emit("copyObject",t,r),t}catch(n){throw this.errorProxy(n,{from:t,to:e,command:r})}}async exists(t){try{return await this.headObject(t),!0}catch(t){if("NoSuchKey"===t.name)return!1;if("NotFound"===t.name)return!1;throw t}}async deleteObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?m.join(e,t):t};try{const t=await this.sendCommand(new i.DeleteObjectCommand(r));return this.emit("deleteObject",t,r),t}catch(e){throw this.errorProxy(e,{key:t,command:r})}}async deleteObjects(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",s=r.chunk(t,1e3),{results:o,errors:a}=await n.PromisePool.for(s).withConcurrency(this.parallelism).process(async t=>{const r={Bucket:this.config.bucket,Delete:{Objects:t.map(t=>({Key:e?m.join(e,t):t}))}};try{return await this.sendCommand(new i.DeleteObjectsCommand(r))}catch(e){throw this.errorProxy(e,{keys:t,command:r})}}),c={deleted:o,notFound:a};return this.emit("deleteObjects",c,t),c}async deleteAll({prefix:t}={}){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,n=0;do{const s=new i.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:e?m.join(e,t):t,ContinuationToken:r}),o=await this.client.send(s);if(o.Contents&&o.Contents.length>0){const e=new i.DeleteObjectsCommand({Bucket:this.config.bucket,Delete:{Objects:o.Contents.map(t=>({Key:t.Key}))}}),r=await this.client.send(e),s=r.Deleted?r.Deleted.length:0;n+=s,this.emit("deleteAll",{prefix:t,batch:s,total:n})}r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:t,totalDeleted:n}),n}async moveObject({from:t,to:e}){try{return await this.copyObject({from:t,to:e}),await this.deleteObject(t),!0}catch(r){throw this.errorProxy(r,{from:t,to:e,command:options})}}async listObjects({prefix:t,maxKeys:e=1e3,continuationToken:r}={}){const n={Bucket:this.config.bucket,MaxKeys:e,ContinuationToken:r,Prefix:this.config.keyPrefix?m.join(this.config.keyPrefix,t||""):t||""};try{const t=await this.sendCommand(new i.ListObjectsV2Command(n));return this.emit("listObjects",t,n),t}catch(t){throw this.errorProxy(t,{command:n})}}async count({prefix:t}={}){let e,r=0,n=!0;for(;n;){const i={prefix:t,continuationToken:e},s=await this.listObjects(i);r+=s.KeyCount||0,n=s.IsTruncated||!1,e=s.NextContinuationToken}return this.emit("count",r,{prefix:t}),r}async getAllKeys({prefix:t}={}){let e,r=[],n=!0;for(;n;){const i={prefix:t,continuationToken:e},s=await this.listObjects(i);s.Contents&&(r=r.concat(s.Contents.map(t=>t.Key))),n=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 n,i=!0,s=0;for(;i;){const t={prefix:e,maxKeys:r<1e3?r:r-s>1e3?1e3:r-s,continuationToken:n},o=await this.listObjects(t);if(o.Contents&&(s+=o.Contents.length),i=o.IsTruncated||!1,n=o.NextContinuationToken,s>=r)break}return this.emit("getContinuationTokenAfterOffset",n||null,t),n||null}async getKeysPage(t={}){const{prefix:e,offset:r=0,amount:n=100}=t;let i,s=[],o=!0;if(r>0&&(i=await this.getContinuationTokenAfterOffset({prefix:e,offset:r}),!i))return this.emit("getKeysPage",[],t),[];for(;o;){const t={prefix:e,continuationToken:i},r=await this.listObjects(t);if(r.Contents&&(s=s.concat(r.Contents.map(t=>t.Key))),o=r.IsTruncated||!1,i=r.NextContinuationToken,s.length>=n){s=s.slice(0,n);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:i,errors:s}=await n.PromisePool.for(r).withConcurrency(this.parallelism).process(async r=>{const n=r.replace(t,e);try{return await this.moveObject({from:r,to:n}),n}catch(t){throw this.errorProxy(t,{from:r,to:n})}});if(this.emit("moveAllObjects",{results:i,errors:s},{prefixFrom:t,prefixTo:e}),s.length>0)throw new Error("Some objects could not be moved");return i}}async function B(){let t;if("undefined"!=typeof process)try{const{webcrypto:e}=await import("crypto");t=e}catch(t){throw new Error("Crypto API not available")}else"undefined"!=typeof window&&(t=window.crypto);if(!t)throw new Error("Could not load any crypto library");return t}async function q(t){const e=await B(),r=(new TextEncoder).encode(t),n=await e.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function V(t,e){const r=await B(),n=r.getRandomValues(new Uint8Array(16)),i=await K(e,n),s=r.getRandomValues(new Uint8Array(12)),o=(new TextEncoder).encode(t),a=await r.subtle.encrypt({name:"AES-GCM",iv:s},i,o),c=new Uint8Array(n.length+s.length+a.byteLength);return c.set(n),c.set(s,n.length),c.set(new Uint8Array(a),n.length+s.length),function(t){if("undefined"!=typeof process)return Buffer.from(t).toString("base64");{const e=String.fromCharCode.apply(null,new Uint8Array(t));return window.btoa(e)}}(c)}async function H(t,e){const r=await B(),n=function(t){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(t,"base64"));{const e=window.atob(t),r=e.length,n=new Uint8Array(r);for(let t=0;t<r;t++)n[t]=e.charCodeAt(t);return n}}(t),i=n.slice(0,16),s=n.slice(16,28),o=n.slice(28),a=await K(e,i),c=await r.subtle.decrypt({name:"AES-GCM",iv:s},a,o);return(new TextDecoder).decode(c)}async function K(t,e){const r=await B(),n=(new TextEncoder).encode(t),i=await r.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]);return await r.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:1e5,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}function Z(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var W,J,G,Y,Q,X,tt,et,rt,nt,it,st,ot,at={};function ct(){if(J)return W;var t,e;J=1;var r,n={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function i(e){throw{name:"SyntaxError",message:e,at:t,text:r}}function s(n){return n&&n!==e&&i("Expected '"+n+"' instead of '"+e+"'"),e=r.charAt(t),t+=1,e}function o(){var t,r="";for("-"===e&&(r="-",s("-"));e>="0"&&e<="9";)r+=e,s();if("."===e)for(r+=".";s()&&e>="0"&&e<="9";)r+=e;if("e"===e||"E"===e)for(r+=e,s(),"-"!==e&&"+"!==e||(r+=e,s());e>="0"&&e<="9";)r+=e,s();return t=Number(r),isFinite(t)||i("Bad number"),t}function a(){var t,r,o,a="";if('"'===e)for(;s();){if('"'===e)return s(),a;if("\\"===e)if(s(),"u"===e){for(o=0,r=0;r<4&&(t=parseInt(s(),16),isFinite(t));r+=1)o=16*o+t;a+=String.fromCharCode(o)}else{if("string"!=typeof n[e])break;a+=n[e]}else a+=e}i("Bad string")}function c(){for(;e&&e<=" ";)s()}function u(){switch(c(),e){case"{":return function(){var t,r={};if("{"===e){if(s("{"),c(),"}"===e)return s("}"),r;for(;e;){if(t=a(),c(),s(":"),Object.prototype.hasOwnProperty.call(r,t)&&i('Duplicate key "'+t+'"'),r[t]=u(),c(),"}"===e)return s("}"),r;s(","),c()}}i("Bad object")}();case"[":return function(){var t=[];if("["===e){if(s("["),c(),"]"===e)return s("]"),t;for(;e;){if(t.push(u()),c(),"]"===e)return s("]"),t;s(","),c()}}i("Bad array")}();case'"':return a();case"-":return o();default:return e>="0"&&e<="9"?o():function(){switch(e){case"t":return s("t"),s("r"),s("u"),s("e"),!0;case"f":return s("f"),s("a"),s("l"),s("s"),s("e"),!1;case"n":return s("n"),s("u"),s("l"),s("l"),null;default:i("Unexpected '"+e+"'")}}()}}return W=function(n,s){var o;return r=n,t=0,e=" ",o=u(),c(),e&&i("Syntax error"),"function"==typeof s?function t(e,r){var n,i,o=e[r];if(o&&"object"==typeof o)for(n in u)Object.prototype.hasOwnProperty.call(o,n)&&(void 0===(i=t(o,n))?delete o[n]:o[n]=i);return s.call(e,r,o)}({"":o},""):o},W}function ut(){if(Y)return G;Y=1;var t,e,r,n=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,i={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function s(t){return n.lastIndex=0,n.test(t)?'"'+t.replace(n,function(t){var e=i[t];return"string"==typeof e?e:"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+t+'"'}function o(n,i){var a,c,u,l,h,f=t,d=i[n];switch(d&&"object"==typeof d&&"function"==typeof d.toJSON&&(d=d.toJSON(n)),"function"==typeof r&&(d=r.call(i,n,d)),typeof d){case"string":return s(d);case"number":return isFinite(d)?String(d):"null";case"boolean":case"null":return String(d);case"object":if(!d)return"null";if(t+=e,h=[],"[object Array]"===Object.prototype.toString.apply(d)){for(l=d.length,a=0;a<l;a+=1)h[a]=o(a,d)||"null";return u=0===h.length?"[]":t?"[\n"+t+h.join(",\n"+t)+"\n"+f+"]":"["+h.join(",")+"]",t=f,u}if(r&&"object"==typeof r)for(l=r.length,a=0;a<l;a+=1)"string"==typeof(c=r[a])&&(u=o(c,d))&&h.push(s(c)+(t?": ":":")+u);else for(c in d)Object.prototype.hasOwnProperty.call(d,c)&&(u=o(c,d))&&h.push(s(c)+(t?": ":":")+u);return u=0===h.length?"{}":t?"{\n"+t+h.join(",\n"+t)+"\n"+f+"}":"{"+h.join(",")+"}",t=f,u}}return G=function(n,i,s){var a;if(t="",e="","number"==typeof s)for(a=0;a<s;a+=1)e+=" ";else"string"==typeof s&&(e=s);if(r=i,i&&"function"!=typeof i&&("object"!=typeof i||"number"!=typeof i.length))throw new Error("JSON.stringify");return o("",{"":n})}}function lt(){if(rt)return et;rt=1;var t=Object.prototype.toString;return et=function(e){var r=t.call(e),n="[object Arguments]"===r;return n||(n="[object Array]"!==r&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===t.call(e.callee)),n}}function ht(){if(it)return nt;var t;if(it=1,!Object.keys){var e=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=lt(),i=Object.prototype.propertyIsEnumerable,s=!i.call({toString:null},"toString"),o=i.call(function(){},"prototype"),a=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],c=function(t){var e=t.constructor;return e&&e.prototype===t},u={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},l=function(){if("undefined"==typeof window)return!1;for(var t in window)try{if(!u["$"+t]&&e.call(window,t)&&null!==window[t]&&"object"==typeof window[t])try{c(window[t])}catch(t){return!0}}catch(t){return!0}return!1}();t=function(t){var i=null!==t&&"object"==typeof t,u="[object Function]"===r.call(t),h=n(t),f=i&&"[object String]"===r.call(t),d=[];if(!i&&!u&&!h)throw new TypeError("Object.keys called on a non-object");var p=o&&u;if(f&&t.length>0&&!e.call(t,0))for(var g=0;g<t.length;++g)d.push(String(g));if(h&&t.length>0)for(var m=0;m<t.length;++m)d.push(String(m));else for(var y in t)p&&"prototype"===y||!e.call(t,y)||d.push(String(y));if(s)for(var b=function(t){if("undefined"==typeof window||!l)return c(t);try{return c(t)}catch(t){return!1}}(t),w=0;w<a.length;++w)b&&"constructor"===a[w]||!e.call(t,a[w])||d.push(a[w]);return d}}return nt=t}function ft(){if(ot)return st;ot=1;var t=Array.prototype.slice,e=lt(),r=Object.keys,n=r?function(t){return r(t)}:ht(),i=Object.keys;return n.shim=function(){if(Object.keys){var r=function(){var t=Object.keys(arguments);return t&&t.length===arguments.length}(1,2);r||(Object.keys=function(r){return e(r)?i(t.call(r)):i(r)})}else Object.keys=n;return Object.keys||n},st=n}var dt,pt,gt,mt,yt,bt,wt,_t,vt,kt,St,Ot,Et,Rt,xt,At,jt,It,Dt,Pt,Tt,Nt,Ct,Mt,Lt,$t,Ut,zt,Ft,Bt,qt,Vt,Ht,Kt,Zt,Wt,Jt,Gt,Yt,Qt,Xt,te,ee,re,ne,ie,se,oe,ae,ce,ue,le,he,fe,de,pe,ge,me,ye,be,we,_e,ve,ke,Se,Oe,Ee,Re,xe,Ae,je,Ie,De,Pe,Te,Ne,Ce,Me,Le,$e,Ue,ze={exports:{}};function Fe(){return pt?dt:(pt=1,dt=Object)}function Be(){return mt?gt:(mt=1,gt=Error)}function qe(){return bt?yt:(bt=1,yt=EvalError)}function Ve(){return _t?wt:(_t=1,wt=RangeError)}function He(){return kt?vt:(kt=1,vt=ReferenceError)}function Ke(){return Ot?St:(Ot=1,St=SyntaxError)}function Ze(){return Rt?Et:(Rt=1,Et=TypeError)}function We(){return At?xt:(At=1,xt=URIError)}function Je(){return It?jt:(It=1,jt=Math.abs)}function Ge(){return Pt?Dt:(Pt=1,Dt=Math.floor)}function Ye(){return Nt?Tt:(Nt=1,Tt=Math.max)}function Qe(){return Mt?Ct:(Mt=1,Ct=Math.min)}function Xe(){return $t?Lt:($t=1,Lt=Math.pow)}function tr(){return zt?Ut:(zt=1,Ut=Math.round)}function er(){if(Vt)return qt;Vt=1;var t=Bt?Ft:(Bt=1,Ft=Number.isNaN||function(t){return t!=t});return qt=function(e){return t(e)||0===e?e:e<0?-1:1}}function rr(){if(Wt)return Zt;Wt=1;var t=Kt?Ht:(Kt=1,Ht=Object.getOwnPropertyDescriptor);if(t)try{t([],"length")}catch(e){t=null}return Zt=t}function nr(){if(Gt)return Jt;Gt=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}return Jt=t}function ir(){if(te)return Xt;te=1;var t="undefined"!=typeof Symbol&&Symbol,e=Qt?Yt:(Qt=1,Yt=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var t={},e=Symbol("test"),r=Object(e);if("string"==typeof e)return!1;if("[object Symbol]"!==Object.prototype.toString.call(e))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in t[e]=42,t)return!1;if("function"==typeof Object.keys&&0!==Object.keys(t).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var i=Object.getOwnPropertySymbols(t);if(1!==i.length||i[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var s=Object.getOwnPropertyDescriptor(t,e);if(42!==s.value||!0!==s.enumerable)return!1}return!0});return Xt=function(){return"function"==typeof t&&("function"==typeof Symbol&&("symbol"==typeof t("foo")&&("symbol"==typeof Symbol("bar")&&e())))}}function sr(){return re?ee:(re=1,ee="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function or(){return ie?ne:(ie=1,ne=Fe().getPrototypeOf||null)}function ar(){if(oe)return se;oe=1;var t=Object.prototype.toString,e=Math.max,r=function(t,e){for(var r=[],n=0;n<t.length;n+=1)r[n]=t[n];for(var i=0;i<e.length;i+=1)r[i+t.length]=e[i];return r};return se=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==t.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var s,o=function(t,e){for(var r=[],n=e,i=0;n<t.length;n+=1,i+=1)r[i]=t[n];return r}(arguments,1),a=e(0,i.length-o.length),c=[],u=0;u<a;u++)c[u]="$"+u;if(s=Function("binder","return function ("+function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r}(c,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof s){var t=i.apply(this,r(o,arguments));return Object(t)===t?t:this}return i.apply(n,r(o,arguments))}),i.prototype){var l=function(){};l.prototype=i.prototype,s.prototype=new l,l.prototype=null}return s},se}function cr(){if(ce)return ae;ce=1;var t=ar();return ae=Function.prototype.bind||t}function ur(){return le?ue:(le=1,ue=Function.prototype.call)}function lr(){return fe?he:(fe=1,he=Function.prototype.apply)}function hr(){if(me)return ge;me=1;var t=cr(),e=lr(),r=ur(),n=pe?de:(pe=1,de="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return ge=n||t.call(r,e)}function fr(){if(be)return ye;be=1;var t=cr(),e=Ze(),r=ur(),n=hr();return ye=function(i){if(i.length<1||"function"!=typeof i[0])throw new e("a function is required");return n(t,r,i)}}function dr(){if(_e)return we;_e=1;var t,e=fr(),r=rr();try{t=[].__proto__===Array.prototype}catch(t){if(!t||"object"!=typeof t||!("code"in t)||"ERR_PROTO_ACCESS"!==t.code)throw t}var n=!!t&&r&&r(Object.prototype,"__proto__"),i=Object,s=i.getPrototypeOf;return we=n&&"function"==typeof n.get?e([n.get]):"function"==typeof s&&function(t){return s(null==t?t:i(t))}}function pr(){if(ke)return ve;ke=1;var t=sr(),e=or(),r=dr();return ve=t?function(e){return t(e)}:e?function(t){if(!t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("getProto: not an object");return e(t)}:r?function(t){return r(t)}:null}function gr(){if(Oe)return Se;Oe=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=cr();return Se=r.call(t,e)}function mr(){if(Re)return Ee;var t;Re=1;var e=Fe(),r=Be(),n=qe(),i=Ve(),s=He(),o=Ke(),a=Ze(),c=We(),u=Je(),l=Ge(),h=Ye(),f=Qe(),d=Xe(),p=tr(),g=er(),m=Function,y=function(t){try{return m('"use strict"; return ('+t+").constructor;")()}catch(t){}},b=rr(),w=nr(),_=function(){throw new a},v=b?function(){try{return _}catch(t){try{return b(arguments,"callee").get}catch(t){return _}}}():_,k=ir()(),S=pr(),O=or(),E=sr(),R=lr(),x=ur(),A={},j="undefined"!=typeof Uint8Array&&S?S(Uint8Array):t,I={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?t:ArrayBuffer,"%ArrayIteratorPrototype%":k&&S?S([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":A,"%AsyncGenerator%":A,"%AsyncGeneratorFunction%":A,"%AsyncIteratorPrototype%":A,"%Atomics%":"undefined"==typeof Atomics?t:Atomics,"%BigInt%":"undefined"==typeof BigInt?t:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?t:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":"undefined"==typeof Float16Array?t:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?t:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?t:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?t:FinalizationRegistry,"%Function%":m,"%GeneratorFunction%":A,"%Int8Array%":"undefined"==typeof Int8Array?t:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?t:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":k&&S?S(S([][Symbol.iterator]())):t,"%JSON%":"object"==typeof JSON?JSON:t,"%Map%":"undefined"==typeof Map?t:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&k&&S?S((new Map)[Symbol.iterator]()):t,"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?t:Promise,"%Proxy%":"undefined"==typeof Proxy?t:Proxy,"%RangeError%":i,"%ReferenceError%":s,"%Reflect%":"undefined"==typeof Reflect?t:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?t:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&k&&S?S((new Set)[Symbol.iterator]()):t,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":k&&S?S(""[Symbol.iterator]()):t,"%Symbol%":k?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":v,"%TypedArray%":j,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?t:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?t:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?t:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?t:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?t:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?t:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?t:WeakSet,"%Function.prototype.call%":x,"%Function.prototype.apply%":R,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":O,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":h,"%Math.min%":f,"%Math.pow%":d,"%Math.round%":p,"%Math.sign%":g,"%Reflect.getPrototypeOf%":E};if(S)try{null.error}catch(t){var D=S(S(t));I["%Error.prototype%"]=D}var P=function t(e){var r;if("%AsyncFunction%"===e)r=y("async function () {}");else if("%GeneratorFunction%"===e)r=y("function* () {}");else if("%AsyncGeneratorFunction%"===e)r=y("async function* () {}");else if("%AsyncGenerator%"===e){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===e){var i=t("%AsyncGenerator%");i&&S&&(r=S(i.prototype))}return I[e]=r,r},T={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},N=cr(),C=gr(),M=N.call(x,Array.prototype.concat),L=N.call(R,Array.prototype.splice),$=N.call(x,String.prototype.replace),U=N.call(x,String.prototype.slice),z=N.call(x,RegExp.prototype.exec),F=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,B=/\\(\\)?/g,q=function(t,e){var r,n=t;if(C(T,n)&&(n="%"+(r=T[n])[0]+"%"),C(I,n)){var i=I[n];if(i===A&&(i=P(n)),void 0===i&&!e)throw new a("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new o("intrinsic "+t+" does not exist!")};return Ee=function(t,e){if("string"!=typeof t||0===t.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new a('"allowMissing" argument must be a boolean');if(null===z(/^%?[^%]*%?$/,t))throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(t){var e=U(t,0,1),r=U(t,-1);if("%"===e&&"%"!==r)throw new o("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==e)throw new o("invalid intrinsic syntax, expected opening `%`");var n=[];return $(t,F,function(t,e,r,i){n[n.length]=r?$(i,B,"$1"):e||t}),n}(t),n=r.length>0?r[0]:"",i=q("%"+n+"%",e),s=i.name,c=i.value,u=!1,l=i.alias;l&&(n=l[0],L(r,M([0,1],l)));for(var h=1,f=!0;h<r.length;h+=1){var d=r[h],p=U(d,0,1),g=U(d,-1);if(('"'===p||"'"===p||"`"===p||'"'===g||"'"===g||"`"===g)&&p!==g)throw new o("property names with quotes must have matching quotes");if("constructor"!==d&&f||(u=!0),C(I,s="%"+(n+="."+d)+"%"))c=I[s];else if(null!=c){if(!(d in c)){if(!e)throw new a("base intrinsic for "+t+" exists, but the property is not available.");return}if(b&&h+1>=r.length){var m=b(c,d);c=(f=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:c[d]}else f=C(c,d),c=c[d];f&&!u&&(I[s]=c)}}return c},Ee}function yr(){if(Ae)return xe;Ae=1;var t=nr(),e=Ke(),r=Ze(),n=rr();return xe=function(i,s,o){if(!i||"object"!=typeof i&&"function"!=typeof i)throw new r("`obj` must be an object or a function`");if("string"!=typeof s&&"symbol"!=typeof s)throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new r("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],h=!!n&&n(i,s);if(t)t(i,s,{configurable:null===u&&h?h.configurable:!u,enumerable:null===a&&h?h.enumerable:!a,value:o,writable:null===c&&h?h.writable:!c});else{if(!l&&(a||c||u))throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");i[s]=o}},xe}function br(){if(Ie)return je;Ie=1;var t=nr(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return 1!==t([],"length",{value:1}).length}catch(t){return!0}},je=e}function wr(){if(Pe)return De;Pe=1;var t=mr(),e=yr(),r=br()(),n=rr(),i=Ze(),s=t("%Math.floor%");return De=function(t,o){if("function"!=typeof t)throw new i("`fn` is not a function");if("number"!=typeof o||o<0||o>4294967295||s(o)!==o)throw new i("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in t&&n){var l=n(t,"length");l&&!l.configurable&&(c=!1),l&&!l.writable&&(u=!1)}return(c||u||!a)&&(r?e(t,"length",o,!0,!0):e(t,"length",o)),t},De}function _r(){if(Ne)return Te;Ne=1;var t=cr(),e=lr(),r=hr();return Te=function(){return r(t,e,arguments)},Te}function vr(){return Ce||(Ce=1,function(t){var e=wr(),r=nr(),n=fr(),i=_r();t.exports=function(t){var r=n(arguments),i=t.length-(arguments.length-1);return e(r,1+(i>0?i:0),!0)},r?r(t.exports,"apply",{value:i}):t.exports.apply=i}(ze)),ze.exports}function kr(){if(Le)return Me;Le=1;var t=mr(),e=fr(),r=e([t("%String.prototype.indexOf%")]);return Me=function(n,i){var s=t(n,!!i);return"function"==typeof s&&r(n,".prototype.")>-1?e([s]):s}}var Sr=function(){if(Ue)return $e;Ue=1;var t=("undefined"!=typeof JSON?JSON:(Q||(Q=1,at.parse=ct(),at.stringify=ut()),at)).stringify,e=function(){if(tt)return X;tt=1;var t={}.toString;return X=Array.isArray||function(e){return"[object Array]"==t.call(e)}}(),r=ft(),n=vr(),i=kr(),s=i("Array.prototype.join"),o=i("Array.prototype.indexOf"),a=i("Array.prototype.splice"),c=i("Array.prototype.sort"),u=function(t,e){for(var r="",n=0;n<t;n+=1)r+=e;return r},l=function(t,e,r){return r};return $e=function(i){var h=arguments.length>1?arguments[1]:void 0,f=h&&h.space||"";"number"==typeof f&&(f=u(f," "));var d=!!h&&"boolean"==typeof h.cycles&&h.cycles,p=h&&h.replacer?n(h.replacer):l;if(h&&void 0!==h.collapseEmpty&&"boolean"!=typeof h.collapseEmpty)throw new TypeError("`collapseEmpty` must be a boolean, if provided");var g=!!h&&h.collapseEmpty,m="function"==typeof h?h:h&&h.cmp,y=m&&function(t){var e=m.length>2&&function(e){return t[e]};return function(r,n){return m({key:r,value:t[r]},{key:n,value:t[n]},e?{__proto__:null,get:e}:void 0)}},b=[];return function n(i,l,h,m){var w=f?"\n"+u(m,f):"",_=f?": ":":";if(h&&h.toJSON&&"function"==typeof h.toJSON&&(h=h.toJSON()),void 0!==(h=p(i,l,h))){if("object"!=typeof h||null===h)return t(h);var v=function(t,e){return g&&0===t.length?e:("[]"===e?"[":"{")+s(t,",")+w+("[]"===e?"]":"}")};if(e(h)){for(var k=[],S=0;S<h.length;S++){var O=n(h,S,h[S],m+1)||t(null);k[k.length]=w+f+O}return v(k,"[]")}if(-1!==o(b,h)){if(d)return t("__cycle__");throw new TypeError("Converting circular structure to JSON")}b[b.length]=h;var E=c(r(h),y&&y(h));for(k=[],S=0;S<E.length;S++){var R=n(h,l=E[S],h[l],m+1);if(R){var x=t(l)+_+R;k[k.length]=w+f+x}}return a(b,o(b,h),1),v(k,"{}")}}({"":i},"",i,0)},$e}(),Or=Z(Sr);async function Er(t,e,r){if(!this.passphrase)return e.push({actual:t,type:"encryptionKeyMissing"}),t;try{return await V(String(t),this.passphrase)}catch(r){e.push({actual:t,type:"encryptionProblem",error:r})}return t}async function Rr(t,e,n){return r.isString(t)?t:JSON.stringify(t)}class xr extends a{constructor({options:t,passphrase:e,autoEncrypt:n=!0}={}){super(r.merge({},{useNewCustomCheckerFunction:!0,messages:{encryptionKeyMissing:"Missing configuration for secrets encryption.",encryptionProblem:"Problem encrypting secret. Actual: {actual}. Error: {error}"},defaults:{string:{trim:!0},object:{strict:"remove"}}},t)),this.passphrase=e,this.autoEncrypt=n,this.alias("secret",{type:"string",custom:this.autoEncrypt?Er: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?Er:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Er:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?Rr:void 0})}}const Ar=new Proxy(xr,{instance:null,construct(t,e){return this.instance||(this.instance=new t(...e)),this.instance}});const jr={trim:t=>t.trim(),encrypt:(t,{passphrase:e})=>V(t,e),decrypt:async(t,{passphrase:e})=>{try{return await H(t,e)}catch(e){return console.warn(`Schema decrypt error: ${e}`,e),t}},toString: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(null==t)return t;if("[]"===t)return[];if(""===t)return[];const r=[];let n="",i=0;const s=String(t);for(;i<s.length;)"\\"===s[i]&&i+1<s.length?s[i+1]===e?(n+=e,i+=2):"\\"===s[i+1]?(n+="\\",i+=2):(n+=s[i],i++):s[i]===e?(r.push(n),n="",i++):(n+=s[i],i++);return r.push(n),r},toJSON:t=>JSON.stringify(t),fromJSON:t=>JSON.parse(t),toNumber:t=>r.isString(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"};class Ir{constructor(t){const{map:e,name:n,attributes:i,passphrase:s,version:a=1,options:c={}}=t;this.name=n,this.version=a,this.attributes=i||{},this.passphrase=s??"secret",this.options=r.merge({},this.defaultOptions(),c),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const u=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Ar({autoEncrypt:!1}).compile(r.merge({$$async:!0},u)),this.options.generateAutoHooks&&this.generateAutoHooks(),r.isEmpty(e)){const t=o.flatten(this.attributes,{safe:!0}),e=Object.keys(t).filter(t=>!t.includes("$$")),r=this.extractObjectKeys(this.attributes),n=[...new Set([...e,...r])],{mapping:i,reversedMapping:s}=function(t){const e={},r={};return t.forEach((t,n)=>{const i=n.toString(36);e[t]=i,r[i]=t}),{mapping:e,reversedMapping:r}}(n);this.map=i,this.reversedMap=s}else this.map=e,this.reversedMap=r.invert(e)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(t,e,n){this.options.hooks[t][e]||(this.options.hooks[t][e]=[]),this.options.hooks[t][e]=r.uniq([...this.options.hooks[t][e],n])}extractObjectKeys(t,e=""){const r=[];for(const[n,i]of Object.entries(t)){if(n.startsWith("$$"))continue;const t=e?`${e}.${n}`:n;"object"!=typeof i||null===i||Array.isArray(i)||(r.push(t),"object"===i.$$type&&r.push(...this.extractObjectKeys(i,t)))}return r}generateAutoHooks(){const t=o.flatten(r.cloneDeep(this.attributes),{safe:!0});for(const[e,r]of Object.entries(t))r.includes("array")&&(this.addHook("beforeMap",e,"fromArray"),this.addHook("afterUnmap",e,"toArray")),r.includes("secret")&&(this.options.autoEncrypt&&this.addHook("beforeMap",e,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",e,"decrypt")),r.includes("number")&&(this.addHook("beforeMap",e,"toString"),this.addHook("afterUnmap",e,"toNumber")),r.includes("boolean")&&(this.addHook("beforeMap",e,"fromBool"),this.addHook("afterUnmap",e,"toBool")),r.includes("json")&&(this.addHook("beforeMap",e,"toJSON"),this.addHook("afterUnmap",e,"fromJSON"))}static import(t){let{map:e,name:n,options:i,version:s,attributes:o}=r.isString(t)?JSON.parse(t):t;o=Ir._importAttributes(o);return new Ir({map:e,name:n,options:i,version:s,attributes:o})}static _importAttributes(t){if("string"==typeof t){try{const e=JSON.parse(t);if("object"==typeof e&&null!==e)return Ir._importAttributes(e)}catch(t){}return t}if(Array.isArray(t))return t.map(t=>Ir._importAttributes(t));if("object"==typeof t&&null!==t){const e={};for(const[r,n]of Object.entries(t))e[r]=Ir._importAttributes(n);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,n]of Object.entries(t))e[r]=this._exportAttributes(n);return e}return t}async applyHooksActions(t,e){for(const[n,i]of Object.entries(this.options.hooks[e]))for(const e of i){const i=r.get(t,n);void 0!==i&&"function"==typeof jr[e]&&r.set(t,n,await jr[e](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}}async validate(t,{mutateOriginal:e=!1}={}){let n=e?t:r.cloneDeep(t);return await this.validator(n)}async mapper(t){const e=o.flatten(r.cloneDeep(t),{safe:!0});await this.applyHooksActions(e,"beforeMap");const n={_v:this.version+""};for(const[t,r]of Object.entries(e))n[this.map[t]]=r;return await this.applyHooksActions(n,"afterMap"),n}async unmapper(t){const e=r.cloneDeep(t);delete e._v,await this.applyHooksActions(e,"beforeUnmap");const n={};for(const[t,r]of Object.entries(e))n[this.reversedMap[t]]=r;return await this.applyHooksActions(n,"afterUnmap"),o.unflatten(n)}preprocessAttributesForValidation(t){const e={};for(const[r,n]of Object.entries(t))if("object"!=typeof n||null===n||Array.isArray(n))e[r]=n;else{const t=n.$$type&&n.$$type.includes("required"),i=n.$$type&&n.$$type.includes("optional"),s={type:"object",properties:this.preprocessAttributesForValidation(n),strict:!1};t||(i||this.allNestedObjectsOptional)&&(s.optional=!0),e[r]=s}return e}}var Dr="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Pr=[],Tr=[],Nr="undefined"!=typeof Uint8Array?Uint8Array:Array,Cr=!1;function Mr(){Cr=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0;e<64;++e)Pr[e]=t[e],Tr[t.charCodeAt(e)]=e;Tr["-".charCodeAt(0)]=62,Tr["_".charCodeAt(0)]=63}function Lr(t){return Pr[t>>18&63]+Pr[t>>12&63]+Pr[t>>6&63]+Pr[63&t]}function $r(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16)+(t[s+1]<<8)+t[s+2],i.push(Lr(n));return i.join("")}function Ur(t){var e;Cr||Mr();for(var r=t.length,n=r%3,i="",s=[],o=16383,a=0,c=r-n;a<c;a+=o)s.push($r(t,a,a+o>c?c:a+o));return 1===n?(e=t[r-1],i+=Pr[e>>2],i+=Pr[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=Pr[e>>10],i+=Pr[e>>4&63],i+=Pr[e<<2&63],i+="="),s.push(i),s.join("")}function zr(t,e,r,n,i){var s,o,a=8*i-n-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?i-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+=n;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,n),s-=u}return(d?-1:1)*o*Math.pow(2,s-n)}function Fr(t,e,r,n,i,s){var o,a,c,u=8*s-i-1,l=(1<<u)-1,h=l>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:s-1,p=n?1:-1,g=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,i),o+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&a,d+=p,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*g}var Br={}.toString,qr=Array.isArray||function(t){return"[object Array]"==Br.call(t)};function Vr(){return Kr.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Hr(t,e){if(Vr()<e)throw new RangeError("Invalid typed array length");return Kr.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Kr.prototype:(null===t&&(t=new Kr(e)),t.length=e),t}function Kr(t,e,r){if(!(Kr.TYPED_ARRAY_SUPPORT||this instanceof Kr))return new Kr(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 Jr(this,t)}return Zr(this,t,e,r)}function Zr(t,e,r,n){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,n){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");e=void 0===r&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,r):new Uint8Array(e,r,n);Kr.TYPED_ARRAY_SUPPORT?(t=e).__proto__=Kr.prototype:t=Gr(t,e);return t}(t,e,r,n):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!Kr.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|Xr(e,r);t=Hr(t,n);var i=t.write(e,r);i!==n&&(t=t.slice(0,i));return t}(t,e,r):function(t,e){if(Qr(e)){var r=0|Yr(e.length);return 0===(t=Hr(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||(n=e.length)!=n?Hr(t,0):Gr(t,e);if("Buffer"===e.type&&qr(e.data))return Gr(t,e.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function Wr(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 Jr(t,e){if(Wr(e),t=Hr(t,e<0?0:0|Yr(e)),!Kr.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function Gr(t,e){var r=e.length<0?0:0|Yr(e.length);t=Hr(t,r);for(var n=0;n<r;n+=1)t[n]=255&e[n];return t}function Yr(t){if(t>=Vr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Vr().toString(16)+" bytes");return 0|t}function Qr(t){return!(null==t||!t._isBuffer)}function Xr(t,e){if(Qr(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 n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return xn(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return An(t).length;default:if(n)return xn(t).length;e=(""+e).toLowerCase(),n=!0}}function tn(t,e,r){var n=!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 mn(this,e,r);case"utf8":case"utf-8":return fn(this,e,r);case"ascii":return pn(this,e,r);case"latin1":case"binary":return gn(this,e,r);case"base64":return hn(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return yn(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function en(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function rn(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=Kr.from(e,n)),Qr(e))return 0===e.length?-1:nn(t,e,r,n,i);if("number"==typeof e)return e&=255,Kr.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):nn(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function nn(t,e,r,n,i){var s,o=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){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(i){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 sn(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;var s=e.length;if(s%2!=0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;o<n;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[r+o]=a}return o}function on(t,e,r,n){return jn(xn(e,t.length-r),t,r,n)}function an(t,e,r,n){return jn(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function cn(t,e,r,n){return an(t,e,r,n)}function un(t,e,r,n){return jn(An(e),t,r,n)}function ln(t,e,r,n){return jn(function(t,e){for(var r,n,i,s=[],o=0;o<t.length&&!((e-=2)<0);++o)n=(r=t.charCodeAt(o))>>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function hn(t,e,r){return 0===e&&r===t.length?Ur(t):Ur(t.slice(e,r))}function fn(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var s,o,a,c,u=t[i],l=null,h=u>239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(s=t[i+1]))&&(c=(31&u)<<6|63&s)>127&&(l=c);break;case 3:s=t[i+1],o=t[i+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[i+1],o=t[i+2],a=t[i+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,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=h}return function(t){var e=t.length;if(e<=dn)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=dn));return r}(n)}Kr.TYPED_ARRAY_SUPPORT=void 0===Dr.TYPED_ARRAY_SUPPORT||Dr.TYPED_ARRAY_SUPPORT,Vr(),Kr.poolSize=8192,Kr._augment=function(t){return t.__proto__=Kr.prototype,t},Kr.from=function(t,e,r){return Zr(null,t,e,r)},Kr.TYPED_ARRAY_SUPPORT&&(Kr.prototype.__proto__=Uint8Array.prototype,Kr.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Kr[Symbol.species]),Kr.alloc=function(t,e,r){return function(t,e,r,n){return Wr(e),e<=0?Hr(t,e):void 0!==r?"string"==typeof n?Hr(t,e).fill(r,n):Hr(t,e).fill(r):Hr(t,e)}(null,t,e,r)},Kr.allocUnsafe=function(t){return Jr(null,t)},Kr.allocUnsafeSlow=function(t){return Jr(null,t)},Kr.isBuffer=function(t){return null!=t&&(!!t._isBuffer||In(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&In(t.slice(0,0))}(t))},Kr.compare=function(t,e){if(!Qr(t)||!Qr(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,s=Math.min(r,n);i<s;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},Kr.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}},Kr.concat=function(t,e){if(!qr(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Kr.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var n=Kr.allocUnsafe(e),i=0;for(r=0;r<t.length;++r){var s=t[r];if(!Qr(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,i),i+=s.length}return n},Kr.byteLength=Xr,Kr.prototype._isBuffer=!0,Kr.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)en(this,e,e+1);return this},Kr.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)en(this,e,e+3),en(this,e+1,e+2);return this},Kr.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)en(this,e,e+7),en(this,e+1,e+6),en(this,e+2,e+5),en(this,e+3,e+4);return this},Kr.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?fn(this,0,t):tn.apply(this,arguments)},Kr.prototype.equals=function(t){if(!Qr(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Kr.compare(this,t)},Kr.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+">"},Kr.prototype.compare=function(t,e,r,n,i){if(!Qr(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===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var s=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(e>>>=0),a=Math.min(s,o),c=this.slice(n,i),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},Kr.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},Kr.prototype.indexOf=function(t,e,r){return rn(this,t,e,r,!0)},Kr.prototype.lastIndexOf=function(t,e,r){return rn(this,t,e,r,!1)},Kr.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=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===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var s=!1;;)switch(n){case"hex":return sn(this,t,e,r);case"utf8":case"utf-8":return on(this,t,e,r);case"ascii":return an(this,t,e,r);case"latin1":case"binary":return cn(this,t,e,r);case"base64":return un(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ln(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},Kr.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var dn=4096;function pn(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function gn(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function mn(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=e;s<r;++s)i+=Rn(t[s]);return i}function yn(t,e,r){for(var n=t.slice(e,r),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+256*n[s+1]);return i}function bn(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 wn(t,e,r,n,i,s){if(!Qr(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function _n(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(t.length-r,2);i<s;++i)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function vn(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(t.length-r,4);i<s;++i)t[r+i]=e>>>8*(n?i:3-i)&255}function kn(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Sn(t,e,r,n,i){return i||kn(t,0,r,4),Fr(t,e,r,n,23,4),r+4}function On(t,e,r,n,i){return i||kn(t,0,r,8),Fr(t,e,r,n,52,8),r+8}Kr.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e<t&&(e=t),Kr.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=Kr.prototype;else{var i=e-t;r=new Kr(i,void 0);for(var s=0;s<i;++s)r[s]=this[s+t]}return r},Kr.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||bn(t,e,this.length);for(var n=this[t],i=1,s=0;++s<e&&(i*=256);)n+=this[t+s]*i;return n},Kr.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||bn(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},Kr.prototype.readUInt8=function(t,e){return e||bn(t,1,this.length),this[t]},Kr.prototype.readUInt16LE=function(t,e){return e||bn(t,2,this.length),this[t]|this[t+1]<<8},Kr.prototype.readUInt16BE=function(t,e){return e||bn(t,2,this.length),this[t]<<8|this[t+1]},Kr.prototype.readUInt32LE=function(t,e){return e||bn(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Kr.prototype.readUInt32BE=function(t,e){return e||bn(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Kr.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||bn(t,e,this.length);for(var n=this[t],i=1,s=0;++s<e&&(i*=256);)n+=this[t+s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*e)),n},Kr.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||bn(t,e,this.length);for(var n=e,i=1,s=this[t+--n];n>0&&(i*=256);)s+=this[t+--n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*e)),s},Kr.prototype.readInt8=function(t,e){return e||bn(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Kr.prototype.readInt16LE=function(t,e){e||bn(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Kr.prototype.readInt16BE=function(t,e){e||bn(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Kr.prototype.readInt32LE=function(t,e){return e||bn(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Kr.prototype.readInt32BE=function(t,e){return e||bn(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Kr.prototype.readFloatLE=function(t,e){return e||bn(t,4,this.length),zr(this,t,!0,23,4)},Kr.prototype.readFloatBE=function(t,e){return e||bn(t,4,this.length),zr(this,t,!1,23,4)},Kr.prototype.readDoubleLE=function(t,e){return e||bn(t,8,this.length),zr(this,t,!0,52,8)},Kr.prototype.readDoubleBE=function(t,e){return e||bn(t,8,this.length),zr(this,t,!1,52,8)},Kr.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||wn(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,s=0;for(this[e]=255&t;++s<r&&(i*=256);)this[e+s]=t/i&255;return e+r},Kr.prototype.writeUIntBE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||wn(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},Kr.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,1,255,0),Kr.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Kr.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,2,65535,0),Kr.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):_n(this,t,e,!0),e+2},Kr.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,2,65535,0),Kr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):_n(this,t,e,!1),e+2},Kr.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,4,4294967295,0),Kr.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):vn(this,t,e,!0),e+4},Kr.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,4,4294967295,0),Kr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):vn(this,t,e,!1),e+4},Kr.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);wn(this,t,e,r,i-1,-i)}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},Kr.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);wn(this,t,e,r,i-1,-i)}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},Kr.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,1,127,-128),Kr.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Kr.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,2,32767,-32768),Kr.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):_n(this,t,e,!0),e+2},Kr.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,2,32767,-32768),Kr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):_n(this,t,e,!1),e+2},Kr.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,4,2147483647,-2147483648),Kr.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):vn(this,t,e,!0),e+4},Kr.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||wn(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Kr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):vn(this,t,e,!1),e+4},Kr.prototype.writeFloatLE=function(t,e,r){return Sn(this,t,e,!0,r)},Kr.prototype.writeFloatBE=function(t,e,r){return Sn(this,t,e,!1,r)},Kr.prototype.writeDoubleLE=function(t,e,r){return On(this,t,e,!0,r)},Kr.prototype.writeDoubleBE=function(t,e,r){return On(this,t,e,!1,r)},Kr.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===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(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);var i,s=n-r;if(this===t&&r<e&&e<n)for(i=s-1;i>=0;--i)t[i+e]=this[i+r];else if(s<1e3||!Kr.TYPED_ARRAY_SUPPORT)for(i=0;i<s;++i)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+s),e);return s},Kr.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===t.length){var i=t.charCodeAt(0);i<256&&(t=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Kr.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}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=Qr(t)?t:xn(new Kr(t,n).toString()),a=o.length;for(s=0;s<r-e;++s)this[s+e]=o[s%a]}return this};var En=/[^+\/0-9A-Za-z-_]/g;function Rn(t){return t<16?"0"+t.toString(16):t.toString(16)}function xn(t,e){var r;e=e||1/0;for(var n=t.length,i=null,s=[],o=0;o<n;++o){if((r=t.charCodeAt(o))>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=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 An(t){return function(t){var e,r,n,i,s,o;Cr||Mr();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 Nr(3*a/4-s),n=s>0?a-4:a;var c=0;for(e=0,r=0;e<n;e+=4,r+=3)i=Tr[t.charCodeAt(e)]<<18|Tr[t.charCodeAt(e+1)]<<12|Tr[t.charCodeAt(e+2)]<<6|Tr[t.charCodeAt(e+3)],o[c++]=i>>16&255,o[c++]=i>>8&255,o[c++]=255&i;return 2===s?(i=Tr[t.charCodeAt(e)]<<2|Tr[t.charCodeAt(e+1)]>>4,o[c++]=255&i):1===s&&(i=Tr[t.charCodeAt(e)]<<10|Tr[t.charCodeAt(e+1)]<<4|Tr[t.charCodeAt(e+2)]>>2,o[c++]=i>>8&255,o[c++]=255&i),o}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(En,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function jn(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function In(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function Dn(){throw new Error("setTimeout has not been defined")}function Pn(){throw new Error("clearTimeout has not been defined")}var Tn=Dn,Nn=Pn;function Cn(t){if(Tn===setTimeout)return setTimeout(t,0);if((Tn===Dn||!Tn)&&setTimeout)return Tn=setTimeout,setTimeout(t,0);try{return Tn(t,0)}catch(e){try{return Tn.call(null,t,0)}catch(e){return Tn.call(this,t,0)}}}"function"==typeof Dr.setTimeout&&(Tn=setTimeout),"function"==typeof Dr.clearTimeout&&(Nn=clearTimeout);var Mn,Ln=[],$n=!1,Un=-1;function zn(){$n&&Mn&&($n=!1,Mn.length?Ln=Mn.concat(Ln):Un=-1,Ln.length&&Fn())}function Fn(){if(!$n){var t=Cn(zn);$n=!0;for(var e=Ln.length;e;){for(Mn=Ln,Ln=[];++Un<e;)Mn&&Mn[Un].run();Un=-1,e=Ln.length}Mn=null,$n=!1,function(t){if(Nn===clearTimeout)return clearTimeout(t);if((Nn===Pn||!Nn)&&clearTimeout)return Nn=clearTimeout,clearTimeout(t);try{return Nn(t)}catch(e){try{return Nn.call(null,t)}catch(e){return Nn.call(this,t)}}}(t)}}function Bn(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];Ln.push(new qn(t,e)),1!==Ln.length||$n||Cn(Fn)}function qn(t,e){this.fun=t,this.array=e}qn.prototype.run=function(){this.fun.apply(null,this.array)};function Vn(){}var Hn=Vn,Kn=Vn,Zn=Vn,Wn=Vn,Jn=Vn,Gn=Vn,Yn=Vn;var Qn=Dr.performance||{},Xn=Qn.now||Qn.mozNow||Qn.msNow||Qn.oNow||Qn.webkitNow||function(){return(new Date).getTime()};var ti=new Date;var ei,ri={nextTick:Bn,title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Hn,addListener:Kn,once:Zn,off:Wn,removeListener:Jn,removeAllListeners:Gn,emit:Yn,binding:function(t){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(t){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(t){var e=.001*Xn.call(Qn),r=Math.floor(e),n=Math.floor(e%1*1e9);return t&&(r-=t[0],(n-=t[1])<0&&(r--,n+=1e9)),[r,n]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-ti)/1e3}};ei="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 ni=Object.getOwnPropertyDescriptors||function(t){for(var e=Object.keys(t),r={},n=0;n<e.length;n++)r[e[n]]=Object.getOwnPropertyDescriptor(t,e[n]);return r},ii=/%[sdj%]/g;function si(t){if(!yi(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(ui(arguments[r]));return e.join(" ")}r=1;for(var n=arguments,i=n.length,s=String(t).replace(ii,function(t){if("%%"===t)return"%";if(r>=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),o=n[r];r<i;o=n[++r])mi(o)||!_i(o)?s+=" "+o:s+=" "+ui(o);return s}function oi(t,e){if(bi(Dr.process))return function(){return oi(t,e).apply(this,arguments)};if(!0===ri.noDeprecation)return t;var r=!1;return function(){if(!r){if(ri.throwDeprecation)throw new Error(e);ri.traceDeprecation?console.trace(e):console.error(e),r=!0}return t.apply(this,arguments)}}var ai,ci={};function ui(t,e){var r={seen:[],stylize:hi};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),gi(e)?r.showHidden=e:e&&function(t,e){if(!e||!_i(e))return t;var r=Object.keys(e),n=r.length;for(;n--;)t[r[n]]=e[r[n]]}(r,e),bi(r.showHidden)&&(r.showHidden=!1),bi(r.depth)&&(r.depth=2),bi(r.colors)&&(r.colors=!1),bi(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=li),fi(r,t,r.depth)}function li(t,e){var r=ui.styles[e];return r?"["+ui.colors[r][0]+"m"+t+"["+ui.colors[r][1]+"m":t}function hi(t,e){return t}function fi(t,e,r){if(t.customInspect&&e&&Si(e.inspect)&&e.inspect!==ui&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return yi(n)||(n=fi(t,n,r)),n}var i=function(t,e){if(bi(e))return t.stylize("undefined","undefined");if(yi(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(n=e,"number"==typeof n)return t.stylize(""+e,"number");var n;if(gi(e))return t.stylize(""+e,"boolean");if(mi(e))return t.stylize("null","null")}(t,e);if(i)return i;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)),ki(e)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return di(e);if(0===s.length){if(Si(e)){var a=e.name?": "+e.name:"";return t.stylize("[Function"+a+"]","special")}if(wi(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(vi(e))return t.stylize(Date.prototype.toString.call(e),"date");if(ki(e))return di(e)}var c,u,l="",h=!1,f=["{","}"];(c=e,Array.isArray(c)&&(h=!0,f=["[","]"]),Si(e))&&(l=" [Function"+(e.name?": "+e.name:"")+"]");return wi(e)&&(l=" "+RegExp.prototype.toString.call(e)),vi(e)&&(l=" "+Date.prototype.toUTCString.call(e)),ki(e)&&(l=" "+di(e)),0!==s.length||h&&0!=e.length?r<0?wi(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),u=h?function(t,e,r,n,i){for(var s=[],o=0,a=e.length;o<a;++o)Ei(e,String(o))?s.push(pi(t,e,r,n,String(o),!0)):s.push("");return i.forEach(function(i){i.match(/^\d+$/)||s.push(pi(t,e,r,n,i,!0))}),s}(t,e,r,o,s):s.map(function(n){return pi(t,e,r,o,n,h)}),t.seen.pop(),function(t,e,r){var n=t.reduce(function(t,e){return e.indexOf("\n"),t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(n>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 di(t){return"["+Error.prototype.toString.call(t)+"]"}function pi(t,e,r,n,i,s){var o,a,c;if((c=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?a=c.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):c.set&&(a=t.stylize("[Setter]","special")),Ei(n,i)||(o="["+i+"]"),a||(t.seen.indexOf(c.value)<0?(a=mi(r)?fi(t,c.value,null):fi(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")),bi(o)){if(s&&i.match(/^\d+$/))return a;(o=JSON.stringify(""+i)).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 gi(t){return"boolean"==typeof t}function mi(t){return null===t}function yi(t){return"string"==typeof t}function bi(t){return void 0===t}function wi(t){return _i(t)&&"[object RegExp]"===Oi(t)}function _i(t){return"object"==typeof t&&null!==t}function vi(t){return _i(t)&&"[object Date]"===Oi(t)}function ki(t){return _i(t)&&("[object Error]"===Oi(t)||t instanceof Error)}function Si(t){return"function"==typeof t}function Oi(t){return Object.prototype.toString.call(t)}function Ei(t,e){return Object.prototype.hasOwnProperty.call(t,e)}ui.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]},ui.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var Ri="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function xi(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(Ri&&t[Ri]){var e;if("function"!=typeof(e=t[Ri]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,Ri,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,r,n=new Promise(function(t,n){e=t,r=n}),i=[],s=0;s<arguments.length;s++)i.push(arguments[s]);i.push(function(t,n){t?r(t):e(n)});try{t.apply(this,i)}catch(t){r(t)}return n}return Object.setPrototypeOf(e,Object.getPrototypeOf(t)),Ri&&Object.defineProperty(e,Ri,{value:e,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(e,ni(t))}function Ai(){this.head=null,this.tail=null,this.length=0}xi.custom=Ri,Ai.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},Ai.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Ai.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}},Ai.prototype.clear=function(){this.head=this.tail=null,this.length=0},Ai.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},Ai.prototype.concat=function(t){if(0===this.length)return Kr.alloc(0);if(1===this.length)return this.head.data;for(var e=Kr.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var ji=Kr.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 Ii(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!ji(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=Pi;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Ti;break;default:return void(this.write=Di)}this.charBuffer=new Kr(6),this.charReceived=0,this.charLength=0}function Di(t){return t.toString(this.encoding)}function Pi(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function Ti(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}Ii.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),!((i=(e=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(e.length-1))>=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=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,n)}return e},Ii.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},Ii.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e},Mi.ReadableState=Ci;var Ni=function(t){if(bi(ai)&&(ai=ri.env.NODE_DEBUG||""),t=t.toUpperCase(),!ci[t])if(new RegExp("\\b"+t+"\\b","i").test(ai)){ci[t]=function(){var e=si.apply(null,arguments);console.error("%s %d: %s",t,0,e)}}else ci[t]=function(){};return ci[t]}("stream");function Ci(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof ls&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Ai,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 Ii(t.encoding),this.encoding=t.encoding)}function Mi(t){if(!(this instanceof Mi))return new Mi(t);this._readableState=new Ci(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),S.call(this)}function Li(t,e,r,n,i){var s=function(t,e){var r=null;Kr.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,zi(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var o=new Error("stream.push() after EOF");t.emit("error",o)}else if(e.endEmitted&&i){var a=new Error("stream.unshift() after end event");t.emit("error",a)}else{var c;!e.decoder||i||n||(r=e.decoder.write(r),c=!e.objectMode&&0===r.length),i||(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,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&zi(t))),function(t,e){e.readingMore||(e.readingMore=!0,Bn(Bi,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(e)}ei(Mi,S),Mi.prototype.push=function(t,e){var r=this._readableState;return r.objectMode||"string"!=typeof t||(e=e||r.defaultEncoding)!==r.encoding&&(t=Kr.from(t,e),e=""),Li(this,r,t,e,!1)},Mi.prototype.unshift=function(t){return Li(this,this._readableState,t,"",!0)},Mi.prototype.isPaused=function(){return!1===this._readableState.flowing},Mi.prototype.setEncoding=function(t){return this._readableState.decoder=new Ii(t),this._readableState.encoding=t,this};var $i=8388608;function Ui(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>=$i?t=$i:(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 zi(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Ni("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?Bn(Fi,t):Fi(t))}function Fi(t){Ni("emit readable"),t.emit("readable"),Hi(t)}function Bi(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(Ni("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function qi(t){Ni("readable nexttick read 0"),t.read(0)}function Vi(t,e){e.reading||(Ni("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),Hi(t),e.flowing&&!e.reading&&t.read(0)}function Hi(t){var e=t._readableState;for(Ni("flow",e.flowing);e.flowing&&null!==t.read(););}function Ki(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 n;t<e.head.data.length?(n=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):n=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,n=1,i=r.data;t-=i.length;for(;r=r.next;){var s=r.data,o=t>s.length?s.length:t;if(o===s.length?i+=s:i+=s.slice(0,t),0===(t-=o)){o===s.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=s.slice(o));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Kr.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var s=n.data,o=t>s.length?s.length:t;if(s.copy(r,r.length-t,0,o),0===(t-=o)){o===s.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=s.slice(o));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function Zi(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,Bn(Wi,e,t))}function Wi(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function Ji(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}function Gi(){}function Yi(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function Qi(t,e){Object.defineProperty(this,"buffer",{get:oi(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),t=t||{},this.objectMode=!!t.objectMode,e instanceof ls&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var i=!1===t.decodeStrings;this.decodeStrings=!i,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,n=r.sync,i=r.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?Bn(i,n):i(n);t._writableState.errorEmitted=!0,t.emit("error",n)}(t,r,n,e,i);else{var s=ns(r);s||r.corked||r.bufferProcessing||!r.bufferedRequest||rs(t,r),n?Bn(es,t,r,s,i):es(t,r,s,i)}}(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 os(this)}function Xi(t){if(!(this instanceof Xi||this instanceof ls))return new Xi(t);this._writableState=new Qi(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev)),S.call(this)}function ts(t,e,r,n,i,s,o){e.writelen=n,e.writecb=o,e.writing=!0,e.sync=!0,r?t._writev(i,e.onwrite):t._write(i,s,e.onwrite),e.sync=!1}function es(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),ss(t,e)}function rs(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),s=e.corkedRequestsFree;s.entry=r;for(var o=0;r;)i[o]=r,r=r.next,o+=1;ts(t,e,!0,e.length,i,"",s.finish),e.pendingcb++,e.lastBufferedRequest=null,s.next?(e.corkedRequestsFree=s.next,s.next=null):e.corkedRequestsFree=new os(e)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(ts(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 ns(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function is(t,e){e.prefinished||(e.prefinished=!0,t.emit("prefinish"))}function ss(t,e){var r=ns(e);return r&&(0===e.pendingcb?(is(t,e),e.finished=!0,t.emit("finish")):is(t,e)),r}function os(t){var e=this;this.next=null,this.entry=null,this.finish=function(r){var n=e.entry;for(e.entry=null;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}}Mi.prototype.read=function(t){Ni("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 Ni("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Zi(this):zi(this),null;if(0===(t=Ui(t,e))&&e.ended)return 0===e.length&&Zi(this),null;var n,i=e.needReadable;return Ni("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&Ni("length less than watermark",i=!0),e.ended||e.reading?Ni("reading or ended",i=!1):i&&(Ni("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=Ui(r,e))),null===(n=t>0?Ki(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Zi(this)),null!==n&&this.emit("data",n),n},Mi.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Mi.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Ni("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?o:u;function s(t){Ni("onunpipe"),t===r&&u()}function o(){Ni("onend"),t.end()}n.endEmitted?Bn(i):r.once("end",i),t.on("unpipe",s);var a=function(t){return function(){var e=t._readableState;Ni("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Hi(t))}}(r);t.on("drain",a);var c=!1;function u(){Ni("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,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||a()}var l=!1;function h(e){Ni("ondata"),l=!1,!1!==t.write(e)||l||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Ji(n.pipes,t))&&!c&&(Ni("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function f(e){Ni("onerror",e),g(),t.removeListener("error",f),0===function(t,e){return t.listeners(e).length}(t,"error")&&t.emit("error",e)}function d(){t.removeListener("finish",p),g()}function p(){Ni("onfinish"),t.removeListener("close",d),g()}function g(){Ni("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),n.flowing||(Ni("pipe resume"),r.resume()),t},Mi.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,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i<n;i++)r[i].emit("unpipe",this);return this}var s=Ji(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},Mi.prototype.on=function(t,e){var r=S.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var n=this._readableState;n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&zi(this):Bn(qi,this))}return r},Mi.prototype.addListener=Mi.prototype.on,Mi.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ni("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,Bn(Vi,t,e))}(this,t)),this},Mi.prototype.pause=function(){return Ni("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Ni("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Mi.prototype.wrap=function(t){var e=this._readableState,r=!1,n=this;for(var i in t.on("end",function(){if(Ni("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&n.push(t)}n.push(null)}),t.on("data",function(i){(Ni("wrapped data"),e.decoder&&(i=e.decoder.write(i)),e.objectMode&&null==i)||(e.objectMode||i&&i.length)&&(n.push(i)||(r=!0,t.pause()))}),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));return function(t,e){for(var r=0,n=t.length;r<n;r++)e(t[r],r)}(["error","close","destroy","pause","resume"],function(e){t.on(e,n.emit.bind(n,e))}),n._read=function(e){Ni("wrapped _read",e),r&&(r=!1,t.resume())},n},Mi._fromList=Ki,Xi.WritableState=Qi,ei(Xi,S),Qi.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},Xi.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Xi.prototype.write=function(t,e,r){var n=this._writableState,i=!1;return"function"==typeof e&&(r=e,e=null),Kr.isBuffer(t)?e="buffer":e||(e=n.defaultEncoding),"function"!=typeof r&&(r=Gi),n.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),Bn(e,r)}(this,r):function(t,e,r,n){var i=!0,s=!1;return null===r?s=new TypeError("May not write null values to stream"):Kr.isBuffer(r)||"string"==typeof r||void 0===r||e.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(t.emit("error",s),Bn(n,s),i=!1),i}(this,n,t,r)&&(n.pendingcb++,i=function(t,e,r,n,i){r=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Kr.from(e,r));return e}(e,r,n),Kr.isBuffer(r)&&(n="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 Yi(r,n,i),a?a.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else ts(t,e,!1,s,r,n,i);return o}(this,n,t,e,r)),i},Xi.prototype.cork=function(){this._writableState.corked++},Xi.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||rs(this,t))},Xi.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},Xi.prototype._write=function(t,e,r){r(new Error("not implemented"))},Xi.prototype._writev=null,Xi.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,ss(t,e),r&&(e.finished?Bn(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},ei(ls,Mi);for(var as=Object.keys(Xi.prototype),cs=0;cs<as.length;cs++){var us=as[cs];ls.prototype[us]||(ls.prototype[us]=Xi.prototype[us])}function ls(t){if(!(this instanceof ls))return new ls(t);Mi.call(this,t),Xi.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",hs)}function hs(){this.allowHalfOpen||this._writableState.ended||Bn(fs,this)}function fs(t){t.end()}function ds(t){this.afterTransform=function(e,r){return function(t,e,r){var n=t._transformState;n.transforming=!1;var i=n.writecb;if(!i)return t.emit("error",new Error("no writecb in Transform class"));n.writechunk=null,n.writecb=null,null!=r&&t.push(r);i(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 ps(t){if(!(this instanceof ps))return new ps(t);ls.call(this,t),this._transformState=new ds(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){gs(e,t)}):gs(e)})}function gs(t,e){if(e)return t.emit("error",e);var r=t._writableState,n=t._transformState;if(r.length)throw new Error("Calling transform done when ws.length != 0");if(n.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}function ms(t){if(!(this instanceof ms))return new ms(t);ps.call(this,t)}function ys(){S.call(this)}ei(ps,ls),ps.prototype.push=function(t,e){return this._transformState.needTransform=!1,ls.prototype.push.call(this,t,e)},ps.prototype._transform=function(t,e,r){throw new Error("Not implemented")},ps.prototype._write=function(t,e,r){var n=this._transformState;if(n.writecb=r,n.writechunk=t,n.writeencoding=e,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},ps.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},ei(ms,ps),ms.prototype._transform=function(t,e,r){r(null,t)},ei(ys,S),ys.Readable=Mi,ys.Writable=Xi,ys.Duplex=ls,ys.Transform=ps,ys.PassThrough=ms,ys.Stream=ys,ys.prototype.pipe=function(t,e){var r=this;function n(e){t.writable&&!1===t.write(e)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),t.on("drain",i),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===S.listenerCount(this,"error"))throw t}function u(){r.removeListener("data",n),t.removeListener("drain",i),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 bs extends S{constructor({resource:t}){super(),this.resource=t,this.client=t.client,this.stream=new c.ReadableStream({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){console.warn("Stream cancelled",t)}}class ws extends bs{enqueue(t){this.controller.enqueue(t),this.emit("page",t)}}class _s extends S{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 ws({resource:this.resource}),this.transform=new ps({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){try{await n.PromisePool.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()}catch(t){r(t)}}resume(){this.input.resume()}}class vs extends S{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 Xi({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);try{await n.PromisePool.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{await this.resource.insert(t)})}catch(t){this.emit("error",t)}}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(t,e,r){r()}}function ks(t){return new Promise((e,r)=>{const n=[];t.on("data",t=>n.push(t)),t.on("error",r),t.on("end",()=>e(Buffer.concat(n).toString("utf-8")))})}function Ss(t){"string"!=typeof t&&(t=String(t));let e=0;for(let r=0;r<t.length;r++){const n=t.codePointAt(r);n<=127?e+=1:n<=2047?e+=2:n<=65535?e+=3:n<=1114111&&(e+=4,n>65535&&r++)}return e}function Os(t){let e=0;for(const r of Object.keys(t))e+=Ss(r);return e}function Es(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 Rs(t){const e={};for(const[r,n]of Object.entries(t)){const t=Ss(Es(n));e[r]=t}return e}function xs(t){const e=Rs(t);return Object.values(e).reduce((t,e)=>t+e,0)+Os(t)}const As=2048;var js=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:As,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r}){const n=xs(r);if(n>As)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, limit: 2048 bytes`);return{mappedData:r,body:""}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){const i=xs(n);if(i>As)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${i} bytes, limit: 2048 bytes`);return{mappedData:n,body:""}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){const i=xs(n);if(i>As)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${i} bytes, limit: 2048 bytes`);return{mappedData:n,body:""}}});var Is=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}){const n=xs(r);return n>As&&t.emit("exceedsLimit",{operation:"insert",totalSize:n,limit:As,excess:n-As,data:e}),{mappedData:r,body:""}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){const i=xs(n);return i>As&&t.emit("exceedsLimit",{operation:"update",id:e,totalSize:i,limit:As,excess:i-As,data:r}),{mappedData:n,body:""}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){const i=xs(n);return i>As&&t.emit("exceedsLimit",{operation:"upsert",id:e,totalSize:i,limit:As,excess:i-As,data:r}),{mappedData:n,body:""}}});const Ds=Ss("...");function Ps({resource:t,data:e,mappedData:r}){const n=Rs(r),i=Object.entries(n).sort(([,t],[,e])=>t-e),s={};let o=0;for(const[t,e]of i){const n=As-o;if(!(e<=n)){if(n>Ds){const e=n-Ds,i=Es(r[t]);let a="",c=0;for(let t=0;t<i.length;t++){const r=i[t],n=Ss(r);if(!(c+n<=e))break;a+=r,c+=n}s[t]=a+"...",o=As;break}break}s[t]=r[t],o+=e}return{mappedData:s,body:""}}var Ts=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}){return Ps({resource:t,data:e,mappedData:r})},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){return Ps({resource:t,data:r,mappedData:n})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){return Ps({resource:t,data:r,mappedData:n})}});const Ns="$overflow",Cs="true",Ms=Ss(Ns)+Ss(Cs);function Ls({resource:t,data:e,mappedData:r}){if(xs(r)<=As)return{mappedData:r,body:""};const n=As-Ms,i=Rs(r),s=Object.entries(i).sort(([,t],[,e])=>t-e),o={},a={};let c=0;for(const[t,e]of s)c+e<=n?(o[t]=r[t],c+=e):a[t]=r[t];o[Ns]=Cs;return{mappedData:o,body:Object.keys(a).length>0?JSON.stringify(a):""}}const $s={"user-managed":Is,"enforce-limits":js,"data-truncate":Ts,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){if(e[Ns]===Cs)try{const t=r?JSON.parse(r):{},n={...e};delete n[Ns];return{metadata:{...n,...t},body:""}}catch(t){return{metadata:e,body:r}}return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r}){return Ls({resource:t,data:e,mappedData:r})},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){return Ls({resource:t,data:r,mappedData:n})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){return Ls({resource:t,data:r,mappedData:n})}}),"body-only":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){try{return{metadata:r?JSON.parse(r):{},body:""}}catch(t){return console.warn("Failed to parse body-only content:",t.message),{metadata:e,body:""}}},handleInsert:async function({resource:t,data:e,mappedData:r}){return{mappedData:{},body:JSON.stringify(r)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){return{mappedData:{},body:JSON.stringify(n)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){return{mappedData:{},body:JSON.stringify(n)}}})};function Us(t){const e=$s[t];if(!e)throw new Error(`Unknown behavior: ${t}. Available behaviors: ${Object.keys($s).join(", ")}`);return e}const zs=Object.keys($s),Fs="user-managed";function Bs(t){return e.customAlphabet(e.urlAlphabet,t)}class qs extends S{constructor(t){super();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 n of r)void 0!==t[n]&&"boolean"!=typeof t[n]&&e.push(`Resource '${n}' 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,n]of Object.entries(t.partitions))if("object"!=typeof n||Array.isArray(n))e.push(`Partition '${r}' must be an object`);else if(n.fields)if("object"!=typeof n.fields||Array.isArray(n.fields))e.push(`Partition '${r}.fields' must be an object`);else for(const[t,i]of Object.entries(n.fields))"string"!=typeof i&&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=["preInsert","afterInsert","preUpdate","afterUpdate","preDelete","afterDelete"];for(const[n,i]of Object.entries(t.hooks))if(r.includes(n))if(Array.isArray(i))for(let t=0;t<i.length;t++){const e=i[t];if("function"==typeof e);else if("string"==typeof e)continue}else e.push(`Resource 'hooks.${n}' must be an array`);else e.push(`Invalid hook event '${n}'. Valid events: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}(t);if(!e.isValid)throw new Error(`Invalid Resource configuration:\n${e.errors.join("\n")}`);const{name:r,client:n,version:i="1",attributes:s={},behavior:o=Fs,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}=t;if(this.name=r,this.client=n,this.version=i,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={preInsert:[],afterInsert:[],preUpdate:[],afterUpdate:[],preDelete:[],afterDelete:[]},this.attributes=s||{},this.applyConfiguration(),m)for(const[t,e]of Object.entries(m))if(Array.isArray(e)&&this.hooks[t])for(const r of e)"function"==typeof r&&this.hooks[t].push(r.bind(this))}configureIdGenerator(t,e){return"function"==typeof t?t:"number"==typeof t&&t>0?Bs(t):"number"==typeof e&&e>0?Bs(e):w}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}applyConfiguration(){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 Ir({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional}}),this.validatePartitions()}updateAttributes(t){const e=this.attributes;return this.attributes=t,this.applyConfiguration(),{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:r.cloneDeep(t),isValid:!1,errors:[]},n=await this.schema.validate(t,{mutateOriginal:!0});return!0===n?e.isValid=!0:e.errors=n,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,n]of Object.entries(t))if(n.fields)for(const t of Object.keys(n.fields))if(!this.fieldExistsInAttributes(t))throw new Error(`Partition '${r}' uses field '${t}' which does not exist in resource attributes. Available fields: ${e.join(", ")}.`)}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)try{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])}}catch(t){}return r}getResourceKey(t){return g(`resource=${this.name}`,"data",`id=${t}`)}getPartitionKey({partitionName:t,id:e,data:r}){if(!this.config.partitions||!this.config.partitions[t])throw new Error(`Partition '${t}' not found`);const n=this.config.partitions[t],i=[],s=Object.entries(n.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of s){const n=this.getNestedFieldValue(r,t),s=this.applyPartitionRule(n,e);if(null==s)return null;i.push(`${t}=${s}`)}if(0===i.length)return null;const o=e||r?.id;return o?g(`resource=${this.name}`,`partition=${t}`,...i,`id=${o}`):null}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let n=t;for(const t of r){if(!n||"object"!=typeof n||!(t in n))return;n=n[t]}return n}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}){this.options.timestamps&&(e.createdAt=(new Date).toISOString(),e.updatedAt=(new Date).toISOString());const n={id:t,...e},i=await this.executeHooks("preInsert",n),{errors:s,isValid:o,data:a}=await this.validate(i);if(!o)throw new C({bucket:this.client.config.bucket,resourceName:this.name,attributes:i,validation:s});const{id:c,...u}=a,l=c||t||this.idGenerator(),h=await this.schema.mapper(u);h._v=String(this.version);const f=Us(this.behavior),{mappedData:d,body:p}=await f.handleInsert({resource:this,data:u,mappedData:h}),g=d,m=this.getResourceKey(l);let y;if(p&&""!==p)try{JSON.parse(p),y="application/json"}catch{}await this.client.putObject({metadata:g,key:m,body:p,contentType:y,contentLength:this.calculateContentLength(p)});const b=r.merge({id:l},u);return await this.executeHooks("afterInsert",b),this.emit("insert",b),b}async get(t){const e=this.getResourceKey(t);try{const r=await this.client.headObject(e),n=r.Metadata?._v||this.version,i="string"==typeof n&&n.startsWith("v")?n.slice(1):n,s=await this.getSchemaForVersion(i);let o=await s.unmapper(r.Metadata);const a=Us(this.behavior);let c="";if(r.ContentLength>0)try{const t=await this.client.getObject(e);c=await ks(t.Body)}catch(e){console.warn(`Failed to read body for resource ${t}:`,e.message),c=""}const{metadata:u}=await a.handleGet({resource:this,metadata:o,body:c});let l=u;return l.id=t,l._contentLength=r.ContentLength,l._lastModified=r.LastModified,l._hasContent=r.ContentLength>0,l._mimeType=r.ContentType||null,l._v=i,r.VersionId&&(l._versionId=r.VersionId),r.Expiration&&(l._expiresAt=r.Expiration),l._definitionHash=this.getDefinitionHash(),i!==this.version&&(l=await this.applyVersionMapping(l,i,this.version)),this.emit("get",l),l}catch(r){if(r.message.includes("Cipher job failed")||r.message.includes("OperationError")||r.originalError?.message?.includes("Cipher job failed"))try{console.warn(`Decryption failed for resource ${t}, attempting to get raw metadata`);const r=await this.client.headObject(e),n=this.extractVersionFromKey(e)||this.version,i=new Ir({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:n,options:{...this.config,autoDecrypt:!1,autoEncrypt:!1}});let s=await i.unmapper(r.Metadata);const o=Us(this.behavior);let a="";if(r.ContentLength>0)try{const t=await this.client.getObject(e);a=await ks(t.Body)}catch(e){console.warn(`Failed to read body for resource ${t}:`,e.message),a=""}const{metadata:c}=await o.handleGet({resource:this,metadata:s,body:a});let u=c;return u.id=t,u._contentLength=r.ContentLength,u._lastModified=r.LastModified,u._hasContent=r.ContentLength>0,u._mimeType=r.ContentType||null,u._version=n,u._decryptionFailed=!0,r.VersionId&&(u._versionId=r.VersionId),r.Expiration&&(u._expiresAt=r.Expiration),u._definitionHash=this.getDefinitionHash(),this.emit("get",u),u}catch(e){console.error(`Fallback attempt also failed for resource ${t}:`,e.message)}const n=new Error(`Failed to get resource with id '${t}': ${r.message}`);throw n.originalError=r,n.resourceId=t,n.resourceKey=e,n}}async exists(t){try{const e=this.getResourceKey(t);return await this.client.headObject(e),!0}catch(t){return!1}}async update(t,e){const r=await this.get(t);this.config.timestamps&&(e.updatedAt=(new Date).toISOString());const n=await this.executeHooks("preUpdate",e),i={...r,...n,id:t},{isValid:s,errors:o,data:a}=await this.validate(i);if(!s)throw new C({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:o});const{id:c,...u}=a,l={...r,id:t},h={...u,id:t};await this.handlePartitionReferenceUpdates(l,h);const f=await this.schema.mapper(u);f._v=String(this.version);const d=Us(this.behavior),{mappedData:p,body:g}=await d.handleUpdate({resource:this,id:t,data:u,mappedData:f}),m=p,y=this.getResourceKey(t);let b,w=g;if(""===g&&"body-overflow"!==this.behavior)try{const t=await this.client.getObject(y);if(t.ContentLength>0){const e=Buffer.from(await t.Body.transformToByteArray()),r=e.toString();try{JSON.parse(r)}catch{w=e,b=t.ContentType}}}catch(t){}let _=b;if(w&&""!==w&&!_)try{JSON.parse(w),_="application/json"}catch{}return this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(t,r),await this.client.putObject({key:y,body:w,contentType:_,metadata:m}),u.id=t,await this.executeHooks("afterUpdate",u),this.emit("update",n,u),u}async delete(t){let e;try{e=await this.get(t)}catch(r){e={id:t}}await this.executeHooks("preDelete",e);const r=this.getResourceKey(t),n=await this.client.deleteObject(r);return await this.executeHooks("afterDelete",e),this.emit("delete",t),n}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 n=this.config.partitions[t];if(!n)throw new Error(`Partition '${t}' not found`);const i=[],s=Object.entries(n.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}`)}}r=i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}else r=`resource=${this.name}/data`;const n=await this.client.count({prefix:r});return this.emit("count",n),n}async insertMany(t){const{results:e}=await n.PromisePool.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=r.chunk(t.map(t=>this.getResourceKey(t)),1e3),{results:i}=await n.PromisePool.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),i}async deleteAll(){if(!1!==this.config.paranoid)throw new Error(`deleteAll() is a dangerous operation and requires paranoid: false option. Current paranoid setting: ${this.config.paranoid}`);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 Error(`deleteAllData() is a dangerous operation and requires paranoid: false option. Current paranoid setting: ${this.config.paranoid}`);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:n=0}={}){let i;if(t&&Object.keys(e).length>0){if(!this.config.partitions||!this.config.partitions[t])throw new Error(`Partition '${t}' not found`);const r=this.config.partitions[t],n=[],s=Object.entries(r.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}`)}}i=n.length>0?`resource=${this.name}/partition=${t}/${n.join("/")}`:`resource=${this.name}/partition=${t}`}else i=`resource=${this.name}/data`;const s=(await this.client.getKeysPage({prefix:i,offset:n,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:n=0}={}){try{return t?await this.listPartition({partition:t,partitionValues:e,limit:r,offset:n}):await this.listMain({limit:r,offset:n})}catch(r){return this.handleListError(r,{partition:t,partitionValues:e})}}async listMain({limit:t,offset:e=0}){const r=await this.listIds({limit:t,offset:e}),n=await this.processListResults(r,"main");return this.emit("list",{count:n.length,errors:0}),n}async listPartition({partition:t,partitionValues:e,limit:r,offset:n=0}){if(!this.config.partitions?.[t])return console.warn(`Partition '${t}' not found in resource '${this.name}'`),this.emit("list",{partition:t,partitionValues:e,count:0,errors:0}),[];const i=this.config.partitions[t],s=this.buildPartitionPrefix(t,i,e),o=await this.client.getAllKeys({prefix:s}),a=this.extractIdsFromKeys(o).slice(n),c=r?a.slice(0,r):a,u=await this.processPartitionResults(c,t,i,o);return this.emit("list",{partition:t,partitionValues:e,count:u.length,errors:0}),u}buildPartitionPrefix(t,e,r){const n=[],i=Object.entries(e.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of i){const i=r[t];if(null!=i){const r=this.applyPartitionRule(i,e);n.push(`${t}=${r}`)}}return n.length>0?`resource=${this.name}/partition=${t}/${n.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:i}=await n.PromisePool.for(t).withConcurrency(this.parallelism).handleError(async(t,r)=>(console.warn(`Failed to get ${e} resource ${r}:`,t.message),null)).process(async t=>{try{return await this.get(t)}catch(r){return this.handleResourceError(r,t,e)}});return r.filter(t=>null!==t)}async processPartitionResults(t,e,r,i){const s=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e)),{results:o,errors:a}=await n.PromisePool.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>(console.warn(`Failed to get partition resource ${e}:`,t.message),null)).process(async t=>{try{const r=this.extractPartitionValuesFromKey(t,i,s);return await this.getFromPartition({id:t,partitionName:e,partitionValues:r})}catch(e){return this.handleResourceError(e,t,"partition")}});return o.filter(t=>null!==t)}extractPartitionValuesFromKey(t,e,r){const n=e.find(e=>e.includes(`id=${t}`));if(!n)throw new Error(`Partition key not found for ID ${t}`);const i=n.split("/"),s={};for(const[t]of r){const e=i.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 console.warn(`Decryption failed for ${r} resource ${e}, returning basic info`),{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")?(console.warn("Partition error in list method:",t.message),this.emit("list",{partition:e,partitionValues:r,count:0,errors:1}),[]):(console.error("Critical error in list method:",t.message),this.emit("list",{partition:e,partitionValues:r,count:0,errors:1}),[])}async getMany(t){const{results:e,errors:r}=await n.PromisePool.for(t).withConcurrency(this.client.parallelism).handleError(async(t,e)=>(console.warn(`Failed to get resource ${e}:`,t.message),{id:e,_error:t.message,_decryptionFailed:t.message.includes("Cipher job failed")||t.message.includes("OperationError")})).process(async t=>{this.emit("id",t);try{const e=await this.get(t);return this.emit("data",e),e}catch(e){if(e.message.includes("Cipher job failed")||e.message.includes("OperationError"))return console.warn(`Decryption failed for ${t}, returning basic info`),{id:t,_decryptionFailed:!0,_error:e.message};throw e}});return this.emit("getMany",t.length),e}async getAll(){let t=await this.listIds();if(0===t.length)return[];const{results:e,errors:r}=await n.PromisePool.for(t).withConcurrency(this.client.parallelism).handleError(async(t,e)=>(console.warn(`Failed to get resource ${e}:`,t.message),{id:e,_error:t.message,_decryptionFailed:t.message.includes("Cipher job failed")||t.message.includes("OperationError")})).process(async t=>{try{return await this.get(t)}catch(e){if(e.message.includes("Cipher job failed")||e.message.includes("OperationError"))return console.warn(`Decryption failed for ${t}, returning basic info`),{id:t,_decryptionFailed:!0,_error:e.message};throw e}});return this.emit("getAll",e.length),e}async page({offset:t=0,size:e=100,partition:r=null,partitionValues:n={},skipCount:i=!1}={}){try{let s=null,o=null;if(!i)try{s=await this.count({partition:r,partitionValues:n}),o=Math.ceil(s/e)}catch(t){console.warn("Failed to get count for page:",t.message),s=null,o=null}const a=Math.floor(t/e);let c=[];try{c=await this.list({partition:r,partitionValues:n,limit:e,offset:t})}catch(t){console.warn("Failed to get items for page:",t.message),c=[]}const u={items:c,totalItems:s,page:a,pageSize:e,totalPages:o,_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:c.length,skipCount:i,hasTotalItems:null!==s}};return this.emit("page",u),u}catch(r){return console.error("Critical error in page method:",r.message),{items:[],totalItems:null,page:Math.floor(t/e),pageSize:e,totalPages:null,_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:0,skipCount:i,hasTotalItems:!1,error:r.message}}}}readable(){return new _s({resource:this}).build()}writable(){return new vs({resource:this}).build()}async setContent({id:t,buffer:e,contentType:r="application/octet-stream"}){const n=await this.get(t);if(!n)throw new Error(`Resource with id '${t}' not found`);const i={...n,_hasContent:!0,_contentLength:e.length,_mimeType:r};return await this.client.putObject({key:this.getResourceKey(t),metadata:await this.schema.mapper(i),body:e,contentType:r}),this.emit("setContent",{id:t,contentType:r,contentLength:e.length}),i}async content(t){const e=this.getResourceKey(t);try{const r=await this.client.getObject(e),n=Buffer.from(await r.Body.transformToByteArray()),i=r.ContentType||null;return this.emit("content",t,n.length,i),{buffer:n,contentType:i}}catch(t){if("NoSuchKey"===t.name)return{buffer:null,contentType:null};throw t}}async hasContent(t){const e=this.getResourceKey(t);try{return(await this.client.headObject(e)).ContentLength>0}catch(t){return!1}}async deleteContent(t){const e=this.getResourceKey(t),r=(await this.client.headObject(e)).Metadata||{},n=await this.client.putObject({key:e,body:"",metadata:r});return this.emit("deleteContent",t),n}getDefinitionHash(){const t={attributes:this.attributes,behavior:this.behavior},e=Or(t);return`sha256:${s.createHash("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;try{return new Ir({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:t,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})}catch(e){return console.warn(`Failed to create compatible schema for version ${t}, using current schema:`,e.message),this.schema}}async createPartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,n]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[n,i]of Object.entries(e)){const e=this.getPartitionKey({partitionName:n,id:t.id,data:t});e&&r.push(e)}if(r.length>0)try{await this.client.deleteObjects(r)}catch(t){console.warn("Some partition objects could not be deleted:",t.message)}}async query(t={},{limit:e=100,offset:r=0,partition:n=null,partitionValues:i={}}={}){if(0===Object.keys(t).length)return await this.list({partition:n,partitionValues:i,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:n,partitionValues:i,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[n,i]of Object.entries(r))try{await this.handlePartitionReferenceUpdate(n,i,t,e)}catch(t){console.warn(`Failed to update partition references for ${n}:`,t.message)}const n=e.id||t.id;for(const[t,i]of Object.entries(r)){const r=`resource=${this.name}/partition=${t}`;let i=[];try{i=await this.client.getAllKeys({prefix:r})}catch(e){console.warn(`Aggressive cleanup: could not list keys for partition ${t}:`,e.message);continue}const s=this.getPartitionKey({partitionName:t,id:n,data:e});for(const t of i)if(t.endsWith(`/id=${n}`)&&t!==s)try{await this.client.deleteObject(t)}catch(e){console.warn(`Aggressive cleanup: could not delete stale partition key ${t}:`,e.message)}}}async handlePartitionReferenceUpdate(t,e,r,n){const i=n.id||r.id,s=this.getPartitionKey({partitionName:t,id:i,data:r}),o=this.getPartitionKey({partitionName:t,id:i,data:n});if(s!==o){if(s)try{await this.client.deleteObject(s)}catch(e){console.warn(`Old partition object could not be deleted for ${t}:`,e.message)}if(o)try{const t={_v:String(this.version)};await this.client.putObject({key:o,metadata:t,body:"",contentType:void 0})}catch(e){console.warn(`New partition object could not be created for ${t}:`,e.message)}}else if(o)try{const t={_v:String(this.version)};await this.client.putObject({key:o,metadata:t,body:"",contentType:void 0})}catch(e){console.warn(`Partition object could not be updated for ${t}:`,e.message)}}async updatePartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,n]of Object.entries(e)){if(!n||!n.fields||"object"!=typeof n.fields){console.warn(`Skipping invalid partition '${r}' in resource '${this.name}'`);continue}const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)};try{await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})}catch(t){console.warn(`Partition object could not be updated for ${r}:`,t.message)}}}}async getFromPartition({id:t,partitionName:e,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[e])throw new Error(`Partition '${e}' not found`);const n=this.config.partitions[e],i=[],s=Object.entries(n.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of s){const n=r[t];if(null!=n){const r=this.applyPartitionRule(n,e);i.push(`${t}=${r}`)}}if(0===i.length)throw new Error(`No partition values provided for partition '${e}'`);const o=g(`resource=${this.name}`,`partition=${e}`,...i,`id=${t}`);try{await this.client.headObject(o)}catch(r){throw new Error(`Resource with id '${t}' not found in partition '${e}'`)}const a=await this.get(t);return a._partition=e,a._partitionValues=r,this.emit("getFromPartition",a),a}async createHistoricalVersion(t,e){const r=g(`resource=${this.name}`,"historical",`id=${t}`),n={...e,_v:e._v||this.version,_historicalTimestamp:(new Date).toISOString()},i=await this.schema.mapper(n),s=Us(this.behavior),{mappedData:o,body:a}=await s.handleInsert({resource:this,data:n,mappedData:i}),c={...o,_v:e._v||this.version,_historicalTimestamp:n._historicalTimestamp};let u;if(a&&""!==a)try{JSON.parse(a),u="application/json"}catch{}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}}}class Vs extends S{constructor(t){super(),this.version="1",this.s3dbVersion=(()=>{try{return"6.1.0"}catch(t){return"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:n,accessKeyId:i,secretAccessKey:s,endpoint:o,forcePathStyle:a}=t;if(o){const t=new URL(o);i&&(t.username=encodeURIComponent(i)),s&&(t.password=encodeURIComponent(s)),t.pathname=`/${r||"s3db"}`,a&&t.searchParams.set("forcePathStyle","true"),e=t.toString()}else if(i&&s){const t=new URLSearchParams;t.set("region",n||"us-east-1"),a&&t.set("forcePathStyle","true"),e=`s3://${encodeURIComponent(i)}:${encodeURIComponent(s)}@${r||"s3db"}?${t.toString()}`}}this.client=t.client||new F({verbose:this.verbose,parallelism:this.parallelism,connectionString:e}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix}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 ks(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",n=r.versions?.[t];n&&(this.resources[e]=new qs({name:e,client:this.client,version:t,attributes:n.attributes,behavior:n.behavior||"user-managed",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:void 0!==n.timestamps&&n.timestamps,partitions:r.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:n.hooks||{},versioningEnabled:this.versioningEnabled}))}e.length>0&&this.emit("resourceDefinitionsChanged",{changes:e,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(t){const e=[];for(const[r,n]of Object.entries(this.resources)){const i=this.generateDefinitionHash(n.export()),s=t.resources?.[r];if(s){const t=s.currentVersion||"v0",n=s.versions?.[t],o=n?.hash;o!==i&&e.push({type:"changed",resourceName:r,currentHash:i,savedHash:o,fromVersion:t,toVersion:this.getNextVersion(s.versions)})}else e.push({type:"new",resourceName:r,currentHash:i,savedHash:null})}for(const[r,n]of Object.entries(t.resources||{}))if(!this.resources[r]){const t=n.currentVersion||"v0",i=n.versions?.[t];e.push({type:"deleted",resourceName:r,currentHash:null,savedHash:i?.hash,deletedVersion:t})}return e}generateDefinitionHash(t,e=void 0){const r={...t.attributes};t.timestamps&&(delete r.createdAt,delete r.updatedAt);const n={attributes:r,behavior:e||t.behavior||"user-managed"},i=Or(n);return`sha256:${s.createHash("sha256").update(i).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(!r.isEmpty(this.pluginList)){const e=this.pluginList.map(t=>r.isFunction(t)?new t(this):t),n=e.map(async e=>{e.beforeSetup&&await e.beforeSetup(),await e.setup(t),e.afterSetup&&await e.afterSetup()});await Promise.all(n);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 n=r.export(),i=this.generateDefinitionHash(n),s=this.savedMetadata?.resources?.[e],o=s?.currentVersion||"v0",a=s?.versions?.[o];let c,u;a&&a.hash===i?(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:i,attributes:n.attributes,behavior:n.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",options:n={}}){if(!this.resources[t])return{exists:!1,sameHash:!1,hash:null};const i=this.resources[t],s=this.generateDefinitionHash(i.export()),o=new qs({name:t,attributes:e,behavior:r,client:this.client,version:i.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...n}),a=this.generateDefinitionHash(o.export());return{exists:!0,sameHash:s===a,hash:a,existingHash:s}}async createResource({name:t,attributes:e,behavior:r="user-managed",hooks:n,...i}){if(this.resources[t]){const s=this.resources[t];if(Object.assign(s.config,{cache:this.cache,...i}),r&&(s.behavior=r),s.versioningEnabled=this.versioningEnabled,s.updateAttributes(e),n)for(const[t,e]of Object.entries(n))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 qs({name:t,attributes:e,behavior:r,observers:[this],client:this.client,version:o,passphrase:this.passphrase,cache:this.cache,hooks:n,versioningEnabled:this.versioningEnabled,...i});return 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 Error(`Resource not found: ${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}}class Hs extends Vs{}class Ks extends S{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(){const t=await this._clear();return this.emit("clear",t),t}}class Zs extends Ks{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(){return this.cache={},this.meta={},!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}}var Ws={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};function Js(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}function Gs(t,e,r,n,i){if(e.subarray&&t.subarray)t.set(e.subarray(r,r+n),i);else for(var s=0;s<n;s++)t[i+s]=e[r+s]}var Ys=Uint8Array,Qs=Uint16Array,Xs=Int32Array;function to(t){for(var e=t.length;--e>=0;)t[e]=0}var eo=256,ro=286,no=30,io=15,so=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],oo=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ao=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],co=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],uo=new Array(576);to(uo);var lo=new Array(60);to(lo);var ho=new Array(512);to(ho);var fo=new Array(256);to(fo);var po=new Array(29);to(po);var go,mo,yo,bo=new Array(no);function wo(t,e,r,n,i){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=t&&t.length}function _o(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function vo(t){return t<256?ho[t]:ho[256+(t>>>7)]}function ko(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function So(t,e,r){t.bi_valid>16-r?(t.bi_buf|=e<<t.bi_valid&65535,ko(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=r-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)}function Oo(t,e,r){So(t,r[2*e],r[2*e+1])}function Eo(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function Ro(t,e,r){var n,i,s=new Array(16),o=0;for(n=1;n<=io;n++)s[n]=o=o+r[n-1]<<1;for(i=0;i<=e;i++){var a=t[2*i+1];0!==a&&(t[2*i]=Eo(s[a]++,a))}}function xo(t){var e;for(e=0;e<ro;e++)t.dyn_ltree[2*e]=0;for(e=0;e<no;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function Ao(t){t.bi_valid>8?ko(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function jo(t,e,r,n){var i=2*e,s=2*r;return t[i]<t[s]||t[i]===t[s]&&n[e]<=n[r]}function Io(t,e,r){for(var n=t.heap[r],i=r<<1;i<=t.heap_len&&(i<t.heap_len&&jo(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!jo(e,n,t.heap[i],t.depth));)t.heap[r]=t.heap[i],r=i,i<<=1;t.heap[r]=n}function Do(t,e,r){var n,i,s,o,a=0;if(0!==t.last_lit)do{n=t.pending_buf[t.d_buf+2*a]<<8|t.pending_buf[t.d_buf+2*a+1],i=t.pending_buf[t.l_buf+a],a++,0===n?Oo(t,i,e):(Oo(t,(s=fo[i])+eo+1,e),0!==(o=so[s])&&So(t,i-=po[s],o),Oo(t,s=vo(--n),r),0!==(o=oo[s])&&So(t,n-=bo[s],o))}while(a<t.last_lit);Oo(t,256,e)}function Po(t,e){var r,n,i,s=e.dyn_tree,o=e.stat_desc.static_tree,a=e.stat_desc.has_stree,c=e.stat_desc.elems,u=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<c;r++)0!==s[2*r]?(t.heap[++t.heap_len]=u=r,t.depth[r]=0):s[2*r+1]=0;for(;t.heap_len<2;)s[2*(i=t.heap[++t.heap_len]=u<2?++u:0)]=1,t.depth[i]=0,t.opt_len--,a&&(t.static_len-=o[2*i+1]);for(e.max_code=u,r=t.heap_len>>1;r>=1;r--)Io(t,s,r);i=c;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],Io(t,s,1),n=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=n,s[2*i]=s[2*r]+s[2*n],t.depth[i]=(t.depth[r]>=t.depth[n]?t.depth[r]:t.depth[n])+1,s[2*r+1]=s[2*n+1]=i,t.heap[1]=i++,Io(t,s,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var r,n,i,s,o,a,c=e.dyn_tree,u=e.max_code,l=e.stat_desc.static_tree,h=e.stat_desc.has_stree,f=e.stat_desc.extra_bits,d=e.stat_desc.extra_base,p=e.stat_desc.max_length,g=0;for(s=0;s<=io;s++)t.bl_count[s]=0;for(c[2*t.heap[t.heap_max]+1]=0,r=t.heap_max+1;r<573;r++)(s=c[2*c[2*(n=t.heap[r])+1]+1]+1)>p&&(s=p,g++),c[2*n+1]=s,n>u||(t.bl_count[s]++,o=0,n>=d&&(o=f[n-d]),a=c[2*n],t.opt_len+=a*(s+o),h&&(t.static_len+=a*(l[2*n+1]+o)));if(0!==g){do{for(s=p-1;0===t.bl_count[s];)s--;t.bl_count[s]--,t.bl_count[s+1]+=2,t.bl_count[p]--,g-=2}while(g>0);for(s=p;0!==s;s--)for(n=t.bl_count[s];0!==n;)(i=t.heap[--r])>u||(c[2*i+1]!==s&&(t.opt_len+=(s-c[2*i+1])*c[2*i],c[2*i+1]=s),n--)}}(t,e),Ro(s,u,t.bl_count)}function To(t,e,r){var n,i,s=-1,o=e[1],a=0,c=7,u=4;for(0===o&&(c=138,u=3),e[2*(r+1)+1]=65535,n=0;n<=r;n++)i=o,o=e[2*(n+1)+1],++a<c&&i===o||(a<u?t.bl_tree[2*i]+=a:0!==i?(i!==s&&t.bl_tree[2*i]++,t.bl_tree[32]++):a<=10?t.bl_tree[34]++:t.bl_tree[36]++,a=0,s=i,0===o?(c=138,u=3):i===o?(c=6,u=3):(c=7,u=4))}function No(t,e,r){var n,i,s=-1,o=e[1],a=0,c=7,u=4;for(0===o&&(c=138,u=3),n=0;n<=r;n++)if(i=o,o=e[2*(n+1)+1],!(++a<c&&i===o)){if(a<u)do{Oo(t,i,t.bl_tree)}while(0!==--a);else 0!==i?(i!==s&&(Oo(t,i,t.bl_tree),a--),Oo(t,16,t.bl_tree),So(t,a-3,2)):a<=10?(Oo(t,17,t.bl_tree),So(t,a-3,3)):(Oo(t,18,t.bl_tree),So(t,a-11,7));a=0,s=i,0===o?(c=138,u=3):i===o?(c=6,u=3):(c=7,u=4)}}to(bo);var Co=!1;function Mo(t){Co||(!function(){var t,e,r,n,i,s=new Array(16);for(r=0,n=0;n<28;n++)for(po[n]=r,t=0;t<1<<so[n];t++)fo[r++]=n;for(fo[r-1]=n,i=0,n=0;n<16;n++)for(bo[n]=i,t=0;t<1<<oo[n];t++)ho[i++]=n;for(i>>=7;n<no;n++)for(bo[n]=i<<7,t=0;t<1<<oo[n]-7;t++)ho[256+i++]=n;for(e=0;e<=io;e++)s[e]=0;for(t=0;t<=143;)uo[2*t+1]=8,t++,s[8]++;for(;t<=255;)uo[2*t+1]=9,t++,s[9]++;for(;t<=279;)uo[2*t+1]=7,t++,s[7]++;for(;t<=287;)uo[2*t+1]=8,t++,s[8]++;for(Ro(uo,287,s),t=0;t<no;t++)lo[2*t+1]=5,lo[2*t]=Eo(t,5);go=new wo(uo,so,257,ro,io),mo=new wo(lo,oo,0,no,io),yo=new wo(new Array(0),ao,0,19,7)}(),Co=!0),t.l_desc=new _o(t.dyn_ltree,go),t.d_desc=new _o(t.dyn_dtree,mo),t.bl_desc=new _o(t.bl_tree,yo),t.bi_buf=0,t.bi_valid=0,xo(t)}function Lo(t,e,r,n){So(t,0+(n?1:0),3),function(t,e,r){Ao(t),ko(t,r),ko(t,~r),Gs(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}(t,e,r)}function $o(t){So(t,2,3),Oo(t,256,uo),function(t){16===t.bi_valid?(ko(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}function Uo(t,e,r,n){var i,s,o=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,r=4093624447;for(e=0;e<=31;e++,r>>>=1)if(1&r&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<eo;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),Po(t,t.l_desc),Po(t,t.d_desc),o=function(t){var e;for(To(t,t.dyn_ltree,t.l_desc.max_code),To(t,t.dyn_dtree,t.d_desc.max_code),Po(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*co[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),i=t.opt_len+3+7>>>3,(s=t.static_len+3+7>>>3)<=i&&(i=s)):i=s=r+5,r+4<=i&&-1!==e?Lo(t,e,r,n):4===t.strategy||s===i?(So(t,2+(n?1:0),3),Do(t,uo,lo)):(So(t,4+(n?1:0),3),function(t,e,r,n){var i;for(So(t,e-257,5),So(t,r-1,5),So(t,n-4,4),i=0;i<n;i++)So(t,t.bl_tree[2*co[i]+1],3);No(t,t.dyn_ltree,e-1),No(t,t.dyn_dtree,r-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),Do(t,t.dyn_ltree,t.dyn_dtree)),xo(t),n&&Ao(t)}function zo(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(fo[r]+eo+1)]++,t.dyn_dtree[2*vo(e)]++),t.last_lit===t.lit_bufsize-1}function Fo(t,e,r,n){for(var i=65535&t,s=t>>>16&65535,o=0;0!==r;){r-=o=r>2e3?2e3:r;do{s=s+(i=i+e[n++]|0)|0}while(--o);i%=65521,s%=65521}return i|s<<16}var Bo=function(){for(var t,e=[],r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();function qo(t,e,r,n){var i=Bo,s=n+r;t^=-1;for(var o=n;o<s;o++)t=t>>>8^i[255&(t^e[o])];return-1^t}var Vo,Ho=-2,Ko=258,Zo=262,Wo=103,Jo=113,Go=666;function Yo(t,e){return t.msg=Ws[e],e}function Qo(t){return(t<<1)-(t>4?9:0)}function Xo(t){for(var e=t.length;--e>=0;)t[e]=0}function ta(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(Gs(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function ea(t,e){Uo(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ta(t.strm)}function ra(t,e){t.pending_buf[t.pending++]=e}function na(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function ia(t,e,r,n){var i=t.avail_in;return i>n&&(i=n),0===i?0:(t.avail_in-=i,Gs(e,t.input,t.next_in,i,r),1===t.state.wrap?t.adler=Fo(t.adler,e,i,r):2===t.state.wrap&&(t.adler=qo(t.adler,e,i,r)),t.next_in+=i,t.total_in+=i,i)}function sa(t,e){var r,n,i=t.max_chain_length,s=t.strstart,o=t.prev_length,a=t.nice_match,c=t.strstart>t.w_size-Zo?t.strstart-(t.w_size-Zo):0,u=t.window,l=t.w_mask,h=t.prev,f=t.strstart+Ko,d=u[s+o-1],p=u[s+o];t.prev_length>=t.good_match&&(i>>=2),a>t.lookahead&&(a=t.lookahead);do{if(u[(r=e)+o]===p&&u[r+o-1]===d&&u[r]===u[s]&&u[++r]===u[s+1]){s+=2,r++;do{}while(u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&s<f);if(n=Ko-(f-s),s=f-Ko,n>o){if(t.match_start=e,o=n,n>=a)break;d=u[s+o-1],p=u[s+o]}}}while((e=h[e&l])>c&&0!==--i);return o<=t.lookahead?o:t.lookahead}function oa(t){var e,r,n,i,s,o=t.w_size;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=o+(o-Zo)){Gs(t.window,t.window,o,o,0),t.match_start-=o,t.strstart-=o,t.block_start-=o,e=r=t.hash_size;do{n=t.head[--e],t.head[e]=n>=o?n-o:0}while(--r);e=r=o;do{n=t.prev[--e],t.prev[e]=n>=o?n-o:0}while(--r);i+=o}if(0===t.strm.avail_in)break;if(r=ia(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=r,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=(t.ins_h<<t.hash_shift^t.window[s+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[s+3-1])&t.hash_mask,t.prev[s&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=s,s++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Zo&&0!==t.strm.avail_in)}function aa(t,e){for(var r,n;;){if(t.lookahead<Zo){if(oa(t),t.lookahead<Zo&&0===e)return 1;if(0===t.lookahead)break}if(r=0,t.lookahead>=3&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==r&&t.strstart-r<=t.w_size-Zo&&(t.match_length=sa(t,r)),t.match_length>=3)if(n=zo(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=zo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(ea(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,4===e?(ea(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ea(t,!1),0===t.strm.avail_out)?1:2}function ca(t,e){for(var r,n,i;;){if(t.lookahead<Zo){if(oa(t),t.lookahead<Zo&&0===e)return 1;if(0===t.lookahead)break}if(r=0,t.lookahead>=3&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==r&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-Zo&&(t.match_length=sa(t,r),t.match_length<=5&&(1===t.strategy||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-3,n=zo(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=i&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,n&&(ea(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if((n=zo(t,0,t.window[t.strstart-1]))&&ea(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=zo(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,4===e?(ea(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ea(t,!1),0===t.strm.avail_out)?1:2}function ua(t,e,r,n,i){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=i}function la(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Qs(1146),this.dyn_dtree=new Qs(122),this.bl_tree=new Qs(78),Xo(this.dyn_ltree),Xo(this.dyn_dtree),Xo(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Qs(16),this.heap=new Qs(573),Xo(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Qs(573),Xo(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function ha(t){var e,r=function(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=2,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?42:Jo,t.adler=2===e.wrap?0:1,e.last_flush=0,Mo(e),0):Yo(t,Ho)}(t);return 0===r&&((e=t.state).window_size=2*e.w_size,Xo(e.head),e.max_lazy_match=Vo[e.level].max_lazy,e.good_match=Vo[e.level].good_length,e.nice_match=Vo[e.level].nice_length,e.max_chain_length=Vo[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0),r}function fa(t,e){var r,n,i,s;if(!t||!t.state||e>5||e<0)return t?Yo(t,Ho):Ho;if(n=t.state,!t.output||!t.input&&0!==t.avail_in||n.status===Go&&4!==e)return Yo(t,0===t.avail_out?-5:Ho);if(n.strm=t,r=n.last_flush,n.last_flush=e,42===n.status)if(2===n.wrap)t.adler=0,ra(n,31),ra(n,139),ra(n,8),n.gzhead?(ra(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),ra(n,255&n.gzhead.time),ra(n,n.gzhead.time>>8&255),ra(n,n.gzhead.time>>16&255),ra(n,n.gzhead.time>>24&255),ra(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),ra(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(ra(n,255&n.gzhead.extra.length),ra(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=qo(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(ra(n,0),ra(n,0),ra(n,0),ra(n,0),ra(n,0),ra(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),ra(n,3),n.status=Jo);else{var o=8+(n.w_bits-8<<4)<<8;o|=(n.strategy>=2||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(o|=32),o+=31-o%31,n.status=Jo,na(n,o),0!==n.strstart&&(na(n,t.adler>>>16),na(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(t.adler=qo(t.adler,n.pending_buf,n.pending-i,i)),ta(t),i=n.pending,n.pending!==n.pending_buf_size));)ra(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(t.adler=qo(t.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=qo(t.adler,n.pending_buf,n.pending-i,i)),ta(t),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,ra(n,s)}while(0!==s);n.gzhead.hcrc&&n.pending>i&&(t.adler=qo(t.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=qo(t.adler,n.pending_buf,n.pending-i,i)),ta(t),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,ra(n,s)}while(0!==s);n.gzhead.hcrc&&n.pending>i&&(t.adler=qo(t.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.status=Wo)}else n.status=Wo;if(n.status===Wo&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&ta(t),n.pending+2<=n.pending_buf_size&&(ra(n,255&t.adler),ra(n,t.adler>>8&255),t.adler=0,n.status=Jo)):n.status=Jo),0!==n.pending){if(ta(t),0===t.avail_out)return n.last_flush=-1,0}else if(0===t.avail_in&&Qo(e)<=Qo(r)&&4!==e)return Yo(t,-5);if(n.status===Go&&0!==t.avail_in)return Yo(t,-5);if(0!==t.avail_in||0!==n.lookahead||0!==e&&n.status!==Go){var a=2===n.strategy?function(t,e){for(var r;;){if(0===t.lookahead&&(oa(t),0===t.lookahead)){if(0===e)return 1;break}if(t.match_length=0,r=zo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(ea(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(ea(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ea(t,!1),0===t.strm.avail_out)?1:2}(n,e):3===n.strategy?function(t,e){for(var r,n,i,s,o=t.window;;){if(t.lookahead<=Ko){if(oa(t),t.lookahead<=Ko&&0===e)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=o[i=t.strstart-1])===o[++i]&&n===o[++i]&&n===o[++i]){s=t.strstart+Ko;do{}while(n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&i<s);t.match_length=Ko-(s-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(r=zo(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=zo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(ea(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(ea(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ea(t,!1),0===t.strm.avail_out)?1:2}(n,e):Vo[n.level].func(n,e);if(3!==a&&4!==a||(n.status=Go),1===a||3===a)return 0===t.avail_out&&(n.last_flush=-1),0;if(2===a&&(1===e?$o(n):5!==e&&(Lo(n,0,0,!1),3===e&&(Xo(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),ta(t),0===t.avail_out))return n.last_flush=-1,0}return 4!==e?0:n.wrap<=0?1:(2===n.wrap?(ra(n,255&t.adler),ra(n,t.adler>>8&255),ra(n,t.adler>>16&255),ra(n,t.adler>>24&255),ra(n,255&t.total_in),ra(n,t.total_in>>8&255),ra(n,t.total_in>>16&255),ra(n,t.total_in>>24&255)):(na(n,t.adler>>>16),na(n,65535&t.adler)),ta(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?0:1)}Vo=[new ua(0,0,0,0,function(t,e){var r=65535;for(r>t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(oa(t),0===t.lookahead&&0===e)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+r;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,ea(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-Zo&&(ea(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(ea(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(ea(t,!1),t.strm.avail_out),1)}),new ua(4,4,8,4,aa),new ua(4,5,16,8,aa),new ua(4,6,32,32,aa),new ua(4,4,16,16,ca),new ua(8,16,32,32,ca),new ua(8,16,128,128,ca),new ua(8,32,128,256,ca),new ua(32,128,258,1024,ca),new ua(32,258,258,4096,ca)];function da(t,e){var r,n,i,s,o,a,c,u,l,h,f,d,p,g,m,y,b,w,_,v,k,S,O,E,R;r=t.state,n=t.next_in,E=t.input,i=n+(t.avail_in-5),s=t.next_out,R=t.output,o=s-(e-t.avail_out),a=s+(t.avail_out-257),c=r.dmax,u=r.wsize,l=r.whave,h=r.wnext,f=r.window,d=r.hold,p=r.bits,g=r.lencode,m=r.distcode,y=(1<<r.lenbits)-1,b=(1<<r.distbits)-1;t:do{p<15&&(d+=E[n++]<<p,p+=8,d+=E[n++]<<p,p+=8),w=g[d&y];e:for(;;){if(d>>>=_=w>>>24,p-=_,0===(_=w>>>16&255))R[s++]=65535&w;else{if(!(16&_)){if(64&_){if(32&_){r.mode=12;break t}t.msg="invalid literal/length code",r.mode=30;break t}w=g[(65535&w)+(d&(1<<_)-1)];continue e}for(v=65535&w,(_&=15)&&(p<_&&(d+=E[n++]<<p,p+=8),v+=d&(1<<_)-1,d>>>=_,p-=_),p<15&&(d+=E[n++]<<p,p+=8,d+=E[n++]<<p,p+=8),w=m[d&b];;){if(d>>>=_=w>>>24,p-=_,16&(_=w>>>16&255)){if(k=65535&w,p<(_&=15)&&(d+=E[n++]<<p,(p+=8)<_&&(d+=E[n++]<<p,p+=8)),(k+=d&(1<<_)-1)>c){t.msg="invalid distance too far back",r.mode=30;break t}if(d>>>=_,p-=_,k>(_=s-o)){if((_=k-_)>l&&r.sane){t.msg="invalid distance too far back",r.mode=30;break t}if(S=0,O=f,0===h){if(S+=u-_,_<v){v-=_;do{R[s++]=f[S++]}while(--_);S=s-k,O=R}}else if(h<_){if(S+=u+h-_,(_-=h)<v){v-=_;do{R[s++]=f[S++]}while(--_);if(S=0,h<v){v-=_=h;do{R[s++]=f[S++]}while(--_);S=s-k,O=R}}}else if(S+=h-_,_<v){v-=_;do{R[s++]=f[S++]}while(--_);S=s-k,O=R}for(;v>2;)R[s++]=O[S++],R[s++]=O[S++],R[s++]=O[S++],v-=3;v&&(R[s++]=O[S++],v>1&&(R[s++]=O[S++]))}else{S=s-k;do{R[s++]=R[S++],R[s++]=R[S++],R[s++]=R[S++],v-=3}while(v>2);v&&(R[s++]=R[S++],v>1&&(R[s++]=R[S++]))}break}if(64&_){t.msg="invalid distance code",r.mode=30;break t}w=m[(65535&w)+(d&(1<<_)-1)]}}break}}while(n<i&&s<a);n-=v=p>>3,d&=(1<<(p-=v<<3))-1,t.next_in=n,t.next_out=s,t.avail_in=n<i?i-n+5:5-(n-i),t.avail_out=s<a?a-s+257:257-(s-a),r.hold=d,r.bits=p}var pa=15,ga=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],ma=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],ya=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],ba=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function wa(t,e,r,n,i,s,o,a){var c,u,l,h,f,d,p,g,m,y=a.bits,b=0,w=0,_=0,v=0,k=0,S=0,O=0,E=0,R=0,x=0,A=null,j=0,I=new Qs(16),D=new Qs(16),P=null,T=0;for(b=0;b<=pa;b++)I[b]=0;for(w=0;w<n;w++)I[e[r+w]]++;for(k=y,v=pa;v>=1&&0===I[v];v--);if(k>v&&(k=v),0===v)return i[s++]=20971520,i[s++]=20971520,a.bits=1,0;for(_=1;_<v&&0===I[_];_++);for(k<_&&(k=_),E=1,b=1;b<=pa;b++)if(E<<=1,(E-=I[b])<0)return-1;if(E>0&&(0===t||1!==v))return-1;for(D[1]=0,b=1;b<pa;b++)D[b+1]=D[b]+I[b];for(w=0;w<n;w++)0!==e[r+w]&&(o[D[e[r+w]]++]=w);if(0===t?(A=P=o,d=19):1===t?(A=ga,j-=257,P=ma,T-=257,d=256):(A=ya,P=ba,d=-1),x=0,w=0,b=_,f=s,S=k,O=0,l=-1,h=(R=1<<k)-1,1===t&&R>852||2===t&&R>592)return 1;for(;;){p=b-O,o[w]<d?(g=0,m=o[w]):o[w]>d?(g=P[T+o[w]],m=A[j+o[w]]):(g=96,m=0),c=1<<b-O,_=u=1<<S;do{i[f+(x>>O)+(u-=c)]=p<<24|g<<16|m}while(0!==u);for(c=1<<b-1;x&c;)c>>=1;if(0!==c?(x&=c-1,x+=c):x=0,w++,0===--I[b]){if(b===v)break;b=e[r+o[w]]}if(b>k&&(x&h)!==l){for(0===O&&(O=k),f+=_,E=1<<(S=b-O);S+O<v&&!((E-=I[S+O])<=0);)S++,E<<=1;if(R+=1<<S,1===t&&R>852||2===t&&R>592)return 1;i[l=x&h]=k<<24|S<<16|f-s}}return 0!==x&&(i[f+x]=b-O<<24|64<<16),a.bits=k,0}var _a=-2,va=12,ka=30;function Sa(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function Oa(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Qs(320),this.work=new Qs(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ea(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,function(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Xs(852),e.distcode=e.distdyn=new Xs(592),e.sane=1,e.back=-1,0):_a}(t)):_a}function Ra(t,e){var r,n;return t?(n=new Oa,t.state=n,n.window=null,r=function(t,e){var r,n;return t&&t.state?(n=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_a:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,Ea(t))):_a}(t,e),0!==r&&(t.state=null),r):_a}var xa,Aa,ja=!0;function Ia(t){if(ja){var e;for(xa=new Xs(512),Aa=new Xs(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(wa(1,t.lens,0,288,xa,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;wa(2,t.lens,0,32,Aa,0,t.work,{bits:5}),ja=!1}t.lencode=xa,t.lenbits=9,t.distcode=Aa,t.distbits=5}function Da(t,e){var r,n,i,s,o,a,c,u,l,h,f,d,p,g,m,y,b,w,_,v,k,S,O,E,R=0,x=new Ys(4),A=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return _a;(r=t.state).mode===va&&(r.mode=13),o=t.next_out,i=t.output,c=t.avail_out,s=t.next_in,n=t.input,a=t.avail_in,u=r.hold,l=r.bits,h=a,f=c,S=0;t:for(;;)switch(r.mode){case 1:if(0===r.wrap){r.mode=13;break}for(;l<16;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(2&r.wrap&&35615===u){r.check=0,x[0]=255&u,x[1]=u>>>8&255,r.check=qo(r.check,x,2,0),u=0,l=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){t.msg="incorrect header check",r.mode=ka;break}if(8!=(15&u)){t.msg="unknown compression method",r.mode=ka;break}if(l-=4,k=8+(15&(u>>>=4)),0===r.wbits)r.wbits=k;else if(k>r.wbits){t.msg="invalid window size",r.mode=ka;break}r.dmax=1<<k,t.adler=r.check=1,r.mode=512&u?10:va,u=0,l=0;break;case 2:for(;l<16;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(r.flags=u,8!=(255&r.flags)){t.msg="unknown compression method",r.mode=ka;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=ka;break}r.head&&(r.head.text=u>>8&1),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=qo(r.check,x,2,0)),u=0,l=0,r.mode=3;case 3:for(;l<32;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}r.head&&(r.head.time=u),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,x[2]=u>>>16&255,x[3]=u>>>24&255,r.check=qo(r.check,x,4,0)),u=0,l=0,r.mode=4;case 4:for(;l<16;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}r.head&&(r.head.xflags=255&u,r.head.os=u>>8),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=qo(r.check,x,2,0)),u=0,l=0,r.mode=5;case 5:if(1024&r.flags){for(;l<16;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}r.length=u,r.head&&(r.head.extra_len=u),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=qo(r.check,x,2,0)),u=0,l=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&((d=r.length)>a&&(d=a),d&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),Gs(r.head.extra,n,s,d,k)),512&r.flags&&(r.check=qo(r.check,n,d,s)),a-=d,s+=d,r.length-=d),r.length))break t;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===a)break t;d=0;do{k=n[s+d++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k))}while(k&&d<a);if(512&r.flags&&(r.check=qo(r.check,n,d,s)),a-=d,s+=d,k)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=8;case 8:if(4096&r.flags){if(0===a)break t;d=0;do{k=n[s+d++],r.head&&k&&r.length<65536&&(r.head.comment+=String.fromCharCode(k))}while(k&&d<a);if(512&r.flags&&(r.check=qo(r.check,n,d,s)),a-=d,s+=d,k)break t}else r.head&&(r.head.comment=null);r.mode=9;case 9:if(512&r.flags){for(;l<16;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(u!==(65535&r.check)){t.msg="header crc mismatch",r.mode=ka;break}u=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=va;break;case 10:for(;l<32;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}t.adler=r.check=Sa(u),u=0,l=0,r.mode=11;case 11:if(0===r.havedict)return t.next_out=o,t.avail_out=c,t.next_in=s,t.avail_in=a,r.hold=u,r.bits=l,2;t.adler=r.check=1,r.mode=va;case va:if(5===e||6===e)break t;case 13:if(r.last){u>>>=7&l,l-=7&l,r.mode=27;break}for(;l<3;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}switch(r.last=1&u,l-=1,3&(u>>>=1)){case 0:r.mode=14;break;case 1:if(Ia(r),r.mode=20,6===e){u>>>=2,l-=2;break t}break;case 2:r.mode=17;break;case 3:t.msg="invalid block type",r.mode=ka}u>>>=2,l-=2;break;case 14:for(u>>>=7&l,l-=7&l;l<32;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if((65535&u)!=(u>>>16^65535)){t.msg="invalid stored block lengths",r.mode=ka;break}if(r.length=65535&u,u=0,l=0,r.mode=15,6===e)break t;case 15:r.mode=16;case 16:if(d=r.length){if(d>a&&(d=a),d>c&&(d=c),0===d)break t;Gs(i,n,s,d,o),a-=d,s+=d,c-=d,o+=d,r.length-=d;break}r.mode=va;break;case 17:for(;l<14;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(r.nlen=257+(31&u),u>>>=5,l-=5,r.ndist=1+(31&u),u>>>=5,l-=5,r.ncode=4+(15&u),u>>>=4,l-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=ka;break}r.have=0,r.mode=18;case 18:for(;r.have<r.ncode;){for(;l<3;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}r.lens[A[r.have++]]=7&u,u>>>=3,l-=3}for(;r.have<19;)r.lens[A[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,O={bits:r.lenbits},S=wa(0,r.lens,0,19,r.lencode,0,r.work,O),r.lenbits=O.bits,S){t.msg="invalid code lengths set",r.mode=ka;break}r.have=0,r.mode=19;case 19:for(;r.have<r.nlen+r.ndist;){for(;y=(R=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,b=65535&R,!((m=R>>>24)<=l);){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(b<16)u>>>=m,l-=m,r.lens[r.have++]=b;else{if(16===b){for(E=m+2;l<E;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(u>>>=m,l-=m,0===r.have){t.msg="invalid bit length repeat",r.mode=ka;break}k=r.lens[r.have-1],d=3+(3&u),u>>>=2,l-=2}else if(17===b){for(E=m+3;l<E;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}l-=m,k=0,d=3+(7&(u>>>=m)),u>>>=3,l-=3}else{for(E=m+7;l<E;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}l-=m,k=0,d=11+(127&(u>>>=m)),u>>>=7,l-=7}if(r.have+d>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=ka;break}for(;d--;)r.lens[r.have++]=k}}if(r.mode===ka)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=ka;break}if(r.lenbits=9,O={bits:r.lenbits},S=wa(1,r.lens,0,r.nlen,r.lencode,0,r.work,O),r.lenbits=O.bits,S){t.msg="invalid literal/lengths set",r.mode=ka;break}if(r.distbits=6,r.distcode=r.distdyn,O={bits:r.distbits},S=wa(2,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,O),r.distbits=O.bits,S){t.msg="invalid distances set",r.mode=ka;break}if(r.mode=20,6===e)break t;case 20:r.mode=21;case 21:if(a>=6&&c>=258){t.next_out=o,t.avail_out=c,t.next_in=s,t.avail_in=a,r.hold=u,r.bits=l,da(t,f),o=t.next_out,i=t.output,c=t.avail_out,s=t.next_in,n=t.input,a=t.avail_in,u=r.hold,l=r.bits,r.mode===va&&(r.back=-1);break}for(r.back=0;y=(R=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,b=65535&R,!((m=R>>>24)<=l);){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(y&&!(240&y)){for(w=m,_=y,v=b;y=(R=r.lencode[v+((u&(1<<w+_)-1)>>w)])>>>16&255,b=65535&R,!(w+(m=R>>>24)<=l);){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}u>>>=w,l-=w,r.back+=w}if(u>>>=m,l-=m,r.back+=m,r.length=b,0===y){r.mode=26;break}if(32&y){r.back=-1,r.mode=va;break}if(64&y){t.msg="invalid literal/length code",r.mode=ka;break}r.extra=15&y,r.mode=22;case 22:if(r.extra){for(E=r.extra;l<E;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}r.length+=u&(1<<r.extra)-1,u>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;y=(R=r.distcode[u&(1<<r.distbits)-1])>>>16&255,b=65535&R,!((m=R>>>24)<=l);){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(!(240&y)){for(w=m,_=y,v=b;y=(R=r.distcode[v+((u&(1<<w+_)-1)>>w)])>>>16&255,b=65535&R,!(w+(m=R>>>24)<=l);){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}u>>>=w,l-=w,r.back+=w}if(u>>>=m,l-=m,r.back+=m,64&y){t.msg="invalid distance code",r.mode=ka;break}r.offset=b,r.extra=15&y,r.mode=24;case 24:if(r.extra){for(E=r.extra;l<E;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}r.offset+=u&(1<<r.extra)-1,u>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=ka;break}r.mode=25;case 25:if(0===c)break t;if(d=f-c,r.offset>d){if((d=r.offset-d)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=ka;break}d>r.wnext?(d-=r.wnext,p=r.wsize-d):p=r.wnext-d,d>r.length&&(d=r.length),g=r.window}else g=i,p=o-r.offset,d=r.length;d>c&&(d=c),c-=d,r.length-=d;do{i[o++]=g[p++]}while(--d);0===r.length&&(r.mode=21);break;case 26:if(0===c)break t;i[o++]=r.length,c--,r.mode=21;break;case 27:if(r.wrap){for(;l<32;){if(0===a)break t;a--,u|=n[s++]<<l,l+=8}if(f-=c,t.total_out+=f,r.total+=f,f&&(t.adler=r.check=r.flags?qo(r.check,i,f,o-f):Fo(r.check,i,f,o-f)),f=c,(r.flags?u:Sa(u))!==r.check){t.msg="incorrect data check",r.mode=ka;break}u=0,l=0}r.mode=28;case 28:if(r.wrap&&r.flags){for(;l<32;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(u!==(4294967295&r.total)){t.msg="incorrect length check",r.mode=ka;break}u=0,l=0}r.mode=29;case 29:S=1;break t;case ka:S=-3;break t;case 31:return-4;default:return _a}return t.next_out=o,t.avail_out=c,t.next_in=s,t.avail_in=a,r.hold=u,r.bits=l,(r.wsize||f!==t.avail_out&&r.mode<ka&&(r.mode<27||4!==e))&&function(t,e,r,n){var i,s=t.state;null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Ys(s.wsize)),n>=s.wsize?(Gs(s.window,e,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):((i=s.wsize-s.wnext)>n&&(i=n),Gs(s.window,e,r-n,i,s.wnext),(n-=i)?(Gs(s.window,e,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i)))}(t,t.output,t.next_out,f-t.avail_out),h-=t.avail_in,f-=t.avail_out,t.total_in+=h,t.total_out+=f,r.total+=f,r.wrap&&f&&(t.adler=r.check=r.flags?qo(r.check,i,f,t.next_out-f):Fo(r.check,i,f,t.next_out-f)),t.data_type=r.bits+(r.last?64:0)+(r.mode===va?128:0)+(20===r.mode||15===r.mode?256:0),(0===h&&0===f||4===e)&&0===S&&(S=-5),S}var Pa;function Ta(t){if(t<1||t>7)throw new TypeError("Bad argument");this.mode=t,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function Na(t,e){for(var r=0;r<t.length;r++)this[e+r]=t[r]}Ta.prototype.init=function(t,e,r,n,i){var s;switch(this.windowBits=t,this.level=e,this.memLevel=r,this.strategy=n,3!==this.mode&&4!==this.mode||(this.windowBits+=16),7===this.mode&&(this.windowBits+=32),5!==this.mode&&6!==this.mode||(this.windowBits=-this.windowBits),this.strm=new Js,this.mode){case 1:case 3:case 5:s=function(t,e,r,n,i,s){if(!t)return Ho;var o=1;if(-1===e&&(e=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),i<1||i>9||8!==r||n<8||n>15||e<0||e>9||s<0||s>4)return Yo(t,Ho);8===n&&(n=9);var a=new la;return t.state=a,a.strm=t,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=i+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Ys(2*a.w_size),a.head=new Qs(a.hash_size),a.prev=new Qs(a.w_size),a.lit_bufsize=1<<i+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Ys(a.pending_buf_size),a.d_buf=1*a.lit_bufsize,a.l_buf=3*a.lit_bufsize,a.level=e,a.strategy=s,a.method=r,ha(t)}(this.strm,this.level,8,this.windowBits,this.memLevel,this.strategy);break;case 2:case 4:case 6:case 7:s=Ra(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}0===s?(this.write_in_progress=!1,this.init_done=!0):this._error(s)},Ta.prototype.params=function(){throw new Error("deflateParams Not supported")},Ta.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(0===this.mode)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},Ta.prototype.write=function(t,e,r,n,i,s,o){this._writeCheck(),this.write_in_progress=!0;var a=this;return ri.nextTick(function(){a.write_in_progress=!1;var c=a._write(t,e,r,n,i,s,o);a.callback(c[0],c[1]),a.pending_close&&a.close()}),this},Ta.prototype.writeSync=function(t,e,r,n,i,s,o){return this._writeCheck(),this._write(t,e,r,n,i,s,o)},Ta.prototype._write=function(t,e,r,n,i,s,o){if(this.write_in_progress=!0,0!==t&&1!==t&&2!==t&&3!==t&&4!==t&&5!==t)throw new Error("Invalid flush value");null==e&&(e=new Kr(0),n=0,r=0),i._set?i.set=i._set:i.set=Na;var a,c=this.strm;switch(c.avail_in=n,c.input=e,c.next_in=r,c.avail_out=o,c.output=i,c.next_out=s,this.mode){case 1:case 3:case 5:a=fa(c,t);break;case 7:case 2:case 4:case 6:a=Da(c,t);break;default:throw new Error("Unknown mode "+this.mode)}return this._checkError(a,c,t)||this._error(a),this.write_in_progress=!1,[c.avail_in,c.avail_out]},Ta.prototype._checkError=function(t,e,r){switch(t){case 0:case-5:if(0!==e.avail_out&&4===r)return!1;break;case 1:break;default:return!1}return!0},Ta.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,1===this.mode||3===this.mode||5===this.mode?function(t){var e;t&&t.state&&(42!==(e=t.state.status)&&69!==e&&73!==e&&91!==e&&e!==Wo&&e!==Jo&&e!==Go?Yo(t,Ho):(t.state=null,e===Jo&&Yo(t,-3)))}(this.strm):function(t){if(!t||!t.state)return _a;var e=t.state;e.window&&(e.window=null),t.state=null}(this.strm),this.mode=0)},Ta.prototype.reset=function(){switch(this.mode){case 1:case 5:Pa=ha(this.strm);break;case 2:case 6:Pa=Ea(this.strm)}0!==Pa&&this._error(Pa)},Ta.prototype._error=function(t){this.onerror(Ws[t]+": "+this.strm.msg,t),this.write_in_progress=!1,this.pending_close&&this.close()};var Ca=Object.freeze({__proto__:null,DEFLATE:1,DEFLATERAW:5,GUNZIP:4,GZIP:3,INFLATE:2,INFLATERAW:6,NONE:0,UNZIP:7,Z_BEST_COMPRESSION:9,Z_BEST_SPEED:1,Z_BINARY:0,Z_BLOCK:5,Z_BUF_ERROR:-5,Z_DATA_ERROR:-3,Z_DEFAULT_COMPRESSION:-1,Z_DEFAULT_STRATEGY:0,Z_DEFLATED:8,Z_ERRNO:-1,Z_FILTERED:1,Z_FINISH:4,Z_FIXED:4,Z_FULL_FLUSH:3,Z_HUFFMAN_ONLY:2,Z_NEED_DICT:2,Z_NO_COMPRESSION:0,Z_NO_FLUSH:0,Z_OK:0,Z_PARTIAL_FLUSH:1,Z_RLE:3,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_SYNC_FLUSH:2,Z_TEXT:1,Z_TREES:6,Z_UNKNOWN:2,Zlib:Ta});var Ma={};Object.keys(Ca).forEach(function(t){Ma[t]=Ca[t]}),Ma.Z_MIN_WINDOWBITS=8,Ma.Z_MAX_WINDOWBITS=15,Ma.Z_DEFAULT_WINDOWBITS=15,Ma.Z_MIN_CHUNK=64,Ma.Z_MAX_CHUNK=1/0,Ma.Z_DEFAULT_CHUNK=16384,Ma.Z_MIN_MEMLEVEL=1,Ma.Z_MAX_MEMLEVEL=9,Ma.Z_DEFAULT_MEMLEVEL=8,Ma.Z_MIN_LEVEL=-1,Ma.Z_MAX_LEVEL=9,Ma.Z_DEFAULT_LEVEL=Ma.Z_DEFAULT_COMPRESSION;var La={Z_OK:Ma.Z_OK,Z_STREAM_END:Ma.Z_STREAM_END,Z_NEED_DICT:Ma.Z_NEED_DICT,Z_ERRNO:Ma.Z_ERRNO,Z_STREAM_ERROR:Ma.Z_STREAM_ERROR,Z_DATA_ERROR:Ma.Z_DATA_ERROR,Z_MEM_ERROR:Ma.Z_MEM_ERROR,Z_BUF_ERROR:Ma.Z_BUF_ERROR,Z_VERSION_ERROR:Ma.Z_VERSION_ERROR};function $a(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new Va(e),t,r)}function Ua(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new Ha(e),t,r)}function za(t,e,r){var n=[],i=0;function s(){for(var e;null!==(e=t.read());)n.push(e),i+=e.length;t.once("readable",s)}function o(){var e=Kr.concat(n,i);n=[],r(null,e),t.close()}t.on("error",function(e){t.removeListener("end",o),t.removeListener("readable",s),r(e)}),t.on("end",o),t.end(e),s()}function Fa(t,e){if("string"==typeof e&&(e=new Kr(e)),!Kr.isBuffer(e))throw new TypeError("Not a string or buffer");var r=Ma.Z_FINISH;return t._processChunk(e,r)}function Ba(t){if(!(this instanceof Ba))return new Ba(t);Ja.call(this,t,Ma.DEFLATE)}function qa(t){if(!(this instanceof qa))return new qa(t);Ja.call(this,t,Ma.INFLATE)}function Va(t){if(!(this instanceof Va))return new Va(t);Ja.call(this,t,Ma.GZIP)}function Ha(t){if(!(this instanceof Ha))return new Ha(t);Ja.call(this,t,Ma.GUNZIP)}function Ka(t){if(!(this instanceof Ka))return new Ka(t);Ja.call(this,t,Ma.DEFLATERAW)}function Za(t){if(!(this instanceof Za))return new Za(t);Ja.call(this,t,Ma.INFLATERAW)}function Wa(t){if(!(this instanceof Wa))return new Wa(t);Ja.call(this,t,Ma.UNZIP)}function Ja(t,e){if(this._opts=t=t||{},this._chunkSize=t.chunkSize||Ma.Z_DEFAULT_CHUNK,ps.call(this,t),t.flush&&t.flush!==Ma.Z_NO_FLUSH&&t.flush!==Ma.Z_PARTIAL_FLUSH&&t.flush!==Ma.Z_SYNC_FLUSH&&t.flush!==Ma.Z_FULL_FLUSH&&t.flush!==Ma.Z_FINISH&&t.flush!==Ma.Z_BLOCK)throw new Error("Invalid flush flag: "+t.flush);if(this._flushFlag=t.flush||Ma.Z_NO_FLUSH,t.chunkSize&&(t.chunkSize<Ma.Z_MIN_CHUNK||t.chunkSize>Ma.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+t.chunkSize);if(t.windowBits&&(t.windowBits<Ma.Z_MIN_WINDOWBITS||t.windowBits>Ma.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+t.windowBits);if(t.level&&(t.level<Ma.Z_MIN_LEVEL||t.level>Ma.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+t.level);if(t.memLevel&&(t.memLevel<Ma.Z_MIN_MEMLEVEL||t.memLevel>Ma.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+t.memLevel);if(t.strategy&&t.strategy!=Ma.Z_FILTERED&&t.strategy!=Ma.Z_HUFFMAN_ONLY&&t.strategy!=Ma.Z_RLE&&t.strategy!=Ma.Z_FIXED&&t.strategy!=Ma.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+t.strategy);if(t.dictionary&&!Kr.isBuffer(t.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new Ma.Zlib(e);var r=this;this._hadError=!1,this._binding.onerror=function(t,e){r._binding=null,r._hadError=!0;var n=new Error(t);n.errno=e,n.code=La[e],r.emit("error",n)};var n=Ma.Z_DEFAULT_COMPRESSION;"number"==typeof t.level&&(n=t.level);var i=Ma.Z_DEFAULT_STRATEGY;"number"==typeof t.strategy&&(i=t.strategy),this._binding.init(t.windowBits||Ma.Z_DEFAULT_WINDOWBITS,n,t.memLevel||Ma.Z_DEFAULT_MEMLEVEL,i,t.dictionary),this._buffer=new Kr(this._chunkSize),this._offset=0,this._closed=!1,this._level=n,this._strategy=i,this.once("end",this.close)}Object.keys(La).forEach(function(t){La[La[t]]=t}),ei(Ja,ps),Ja.prototype.params=function(t,e,r){if(t<Ma.Z_MIN_LEVEL||t>Ma.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(e!=Ma.Z_FILTERED&&e!=Ma.Z_HUFFMAN_ONLY&&e!=Ma.Z_RLE&&e!=Ma.Z_FIXED&&e!=Ma.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+e);if(this._level!==t||this._strategy!==e){var n=this;this.flush(Ma.Z_SYNC_FLUSH,function(){n._binding.params(t,e),n._hadError||(n._level=t,n._strategy=e,r&&r())})}else ri.nextTick(r)},Ja.prototype.reset=function(){return this._binding.reset()},Ja.prototype._flush=function(t){this._transform(new Kr(0),"",t)},Ja.prototype.flush=function(t,e){var r=this._writableState;if(("function"==typeof t||void 0===t&&!e)&&(e=t,t=Ma.Z_FULL_FLUSH),r.ended)e&&ri.nextTick(e);else if(r.ending)e&&this.once("end",e);else if(r.needDrain){var n=this;this.once("drain",function(){n.flush(e)})}else this._flushFlag=t,this.write(new Kr(0),"",e)},Ja.prototype.close=function(t){if(t&&ri.nextTick(t),!this._closed){this._closed=!0,this._binding.close();var e=this;ri.nextTick(function(){e.emit("close")})}},Ja.prototype._transform=function(t,e,r){var n,i=this._writableState,s=(i.ending||i.ended)&&(!t||i.length===t.length);if(null===!t&&!Kr.isBuffer(t))return r(new Error("invalid input"));s?n=Ma.Z_FINISH:(n=this._flushFlag,t.length>=i.length&&(this._flushFlag=this._opts.flush||Ma.Z_NO_FLUSH)),this._processChunk(t,n,r)},Ja.prototype._processChunk=function(t,e,r){var n=t&&t.length,i=this._chunkSize-this._offset,s=0,o=this,a="function"==typeof r;if(!a){var c,u=[],l=0;this.on("error",function(t){c=t});do{var h=this._binding.writeSync(e,t,s,n,this._buffer,this._offset,i)}while(!this._hadError&&p(h[0],h[1]));if(this._hadError)throw c;var f=Kr.concat(u,l);return this.close(),f}var d=this._binding.write(e,t,s,n,this._buffer,this._offset,i);function p(c,h){if(!o._hadError){var f=i-h;if(function(t,e){if(!t)throw new Error(e)}(f>=0,"have should not go down"),f>0){var d=o._buffer.slice(o._offset,o._offset+f);o._offset+=f,a?o.push(d):(u.push(d),l+=d.length)}if((0===h||o._offset>=o._chunkSize)&&(i=o._chunkSize,o._offset=0,o._buffer=new Kr(o._chunkSize)),0===h){if(s+=n-c,n=c,!a)return!0;var g=o._binding.write(e,t,s,n,o._buffer,o._offset,o._chunkSize);return g.callback=p,void(g.buffer=t)}if(!a)return!1;r()}}d.buffer=t,d.callback=p},ei(Ba,Ja),ei(qa,Ja),ei(Va,Ja),ei(Ha,Ja),ei(Ka,Ja),ei(Za,Ja),ei(Wa,Ja);var Ga={codes:La,createDeflate:function(t){return new Ba(t)},createInflate:function(t){return new qa(t)},createDeflateRaw:function(t){return new Ka(t)},createInflateRaw:function(t){return new Za(t)},createGzip:function(t){return new Va(t)},createGunzip:function(t){return new Ha(t)},createUnzip:function(t){return new Wa(t)},deflate:function(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new Ba(e),t,r)},deflateSync:function(t,e){return Fa(new Ba(e),t)},gzip:$a,gzipSync:function(t,e){return Fa(new Va(e),t)},deflateRaw:function(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new Ka(e),t,r)},deflateRawSync:function(t,e){return Fa(new Ka(e),t)},unzip:function(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new Wa(e),t,r)},unzipSync:function(t,e){return Fa(new Wa(e),t)},inflate:function(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new qa(e),t,r)},inflateSync:function(t,e){return Fa(new qa(e),t)},gunzip:Ua,gunzipSync:function(t,e){return Fa(new Ha(e),t)},inflateRaw:function(t,e,r){return"function"==typeof e&&(r=e,e={}),za(new Za(e),t,r)},inflateRawSync:function(t,e){return Fa(new Za(e),t)},Deflate:Ba,Inflate:qa,Gzip:Va,Gunzip:Ha,DeflateRaw:Ka,InflateRaw:Za,Unzip:Wa,Zlib:Ja};class Ya extends Ks{constructor({client:t,keyPrefix:e="cache",ttl:r=0,prefix:n}){super({client:t,keyPrefix:e,ttl:r,prefix:n}),this.client=t,this.keyPrefix=e,this.config.ttl=r,this.config.client=t,this.config.prefix=void 0!==n?n:e+(e.endsWith("/")?"":"/")}async _set(t,e){let r=JSON.stringify(e);const n=r.length;return r=Ga.gzipSync(r).toString("base64"),this.client.putObject({key:g(this.keyPrefix,t),body:r,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(n),"length-compressed":String(r.length),"compression-gain":(r.length/n).toFixed(2)}})}async _get(t){try{const{Body:e}=await this.client.getObject(g(this.keyPrefix,t));let r=await ks(e);return r=Buffer.from(r,"base64"),r=Ga.unzipSync(r).toString(),JSON.parse(r)}catch(t){if("NoSuchKey"===t.name||"NotFound"===t.name)return null;throw t}}async _del(t){return await this.client.deleteObject(g(this.keyPrefix,t)),!0}async _clear(){const t=await this.client.getAllKeys({prefix:this.keyPrefix});for(const e of t)await this.client.deleteObject(e)}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)}}class Qa extends S{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 n=this.hooks.get(t);n.has(e)||n.set(e,[]),n.get(e).push(r)}removeHook(t,e,r){const n=this.hooks.get(t);if(n&&n.has(e)){const t=n.get(e),i=t.indexOf(r);i>-1&&t.splice(i,1)}}wrapResourceMethod(t,e,r){const n=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}`]=n;const r=n&&n._isMockFunction;t[e]=async function(...r){let n=await t[`_wrapped_${e}`](...r);for(const i of t._pluginWrappers.get(e))n=await i.call(this,n,r,e);return n},r&&(Object.setPrototypeOf(t[e],Object.getPrototypeOf(n)),Object.assign(t[e],n))}}getPartitionValues(t,e){if(!e.config?.partitions)return{};const r={};for(const[n,i]of Object.entries(e.config.partitions))if(i.fields){r[n]={};for(const[s,o]of Object.entries(i.fields)){const i=this.getNestedFieldValue(t,s);null!=i&&(r[n][s]=e.applyPartitionRule(i,o))}}else r[n]={};return r}getNestedFieldValue(t,e){if(!e.includes("."))return t[e]??null;const r=e.split(".");let n=t;for(const t of r){if(!n||"object"!=typeof n||!(t in n))return null;n=n[t]}return n??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 Xa={setup(t){},start(){},stop(){}};const tc={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 ec extends S{constructor(t={}){super(),this.config=t,this.name=this.constructor.name,this.enabled=!1!==t.enabled}async initialize(t){this.database=t,this.emit("initialized",{replicator:this.name})}async replicate(t,e,r,n){throw new Error(`replicate() method must be implemented by ${this.name}`)}async replicateBatch(t,e){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,enabled:this.enabled,config:this.config,connected:!1}}async cleanup(){this.emit("cleanup",{replicator:this.name})}validateConfig(){return{isValid:!0,errors:[]}}}const rc={s3db:class extends ec{constructor(t={},e=[]){super(t),this.resources=e,this.connectionString=t.connectionString,this.region=t.region,this.bucket=t.bucket,this.keyPrefix=t.keyPrefix}validateConfig(){const t=[];return this.connectionString||this.bucket||t.push("Either connectionString or bucket must be provided"),{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const e={connectionString:this.connectionString,region:this.region,bucket:this.bucket,keyPrefix:this.keyPrefix,verbose:this.config.verbose||!1};this.targetDatabase=new Hs(e),await this.targetDatabase.connect(),this.emit("connected",{replicator:this.name,target:this.connectionString||this.bucket})}async replicate(t,e,r,n){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};try{let i;switch(e){case"insert":i=await(this.targetDatabase.resources[t]?.insert(r));break;case"update":i=await(this.targetDatabase.resources[t]?.update(n,r));break;case"delete":i=await(this.targetDatabase.resources[t]?.delete(n));break;default:throw new Error(`Unsupported operation: ${e}`)}return this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:n,success:!0}),{success:!0,result:i}}catch(r){return this.emit("replication_error",{replicator:this.name,resourceName:t,operation:e,id:n,error:r.message}),{success:!1,error:r.message}}}async replicateBatch(t,e){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};try{const r=[],n=[];for(const i of e)try{const e=await this.replicate(t,i.operation,i.data,i.id);r.push(e)}catch(t){n.push({id:i.id,error:t.message})}return this.emit("batch_replicated",{replicator:this.name,resourceName:t,total:e.length,successful:r.filter(t=>t.success).length,errors:n.length}),{success:0===n.length,results:r,errors:n,total:e.length}}catch(e){return this.emit("batch_replication_error",{replicator:this.name,resourceName:t,error:e.message}),{success:!1,error:e.message}}}async testConnection(){try{return this.targetDatabase||await this.initialize(this.database),await this.targetDatabase.listResources(),!0}catch(t){return this.emit("connection_error",{replicator:this.name,error:t.message}),!1}}async getStatus(){return{...await super.getStatus(),connected:!!this.targetDatabase,targetDatabase:this.connectionString||this.bucket,resources:this.resources,totalReplications:this.listenerCount("replicated"),totalErrors:this.listenerCount("replication_error")}}async cleanup(){this.targetDatabase&&this.targetDatabase.removeAllListeners(),await super.cleanup()}shouldReplicateResource(t){return 0===this.resources.length||this.resources.includes(t)}},sqs:class extends ec{constructor(t={},e=[]){super(t),this.resources=e,this.queueUrl=t.queueUrl,this.queues=t.queues||{},this.defaultQueueUrl=t.defaultQueueUrl,this.region=t.region||"us-east-1",this.sqsClient=null,this.messageGroupId=t.messageGroupId,this.deduplicationId=t.deduplicationId}validateConfig(){const t=[];return this.queueUrl||0!==Object.keys(this.queues).length||this.defaultQueueUrl||t.push("Either queueUrl, queues object, or defaultQueueUrl must be provided"),{isValid:0===t.length,errors:t}}getQueueUrlForResource(t){if(this.queues[t])return this.queues[t];if(this.queueUrl)return this.queueUrl;if(this.defaultQueueUrl)return this.defaultQueueUrl;throw new Error(`No queue URL found for resource '${t}'`)}createMessage(t,e,r,n,i=null){const s={resource:t,action:e,timestamp:(new Date).toISOString(),source:"s3db-replication"};switch(e){case"insert":case"delete":default:return{...s,data:r};case"update":return{...s,before:i,data:r}}}async initialize(t){await super.initialize(t);try{const{SQSClient:t,SendMessageCommand:e,SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs");this.sqsClient=new t({region:this.region,credentials:this.config.credentials}),this.emit("initialized",{replicator:this.name,queueUrl:this.queueUrl,queues:this.queues,defaultQueueUrl:this.defaultQueueUrl})}catch(t){throw this.emit("initialization_error",{replicator:this.name,error:t.message}),t}}async replicate(t,e,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};try{const{SendMessageCommand:s}=await import("@aws-sdk/client-sqs"),o=this.getQueueUrlForResource(t),a=this.createMessage(t,e,r,n,i),c=new s({QueueUrl:o,MessageBody:JSON.stringify(a),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${t}:${e}:${n}`:void 0}),u=await this.sqsClient.send(c);return this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:n,queueUrl:o,messageId:u.MessageId,success:!0}),{success:!0,messageId:u.MessageId,queueUrl:o}}catch(r){return this.emit("replication_error",{replicator:this.name,resourceName:t,operation:e,id:n,error:r.message}),{success:!1,error:r.message}}}async replicateBatch(t,e){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};try{const{SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs"),n=this.getQueueUrlForResource(t),i=10,s=[];for(let t=0;t<e.length;t+=i)s.push(e.slice(t,t+i));const o=[],a=[];for(const e of s)try{const i=new r({QueueUrl:n,Entries:e.map((e,r)=>({Id:`${e.id}-${r}`,MessageBody:JSON.stringify(this.createMessage(t,e.operation,e.data,e.id,e.beforeData)),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${t}:${e.operation}:${e.id}`:void 0}))}),s=await this.sqsClient.send(i);o.push(s)}catch(t){a.push({batch:e.length,error:t.message})}return this.emit("batch_replicated",{replicator:this.name,resourceName:t,queueUrl:n,total:e.length,successful:o.length,errors:a.length}),{success:0===a.length,results:o,errors:a,total:e.length,queueUrl:n}}catch(e){return this.emit("batch_replication_error",{replicator:this.name,resourceName:t,error:e.message}),{success:!1,error:e.message}}}async testConnection(){try{this.sqsClient||await this.initialize(this.database);const{GetQueueAttributesCommand:t}=await import("@aws-sdk/client-sqs"),e=new t({QueueUrl:this.queueUrl,AttributeNames:["QueueArn"]});return await this.sqsClient.send(e),!0}catch(t){return 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,totalReplications:this.listenerCount("replicated"),totalErrors:this.listenerCount("replication_error")}}async cleanup(){this.sqsClient&&this.sqsClient.destroy(),await super.cleanup()}shouldReplicateResource(t){return 0===this.resources.length||this.resources.includes(t)}},bigquery:class extends ec{constructor(t={},e={}){super(t),this.projectId=t.projectId,this.datasetId=t.datasetId,this.bigqueryClient=null,this.credentials=t.credentials,this.location=t.location||"US",this.logTable=t.logTable,this.resources=this.parseResourcesConfig(e)}parseResourcesConfig(t){const e={};for(const[r,n]of Object.entries(t))"string"==typeof n?e[r]=[{table:n,actions:["insert"]}]:Array.isArray(n)?e[r]=n.map(t=>"string"==typeof t?{table:t,actions:["insert"]}:{table:t.table,actions:t.actions||["insert"]}):"object"==typeof n&&(e[r]=[{table:n.table,actions:n.actions||["insert"]}]);return e}validateConfig(){const t=[];this.projectId||t.push("projectId is required"),this.datasetId||t.push("datasetId is required"),0===Object.keys(this.resources).length&&t.push("At least one resource must be configured");for(const[e,r]of Object.entries(this.resources))for(const n of r){n.table||t.push(`Table name is required for resource '${e}'`),Array.isArray(n.actions)&&0!==n.actions.length||t.push(`Actions array is required for resource '${e}'`);const r=["insert","update","delete"],i=n.actions.filter(t=>!r.includes(t));i.length>0&&t.push(`Invalid actions for resource '${e}': ${i.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);try{const{BigQuery:t}=await import("@google-cloud/bigquery");this.bigqueryClient=new t({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)})}catch(t){throw this.emit("initialization_error",{replicator:this.name,error:t.message}),t}}shouldReplicateResource(t){return this.resources.hasOwnProperty(t)}shouldReplicateAction(t,e){return!!this.resources[t]&&this.resources[t].some(t=>t.actions.includes(e))}getTablesForResource(t,e){return this.resources[t]?this.resources[t].filter(t=>t.actions.includes(e)).map(t=>t.table):[]}async replicate(t,e,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(t,e))return{skipped:!0,reason:"action_not_included"};const s=this.getTablesForResource(t,e);if(0===s.length)return{skipped:!0,reason:"no_tables_for_action"};const o=[],a=[];try{const i=this.bigqueryClient.dataset(this.datasetId);for(const t of s)try{const s=i.table(t);let a;if("insert"===e){const t={...r};a=await s.insert([t])}else if("update"===e){const e=Object.keys(r).filter(t=>"id"!==t),i=e.map(t=>`${t}=@${t}`).join(", "),s={id:n};e.forEach(t=>{s[t]=r[t]});const o=`UPDATE \`${this.projectId}.${this.datasetId}.${t}\` SET ${i} WHERE id=@id`,[c]=await this.bigqueryClient.createQueryJob({query:o,params:s});await c.getQueryResults(),a=[c]}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const e=`DELETE FROM \`${this.projectId}.${this.datasetId}.${t}\` WHERE id=@id`,[r]=await this.bigqueryClient.createQueryJob({query:e,params:{id:n}});await r.getQueryResults(),a=[r]}}o.push({table:t,success:!0,jobId:a[0]?.id})}catch(e){a.push({table:t,error:e.message})}if(this.logTable)try{const s=i.table(this.logTable);await s.insert([{resource_name:t,operation:e,record_id:n,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replication"}])}catch(t){console.warn(`Failed to log operation to ${this.logTable}:`,t.message)}const c=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:n,tables:s,results:o,errors:a,success:c}),{success:c,results:o,errors:a,tables:s}}catch(r){return this.emit("replication_error",{replicator:this.name,resourceName:t,operation:e,id:n,error:r.message}),{success:!1,error:r.message}}}async replicateBatch(t,e){const r=[],n=[];for(const i of e)try{const e=await this.replicate(t,i.operation,i.data,i.id,i.beforeData);r.push(e)}catch(t){n.push({id:i.id,error:t.message})}return{success:0===n.length,results:r,errors:n}}async testConnection(){try{this.bigqueryClient||await this.initialize();const t=this.bigqueryClient.dataset(this.datasetId);return await t.getMetadata(),!0}catch(t){return 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}}},postgres:class extends ec{constructor(t={},e={}){super(t),this.connectionString=t.connectionString,this.host=t.host,this.port=t.port||5432,this.database=t.database,this.user=t.user,this.password=t.password,this.client=null,this.ssl=t.ssl,this.logTable=t.logTable,this.resources=this.parseResourcesConfig(e)}parseResourcesConfig(t){const e={};for(const[r,n]of Object.entries(t))"string"==typeof n?e[r]=[{table:n,actions:["insert"]}]:Array.isArray(n)?e[r]=n.map(t=>"string"==typeof t?{table:t,actions:["insert"]}:{table:t.table,actions:t.actions||["insert"]}):"object"==typeof n&&(e[r]=[{table:n.table,actions:n.actions||["insert"]}]);return e}validateConfig(){const t=[];this.connectionString||this.host&&this.database||t.push("Either connectionString or host+database must be provided"),0===Object.keys(this.resources).length&&t.push("At least one resource must be configured");for(const[e,r]of Object.entries(this.resources))for(const n of r){n.table||t.push(`Table name is required for resource '${e}'`),Array.isArray(n.actions)&&0!==n.actions.length||t.push(`Actions array is required for resource '${e}'`);const r=["insert","update","delete"],i=n.actions.filter(t=>!r.includes(t));i.length>0&&t.push(`Invalid actions for resource '${e}': ${i.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);try{const{Client:t}=await import("pg"),e=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 t(e),await this.client.connect(),this.logTable&&await this.createLogTableIfNotExists(),this.emit("initialized",{replicator:this.name,database:this.database||"postgres",resources:Object.keys(this.resources)})}catch(t){throw this.emit("initialization_error",{replicator:this.name,error:t.message}),t}}async createLogTableIfNotExists(){const t=`\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-replication',\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(t)}shouldReplicateResource(t){return this.resources.hasOwnProperty(t)}shouldReplicateAction(t,e){return!!this.resources[t]&&this.resources[t].some(t=>t.actions.includes(e))}getTablesForResource(t,e){return this.resources[t]?this.resources[t].filter(t=>t.actions.includes(e)).map(t=>t.table):[]}async replicate(t,e,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(t,e))return{skipped:!0,reason:"action_not_included"};const s=this.getTablesForResource(t,e);if(0===s.length)return{skipped:!0,reason:"no_tables_for_action"};const o=[],a=[];try{for(const t of s)try{let i;if("insert"===e){const e=Object.keys(r),n=e.map(t=>r[t]),s=e.map(t=>`"${t}"`).join(", "),o=`INSERT INTO ${t} (${s}) VALUES (${e.map((t,e)=>`$${e+1}`).join(", ")}) ON CONFLICT (id) DO NOTHING RETURNING *`;i=await this.client.query(o,n)}else if("update"===e){const e=Object.keys(r).filter(t=>"id"!==t),s=e.map((t,e)=>`"${t}"=$${e+1}`).join(", "),o=e.map(t=>r[t]);o.push(n);const a=`UPDATE ${t} SET ${s} WHERE id=$${e.length+1} RETURNING *`;i=await this.client.query(a,o)}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const e=`DELETE FROM ${t} WHERE id=$1 RETURNING *`;i=await this.client.query(e,[n])}}o.push({table:t,success:!0,rows:i.rows,rowCount:i.rowCount})}catch(e){a.push({table:t,error:e.message})}if(this.logTable)try{await this.client.query(`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,[t,e,n,JSON.stringify(r),(new Date).toISOString(),"s3db-replication"])}catch(t){console.warn(`Failed to log operation to ${this.logTable}:`,t.message)}const i=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:n,tables:s,results:o,errors:a,success:i}),{success:i,results:o,errors:a,tables:s}}catch(r){return this.emit("replication_error",{replicator:this.name,resourceName:t,operation:e,id:n,error:r.message}),{success:!1,error:r.message}}}async replicateBatch(t,e){const r=[],n=[];for(const i of e)try{const e=await this.replicate(t,i.operation,i.data,i.id,i.beforeData);r.push(e)}catch(t){n.push({id:i.id,error:t.message})}return{success:0===n.length,results:r,errors:n}}async testConnection(){try{return this.client||await this.initialize(),await this.client.query("SELECT 1"),!0}catch(t){return 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}}}};function nc(t,e={},r=[]){const n=rc[t];if(!n)throw new Error(`Unknown replicator driver: ${t}. Available drivers: ${Object.keys(rc).join(", ")}`);return new n(e,r)}function ic(t,e,r=[]){return nc(t,e,r).validateConfig()}const sc=xi($a),oc=xi(Ua);return t.AVAILABLE_BEHAVIORS=zs,t.AuditPlugin=class extends Qa{constructor(t={}){super(t),this.auditResource=null,this.config={enabled:!1!==t.enabled,includeData:!1!==t.includeData,includePartitions:!1!==t.includePartitions,maxDataSize:t.maxDataSize||1e4,...t}}async onSetup(){if(this.config.enabled){try{this.auditResource=await 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"}})}catch(t){try{this.auditResource=this.database.resources.audits}catch(t){return void(this.auditResource=null)}}this.installDatabaseProxy(),this.installResourceHooks()}else this.auditResource=null}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const t=this.installResourceHooksForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResource(...e);return"audit_logs"!==r.name&&t(r),r},this.database._auditProxyInstalled=!0}installResourceHooks(){for(const t of Object.values(this.database.resources))"audits"!==t.name&&this.installResourceHooksForResource(t)}installResourceHooksForResource(t){this.wrapResourceMethod(t,"insert",async(e,r,n)=>{const[i]=r,s=i.id||e.id||"auto-generated",o=this.config.includePartitions?this.getPartitionValues(i,t):null,a={id:`audit-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.name,operation:"insert",recordId:s,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(i)),partition:this.config.includePartitions?this.getPrimaryPartition(o):null,partitionValues:this.config.includePartitions&&o&&Object.keys(o).length>0?JSON.stringify(o):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};return this.logAudit(a).catch(console.error),e}),this.wrapResourceMethod(t,"update",async(e,r,n)=>{const[i,s]=r;let o=null;if(this.config.includeData)try{o=await t.get(i)}catch(t){}const a=this.config.includePartitions?this.getPartitionValues(e,t):null,c={id:`audit-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.name,operation:"update",recordId:i,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:o&&!1===this.config.includeData?null:o?JSON.stringify(this.truncateData(o)):null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(a):null,partitionValues:this.config.includePartitions&&a&&Object.keys(a).length>0?JSON.stringify(a):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};return this.logAudit(c).catch(console.error),e}),this.wrapResourceMethod(t,"delete",async(e,r,n)=>{const[i]=r;let s=null;if(this.config.includeData)try{s=await t.get(i)}catch(t){}const o=s&&this.config.includePartitions?this.getPartitionValues(s,t):null,a={id:`audit-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.name,operation:"delete",recordId:i,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:s&&!1===this.config.includeData?null:s?JSON.stringify(this.truncateData(s)):null,newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(o):null,partitionValues:this.config.includePartitions&&o&&Object.keys(o).length>0?JSON.stringify(o):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};return this.logAudit(a).catch(console.error),e}),this.wrapResourceMethod(t,"deleteMany",async(e,r,n)=>{const[i]=r,s=[];if(this.config.includeData)for(const e of i)try{const r=await t.get(e),n=this.config.includePartitions?this.getPartitionValues(r,t):null;s.push({id:`audit-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,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(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",batchOperation:!0})})}catch(t){}for(const t of s)this.logAudit(t).catch(console.error);return e})}getPartitionValues(t,e){const r=e.config?.partitions||{},n={};for(const[e,i]of Object.entries(r))if(i.fields){const r={};for(const[e,n]of Object.entries(i.fields)){const n=this.getNestedFieldValue(t,e);null!=n&&(r[e]=n)}Object.keys(r).length>0&&(n[e]=r)}return n}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let n=t;for(const t of r){if(!n||"object"!=typeof n||!(t in n))return;n=n[t]}return n}getPrimaryPartition(t){if(!t)return null;const e=Object.keys(t);return e.length>0?e[0]:null}async logAudit(t){if(this.auditResource)try{await this.auditResource.insert(t)}catch(t){console.error("Failed to log audit record:",t),t&&t.stack&&console.error(t.stack)}}truncateData(t){if(!t)return t;const e=JSON.stringify(t);return e.length<=this.config.maxDataSize?t:{...t,_truncated:!0,_originalSize:e.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(t={}){if(!this.auditResource)return[];try{const{resourceName:e,operation:r,recordId:n,userId:i,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)&&((!n||t.recordId===n)&&((!i||t.userId===i)&&((!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=>({...t,oldData:t.oldData?JSON.parse(t.oldData):null,newData:t.newData?JSON.parse(t.newData):null,partitionValues:t.partitionValues?JSON.parse(t.partitionValues):null,metadata:t.metadata?JSON.parse(t.metadata):null}))}catch(t){return console.error("Failed to get audit logs:",t),t&&t.stack&&console.error(t.stack),[]}}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:n}=t,i=await this.getAuditLogs({resourceName:e,startDate:r,endDate:n,limit:1e4}),s={total:i.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const t of i){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;const e=t.timestamp.split("T")[0];s.timeline[e]=(s.timeline[e]||0)+1}return s}},t.AuthenticationError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},t.BaseError=j,t.Cache=Ks,t.CachePlugin=class extends Qa{constructor(t={}){super(t),this.driver=t.driver,this.config={enabled:!1!==t.enabled,includePartitions:!1!==t.includePartitions,...t}}async setup(t){this.config.enabled&&await super.setup(t)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new Zs(this.config.memoryOptions||{}):this.driver=new Ya(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){this.driver&&(t.cache=this.driver,t.cacheKeyFor=async(e={})=>{const{action:r,params:n={},partition:i,partitionValues:s}=e;return this.generateCacheKey(t,r,n,i,s)},t._originalCount=t.count,t._originalListIds=t.listIds,t._originalGetMany=t.getMany,t._originalGetAll=t.getAll,t._originalPage=t.page,t._originalList=t.list,t.count=async function(e={}){const{partition:r,partitionValues:n}=e,i=await t.cacheKeyFor({action:"count",partition:r,partitionValues:n});try{const e=await t.cache.get(i);if(null!=e)return e}catch(t){if("NoSuchKey"!==t.name)throw t}const s=await t._originalCount(e);return await t.cache.set(i,s),s},t.listIds=async function(e={}){const{partition:r,partitionValues:n}=e,i=await t.cacheKeyFor({action:"listIds",partition:r,partitionValues:n});try{const e=await t.cache.get(i);if(null!=e)return e}catch(t){if("NoSuchKey"!==t.name)throw t}const s=await t._originalListIds(e);return await t.cache.set(i,s),s},t.getMany=async function(e){const r=await t.cacheKeyFor({action:"getMany",params:{ids:e}});try{const e=await t.cache.get(r);if(null!=e)return e}catch(t){if("NoSuchKey"!==t.name)throw t}const n=await t._originalGetMany(e);return await t.cache.set(r,n),n},t.getAll=async function(){const e=await t.cacheKeyFor({action:"getAll"});try{const r=await t.cache.get(e);if(null!=r)return r}catch(t){if("NoSuchKey"!==t.name)throw t}const r=await t._originalGetAll();return await t.cache.set(e,r),r},t.page=async function({offset:e,size:r,partition:n,partitionValues:i}={}){const s=await t.cacheKeyFor({action:"page",params:{offset:e,size:r},partition:n,partitionValues:i});try{const e=await t.cache.get(s);if(null!=e)return e}catch(t){if("NoSuchKey"!==t.name)throw t}const o=await t._originalPage({offset:e,size:r,partition:n,partitionValues:i});return await t.cache.set(s,o),o},t.list=async function(e={}){const{partition:r,partitionValues:n}=e,i=await t.cacheKeyFor({action:"list",partition:r,partitionValues:n});try{const e=await t.cache.get(i);if(null!=e)return e}catch(t){if("NoSuchKey"!==t.name)throw t}const s=await t._originalList(e);return await t.cache.set(i,s),s},this.wrapResourceMethod(t,"insert",async(e,r,n)=>{const[i]=r;return await this.clearCacheForResource(t,i),e}),this.wrapResourceMethod(t,"update",async(e,r,n)=>{const[i,s]=r;return await this.clearCacheForResource(t,{id:i,...s}),e}),this.wrapResourceMethod(t,"delete",async(e,r,n)=>{const[i]=r;let s={id:i};if("function"==typeof t.get)try{const e=await t.get(i);e&&(s=e)}catch{}return await this.clearCacheForResource(t,s),e}),this.wrapResourceMethod(t,"deleteMany",async(e,r,n)=>{const[i]=r;for(const e of i){let r={id:e};if("function"==typeof t.get)try{const n=await t.get(e);n&&(r=n)}catch{}await this.clearCacheForResource(t,r)}return e}))}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){const n=this.getPartitionValues(e,t);for(const[e,i]of Object.entries(n))if(i&&Object.keys(i).length>0&&Object.values(i).some(t=>null!=t)){const n=g(r,`partition=${e}`);await t.cache.clear(n)}}}async generateCacheKey(t,e,r={},n=null,i=null){const s=[`resource=${t.name}`,`action=${e}`];if(n&&i&&Object.keys(i).length>0){s.push(`partition:${n}`);for(const[t,e]of Object.entries(i))null!=e&&s.push(`${t}:${e}`)}if(Object.keys(r).length>0){const t=await this.hashParams(r);s.push(t)}return g(...s)+".json.gz"}async hashParams(t){const e=Object.keys(t).sort().map(e=>`${e}:${t[e]}`).join("|")||"empty";return await q(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:n=!0}=e;if(await r.getAll(),n&&r.config.partitions)for(const[t,e]of Object.entries(r.config.partitions))if(e.fields){const e=await r.getAll(),n=Array.isArray(e)?e:[],i=new Set;for(const e of n.slice(0,10)){const n=this.getPartitionValues(e,r);n[t]&&i.add(JSON.stringify(n[t]))}for(const e of i){const n=JSON.parse(e);await r.list({partition:t,partitionValues:n})}}}},t.Client=F,t.ConnectionString=z,t.CostsPlugin=tc,t.DEFAULT_BEHAVIOR=Fs,t.Database=Vs,t.DatabaseError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},t.EncryptionError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},t.ErrorMap=L,t.FullTextPlugin=class extends Qa{constructor(t={}){super(),this.indexResource=null,this.config={enabled:!1!==t.enabled,minWordLength:t.minWordLength||3,maxResults:t.maxResults||100,...t},this.indexes=new Map}async setup(t){if(this.database=t,this.config.enabled){try{this.indexResource=await 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"}})}catch(e){this.indexResource=t.resources.fulltext_indexes}await this.loadIndexes(),this.installIndexingHooks()}}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(this.indexResource)try{const t=await this.indexResource.getAll();for(const e of t){const t=`${e.resourceName}:${e.fieldName}:${e.word}`;this.indexes.set(t,{recordIds:e.recordIds||[],count:e.count||0})}}catch(t){console.warn("Failed to load existing indexes:",t.message)}}async saveIndexes(){if(this.indexResource)try{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,n,i]=t.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:n,word:i,recordIds:e.recordIds,count:e.count,lastUpdated:(new Date).toISOString()})}}catch(t){console.error("Failed to save indexes:",t)}}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,n)=>{const[i]=r;return this.indexRecord(t.name,e.id,i).catch(console.error),e}),this.wrapResourceMethod(t,"update",async(e,r,n)=>{const[i,s]=r;return this.removeRecordFromIndex(t.name,i).catch(console.error),this.indexRecord(t.name,i,e).catch(console.error),e}),this.wrapResourceMethod(t,"delete",async(e,r,n)=>{const[i]=r;return this.removeRecordFromIndex(t.name,i).catch(console.error),e}),this.wrapResourceMethod(t,"deleteMany",async(e,r,n)=>{const[i]=r;for(const e of i)this.removeRecordFromIndex(t.name,e).catch(console.error);return e})}async indexRecord(t,e,r){const n=this.getIndexedFields(t);if(n&&0!==n.length)for(const i of n){const n=this.getFieldValue(r,i);if(!n)continue;const s=this.tokenize(n);for(const r of s){if(r.length<this.config.minWordLength)continue;const n=`${t}:${i}:${r.toLowerCase()}`,s=this.indexes.get(n)||{recordIds:[],count:0};s.recordIds.includes(e)||(s.recordIds.push(e),s.count=s.recordIds.length),this.indexes.set(n,s)}}}async removeRecordFromIndex(t,e){for(const[r,n]of this.indexes.entries())if(r.startsWith(`${t}:`)){const t=n.recordIds.indexOf(e);t>-1&&(n.recordIds.splice(t,1),n.count=n.recordIds.length,0===n.recordIds.length?this.indexes.delete(r):this.indexes.set(r,n))}}getFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let n=t;for(const t of r){if(!n||"object"!=typeof n||!(t in n))return null;n=n[t]}return n}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:n=null,limit:i=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=n||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 n=`${t}:${r}:${e.toLowerCase()}`,i=this.indexes.get(n);if(i)for(const t of i.recordIds){const e=c.get(t)||0;c.set(t,e+1)}}else for(const[n,i]of this.indexes.entries())if(n.startsWith(`${t}:${r}:${e.toLowerCase()}`))for(const t of i.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+i)}async searchRecords(t,e,r={}){const n=await this.search(t,e,r);if(0===n.length)return[];const i=this.database.resources[t];if(!i)throw new Error(`Resource '${t}' not found`);const s=n.map(t=>t.recordId);return(await i.getMany(s)).map(t=>{const e=n.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 n=r.slice(e,e+100);for(const e of n)await 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[n,i]=e.split(":");t.resources[n]||(t.resources[n]={fields:{},totalRecords:new Set,totalWords:0}),t.resources[n].fields[i]||(t.resources[n].fields[i]={words:0,totalOccurrences:0}),t.resources[n].fields[i].words++,t.resources[n].fields[i].totalOccurrences+=r.count,t.resources[n].totalWords++;for(const e of r.recordIds)t.resources[n].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)try{await this.rebuildIndex(e)}catch(t){console.warn(`Failed to rebuild index for resource ${e}:`,t.message)}}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()}},t.InvalidResourceItem=C,t.MemoryCache=Zs,t.MetricsPlugin=class extends Qa{constructor(t={}){super(),this.config={enabled:!1!==t.enabled,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,this.config.enabled&&"test"!==process.env.NODE_ENV){try{this.metricsResource=await 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.errorsResource=await t.createResource({name:"error_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",error:"string|required",timestamp:"string|required",metadata:"json"}}),this.performanceResource=await t.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}})}catch(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();try{const n=await t._insert(...e);return this.recordOperation(t.name,"insert",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"insert",Date.now()-r,!0),this.recordError(t.name,"insert",e),e}}.bind(this),t.update=async function(...e){const r=Date.now();try{const n=await t._update(...e);return this.recordOperation(t.name,"update",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"update",Date.now()-r,!0),this.recordError(t.name,"update",e),e}}.bind(this),t.delete=async function(...e){const r=Date.now();try{const n=await t._delete(...e);return this.recordOperation(t.name,"delete",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"delete",Date.now()-r,!0),this.recordError(t.name,"delete",e),e}}.bind(this),t.deleteMany=async function(...e){const r=Date.now();try{const n=await t._deleteMany(...e);return this.recordOperation(t.name,"delete",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"delete",Date.now()-r,!0),this.recordError(t.name,"delete",e),e}}.bind(this),t.get=async function(...e){const r=Date.now();try{const n=await t._get(...e);return this.recordOperation(t.name,"get",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"get",Date.now()-r,!0),this.recordError(t.name,"get",e),e}}.bind(this),t.getMany=async function(...e){const r=Date.now();try{const n=await t._getMany(...e);return this.recordOperation(t.name,"get",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"get",Date.now()-r,!0),this.recordError(t.name,"get",e),e}}.bind(this),t.getAll=async function(...e){const r=Date.now();try{const n=await t._getAll(...e);return this.recordOperation(t.name,"list",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"list",Date.now()-r,!0),this.recordError(t.name,"list",e),e}}.bind(this),t.list=async function(...e){const r=Date.now();try{const n=await t._list(...e);return this.recordOperation(t.name,"list",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"list",Date.now()-r,!0),this.recordError(t.name,"list",e),e}}.bind(this),t.listIds=async function(...e){const r=Date.now();try{const n=await t._listIds(...e);return this.recordOperation(t.name,"list",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"list",Date.now()-r,!0),this.recordError(t.name,"list",e),e}}.bind(this),t.count=async function(...e){const r=Date.now();try{const n=await t._count(...e);return this.recordOperation(t.name,"count",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"count",Date.now()-r,!0),this.recordError(t.name,"count",e),e}}.bind(this),t.page=async function(...e){const r=Date.now();try{const n=await t._page(...e);return this.recordOperation(t.name,"list",Date.now()-r,!1),n}catch(e){throw this.recordOperation(t.name,"list",Date.now()-r,!0),this.recordError(t.name,"list",e),e}}.bind(this)}recordOperation(t,e,r,n){this.metrics.operations[e]&&(this.metrics.operations[e].count++,this.metrics.operations[e].totalTime+=r,n&&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,n&&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)try{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"},n="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,i]of Object.entries(e))i.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:t,operation:r,count:i.count,totalTime:i.totalTime,errors:i.errors,avgTime:i.count>0?i.totalTime/i.count:0,timestamp:(new Date).toISOString(),metadata:n});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()}catch(t){console.error("Failed to flush metrics:",t)}}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:n,startDate:i,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)&&((!n||t.operation===n)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(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:n,endDate:i,limit:s=100,offset:o=0}=t;let a=(await this.errorsResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(n&&new Date(t.timestamp)<new Date(n))&&!(i&&new Date(t.timestamp)>new Date(i)))));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:n,endDate:i,limit:s=100,offset:o=0}=t;let a=(await this.performanceResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(n&&new Date(t.timestamp)<new Date(n))&&!(i&&new Date(t.timestamp)>new Date(i)))));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,n,i]=await Promise.all([this.getMetrics({startDate:e.toISOString()}),this.getErrorLogs({startDate:e.toISOString()}),this.getPerformanceLogs({startDate:e.toISOString()})]),s={period:"24h",totalOperations:0,totalErrors:n.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,n=(e.avgTime*(r-t.count)+t.totalTime)/r;e.avgTime=n}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)}console.log(`Cleaned up data older than ${this.config.retentionDays} days`)}},t.MissingMetadata=N,t.NoSuchBucket=D,t.NoSuchKey=P,t.NotFound=T,t.PermissionError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},t.Plugin=Qa,t.PluginObject=Xa,t.ReplicationPlugin=class extends Qa{constructor(t={}){super(),this.config={enabled:!1!==t.enabled,replicators:t.replicators||[],syncMode:t.syncMode||"async",retryAttempts:t.retryAttempts||3,retryDelay:t.retryDelay||1e3,batchSize:t.batchSize||10,compression:t.compression||!1,compressionLevel:t.compressionLevel||6,...t},this.replicators=[],this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,successfulOperations:0,failedOperations:0,lastSync:null}}processDataForReplication(t,e={}){switch(this.config.replicationMode){case"exact-copy":default:return{body:t,metadata:e};case"just-metadata":return{body:null,metadata:e};case"all-in-body":return{body:{data:t,metadata:e,replicationMode:this.config.replicationMode,timestamp:(new Date).toISOString()},metadata:{replicationMode:this.config.replicationMode,timestamp:(new Date).toISOString()}}}}async compressData(t){if(!this.config.compression||!t)return t;try{const e=JSON.stringify(t);return(await sc(e,{level:this.config.compressionLevel})).toString("base64")}catch(e){return this.emit("replication.compression.failed",{error:e,data:t}),t}}async decompressData(t){if(!this.config.compression||!t)return t;try{if("string"==typeof t&&t.startsWith("H4sI")){const e=Buffer.from(t,"base64"),r=await oc(e);return JSON.parse(r.toString())}return t}catch(e){return this.emit("replication.decompression.failed",{error:e,data:t}),t}}async setup(t){if(this.database=t,!this.config.enabled)return;this.config.replicators&&this.config.replicators.length>0&&await this.initializeReplicators(),t.resources.replication_logs?this.replicationLog=t.resources.replication_logs:this.replicationLog=await t.createResource({name:"replication_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",recordId:"string|required",replicatorId:"string|required",status:"string|required",attempts:"number|required",lastAttempt:"string|required",error:"string|required",data:"object|required",timestamp:"string|required"}});for(const e in t.resources)"replication_logs"!==e&&this.installHooks(t.resources[e]);const e=t.createResource.bind(t);t.createResource=async t=>{const r=await e(t);return r&&"replication_logs"!==r.name&&this.installHooks(r),r},this.startQueueProcessor()}async initializeReplicators(){for(const t of this.config.replicators)try{const{driver:e,config:r,resources:n=[]}=t,i=ic(e,r,n);if(!i.isValid){this.emit("replicator.validation.failed",{driver:e,errors:i.errors});continue}const s=nc(e,r,n);await s.initialize(this.database),s.on("replicated",t=>{this.emit("replication.success",t)}),s.on("replication_error",t=>{this.emit("replication.failed",t)}),this.replicators.push({id:`${e}-${Date.now()}`,driver:e,config:r,resources:n,instance:s}),this.emit("replicator.initialized",{driver:e,config:r,resources:n})}catch(e){this.emit("replicator.initialization.failed",{driver:t.driver,error:e.message})}}async start(){}async stop(){this.isProcessing=!1,await this.processQueue()}installHooks(t){if(!t||"replication_logs"===t.name)return;const e=new Map;t.addHook("afterInsert",async e=>(await this.queueReplication(t.name,"insert",e.id,e),e)),t.addHook("preUpdate",async r=>{if(r.id)try{const n=await t.get(r.id);e.set(r.id,n)}catch(t){e.set(r.id,{id:r.id})}return r}),t.addHook("afterUpdate",async r=>{const n=e.get(r.id);return await this.queueReplication(t.name,"update",r.id,r,n),e.delete(r.id),r}),t.addHook("afterDelete",async e=>(await this.queueReplication(t.name,"delete",e.id,e),e));const r=t.deleteMany.bind(t);t.deleteMany=async e=>{const n=await r(e);if(n&&n.length>0)for(const r of e)await this.queueReplication(t.name,"delete",r,{id:r});return n}}async queueReplication(t,e,n,i,s=null){if(!this.config.enabled)return;if(0===this.replicators.length)return;if(0===this.replicators.filter(e=>e.instance.shouldReplicateResource(t)).length)return;const o={id:`repl-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t,operation:e,recordId:n,data:r.isPlainObject(i)?i:{raw:i},beforeData:s?r.isPlainObject(s)?s:{raw:s}:null,timestamp:(new Date).toISOString(),attempts:0},a=await this.logReplication(o);if("sync"===this.config.syncMode)try{const t=await this.processReplicationItem(o);a&&await this.updateReplicationLog(a,{status:t.success?"success":"failed",attempts:1,error:t.success?"":JSON.stringify(t.results)}),this.stats.totalOperations++,t.success?this.stats.successfulOperations++:this.stats.failedOperations++}catch(t){a&&await this.updateReplicationLog(a,{status:"failed",attempts:1,error:t.message}),this.stats.failedOperations++}else this.queue.push(o),this.emit("replication.queued",{item:o,queueLength:this.queue.length})}async processReplicationItem(t){const{resourceName:e,operation:r,recordId:n,data:i,beforeData:s}=t,o=this.replicators.filter(t=>t.instance.shouldReplicateResource(e));if(0===o.length)return{success:!0,skipped:!0,reason:"no_applicable_replicators"};const a=[];for(const t of o)try{const o=await t.instance.replicate(e,r,i,n,s);a.push({replicatorId:t.id,driver:t.driver,success:o.success,error:o.error,skipped:o.skipped})}catch(e){a.push({replicatorId:t.id,driver:t.driver,success:!1,error:e.message})}return{success:a.every(t=>t.success||t.skipped),results:a}}async logReplication(t){if(this.replicationLog)try{const e=`log-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return await this.replicationLog.insert({id:e,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,replicatorId:"all",status:"queued",attempts:0,lastAttempt:(new Date).toISOString(),error:"",data:r.isPlainObject(t.data)?t.data:{raw:t.data},timestamp:(new Date).toISOString()}),e}catch(e){return this.emit("replication.log.failed",{error:e.message,item:t}),null}}async updateReplicationLog(t,e){if(this.replicationLog)try{await this.replicationLog.update(t,{...e,lastAttempt:(new Date).toISOString()})}catch(r){this.emit("replication.updateLog.failed",{error:r.message,logId:t,updates:e})}}startQueueProcessor(){this.isProcessing||(this.isProcessing=!0,this.processQueueLoop())}async processQueueLoop(){for(;this.isProcessing;)if(this.queue.length>0){const t=this.queue.splice(0,this.config.batchSize);for(const e of t)await this.processReplicationItem(e)}else await new Promise(t=>setTimeout(t,1e3))}async processQueue(){if(0===this.queue.length)return;const t=this.queue.shift();let e=0,r=null;for(;e<this.config.retryAttempts;)try{e++,this.emit("replication.retry.started",{item:t,attempt:e,maxAttempts:this.config.retryAttempts});const n=await this.processReplicationItem(t);if(n.success)return this.stats.successfulOperations++,void this.emit("replication.success",{item:t,attempts:e,results:n.results,stats:this.stats});r=n.results,e<this.config.retryAttempts&&await new Promise(t=>setTimeout(t,this.config.retryDelay*e))}catch(n){r=n.message,e<this.config.retryAttempts?await new Promise(t=>setTimeout(t,this.config.retryDelay*e)):this.emit("replication.retry.exhausted",{attempts:e,lastError:r,item:t})}this.stats.failedOperations++,this.emit("replication.failed",{attempts:e,lastError:r,item:t,stats:this.stats})}async getReplicationStats(){const t=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}}));return{enabled:this.config.enabled,replicators:t,queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getReplicationLogs(t={}){if(!this.replicationLog)return[];const{resourceName:e,operation:r,status:n,limit:i=100,offset:s=0}=t;let o={};e&&(o.resourceName=e),r&&(o.operation=r),n&&(o.status=n);return(await this.replicationLog.list(o)).slice(s,s+i)}async retryFailedReplications(){if(!this.replicationLog)return{retried:0};const t=await this.replicationLog.list({status:"failed"});let e=0;for(const r of t)try{await this.queueReplication(r.resourceName,r.operation,r.recordId,r.data),e++}catch(t){console.error("Failed to retry replication:",t)}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("replication_logs"!==r&&e.instance.shouldReplicateResource(r)){this.emit("replication.sync.resource",{resourceName:r,replicatorId:t});const n=this.database.resources[r],i=await n.getAll();for(const t of i)await e.instance.replicate(r,"insert",t,t.id)}this.emit("replication.sync.completed",{replicatorId:t,stats:this.stats})}},t.Resource=qs,t.ResourceIdsPageReader=ws,t.ResourceIdsReader=bs,t.ResourceNotFound=class extends I{constructor({bucket:t,resourceName:e,id:r,...n}){super(`Resource not found: ${e}/${r} [bucket:${t}]`,{bucket:t,resourceName:e,id:r,...n})}},t.ResourceReader=_s,t.ResourceWriter=vs,t.S3Cache=Ya,t.S3DBError=I,t.S3_DEFAULT_ENDPOINT=U,t.S3_DEFAULT_REGION=$,t.S3db=Hs,t.Schema=Ir,t.SchemaActions=jr,t.UnknownError=M,t.ValidationError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},t.Validator=xr,t.ValidatorManager=Ar,t.behaviors=$s,t.calculateAttributeNamesSize=Os,t.calculateAttributeSizes=Rs,t.calculateTotalSize=xs,t.calculateUTF8Bytes=Ss,t.decrypt=H,t.default=Hs,t.encrypt=V,t.getBehavior=Us,t.getSizeBreakdown=function(t){const e=Rs(t),r=Os(t),n=Object.values(e).reduce((t,e)=>t+e,0),i=n+r,s=Object.entries(e).sort(([,t],[,e])=>e-t).map(([t,e])=>({attribute:t,size:e,percentage:(e/i*100).toFixed(2)+"%"}));return{total:i,valueSizes:e,namesSize:r,valueTotal:n,breakdown:s,detailedBreakdown:{values:n,names:r,total:i}}},t.idGenerator=w,t.passwordGenerator=_,t.sha256=q,t.streamToString=ks,t.transformValue=Es,Object.defineProperty(t,"__esModule",{value:!0}),t}({},nanoid,lodashEs,promisePool,clientS3,crypto,flat,FastestValidator,web);
|
|
1
|
+
var S3DB=function(e,t,r,i,s,n,o,a,c,u,l,h,d){"use strict";function f(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 p(e){let t=0;for(const r of Object.keys(e))t+=f(r);return t}function g(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 m(e){const t={};for(const[r,i]of Object.entries(e)){const e=f(g(i));t[r]=e}return t}function y(e){const t=m(e);return Object.values(t).reduce((e,t)=>e+t,0)+p(e)}function b(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 y(n)}function w(e={}){const{s3Limit:t=2048,systemConfig:r={}}=e;return t-b(r)}const v=2047;var O=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:v,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=y(r),n=w({s3Limit:v,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=y(i),o=w({s3Limit:v,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=y(i),n=w({s3Limit:v,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 k=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=y(r);return s>w({s3Limit:v,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=y(i);return n>w({s3Limit:v,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=y(i);return n>w({s3Limit:v,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 S="$truncated",_="true",R=f(S)+f(_);async function j({resource:e,data:t,mappedData:r,originalData:i}){const s=w({s3Limit:v,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),n=m(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:R))<=s)){const t=s-c-(u?0:R);if(t>0){const r=E(i,t);a[e]=r,u=!0,c+=f(r)}else a[e]="",u=!0;break}a[e]=i,c+=t}let l=y(a)+(u?R: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=y(a)+R,u=!0}return u&&(a[S]=_),{mappedData:a,body:JSON.stringify(r)}}function E(e,t){if("string"==typeof e)return N(e,t);if("object"==typeof e&&null!==e){return N(JSON.stringify(e),t)}return N(String(e),t)}function N(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 A=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:j,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){return j({resource:e,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return j({resource:e,data:r,mappedData:i})}});function I(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 D(e){try{return[!0,null,e()]}catch(e){return[!1,e,null]}}const x="$overflow",P="true",C=f(x)+f(P);async function T({resource:e,data:t,mappedData:r,originalData:i}){const s=w({s3Limit:v,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),n=m(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-=C,l=!0),!l&&u+t<=h?(a[e]=r[e],u+=t):(c[e]=r[e],l=!0));l&&(a[x]=P);const d=Object.keys(c).length>0;let f=d?JSON.stringify(c):"";return d||(f="{}"),{mappedData:a,body:f}}async function L({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 $={"user-managed":k,"enforce-limits":O,"truncate-data":A,"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]=D(()=>JSON.parse(r));i=e?s:{}}const s={...i,...t};return delete s.$overflow,{metadata:s,body:r}},handleInsert:T,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){return T({resource:e,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return T({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]=D(()=>JSON.parse(r));i=e?s:{}}return{metadata:{...i,...t},body:r}},handleInsert:L,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 L({resource:e,data:r,mappedData:i})}})};function M(e){const t=$[e];if(!t)throw new Error(`Unknown behavior: ${e}. Available behaviors: ${Object.keys($).join(", ")}`);return t}const U=Object.keys($),q="user-managed",F="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",B=Object.fromEntries([...F].map((e,t)=>[e,t])),z=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";if(0===e)return F[0];if(e<0)return"-"+z(-Math.floor(e));e=Math.floor(e);let t="";for(;e;)t=F[e%62]+t,e=Math.floor(e/62);return t},V=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=B[e[t]];if(void 0===i)return NaN;r=62*r+i}return t?-r:r},K=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=z(Number(r));return i?(t?"-":"")+s+"."+i:(t?"-":"")+s},H=e=>{if("string"!=typeof e)return NaN;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));const[r,i]=e.split("."),s=V(r);if(isNaN(s))return NaN;const n=i?Number(s+"."+i):s;return t?-n:n};class W 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:d,...f}){e&&(i+=`\n\nVerbose:\n\n${JSON.stringify(f,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=d,this.data={bucket:t,key:r,...f,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 G extends W{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 J extends G{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class Y extends G{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class Q extends G{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 G{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 G{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 G{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 G{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 G{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 G{}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 Y("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 J("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 G{constructor(e,t={}){super(e,{...t,suggestion:"Check the connection string format and credentials."})}}class ae extends G{constructor(e,t={}){super(e,{...t,suggestion:"Check if the crypto library is available and input is valid."})}}class ce extends G{constructor(e,t={}){super(e,{...t,suggestion:"Check schema definition and input data."})}}class ue extends G{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,t)}}class le extends G{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check partition definition, fields, and input values."})}}async function he(){let e;if("undefined"!=typeof process){const[t,r,i]=await I(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 de(e){const[t,r,i]=await I(he);if(!t)throw new ae("Crypto API not available",{original:r});const s=(new TextEncoder).encode(e),[n,o,a]=await I(()=>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 fe(e,t){const[r,i,s]=await I(he);if(!r)throw new ae("Crypto API not available",{original:i});const n=s.getRandomValues(new Uint8Array(16)),[o,a,c]=await I(()=>me(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,d,f]=await I(()=>s.subtle.encrypt({name:"AES-GCM",iv:u},c,l));if(!h)throw new ae("Encryption failed",{original:d,content:e});const p=new Uint8Array(n.length+u.length+f.byteLength);return p.set(n),p.set(u,n.length),p.set(new Uint8Array(f),n.length+u.length),function(e){if("undefined"!=typeof process)return Buffer.from(e).toString("base64");{const[t,r,i]=D(()=>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 pe(e,t){const[r,i,s]=await I(he);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]=D(()=>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 I(()=>me(t,o));if(!u)throw new ae("Key derivation failed (decrypt)",{original:l,passphrase:t,salt:o});const[d,f,p]=await I(()=>s.subtle.decrypt({name:"AES-GCM",iv:a},h,c));if(!d)throw new ae("Decryption failed",{original:f,encryptedBase64:e});return(new TextDecoder).decode(p)}async function ge(e){if("undefined"==typeof process)throw new ae("MD5 hashing is only available in Node.js environment",{context:"md5"});const[t,r,i]=await I(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 me(e,t){const[r,i,s]=await I(he);if(!r)throw new ae("Crypto API not available",{original:i});const n=(new TextEncoder).encode(e),[o,a,c]=await I(()=>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 I(()=>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 ye=t.customAlphabet(t.urlAlphabet,22),be=t.customAlphabet("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var we;function ve(){}function Oe(){Oe.init.call(this)}function ke(e){return void 0===e._maxListeners?Oe.defaultMaxListeners:e._maxListeners}function Se(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 ve,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=ke(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 _e(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 Re(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 je(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}ve.prototype=Object.create(null),Oe.EventEmitter=Oe,Oe.usingDomains=!1,Oe.prototype.domain=void 0,Oe.prototype._events=void 0,Oe.prototype._maxListeners=void 0,Oe.defaultMaxListeners=10,Oe.init=function(){this.domain=null,Oe.usingDomains&&(!we.active||this instanceof we.Domain||(this.domain=we.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new ve,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Oe.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},Oe.prototype.getMaxListeners=function(){return ke(this)},Oe.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=je(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=je(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=je(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=je(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=je(e,s),o=0;o<s;++o)n[o].apply(r,i)}(r,l,this,s)}return!0},Oe.prototype.addListener=function(e,t){return Se(this,e,t,!1)},Oe.prototype.on=Oe.prototype.addListener,Oe.prototype.prependListener=function(e,t){return Se(this,e,t,!0)},Oe.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,_e(this,e,t)),this},Oe.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,_e(this,e,t)),this},Oe.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 ve:(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 ve,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},Oe.prototype.off=function(e,t){return this.removeListener(e,t)},Oe.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new ve,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new ve: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 ve,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},Oe.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):[]},Oe.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Re.call(e,t)},Oe.prototype.listenerCount=Re,Oe.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Ee extends Oe{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 Ne={setup(e){},start(){},stop(){}};function Ae(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 Ie=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,De=function(e){return Ie.exec(e).slice(1)};function xe(){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=Ae($e(e.split("/"),function(e){return!!e}),!t).join("/"))||"."}function Pe(e){var t=Ce(e),r="/"===Me(e,-1);return(e=Ae($e(e.split("/"),function(e){return!!e}),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function Ce(e){return"/"===e.charAt(0)}function Te(){return Pe($e(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 Le={extname:function(e){return De(e)[3]},basename:function(e,t){var r=De(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},dirname:function(e){var t=De(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=xe(e).substr(1),t=xe(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:Te,isAbsolute:Ce,normalize:Pe,resolve:xe};function $e(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 Me="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 Ue extends Oe{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}}class qe extends Ue{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:Te(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,s,n]=await I(async()=>{const{Body:t}=await this.client.getObject(Te(this.keyPrefix,e));let s=await i.streamToString(t);return s=Buffer.from(s,"base64"),s=r.unzipSync(s).toString(),JSON.parse(s)});if(t)return n;if("NoSuchKey"===s.name||"NotFound"===s.name)return null;throw s}async _del(e){return await this.client.deleteObject(Te(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)}}class Fe extends Ue{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)}}const Be={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 ze extends Oe{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:[]}}}const Ve="us-east-1",Ke="https://s3.us-east-1.amazonaws.com";class He{constructor(e){let t;const[r,i,s]=I(()=>new URL(e));if(!r)throw new oe("Invalid connection string: "+e,{original:i,input:e});t=s,this.region=Ve,"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]=D(()=>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]=D(()=>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]=D(()=>decodeURIComponent(e.password));if(!a)throw new oe("Invalid secretAccessKey in connection string",{original:c,input:e.password});if(this.secretAccessKey=u,this.endpoint=Ke,["/","",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]=D(()=>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]=D(()=>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]=D(()=>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 We extends Oe{constructor({verbose:e=!1,id:t=null,AwsS3Client:r,connectionString:i,parallelism:s=10}){super(),this.verbose=e,this.id=t??ye(),this.parallelism=s,this.config=new He(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 u.S3Client(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 ge(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 I(()=>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&&Le.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?Le.join(o,e):e,Metadata:a,Body:i||Buffer.alloc(0)};let l,h;void 0!==r&&(c.ContentType=r),void 0!==s&&(c.ContentEncoding=s),void 0!==n&&(c.ContentLength=n);try{return l=await this.sendCommand(new u.PutObjectCommand(c)),l}catch(t){throw h=t,ne(t,{bucket:this.config.bucket,key:e,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",h||l,{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?Le.join(t,e):e};let i,s;try{return i=await this.sendCommand(new u.GetObjectCommand(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?Le.join(t,e):e};let i,s;try{return i=await this.sendCommand(new u.HeadObjectCommand(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?Le.join(this.config.keyPrefix,t):t,CopySource:Le.join(this.config.bucket,this.config.keyPrefix?Le.join(this.config.keyPrefix,e):e)};let i,s;try{return i=await this.sendCommand(new u.CopyObjectCommand(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 I(()=>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&&Le.join(t,e);const r={Bucket:this.config.bucket,Key:t?Le.join(t,e):e};let i,s;try{return i=await this.sendCommand(new u.DeleteObjectCommand(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.chunk(e,1e3),{results:i,errors:s}=await c.PromisePool.for(r).withConcurrency(this.parallelism).process(async e=>{for(const r of e)t&&Le.join(t,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:e.map(e=>({Key:t?Le.join(t,e):e}))}};let i;const[s,n,o]=await I(()=>this.sendCommand(new u.DeleteObjectsCommand(r)));if(!s)throw n;return i=o,i&&i.Errors&&i.Errors.length,i&&i.Deleted&&(i.Deleted.length,e.length),i}),o={deleted:i,notFound:s};return this.emit("deleteObjects",o,e),o}async deleteAll({prefix:e}={}){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,i=0;do{const s=new u.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:t?Le.join(t,e||""):e||"",ContinuationToken:r}),n=await this.client.send(s);if(n.Contents&&n.Contents.length>0){const t=new u.DeleteObjectsCommand({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 I(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?Le.join(this.config.keyPrefix,e||""):e||""},[s,n,o]=await I(()=>this.sendCommand(new u.ListObjectsV2Command(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:i,errors:s}=await c.PromisePool.for(r).withConcurrency(this.parallelism).process(async r=>{const i=r.replace(e,t),[s,n]=await I(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:i,errors:s},{prefixFrom:e,prefixTo:t}),s.length>0)throw new Error("Some objects could not be moved");return i}}async function Ge(e,t,r){if(!this.passphrase)return t.push(new J("Missing configuration for secrets encryption.",{actual:e,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),e;const[i,s,n]=await I(()=>fe(String(e),this.passphrase));return i?n:(t.push(new J("Problem encrypting secret.",{actual:e,type:"encryptionProblem",error:s,suggestion:"Check the passphrase and input value."})),e)}async function Je(e,t,r){if(n.isString(e))return e;const[i,s,o]=D(()=>JSON.stringify(e));if(!i)throw new J("Failed to stringify JSON",{original:s,input:e});return o}class Ye extends h{constructor({options:e,passphrase:t,autoEncrypt:r=!0}={}){super(n.merge({},{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?Ge: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?Ge:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Ge:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?Je:void 0})}}const Qe=new Proxy(Ye,{instance:null,construct(e,t){return this.instance||(this.instance=new e(...t)),this.instance}});const Xe={trim:e=>null==e?e:e.trim(),encrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,i,s]=await I(()=>fe(e,t));return r?s:e},decrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,i,s]=await I(()=>pe(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]=D(()=>JSON.parse(e));return e}const[t,r,i]=D(()=>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]=D(()=>JSON.parse(e));return t?i:e},toNumber:e=>n.isString(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=V(e);return isNaN(t)?void 0:t}},toBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return z(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:z(t)}return e},fromBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=H(e);return isNaN(t)?void 0:t}},toBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return K(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:K(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 z(e);const t=Number(e);return isNaN(t)?"":z(t)}).join(t)},toArrayOfNumbers:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:V(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=V(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 K(e);const t=Number(e);return isNaN(t)?"":K(t)}).join(t)},toArrayOfDecimals:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:H(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=H(e);return isNaN(t)?NaN:t}return NaN})}};class Ze{constructor(e){const{map:t,name:r,attributes:i,passphrase:s,version:o=1,options:a={}}=e;this.name=r,this.version=o,this.attributes=i||{},this.passphrase=s??"secret",this.options=n.merge({},this.defaultOptions(),a),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const c=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Qe({autoEncrypt:!1}).compile(n.merge({$$async:!0},c)),this.options.generateAutoHooks&&this.generateAutoHooks(),n.isEmpty(t)){const e=l.flatten(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=z(i);t[e]=s,r[s]=e}),{mapping:t,reversedMapping:r}}(i);this.map=s,this.reversedMap=n}else this.map=t,this.reversedMap=n.invert(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]=n.uniq([...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=l.flatten(n.cloneDeep(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:o}=n.isString(e)?JSON.parse(e):e;const[a,c,u]=D(()=>Ze._importAttributes(o));if(!a)throw new ce("Failed to import schema attributes",{original:c,input:o});o=u;return new Ze({map:t,name:r,options:i,version:s,attributes:o})}static _importAttributes(e){if("string"==typeof e){const[t,r,i]=D(()=>JSON.parse(e));if(t&&"object"==typeof i&&null!==i){const[t,r,s]=D(()=>Ze._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]=D(()=>e.map(e=>Ze._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]=D(()=>Ze._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=n.cloneDeep(e);for(const[e,i]of Object.entries(this.options.hooks[t]))for(const t of i){const i=n.get(r,e);void 0!==i&&"function"==typeof Xe[t]&&n.set(r,e,await Xe[t](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(e,{mutateOriginal:t=!1}={}){let r=t?e:n.cloneDeep(e);return await this.validator(r)}async mapper(e){let t=n.cloneDeep(e);t=await this.applyHooksActions(t,"beforeMap");const r=l.flatten(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]=z(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=n.cloneDeep(e);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const i=t?n.invert(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]=D(()=>JSON.parse(t));e&&(n=i)}}else"string"==typeof n&&""!==n?n=V(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]=D(()=>JSON.parse(n));e&&Array.isArray(r)&&(n=r)}else n=Xe.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 Xe[e]&&(n=await Xe[e](n,{passphrase:this.passphrase,separator:this.options.arraySeparator}));s[r]=n}await this.applyHooksActions(s,"afterUnmap");const o=l.unflatten(s);for(const[t,r]of Object.entries(e))t.startsWith("$")&&(o[t]=r);return o}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 et="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},tt=[],rt=[],it="undefined"!=typeof Uint8Array?Uint8Array:Array,st=!1;function nt(){st=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)tt[t]=e[t],rt[e.charCodeAt(t)]=t;rt["-".charCodeAt(0)]=62,rt["_".charCodeAt(0)]=63}function ot(e){return tt[e>>18&63]+tt[e>>12&63]+tt[e>>6&63]+tt[63&e]}function at(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(ot(i));return s.join("")}function ct(e){var t;st||nt();for(var r=e.length,i=r%3,s="",n=[],o=16383,a=0,c=r-i;a<c;a+=o)n.push(at(e,a,a+o>c?c:a+o));return 1===i?(t=e[r-1],s+=tt[t>>2],s+=tt[t<<4&63],s+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],s+=tt[t>>10],s+=tt[t>>4&63],s+=tt[t<<2&63],s+="="),n.push(s),n.join("")}function ut(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,d=r?-1:1,f=e[t+h];for(h+=d,n=f&(1<<-l)-1,f>>=-l,l+=a;l>0;n=256*n+e[t+h],h+=d,l-=8);for(o=n&(1<<-l)-1,n>>=-l,l+=i;l>0;o=256*o+e[t+h],h+=d,l-=8);if(0===n)n=1-u;else{if(n===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,i),n-=u}return(f?-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,d=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,f=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?d/c:d*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+f]=255&a,f+=p,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;e[r+f]=255&o,f+=p,o/=256,u-=8);e[r+f-p]|=128*g}var ht={}.toString,dt=Array.isArray||function(e){return"[object Array]"==ht.call(e)};function ft(){return gt.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function pt(e,t){if(ft()<t)throw new RangeError("Invalid typed array length");return gt.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=gt.prototype:(null===e&&(e=new gt(t)),e.length=t),e}function gt(e,t,r){if(!(gt.TYPED_ARRAY_SUPPORT||this instanceof gt))return new gt(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 bt(this,e)}return mt(this,e,t,r)}function mt(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);gt.TYPED_ARRAY_SUPPORT?(e=t).__proto__=gt.prototype:e=wt(e,t);return e}(e,t,r,i):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!gt.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|kt(t,r);e=pt(e,i);var s=e.write(t,r);s!==i&&(e=e.slice(0,s));return e}(e,t,r):function(e,t){if(Ot(t)){var r=0|vt(t.length);return 0===(e=pt(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?pt(e,0):wt(e,t);if("Buffer"===t.type&&dt(t.data))return wt(e,t.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function yt(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 bt(e,t){if(yt(t),e=pt(e,t<0?0:0|vt(t)),!gt.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function wt(e,t){var r=t.length<0?0:0|vt(t.length);e=pt(e,r);for(var i=0;i<r;i+=1)e[i]=255&t[i];return e}function vt(e){if(e>=ft())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ft().toString(16)+" bytes");return 0|e}function Ot(e){return!(null==e||!e._isBuffer)}function kt(e,t){if(Ot(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 Jt(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Yt(e).length;default:if(i)return Jt(e).length;t=(""+t).toLowerCase(),i=!0}}function St(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 Mt(this,t,r);case"utf8":case"utf-8":return Ct(this,t,r);case"ascii":return Lt(this,t,r);case"latin1":case"binary":return $t(this,t,r);case"base64":return Pt(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ut(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function _t(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function Rt(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=gt.from(t,i)),Ot(t))return 0===t.length?-1:jt(e,t,r,i,s);if("number"==typeof t)return t&=255,gt.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):jt(e,[t],r,i,s);throw new TypeError("val must be string, number or Buffer")}function jt(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,d=0;d<c;d++)if(u(e,n+d)!==u(t,d)){h=!1;break}if(h)return n}return-1}function Et(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 Nt(e,t,r,i){return Qt(Jt(t,e.length-r),e,r,i)}function At(e,t,r,i){return Qt(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function It(e,t,r,i){return At(e,t,r,i)}function Dt(e,t,r,i){return Qt(Yt(t),e,r,i)}function xt(e,t,r,i){return Qt(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 Pt(e,t,r){return 0===t&&r===e.length?ct(e):ct(e.slice(t,r))}function Ct(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<=Tt)return String.fromCharCode.apply(String,e);var r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=Tt));return r}(i)}gt.TYPED_ARRAY_SUPPORT=void 0===et.TYPED_ARRAY_SUPPORT||et.TYPED_ARRAY_SUPPORT,ft(),gt.poolSize=8192,gt._augment=function(e){return e.__proto__=gt.prototype,e},gt.from=function(e,t,r){return mt(null,e,t,r)},gt.TYPED_ARRAY_SUPPORT&&(gt.prototype.__proto__=Uint8Array.prototype,gt.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&>[Symbol.species]),gt.alloc=function(e,t,r){return function(e,t,r,i){return yt(t),t<=0?pt(e,t):void 0!==r?"string"==typeof i?pt(e,t).fill(r,i):pt(e,t).fill(r):pt(e,t)}(null,e,t,r)},gt.allocUnsafe=function(e){return bt(null,e)},gt.allocUnsafeSlow=function(e){return bt(null,e)},gt.isBuffer=function(e){return null!=e&&(!!e._isBuffer||Xt(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&Xt(e.slice(0,0))}(e))},gt.compare=function(e,t){if(!Ot(e)||!Ot(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},gt.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}},gt.concat=function(e,t){if(!dt(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return gt.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=gt.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var n=e[r];if(!Ot(n))throw new TypeError('"list" argument must be an Array of Buffers');n.copy(i,s),s+=n.length}return i},gt.byteLength=kt,gt.prototype._isBuffer=!0,gt.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)_t(this,t,t+1);return this},gt.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)_t(this,t,t+3),_t(this,t+1,t+2);return this},gt.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)_t(this,t,t+7),_t(this,t+1,t+6),_t(this,t+2,t+5),_t(this,t+3,t+4);return this},gt.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Ct(this,0,e):St.apply(this,arguments)},gt.prototype.equals=function(e){if(!Ot(e))throw new TypeError("Argument must be a Buffer");return this===e||0===gt.compare(this,e)},gt.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+">"},gt.prototype.compare=function(e,t,r,i,s){if(!Ot(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},gt.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},gt.prototype.indexOf=function(e,t,r){return Rt(this,e,t,r,!0)},gt.prototype.lastIndexOf=function(e,t,r){return Rt(this,e,t,r,!1)},gt.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 Et(this,e,t,r);case"utf8":case"utf-8":return Nt(this,e,t,r);case"ascii":return At(this,e,t,r);case"latin1":case"binary":return It(this,e,t,r);case"base64":return Dt(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return xt(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},gt.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Tt=4096;function Lt(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 $t(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 Mt(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+=Gt(e[n]);return s}function Ut(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 qt(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 Ft(e,t,r,i,s,n){if(!Ot(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 Bt(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 zt(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 Vt(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 Kt(e,t,r,i,s){return s||Vt(e,0,r,4),lt(e,t,r,i,23,4),r+4}function Ht(e,t,r,i,s){return s||Vt(e,0,r,8),lt(e,t,r,i,52,8),r+8}gt.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),gt.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=gt.prototype;else{var s=t-e;r=new gt(s,void 0);for(var n=0;n<s;++n)r[n]=this[n+e]}return r},gt.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||qt(e,t,this.length);for(var i=this[e],s=1,n=0;++n<t&&(s*=256);)i+=this[e+n]*s;return i},gt.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||qt(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i},gt.prototype.readUInt8=function(e,t){return t||qt(e,1,this.length),this[e]},gt.prototype.readUInt16LE=function(e,t){return t||qt(e,2,this.length),this[e]|this[e+1]<<8},gt.prototype.readUInt16BE=function(e,t){return t||qt(e,2,this.length),this[e]<<8|this[e+1]},gt.prototype.readUInt32LE=function(e,t){return t||qt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},gt.prototype.readUInt32BE=function(e,t){return t||qt(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},gt.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||qt(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},gt.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||qt(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},gt.prototype.readInt8=function(e,t){return t||qt(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},gt.prototype.readInt16LE=function(e,t){t||qt(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},gt.prototype.readInt16BE=function(e,t){t||qt(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},gt.prototype.readInt32LE=function(e,t){return t||qt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},gt.prototype.readInt32BE=function(e,t){return t||qt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},gt.prototype.readFloatLE=function(e,t){return t||qt(e,4,this.length),ut(this,e,!0,23,4)},gt.prototype.readFloatBE=function(e,t){return t||qt(e,4,this.length),ut(this,e,!1,23,4)},gt.prototype.readDoubleLE=function(e,t){return t||qt(e,8,this.length),ut(this,e,!0,52,8)},gt.prototype.readDoubleBE=function(e,t){return t||qt(e,8,this.length),ut(this,e,!1,52,8)},gt.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||Ft(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},gt.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||Ft(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},gt.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,1,255,0),gt.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},gt.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,2,65535,0),gt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Bt(this,e,t,!0),t+2},gt.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,2,65535,0),gt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Bt(this,e,t,!1),t+2},gt.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,4,4294967295,0),gt.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):zt(this,e,t,!0),t+4},gt.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,4,4294967295,0),gt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):zt(this,e,t,!1),t+4},gt.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t|=0,!i){var s=Math.pow(2,8*r-1);Ft(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},gt.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t|=0,!i){var s=Math.pow(2,8*r-1);Ft(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},gt.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,1,127,-128),gt.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},gt.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,2,32767,-32768),gt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Bt(this,e,t,!0),t+2},gt.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,2,32767,-32768),gt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Bt(this,e,t,!1),t+2},gt.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,4,2147483647,-2147483648),gt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):zt(this,e,t,!0),t+4},gt.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Ft(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),gt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):zt(this,e,t,!1),t+4},gt.prototype.writeFloatLE=function(e,t,r){return Kt(this,e,t,!0,r)},gt.prototype.writeFloatBE=function(e,t,r){return Kt(this,e,t,!1,r)},gt.prototype.writeDoubleLE=function(e,t,r){return Ht(this,e,t,!0,r)},gt.prototype.writeDoubleBE=function(e,t,r){return Ht(this,e,t,!1,r)},gt.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||!gt.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},gt.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&&!gt.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=Ot(e)?e:Jt(new gt(e,i).toString()),a=o.length;for(n=0;n<r-t;++n)this[n+t]=o[n%a]}return this};var Wt=/[^+\/0-9A-Za-z-_]/g;function Gt(e){return e<16?"0"+e.toString(16):e.toString(16)}function Jt(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 Yt(e){return function(e){var t,r,i,s,n,o;st||nt();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 it(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=rt[e.charCodeAt(t)]<<18|rt[e.charCodeAt(t+1)]<<12|rt[e.charCodeAt(t+2)]<<6|rt[e.charCodeAt(t+3)],o[c++]=s>>16&255,o[c++]=s>>8&255,o[c++]=255&s;return 2===n?(s=rt[e.charCodeAt(t)]<<2|rt[e.charCodeAt(t+1)]>>4,o[c++]=255&s):1===n&&(s=rt[e.charCodeAt(t)]<<10|rt[e.charCodeAt(t+1)]<<4|rt[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(Wt,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Qt(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 Xt(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function Zt(){throw new Error("setTimeout has not been defined")}function er(){throw new Error("clearTimeout has not been defined")}var tr=Zt,rr=er;function ir(e){if(tr===setTimeout)return setTimeout(e,0);if((tr===Zt||!tr)&&setTimeout)return tr=setTimeout,setTimeout(e,0);try{return tr(e,0)}catch(t){try{return tr.call(null,e,0)}catch(t){return tr.call(this,e,0)}}}"function"==typeof et.setTimeout&&(tr=setTimeout),"function"==typeof et.clearTimeout&&(rr=clearTimeout);var sr,nr=[],or=!1,ar=-1;function cr(){or&&sr&&(or=!1,sr.length?nr=sr.concat(nr):ar=-1,nr.length&&ur())}function ur(){if(!or){var e=ir(cr);or=!0;for(var t=nr.length;t;){for(sr=nr,nr=[];++ar<t;)sr&&sr[ar].run();ar=-1,t=nr.length}sr=null,or=!1,function(e){if(rr===clearTimeout)return clearTimeout(e);if((rr===er||!rr)&&clearTimeout)return rr=clearTimeout,clearTimeout(e);try{return rr(e)}catch(t){try{return rr.call(null,e)}catch(t){return rr.call(this,e)}}}(e)}}function lr(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];nr.push(new hr(e,t)),1!==nr.length||or||ir(ur)}function hr(e,t){this.fun=e,this.array=t}hr.prototype.run=function(){this.fun.apply(null,this.array)};var dr=et.performance||{};dr.now||dr.mozNow||dr.msNow||dr.oNow||dr.webkitNow;var fr,pr={env:{}};fr="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 gr=/%[sdj%]/g;function mr(e){if(!Nr(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(vr(arguments[r]));return t.join(" ")}r=1;for(var i=arguments,s=i.length,n=String(e).replace(gr,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])Er(o)||!Dr(o)?n+=" "+o:n+=" "+vr(o);return n}function yr(e,t){if(Ar(et.process))return function(){return yr(e,t).apply(this,arguments)};if(!0===pr.noDeprecation)return e;var r=!1;return function(){if(!r){if(pr.throwDeprecation)throw new Error(t);pr.traceDeprecation?console.trace(t):console.error(t),r=!0}return e.apply(this,arguments)}}var br,wr={};function vr(e,t){var r={seen:[],stylize:kr};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),jr(t)?r.showHidden=t:t&&function(e,t){if(!t||!Dr(t))return e;var r=Object.keys(t),i=r.length;for(;i--;)e[r[i]]=t[r[i]]}(r,t),Ar(r.showHidden)&&(r.showHidden=!1),Ar(r.depth)&&(r.depth=2),Ar(r.colors)&&(r.colors=!1),Ar(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Or),Sr(r,e,r.depth)}function Or(e,t){var r=vr.styles[t];return r?"["+vr.colors[r][0]+"m"+e+"["+vr.colors[r][1]+"m":e}function kr(e,t){return e}function Sr(e,t,r){if(e.customInspect&&t&&Cr(t.inspect)&&t.inspect!==vr&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return Nr(i)||(i=Sr(e,i,r)),i}var s=function(e,t){if(Ar(t))return e.stylize("undefined","undefined");if(Nr(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(jr(t))return e.stylize(""+t,"boolean");if(Er(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)),Pr(t)&&(n.indexOf("message")>=0||n.indexOf("description")>=0))return _r(t);if(0===n.length){if(Cr(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(Ir(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(xr(t))return e.stylize(Date.prototype.toString.call(t),"date");if(Pr(t))return _r(t)}var c,u,l="",h=!1,d=["{","}"];(c=t,Array.isArray(c)&&(h=!0,d=["[","]"]),Cr(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return Ir(t)&&(l=" "+RegExp.prototype.toString.call(t)),xr(t)&&(l=" "+Date.prototype.toUTCString.call(t)),Pr(t)&&(l=" "+_r(t)),0!==n.length||h&&0!=t.length?r<0?Ir(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)Lr(t,String(o))?n.push(Rr(e,t,r,i,String(o),!0)):n.push("");return s.forEach(function(s){s.match(/^\d+$/)||n.push(Rr(e,t,r,i,s,!0))}),n}(e,t,r,o,n):n.map(function(i){return Rr(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,d)):d[0]+l+d[1]}function _r(e){return"["+Error.prototype.toString.call(e)+"]"}function Rr(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")),Lr(i,s)||(o="["+s+"]"),a||(e.seen.indexOf(c.value)<0?(a=Er(r)?Sr(e,c.value,null):Sr(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")),Ar(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 jr(e){return"boolean"==typeof e}function Er(e){return null===e}function Nr(e){return"string"==typeof e}function Ar(e){return void 0===e}function Ir(e){return Dr(e)&&"[object RegExp]"===Tr(e)}function Dr(e){return"object"==typeof e&&null!==e}function xr(e){return Dr(e)&&"[object Date]"===Tr(e)}function Pr(e){return Dr(e)&&("[object Error]"===Tr(e)||e instanceof Error)}function Cr(e){return"function"==typeof e}function Tr(e){return Object.prototype.toString.call(e)}function Lr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function $r(){this.head=null,this.tail=null,this.length=0}vr.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]},vr.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},$r.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},$r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},$r.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}},$r.prototype.clear=function(){this.head=this.tail=null,this.length=0},$r.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},$r.prototype.concat=function(e){if(0===this.length)return gt.alloc(0);if(1===this.length)return this.head.data;for(var t=gt.allocUnsafe(e>>>0),r=this.head,i=0;r;)r.data.copy(t,i),i+=r.data.length,r=r.next;return t};var Mr=gt.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 Ur(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!Mr(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=Fr;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Br;break;default:return void(this.write=qr)}this.charBuffer=new gt(6),this.charReceived=0,this.charLength=0}function qr(e){return e.toString(this.encoding)}function Fr(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Br(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}Ur.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},Ur.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},Ur.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},Kr.ReadableState=Vr;var zr=function(e){if(Ar(br)&&(br=pr.env.NODE_DEBUG||""),e=e.toUpperCase(),!wr[e])if(new RegExp("\\b"+e+"\\b","i").test(br)){wr[e]=function(){var t=mr.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else wr[e]=function(){};return wr[e]}("stream");function Vr(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof wi&&(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 $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=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new Ur(e.encoding),this.encoding=e.encoding)}function Kr(e){if(!(this instanceof Kr))return new Kr(e);this._readableState=new Vr(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Oe.call(this)}function Hr(e,t,r,i,s){var n=function(e,t){var r=null;gt.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,Jr(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&&Jr(e))),function(e,t){t.readingMore||(t.readingMore=!0,lr(Qr,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)}fr(Kr,Oe),Kr.prototype.push=function(e,t){var r=this._readableState;return r.objectMode||"string"!=typeof e||(t=t||r.defaultEncoding)!==r.encoding&&(e=gt.from(e,t),t=""),Hr(this,r,e,t,!1)},Kr.prototype.unshift=function(e){return Hr(this,this._readableState,e,"",!0)},Kr.prototype.isPaused=function(){return!1===this._readableState.flowing},Kr.prototype.setEncoding=function(e){return this._readableState.decoder=new Ur(e),this._readableState.encoding=e,this};var Wr=8388608;function Gr(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>=Wr?e=Wr:(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 Jr(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(zr("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?lr(Yr,e):Yr(e))}function Yr(e){zr("emit readable"),e.emit("readable"),ei(e)}function Qr(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(zr("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=!1}function Xr(e){zr("readable nexttick read 0"),e.read(0)}function Zr(e,t){t.reading||(zr("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),ei(e),t.flowing&&!t.reading&&e.read(0)}function ei(e){var t=e._readableState;for(zr("flow",t.flowing);t.flowing&&null!==e.read(););}function ti(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=gt.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 ri(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,lr(ii,t,e))}function ii(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function si(e,t){for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function ni(){}function oi(e,t,r){this.chunk=e,this.encoding=t,this.callback=r,this.next=null}function ai(e,t){Object.defineProperty(this,"buffer",{get:yr(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),e=e||{},this.objectMode=!!e.objectMode,t instanceof wi&&(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?lr(s,i):s(i);e._writableState.errorEmitted=!0,e.emit("error",i)}(e,r,i,t,s);else{var n=di(r);n||r.corked||r.bufferProcessing||!r.bufferedRequest||hi(e,r),i?lr(li,e,r,n,s):li(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 gi(this)}function ci(e){if(!(this instanceof ci||this instanceof wi))return new ci(e);this._writableState=new ai(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev)),Oe.call(this)}function ui(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 li(e,t,r,i){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,i(),pi(e,t)}function hi(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;ui(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 gi(t)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(ui(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 di(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function fi(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function pi(e,t){var r=di(t);return r&&(0===t.pendingcb?(fi(e,t),t.finished=!0,e.emit("finish")):fi(e,t)),r}function gi(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}}Kr.prototype.read=function(e){zr("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 zr("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ri(this):Jr(this),null;if(0===(e=Gr(e,t))&&t.ended)return 0===t.length&&ri(this),null;var i,s=t.needReadable;return zr("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&zr("length less than watermark",s=!0),t.ended||t.reading?zr("reading or ended",s=!1):s&&(zr("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=Gr(r,t))),null===(i=e>0?ti(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ri(this)),null!==i&&this.emit("data",i),i},Kr.prototype._read=function(e){this.emit("error",new Error("not implemented"))},Kr.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,zr("pipe count=%d opts=%j",i.pipesCount,t);var s=!t||!1!==t.end?o:u;function n(e){zr("onunpipe"),e===r&&u()}function o(){zr("onend"),e.end()}i.endEmitted?lr(s):r.once("end",s),e.on("unpipe",n);var a=function(e){return function(){var t=e._readableState;zr("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,ei(e))}}(r);e.on("drain",a);var c=!1;function u(){zr("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",a),e.removeListener("error",d),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){zr("ondata"),l=!1,!1!==e.write(t)||l||((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==si(i.pipes,e))&&!c&&(zr("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function d(t){var r;zr("onerror",t),g(),e.removeListener("error",d),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){zr("onfinish"),e.removeListener("close",f),g()}function g(){zr("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",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),i.flowing||(zr("pipe resume"),r.resume()),e},Kr.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=si(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},Kr.prototype.on=function(e,t){var r=Oe.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&&Jr(this):lr(Xr,this))}return r},Kr.prototype.addListener=Kr.prototype.on,Kr.prototype.resume=function(){var e=this._readableState;return e.flowing||(zr("resume"),e.flowing=!0,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,lr(Zr,e,t))}(this,e)),this},Kr.prototype.pause=function(){return zr("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(zr("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Kr.prototype.wrap=function(e){var t=this._readableState,r=!1,i=this;for(var s in e.on("end",function(){if(zr("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){(zr("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){zr("wrapped _read",t),r&&(r=!1,e.resume())},i},Kr._fromList=ti,ci.WritableState=ai,fr(ci,Oe),ai.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},ci.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},ci.prototype.write=function(e,t,r){var i=this._writableState,s=!1;return"function"==typeof t&&(r=t,t=null),gt.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=ni),i.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),lr(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"):gt.isBuffer(r)||"string"==typeof r||void 0===r||t.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n&&(e.emit("error",n),lr(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=gt.from(t,r));return t}(t,r,i),gt.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 oi(r,i,s),a?a.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else ui(e,t,!1,n,r,i,s);return o}(this,i,e,t,r)),s},ci.prototype.cork=function(){this._writableState.corked++},ci.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||hi(this,e))},ci.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},ci.prototype._write=function(e,t,r){r(new Error("not implemented"))},ci.prototype._writev=null,ci.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,pi(e,t),r&&(t.finished?lr(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,i,r)},fr(wi,Kr);for(var mi=Object.keys(ci.prototype),yi=0;yi<mi.length;yi++){var bi=mi[yi];wi.prototype[bi]||(wi.prototype[bi]=ci.prototype[bi])}function wi(e){if(!(this instanceof wi))return new wi(e);Kr.call(this,e),ci.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",vi)}function vi(){this.allowHalfOpen||this._writableState.ended||lr(Oi,this)}function Oi(e){e.end()}function ki(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 Si(e){if(!(this instanceof Si))return new Si(e);wi.call(this,e),this._transformState=new ki(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){_i(t,e)}):_i(t)})}function _i(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 Ri(e){if(!(this instanceof Ri))return new Ri(e);Si.call(this,e)}function ji(){Oe.call(this)}fr(Si,wi),Si.prototype.push=function(e,t){return this._transformState.needTransform=!1,wi.prototype.push.call(this,e,t)},Si.prototype._transform=function(e,t,r){throw new Error("Not implemented")},Si.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)}},Si.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},fr(Ri,Si),Ri.prototype._transform=function(e,t,r){r(null,e)},fr(ji,Oe),ji.Readable=Kr,ji.Writable=ci,ji.Duplex=wi,ji.Transform=Si,ji.PassThrough=Ri,ji.Stream=ji,ji.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===Oe.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 Ei extends Oe{constructor({resource:e}){super(),this.resource=e,this.client=e.client,this.stream=new d.ReadableStream({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){}}class Ni extends Ei{enqueue(e){this.controller.enqueue(e),this.emit("page",e)}}class Ai extends Oe{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 Ni({resource:this.resource}),this.transform=new Si({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[i,s]=await I(async()=>{await c.PromisePool.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(s)}resume(){this.input.resume()}}class Ii extends Oe{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 ci({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 I(async()=>{await c.PromisePool.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const[t,r,i]=await I(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 Di(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")))})}class xi extends Oe{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=q,passphrase:a="secret",parallelism:c=10,observers:u=[],cache:l=!1,autoDecrypt:h=!0,timestamps:d=!1,partitions:f={},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:d,partitions:f,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(e,r){return"function"==typeof e?e:"number"==typeof e&&e>0?t.customAlphabet(t.urlAlphabet,e):"number"==typeof r&&r>0&&22!==r?t.customAlphabet(t.urlAlphabet,r):ye}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 Ze({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:n.cloneDeep(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 Te("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?Te(`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(),d=await this.schema.mapper(l);d._v=String(this.version);const f=M(this.behavior),{mappedData:p,body:g}=await f.handleInsert({resource:this,data:l,mappedData:d,originalData:r}),m=p,b=this.getResourceKey(h);let v;if(g&&""!==g){const[e,t]=await I(()=>Promise.resolve(JSON.parse(g)));e&&(v="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[O,k,S]=await I(()=>this.client.putObject({key:b,body:g,contentType:v,metadata:m}));if(!O){const e=k&&k.message?k.message:"";if(e.includes("metadata headers exceed")||e.includes("Insert failed")){const e=y(m),t=w({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=e-t;throw k.totalSize=e,k.limit=2047,k.effectiveLimit=t,k.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(k,{bucket:this.client.config.bucket,key:b,resourceName:this.name,operation:"insert",id:h})}let _=await this.composeFullObjectFromWrite({id:h,metadata:m,body:g,behavior:this.behavior});const R=await this.executeHooks("afterInsert",_);return this.emit("insert",{..._,$before:{...r},$after:{...R}}),R}async get(e){if(n.isObject(e))throw new Error("id cannot be an object");if(n.isEmpty(e))throw new Error("id cannot be empty");const t=this.getResourceKey(e),[r,i,s]=await I(()=>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 o=s.Metadata?._v||this.version,a="string"==typeof o&&o.startsWith("v")?o.slice(1):o,c=await this.getSchemaForVersion(a);let u=await c.unmapper(s.Metadata);const l=M(this.behavior);let h="";if(s.ContentLength>0){const[e,r,i]=await I(()=>this.client.getObject(t));h=e?await Di(i.Body):""}const{metadata:d}=await l.handleGet({resource:this,metadata:u,body:h});let f=await this.composeFullObjectFromWrite({id:e,metadata:d,body:h,behavior:this.behavior});f._contentLength=s.ContentLength,f._lastModified=s.LastModified,f._hasContent=s.ContentLength>0,f._mimeType=s.ContentType||null,f._v=a,s.VersionId&&(f._versionId=s.VersionId),s.Expiration&&(f._expiresAt=s.Expiration),f._definitionHash=this.getDefinitionHash(),a!==this.version&&(f=await this.applyVersionMapping(f,a,this.version)),this.emit("get",f);return f}async exists(e){const t=this.getResourceKey(e),[r,i]=await I(()=>this.client.headObject(t));return r}async update(e,t){if(n.isEmpty(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=n.cloneDeep(t);let s=n.cloneDeep(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]]=n.cloneDeep(t)}else"object"!=typeof t||null===t||Array.isArray(t)?s[e]=n.cloneDeep(t):s[e]=n.merge({},s[e],t);if(this.config.timestamps){const e=(new Date).toISOString();s.updatedAt=e,s.metadata||(s.metadata={}),s.metadata.updatedAt=e}const o=await this.executeHooks("beforeUpdate",n.cloneDeep(s)),a={...r,...o,id:e},{isValid:c,errors:u,data:l}=await this.validate(n.cloneDeep(a));if(!c)throw new re({bucket:this.client.config.bucket,resourceName:this.name,attributes:o,validation:u,message:"validation: "+(u&&u.length?JSON.stringify(u):"unknown")});await this.schema.mapper(l);const h=M(this.behavior),d=await this.schema.mapper({...r,...o});d._v=String(this.version),await h.handleUpdate({resource:this,id:e,data:{...r,...o},mappedData:d,originalData:{...i,id:e}});const{id:f,...p}=l,g={...r,id:e},m={...p,id:e};await this.handlePartitionReferenceUpdates(g,m);const b=await this.schema.mapper(p);b._v=String(this.version);const v=M(this.behavior),{mappedData:O,body:k}=await v.handleUpdate({resource:this,id:e,data:p,mappedData:b,originalData:{...i,id:e}}),S=O,_=this.getResourceKey(e);let R,j=k;if(""===k&&"body-overflow"!==this.behavior){const[e,t,r]=await I(()=>this.client.getObject(_));if(e&&r.ContentLength>0){const e=Buffer.from(await r.Body.transformToByteArray()),t=e.toString(),[i,s]=await I(()=>Promise.resolve(JSON.parse(t)));i||(j=e,R=r.ContentType)}}let E=R;if(j&&""!==j&&!E){const[e,t]=await I(()=>Promise.resolve(JSON.parse(j)));e&&(E="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(e,r);const[N,A]=await I(()=>this.client.putObject({key:_,body:j,contentType:E,metadata:S}));if(!N&&A&&A.message&&A.message.includes("metadata headers exceed")){const t=y(S),r=w({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:e}}),i=t-r;throw A.totalSize=t,A.limit=2047,A.effectiveLimit=r,A.excess=i,this.emit("exceedsLimit",{operation:"update",totalSize:t,limit:2047,effectiveLimit:r,excess:i,data:p}),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(!N)throw ne(A,{bucket:this.client.config.bucket,key:_,resourceName:this.name,operation:"update",id:e});const D=await this.composeFullObjectFromWrite({id:e,metadata:S,body:j,behavior:this.behavior}),x=await this.executeHooks("afterUpdate",D);return this.emit("update",{...D,$before:{...r},$after:{...x}}),x}async delete(e){if(n.isEmpty(e))throw new Error("id cannot be empty");let t,r=null;const[i,s,o]=await I(()=>this.get(e));i?t=o:(t={id:e},r=s),await this.executeHooks("beforeDelete",t);const a=this.getResourceKey(e),[c,u,l]=await I(()=>this.client.deleteObject(a));if(this.emit("delete",{...t,$before:{...t},$after:null}),r)throw ne(r,{bucket:this.client.config.bucket,key:a,resourceName:this.name,operation:"delete",id:e});if(!c)throw ne(u,{key:a,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 c.PromisePool.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.chunk(e.map(e=>this.getResourceKey(e)),1e3);e.map(e=>this.getResourceKey(e));const{results:r}=await c.PromisePool.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 I(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 I(()=>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 I(()=>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:i}=await c.PromisePool.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 I(()=>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,i){const s=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t)),{results:n,errors:o}=await c.PromisePool.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,n,o]=await I(async()=>{const r=this.extractPartitionValuesFromKey(e,i,s);return await this.getFromPartition({id:e,partitionName:t,partitionValues:r})});return r?o:this.handleResourceError(n,e,"partition")});return n.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 c.PromisePool.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 I(()=>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 I(()=>this.listIds());if(!e)throw t;const i=[];for(const e of r){const[t,r,s]=await I(()=>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 I(async()=>{let n=null,o=null;if(!s){const[e,s,a]=await I(()=>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 I(()=>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 Ai({resource:this}).build()}writable(){return new Ii({resource:this}).build()}async setContent({id:e,buffer:t,contentType:r="application/octet-stream"}){const[i,s,n]=await I(()=>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 I(()=>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 I(()=>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 I(()=>this.client.headObject(t));return!!r&&s.ContentLength>0}async deleteContent(e){const t=this.getResourceKey(e),[r,i,s]=await I(()=>this.client.headObject(t));if(!r)throw i;const n=s.Metadata||{},[o,a,c]=await I(()=>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=a(e);return`sha256:${o.createHash("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 I(()=>Promise.resolve(new Ze({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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(async()=>{await this.client.deleteObject(n)})}if(o){const[e,t]=await I(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 I(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 I(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=Te(`resource=${this.name}`,`partition=${t}`,...s,`id=${e}`),[a,c]=await I(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=Te(`resource=${this.name}`,"historical",`id=${e}`),i={...t,_v:t._v||this.version,_historicalTimestamp:(new Date).toISOString()},s=await this.schema.mapper(i),n=M(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 I(()=>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 I(()=>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]=D(()=>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 I(()=>Promise.resolve(JSON.parse(r)));if(e){const[e,t,r]=await I(()=>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 I(()=>Promise.resolve(r?JSON.parse(r):{}));let o=this.schema.map;if(t&&t._map){const[e,r,i]=await I(()=>Promise.resolve("string"==typeof t._map?JSON.parse(t._map):t._map));o=e?i:this.schema.map}const[a,c,u]=await I(()=>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 d=u(h);return s.$truncated&&(d.$truncated=s.$truncated),s.$overflow&&(d.$overflow=s.$overflow),d}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}}class Pi extends Oe{constructor(e){super(),this.version="1",this.s3dbVersion=(()=>{const[e,t,r]=I(()=>"7.0.1");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 We({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 Di(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 xi({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=a(i);return`sha256:${o.createHash("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(!n.isEmpty(this.pluginList)){const t=this.pluginList.map(e=>n.isFunction(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 xi({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 xi({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 Ci extends Pi{}function Ti(e){return"string"==typeof e?e.trim().toLowerCase():e}const Li={s3db:class extends ze{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[Ti(e)]=e)}else"string"==typeof t&&(i[Ti(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[Ti(r)]=r:Array.isArray(r)&&"string"==typeof r[0]?t[Ti(r[0])]=r:"object"==typeof r&&r.resource&&(t[Ti(r.resource)]={...r});return t}if("object"==typeof e){const t={};for(const[r,i]of Object.entries(e)){const e=Ti(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{[Ti(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 Ci(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=Ti(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=Ti(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=Ti(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=Ti(e),i=t.find(e=>Ti(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 I(()=>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 I(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=Ti(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}},sqs:class extends ze{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 I(()=>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 I(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 I(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 I(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 I(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:class extends ze{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"]}]: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.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(", ")}`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,i]=await I(()=>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=>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 I(async()=>{const s=this.bigqueryClient.dataset(this.datasetId);for(const e of n){const[n,c]=await I(async()=>{const n=s.table(e);let a;if("insert"===t){const e={...r};a=await n.insert([e])}else if("update"===t){const t=Object.keys(r).filter(e=>"id"!==e),s=t.map(e=>`${e}=@${e}`).join(", "),n={id:i};t.forEach(e=>{n[e]=r[e]});const o=`UPDATE \`${this.projectId}.${this.datasetId}.${e}\` SET ${s} WHERE id=@id`,[c]=await this.bigqueryClient.createQueryJob({query:o,params:n});await c.getQueryResults(),a=[c]}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM \`${this.projectId}.${this.datasetId}.${e}\` WHERE id=@id`,[r]=await this.bigqueryClient.createQueryJob({query:t,params:{id:i}});await r.getQueryResults(),a=[r]}}o.push({table:e,success:!0,jobId:a[0]?.id})});n||a.push({table:e,error:c.message})}if(this.logTable){const[n,o]=await I(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,results:o,errors:a,success:c}),{success:c,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 I(()=>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 I(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}}},postgres:class extends ze{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 I(()=>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 I(async()=>{for(const e of n){const[s,n]=await I(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 I(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 I(()=>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 I(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}}}};function $i(e,t={},r=[],i=null){const s=Li[e];if(!s)throw new Error(`Unknown replicator driver: ${e}. Available drivers: ${Object.keys(Li).join(", ")}`);return new s(t,r,i)}function Mi(e){return"string"==typeof e?e.trim().toLowerCase():e}return e.AVAILABLE_BEHAVIORS=U,e.AuditPlugin=class extends Ee{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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(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?D(()=>JSON.parse(e.oldData)):[!0,null,e.oldData],[i,,s]="string"==typeof e.newData?D(()=>JSON.parse(e.newData)):[!0,null,e.newData],[n,,o]=e.partitionValues&&"string"==typeof e.partitionValues?D(()=>JSON.parse(e.partitionValues)):[!0,null,e.partitionValues],[a,,c]=e.metadata&&"string"==typeof e.metadata?D(()=>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}},e.AuthenticationError=class extends G{constructor(e,t={}){super(e,t),Object.assign(this,t)}},e.BaseError=W,e.CachePlugin=class extends Ee{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 Fe(this.config.memoryOptions||{}):this.driver=new qe({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 I(()=>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 I(()=>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=Te(r,`partition=${t}`);await e.cache.clear(i)}}else for(const t of Object.keys(e.config.partitions)){const i=Te(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 Te(...n)+".json.gz"}async hashParams(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("|")||"empty";return await de(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})}}}},e.Client=We,e.ConnectionString=He,e.ConnectionStringError=oe,e.CostsPlugin=Be,e.CryptoError=ae,e.DEFAULT_BEHAVIOR=q,e.Database=Pi,e.DatabaseError=class extends G{constructor(e,t={}){super(e,t),Object.assign(this,t)}},e.EncryptionError=class extends G{constructor(e,t={}){super(e,t),Object.assign(this,t)}},e.ErrorMap=se,e.FullTextPlugin=class extends Ee{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 I(()=>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 I(()=>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 I(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 I(()=>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 I(()=>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()}},e.InvalidResourceItem=re,e.MetricsPlugin=class extends Ee{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 I(async()=>{const[t,r,i]=await I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(()=>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 I(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)}}},e.MissingMetadata=te,e.NoSuchBucket=X,e.NoSuchKey=Z,e.NotFound=ee,e.PartitionError=le,e.PermissionError=Y,e.Plugin=Ee,e.PluginObject=Ne,e.ReplicatorPlugin=class extends Ee{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 I(()=>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 I(()=>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[Mi(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[Mi(this.config.replicatorLogResource)]=t,this.replicatorLog=t,this.config.verbose&&console.log("[PLUGIN] Log resource created and registered:",this.config.replicatorLogResource,!!e.resources[Mi(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)Mi(t)!==Mi(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t]);e.on("connected",()=>{for(const t in e.resources)Mi(t)!==Mi(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=$i(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 o=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}:`,o.map(e=>e.driver)),0===o.length)return void(this.config.verbose&&console.log("[PLUGIN] No applicable replicators for resource",e));const a=this.filterInternalFields(n.isPlainObject(i)?i:{raw:i}),c=s?this.filterInternalFields(n.isPlainObject(s)?s:{raw:s}):null,u={id:`repl-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e,operation:t,recordId:r,data:a,beforeData:c,timestamp:(new Date).toISOString(),attempts:0},l=await this.logreplicator(u),[h,d,f]=await I(async()=>this.processreplicatorItem(u));h?(l&&await this.updatereplicatorLog(l,{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++):(l&&await this.updatereplicatorLog(l,{status:"failed",attempts:1,error:d.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 I(()=>i.instance.replicate({resource:e.resourceName,operation:e.operation,data:e.data,id:e.recordId,beforeData:e.beforeData})):[s,n,t]=await I(()=>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[Mi(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 I(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 I(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(Mi(r)!==Mi("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")}},e.Resource=xi,e.ResourceError=ue,e.ResourceIdsPageReader=Ni,e.ResourceIdsReader=Ei,e.ResourceNotFound=Q,e.ResourceReader=Ai,e.ResourceWriter=Ii,e.S3_DEFAULT_ENDPOINT=Ke,e.S3_DEFAULT_REGION=Ve,e.S3db=Ci,e.S3dbError=G,e.Schema=Ze,e.SchemaActions=Xe,e.SchemaError=ce,e.UnknownError=ie,e.ValidationError=J,e.Validator=Ye,e.ValidatorManager=Qe,e.behaviors=$,e.calculateAttributeNamesSize=p,e.calculateAttributeSizes=m,e.calculateEffectiveLimit=w,e.calculateSystemOverhead=b,e.calculateTotalSize=y,e.calculateUTF8Bytes=f,e.decode=V,e.decodeDecimal=H,e.decrypt=pe,e.default=Ci,e.encode=z,e.encodeDecimal=K,e.encrypt=fe,e.getBehavior=M,e.getSizeBreakdown=function(e){const t=m(e),r=p(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}}},e.idGenerator=ye,e.mapAwsError=ne,e.md5=ge,e.passwordGenerator=be,e.sha256=de,e.streamToString=Di,e.transformValue=g,e.tryFn=I,e.tryFnSync=D,Object.defineProperty(e,"__esModule",{value:!0}),e}({},nanoid,zlib,index_js,0,lodashEs,crypto,jsonStableStringify,promisePool,clientS3,flat,FastestValidator,web);
|