s3db.js 5.2.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1142 -612
- package/dist/s3db.cjs.js +3541 -484
- package/dist/s3db.cjs.min.js +1 -31
- package/dist/s3db.d.ts +891 -62
- package/dist/s3db.es.js +3539 -486
- package/dist/s3db.es.min.js +1 -31
- package/dist/s3db.iife.js +3541 -484
- package/dist/s3db.iife.min.js +1 -31
- package/package.json +33 -14
package/dist/s3db.cjs.min.js
CHANGED
|
@@ -1,31 +1 @@
|
|
|
1
|
-
/* istanbul ignore file */
|
|
2
|
-
"use strict";var $c=Object.create;var Zi=Object.defineProperty;var Bc=Object.getOwnPropertyDescriptor;var Uc=Object.getOwnPropertyNames;var zc=Object.getPrototypeOf,Zc=Object.prototype.hasOwnProperty;var qc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Uc(t))!Zc.call(e,i)&&i!==r&&Zi(e,i,{get:()=>t[i],enumerable:!(n=Bc(t,i))||n.enumerable});return e};var Hc=(e,t,r)=>(r=e!=null?$c(zc(e)):{},qc(t||!e||!e.__esModule?Zi(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,"__esModule",{value:!0});var $r=require("nanoid"),L=require("lodash-es"),de=require("@supercharge/promise-pool"),pe=require("@aws-sdk/client-s3"),qi=require("crypto"),rr=require("flat"),Kc=require("fastest-validator"),Vc=require("node:stream/web");function Hi(e,t){for(var r=0,n=e.length-1;n>=0;n--){var i=e[n];i==="."?e.splice(n,1):i===".."?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}var Wc=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,Br=function(e){return Wc.exec(e).slice(1)};function Ur(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:"/";if(typeof n!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!n)continue;e=n+"/"+e,t=n.charAt(0)==="/"}return e=Hi(zr(e.split("/"),function(i){return!!i}),!t).join("/"),(t?"/":"")+e||"."}function Ki(e){var t=Vi(e),r=tf(e,-1)==="/";return e=Hi(zr(e.split("/"),function(n){return!!n}),!t).join("/"),!e&&!t&&(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function Vi(e){return e.charAt(0)==="/"}function xe(){var e=Array.prototype.slice.call(arguments,0);return Ki(zr(e,function(t,r){if(typeof t!="string")throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))}function Gc(e,t){e=Ur(e).substr(1),t=Ur(t).substr(1);function r(c){for(var l=0;l<c.length&&c[l]==="";l++);for(var d=c.length-1;d>=0&&c[d]==="";d--);return l>d?[]:c.slice(l,d-l+1)}for(var n=r(e.split("/")),i=r(t.split("/")),a=Math.min(n.length,i.length),o=a,s=0;s<a;s++)if(n[s]!==i[s]){o=s;break}for(var f=[],s=o;s<n.length;s++)f.push("..");return f=f.concat(i.slice(o)),f.join("/")}var Yc="/",Jc=":";function Xc(e){var t=Br(e),r=t[0],n=t[1];return!r&&!n?".":(n&&(n=n.substr(0,n.length-1)),r+n)}function Qc(e,t){var r=Br(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r}function ef(e){return Br(e)[3]}var ye={extname:ef,basename:Qc,dirname:Xc,sep:Yc,delimiter:Jc,relative:Gc,join:xe,isAbsolute:Vi,normalize:Ki,resolve:Ur};function zr(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n<e.length;n++)t(e[n],n,e)&&r.push(e[n]);return r}var tf="ab".substr(-1)==="b"?function(e,t,r){return e.substr(t,r)}:function(e,t,r){return t<0&&(t=e.length+t),e.substr(t,r)};const Zr=$r.customAlphabet($r.urlAlphabet,22),rf="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",nf=$r.customAlphabet(rf,12);var qr;function Te(){}Te.prototype=Object.create(null);function R(){R.init.call(this)}R.EventEmitter=R,R.usingDomains=!1,R.prototype.domain=void 0,R.prototype._events=void 0,R.prototype._maxListeners=void 0,R.defaultMaxListeners=10,R.init=function(){this.domain=null,R.usingDomains&&qr.active&&!(this instanceof qr.Domain)&&(this.domain=qr.active),(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new Te,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},R.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this};function Wi(e){return e._maxListeners===void 0?R.defaultMaxListeners:e._maxListeners}R.prototype.getMaxListeners=function(){return Wi(this)};function af(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Ot(e,n),a=0;a<n;++a)i[a].call(r)}function of(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,a=Ot(e,i),o=0;o<i;++o)a[o].call(r,n)}function sf(e,t,r,n,i){if(t)e.call(r,n,i);else for(var a=e.length,o=Ot(e,a),s=0;s<a;++s)o[s].call(r,n,i)}function cf(e,t,r,n,i,a){if(t)e.call(r,n,i,a);else for(var o=e.length,s=Ot(e,o),f=0;f<o;++f)s[f].call(r,n,i,a)}function ff(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,a=Ot(e,i),o=0;o<i;++o)a[o].apply(r,n)}R.prototype.emit=function(t){var r,n,i,a,o,s,f,c=t==="error";if(s=this._events,s)c=c&&s.error==null;else if(!c)return!1;if(f=this.domain,c){if(r=arguments[1],f)r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=f,r.domainThrown=!1,f.emit("error",r);else{if(r instanceof Error)throw r;var l=new Error('Uncaught, unspecified "error" event. ('+r+")");throw l.context=r,l}return!1}if(n=s[t],!n)return!1;var d=typeof n=="function";switch(i=arguments.length,i){case 1:af(n,d,this);break;case 2:of(n,d,this,arguments[1]);break;case 3:sf(n,d,this,arguments[1],arguments[2]);break;case 4:cf(n,d,this,arguments[1],arguments[2],arguments[3]);break;default:for(a=new Array(i-1),o=1;o<i;o++)a[o-1]=arguments[o];ff(n,d,this,a)}return!0};function Gi(e,t,r,n){var i,a,o;if(typeof r!="function")throw new TypeError('"listener" argument must be a function');if(a=e._events,a?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),o=a[t]):(a=e._events=new Te,e._eventsCount=0),!o)o=a[t]=r,++e._eventsCount;else if(typeof o=="function"?o=a[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=Wi(e),i&&i>0&&o.length>i)){o.warned=!0;var s=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");s.name="MaxListenersExceededWarning",s.emitter=e,s.type=t,s.count=o.length,lf(s)}return e}function lf(e){typeof console.warn=="function"?console.warn(e):console.log(e)}R.prototype.addListener=function(t,r){return Gi(this,t,r,!1)},R.prototype.on=R.prototype.addListener,R.prototype.prependListener=function(t,r){return Gi(this,t,r,!0)};function Yi(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}R.prototype.once=function(t,r){if(typeof r!="function")throw new TypeError('"listener" argument must be a function');return this.on(t,Yi(this,t,r)),this},R.prototype.prependOnceListener=function(t,r){if(typeof r!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(t,Yi(this,t,r)),this},R.prototype.removeListener=function(t,r){var n,i,a,o,s;if(typeof r!="function")throw new TypeError('"listener" argument must be a function');if(i=this._events,!i)return this;if(n=i[t],!n)return this;if(n===r||n.listener&&n.listener===r)--this._eventsCount===0?this._events=new Te:(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(a=-1,o=n.length;o-- >0;)if(n[o]===r||n[o].listener&&n[o].listener===r){s=n[o].listener,a=o;break}if(a<0)return this;if(n.length===1){if(n[0]=void 0,--this._eventsCount===0)return this._events=new Te,this;delete i[t]}else uf(n,a);i.removeListener&&this.emit("removeListener",t,s||r)}return this},R.prototype.off=function(e,t){return this.removeListener(e,t)},R.prototype.removeAllListeners=function(t){var r,n;if(n=this._events,!n)return this;if(!n.removeListener)return arguments.length===0?(this._events=new Te,this._eventsCount=0):n[t]&&(--this._eventsCount===0?this._events=new Te:delete n[t]),this;if(arguments.length===0){for(var i=Object.keys(n),a=0,o;a<i.length;++a)o=i[a],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=new Te,this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r)do this.removeListener(t,r[r.length-1]);while(r[0]);return this},R.prototype.listeners=function(t){var r,n,i=this._events;return i?(r=i[t],r?typeof r=="function"?n=[r.listener||r]:n=hf(r):n=[]):n=[],n},R.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):Ji.call(e,t)},R.prototype.listenerCount=Ji;function Ji(e){var t=this._events;if(t){var r=t[e];if(typeof r=="function")return 1;if(r)return r.length}return 0}R.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function uf(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}function Ot(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}function hf(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}class Xi extends Error{constructor({verbose:t,bucket:r,message:n,...i}){t&&(n=n+`
|
|
3
|
-
|
|
4
|
-
Verbose:
|
|
5
|
-
|
|
6
|
-
${JSON.stringify(i,null,2)}`),super(n),typeof Error.captureStackTrace=="function"?Error.captureStackTrace(this,this.constructor):this.stack=new Error(n).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=r,this.thrownAt=new Date}toJson(){return{...this}}toString(){return`${this.name} | ${this.message}`}}class ie extends Xi{constructor(t,r={}){super({message:t,...r})}}class df extends ie{constructor(t,r={}){super(t,r),Object.assign(this,r)}}class pf extends ie{constructor(t,r={}){super(t,r),Object.assign(this,r)}}class yf extends ie{constructor(t,r={}){super(t,r),Object.assign(this,r)}}class gf extends ie{constructor(t,r={}){super(t,r),Object.assign(this,r)}}class vf extends ie{constructor(t,r={}){super(t,r),Object.assign(this,r)}}class wf extends ie{constructor({bucket:t,resourceName:r,id:n,...i}){super(`Resource not found: ${r}/${n} [bucket:${t}]`,{bucket:t,resourceName:r,id:n,...i})}}class Qi extends ie{constructor({bucket:t,...r}){super(`Bucket does not exists [bucket:${t}]`,{bucket:t,...r})}}class Hr extends ie{constructor({bucket:t,key:r,...n}){super(`Key [${r}] does not exists [bucket:${t}/${r}]`,{bucket:t,key:r,...n})}}class ea extends Hr{}class ta extends ie{constructor({bucket:t,...r}){super(`Missing metadata for bucket [bucket:${t}]`,{bucket:t,...r})}}class nr extends ie{constructor({bucket:t,resourceName:r,attributes:n,validation:i}){super(`This item is not valid. Resource=${r} [bucket:${t}].
|
|
7
|
-
${JSON.stringify(i,null,2)}`,{bucket:t,resourceName:r,attributes:n,validation:i})}}class ra extends ie{}const na={NotFound:ea,NoSuchKey:Hr,UnknownError:ra,NoSuchBucket:Qi,MissingMetadata:ta,InvalidResourceItem:nr},ia="us-east-1",aa="https://s3.us-east-1.amazonaws.com";class oa{constructor(t){let r;try{r=new URL(t)}catch{throw new Error("Invalid connection string: "+t)}this.region=ia,r.protocol==="s3:"?this.defineS3(r):this.defineMinio(r);for(const[n,i]of r.searchParams.entries())this[n]=i}defineS3(t){if(this.bucket=decodeURIComponent(t.hostname),this.accessKeyId=decodeURIComponent(t.username),this.secretAccessKey=decodeURIComponent(t.password),this.endpoint=aa,["/","",null].includes(t.pathname))this.keyPrefix="";else{let[,...r]=t.pathname.split("/");this.keyPrefix=[...r||[]].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[,r,...n]=t.pathname.split("/");this.bucket=decodeURIComponent(r),this.keyPrefix=[...n||[]].join("/")}}}class sa extends R{constructor({verbose:t=!1,id:r=null,AwsS3Client:n,connectionString:i,parallelism:a=10}){super(),this.verbose=t,this.id=r??Zr(),this.parallelism=a,this.config=new oa(i),this.client=n||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 pe.S3Client(t)}async sendCommand(t){this.emit("command.request",t.constructor.name,t.input);const r=console.warn;try{console.warn=i=>{i.includes("Stream of unknown length")||r(i)}}catch(i){console.error(i)}const n=await this.client.send(t);this.emit("command.response",t.constructor.name,n,t.input);try{console.warn=r}catch(i){console.error(i)}return n}errorProxy(t,r){this.verbose&&(r.bucket=this.config.bucket,r.config=this.config,r.verbose=this.verbose),t.data=r;const n=na[t.name];return n?new n(r):t}async putObject({key:t,metadata:r,contentType:n,body:i,contentEncoding:a}){const o={Bucket:this.config.bucket,Key:this.config.keyPrefix?ye.join(this.config.keyPrefix,t):t,Metadata:{...r},Body:i||Buffer.alloc(0)};n!==void 0&&(o.ContentType=n),a!==void 0&&(o.ContentEncoding=a);try{const s=await this.sendCommand(new pe.PutObjectCommand(o));return this.emit("putObject",s,o),s}catch(s){throw this.errorProxy(s,{key:t,command:o})}}async getObject(t){const r={Bucket:this.config.bucket,Key:ye.join(this.config.keyPrefix,t)};try{const n=await this.sendCommand(new pe.GetObjectCommand(r));return this.emit("getObject",n,r),n}catch(n){throw this.errorProxy(n,{key:t,command:r})}}async headObject(t){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?ye.join(this.config.keyPrefix,t):t};try{const n=await this.sendCommand(new pe.HeadObjectCommand(r));return this.emit("headObject",n,r),n}catch(n){throw this.errorProxy(n,{key:t,command:r})}}async copyObject({from:t,to:r}){const n={Bucket:this.config.bucket,Key:this.config.keyPrefix?ye.join(this.config.keyPrefix,r):r,CopySource:ye.join(this.config.bucket,this.config.keyPrefix?ye.join(this.config.keyPrefix,t):t)};try{const i=await this.client.send(new pe.CopyObjectCommand(n));return this.emit("copyObject",i,n),i}catch(i){throw this.errorProxy(i,{from:t,to:r,command:n})}}async exists(t){try{return await this.headObject(t),!0}catch(r){if(r.name==="NoSuchKey")return!1;if(r.name==="NotFound")return!1;throw r}}async deleteObject(t){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?ye.join(this.config.keyPrefix,t):t};try{const n=await this.sendCommand(new pe.DeleteObjectCommand(r));return this.emit("deleteObject",n,r),n}catch(n){throw this.errorProxy(n,{key:t,command:r})}}async deleteObjects(t){const r=L.chunk(t,1e3),{results:n,errors:i}=await de.PromisePool.for(r).withConcurrency(this.parallelism).process(async o=>{const s={Bucket:this.config.bucket,Delete:{Objects:o.map(f=>({Key:this.config.keyPrefix?ye.join(this.config.keyPrefix,f):f}))}};try{return await this.sendCommand(new pe.DeleteObjectsCommand(s))}catch(f){throw this.errorProxy(f,{keys:o,command:s})}}),a={deleted:n,notFound:i};return this.emit("deleteObjects",a,t),a}async deleteAll({prefix:t}={}){let r,n=0;do{const i=new pe.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:this.config.keyPrefix?ye.join(this.config.keyPrefix,t):t,ContinuationToken:r}),a=await this.client.send(i);if(a.Contents&&a.Contents.length>0){const o=new pe.DeleteObjectsCommand({Bucket:this.config.bucket,Delete:{Objects:a.Contents.map(c=>({Key:c.Key}))}}),s=await this.client.send(o),f=s.Deleted?s.Deleted.length:0;n+=f,this.emit("deleteAll",{prefix:t,batch:f,total:n})}r=a.IsTruncated?a.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:t,totalDeleted:n}),n}async moveObject({from:t,to:r}){try{return await this.copyObject({from:t,to:r}),await this.deleteObject(t),!0}catch(n){throw this.errorProxy(n,{from:t,to:r,command:options})}}async listObjects({prefix:t,maxKeys:r=1e3,continuationToken:n}={}){const i={Bucket:this.config.bucket,MaxKeys:r,ContinuationToken:n,Prefix:this.config.keyPrefix?ye.join(this.config.keyPrefix,t||""):t||""};try{const a=await this.sendCommand(new pe.ListObjectsV2Command(i));return this.emit("listObjects",a,i),a}catch(a){throw this.errorProxy(a,{command:i})}}async count({prefix:t}={}){let r=0,n=!0,i;for(;n;){const a={prefix:t,continuationToken:i},o=await this.listObjects(a);r+=o.KeyCount||0,n=o.IsTruncated||!1,i=o.NextContinuationToken}return this.emit("count",r,{prefix:t}),r}async getAllKeys({prefix:t}={}){let r=[],n=!0,i;for(;n;){const a={prefix:t,continuationToken:i},o=await this.listObjects(a);o.Contents&&(r=r.concat(o.Contents.map(s=>s.Key))),n=o.IsTruncated||!1,i=o.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(a=>a.replace(this.config.keyPrefix,"")).map(a=>a.startsWith("/")?a.replace("/",""):a)),this.emit("getAllKeys",r,{prefix:t}),r}async getContinuationTokenAfterOffset(t={}){const{prefix:r,offset:n=1e3}=t;if(n===0)return null;let i=!0,a,o=0;for(;i;){let s=n<1e3?n:n-o>1e3?1e3:n-o;const f={prefix:r,maxKeys:s,continuationToken:a},c=await this.listObjects(f);if(c.Contents&&(o+=c.Contents.length),i=c.IsTruncated||!1,a=c.NextContinuationToken,o>=n)break}return this.emit("getContinuationTokenAfterOffset",a||null,t),a||null}async getKeysPage(t={}){const{prefix:r,offset:n=0,amount:i=100}=t;let a=[],o=!0,s;for(n>0&&(s=await this.getContinuationTokenAfterOffset({prefix:r,offset:n}));o;){const f={prefix:r,continuationToken:s},c=await this.listObjects(f);if(c.Contents&&(a=a.concat(c.Contents.map(l=>l.Key))),o=c.IsTruncated||!1,s=c.NextContinuationToken,a.length>i){a=a.splice(0,i);break}}return this.config.keyPrefix&&(a=a.map(f=>f.replace(this.config.keyPrefix,"")).map(f=>f.startsWith("/")?f.replace("/",""):f)),this.emit("getKeysPage",a,t),a}async moveAllObjects({prefixFrom:t,prefixTo:r}){const n=await this.getAllKeys({prefix:t}),{results:i,errors:a}=await de.PromisePool.for(n).withConcurrency(this.parallelism).process(async o=>{const s=o.replace(t,r);try{return await this.moveObject({from:o,to:s}),s}catch(f){throw this.errorProxy(f,{from:o,to:s})}});if(this.emit("moveAllObjects",{results:i,errors:a},{prefixFrom:t,prefixTo:r}),a.length>0)throw new Error("Some objects could not be moved");return i}}async function ir(){let e;if(typeof process<"u")try{const{webcrypto:t}=await import("crypto");e=t}catch{throw new Error("Crypto API not available")}else typeof window<"u"&&(e=window.crypto);if(!e)throw new Error("Could not load any crypto library");return e}async function ca(e){const t=await ir(),n=new TextEncoder().encode(e),i=await t.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("")}async function Kr(e,t){const r=await ir(),n=r.getRandomValues(new Uint8Array(16)),i=await la(t,n),a=r.getRandomValues(new Uint8Array(12)),s=new TextEncoder().encode(e),f=await r.subtle.encrypt({name:"AES-GCM",iv:a},i,s),c=new Uint8Array(n.length+a.length+f.byteLength);return c.set(n),c.set(a,n.length),c.set(new Uint8Array(f),n.length+a.length),_f(c)}async function fa(e,t){const r=await ir(),n=bf(e),i=n.slice(0,16),a=n.slice(16,28),o=n.slice(28),s=await la(t,i),f=await r.subtle.decrypt({name:"AES-GCM",iv:a},s,o);return new TextDecoder().decode(f)}async function la(e,t){const r=await ir(),i=new TextEncoder().encode(e),a=await r.subtle.importKey("raw",i,{name:"PBKDF2"},!1,["deriveKey"]);return await r.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:1e5,hash:"SHA-256"},a,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}function _f(e){if(typeof process<"u")return Buffer.from(e).toString("base64");{const t=String.fromCharCode.apply(null,new Uint8Array(e));return window.btoa(t)}}function bf(e){if(typeof process<"u")return new Uint8Array(Buffer.from(e,"base64"));{const t=window.atob(e),r=t.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=t.charCodeAt(i);return n}}function mf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ar={},Vr,ua;function Ef(){if(ua)return Vr;ua=1;var e,t,r={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
8
|
-
`,r:"\r",t:" "},n;function i(u){throw{name:"SyntaxError",message:u,at:e,text:n}}function a(u){return u&&u!==t&&i("Expected '"+u+"' instead of '"+t+"'"),t=n.charAt(e),e+=1,t}function o(){var u,p="";for(t==="-"&&(p="-",a("-"));t>="0"&&t<="9";)p+=t,a();if(t===".")for(p+=".";a()&&t>="0"&&t<="9";)p+=t;if(t==="e"||t==="E")for(p+=t,a(),(t==="-"||t==="+")&&(p+=t,a());t>="0"&&t<="9";)p+=t,a();return u=Number(p),isFinite(u)||i("Bad number"),u}function s(){var u,p,y="",w;if(t==='"')for(;a();){if(t==='"')return a(),y;if(t==="\\")if(a(),t==="u"){for(w=0,p=0;p<4&&(u=parseInt(a(),16),!!isFinite(u));p+=1)w=w*16+u;y+=String.fromCharCode(w)}else if(typeof r[t]=="string")y+=r[t];else break;else y+=t}i("Bad string")}function f(){for(;t&&t<=" ";)a()}function c(){switch(t){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null;default:i("Unexpected '"+t+"'")}}function l(){var u=[];if(t==="["){if(a("["),f(),t==="]")return a("]"),u;for(;t;){if(u.push(h()),f(),t==="]")return a("]"),u;a(","),f()}}i("Bad array")}function d(){var u,p={};if(t==="{"){if(a("{"),f(),t==="}")return a("}"),p;for(;t;){if(u=s(),f(),a(":"),Object.prototype.hasOwnProperty.call(p,u)&&i('Duplicate key "'+u+'"'),p[u]=h(),f(),t==="}")return a("}"),p;a(","),f()}}i("Bad object")}function h(){switch(f(),t){case"{":return d();case"[":return l();case'"':return s();case"-":return o();default:return t>="0"&&t<="9"?o():c()}}return Vr=function(u,p){var y;return n=u,e=0,t=" ",y=h(),f(),t&&i("Syntax error"),typeof p=="function"?function w(_,m){var E,v,A=_[m];if(A&&typeof A=="object")for(E in h)Object.prototype.hasOwnProperty.call(A,E)&&(v=w(A,E),typeof v>"u"?delete A[E]:A[E]=v);return p.call(_,m,A)}({"":y},""):y},Vr}var Wr,ha;function xf(){if(ha)return Wr;ha=1;var e=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,t,r,n={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function a(s){return e.lastIndex=0,e.test(s)?'"'+s.replace(e,function(f){var c=n[f];return typeof c=="string"?c:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+s+'"'}function o(s,f){var c,l,d,h,u=t,p,y=f[s];switch(y&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(s)),typeof i=="function"&&(y=i.call(f,s,y)),typeof y){case"string":return a(y);case"number":return isFinite(y)?String(y):"null";case"boolean":case"null":return String(y);case"object":if(!y)return"null";if(t+=r,p=[],Object.prototype.toString.apply(y)==="[object Array]"){for(h=y.length,c=0;c<h;c+=1)p[c]=o(c,y)||"null";return d=p.length===0?"[]":t?`[
|
|
9
|
-
`+t+p.join(`,
|
|
10
|
-
`+t)+`
|
|
11
|
-
`+u+"]":"["+p.join(",")+"]",t=u,d}if(i&&typeof i=="object")for(h=i.length,c=0;c<h;c+=1)l=i[c],typeof l=="string"&&(d=o(l,y),d&&p.push(a(l)+(t?": ":":")+d));else for(l in y)Object.prototype.hasOwnProperty.call(y,l)&&(d=o(l,y),d&&p.push(a(l)+(t?": ":":")+d));return d=p.length===0?"{}":t?`{
|
|
12
|
-
`+t+p.join(`,
|
|
13
|
-
`+t)+`
|
|
14
|
-
`+u+"}":"{"+p.join(",")+"}",t=u,d}}return Wr=function(s,f,c){var l;if(t="",r="",typeof c=="number")for(l=0;l<c;l+=1)r+=" ";else typeof c=="string"&&(r=c);if(i=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return o("",{"":s})},Wr}var da;function Sf(){return da||(da=1,ar.parse=Ef(),ar.stringify=xf()),ar}var Gr,pa;function Af(){if(pa)return Gr;pa=1;var e={}.toString;return Gr=Array.isArray||function(t){return e.call(t)=="[object Array]"},Gr}var Yr,ya;function ga(){if(ya)return Yr;ya=1;var e=Object.prototype.toString;return Yr=function(r){var n=e.call(r),i=n==="[object Arguments]";return i||(i=n!=="[object Array]"&&r!==null&&typeof r=="object"&&typeof r.length=="number"&&r.length>=0&&e.call(r.callee)==="[object Function]"),i},Yr}var Jr,va;function kf(){if(va)return Jr;va=1;var e;if(!Object.keys){var t=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=ga(),i=Object.prototype.propertyIsEnumerable,a=!i.call({toString:null},"toString"),o=i.call(function(){},"prototype"),s=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],f=function(h){var u=h.constructor;return u&&u.prototype===h},c={$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(typeof window>"u")return!1;for(var h in window)try{if(!c["$"+h]&&t.call(window,h)&&window[h]!==null&&typeof window[h]=="object")try{f(window[h])}catch{return!0}}catch{return!0}return!1}(),d=function(h){if(typeof window>"u"||!l)return f(h);try{return f(h)}catch{return!1}};e=function(u){var p=u!==null&&typeof u=="object",y=r.call(u)==="[object Function]",w=n(u),_=p&&r.call(u)==="[object String]",m=[];if(!p&&!y&&!w)throw new TypeError("Object.keys called on a non-object");var E=o&&y;if(_&&u.length>0&&!t.call(u,0))for(var v=0;v<u.length;++v)m.push(String(v));if(w&&u.length>0)for(var A=0;A<u.length;++A)m.push(String(A));else for(var O in u)!(E&&O==="prototype")&&t.call(u,O)&&m.push(String(O));if(a)for(var b=d(u),S=0;S<s.length;++S)!(b&&s[S]==="constructor")&&t.call(u,s[S])&&m.push(s[S]);return m}}return Jr=e,Jr}var Xr,wa;function Rf(){if(wa)return Xr;wa=1;var e=Array.prototype.slice,t=ga(),r=Object.keys,n=r?function(o){return r(o)}:kf(),i=Object.keys;return n.shim=function(){if(Object.keys){var o=function(){var s=Object.keys(arguments);return s&&s.length===arguments.length}(1,2);o||(Object.keys=function(f){return t(f)?i(e.call(f)):i(f)})}else Object.keys=n;return Object.keys||n},Xr=n,Xr}var Qr={exports:{}},en,_a;function ba(){return _a||(_a=1,en=Object),en}var tn,ma;function Of(){return ma||(ma=1,tn=Error),tn}var rn,Ea;function If(){return Ea||(Ea=1,rn=EvalError),rn}var nn,xa;function Pf(){return xa||(xa=1,nn=RangeError),nn}var an,Sa;function Tf(){return Sa||(Sa=1,an=ReferenceError),an}var on,Aa;function ka(){return Aa||(Aa=1,on=SyntaxError),on}var sn,Ra;function or(){return Ra||(Ra=1,sn=TypeError),sn}var cn,Oa;function jf(){return Oa||(Oa=1,cn=URIError),cn}var fn,Ia;function Ff(){return Ia||(Ia=1,fn=Math.abs),fn}var ln,Pa;function Cf(){return Pa||(Pa=1,ln=Math.floor),ln}var un,Ta;function Df(){return Ta||(Ta=1,un=Math.max),un}var hn,ja;function Mf(){return ja||(ja=1,hn=Math.min),hn}var dn,Fa;function Lf(){return Fa||(Fa=1,dn=Math.pow),dn}var pn,Ca;function Nf(){return Ca||(Ca=1,pn=Math.round),pn}var yn,Da;function $f(){return Da||(Da=1,yn=Number.isNaN||function(t){return t!==t}),yn}var gn,Ma;function Bf(){if(Ma)return gn;Ma=1;var e=$f();return gn=function(r){return e(r)||r===0?r:r<0?-1:1},gn}var vn,La;function Uf(){return La||(La=1,vn=Object.getOwnPropertyDescriptor),vn}var wn,Na;function sr(){if(Na)return wn;Na=1;var e=Uf();if(e)try{e([],"length")}catch{e=null}return wn=e,wn}var _n,$a;function cr(){if($a)return _n;$a=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return _n=e,_n}var bn,Ba;function zf(){return Ba||(Ba=1,bn=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;t[r]=i;for(var a in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var o=Object.getOwnPropertySymbols(t);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(t,r);if(s.value!==i||s.enumerable!==!0)return!1}return!0}),bn}var mn,Ua;function Zf(){if(Ua)return mn;Ua=1;var e=typeof Symbol<"u"&&Symbol,t=zf();return mn=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},mn}var En,za;function Za(){return za||(za=1,En=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),En}var xn,qa;function Ha(){if(qa)return xn;qa=1;var e=ba();return xn=e.getPrototypeOf||null,xn}var Sn,Ka;function qf(){if(Ka)return Sn;Ka=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",i=function(f,c){for(var l=[],d=0;d<f.length;d+=1)l[d]=f[d];for(var h=0;h<c.length;h+=1)l[h+f.length]=c[h];return l},a=function(f,c){for(var l=[],d=c,h=0;d<f.length;d+=1,h+=1)l[h]=f[d];return l},o=function(s,f){for(var c="",l=0;l<s.length;l+=1)c+=s[l],l+1<s.length&&(c+=f);return c};return Sn=function(f){var c=this;if(typeof c!="function"||t.apply(c)!==n)throw new TypeError(e+c);for(var l=a(arguments,1),d,h=function(){if(this instanceof d){var _=c.apply(this,i(l,arguments));return Object(_)===_?_:this}return c.apply(f,i(l,arguments))},u=r(0,c.length-l.length),p=[],y=0;y<u;y++)p[y]="$"+y;if(d=Function("binder","return function ("+o(p,",")+"){ return binder.apply(this,arguments); }")(h),c.prototype){var w=function(){};w.prototype=c.prototype,d.prototype=new w,w.prototype=null}return d},Sn}var An,Va;function It(){if(Va)return An;Va=1;var e=qf();return An=Function.prototype.bind||e,An}var kn,Wa;function Rn(){return Wa||(Wa=1,kn=Function.prototype.call),kn}var On,Ga;function In(){return Ga||(Ga=1,On=Function.prototype.apply),On}var Pn,Ya;function Hf(){return Ya||(Ya=1,Pn=typeof Reflect<"u"&&Reflect&&Reflect.apply),Pn}var Tn,Ja;function Xa(){if(Ja)return Tn;Ja=1;var e=It(),t=In(),r=Rn(),n=Hf();return Tn=n||e.call(r,t),Tn}var jn,Qa;function Fn(){if(Qa)return jn;Qa=1;var e=It(),t=or(),r=Rn(),n=Xa();return jn=function(a){if(a.length<1||typeof a[0]!="function")throw new t("a function is required");return n(e,r,a)},jn}var Cn,eo;function Kf(){if(eo)return Cn;eo=1;var e=Fn(),t=sr(),r;try{r=[].__proto__===Array.prototype}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="ERR_PROTO_ACCESS")throw o}var n=!!r&&t&&t(Object.prototype,"__proto__"),i=Object,a=i.getPrototypeOf;return Cn=n&&typeof n.get=="function"?e([n.get]):typeof a=="function"?function(s){return a(s==null?s:i(s))}:!1,Cn}var Dn,to;function Vf(){if(to)return Dn;to=1;var e=Za(),t=Ha(),r=Kf();return Dn=e?function(i){return e(i)}:t?function(i){if(!i||typeof i!="object"&&typeof i!="function")throw new TypeError("getProto: not an object");return t(i)}:r?function(i){return r(i)}:null,Dn}var Mn,ro;function Wf(){if(ro)return Mn;ro=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=It();return Mn=r.call(e,t),Mn}var Ln,no;function io(){if(no)return Ln;no=1;var e,t=ba(),r=Of(),n=If(),i=Pf(),a=Tf(),o=ka(),s=or(),f=jf(),c=Ff(),l=Cf(),d=Df(),h=Mf(),u=Lf(),p=Nf(),y=Bf(),w=Function,_=function(ue){try{return w('"use strict"; return ('+ue+").constructor;")()}catch{}},m=sr(),E=cr(),v=function(){throw new s},A=m?function(){try{return arguments.callee,v}catch{try{return m(arguments,"callee").get}catch{return v}}}():v,O=Zf()(),b=Vf(),S=Ha(),I=Za(),k=In(),F=Rn(),q={},G=typeof Uint8Array>"u"||!b?e:b(Uint8Array),ne={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":O&&b?b([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":q,"%AsyncGenerator%":q,"%AsyncGeneratorFunction%":q,"%AsyncIteratorPrototype%":q,"%Atomics%":typeof Atomics>"u"?e:Atomics,"%BigInt%":typeof BigInt>"u"?e:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?e:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?e:Float16Array,"%Float32Array%":typeof Float32Array>"u"?e:Float32Array,"%Float64Array%":typeof Float64Array>"u"?e:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?e:FinalizationRegistry,"%Function%":w,"%GeneratorFunction%":q,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":O&&b?b(b([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!O||!b?e:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":m,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":i,"%ReferenceError%":a,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!O||!b?e:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":O&&b?b(""[Symbol.iterator]()):e,"%Symbol%":O?Symbol:e,"%SyntaxError%":o,"%ThrowTypeError%":A,"%TypedArray%":G,"%TypeError%":s,"%Uint8Array%":typeof Uint8Array>"u"?e:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?e:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?e:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?e:Uint32Array,"%URIError%":f,"%WeakMap%":typeof WeakMap>"u"?e:WeakMap,"%WeakRef%":typeof WeakRef>"u"?e:WeakRef,"%WeakSet%":typeof WeakSet>"u"?e:WeakSet,"%Function.prototype.call%":F,"%Function.prototype.apply%":k,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":S,"%Math.abs%":c,"%Math.floor%":l,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":u,"%Math.round%":p,"%Math.sign%":y,"%Reflect.getPrototypeOf%":I};if(b)try{null.error}catch(ue){var He=b(b(ue));ne["%Error.prototype%"]=He}var J=function ue(M){var V;if(M==="%AsyncFunction%")V=_("async function () {}");else if(M==="%GeneratorFunction%")V=_("function* () {}");else if(M==="%AsyncGeneratorFunction%")V=_("async function* () {}");else if(M==="%AsyncGenerator%"){var $=ue("%AsyncGeneratorFunction%");$&&(V=$.prototype)}else if(M==="%AsyncIteratorPrototype%"){var Y=ue("%AsyncGenerator%");Y&&b&&(V=b(Y.prototype))}return ne[M]=V,V},le={__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"]},Ke=It(),Ve=Wf(),kt=Ke.call(F,Array.prototype.concat),Fc=Ke.call(k,Array.prototype.splice),zi=Ke.call(F,String.prototype.replace),Yt=Ke.call(F,String.prototype.slice),Cc=Ke.call(F,RegExp.prototype.exec),Dc=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Mc=/\\(\\)?/g,Lc=function(M){var V=Yt(M,0,1),$=Yt(M,-1);if(V==="%"&&$!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if($==="%"&&V!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var Y=[];return zi(M,Dc,function(he,dt,X,Jt){Y[Y.length]=X?zi(Jt,Mc,"$1"):dt||he}),Y},Nc=function(M,V){var $=M,Y;if(Ve(le,$)&&(Y=le[$],$="%"+Y[0]+"%"),Ve(ne,$)){var he=ne[$];if(he===q&&(he=J($)),typeof he>"u"&&!V)throw new s("intrinsic "+M+" exists, but is not available. Please file an issue!");return{alias:Y,name:$,value:he}}throw new o("intrinsic "+M+" does not exist!")};return Ln=function(M,V){if(typeof M!="string"||M.length===0)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="boolean")throw new s('"allowMissing" argument must be a boolean');if(Cc(/^%?[^%]*%?$/,M)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var $=Lc(M),Y=$.length>0?$[0]:"",he=Nc("%"+Y+"%",V),dt=he.name,X=he.value,Jt=!1,Nr=he.alias;Nr&&(Y=Nr[0],Fc($,kt([0,1],Nr)));for(var Xt=1,Rt=!0;Xt<$.length;Xt+=1){var Ee=$[Xt],Qt=Yt(Ee,0,1),er=Yt(Ee,-1);if((Qt==='"'||Qt==="'"||Qt==="`"||er==='"'||er==="'"||er==="`")&&Qt!==er)throw new o("property names with quotes must have matching quotes");if((Ee==="constructor"||!Rt)&&(Jt=!0),Y+="."+Ee,dt="%"+Y+"%",Ve(ne,dt))X=ne[dt];else if(X!=null){if(!(Ee in X)){if(!V)throw new s("base intrinsic for "+M+" exists, but the property is not available.");return}if(m&&Xt+1>=$.length){var tr=m(X,Ee);Rt=!!tr,Rt&&"get"in tr&&!("originalValue"in tr.get)?X=tr.get:X=X[Ee]}else Rt=Ve(X,Ee),X=X[Ee];Rt&&!Jt&&(ne[dt]=X)}}return X},Ln}var Nn,ao;function Gf(){if(ao)return Nn;ao=1;var e=cr(),t=ka(),r=or(),n=sr();return Nn=function(a,o,s){if(!a||typeof a!="object"&&typeof a!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var f=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,d=arguments.length>6?arguments[6]:!1,h=!!n&&n(a,o);if(e)e(a,o,{configurable:l===null&&h?h.configurable:!l,enumerable:f===null&&h?h.enumerable:!f,value:s,writable:c===null&&h?h.writable:!c});else if(d||!f&&!c&&!l)a[o]=s;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Nn}var $n,oo;function Yf(){if(oo)return $n;oo=1;var e=cr(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},$n=t,$n}var Bn,so;function Jf(){if(so)return Bn;so=1;var e=io(),t=Gf(),r=Yf()(),n=sr(),i=or(),a=e("%Math.floor%");return Bn=function(s,f){if(typeof s!="function")throw new i("`fn` is not a function");if(typeof f!="number"||f<0||f>4294967295||a(f)!==f)throw new i("`length` must be a positive 32-bit integer");var c=arguments.length>2&&!!arguments[2],l=!0,d=!0;if("length"in s&&n){var h=n(s,"length");h&&!h.configurable&&(l=!1),h&&!h.writable&&(d=!1)}return(l||d||!c)&&(r?t(s,"length",f,!0,!0):t(s,"length",f)),s},Bn}var Un,co;function Xf(){if(co)return Un;co=1;var e=It(),t=In(),r=Xa();return Un=function(){return r(e,t,arguments)},Un}var fo;function Qf(){return fo||(fo=1,function(e){var t=Jf(),r=cr(),n=Fn(),i=Xf();e.exports=function(o){var s=n(arguments),f=o.length-(arguments.length-1);return t(s,1+(f>0?f:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(Qr)),Qr.exports}var zn,lo;function el(){if(lo)return zn;lo=1;var e=io(),t=Fn(),r=t([e("%String.prototype.indexOf%")]);return zn=function(i,a){var o=e(i,!!a);return typeof o=="function"&&r(i,".prototype.")>-1?t([o]):o},zn}var Zn,uo;function tl(){if(uo)return Zn;uo=1;var e=(typeof JSON<"u"?JSON:Sf()).stringify,t=Af(),r=Rf(),n=Qf(),i=el(),a=i("Array.prototype.join"),o=i("Array.prototype.indexOf"),s=i("Array.prototype.splice"),f=i("Array.prototype.sort"),c=function(h,u){for(var p="",y=0;y<h;y+=1)p+=u;return p},l=function(d,h,u){return u};return Zn=function(h){var u=arguments.length>1?arguments[1]:void 0,p=u&&u.space||"";typeof p=="number"&&(p=c(p," "));var y=!!u&&typeof u.cycles=="boolean"&&u.cycles,w=u&&u.replacer?n(u.replacer):l;if(u&&typeof u.collapseEmpty<"u"&&typeof u.collapseEmpty!="boolean")throw new TypeError("`collapseEmpty` must be a boolean, if provided");var _=!!u&&u.collapseEmpty,m=typeof u=="function"?u:u&&u.cmp,E=m&&function(A){var O=m.length>2&&function(S){return A[S]};return function(b,S){return m({key:b,value:A[b]},{key:S,value:A[S]},O?{__proto__:null,get:O}:void 0)}},v=[];return function A(O,b,S,I){var k=p?`
|
|
15
|
-
`+c(I,p):"",F=p?": ":":";if(S&&S.toJSON&&typeof S.toJSON=="function"&&(S=S.toJSON()),S=w(O,b,S),S!==void 0){if(typeof S!="object"||S===null)return e(S);var q=function(Ve,kt){return _&&Ve.length===0?kt:(kt==="[]"?"[":"{")+a(Ve,",")+k+(kt==="[]"?"]":"}")};if(t(S)){for(var J=[],G=0;G<S.length;G++){var ne=A(S,G,S[G],I+1)||e(null);J[J.length]=k+p+ne}return q(J,"[]")}if(o(v,S)!==-1){if(y)return e("__cycle__");throw new TypeError("Converting circular structure to JSON")}else v[v.length]=S;for(var He=f(r(S),E&&E(S)),J=[],G=0;G<He.length;G++){var b=He[G],le=A(S,b,S[b],I+1);if(le){var Ke=e(b)+F+le;J[J.length]=k+p+Ke}}return s(v,o(v,S),1),q(J,"{}")}}({"":h},"",h,0)},Zn}var rl=tl(),ho=mf(rl);async function qn(e,t,r){if(!this.passphrase)return t.push({actual:e,type:"encryptionKeyMissing"}),e;try{return await Kr(String(e),this.passphrase)}catch(n){t.push({actual:e,type:"encryptionProblem",error:n})}return e}async function nl(e,t,r){return L.isString(e)?e:JSON.stringify(e)}class po extends Kc{constructor({options:t,passphrase:r,autoEncrypt:n=!0}={}){super(L.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=r,this.autoEncrypt=n,this.alias("secret",{type:"string",custom:this.autoEncrypt?qn: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?qn:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?qn:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?nl:void 0})}}const yo=new Proxy(po,{instance:null,construct(e,t){return this.instance||(this.instance=new e(...t)),this.instance}});function il(e){return e.toString(36)}function al(e){const t={},r={};return e.forEach((n,i)=>{const a=il(i);t[n]=a,r[a]=n}),{mapping:t,reversedMapping:r}}const Hn={trim:e=>e.trim(),encrypt:(e,{passphrase:t})=>Kr(e,t),decrypt:async(e,{passphrase:t})=>{try{return await fa(e,t)}catch(r){return console.warn(`Schema decrypt error: ${r}`,r),e}},toString:e=>String(e),fromArray:(e,{separator:t})=>e==null||!Array.isArray(e)?e:e.length===0?"[]":e.map(n=>typeof n=="string"?n.replace(/\\/g,"\\\\").replace(new RegExp(`\\${t}`,"g"),`\\${t}`):String(n)).join(t),toArray:(e,{separator:t})=>{if(e==null)return e;if(e==="[]")return[];if(e==="")return[];const r=[];let n="",i=0;const a=String(e);for(;i<a.length;)a[i]==="\\"&&i+1<a.length?a[i+1]===t?(n+=t,i+=2):a[i+1]==="\\"?(n+="\\",i+=2):(n+=a[i],i++):a[i]===t?(r.push(n),n="",i++):(n+=a[i],i++);return r.push(n),r},toJSON:e=>JSON.stringify(e),fromJSON:e=>JSON.parse(e),toNumber:e=>L.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"};class me{constructor(t){const{map:r,name:n,attributes:i,passphrase:a,version:o=1,options:s={}}=t;this.name=n,this.version=o,this.attributes=i||{},this.passphrase=a??"secret",this.options=L.merge({},this.defaultOptions(),s),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const f=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new yo({autoEncrypt:!1}).compile(L.merge({$$async:!0},f)),this.options.generateAutoHooks&&this.generateAutoHooks(),!L.isEmpty(r))this.map=r,this.reversedMap=L.invert(r);else{const c=rr.flatten(this.attributes,{safe:!0}),l=Object.keys(c).filter(y=>!y.includes("$$")),d=this.extractObjectKeys(this.attributes),h=[...new Set([...l,...d])],{mapping:u,reversedMapping:p}=al(h);this.map=u,this.reversedMap=p}}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(t,r,n){this.options.hooks[t][r]||(this.options.hooks[t][r]=[]),this.options.hooks[t][r]=L.uniq([...this.options.hooks[t][r],n])}extractObjectKeys(t,r=""){const n=[];for(const[i,a]of Object.entries(t)){if(i.startsWith("$$"))continue;const o=r?`${r}.${i}`:i;typeof a=="object"&&a!==null&&!Array.isArray(a)&&(n.push(o),a.$$type==="object"&&n.push(...this.extractObjectKeys(a,o)))}return n}generateAutoHooks(){const t=rr.flatten(L.cloneDeep(this.attributes),{safe:!0});for(const[r,n]of Object.entries(t))n.includes("array")&&(this.addHook("beforeMap",r,"fromArray"),this.addHook("afterUnmap",r,"toArray")),n.includes("secret")&&(this.options.autoEncrypt&&this.addHook("beforeMap",r,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",r,"decrypt")),n.includes("number")&&(this.addHook("beforeMap",r,"toString"),this.addHook("afterUnmap",r,"toNumber")),n.includes("boolean")&&(this.addHook("beforeMap",r,"fromBool"),this.addHook("afterUnmap",r,"toBool")),n.includes("json")&&(this.addHook("beforeMap",r,"toJSON"),this.addHook("afterUnmap",r,"fromJSON"))}static import(t){let{map:r,name:n,options:i,version:a,attributes:o}=L.isString(t)?JSON.parse(t):t;return o=me._importAttributes(o),new me({map:r,name:n,options:i,version:a,attributes:o})}static _importAttributes(t){if(typeof t=="string"){try{const r=JSON.parse(t);if(typeof r=="object"&&r!==null)return me._importAttributes(r)}catch{}return t}if(Array.isArray(t))return t.map(r=>me._importAttributes(r));if(typeof t=="object"&&t!==null){const r={};for(const[n,i]of Object.entries(t))r[n]=me._importAttributes(i);return r}return t}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>this._exportAttributes(r));if(typeof t=="object"&&t!==null){const r={};for(const[n,i]of Object.entries(t))r[n]=this._exportAttributes(i);return r}return t}async applyHooksActions(t,r){for(const[n,i]of Object.entries(this.options.hooks[r]))for(const a of i){const o=L.get(t,n);o!==void 0&&typeof Hn[a]=="function"&&L.set(t,n,await Hn[a](o,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}}async validate(t,{mutateOriginal:r=!1}={}){let n=r?t:L.cloneDeep(t);return await this.validator(n)}async mapper(t){const r=rr.flatten(L.cloneDeep(t),{safe:!0});await this.applyHooksActions(r,"beforeMap");const n={_v:this.version+""};for(const[i,a]of Object.entries(r))n[this.map[i]]=a;return await this.applyHooksActions(n,"afterMap"),n}async unmapper(t){const r=L.cloneDeep(t);delete r._v,await this.applyHooksActions(r,"beforeUnmap");const n={};for(const[i,a]of Object.entries(r))n[this.reversedMap[i]]=a;return await this.applyHooksActions(n,"afterUnmap"),rr.unflatten(n)}preprocessAttributesForValidation(t){const r={};for(const[n,i]of Object.entries(t))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const a=i.$$type&&i.$$type.includes("required"),o=i.$$type&&i.$$type.includes("optional"),s={type:"object",properties:this.preprocessAttributesForValidation(i),strict:!1};a||(o||this.allNestedObjectsOptional)&&(s.optional=!0),r[n]=s}else r[n]=i;return r}}var pt=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},ge=[],ae=[],ol=typeof Uint8Array<"u"?Uint8Array:Array,Kn=!1;function go(){Kn=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t<r;++t)ge[t]=e[t],ae[e.charCodeAt(t)]=t;ae[45]=62,ae[95]=63}function sl(e){Kn||go();var t,r,n,i,a,o,s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a=e[s-2]==="="?2:e[s-1]==="="?1:0,o=new ol(s*3/4-a),n=a>0?s-4:s;var f=0;for(t=0,r=0;t<n;t+=4,r+=3)i=ae[e.charCodeAt(t)]<<18|ae[e.charCodeAt(t+1)]<<12|ae[e.charCodeAt(t+2)]<<6|ae[e.charCodeAt(t+3)],o[f++]=i>>16&255,o[f++]=i>>8&255,o[f++]=i&255;return a===2?(i=ae[e.charCodeAt(t)]<<2|ae[e.charCodeAt(t+1)]>>4,o[f++]=i&255):a===1&&(i=ae[e.charCodeAt(t)]<<10|ae[e.charCodeAt(t+1)]<<4|ae[e.charCodeAt(t+2)]>>2,o[f++]=i>>8&255,o[f++]=i&255),o}function cl(e){return ge[e>>18&63]+ge[e>>12&63]+ge[e>>6&63]+ge[e&63]}function fl(e,t,r){for(var n,i=[],a=t;a<r;a+=3)n=(e[a]<<16)+(e[a+1]<<8)+e[a+2],i.push(cl(n));return i.join("")}function vo(e){Kn||go();for(var t,r=e.length,n=r%3,i="",a=[],o=16383,s=0,f=r-n;s<f;s+=o)a.push(fl(e,s,s+o>f?f:s+o));return n===1?(t=e[r-1],i+=ge[t>>2],i+=ge[t<<4&63],i+="=="):n===2&&(t=(e[r-2]<<8)+e[r-1],i+=ge[t>>10],i+=ge[t>>4&63],i+=ge[t<<2&63],i+="="),a.push(i),a.join("")}function fr(e,t,r,n,i){var a,o,s=i*8-n-1,f=(1<<s)-1,c=f>>1,l=-7,d=r?i-1:0,h=r?-1:1,u=e[t+d];for(d+=h,a=u&(1<<-l)-1,u>>=-l,l+=s;l>0;a=a*256+e[t+d],d+=h,l-=8);for(o=a&(1<<-l)-1,a>>=-l,l+=n;l>0;o=o*256+e[t+d],d+=h,l-=8);if(a===0)a=1-c;else{if(a===f)return o?NaN:(u?-1:1)*(1/0);o=o+Math.pow(2,n),a=a-c}return(u?-1:1)*o*Math.pow(2,a-n)}function wo(e,t,r,n,i,a){var o,s,f,c=a*8-i-1,l=(1<<c)-1,d=l>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,u=n?0:a-1,p=n?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(f=Math.pow(2,-o))<1&&(o--,f*=2),o+d>=1?t+=h/f:t+=h*Math.pow(2,1-d),t*f>=2&&(o++,f/=2),o+d>=l?(s=0,o=l):o+d>=1?(s=(t*f-1)*Math.pow(2,i),o=o+d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[r+u]=s&255,u+=p,s/=256,i-=8);for(o=o<<i|s,c+=i;c>0;e[r+u]=o&255,u+=p,o/=256,c-=8);e[r+u-p]|=y*128}var ll={}.toString,_o=Array.isArray||function(e){return ll.call(e)=="[object Array]"};/*!
|
|
16
|
-
* The buffer module from node.js, for the browser.
|
|
17
|
-
*
|
|
18
|
-
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
|
|
19
|
-
* @license MIT
|
|
20
|
-
*/var ul=50;g.TYPED_ARRAY_SUPPORT=pt.TYPED_ARRAY_SUPPORT!==void 0?pt.TYPED_ARRAY_SUPPORT:!0,lr();function lr(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Se(e,t){if(lr()<t)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t),e.__proto__=g.prototype):(e===null&&(e=new g(t)),e.length=t),e}function g(e,t,r){if(!g.TYPED_ARRAY_SUPPORT&&!(this instanceof g))return new g(e,t,r);if(typeof e=="number"){if(typeof t=="string")throw new Error("If encoding is specified then the first argument must be a string");return Vn(this,e)}return bo(this,e,t,r)}g.poolSize=8192,g._augment=function(e){return e.__proto__=g.prototype,e};function bo(e,t,r,n){if(typeof t=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer?pl(e,t,r,n):typeof t=="string"?dl(e,t,r):yl(e,t)}g.from=function(e,t,r){return bo(null,e,t,r)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]);function mo(e){if(typeof e!="number")throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function hl(e,t,r,n){return mo(t),t<=0?Se(e,t):r!==void 0?typeof n=="string"?Se(e,t).fill(r,n):Se(e,t).fill(r):Se(e,t)}g.alloc=function(e,t,r){return hl(null,e,t,r)};function Vn(e,t){if(mo(t),e=Se(e,t<0?0:Gn(t)|0),!g.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}g.allocUnsafe=function(e){return Vn(null,e)},g.allocUnsafeSlow=function(e){return Vn(null,e)};function dl(e,t,r){if((typeof r!="string"||r==="")&&(r="utf8"),!g.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=Eo(t,r)|0;e=Se(e,n);var i=e.write(t,r);return i!==n&&(e=e.slice(0,i)),e}function Wn(e,t){var r=t.length<0?0:Gn(t.length)|0;e=Se(e,r);for(var n=0;n<r;n+=1)e[n]=t[n]&255;return e}function pl(e,t,r,n){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return r===void 0&&n===void 0?t=new Uint8Array(t):n===void 0?t=new Uint8Array(t,r):t=new Uint8Array(t,r,n),g.TYPED_ARRAY_SUPPORT?(e=t,e.__proto__=g.prototype):e=Wn(e,t),e}function yl(e,t){if(ve(t)){var r=Gn(t.length)|0;return e=Se(e,r),e.length===0||t.copy(e,0,0,r),e}if(t){if(typeof ArrayBuffer<"u"&&t.buffer instanceof ArrayBuffer||"length"in t)return typeof t.length!="number"||Cl(t.length)?Se(e,0):Wn(e,t);if(t.type==="Buffer"&&_o(t.data))return Wn(e,t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function Gn(e){if(e>=lr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+lr().toString(16)+" bytes");return e|0}g.isBuffer=Dl;function ve(e){return!!(e!=null&&e._isBuffer)}g.compare=function(t,r){if(!ve(t)||!ve(r))throw new TypeError("Arguments must be Buffers");if(t===r)return 0;for(var n=t.length,i=r.length,a=0,o=Math.min(n,i);a<o;++a)if(t[a]!==r[a]){n=t[a],i=r[a];break}return n<i?-1:i<n?1:0},g.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}},g.concat=function(t,r){if(!_o(t))throw new TypeError('"list" argument must be an Array of Buffers');if(t.length===0)return g.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<t.length;++n)r+=t[n].length;var i=g.allocUnsafe(r),a=0;for(n=0;n<t.length;++n){var o=t[n];if(!ve(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,a),a+=o.length}return i};function Eo(e,t){if(ve(e))return e.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;typeof e!="string"&&(e=""+e);var r=e.length;if(r===0)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return dr(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return To(e).length;default:if(n)return dr(e).length;t=(""+t).toLowerCase(),n=!0}}g.byteLength=Eo;function gl(e,t,r){var n=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,t>>>=0,r<=t))return"";for(e||(e="utf8");;)switch(e){case"hex":return kl(this,t,r);case"utf8":case"utf-8":return ko(this,t,r);case"ascii":return Sl(this,t,r);case"latin1":case"binary":return Al(this,t,r);case"base64":return El(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Rl(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}g.prototype._isBuffer=!0;function We(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}g.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 r=0;r<t;r+=2)We(this,r,r+1);return this},g.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 r=0;r<t;r+=4)We(this,r,r+3),We(this,r+1,r+2);return this},g.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 r=0;r<t;r+=8)We(this,r,r+7),We(this,r+1,r+6),We(this,r+2,r+5),We(this,r+3,r+4);return this},g.prototype.toString=function(){var t=this.length|0;return t===0?"":arguments.length===0?ko(this,0,t):gl.apply(this,arguments)},g.prototype.equals=function(t){if(!ve(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:g.compare(this,t)===0},g.prototype.inspect=function(){var t="",r=ul;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),"<Buffer "+t+">"},g.prototype.compare=function(t,r,n,i,a){if(!ve(t))throw new TypeError("Argument must be a Buffer");if(r===void 0&&(r=0),n===void 0&&(n=t?t.length:0),i===void 0&&(i=0),a===void 0&&(a=this.length),r<0||n>t.length||i<0||a>this.length)throw new RangeError("out of range index");if(i>=a&&r>=n)return 0;if(i>=a)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,a>>>=0,this===t)return 0;for(var o=a-i,s=n-r,f=Math.min(o,s),c=this.slice(i,a),l=t.slice(r,n),d=0;d<f;++d)if(c[d]!==l[d]){o=c[d],s=l[d];break}return o<s?-1:s<o?1:0};function xo(e,t,r,n,i){if(e.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof t=="string"&&(t=g.from(t,n)),ve(t))return t.length===0?-1:So(e,t,r,n,i);if(typeof t=="number")return t=t&255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):So(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function So(e,t,r,n,i){var a=1,o=e.length,s=t.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,r/=2}function f(u,p){return a===1?u[p]:u.readUInt16BE(p*a)}var c;if(i){var l=-1;for(c=r;c<o;c++)if(f(e,c)===f(t,l===-1?0:c-l)){if(l===-1&&(l=c),c-l+1===s)return l*a}else l!==-1&&(c-=c-l),l=-1}else for(r+s>o&&(r=o-s),c=r;c>=0;c--){for(var d=!0,h=0;h<s;h++)if(f(e,c+h)!==f(t,h)){d=!1;break}if(d)return c}return-1}g.prototype.includes=function(t,r,n){return this.indexOf(t,r,n)!==-1},g.prototype.indexOf=function(t,r,n){return xo(this,t,r,n,!0)},g.prototype.lastIndexOf=function(t,r,n){return xo(this,t,r,n,!1)};function vl(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var a=t.length;if(a%2!==0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;o<n;++o){var s=parseInt(t.substr(o*2,2),16);if(isNaN(s))return o;e[r+o]=s}return o}function wl(e,t,r,n){return pr(dr(t,e.length-r),e,r,n)}function Ao(e,t,r,n){return pr(jl(t),e,r,n)}function _l(e,t,r,n){return Ao(e,t,r,n)}function bl(e,t,r,n){return pr(To(t),e,r,n)}function ml(e,t,r,n){return pr(Fl(t,e.length-r),e,r,n)}g.prototype.write=function(t,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r|0,isFinite(n)?(n=n|0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var a=this.length-r;if((n===void 0||n>a)&&(n=a),t.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return vl(this,t,r,n);case"utf8":case"utf-8":return wl(this,t,r,n);case"ascii":return Ao(this,t,r,n);case"latin1":case"binary":return _l(this,t,r,n);case"base64":return bl(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ml(this,t,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function El(e,t,r){return t===0&&r===e.length?vo(e):vo(e.slice(t,r))}function ko(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i<r;){var a=e[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(i+s<=r){var f,c,l,d;switch(s){case 1:a<128&&(o=a);break;case 2:f=e[i+1],(f&192)===128&&(d=(a&31)<<6|f&63,d>127&&(o=d));break;case 3:f=e[i+1],c=e[i+2],(f&192)===128&&(c&192)===128&&(d=(a&15)<<12|(f&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:f=e[i+1],c=e[i+2],l=e[i+3],(f&192)===128&&(c&192)===128&&(l&192)===128&&(d=(a&15)<<18|(f&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=s}return xl(n)}var Ro=4096;function xl(e){var t=e.length;if(t<=Ro)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=Ro));return r}function Sl(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]&127);return n}function Al(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function kl(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",a=t;a<r;++a)i+=Tl(e[a]);return i}function Rl(e,t,r){for(var n=e.slice(t,r),i="",a=0;a<n.length;a+=2)i+=String.fromCharCode(n[a]+n[a+1]*256);return i}g.prototype.slice=function(t,r){var n=this.length;t=~~t,r=r===void 0?n:~~r,t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<t&&(r=t);var i;if(g.TYPED_ARRAY_SUPPORT)i=this.subarray(t,r),i.__proto__=g.prototype;else{var a=r-t;i=new g(a,void 0);for(var o=0;o<a;++o)i[o]=this[o+t]}return i};function z(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")}g.prototype.readUIntLE=function(t,r,n){t=t|0,r=r|0,n||z(t,r,this.length);for(var i=this[t],a=1,o=0;++o<r&&(a*=256);)i+=this[t+o]*a;return i},g.prototype.readUIntBE=function(t,r,n){t=t|0,r=r|0,n||z(t,r,this.length);for(var i=this[t+--r],a=1;r>0&&(a*=256);)i+=this[t+--r]*a;return i},g.prototype.readUInt8=function(t,r){return r||z(t,1,this.length),this[t]},g.prototype.readUInt16LE=function(t,r){return r||z(t,2,this.length),this[t]|this[t+1]<<8},g.prototype.readUInt16BE=function(t,r){return r||z(t,2,this.length),this[t]<<8|this[t+1]},g.prototype.readUInt32LE=function(t,r){return r||z(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216},g.prototype.readUInt32BE=function(t,r){return r||z(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])},g.prototype.readIntLE=function(t,r,n){t=t|0,r=r|0,n||z(t,r,this.length);for(var i=this[t],a=1,o=0;++o<r&&(a*=256);)i+=this[t+o]*a;return a*=128,i>=a&&(i-=Math.pow(2,8*r)),i},g.prototype.readIntBE=function(t,r,n){t=t|0,r=r|0,n||z(t,r,this.length);for(var i=r,a=1,o=this[t+--i];i>0&&(a*=256);)o+=this[t+--i]*a;return a*=128,o>=a&&(o-=Math.pow(2,8*r)),o},g.prototype.readInt8=function(t,r){return r||z(t,1,this.length),this[t]&128?(255-this[t]+1)*-1:this[t]},g.prototype.readInt16LE=function(t,r){r||z(t,2,this.length);var n=this[t]|this[t+1]<<8;return n&32768?n|4294901760:n},g.prototype.readInt16BE=function(t,r){r||z(t,2,this.length);var n=this[t+1]|this[t]<<8;return n&32768?n|4294901760:n},g.prototype.readInt32LE=function(t,r){return r||z(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},g.prototype.readInt32BE=function(t,r){return r||z(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},g.prototype.readFloatLE=function(t,r){return r||z(t,4,this.length),fr(this,t,!0,23,4)},g.prototype.readFloatBE=function(t,r){return r||z(t,4,this.length),fr(this,t,!1,23,4)},g.prototype.readDoubleLE=function(t,r){return r||z(t,8,this.length),fr(this,t,!0,52,8)},g.prototype.readDoubleBE=function(t,r){return r||z(t,8,this.length),fr(this,t,!1,52,8)};function Q(e,t,r,n,i,a){if(!ve(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<a)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}g.prototype.writeUIntLE=function(t,r,n,i){if(t=+t,r=r|0,n=n|0,!i){var a=Math.pow(2,8*n)-1;Q(this,t,r,n,a,0)}var o=1,s=0;for(this[r]=t&255;++s<n&&(o*=256);)this[r+s]=t/o&255;return r+n},g.prototype.writeUIntBE=function(t,r,n,i){if(t=+t,r=r|0,n=n|0,!i){var a=Math.pow(2,8*n)-1;Q(this,t,r,n,a,0)}var o=n-1,s=1;for(this[r+o]=t&255;--o>=0&&(s*=256);)this[r+o]=t/s&255;return r+n},g.prototype.writeUInt8=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,1,255,0),g.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=t&255,r+1};function ur(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-r,2);i<a;++i)e[r+i]=(t&255<<8*(n?i:1-i))>>>(n?i:1-i)*8}g.prototype.writeUInt16LE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[r]=t&255,this[r+1]=t>>>8):ur(this,t,r,!0),r+2},g.prototype.writeUInt16BE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=t&255):ur(this,t,r,!1),r+2};function hr(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-r,4);i<a;++i)e[r+i]=t>>>(n?i:3-i)*8&255}g.prototype.writeUInt32LE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=t&255):hr(this,t,r,!0),r+4},g.prototype.writeUInt32BE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255):hr(this,t,r,!1),r+4},g.prototype.writeIntLE=function(t,r,n,i){if(t=+t,r=r|0,!i){var a=Math.pow(2,8*n-1);Q(this,t,r,n,a-1,-a)}var o=0,s=1,f=0;for(this[r]=t&255;++o<n&&(s*=256);)t<0&&f===0&&this[r+o-1]!==0&&(f=1),this[r+o]=(t/s>>0)-f&255;return r+n},g.prototype.writeIntBE=function(t,r,n,i){if(t=+t,r=r|0,!i){var a=Math.pow(2,8*n-1);Q(this,t,r,n,a-1,-a)}var o=n-1,s=1,f=0;for(this[r+o]=t&255;--o>=0&&(s*=256);)t<0&&f===0&&this[r+o+1]!==0&&(f=1),this[r+o]=(t/s>>0)-f&255;return r+n},g.prototype.writeInt8=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,1,127,-128),g.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=t&255,r+1},g.prototype.writeInt16LE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[r]=t&255,this[r+1]=t>>>8):ur(this,t,r,!0),r+2},g.prototype.writeInt16BE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=t&255):ur(this,t,r,!1),r+2},g.prototype.writeInt32LE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[r]=t&255,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):hr(this,t,r,!0),r+4},g.prototype.writeInt32BE=function(t,r,n){return t=+t,r=r|0,n||Q(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),g.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=t&255):hr(this,t,r,!1),r+4};function Oo(e,t,r,n,i,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Io(e,t,r,n,i){return i||Oo(e,t,r,4),wo(e,t,r,n,23,4),r+4}g.prototype.writeFloatLE=function(t,r,n){return Io(this,t,r,!0,n)},g.prototype.writeFloatBE=function(t,r,n){return Io(this,t,r,!1,n)};function Po(e,t,r,n,i){return i||Oo(e,t,r,8),wo(e,t,r,n,52,8),r+8}g.prototype.writeDoubleLE=function(t,r,n){return Po(this,t,r,!0,n)},g.prototype.writeDoubleBE=function(t,r,n){return Po(this,t,r,!1,n)},g.prototype.copy=function(t,r,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),r>=t.length&&(r=t.length),r||(r=0),i>0&&i<n&&(i=n),i===n||t.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-r<i-n&&(i=t.length-r+n);var a=i-n,o;if(this===t&&n<r&&r<i)for(o=a-1;o>=0;--o)t[o+r]=this[o+n];else if(a<1e3||!g.TYPED_ARRAY_SUPPORT)for(o=0;o<a;++o)t[o+r]=this[o+n];else Uint8Array.prototype.set.call(t,this.subarray(n,n+a),r);return a},g.prototype.fill=function(t,r,n,i){if(typeof t=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),t.length===1){var a=t.charCodeAt(0);a<256&&(t=a)}if(i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!g.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof t=="number"&&(t=t&255);if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,t||(t=0);var o;if(typeof t=="number")for(o=r;o<n;++o)this[o]=t;else{var s=ve(t)?t:dr(new g(t,i).toString()),f=s.length;for(o=0;o<n-r;++o)this[o+r]=s[o%f]}return this};var Ol=/[^+\/0-9A-Za-z-_]/g;function Il(e){if(e=Pl(e).replace(Ol,""),e.length<2)return"";for(;e.length%4!==0;)e=e+"=";return e}function Pl(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Tl(e){return e<16?"0"+e.toString(16):e.toString(16)}function dr(e,t){t=t||1/0;for(var r,n=e.length,i=null,a=[],o=0;o<n;++o){if(r=e.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}else if(o+1===n){(t-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return a}function jl(e){for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r)&255);return t}function Fl(e,t){for(var r,n,i,a=[],o=0;o<e.length&&!((t-=2)<0);++o)r=e.charCodeAt(o),n=r>>8,i=r%256,a.push(i),a.push(n);return a}function To(e){return sl(Il(e))}function pr(e,t,r,n){for(var i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Cl(e){return e!==e}function Dl(e){return e!=null&&(!!e._isBuffer||jo(e)||Ml(e))}function jo(e){return!!e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e)}function Ml(e){return typeof e.readFloatLE=="function"&&typeof e.slice=="function"&&jo(e.slice(0,0))}function Fo(){throw new Error("setTimeout has not been defined")}function Co(){throw new Error("clearTimeout has not been defined")}var je=Fo,Fe=Co;typeof pt.setTimeout=="function"&&(je=setTimeout),typeof pt.clearTimeout=="function"&&(Fe=clearTimeout);function Do(e){if(je===setTimeout)return setTimeout(e,0);if((je===Fo||!je)&&setTimeout)return je=setTimeout,setTimeout(e,0);try{return je(e,0)}catch{try{return je.call(null,e,0)}catch{return je.call(this,e,0)}}}function Ll(e){if(Fe===clearTimeout)return clearTimeout(e);if((Fe===Co||!Fe)&&clearTimeout)return Fe=clearTimeout,clearTimeout(e);try{return Fe(e)}catch{try{return Fe.call(null,e)}catch{return Fe.call(this,e)}}}var Ae=[],yt=!1,Ge,yr=-1;function Nl(){!yt||!Ge||(yt=!1,Ge.length?Ae=Ge.concat(Ae):yr=-1,Ae.length&&Mo())}function Mo(){if(!yt){var e=Do(Nl);yt=!0;for(var t=Ae.length;t;){for(Ge=Ae,Ae=[];++yr<t;)Ge&&Ge[yr].run();yr=-1,t=Ae.length}Ge=null,yt=!1,Ll(e)}}function te(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];Ae.push(new Lo(e,t)),Ae.length===1&&!yt&&Do(Mo)}function Lo(e,t){this.fun=e,this.array=t}Lo.prototype.run=function(){this.fun.apply(null,this.array)};var $l="browser",Bl="browser",Ul=!0,zl={},Zl=[],ql="",Hl={},Kl={},Vl={};function Ye(){}var Wl=Ye,Gl=Ye,Yl=Ye,Jl=Ye,Xl=Ye,Ql=Ye,eu=Ye;function tu(e){throw new Error("process.binding is not supported")}function ru(){return"/"}function nu(e){throw new Error("process.chdir is not supported")}function iu(){return 0}var gt=pt.performance||{},au=gt.now||gt.mozNow||gt.msNow||gt.oNow||gt.webkitNow||function(){return new Date().getTime()};function ou(e){var t=au.call(gt)*.001,r=Math.floor(t),n=Math.floor(t%1*1e9);return e&&(r=r-e[0],n=n-e[1],n<0&&(r--,n+=1e9)),[r,n]}var su=new Date;function cu(){var e=new Date,t=e-su;return t/1e3}var ke={nextTick:te,title:$l,browser:Ul,env:zl,argv:Zl,version:ql,versions:Hl,on:Wl,addListener:Gl,once:Yl,off:Jl,removeListener:Xl,removeAllListeners:Ql,emit:eu,binding:tu,cwd:ru,chdir:nu,umask:iu,hrtime:ou,platform:Bl,release:Kl,config:Vl,uptime:cu},W;typeof Object.create=="function"?W=function(t,r){t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:W=function(t,r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t};var fu=/%[sdj%]/g;function lu(e){if(!ei(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(Ce(arguments[r]));return t.join(" ")}for(var r=1,n=arguments,i=n.length,a=String(e).replace(fu,function(s){if(s==="%%")return"%";if(r>=i)return s;switch(s){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch{return"[Circular]"}default:return s}}),o=n[r];r<i;o=n[++r])Qn(o)||!Pt(o)?a+=" "+o:a+=" "+Ce(o);return a}function No(e,t){if(De(pt.process))return function(){return No(e,t).apply(this,arguments)};if(ke.noDeprecation===!0)return e;var r=!1;function n(){if(!r){if(ke.throwDeprecation)throw new Error(t);ke.traceDeprecation?console.trace(t):console.error(t),r=!0}return e.apply(this,arguments)}return n}var gr={},Yn;function uu(e){if(De(Yn)&&(Yn=ke.env.NODE_DEBUG||""),e=e.toUpperCase(),!gr[e])if(new RegExp("\\b"+e+"\\b","i").test(Yn)){var t=0;gr[e]=function(){var r=lu.apply(null,arguments);console.error("%s %d: %s",e,t,r)}}else gr[e]=function(){};return gr[e]}function Ce(e,t){var r={seen:[],stylize:du};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),$o(t)?r.showHidden=t:t&&bu(r,t),De(r.showHidden)&&(r.showHidden=!1),De(r.depth)&&(r.depth=2),De(r.colors)&&(r.colors=!1),De(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=hu),vr(r,e,r.depth)}Ce.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]},Ce.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function hu(e,t){var r=Ce.styles[t];return r?"\x1B["+Ce.colors[r][0]+"m"+e+"\x1B["+Ce.colors[r][1]+"m":e}function du(e,t){return e}function pu(e){var t={};return e.forEach(function(r,n){t[r]=!0}),t}function vr(e,t,r){if(e.customInspect&&t&&ni(t.inspect)&&t.inspect!==Ce&&!(t.constructor&&t.constructor.prototype===t)){var n=t.inspect(r,e);return ei(n)||(n=vr(e,n,r)),n}var i=yu(e,t);if(i)return i;var a=Object.keys(t),o=pu(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),ri(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return Jn(t);if(a.length===0){if(ni(t)){var s=t.name?": "+t.name:"";return e.stylize("[Function"+s+"]","special")}if(ti(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(Bo(t))return e.stylize(Date.prototype.toString.call(t),"date");if(ri(t))return Jn(t)}var f="",c=!1,l=["{","}"];if(wu(t)&&(c=!0,l=["[","]"]),ni(t)){var d=t.name?": "+t.name:"";f=" [Function"+d+"]"}if(ti(t)&&(f=" "+RegExp.prototype.toString.call(t)),Bo(t)&&(f=" "+Date.prototype.toUTCString.call(t)),ri(t)&&(f=" "+Jn(t)),a.length===0&&(!c||t.length==0))return l[0]+f+l[1];if(r<0)return ti(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var h;return c?h=gu(e,t,r,o,a):h=a.map(function(u){return Xn(e,t,r,o,u,c)}),e.seen.pop(),vu(h,f,l)}function yu(e,t){if(De(t))return e.stylize("undefined","undefined");if(ei(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(_u(t))return e.stylize(""+t,"number");if($o(t))return e.stylize(""+t,"boolean");if(Qn(t))return e.stylize("null","null")}function Jn(e){return"["+Error.prototype.toString.call(e)+"]"}function gu(e,t,r,n,i){for(var a=[],o=0,s=t.length;o<s;++o)Uo(t,String(o))?a.push(Xn(e,t,r,n,String(o),!0)):a.push("");return i.forEach(function(f){f.match(/^\d+$/)||a.push(Xn(e,t,r,n,f,!0))}),a}function Xn(e,t,r,n,i,a){var o,s,f;if(f=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},f.get?f.set?s=e.stylize("[Getter/Setter]","special"):s=e.stylize("[Getter]","special"):f.set&&(s=e.stylize("[Setter]","special")),Uo(n,i)||(o="["+i+"]"),s||(e.seen.indexOf(f.value)<0?(Qn(r)?s=vr(e,f.value,null):s=vr(e,f.value,r-1),s.indexOf(`
|
|
21
|
-
`)>-1&&(a?s=s.split(`
|
|
22
|
-
`).map(function(c){return" "+c}).join(`
|
|
23
|
-
`).substr(2):s=`
|
|
24
|
-
`+s.split(`
|
|
25
|
-
`).map(function(c){return" "+c}).join(`
|
|
26
|
-
`))):s=e.stylize("[Circular]","special")),De(o)){if(a&&i.match(/^\d+$/))return s;o=JSON.stringify(""+i),o.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+": "+s}function vu(e,t,r){var n=e.reduce(function(i,a){return a.indexOf(`
|
|
27
|
-
`)>=0,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0);return n>60?r[0]+(t===""?"":t+`
|
|
28
|
-
`)+" "+e.join(`,
|
|
29
|
-
`)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}function wu(e){return Array.isArray(e)}function $o(e){return typeof e=="boolean"}function Qn(e){return e===null}function _u(e){return typeof e=="number"}function ei(e){return typeof e=="string"}function De(e){return e===void 0}function ti(e){return Pt(e)&&ii(e)==="[object RegExp]"}function Pt(e){return typeof e=="object"&&e!==null}function Bo(e){return Pt(e)&&ii(e)==="[object Date]"}function ri(e){return Pt(e)&&(ii(e)==="[object Error]"||e instanceof Error)}function ni(e){return typeof e=="function"}function ii(e){return Object.prototype.toString.call(e)}function bu(e,t){if(!t||!Pt(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}function Uo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Je(){this.head=null,this.tail=null,this.length=0}Je.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},Je.prototype.unshift=function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length},Je.prototype.shift=function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},Je.prototype.clear=function(){this.head=this.tail=null,this.length=0},Je.prototype.join=function(e){if(this.length===0)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},Je.prototype.concat=function(e){if(this.length===0)return g.alloc(0);if(this.length===1)return this.head.data;for(var t=g.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var mu=g.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 Eu(e){if(e&&!mu(e))throw new Error("Unknown encoding: "+e)}function Tt(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),Eu(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Su;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Au;break;default:this.write=xu;return}this.charBuffer=new g(6),this.charReceived=0,this.charLength=0}Tt.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"";e=e.slice(r,e.length),t=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=t.charCodeAt(t.length-1);if(i>=55296&&i<=56319){this.charLength+=this.surrogateSize,t="";continue}if(this.charReceived=this.charLength=0,e.length===0)return t;break}this.detectIncompleteChar(e);var n=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,n),n-=this.charReceived),t+=e.toString(this.encoding,0,n);var n=t.length-1,i=t.charCodeAt(n);if(i>=55296&&i<=56319){var a=this.surrogateSize;return this.charLength+=a,this.charReceived+=a,this.charBuffer.copy(this.charBuffer,a,0,a),e.copy(this.charBuffer,0,0,a),t.substring(0,n)}return t},Tt.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(t==1&&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},Tt.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function xu(e){return e.toString(this.encoding)}function Su(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Au(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}N.ReadableState=zo;var j=uu("stream");W(N,R);function ku(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}function Ru(e,t){return e.listeners(t).length}function zo(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof oe&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16*1024;this.highWaterMark=r||r===0?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Je,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 Tt(e.encoding),this.encoding=e.encoding)}function N(e){if(!(this instanceof N))return new N(e);this._readableState=new zo(e,this),this.readable=!0,e&&typeof e.read=="function"&&(this._read=e.read),R.call(this)}N.prototype.push=function(e,t){var r=this._readableState;return!r.objectMode&&typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=g.from(e,t),t="")),Zo(this,r,e,t,!1)},N.prototype.unshift=function(e){var t=this._readableState;return Zo(this,t,e,"",!0)},N.prototype.isPaused=function(){return this._readableState.flowing===!1};function Zo(e,t,r,n,i){var a=Pu(t,r);if(a)e.emit("error",a);else if(r===null)t.reading=!1,Tu(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var f;t.decoder&&!i&&!n&&(r=t.decoder.write(r),f=!t.objectMode&&r.length===0),i||(t.reading=!1),f||(t.flowing&&t.length===0&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&wr(e))),ju(e,t)}else i||(t.reading=!1);return Ou(t)}function Ou(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}N.prototype.setEncoding=function(e){return this._readableState.decoder=new Tt(e),this._readableState.encoding=e,this};var qo=8388608;function Iu(e){return e>=qo?e=qo:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function Ho(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=Iu(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}N.prototype.read=function(e){j("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return j("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?oi(this):wr(this),null;if(e=Ho(e,t),e===0&&t.ended)return t.length===0&&oi(this),null;var n=t.needReadable;j("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=!0,j("length less than watermark",n)),t.ended||t.reading?(n=!1,j("reading or ended",n)):n&&(j("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=Ho(r,t)));var i;return e>0?i=Vo(e,t):i=null,i===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&oi(this)),i!==null&&this.emit("data",i),i};function Pu(e,t){var r=null;return!g.isBuffer(t)&&typeof t!="string"&&t!==null&&t!==void 0&&!e.objectMode&&(r=new TypeError("Invalid non-string/buffer chunk")),r}function Tu(e,t){if(!t.ended){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,wr(e)}}function wr(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(j("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?te(Ko,e):Ko(e))}function Ko(e){j("emit readable"),e.emit("readable"),ai(e)}function ju(e,t){t.readingMore||(t.readingMore=!0,te(Fu,e,t))}function Fu(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(j("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=!1}N.prototype._read=function(e){this.emit("error",new Error("not implemented"))},N.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,j("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||t.end!==!1,a=i?s:l;n.endEmitted?te(a):r.once("end",a),e.on("unpipe",o);function o(_){j("onunpipe"),_===r&&l()}function s(){j("onend"),e.end()}var f=Cu(r);e.on("drain",f);var c=!1;function l(){j("cleanup"),e.removeListener("close",p),e.removeListener("finish",y),e.removeListener("drain",f),e.removeListener("error",u),e.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",l),r.removeListener("data",h),c=!0,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&f()}var d=!1;r.on("data",h);function h(_){j("ondata"),d=!1;var m=e.write(_);m===!1&&!d&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&Wo(n.pipes,e)!==-1)&&!c&&(j("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,d=!0),r.pause())}function u(_){j("onerror",_),w(),e.removeListener("error",u),Ru(e,"error")===0&&e.emit("error",_)}ku(e,"error",u);function p(){e.removeListener("finish",y),w()}e.once("close",p);function y(){j("onfinish"),e.removeListener("close",p),w()}e.once("finish",y);function w(){j("unpipe"),r.unpipe(e)}return e.emit("pipe",r),n.flowing||(j("pipe resume"),r.resume()),e};function Cu(e){return function(){var t=e._readableState;j("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&e.listeners("data").length&&(t.flowing=!0,ai(e))}}N.prototype.unpipe=function(e){var t=this._readableState;if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(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,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<n;i++)r[i].emit("unpipe",this);return this}var a=Wo(t.pipes,e);return a===-1?this:(t.pipes.splice(a,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this),this)},N.prototype.on=function(e,t){var r=R.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==!1&&this.resume();else if(e==="readable"){var n=this._readableState;!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&wr(this):te(Du,this))}return r},N.prototype.addListener=N.prototype.on;function Du(e){j("readable nexttick read 0"),e.read(0)}N.prototype.resume=function(){var e=this._readableState;return e.flowing||(j("resume"),e.flowing=!0,Mu(this,e)),this};function Mu(e,t){t.resumeScheduled||(t.resumeScheduled=!0,te(Lu,e,t))}function Lu(e,t){t.reading||(j("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),ai(e),t.flowing&&!t.reading&&e.read(0)}N.prototype.pause=function(){return j("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(j("pause"),this._readableState.flowing=!1,this.emit("pause")),this};function ai(e){var t=e._readableState;for(j("flow",t.flowing);t.flowing&&e.read()!==null;);}N.prototype.wrap=function(e){var t=this._readableState,r=!1,n=this;e.on("end",function(){if(j("wrapped end"),t.decoder&&!t.ended){var o=t.decoder.end();o&&o.length&&n.push(o)}n.push(null)}),e.on("data",function(o){if(j("wrapped data"),t.decoder&&(o=t.decoder.write(o)),!(t.objectMode&&o==null)&&!(!t.objectMode&&(!o||!o.length))){var s=n.push(o);s||(r=!0,e.pause())}});for(var i in e)this[i]===void 0&&typeof e[i]=="function"&&(this[i]=function(o){return function(){return e[o].apply(e,arguments)}}(i));var a=["error","close","destroy","pause","resume"];return zu(a,function(o){e.on(o,n.emit.bind(n,o))}),n._read=function(o){j("wrapped _read",o),r&&(r=!1,e.resume())},n},N._fromList=Vo;function Vo(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.head.data:r=t.buffer.concat(t.length),t.buffer.clear()):r=Nu(e,t.buffer,t.decoder),r}function Nu(e,t,r){var n;return e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?n=t.shift():n=r?$u(e,t):Bu(e,t),n}function $u(e,t){var r=t.head,n=1,i=r.data;for(e-=i.length;r=r.next;){var a=r.data,o=e>a.length?a.length:e;if(o===a.length?i+=a:i+=a.slice(0,e),e-=o,e===0){o===a.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=a.slice(o));break}++n}return t.length-=n,i}function Bu(e,t){var r=g.allocUnsafe(e),n=t.head,i=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var a=n.data,o=e>a.length?a.length:e;if(a.copy(r,r.length-e,0,o),e-=o,e===0){o===a.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(o));break}++i}return t.length-=i,r}function oi(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,te(Uu,t,e))}function Uu(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function zu(e,t){for(var r=0,n=e.length;r<n;r++)t(e[r],r)}function Wo(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}H.WritableState=si,W(H,R);function Zu(){}function qu(e,t,r){this.chunk=e,this.encoding=t,this.callback=r,this.next=null}function si(e,t){Object.defineProperty(this,"buffer",{get:No(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),e=e||{},this.objectMode=!!e.objectMode,t instanceof oe&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16*1024;this.highWaterMark=r||r===0?r:n,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var i=e.decodeStrings===!1;this.decodeStrings=!i,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(a){Ju(t,a)},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 es(this)}si.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};function H(e){if(!(this instanceof H)&&!(this instanceof oe))return new H(e);this._writableState=new si(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev)),R.call(this)}H.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function Hu(e,t){var r=new Error("write after end");e.emit("error",r),te(t,r)}function Ku(e,t,r,n){var i=!0,a=!1;return r===null?a=new TypeError("May not write null values to stream"):!g.isBuffer(r)&&typeof r!="string"&&r!==void 0&&!t.objectMode&&(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),te(n,a),i=!1),i}H.prototype.write=function(e,t,r){var n=this._writableState,i=!1;return typeof t=="function"&&(r=t,t=null),g.isBuffer(e)?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=Zu),n.ended?Hu(this,r):Ku(this,n,e,r)&&(n.pendingcb++,i=Wu(this,n,e,t,r)),i},H.prototype.cork=function(){var e=this._writableState;e.corked++},H.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest&&Yo(this,e))},H.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(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};function Vu(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=g.from(t,r)),t}function Wu(e,t,r,n,i){r=Vu(t,r,n),g.isBuffer(r)&&(n="buffer");var a=t.objectMode?1:r.length;t.length+=a;var o=t.length<t.highWaterMark;if(o||(t.needDrain=!0),t.writing||t.corked){var s=t.lastBufferedRequest;t.lastBufferedRequest=new qu(r,n,i),s?s.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else ci(e,t,!1,a,r,n,i);return o}function ci(e,t,r,n,i,a,o){t.writelen=n,t.writecb=o,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function Gu(e,t,r,n,i){--t.pendingcb,r?te(i,n):i(n),e._writableState.errorEmitted=!0,e.emit("error",n)}function Yu(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function Ju(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(Yu(r),t)Gu(e,r,n,t,i);else{var a=Jo(r);!a&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&Yo(e,r),n?te(Go,e,r,a,i):Go(e,r,a,i)}}function Go(e,t,r,n){r||Xu(e,t),t.pendingcb--,n(),Qo(e,t)}function Xu(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function Yo(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var o=0;r;)i[o]=r,r=r.next,o+=1;ci(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new es(t)}else{for(;r;){var s=r.chunk,f=r.encoding,c=r.callback,l=t.objectMode?1:s.length;if(ci(e,t,!1,l,s,f,c),r=r.next,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequestCount=0,t.bufferedRequest=r,t.bufferProcessing=!1}H.prototype._write=function(e,t,r){r(new Error("not implemented"))},H.prototype._writev=null,H.prototype.end=function(e,t,r){var n=this._writableState;typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),!n.ending&&!n.finished&&Qu(this,n,r)};function Jo(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function Xo(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function Qo(e,t){var r=Jo(t);return r&&(t.pendingcb===0?(Xo(e,t),t.finished=!0,e.emit("finish")):Xo(e,t)),r}function Qu(e,t,r){t.ending=!0,Qo(e,t),r&&(t.finished?te(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function es(e){var t=this;this.next=null,this.entry=null,this.finish=function(r){var n=t.entry;for(t.entry=null;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}}W(oe,N);for(var ts=Object.keys(H.prototype),fi=0;fi<ts.length;fi++){var li=ts[fi];oe.prototype[li]||(oe.prototype[li]=H.prototype[li])}function oe(e){if(!(this instanceof oe))return new oe(e);N.call(this,e),H.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",eh)}function eh(){this.allowHalfOpen||this._writableState.ended||te(th,this)}function th(e){e.end()}W(re,oe);function rh(e){this.afterTransform=function(t,r){return nh(e,t,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function nh(e,t,r){var n=e._transformState;n.transforming=!1;var i=n.writecb;if(!i)return e.emit("error",new Error("no writecb in Transform class"));n.writechunk=null,n.writecb=null,r!=null&&e.push(r),i(t);var a=e._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&e._read(a.highWaterMark)}function re(e){if(!(this instanceof re))return new re(e);oe.call(this,e),this._transformState=new rh(this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.once("prefinish",function(){typeof this._flush=="function"?this._flush(function(r){rs(t,r)}):rs(t)})}re.prototype.push=function(e,t){return this._transformState.needTransform=!1,oe.prototype.push.call(this,e,t)},re.prototype._transform=function(e,t,r){throw new Error("Not implemented")},re.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},re.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};function rs(e,t){if(t)return e.emit("error",t);var r=e._writableState,n=e._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 e.push(null)}W(jt,re);function jt(e){if(!(this instanceof jt))return new jt(e);re.call(this,e)}jt.prototype._transform=function(e,t,r){r(null,e)},W(Re,R),Re.Readable=N,Re.Writable=H,Re.Duplex=oe,Re.Transform=re,Re.PassThrough=jt,Re.Stream=Re;function Re(){R.call(this)}Re.prototype.pipe=function(e,t){var r=this;function n(l){e.writable&&e.write(l)===!1&&r.pause&&r.pause()}r.on("data",n);function i(){r.readable&&r.resume&&r.resume()}e.on("drain",i),!e._isStdio&&(!t||t.end!==!1)&&(r.on("end",o),r.on("close",s));var a=!1;function o(){a||(a=!0,e.end())}function s(){a||(a=!0,typeof e.destroy=="function"&&e.destroy())}function f(l){if(c(),R.listenerCount(this,"error")===0)throw l}r.on("error",f),e.on("error",f);function c(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",o),r.removeListener("close",s),r.removeListener("error",f),e.removeListener("error",f),r.removeListener("end",c),r.removeListener("close",c),e.removeListener("close",c)}return r.on("end",c),r.on("close",c),e.on("close",c),e.emit("pipe",r),e};class ns extends R{constructor({resource:t}){super(),this.resource=t,this.client=t.client,this.stream=new Vc.ReadableStream({highWaterMark:this.client.parallelism*3,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){t.close();return}const r=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),n=r?.Contents.map(i=>i.Key).map(i=>i.replace(this.client.config.keyPrefix,"")).map(i=>i.startsWith("/")?i.replace("/",""):i).map(i=>i.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=r.NextContinuationToken,this.enqueue(n),r.IsTruncated||(this.closeNextIteration=!0)}enqueue(t){t.forEach(r=>{this.controller.enqueue(r),this.emit("id",r)})}_cancel(t){console.warn("Stream cancelled",t)}}class is extends ns{enqueue(t){this.controller.enqueue(t),this.emit("page",t)}}class as extends R{constructor({resource:t,batchSize:r=10,concurrency:n=5}){if(super(),!t)throw new Error("Resource is required for ResourceReader");this.resource=t,this.client=t.client,this.batchSize=r,this.concurrency=n,this.input=new is({resource:this.resource}),this.transform=new re({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",i=>{this.transform.write(i)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",i=>{this.emit("error",i)}),this.transform.on("data",i=>{this.emit("data",i)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",i=>{this.emit("error",i)})}build(){return this}async _transform(t,r,n){try{await de.PromisePool.for(t).withConcurrency(this.concurrency).handleError(async(i,a)=>{this.emit("error",i,a)}).process(async i=>{const a=await this.resource.get(i);return this.push(a),a}),n()}catch(i){n(i)}}resume(){this.input.resume()}}class os extends R{constructor({resource:t,batchSize:r=10,concurrency:n=5}){super(),this.resource=t,this.client=t.client,this.batchSize=r,this.concurrency=n,this.buffer=[],this.writing=!1,this.writable=new H({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",i=>{this.emit("error",i)})}build(){return this}write(t){return this.buffer.push(t),this._maybeWrite().catch(r=>{this.emit("error",r)}),!0}end(){this.ended=!0,this._maybeWrite().catch(t=>{this.emit("error",t)})}async _maybeWrite(){if(!this.writing&&!(this.buffer.length===0&&!this.ended)){for(this.writing=!0;this.buffer.length>0;){const t=this.buffer.splice(0,this.batchSize);try{await de.PromisePool.for(t).withConcurrency(this.concurrency).handleError(async(r,n)=>{this.emit("error",r,n)}).process(async r=>{await this.resource.insert(r)})}catch(r){this.emit("error",r)}}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(t,r,n){n()}}function vt(e){return new Promise((t,r)=>{const n=[];e.on("data",i=>n.push(i)),e.on("error",r),e.on("end",()=>t(Buffer.concat(n).toString("utf-8")))})}function Xe(e){typeof e!="string"&&(e=String(e));let t=0;for(let r=0;r<e.length;r++){const n=e.codePointAt(r);n<=127?t+=1:n<=2047?t+=2:n<=65535?t+=3:n<=1114111&&(t+=4,n>65535&&r++)}return t}function ui(e){let t=0;for(const r of Object.keys(e))t+=Xe(r);return t}function hi(e){return e==null?"":typeof e=="boolean"?e?"1":"0":typeof e=="number"?String(e):typeof e=="string"?e:Array.isArray(e)?e.length===0?"[]":e.map(t=>String(t)).join("|"):typeof e=="object"?JSON.stringify(e):String(e)}function Ft(e){const t={};for(const[r,n]of Object.entries(e)){const i=hi(n),a=Xe(i);t[r]=a}return t}function Me(e){const t=Ft(e),r=Object.values(t).reduce((i,a)=>i+a,0),n=ui(e);return r+n}function ih(e){const t=Ft(e),r=ui(e),n=Object.values(t).reduce((o,s)=>o+s,0),i=n+r,a=Object.entries(t).sort(([,o],[,s])=>s-o).map(([o,s])=>({attribute:o,size:s,percentage:(s/i*100).toFixed(2)+"%"}));return{total:i,valueSizes:t,namesSize:r,valueTotal:n,breakdown:a,detailedBreakdown:{values:n,names:r,total:i}}}const B=2048;async function ah({resource:e,data:t,mappedData:r}){const n=Me(r);if(n>B)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, limit: ${B} bytes`);return{mappedData:r,body:""}}async function oh({resource:e,id:t,data:r,mappedData:n}){const i=Me(n);if(i>B)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${i} bytes, limit: ${B} bytes`);return{mappedData:n,body:""}}async function sh({resource:e,id:t,data:r,mappedData:n}){const i=Me(n);if(i>B)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${i} bytes, limit: ${B} bytes`);return{mappedData:n,body:""}}async function ch({resource:e,metadata:t,body:r}){return{metadata:t,body:r}}var fh=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:B,handleGet:ch,handleInsert:ah,handleUpdate:oh,handleUpsert:sh});async function lh({resource:e,data:t,mappedData:r}){const n=Me(r);return n>B&&e.emit("exceedsLimit",{operation:"insert",totalSize:n,limit:B,excess:n-B,data:t}),{mappedData:r,body:""}}async function uh({resource:e,id:t,data:r,mappedData:n}){const i=Me(n);return i>B&&e.emit("exceedsLimit",{operation:"update",id:t,totalSize:i,limit:B,excess:i-B,data:r}),{mappedData:n,body:""}}async function hh({resource:e,id:t,data:r,mappedData:n}){const i=Me(n);return i>B&&e.emit("exceedsLimit",{operation:"upsert",id:t,totalSize:i,limit:B,excess:i-B,data:r}),{mappedData:n,body:""}}async function dh({resource:e,metadata:t,body:r}){return{metadata:t,body:r}}var ph=Object.freeze({__proto__:null,handleGet:dh,handleInsert:lh,handleUpdate:uh,handleUpsert:hh});const ss="...",cs=Xe(ss);async function yh({resource:e,data:t,mappedData:r}){return di({resource:e,data:t,mappedData:r})}async function gh({resource:e,id:t,data:r,mappedData:n}){return di({resource:e,data:r,mappedData:n})}async function vh({resource:e,id:t,data:r,mappedData:n}){return di({resource:e,data:r,mappedData:n})}async function wh({resource:e,metadata:t,body:r}){return{metadata:t,body:r}}function di({resource:e,data:t,mappedData:r}){const n=Ft(r),i=Object.entries(n).sort(([,s],[,f])=>s-f),a={};let o=0;for(const[s,f]of i){const c=B-o;if(f<=c)a[s]=r[s],o+=f;else if(c>cs){const l=c-cs,d=hi(r[s]);let h="",u=0;for(let p=0;p<d.length;p++){const y=d[p],w=Xe(y);if(u+w<=l)h+=y,u+=w;else break}a[s]=h+ss,o=B;break}else break}return{mappedData:a,body:""}}var _h=Object.freeze({__proto__:null,handleGet:wh,handleInsert:yh,handleUpdate:gh,handleUpsert:vh});const _r="$overflow",pi="true",bh=Xe(_r)+Xe(pi);async function mh({resource:e,data:t,mappedData:r}){return yi({resource:e,data:t,mappedData:r})}async function Eh({resource:e,id:t,data:r,mappedData:n}){return yi({resource:e,data:r,mappedData:n})}async function xh({resource:e,id:t,data:r,mappedData:n}){return yi({resource:e,data:r,mappedData:n})}async function Sh({resource:e,metadata:t,body:r}){if(t[_r]===pi)try{const n=r?JSON.parse(r):{},i={...t};return delete i[_r],{metadata:{...i,...n},body:""}}catch{return{metadata:t,body:r}}return{metadata:t,body:r}}function yi({resource:e,data:t,mappedData:r}){if(Me(r)<=B)return{mappedData:r,body:""};const i=B-bh,a=Ft(r),o=Object.entries(a).sort(([,d],[,h])=>d-h),s={},f={};let c=0;for(const[d,h]of o)c+h<=i?(s[d]=r[d],c+=h):f[d]=r[d];s[_r]=pi;const l=Object.keys(f).length>0?JSON.stringify(f):"";return{mappedData:s,body:l}}var Ah=Object.freeze({__proto__:null,handleGet:Sh,handleInsert:mh,handleUpdate:Eh,handleUpsert:xh});const br={"user-management":ph,"enforce-limits":fh,"data-truncate":_h,"body-overflow":Ah};function we(e){const t=br[e];if(!t)throw new Error(`Unknown behavior: ${e}. Available behaviors: ${Object.keys(br).join(", ")}`);return t}const kh=Object.keys(br),fs="user-management";class mr extends R{constructor(t){super();const r=Rh(t);if(!r.isValid)throw new Error(`Invalid Resource configuration:
|
|
30
|
-
${r.errors.join(`
|
|
31
|
-
`)}`);const{name:n,client:i,version:a="1",attributes:o={},behavior:s=fs,passphrase:f="secret",parallelism:c=10,observers:l=[],cache:d=!1,autoDecrypt:h=!0,timestamps:u=!1,partitions:p={},paranoid:y=!0,allNestedObjectsOptional:w=!0,hooks:_={}}=t;if(this.name=n,this.client=i,this.version=a,this.behavior=s,this.observers=l,this.parallelism=c,this.passphrase=f??"secret",this.config={cache:d,hooks:_,paranoid:y,timestamps:u,partitions:p,autoDecrypt:h,allNestedObjectsOptional:w},this.hooks={preInsert:[],afterInsert:[],preUpdate:[],afterUpdate:[],preDelete:[],afterDelete:[]},this.attributes=o||{},this.applyConfiguration(),_){for(const[m,E]of Object.entries(_))if(Array.isArray(E)&&this.hooks[m])for(const v of E)typeof v=="function"&&this.hooks[m].push(v.bind(this))}}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.schema=new me({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 r=this.attributes;return this.attributes=t,this.applyConfiguration(),{oldAttributes:r,newAttributes:t}}addHook(t,r){this.hooks[t]&&this.hooks[t].push(r.bind(this))}async executeHooks(t,r){if(!this.hooks[t])return r;let n=r;for(const i of this.hooks[t])n=await i(n);return n}setupPartitionHooks(){if(!this.config.partitions)return;const t=this.config.partitions;Object.keys(t).length!==0&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async r=>(await this.createPartitionReferences(r),r)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async r=>(await this.deletePartitionReferences(r),r)))}async validate(t){const r={original:L.cloneDeep(t),isValid:!1,errors:[]},n=await this.schema.validate(t,{mutateOriginal:!0});return n===!0?r.isValid=!0:r.errors=n,r.data=t,r}validatePartitions(){if(!this.config.partitions)return;const t=this.config.partitions;if(Object.keys(t).length===0)return;const r=Object.keys(this.attributes||{});for(const[n,i]of Object.entries(t))if(i.fields){for(const a of Object.keys(i.fields))if(!this.fieldExistsInAttributes(a))throw new Error(`Partition '${n}' uses field '${a}' which does not exist in resource attributes. Available fields: ${r.join(", ")}.`)}}fieldExistsInAttributes(t){if(!t.includes("."))return Object.keys(this.attributes||{}).includes(t);const r=t.split(".");let n=this.attributes||{};for(const i of r){if(!n||typeof n!="object"||!(i in n))return!1;n=n[i]}return!0}applyPartitionRule(t,r){if(t==null)return t;let n=t;if(typeof r=="string"&&r.includes("maxlength:")){const i=r.match(/maxlength:(\d+)/);if(i){const a=parseInt(i[1]);typeof n=="string"&&n.length>a&&(n=n.substring(0,a))}}if(r.includes("date")){if(n instanceof Date)n=n.toISOString().split("T")[0];else if(typeof n=="string")try{if(n.includes("T")&&n.includes("Z"))n=n.split("T")[0];else{const i=new Date(n);isNaN(i.getTime())||(n=i.toISOString().split("T")[0])}}catch{}}return n}getResourceKey(t){return xe(`resource=${this.name}`,`v=${this.version}`,`id=${t}`)}getPartitionKey({partitionName:t,id:r,data:n}){if(!this.config.partitions||!this.config.partitions[t])throw new Error(`Partition '${t}' not found`);const i=this.config.partitions[t],a=[],o=Object.entries(i.fields).sort(([f],[c])=>f.localeCompare(c));for(const[f,c]of o){const l=this.getNestedFieldValue(n,f),d=this.applyPartitionRule(l,c);if(d==null)return null;a.push(`${f}=${d}`)}if(a.length===0)return null;const s=r||n?.id;return s?xe(`resource=${this.name}`,`partition=${t}`,...a,`id=${s}`):null}getNestedFieldValue(t,r){if(!r.includes("."))return t[r];const n=r.split(".");let i=t;for(const a of n){if(!i||typeof i!="object"||!(a in i))return;i=i[a]}return i}async insert({id:t,...r}){this.options.timestamps&&(r.createdAt=new Date().toISOString(),r.updatedAt=new Date().toISOString());const n=await this.executeHooks("preInsert",r),{errors:i,isValid:a,data:o}=await this.validate(n);if(!a)throw new nr({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:i});!t&&t!==0&&(t=Zr());const s=await this.schema.mapper(o),f=we(this.behavior),{mappedData:c,body:l}=await f.handleInsert({resource:this,data:o,mappedData:s}),d=this.getResourceKey(t);await this.client.putObject({metadata:c,key:d,body:l});const h=L.merge({id:t},o);return await this.executeHooks("afterInsert",h),this.emit("insert",h),h}async get(t){const r=this.getResourceKey(t);try{const n=await this.client.headObject(r),i=this.extractVersionFromKey(r)||this.version;let o=await(await this.getSchemaForVersion(i)).unmapper(n.Metadata);const s=we(this.behavior);let f="";if(n.ContentLength>0)try{const d=await this.client.getObject(r);f=await vt(d.Body)}catch(d){console.warn(`Failed to read body for resource ${t}:`,d.message),f=""}const{metadata:c}=await s.handleGet({resource:this,metadata:o,body:f});let l=c;return l.id=t,l._contentLength=n.ContentLength,l._lastModified=n.LastModified,l._hasContent=n.ContentLength>0,l._mimeType=n.ContentType||null,n.VersionId&&(l._versionId=n.VersionId),n.Expiration&&(l._expiresAt=n.Expiration),l._definitionHash=this.getDefinitionHash(),this.emit("get",l),l}catch(n){if(n.message.includes("Cipher job failed")||n.message.includes("OperationError")||n.originalError?.message?.includes("Cipher job failed"))try{console.warn(`Decryption failed for resource ${t}, attempting to get raw metadata`);const a=await this.client.headObject(r),o=this.extractVersionFromKey(r)||this.version;let f=await new me({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:o,options:{...this.config,autoDecrypt:!1,autoEncrypt:!1}}).unmapper(a.Metadata);const c=we(this.behavior);let l="";if(a.ContentLength>0)try{const u=await this.client.getObject(r);l=await vt(u.Body)}catch(u){console.warn(`Failed to read body for resource ${t}:`,u.message),l=""}const{metadata:d}=await c.handleGet({resource:this,metadata:f,body:l});let h=d;return h.id=t,h._contentLength=a.ContentLength,h._lastModified=a.LastModified,h._hasContent=a.ContentLength>0,h._mimeType=a.ContentType||null,h._version=o,h._decryptionFailed=!0,a.VersionId&&(h._versionId=a.VersionId),a.Expiration&&(h._expiresAt=a.Expiration),h._definitionHash=this.getDefinitionHash(),this.emit("get",h),h}catch(a){console.error(`Fallback attempt also failed for resource ${t}:`,a.message)}const i=new Error(`Failed to get resource with id '${t}': ${n.message}`);throw i.originalError=n,i.resourceId=t,i.resourceKey=r,i}}async exists(t){try{const r=this.getResourceKey(t);return await this.client.headObject(r),!0}catch{return!1}}async update(t,r){const n=await this.get(t);this.config.timestamps&&(r.updatedAt=new Date().toISOString());const i=await this.executeHooks("preUpdate",r),a=L.merge(n,i);delete a.id;const{isValid:o,errors:s,data:f}=await this.validate(a);if(!o)throw new nr({bucket:this.client.bucket,resourceName:this.name,attributes:i,validation:s});const c={...n,id:t},l={...f,id:t};await this.handlePartitionReferenceUpdates(c,l);const d=await this.schema.mapper(f),h=we(this.behavior),{mappedData:u,body:p}=await h.handleUpdate({resource:this,id:t,data:f,mappedData:d}),y=this.getResourceKey(t);let w,_=p;if(p===""&&this.behavior!=="body-overflow")try{const m=await this.client.getObject(y);if(m.ContentLength>0){const E=Buffer.from(await m.Body.transformToByteArray()),v=E.toString();try{JSON.parse(v)}catch{_=E,w=m.ContentType}}}catch{}return await this.client.putObject({key:y,body:_,contentType:w,metadata:u}),f.id=t,await this.executeHooks("afterUpdate",f),this.emit("update",i,f),f}async delete(t){let r;try{r=await this.get(t)}catch{r={id:t}}await this.executeHooks("preDelete",r);const n=this.getResourceKey(t),i=await this.client.deleteObject(n);return await this.executeHooks("afterDelete",r),this.emit("delete",t),i}async upsert({id:t,...r}){return await this.exists(t)?this.update(t,r):this.insert({id:t,...r})}async count({partition:t=null,partitionValues:r={}}={}){let n;if(t&&Object.keys(r).length>0){const a=this.config.partitions[t];if(!a)throw new Error(`Partition '${t}' not found`);const o=[],s=Object.entries(a.fields).sort(([f],[c])=>f.localeCompare(c));for(const[f,c]of s){const l=r[f];if(l!=null){const d=this.applyPartitionRule(l,c);o.push(`${f}=${d}`)}}o.length>0?n=`resource=${this.name}/partition=${t}/${o.join("/")}`:n=`resource=${this.name}/partition=${t}`}else n=`resource=${this.name}/v=${this.version}`;const i=await this.client.count({prefix:n});return this.emit("count",i),i}async insertMany(t){const{results:r}=await de.PromisePool.for(t).withConcurrency(this.parallelism).handleError(async(n,i)=>{this.emit("error",n,i),this.observers.map(a=>a.emit("error",this.name,n,i))}).process(async n=>await this.insert(n));return this.emit("insertMany",t.length),r}async deleteMany(t){const r=L.chunk(t.map(i=>this.getResourceKey(i)),1e3),{results:n}=await de.PromisePool.for(r).withConcurrency(this.parallelism).handleError(async(i,a)=>{this.emit("error",i,a),this.observers.map(o=>o.emit("error",this.name,i,a))}).process(async i=>{const a=await this.client.deleteObjects(i);return i.forEach(o=>{const f=o.split("/").find(l=>l.startsWith("id=")),c=f?f.replace("id=",""):null;c&&(this.emit("deleted",c),this.observers.map(l=>l.emit("deleted",this.name,c)))}),a});return this.emit("deleteMany",t.length),n}async deleteAll(){if(this.config.paranoid!==!1)throw new Error(`deleteAll() is a dangerous operation and requires paranoid: false option. Current paranoid setting: ${this.config.paranoid}`);const t=`resource=${this.name}/v=${this.version}`,r=await this.client.deleteAll({prefix:t});return this.emit("deleteAll",{version:this.version,prefix:t,deletedCount:r}),{deletedCount:r,version:this.version}}async deleteAllData(){if(this.config.paranoid!==!1)throw new Error(`deleteAllData() is a dangerous operation and requires paranoid: false option. Current paranoid setting: ${this.config.paranoid}`);const t=`resource=${this.name}`,r=await this.client.deleteAll({prefix:t});return this.emit("deleteAllData",{resource:this.name,prefix:t,deletedCount:r}),{deletedCount:r,resource:this.name}}async listIds({partition:t=null,partitionValues:r={},limit:n,offset:i=0}={}){let a;if(t&&Object.keys(r).length>0){if(!this.config.partitions||!this.config.partitions[t])throw new Error(`Partition '${t}' not found`);const f=this.config.partitions[t],c=[],l=Object.entries(f.fields).sort(([d],[h])=>d.localeCompare(h));for(const[d,h]of l){const u=r[d];if(u!=null){const p=this.applyPartitionRule(u,h);c.push(`${d}=${p}`)}}c.length>0?a=`resource=${this.name}/partition=${t}/${c.join("/")}`:a=`resource=${this.name}/partition=${t}`}else a=`resource=${this.name}/v=${this.version}`;const s=(await this.client.getKeysPage({prefix:a,offset:i,amount:n||1e3})).map(f=>{const l=f.split("/").find(d=>d.startsWith("id="));return l?l.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",s.length),s}async list({partition:t=null,partitionValues:r={},limit:n,offset:i=0}={}){try{if(!t){let y=[];try{y=await this.listIds({partition:t,partitionValues:r})}catch(v){return console.warn("Failed to get list IDs:",v.message),[]}let w=y.slice(i);n&&(w=w.slice(0,n));const{results:_,errors:m}=await de.PromisePool.for(w).withConcurrency(this.parallelism).handleError(async(v,A)=>(console.warn(`Failed to get resource ${A}:`,v.message),null)).process(async v=>{try{return await this.get(v)}catch(A){if(A.message.includes("Cipher job failed")||A.message.includes("OperationError"))return console.warn(`Decryption failed for ${v}, returning basic info`),{id:v,_decryptionFailed:!0,_error:A.message};throw A}}),E=_.filter(v=>v!==null);return this.emit("list",{partition:t,partitionValues:r,count:E.length,errors:m.length}),E}if(!this.config.partitions||!this.config.partitions[t])return console.warn(`Partition '${t}' not found in resource '${this.name}'`),this.emit("list",{partition:t,partitionValues:r,count:0,errors:0}),[];const a=this.config.partitions[t],o=[],s=Object.entries(a.fields).sort(([y],[w])=>y.localeCompare(w));for(const[y,w]of s){const _=r[y];if(_!=null){const m=this.applyPartitionRule(_,w);o.push(`${y}=${m}`)}}let f;o.length>0?f=`resource=${this.name}/partition=${t}/${o.join("/")}`:f=`resource=${this.name}/partition=${t}`;let c=[];try{c=await this.client.getAllKeys({prefix:f})}catch(y){return console.warn("Failed to get partition keys:",y.message),[]}let d=c.map(y=>{const _=y.split("/").find(m=>m.startsWith("id="));return _?_.replace("id=",""):null}).filter(Boolean).slice(i);n&&(d=d.slice(0,n));const{results:h,errors:u}=await de.PromisePool.for(d).withConcurrency(this.parallelism).handleError(async(y,w)=>(console.warn(`Failed to get partition resource ${w}:`,y.message),null)).process(async y=>{try{const w=c.find(E=>E.includes(`id=${y}`));if(!w)throw new Error(`Partition key not found for ID ${y}`);const _=w.split("/"),m={};for(const[E,v]of s){const A=_.find(O=>O.startsWith(`${E}=`));if(A){const O=A.replace(`${E}=`,"");m[E]=O}}return await this.getFromPartition({id:y,partitionName:t,partitionValues:m})}catch(w){if(w.message.includes("Cipher job failed")||w.message.includes("OperationError"))return console.warn(`Decryption failed for partition resource ${y}, returning basic info`),{id:y,_partition:t,_partitionValues:r,_decryptionFailed:!0,_error:w.message};throw w}}),p=h.filter(y=>y!==null);return this.emit("list",{partition:t,partitionValues:r,count:p.length,errors:u.length}),p}catch(a){return a.message.includes("Partition '")&&a.message.includes("' not found")?(console.warn("Partition error in list method:",a.message),this.emit("list",{partition:t,partitionValues:r,count:0,errors:1}),[]):(console.error("Critical error in list method:",a.message),this.emit("list",{partition:t,partitionValues:r,count:0,errors:1}),[])}}async getMany(t){const{results:r,errors:n}=await de.PromisePool.for(t).withConcurrency(this.client.parallelism).handleError(async(i,a)=>(console.warn(`Failed to get resource ${a}:`,i.message),{id:a,_error:i.message,_decryptionFailed:i.message.includes("Cipher job failed")||i.message.includes("OperationError")})).process(async i=>{this.emit("id",i);try{const a=await this.get(i);return this.emit("data",a),a}catch(a){if(a.message.includes("Cipher job failed")||a.message.includes("OperationError"))return console.warn(`Decryption failed for ${i}, returning basic info`),{id:i,_decryptionFailed:!0,_error:a.message};throw a}});return this.emit("getMany",t.length),r}async getAll(){let t=await this.listIds();if(t.length===0)return[];const{results:r,errors:n}=await de.PromisePool.for(t).withConcurrency(this.client.parallelism).handleError(async(i,a)=>(console.warn(`Failed to get resource ${a}:`,i.message),{id:a,_error:i.message,_decryptionFailed:i.message.includes("Cipher job failed")||i.message.includes("OperationError")})).process(async i=>{try{return await this.get(i)}catch(a){if(a.message.includes("Cipher job failed")||a.message.includes("OperationError"))return console.warn(`Decryption failed for ${i}, returning basic info`),{id:i,_decryptionFailed:!0,_error:a.message};throw a}});return this.emit("getAll",r.length),r}async page({offset:t=0,size:r=100,partition:n=null,partitionValues:i={},skipCount:a=!1}={}){try{let o=null,s=null;if(!a)try{o=await this.count({partition:n,partitionValues:i}),s=Math.ceil(o/r)}catch(d){console.warn("Failed to get count for page:",d.message),o=null,s=null}const f=Math.floor(t/r);let c=[];try{c=await this.list({partition:n,partitionValues:i,limit:r,offset:t})}catch(d){console.warn("Failed to get items for page:",d.message),c=[]}const l={items:c,totalItems:o,page:f,pageSize:r,totalPages:s,_debug:{requestedSize:r,requestedOffset:t,actualItemsReturned:c.length,skipCount:a,hasTotalItems:o!==null}};return this.emit("page",l),l}catch(o){return console.error("Critical error in page method:",o.message),{items:[],totalItems:null,page:Math.floor(t/r),pageSize:r,totalPages:null,_debug:{requestedSize:r,requestedOffset:t,actualItemsReturned:0,skipCount:a,hasTotalItems:!1,error:o.message}}}}readable(){return new as({resource:this}).build()}writable(){return new os({resource:this}).build()}async setContent({id:t,buffer:r,contentType:n="application/octet-stream"}){const i=await this.get(t);if(!i)throw new Error(`Resource with id '${t}' not found`);const a={...i,_hasContent:!0,_contentLength:r.length,_mimeType:n};return await this.client.putObject({key:this.getResourceKey(t),metadata:await this.schema.mapper(a),body:r,contentType:n}),this.emit("setContent",{id:t,contentType:n,contentLength:r.length}),a}async content(t){const r=this.getResourceKey(t);try{const n=await this.client.getObject(r),i=Buffer.from(await n.Body.transformToByteArray()),a=n.ContentType||null;return this.emit("content",t,i.length,a),{buffer:i,contentType:a}}catch(n){if(n.name==="NoSuchKey")return{buffer:null,contentType:null};throw n}}async hasContent(t){const r=this.getResourceKey(t);try{return(await this.client.headObject(r)).ContentLength>0}catch{return!1}}async deleteContent(t){const r=this.getResourceKey(t),i=(await this.client.headObject(r)).Metadata||{},a=await this.client.putObject({key:r,body:"",metadata:i});return this.emit("deleteContent",t),a}getDefinitionHash(){const t={attributes:this.attributes,behavior:this.behavior},r=ho(t);return`sha256:${qi.createHash("sha256").update(r).digest("hex")}`}extractVersionFromKey(t){const n=t.split("/").find(i=>i.startsWith("v="));return n?n.replace("v=",""):null}async getSchemaForVersion(t){if(t===this.version)return this.schema;try{return new me({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:t,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})}catch(r){return console.warn(`Failed to create compatible schema for version ${t}, using current schema:`,r.message),this.schema}}async createPartitionReferences(t){const r=this.config.partitions;if(!(!r||Object.keys(r).length===0))for(const[n,i]of Object.entries(r)){const a=this.getPartitionKey({partitionName:n,id:t.id,data:t});if(a){const o=await this.schema.mapper(t),s=we(this.behavior),{mappedData:f,body:c}=await s.handleInsert({resource:this,data:t,mappedData:o}),l={...f,_version:this.version};await this.client.putObject({key:a,metadata:l,body:c})}}}async deletePartitionReferences(t){const r=this.config.partitions;if(!r||Object.keys(r).length===0)return;const n=[];for(const[i,a]of Object.entries(r)){const o=this.getPartitionKey({partitionName:i,id:t.id,data:t});o&&n.push(o)}if(n.length>0)try{await this.client.deleteObjects(n)}catch(i){console.warn("Some partition objects could not be deleted:",i.message)}}async query(t={},{limit:r=100,offset:n=0,partition:i=null,partitionValues:a={}}={}){if(Object.keys(t).length===0)return await this.list({partition:i,partitionValues:a,limit:r,offset:n});const o=[];let s=n;const f=Math.min(r,50);for(;o.length<r;){const c=await this.list({partition:i,partitionValues:a,limit:f,offset:s});if(c.length===0)break;const l=c.filter(d=>Object.entries(t).every(([h,u])=>d[h]===u));if(o.push(...l),s+=f,c.length<f)break}return o.slice(0,r)}async handlePartitionReferenceUpdates(t,r){const n=this.config.partitions;if(!n||Object.keys(n).length===0)return;for(const[a,o]of Object.entries(n))try{await this.handlePartitionReferenceUpdate(a,o,t,r)}catch(s){console.warn(`Failed to update partition references for ${a}:`,s.message)}const i=r.id||t.id;for(const[a,o]of Object.entries(n)){const s=`resource=${this.name}/partition=${a}`;let f=[];try{f=await this.client.getAllKeys({prefix:s})}catch(l){console.warn(`Aggressive cleanup: could not list keys for partition ${a}:`,l.message);continue}const c=this.getPartitionKey({partitionName:a,id:i,data:r});for(const l of f)if(l.endsWith(`/id=${i}`)&&l!==c)try{await this.client.deleteObject(l)}catch(d){console.warn(`Aggressive cleanup: could not delete stale partition key ${l}:`,d.message)}}}async handlePartitionReferenceUpdate(t,r,n,i){const a=i.id||n.id,o=this.getPartitionKey({partitionName:t,id:a,data:n}),s=this.getPartitionKey({partitionName:t,id:a,data:i});if(o!==s){if(o)try{await this.client.deleteObject(o)}catch(f){console.warn(`Old partition object could not be deleted for ${t}:`,f.message)}if(s)try{const f=await this.schema.mapper(i);f.undefined!==void 0&&delete f.undefined;const c=we(this.behavior),{mappedData:l,body:d}=await c.handleUpdate({resource:this,id:a,data:i,mappedData:f});l.undefined!==void 0&&delete l.undefined;const h={...l,_version:this.version};h.undefined!==void 0&&delete h.undefined,await this.client.putObject({key:s,metadata:h,body:d})}catch(f){console.warn(`New partition object could not be created for ${t}:`,f.message)}}else if(s)try{const f=await this.schema.mapper(i);f.undefined!==void 0&&delete f.undefined;const c=we(this.behavior),{mappedData:l,body:d}=await c.handleUpdate({resource:this,id:a,data:i,mappedData:f});l.undefined!==void 0&&delete l.undefined;const h={...l,_version:this.version};h.undefined!==void 0&&delete h.undefined,await this.client.putObject({key:s,metadata:h,body:d})}catch(f){console.warn(`Partition object could not be updated for ${t}:`,f.message)}}async updatePartitionReferences(t){const r=this.config.partitions;if(!(!r||Object.keys(r).length===0))for(const[n,i]of Object.entries(r)){if(!i||!i.fields||typeof i.fields!="object"){console.warn(`Skipping invalid partition '${n}' in resource '${this.name}'`);continue}const a=this.getPartitionKey({partitionName:n,id:t.id,data:t});if(a){const o=await this.schema.mapper(t),s=we(this.behavior),{mappedData:f,body:c}=await s.handleUpdate({resource:this,id:t.id,data:t,mappedData:o}),l={...f,_version:this.version};try{await this.client.putObject({key:a,metadata:l,body:c})}catch(d){console.warn(`Partition object could not be updated for ${n}:`,d.message)}}}}async getFromPartition({id:t,partitionName:r,partitionValues:n={}}){if(!this.config.partitions||!this.config.partitions[r])throw new Error(`Partition '${r}' not found`);const i=this.config.partitions[r],a=[],o=Object.entries(i.fields).sort(([w],[_])=>w.localeCompare(_));for(const[w,_]of o){const m=n[w];if(m!=null){const E=this.applyPartitionRule(m,_);a.push(`${w}=${E}`)}}if(a.length===0)throw new Error(`No partition values provided for partition '${r}'`);const s=xe(`resource=${this.name}`,`partition=${r}`,...a,`id=${t}`),f=await this.client.headObject(s),c=f.Metadata?._version||this.version;let d=await(await this.getSchemaForVersion(c)).unmapper(f.Metadata);const h=we(this.behavior);let u="";if(f.ContentLength>0)try{const w=await this.client.getObject(s);u=await vt(w.Body)}catch{u=""}const{metadata:p}=await h.handleGet({resource:this,metadata:d,body:u});let y=p;return y.id=t,y._contentLength=f.ContentLength,y._lastModified=f.LastModified,y._hasContent=f.ContentLength>0,y._mimeType=f.ContentType||null,y._partition=r,y._partitionValues=n,f.VersionId&&(y._versionId=f.VersionId),f.Expiration&&(y._expiresAt=f.Expiration),y._definitionHash=this.getDefinitionHash(),y.undefined!==void 0&&delete y.undefined,this.emit("getFromPartition",y),y}}function Rh(e){const t=[];e.name?typeof e.name!="string"?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?typeof e.attributes!="object"||Array.isArray(e.attributes)?t.push("Resource 'attributes' must be an object"):Object.keys(e.attributes).length===0&&t.push("Resource 'attributes' cannot be empty"):t.push("Resource 'attributes' are required"),e.version!==void 0&&typeof e.version!="string"&&t.push("Resource 'version' must be a string"),e.behavior!==void 0&&typeof e.behavior!="string"&&t.push("Resource 'behavior' must be a string"),e.passphrase!==void 0&&typeof e.passphrase!="string"&&t.push("Resource 'passphrase' must be a string"),e.parallelism!==void 0&&(typeof e.parallelism!="number"||!Number.isInteger(e.parallelism)?t.push("Resource 'parallelism' must be an integer"):e.parallelism<1&&t.push("Resource 'parallelism' must be greater than 0")),e.observers!==void 0&&!Array.isArray(e.observers)&&t.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const n of r)e[n]!==void 0&&typeof e[n]!="boolean"&&t.push(`Resource '${n}' must be a boolean`);if(e.partitions!==void 0)if(typeof e.partitions!="object"||Array.isArray(e.partitions))t.push("Resource 'partitions' must be an object");else for(const[n,i]of Object.entries(e.partitions))if(typeof i!="object"||Array.isArray(i))t.push(`Partition '${n}' must be an object`);else if(!i.fields)t.push(`Partition '${n}' must have a 'fields' property`);else if(typeof i.fields!="object"||Array.isArray(i.fields))t.push(`Partition '${n}.fields' must be an object`);else for(const[a,o]of Object.entries(i.fields))typeof o!="string"&&t.push(`Partition '${n}.fields.${a}' must be a string`);if(e.hooks!==void 0)if(typeof e.hooks!="object"||Array.isArray(e.hooks))t.push("Resource 'hooks' must be an object");else{const n=["preInsert","afterInsert","preUpdate","afterUpdate","preDelete","afterDelete"];for(const[i,a]of Object.entries(e.hooks))if(!n.includes(i))t.push(`Invalid hook event '${i}'. Valid events: ${n.join(", ")}`);else if(!Array.isArray(a))t.push(`Resource 'hooks.${i}' must be an array`);else for(let o=0;o<a.length;o++){const s=a[o];if(typeof s!="function"){if(typeof s=="string")continue;continue}}}return{isValid:t.length===0,errors:t}}class ls extends R{constructor(t){super(),this.version="1",this.s3dbVersion=(()=>{try{return"5.0.0"}catch{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.cache=t.cache,this.passphrase=t.passphrase||"secret";let r=t.connectionString;if(!r&&(t.bucket||t.accessKeyId||t.secretAccessKey)){const{bucket:n,region:i,accessKeyId:a,secretAccessKey:o,endpoint:s,forcePathStyle:f}=t;if(s){const c=new URL(s);a&&(c.username=encodeURIComponent(a)),o&&(c.password=encodeURIComponent(o)),c.pathname=`/${n||"s3db"}`,f&&c.searchParams.set("forcePathStyle","true"),r=c.toString()}else if(a&&o){const c=new URLSearchParams;c.set("region",i||"us-east-1"),f&&c.set("forcePathStyle","true"),r=`s3://${encodeURIComponent(a)}:${encodeURIComponent(o)}@${n||"s3db"}?${c.toString()}`}}this.client=t.client||new sa({verbose:this.verbose,parallelism:this.parallelism,connectionString:r}),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 n=await this.client.getObject("s3db.json");t=JSON.parse(await vt(n?.Body))}else t=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=t;const r=this.detectDefinitionChanges(t);for(const[n,i]of Object.entries(t.resources||{})){const a=i.currentVersion||"v0",o=i.versions?.[a];o&&(this.resources[n]=new mr({name:n,client:this.client,version:a,attributes:o.attributes,behavior:o.behavior||"user-management",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:o.timestamps!==void 0?o.timestamps:!1,partitions:i.partitions||o.partitions||{},paranoid:o.paranoid!==void 0?o.paranoid:!0,allNestedObjectsOptional:o.allNestedObjectsOptional!==void 0?o.allNestedObjectsOptional:!0,autoDecrypt:o.autoDecrypt!==void 0?o.autoDecrypt:!0,hooks:o.hooks||{}}))}r.length>0&&this.emit("resourceDefinitionsChanged",{changes:r,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(t){const r=[];for(const[n,i]of Object.entries(this.resources)){const a=this.generateDefinitionHash(i.export()),o=t.resources?.[n];if(!o)r.push({type:"new",resourceName:n,currentHash:a,savedHash:null});else{const s=o.currentVersion||"v0",c=o.versions?.[s]?.hash;c!==a&&r.push({type:"changed",resourceName:n,currentHash:a,savedHash:c,fromVersion:s,toVersion:this.getNextVersion(o.versions)})}}for(const[n,i]of Object.entries(t.resources||{}))if(!this.resources[n]){const a=i.currentVersion||"v0",o=i.versions?.[a];r.push({type:"deleted",resourceName:n,currentHash:null,savedHash:o?.hash,deletedVersion:a})}return r}generateDefinitionHash(t,r=void 0){const i={...t.attributes};t.timestamps&&(delete i.createdAt,delete i.updatedAt);const a={attributes:i,behavior:r||t.behavior||"user-management"},o=ho(a);return`sha256:${qi.createHash("sha256").update(o).digest("hex")}`}getNextVersion(t={}){const r=Object.keys(t).filter(i=>i.startsWith("v")).map(i=>parseInt(i.substring(1))).filter(i=>!isNaN(i));return`v${(r.length>0?Math.max(...r):-1)+1}`}async startPlugins(){const t=this;if(!L.isEmpty(this.plugins)){const r=this.plugins.map(a=>L.isFunction(a)?new a(this):a),n=r.map(async a=>{a.beforeSetup&&await a.beforeSetup(),await a.setup(t),a.afterSetup&&await a.afterSetup()});await Promise.all(n);const i=r.map(async a=>{a.beforeStart&&await a.beforeStart(),await a.start(),a.afterStart&&await a.afterStart()});await Promise.all(i)}}async uploadMetadataFile(){const t={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:new Date().toISOString(),resources:{}};Object.entries(this.resources).forEach(([r,n])=>{const i=n.export(),a=this.generateDefinitionHash(i),o=this.savedMetadata?.resources?.[r],s=o?.currentVersion||"v0",f=o?.versions?.[s];let c,l;!f||f.hash!==a?(c=this.getNextVersion(o?.versions),l=!0):(c=s,l=!1),t.resources[r]={currentVersion:c,partitions:n.config.partitions||{},versions:{...o?.versions,[c]:{hash:a,attributes:i.attributes,behavior:i.behavior||"user-management",timestamps:n.config.timestamps,partitions:n.config.partitions,paranoid:n.config.paranoid,allNestedObjectsOptional:n.config.allNestedObjectsOptional,autoDecrypt:n.config.autoDecrypt,cache:n.config.cache,hooks:n.config.hooks,createdAt:l?new Date().toISOString():f?.createdAt}}},n.version!==c&&(n.version=c,n.emit("versionUpdated",{oldVersion:s,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:r,behavior:n="user-management",options:i={}}){if(!this.resources[t])return{exists:!1,sameHash:!1,hash:null};const a=this.resources[t],o=this.generateDefinitionHash(a.export()),s=new mr({name:t,attributes:r,behavior:n,client:this.client,version:a.version,passphrase:this.passphrase,...i}),f=this.generateDefinitionHash(s.export());return{exists:!0,sameHash:o===f,hash:f,existingHash:o}}async createResource({name:t,attributes:r,behavior:n="user-management",hooks:i,...a}){if(this.resources[t]){const c=this.resources[t];if(Object.assign(c.config,{cache:this.cache,...a}),n&&(c.behavior=n),c.updateAttributes(r),i){for(const[p,y]of Object.entries(i))if(Array.isArray(y)&&c.hooks[p])for(const w of y)typeof w=="function"&&c.hooks[p].push(w.bind(c))}const l=this.generateDefinitionHash(c.export(),c.behavior),d=this.savedMetadata?.resources?.[t],h=d?.currentVersion||"v0",u=d?.versions?.[h];return(!u||u.hash!==l)&&await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",t),c}const s=this.savedMetadata?.resources?.[t]?.currentVersion||"v0",f=new mr({name:t,attributes:r,behavior:n,observers:[this],client:this.client,version:s,passphrase:this.passphrase,cache:this.cache,hooks:i,...a});return this.resources[t]=f,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",t),f}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 us extends ls{}class gi extends R{constructor(t={}){super(),this.config=t}async _set(t,r){}async _get(t){}async _del(t){}async _clear(t){}validateKey(t){if(t==null||typeof t!="string"||!t)throw new Error("Invalid key")}async set(t,r){return this.validateKey(t),await this._set(t,r),this.emit("set",r),r}async get(t){this.validateKey(t);const r=await this._get(t);return this.emit("get",r),r}async del(t){this.validateKey(t);const r=await this._del(t);return this.emit("delete",r),r}async delete(t){return this.del(t)}async clear(){const t=await this._clear();return this.emit("clear",t),t}}class Oh extends gi{constructor(t={}){super(t),this.cache={},this.meta={},this.maxSize=t.maxSize||0,this.ttl=t.ttl||0}async _set(t,r){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const n=Object.entries(this.meta).sort((i,a)=>i[1].ts-a[1].ts)[0]?.[0];n&&(delete this.cache[n],delete this.meta[n])}return this.cache[t]=r,this.meta[t]={ts:Date.now()},r}async _get(t){if(!Object.prototype.hasOwnProperty.call(this.cache,t))return null;if(this.ttl>0){const r=Date.now(),n=this.meta[t];if(n&&r-n.ts>this.ttl*1e3)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 hs={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 Ih(){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 Oe(e,t,r,n,i){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+n),i);return}for(var a=0;a<n;a++)e[i+a]=t[r+a]}var Er=Uint8Array,se=Uint16Array,xr=Int32Array,Ph=4,ds=0,ps=1,Th=2;function wt(e){for(var t=e.length;--t>=0;)e[t]=0}var jh=0,ys=1,Fh=2,Ch=3,Dh=258,vi=29,Ct=256,Dt=Ct+1+vi,_t=30,wi=19,gs=2*Dt+1,Qe=15,_i=16,Mh=7,bi=256,vs=16,ws=17,_s=18,mi=[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],Sr=[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],Lh=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bs=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Nh=512,Ie=new Array((Dt+2)*2);wt(Ie);var Mt=new Array(_t*2);wt(Mt);var Lt=new Array(Nh);wt(Lt);var Nt=new Array(Dh-Ch+1);wt(Nt);var Ei=new Array(vi);wt(Ei);var Ar=new Array(_t);wt(Ar);function xi(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length}var ms,Es,xs;function Si(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Ss(e){return e<256?Lt[e]:Lt[256+(e>>>7)]}function $t(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function ee(e,t,r){e.bi_valid>_i-r?(e.bi_buf|=t<<e.bi_valid&65535,$t(e,e.bi_buf),e.bi_buf=t>>_i-e.bi_valid,e.bi_valid+=r-_i):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)}function _e(e,t,r){ee(e,r[t*2],r[t*2+1])}function As(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function $h(e){e.bi_valid===16?($t(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Bh(e,t){var r=t.dyn_tree,n=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,f=t.stat_desc.max_length,c,l,d,h,u,p,y=0;for(h=0;h<=Qe;h++)e.bl_count[h]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<gs;c++)l=e.heap[c],h=r[r[l*2+1]*2+1]+1,h>f&&(h=f,y++),r[l*2+1]=h,!(l>n)&&(e.bl_count[h]++,u=0,l>=s&&(u=o[l-s]),p=r[l*2],e.opt_len+=p*(h+u),a&&(e.static_len+=p*(i[l*2+1]+u)));if(y!==0){do{for(h=f-1;e.bl_count[h]===0;)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[f]--,y-=2}while(y>0);for(h=f;h!==0;h--)for(l=e.bl_count[h];l!==0;)d=e.heap[--c],!(d>n)&&(r[d*2+1]!==h&&(e.opt_len+=(h-r[d*2+1])*r[d*2],r[d*2+1]=h),l--)}}function ks(e,t,r){var n=new Array(Qe+1),i=0,a,o;for(a=1;a<=Qe;a++)n[a]=i=i+r[a-1]<<1;for(o=0;o<=t;o++){var s=e[o*2+1];s!==0&&(e[o*2]=As(n[s]++,s))}}function Uh(){var e,t,r,n,i,a=new Array(Qe+1);for(r=0,n=0;n<vi-1;n++)for(Ei[n]=r,e=0;e<1<<mi[n];e++)Nt[r++]=n;for(Nt[r-1]=n,i=0,n=0;n<16;n++)for(Ar[n]=i,e=0;e<1<<Sr[n];e++)Lt[i++]=n;for(i>>=7;n<_t;n++)for(Ar[n]=i<<7,e=0;e<1<<Sr[n]-7;e++)Lt[256+i++]=n;for(t=0;t<=Qe;t++)a[t]=0;for(e=0;e<=143;)Ie[e*2+1]=8,e++,a[8]++;for(;e<=255;)Ie[e*2+1]=9,e++,a[9]++;for(;e<=279;)Ie[e*2+1]=7,e++,a[7]++;for(;e<=287;)Ie[e*2+1]=8,e++,a[8]++;for(ks(Ie,Dt+1,a),e=0;e<_t;e++)Mt[e*2+1]=5,Mt[e*2]=As(e,5);ms=new xi(Ie,mi,Ct+1,Dt,Qe),Es=new xi(Mt,Sr,0,_t,Qe),xs=new xi(new Array(0),Lh,0,wi,Mh)}function Rs(e){var t;for(t=0;t<Dt;t++)e.dyn_ltree[t*2]=0;for(t=0;t<_t;t++)e.dyn_dtree[t*2]=0;for(t=0;t<wi;t++)e.bl_tree[t*2]=0;e.dyn_ltree[bi*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function Os(e){e.bi_valid>8?$t(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function zh(e,t,r,n){Os(e),$t(e,r),$t(e,~r),Oe(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}function Is(e,t,r,n){var i=t*2,a=r*2;return e[i]<e[a]||e[i]===e[a]&&n[t]<=n[r]}function Ai(e,t,r){for(var n=e.heap[r],i=r<<1;i<=e.heap_len&&(i<e.heap_len&&Is(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!Is(t,n,e.heap[i],e.depth));)e.heap[r]=e.heap[i],r=i,i<<=1;e.heap[r]=n}function Ps(e,t,r){var n,i,a=0,o,s;if(e.last_lit!==0)do n=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],i=e.pending_buf[e.l_buf+a],a++,n===0?_e(e,i,t):(o=Nt[i],_e(e,o+Ct+1,t),s=mi[o],s!==0&&(i-=Ei[o],ee(e,i,s)),n--,o=Ss(n),_e(e,o,r),s=Sr[o],s!==0&&(n-=Ar[o],ee(e,n,s)));while(a<e.last_lit);_e(e,bi,t)}function ki(e,t){var r=t.dyn_tree,n=t.stat_desc.static_tree,i=t.stat_desc.has_stree,a=t.stat_desc.elems,o,s,f=-1,c;for(e.heap_len=0,e.heap_max=gs,o=0;o<a;o++)r[o*2]!==0?(e.heap[++e.heap_len]=f=o,e.depth[o]=0):r[o*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=f<2?++f:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,i&&(e.static_len-=n[c*2+1]);for(t.max_code=f,o=e.heap_len>>1;o>=1;o--)Ai(e,r,o);c=a;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Ai(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,r[c*2]=r[o*2]+r[s*2],e.depth[c]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,r[o*2+1]=r[s*2+1]=c,e.heap[1]=c++,Ai(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Bh(e,t),ks(r,f,e.bl_count)}function Ts(e,t,r){var n,i=-1,a,o=t[0*2+1],s=0,f=7,c=4;for(o===0&&(f=138,c=3),t[(r+1)*2+1]=65535,n=0;n<=r;n++)a=o,o=t[(n+1)*2+1],!(++s<f&&a===o)&&(s<c?e.bl_tree[a*2]+=s:a!==0?(a!==i&&e.bl_tree[a*2]++,e.bl_tree[vs*2]++):s<=10?e.bl_tree[ws*2]++:e.bl_tree[_s*2]++,s=0,i=a,o===0?(f=138,c=3):a===o?(f=6,c=3):(f=7,c=4))}function js(e,t,r){var n,i=-1,a,o=t[0*2+1],s=0,f=7,c=4;for(o===0&&(f=138,c=3),n=0;n<=r;n++)if(a=o,o=t[(n+1)*2+1],!(++s<f&&a===o)){if(s<c)do _e(e,a,e.bl_tree);while(--s!==0);else a!==0?(a!==i&&(_e(e,a,e.bl_tree),s--),_e(e,vs,e.bl_tree),ee(e,s-3,2)):s<=10?(_e(e,ws,e.bl_tree),ee(e,s-3,3)):(_e(e,_s,e.bl_tree),ee(e,s-11,7));s=0,i=a,o===0?(f=138,c=3):a===o?(f=6,c=3):(f=7,c=4)}}function Zh(e){var t;for(Ts(e,e.dyn_ltree,e.l_desc.max_code),Ts(e,e.dyn_dtree,e.d_desc.max_code),ki(e,e.bl_desc),t=wi-1;t>=3&&e.bl_tree[bs[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function qh(e,t,r,n){var i;for(ee(e,t-257,5),ee(e,r-1,5),ee(e,n-4,4),i=0;i<n;i++)ee(e,e.bl_tree[bs[i]*2+1],3);js(e,e.dyn_ltree,t-1),js(e,e.dyn_dtree,r-1)}function Hh(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return ds;if(e.dyn_ltree[9*2]!==0||e.dyn_ltree[10*2]!==0||e.dyn_ltree[13*2]!==0)return ps;for(r=32;r<Ct;r++)if(e.dyn_ltree[r*2]!==0)return ps;return ds}var Fs=!1;function Kh(e){Fs||(Uh(),Fs=!0),e.l_desc=new Si(e.dyn_ltree,ms),e.d_desc=new Si(e.dyn_dtree,Es),e.bl_desc=new Si(e.bl_tree,xs),e.bi_buf=0,e.bi_valid=0,Rs(e)}function Cs(e,t,r,n){ee(e,(jh<<1)+(n?1:0),3),zh(e,t,r)}function Vh(e){ee(e,ys<<1,3),_e(e,bi,Ie),$h(e)}function Wh(e,t,r,n){var i,a,o=0;e.level>0?(e.strm.data_type===Th&&(e.strm.data_type=Hh(e)),ki(e,e.l_desc),ki(e,e.d_desc),o=Zh(e),i=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=i&&(i=a)):i=a=r+5,r+4<=i&&t!==-1?Cs(e,t,r,n):e.strategy===Ph||a===i?(ee(e,(ys<<1)+(n?1:0),3),Ps(e,Ie,Mt)):(ee(e,(Fh<<1)+(n?1:0),3),qh(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),Ps(e,e.dyn_ltree,e.dyn_dtree)),Rs(e),n&&Os(e)}function Le(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(Nt[r]+Ct+1)*2]++,e.dyn_dtree[Ss(t)*2]++),e.last_lit===e.lit_bufsize-1}function Ri(e,t,r,n){for(var i=e&65535|0,a=e>>>16&65535|0,o=0;r!==0;){o=r>2e3?2e3:r,r-=o;do i=i+t[n++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0}function Gh(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e}return t}var Yh=Gh();function Z(e,t,r,n){var i=Yh,a=n+r;e^=-1;for(var o=n;o<a;o++)e=e>>>8^i[(e^t[o])&255];return e^-1}var et=0,Jh=1,Xh=3,Ne=4,Ds=5,$e=0,Ms=1,Be=-2,Qh=-3,Oi=-5,ed=-1,td=1,kr=2,rd=3,nd=4,id=2,Ii=8,ad=9,od=29,sd=256,Pi=sd+1+od,cd=30,fd=19,ld=2*Pi+1,ud=15,T=3,Ue=258,ce=Ue+T+1,hd=32,Ti=42,ji=69,Rr=73,Or=91,Ir=103,tt=113,Bt=666,U=1,Ut=2,rt=3,bt=4,dd=3;function ze(e,t){return e.msg=hs[t],t}function Ls(e){return(e<<1)-(e>4?9:0)}function nt(e){for(var t=e.length;--t>=0;)e[t]=0}function Ze(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Oe(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0))}function K(e,t){Wh(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Ze(e.strm)}function P(e,t){e.pending_buf[e.pending++]=t}function zt(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function pd(e,t,r,n){var i=e.avail_in;return i>n&&(i=n),i===0?0:(e.avail_in-=i,Oe(t,e.input,e.next_in,i,r),e.state.wrap===1?e.adler=Ri(e.adler,t,i,r):e.state.wrap===2&&(e.adler=Z(e.adler,t,i,r)),e.next_in+=i,e.total_in+=i,i)}function Ns(e,t){var r=e.max_chain_length,n=e.strstart,i,a,o=e.prev_length,s=e.nice_match,f=e.strstart>e.w_size-ce?e.strstart-(e.w_size-ce):0,c=e.window,l=e.w_mask,d=e.prev,h=e.strstart+Ue,u=c[n+o-1],p=c[n+o];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(i=t,!(c[i+o]!==p||c[i+o-1]!==u||c[i]!==c[n]||c[++i]!==c[n+1])){n+=2,i++;do;while(c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&n<h);if(a=Ue-(h-n),n=h-Ue,a>o){if(e.match_start=t,o=a,a>=s)break;u=c[n+o-1],p=c[n+o]}}while((t=d[t&l])>f&&--r!==0);return o<=e.lookahead?o:e.lookahead}function Zt(e){var t=e.w_size,r,n,i,a,o;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-ce)){Oe(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,r=n;do i=e.head[--r],e.head[r]=i>=t?i-t:0;while(--n);n=t,r=n;do i=e.prev[--r],e.prev[r]=i>=t?i-t:0;while(--n);a+=t}if(e.strm.avail_in===0)break;if(n=pd(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=T)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=(e.ins_h<<e.hash_shift^e.window[o+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[o+T-1])&e.hash_mask,e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<T)););}while(e.lookahead<ce&&e.strm.avail_in!==0)}function yd(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Zt(e),e.lookahead===0&&t===et)return U;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((e.strstart===0||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,K(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-ce&&(K(e,!1),e.strm.avail_out===0))return U}return e.insert=0,t===Ne?(K(e,!0),e.strm.avail_out===0?rt:bt):(e.strstart>e.block_start&&(K(e,!1),e.strm.avail_out===0),U)}function Fi(e,t){for(var r,n;;){if(e.lookahead<ce){if(Zt(e),e.lookahead<ce&&t===et)return U;if(e.lookahead===0)break}if(r=0,e.lookahead>=T&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-ce&&(e.match_length=Ns(e,r)),e.match_length>=T)if(n=Le(e,e.strstart-e.match_start,e.match_length-T),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=T){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=Le(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(K(e,!1),e.strm.avail_out===0))return U}return e.insert=e.strstart<T-1?e.strstart:T-1,t===Ne?(K(e,!0),e.strm.avail_out===0?rt:bt):e.last_lit&&(K(e,!1),e.strm.avail_out===0)?U:Ut}function mt(e,t){for(var r,n,i;;){if(e.lookahead<ce){if(Zt(e),e.lookahead<ce&&t===et)return U;if(e.lookahead===0)break}if(r=0,e.lookahead>=T&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=T-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-ce&&(e.match_length=Ns(e,r),e.match_length<=5&&(e.strategy===td||e.match_length===T&&e.strstart-e.match_start>4096)&&(e.match_length=T-1)),e.prev_length>=T&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-T,n=Le(e,e.strstart-1-e.prev_match,e.prev_length-T),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=i&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=T-1,e.strstart++,n&&(K(e,!1),e.strm.avail_out===0))return U}else if(e.match_available){if(n=Le(e,0,e.window[e.strstart-1]),n&&K(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return U}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Le(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<T-1?e.strstart:T-1,t===Ne?(K(e,!0),e.strm.avail_out===0?rt:bt):e.last_lit&&(K(e,!1),e.strm.avail_out===0)?U:Ut}function gd(e,t){for(var r,n,i,a,o=e.window;;){if(e.lookahead<=Ue){if(Zt(e),e.lookahead<=Ue&&t===et)return U;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=T&&e.strstart>0&&(i=e.strstart-1,n=o[i],n===o[++i]&&n===o[++i]&&n===o[++i])){a=e.strstart+Ue;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<a);e.match_length=Ue-(a-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=T?(r=Le(e,1,e.match_length-T),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=Le(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(K(e,!1),e.strm.avail_out===0))return U}return e.insert=0,t===Ne?(K(e,!0),e.strm.avail_out===0?rt:bt):e.last_lit&&(K(e,!1),e.strm.avail_out===0)?U:Ut}function vd(e,t){for(var r;;){if(e.lookahead===0&&(Zt(e),e.lookahead===0)){if(t===et)return U;break}if(e.match_length=0,r=Le(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(K(e,!1),e.strm.avail_out===0))return U}return e.insert=0,t===Ne?(K(e,!0),e.strm.avail_out===0?rt:bt):e.last_lit&&(K(e,!1),e.strm.avail_out===0)?U:Ut}function be(e,t,r,n,i){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=i}var Et;Et=[new be(0,0,0,0,yd),new be(4,4,8,4,Fi),new be(4,5,16,8,Fi),new be(4,6,32,32,Fi),new be(4,4,16,16,mt),new be(8,16,32,32,mt),new be(8,16,128,128,mt),new be(8,32,128,256,mt),new be(32,128,258,1024,mt),new be(32,258,258,4096,mt)];function wd(e){e.window_size=2*e.w_size,nt(e.head),e.max_lazy_match=Et[e.level].max_lazy,e.good_match=Et[e.level].good_length,e.nice_match=Et[e.level].nice_length,e.max_chain_length=Et[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=T-1,e.match_available=0,e.ins_h=0}function _d(){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=Ii,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 se(ld*2),this.dyn_dtree=new se((2*cd+1)*2),this.bl_tree=new se((2*fd+1)*2),nt(this.dyn_ltree),nt(this.dyn_dtree),nt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new se(ud+1),this.heap=new se(2*Pi+1),nt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new se(2*Pi+1),nt(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 bd(e){var t;return!e||!e.state?ze(e,Be):(e.total_in=e.total_out=0,e.data_type=id,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?Ti:tt,e.adler=t.wrap===2?0:1,t.last_flush=et,Kh(t),$e)}function $s(e){var t=bd(e);return t===$e&&wd(e.state),t}function md(e,t,r,n,i,a){if(!e)return Be;var o=1;if(t===ed&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),i<1||i>ad||r!==Ii||n<8||n>15||t<0||t>9||a<0||a>nd)return ze(e,Be);n===8&&(n=9);var s=new _d;return e.state=s,s.strm=e,s.wrap=o,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+T-1)/T),s.window=new Er(s.w_size*2),s.head=new se(s.hash_size),s.prev=new se(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Er(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=a,s.method=r,$s(e)}function Ed(e,t){var r,n,i,a;if(!e||!e.state||t>Ds||t<0)return e?ze(e,Be):Be;if(n=e.state,!e.output||!e.input&&e.avail_in!==0||n.status===Bt&&t!==Ne)return ze(e,e.avail_out===0?Oi:Be);if(n.strm=e,r=n.last_flush,n.last_flush=t,n.status===Ti)if(n.wrap===2)e.adler=0,P(n,31),P(n,139),P(n,8),n.gzhead?(P(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)),P(n,n.gzhead.time&255),P(n,n.gzhead.time>>8&255),P(n,n.gzhead.time>>16&255),P(n,n.gzhead.time>>24&255),P(n,n.level===9?2:n.strategy>=kr||n.level<2?4:0),P(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(P(n,n.gzhead.extra.length&255),P(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=Z(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=ji):(P(n,0),P(n,0),P(n,0),P(n,0),P(n,0),P(n,n.level===9?2:n.strategy>=kr||n.level<2?4:0),P(n,dd),n.status=tt);else{var o=Ii+(n.w_bits-8<<4)<<8,s=-1;n.strategy>=kr||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,o|=s<<6,n.strstart!==0&&(o|=hd),o+=31-o%31,n.status=tt,zt(n,o),n.strstart!==0&&(zt(n,e.adler>>>16),zt(n,e.adler&65535)),e.adler=1}if(n.status===ji)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=Z(e.adler,n.pending_buf,n.pending-i,i)),Ze(e),i=n.pending,n.pending===n.pending_buf_size));)P(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(e.adler=Z(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=Rr)}else n.status=Rr;if(n.status===Rr)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=Z(e.adler,n.pending_buf,n.pending-i,i)),Ze(e),i=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.name.length?a=n.gzhead.name.charCodeAt(n.gzindex++)&255:a=0,P(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>i&&(e.adler=Z(e.adler,n.pending_buf,n.pending-i,i)),a===0&&(n.gzindex=0,n.status=Or)}else n.status=Or;if(n.status===Or)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=Z(e.adler,n.pending_buf,n.pending-i,i)),Ze(e),i=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.comment.length?a=n.gzhead.comment.charCodeAt(n.gzindex++)&255:a=0,P(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>i&&(e.adler=Z(e.adler,n.pending_buf,n.pending-i,i)),a===0&&(n.status=Ir)}else n.status=Ir;if(n.status===Ir&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Ze(e),n.pending+2<=n.pending_buf_size&&(P(n,e.adler&255),P(n,e.adler>>8&255),e.adler=0,n.status=tt)):n.status=tt),n.pending!==0){if(Ze(e),e.avail_out===0)return n.last_flush=-1,$e}else if(e.avail_in===0&&Ls(t)<=Ls(r)&&t!==Ne)return ze(e,Oi);if(n.status===Bt&&e.avail_in!==0)return ze(e,Oi);if(e.avail_in!==0||n.lookahead!==0||t!==et&&n.status!==Bt){var f=n.strategy===kr?vd(n,t):n.strategy===rd?gd(n,t):Et[n.level].func(n,t);if((f===rt||f===bt)&&(n.status=Bt),f===U||f===rt)return e.avail_out===0&&(n.last_flush=-1),$e;if(f===Ut&&(t===Jh?Vh(n):t!==Ds&&(Cs(n,0,0,!1),t===Xh&&(nt(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Ze(e),e.avail_out===0))return n.last_flush=-1,$e}return t!==Ne?$e:n.wrap<=0?Ms:(n.wrap===2?(P(n,e.adler&255),P(n,e.adler>>8&255),P(n,e.adler>>16&255),P(n,e.adler>>24&255),P(n,e.total_in&255),P(n,e.total_in>>8&255),P(n,e.total_in>>16&255),P(n,e.total_in>>24&255)):(zt(n,e.adler>>>16),zt(n,e.adler&65535)),Ze(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?$e:Ms)}function xd(e){var t;return!e||!e.state?Be:(t=e.state.status,t!==Ti&&t!==ji&&t!==Rr&&t!==Or&&t!==Ir&&t!==tt&&t!==Bt?ze(e,Be):(e.state=null,t===tt?ze(e,Qh):$e))}var Pr=30,Sd=12;function Ad(e,t){var r,n,i,a,o,s,f,c,l,d,h,u,p,y,w,_,m,E,v,A,O,b,S,I,k;r=e.state,n=e.next_in,I=e.input,i=n+(e.avail_in-5),a=e.next_out,k=e.output,o=a-(t-e.avail_out),s=a+(e.avail_out-257),f=r.dmax,c=r.wsize,l=r.whave,d=r.wnext,h=r.window,u=r.hold,p=r.bits,y=r.lencode,w=r.distcode,_=(1<<r.lenbits)-1,m=(1<<r.distbits)-1;e:do{p<15&&(u+=I[n++]<<p,p+=8,u+=I[n++]<<p,p+=8),E=y[u&_];t:for(;;){if(v=E>>>24,u>>>=v,p-=v,v=E>>>16&255,v===0)k[a++]=E&65535;else if(v&16){A=E&65535,v&=15,v&&(p<v&&(u+=I[n++]<<p,p+=8),A+=u&(1<<v)-1,u>>>=v,p-=v),p<15&&(u+=I[n++]<<p,p+=8,u+=I[n++]<<p,p+=8),E=w[u&m];r:for(;;){if(v=E>>>24,u>>>=v,p-=v,v=E>>>16&255,v&16){if(O=E&65535,v&=15,p<v&&(u+=I[n++]<<p,p+=8,p<v&&(u+=I[n++]<<p,p+=8)),O+=u&(1<<v)-1,O>f){e.msg="invalid distance too far back",r.mode=Pr;break e}if(u>>>=v,p-=v,v=a-o,O>v){if(v=O-v,v>l&&r.sane){e.msg="invalid distance too far back",r.mode=Pr;break e}if(b=0,S=h,d===0){if(b+=c-v,v<A){A-=v;do k[a++]=h[b++];while(--v);b=a-O,S=k}}else if(d<v){if(b+=c+d-v,v-=d,v<A){A-=v;do k[a++]=h[b++];while(--v);if(b=0,d<A){v=d,A-=v;do k[a++]=h[b++];while(--v);b=a-O,S=k}}}else if(b+=d-v,v<A){A-=v;do k[a++]=h[b++];while(--v);b=a-O,S=k}for(;A>2;)k[a++]=S[b++],k[a++]=S[b++],k[a++]=S[b++],A-=3;A&&(k[a++]=S[b++],A>1&&(k[a++]=S[b++]))}else{b=a-O;do k[a++]=k[b++],k[a++]=k[b++],k[a++]=k[b++],A-=3;while(A>2);A&&(k[a++]=k[b++],A>1&&(k[a++]=k[b++]))}}else if((v&64)===0){E=w[(E&65535)+(u&(1<<v)-1)];continue r}else{e.msg="invalid distance code",r.mode=Pr;break e}break}}else if((v&64)===0){E=y[(E&65535)+(u&(1<<v)-1)];continue t}else if(v&32){r.mode=Sd;break e}else{e.msg="invalid literal/length code",r.mode=Pr;break e}break}}while(n<i&&a<s);A=p>>3,n-=A,p-=A<<3,u&=(1<<p)-1,e.next_in=n,e.next_out=a,e.avail_in=n<i?5+(i-n):5-(n-i),e.avail_out=a<s?257+(s-a):257-(a-s),r.hold=u,r.bits=p}var xt=15,Bs=852,Us=592,zs=0,Ci=1,Zs=2,kd=[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],Rd=[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],Od=[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],Id=[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 qt(e,t,r,n,i,a,o,s){var f=s.bits,c=0,l=0,d=0,h=0,u=0,p=0,y=0,w=0,_=0,m=0,E,v,A,O,b,S=null,I=0,k,F=new se(xt+1),q=new se(xt+1),G=null,ne=0,He,J,le;for(c=0;c<=xt;c++)F[c]=0;for(l=0;l<n;l++)F[t[r+l]]++;for(u=f,h=xt;h>=1&&F[h]===0;h--);if(u>h&&(u=h),h===0)return i[a++]=1<<24|64<<16|0,i[a++]=1<<24|64<<16|0,s.bits=1,0;for(d=1;d<h&&F[d]===0;d++);for(u<d&&(u=d),w=1,c=1;c<=xt;c++)if(w<<=1,w-=F[c],w<0)return-1;if(w>0&&(e===zs||h!==1))return-1;for(q[1]=0,c=1;c<xt;c++)q[c+1]=q[c]+F[c];for(l=0;l<n;l++)t[r+l]!==0&&(o[q[t[r+l]]++]=l);if(e===zs?(S=G=o,k=19):e===Ci?(S=kd,I-=257,G=Rd,ne-=257,k=256):(S=Od,G=Id,k=-1),m=0,l=0,c=d,b=a,p=u,y=0,A=-1,_=1<<u,O=_-1,e===Ci&&_>Bs||e===Zs&&_>Us)return 1;for(;;){He=c-y,o[l]<k?(J=0,le=o[l]):o[l]>k?(J=G[ne+o[l]],le=S[I+o[l]]):(J=96,le=0),E=1<<c-y,v=1<<p,d=v;do v-=E,i[b+(m>>y)+v]=He<<24|J<<16|le|0;while(v!==0);for(E=1<<c-1;m&E;)E>>=1;if(E!==0?(m&=E-1,m+=E):m=0,l++,--F[c]===0){if(c===h)break;c=t[r+o[l]]}if(c>u&&(m&O)!==A){for(y===0&&(y=u),b+=d,p=c-y,w=1<<p;p+y<h&&(w-=F[p+y],!(w<=0));)p++,w<<=1;if(_+=1<<p,e===Ci&&_>Bs||e===Zs&&_>Us)return 1;A=m&O,i[A]=u<<24|p<<16|b-a|0}}return m!==0&&(i[b+m]=c-y<<24|64<<16|0),s.bits=u,0}var Pd=0,qs=1,Hs=2,Ks=4,Td=5,Tr=6,Ht=0,jd=1,Fd=2,qe=-2,Cd=-3,Dd=-4,Md=-5,Vs=8,Ws=1,Gs=2,Ys=3,Js=4,Xs=5,Qs=6,ec=7,tc=8,rc=9,nc=10,ic=11,Pe=12,Di=13,ac=14,Mi=15,oc=16,sc=17,cc=18,fc=19,jr=20,Fr=21,lc=22,uc=23,hc=24,dc=25,pc=26,Li=27,yc=28,gc=29,C=30,Ld=31,Nd=32,$d=852,Bd=592;function vc(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Ud(){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 se(320),this.work=new se(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function zd(e){var t;return!e||!e.state?qe:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Ws,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new xr($d),t.distcode=t.distdyn=new xr(Bd),t.sane=1,t.back=-1,Ht)}function wc(e){var t;return!e||!e.state?qe:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,zd(e))}function Zd(e,t){var r,n;return!e||!e.state||(n=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?qe:(n.window!==null&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,wc(e))}function qd(e,t){var r,n;return e?(n=new Ud,e.state=n,n.window=null,r=Zd(e,t),r!==Ht&&(e.state=null),r):qe}var _c=!0,Ni,$i;function Hd(e){if(_c){var t;for(Ni=new xr(512),$i=new xr(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(qt(qs,e.lens,0,288,Ni,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;qt(Hs,e.lens,0,32,$i,0,e.work,{bits:5}),_c=!1}e.lencode=Ni,e.lenbits=9,e.distcode=$i,e.distbits=5}function Kd(e,t,r,n){var i,a=e.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new Er(a.wsize)),n>=a.wsize?(Oe(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(i=a.wsize-a.wnext,i>n&&(i=n),Oe(a.window,t,r-n,i,a.wnext),n-=i,n?(Oe(a.window,t,r-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=i,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=i))),0}function Vd(e,t){var r,n,i,a,o,s,f,c,l,d,h,u,p,y,w=0,_,m,E,v,A,O,b,S,I=new Er(4),k,F,q=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return qe;r=e.state,r.mode===Pe&&(r.mode=Di),o=e.next_out,i=e.output,f=e.avail_out,a=e.next_in,n=e.input,s=e.avail_in,c=r.hold,l=r.bits,d=s,h=f,S=Ht;e:for(;;)switch(r.mode){case Ws:if(r.wrap===0){r.mode=Di;break}for(;l<16;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(r.wrap&2&&c===35615){r.check=0,I[0]=c&255,I[1]=c>>>8&255,r.check=Z(r.check,I,2,0),c=0,l=0,r.mode=Gs;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=C;break}if((c&15)!==Vs){e.msg="unknown compression method",r.mode=C;break}if(c>>>=4,l-=4,b=(c&15)+8,r.wbits===0)r.wbits=b;else if(b>r.wbits){e.msg="invalid window size",r.mode=C;break}r.dmax=1<<b,e.adler=r.check=1,r.mode=c&512?nc:Pe,c=0,l=0;break;case Gs:for(;l<16;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(r.flags=c,(r.flags&255)!==Vs){e.msg="unknown compression method",r.mode=C;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=C;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(I[0]=c&255,I[1]=c>>>8&255,r.check=Z(r.check,I,2,0)),c=0,l=0,r.mode=Ys;case Ys:for(;l<32;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}r.head&&(r.head.time=c),r.flags&512&&(I[0]=c&255,I[1]=c>>>8&255,I[2]=c>>>16&255,I[3]=c>>>24&255,r.check=Z(r.check,I,4,0)),c=0,l=0,r.mode=Js;case Js:for(;l<16;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(I[0]=c&255,I[1]=c>>>8&255,r.check=Z(r.check,I,2,0)),c=0,l=0,r.mode=Xs;case Xs:if(r.flags&1024){for(;l<16;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(I[0]=c&255,I[1]=c>>>8&255,r.check=Z(r.check,I,2,0)),c=0,l=0}else r.head&&(r.head.extra=null);r.mode=Qs;case Qs:if(r.flags&1024&&(u=r.length,u>s&&(u=s),u&&(r.head&&(b=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),Oe(r.head.extra,n,a,u,b)),r.flags&512&&(r.check=Z(r.check,n,u,a)),s-=u,a+=u,r.length-=u),r.length))break e;r.length=0,r.mode=ec;case ec:if(r.flags&2048){if(s===0)break e;u=0;do b=n[a+u++],r.head&&b&&r.length<65536&&(r.head.name+=String.fromCharCode(b));while(b&&u<s);if(r.flags&512&&(r.check=Z(r.check,n,u,a)),s-=u,a+=u,b)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=tc;case tc:if(r.flags&4096){if(s===0)break e;u=0;do b=n[a+u++],r.head&&b&&r.length<65536&&(r.head.comment+=String.fromCharCode(b));while(b&&u<s);if(r.flags&512&&(r.check=Z(r.check,n,u,a)),s-=u,a+=u,b)break e}else r.head&&(r.head.comment=null);r.mode=rc;case rc:if(r.flags&512){for(;l<16;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=C;break}c=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Pe;break;case nc:for(;l<32;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}e.adler=r.check=vc(c),c=0,l=0,r.mode=ic;case ic:if(r.havedict===0)return e.next_out=o,e.avail_out=f,e.next_in=a,e.avail_in=s,r.hold=c,r.bits=l,Fd;e.adler=r.check=1,r.mode=Pe;case Pe:if(t===Td||t===Tr)break e;case Di:if(r.last){c>>>=l&7,l-=l&7,r.mode=Li;break}for(;l<3;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}switch(r.last=c&1,c>>>=1,l-=1,c&3){case 0:r.mode=ac;break;case 1:if(Hd(r),r.mode=jr,t===Tr){c>>>=2,l-=2;break e}break;case 2:r.mode=sc;break;case 3:e.msg="invalid block type",r.mode=C}c>>>=2,l-=2;break;case ac:for(c>>>=l&7,l-=l&7;l<32;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=C;break}if(r.length=c&65535,c=0,l=0,r.mode=Mi,t===Tr)break e;case Mi:r.mode=oc;case oc:if(u=r.length,u){if(u>s&&(u=s),u>f&&(u=f),u===0)break e;Oe(i,n,a,u,o),s-=u,a+=u,f-=u,o+=u,r.length-=u;break}r.mode=Pe;break;case sc:for(;l<14;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(r.nlen=(c&31)+257,c>>>=5,l-=5,r.ndist=(c&31)+1,c>>>=5,l-=5,r.ncode=(c&15)+4,c>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=C;break}r.have=0,r.mode=cc;case cc:for(;r.have<r.ncode;){for(;l<3;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}r.lens[q[r.have++]]=c&7,c>>>=3,l-=3}for(;r.have<19;)r.lens[q[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,k={bits:r.lenbits},S=qt(Pd,r.lens,0,19,r.lencode,0,r.work,k),r.lenbits=k.bits,S){e.msg="invalid code lengths set",r.mode=C;break}r.have=0,r.mode=fc;case fc:for(;r.have<r.nlen+r.ndist;){for(;w=r.lencode[c&(1<<r.lenbits)-1],_=w>>>24,m=w>>>16&255,E=w&65535,!(_<=l);){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(E<16)c>>>=_,l-=_,r.lens[r.have++]=E;else{if(E===16){for(F=_+2;l<F;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(c>>>=_,l-=_,r.have===0){e.msg="invalid bit length repeat",r.mode=C;break}b=r.lens[r.have-1],u=3+(c&3),c>>>=2,l-=2}else if(E===17){for(F=_+3;l<F;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}c>>>=_,l-=_,b=0,u=3+(c&7),c>>>=3,l-=3}else{for(F=_+7;l<F;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}c>>>=_,l-=_,b=0,u=11+(c&127),c>>>=7,l-=7}if(r.have+u>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=C;break}for(;u--;)r.lens[r.have++]=b}}if(r.mode===C)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=C;break}if(r.lenbits=9,k={bits:r.lenbits},S=qt(qs,r.lens,0,r.nlen,r.lencode,0,r.work,k),r.lenbits=k.bits,S){e.msg="invalid literal/lengths set",r.mode=C;break}if(r.distbits=6,r.distcode=r.distdyn,k={bits:r.distbits},S=qt(Hs,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,k),r.distbits=k.bits,S){e.msg="invalid distances set",r.mode=C;break}if(r.mode=jr,t===Tr)break e;case jr:r.mode=Fr;case Fr:if(s>=6&&f>=258){e.next_out=o,e.avail_out=f,e.next_in=a,e.avail_in=s,r.hold=c,r.bits=l,Ad(e,h),o=e.next_out,i=e.output,f=e.avail_out,a=e.next_in,n=e.input,s=e.avail_in,c=r.hold,l=r.bits,r.mode===Pe&&(r.back=-1);break}for(r.back=0;w=r.lencode[c&(1<<r.lenbits)-1],_=w>>>24,m=w>>>16&255,E=w&65535,!(_<=l);){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(m&&(m&240)===0){for(v=_,A=m,O=E;w=r.lencode[O+((c&(1<<v+A)-1)>>v)],_=w>>>24,m=w>>>16&255,E=w&65535,!(v+_<=l);){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}c>>>=v,l-=v,r.back+=v}if(c>>>=_,l-=_,r.back+=_,r.length=E,m===0){r.mode=pc;break}if(m&32){r.back=-1,r.mode=Pe;break}if(m&64){e.msg="invalid literal/length code",r.mode=C;break}r.extra=m&15,r.mode=lc;case lc:if(r.extra){for(F=r.extra;l<F;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=uc;case uc:for(;w=r.distcode[c&(1<<r.distbits)-1],_=w>>>24,m=w>>>16&255,E=w&65535,!(_<=l);){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if((m&240)===0){for(v=_,A=m,O=E;w=r.distcode[O+((c&(1<<v+A)-1)>>v)],_=w>>>24,m=w>>>16&255,E=w&65535,!(v+_<=l);){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}c>>>=v,l-=v,r.back+=v}if(c>>>=_,l-=_,r.back+=_,m&64){e.msg="invalid distance code",r.mode=C;break}r.offset=E,r.extra=m&15,r.mode=hc;case hc:if(r.extra){for(F=r.extra;l<F;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=C;break}r.mode=dc;case dc:if(f===0)break e;if(u=h-f,r.offset>u){if(u=r.offset-u,u>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=C;break}u>r.wnext?(u-=r.wnext,p=r.wsize-u):p=r.wnext-u,u>r.length&&(u=r.length),y=r.window}else y=i,p=o-r.offset,u=r.length;u>f&&(u=f),f-=u,r.length-=u;do i[o++]=y[p++];while(--u);r.length===0&&(r.mode=Fr);break;case pc:if(f===0)break e;i[o++]=r.length,f--,r.mode=Fr;break;case Li:if(r.wrap){for(;l<32;){if(s===0)break e;s--,c|=n[a++]<<l,l+=8}if(h-=f,e.total_out+=h,r.total+=h,h&&(e.adler=r.check=r.flags?Z(r.check,i,h,o-h):Ri(r.check,i,h,o-h)),h=f,(r.flags?c:vc(c))!==r.check){e.msg="incorrect data check",r.mode=C;break}c=0,l=0}r.mode=yc;case yc:if(r.wrap&&r.flags){for(;l<32;){if(s===0)break e;s--,c+=n[a++]<<l,l+=8}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=C;break}c=0,l=0}r.mode=gc;case gc:S=jd;break e;case C:S=Cd;break e;case Ld:return Dd;case Nd:default:return qe}return e.next_out=o,e.avail_out=f,e.next_in=a,e.avail_in=s,r.hold=c,r.bits=l,(r.wsize||h!==e.avail_out&&r.mode<C&&(r.mode<Li||t!==Ks))&&Kd(e,e.output,e.next_out,h-e.avail_out),d-=e.avail_in,h-=e.avail_out,e.total_in+=d,e.total_out+=h,r.total+=h,r.wrap&&h&&(e.adler=r.check=r.flags?Z(r.check,i,h,e.next_out-h):Ri(r.check,i,h,e.next_out-h)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Pe?128:0)+(r.mode===jr||r.mode===Mi?256:0),(d===0&&h===0||t===Ks)&&S===Ht&&(S=Md),S}function Wd(e){if(!e||!e.state)return qe;var t=e.state;return t.window&&(t.window=null),e.state=null,Ht}var Bi=0,St=1,Cr=2,Kt=3,Dr=4,At=5,Vt=6,Wt=7,bc=0,mc=1,Ec=2,xc=3,Ui=4,Sc=5,Gd=6,Mr=0,Ac=1,kc=2,Yd=-1,Jd=-2,Xd=-3,Rc=-5,Qd=0,ep=1,tp=9,rp=-1,np=1,ip=2,ap=3,op=4,sp=0,cp=0,fp=1,lp=2,Oc=8;function fe(e){if(e<St||e>Wt)throw new TypeError("Bad argument");this.mode=e,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}fe.prototype.init=function(e,t,r,n,i){this.windowBits=e,this.level=t,this.memLevel=r,this.strategy=n,(this.mode===Kt||this.mode===Dr)&&(this.windowBits+=16),this.mode===Wt&&(this.windowBits+=32),(this.mode===At||this.mode===Vt)&&(this.windowBits=-this.windowBits),this.strm=new Ih;var a;switch(this.mode){case St:case Kt:case At:a=md(this.strm,this.level,Oc,this.windowBits,this.memLevel,this.strategy);break;case Cr:case Dr:case Vt:case Wt:a=qd(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(a!==Mr){this._error(a);return}this.write_in_progress=!1,this.init_done=!0},fe.prototype.params=function(){throw new Error("deflateParams Not supported")},fe.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===Bi)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")},fe.prototype.write=function(e,t,r,n,i,a,o){this._writeCheck(),this.write_in_progress=!0;var s=this;return ke.nextTick(function(){s.write_in_progress=!1;var f=s._write(e,t,r,n,i,a,o);s.callback(f[0],f[1]),s.pending_close&&s.close()}),this};function up(e,t){for(var r=0;r<e.length;r++)this[t+r]=e[r]}fe.prototype.writeSync=function(e,t,r,n,i,a,o){return this._writeCheck(),this._write(e,t,r,n,i,a,o)},fe.prototype._write=function(e,t,r,n,i,a,o){if(this.write_in_progress=!0,e!==bc&&e!==mc&&e!==Ec&&e!==xc&&e!==Ui&&e!==Sc)throw new Error("Invalid flush value");t==null&&(t=new g(0),n=0,r=0),i._set?i.set=i._set:i.set=up;var s=this.strm;s.avail_in=n,s.input=t,s.next_in=r,s.avail_out=o,s.output=i,s.next_out=a;var f;switch(this.mode){case St:case Kt:case At:f=Ed(s,e);break;case Wt:case Cr:case Dr:case Vt:f=Vd(s,e);break;default:throw new Error("Unknown mode "+this.mode)}return this._checkError(f,s,e)||this._error(f),this.write_in_progress=!1,[s.avail_in,s.avail_out]},fe.prototype._checkError=function(e,t,r){switch(e){case Mr:case Rc:if(t.avail_out!==0&&r===Ui)return!1;break;case Ac:break;case kc:return!1;default:return!1}return!0},fe.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,this.mode===St||this.mode===Kt||this.mode===At?xd(this.strm):Wd(this.strm),this.mode=Bi};var Lr;fe.prototype.reset=function(){switch(this.mode){case St:case At:Lr=$s(this.strm);break;case Cr:case Vt:Lr=wc(this.strm);break}Lr!==Mr&&this._error(Lr)},fe.prototype._error=function(e){this.onerror(hs[e]+": "+this.strm.msg,e),this.write_in_progress=!1,this.pending_close&&this.close()};var Ic=Object.freeze({__proto__:null,DEFLATE:St,DEFLATERAW:At,GUNZIP:Dr,GZIP:Kt,INFLATE:Cr,INFLATERAW:Vt,NONE:Bi,UNZIP:Wt,Z_BEST_COMPRESSION:tp,Z_BEST_SPEED:ep,Z_BINARY:cp,Z_BLOCK:Sc,Z_BUF_ERROR:Rc,Z_DATA_ERROR:Xd,Z_DEFAULT_COMPRESSION:rp,Z_DEFAULT_STRATEGY:sp,Z_DEFLATED:Oc,Z_ERRNO:Yd,Z_FILTERED:np,Z_FINISH:Ui,Z_FIXED:op,Z_FULL_FLUSH:xc,Z_HUFFMAN_ONLY:ip,Z_NEED_DICT:kc,Z_NO_COMPRESSION:Qd,Z_NO_FLUSH:bc,Z_OK:Mr,Z_PARTIAL_FLUSH:mc,Z_RLE:ap,Z_STREAM_END:Ac,Z_STREAM_ERROR:Jd,Z_SYNC_FLUSH:Ec,Z_TEXT:fp,Z_TREES:Gd,Z_UNKNOWN:lp,Zlib:fe});function hp(e,t){if(!e)throw new Error(t)}var x={};Object.keys(Ic).forEach(function(e){x[e]=Ic[e]}),x.Z_MIN_WINDOWBITS=8,x.Z_MAX_WINDOWBITS=15,x.Z_DEFAULT_WINDOWBITS=15,x.Z_MIN_CHUNK=64,x.Z_MAX_CHUNK=1/0,x.Z_DEFAULT_CHUNK=16*1024,x.Z_MIN_MEMLEVEL=1,x.Z_MAX_MEMLEVEL=9,x.Z_DEFAULT_MEMLEVEL=8,x.Z_MIN_LEVEL=-1,x.Z_MAX_LEVEL=9,x.Z_DEFAULT_LEVEL=x.Z_DEFAULT_COMPRESSION;var Gt={Z_OK:x.Z_OK,Z_STREAM_END:x.Z_STREAM_END,Z_NEED_DICT:x.Z_NEED_DICT,Z_ERRNO:x.Z_ERRNO,Z_STREAM_ERROR:x.Z_STREAM_ERROR,Z_DATA_ERROR:x.Z_DATA_ERROR,Z_MEM_ERROR:x.Z_MEM_ERROR,Z_BUF_ERROR:x.Z_BUF_ERROR,Z_VERSION_ERROR:x.Z_VERSION_ERROR};Object.keys(Gt).forEach(function(e){Gt[Gt[e]]=e});function dp(e){return new ot(e)}function pp(e){return new st(e)}function yp(e){return new lt(e)}function gp(e){return new ut(e)}function vp(e){return new ct(e)}function wp(e){return new ft(e)}function _p(e){return new ht(e)}function bp(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new ot(t),e,r)}function mp(e,t){return at(new ot(t),e)}function Ep(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new ct(t),e,r)}function xp(e,t){return at(new ct(t),e)}function Sp(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new lt(t),e,r)}function Ap(e,t){return at(new lt(t),e)}function kp(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new ht(t),e,r)}function Rp(e,t){return at(new ht(t),e)}function Op(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new st(t),e,r)}function Ip(e,t){return at(new st(t),e)}function Pp(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new ft(t),e,r)}function Tp(e,t){return at(new ft(t),e)}function jp(e,t,r){return typeof t=="function"&&(r=t,t={}),it(new ut(t),e,r)}function Fp(e,t){return at(new ut(t),e)}function it(e,t,r){var n=[],i=0;e.on("error",o),e.on("end",s),e.end(t),a();function a(){for(var f;(f=e.read())!==null;)n.push(f),i+=f.length;e.once("readable",a)}function o(f){e.removeListener("end",s),e.removeListener("readable",a),r(f)}function s(){var f=g.concat(n,i);n=[],r(null,f),e.close()}}function at(e,t){if(typeof t=="string"&&(t=new g(t)),!g.isBuffer(t))throw new TypeError("Not a string or buffer");var r=x.Z_FINISH;return e._processChunk(t,r)}function ot(e){if(!(this instanceof ot))return new ot(e);D.call(this,e,x.DEFLATE)}function st(e){if(!(this instanceof st))return new st(e);D.call(this,e,x.INFLATE)}function ct(e){if(!(this instanceof ct))return new ct(e);D.call(this,e,x.GZIP)}function ft(e){if(!(this instanceof ft))return new ft(e);D.call(this,e,x.GUNZIP)}function lt(e){if(!(this instanceof lt))return new lt(e);D.call(this,e,x.DEFLATERAW)}function ut(e){if(!(this instanceof ut))return new ut(e);D.call(this,e,x.INFLATERAW)}function ht(e){if(!(this instanceof ht))return new ht(e);D.call(this,e,x.UNZIP)}function D(e,t){if(this._opts=e=e||{},this._chunkSize=e.chunkSize||x.Z_DEFAULT_CHUNK,re.call(this,e),e.flush&&e.flush!==x.Z_NO_FLUSH&&e.flush!==x.Z_PARTIAL_FLUSH&&e.flush!==x.Z_SYNC_FLUSH&&e.flush!==x.Z_FULL_FLUSH&&e.flush!==x.Z_FINISH&&e.flush!==x.Z_BLOCK)throw new Error("Invalid flush flag: "+e.flush);if(this._flushFlag=e.flush||x.Z_NO_FLUSH,e.chunkSize&&(e.chunkSize<x.Z_MIN_CHUNK||e.chunkSize>x.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBits<x.Z_MIN_WINDOWBITS||e.windowBits>x.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.level<x.Z_MIN_LEVEL||e.level>x.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevel<x.Z_MIN_MEMLEVEL||e.memLevel>x.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=x.Z_FILTERED&&e.strategy!=x.Z_HUFFMAN_ONLY&&e.strategy!=x.Z_RLE&&e.strategy!=x.Z_FIXED&&e.strategy!=x.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!g.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new x.Zlib(t);var r=this;this._hadError=!1,this._binding.onerror=function(a,o){r._binding=null,r._hadError=!0;var s=new Error(a);s.errno=o,s.code=Gt[o],r.emit("error",s)};var n=x.Z_DEFAULT_COMPRESSION;typeof e.level=="number"&&(n=e.level);var i=x.Z_DEFAULT_STRATEGY;typeof e.strategy=="number"&&(i=e.strategy),this._binding.init(e.windowBits||x.Z_DEFAULT_WINDOWBITS,n,e.memLevel||x.Z_DEFAULT_MEMLEVEL,i,e.dictionary),this._buffer=new g(this._chunkSize),this._offset=0,this._closed=!1,this._level=n,this._strategy=i,this.once("end",this.close)}W(D,re),D.prototype.params=function(e,t,r){if(e<x.Z_MIN_LEVEL||e>x.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(t!=x.Z_FILTERED&&t!=x.Z_HUFFMAN_ONLY&&t!=x.Z_RLE&&t!=x.Z_FIXED&&t!=x.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+t);if(this._level!==e||this._strategy!==t){var n=this;this.flush(x.Z_SYNC_FLUSH,function(){n._binding.params(e,t),n._hadError||(n._level=e,n._strategy=t,r&&r())})}else ke.nextTick(r)},D.prototype.reset=function(){return this._binding.reset()},D.prototype._flush=function(e){this._transform(new g(0),"",e)},D.prototype.flush=function(e,t){var r=this._writableState;if((typeof e=="function"||e===void 0&&!t)&&(t=e,e=x.Z_FULL_FLUSH),r.ended)t&&ke.nextTick(t);else if(r.ending)t&&this.once("end",t);else if(r.needDrain){var n=this;this.once("drain",function(){n.flush(t)})}else this._flushFlag=e,this.write(new g(0),"",t)},D.prototype.close=function(e){if(e&&ke.nextTick(e),!this._closed){this._closed=!0,this._binding.close();var t=this;ke.nextTick(function(){t.emit("close")})}},D.prototype._transform=function(e,t,r){var n,i=this._writableState,a=i.ending||i.ended,o=a&&(!e||i.length===e.length);if(!e===null&&!g.isBuffer(e))return r(new Error("invalid input"));o?n=x.Z_FINISH:(n=this._flushFlag,e.length>=i.length&&(this._flushFlag=this._opts.flush||x.Z_NO_FLUSH)),this._processChunk(e,n,r)},D.prototype._processChunk=function(e,t,r){var n=e&&e.length,i=this._chunkSize-this._offset,a=0,o=this,s=typeof r=="function";if(!s){var f=[],c=0,l;this.on("error",function(y){l=y});do var d=this._binding.writeSync(t,e,a,n,this._buffer,this._offset,i);while(!this._hadError&&p(d[0],d[1]));if(this._hadError)throw l;var h=g.concat(f,c);return this.close(),h}var u=this._binding.write(t,e,a,n,this._buffer,this._offset,i);u.buffer=e,u.callback=p;function p(y,w){if(!o._hadError){var _=i-w;if(hp(_>=0,"have should not go down"),_>0){var m=o._buffer.slice(o._offset,o._offset+_);o._offset+=_,s?o.push(m):(f.push(m),c+=m.length)}if((w===0||o._offset>=o._chunkSize)&&(i=o._chunkSize,o._offset=0,o._buffer=new g(o._chunkSize)),w===0){if(a+=n-y,n=y,!s)return!0;var E=o._binding.write(t,e,a,n,o._buffer,o._offset,o._chunkSize);E.callback=p,E.buffer=e;return}if(!s)return!1;r()}}},W(ot,D),W(st,D),W(ct,D),W(ft,D),W(lt,D),W(ut,D),W(ht,D);var Pc={codes:Gt,createDeflate:dp,createInflate:pp,createDeflateRaw:yp,createInflateRaw:gp,createGzip:vp,createGunzip:wp,createUnzip:_p,deflate:bp,deflateSync:mp,gzip:Ep,gzipSync:xp,deflateRaw:Sp,deflateRawSync:Ap,unzip:kp,unzipSync:Rp,inflate:Op,inflateSync:Ip,gunzip:Pp,gunzipSync:Tp,inflateRaw:jp,inflateRawSync:Fp,Deflate:ot,Inflate:st,Gzip:ct,Gunzip:ft,DeflateRaw:lt,InflateRaw:ut,Unzip:ht,Zlib:D};class Tc extends gi{constructor({client:t,keyPrefix:r="cache",ttl:n=0,prefix:i=void 0}){super({client:t,keyPrefix:r,ttl:n,prefix:i}),this.client=t,this.keyPrefix=r,this.config.ttl=n,this.config.client=t,this.config.prefix=i!==void 0?i:r+(r.endsWith("/")?"":"/")}async _set(t,r){let n=JSON.stringify(r);const i=n.length;return n=Pc.gzipSync(n).toString("base64"),this.client.putObject({key:xe(this.keyPrefix,t),body:n,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(i),"length-compressed":String(n.length),"compression-gain":(n.length/i).toFixed(2)}})}async _get(t){try{const{Body:r}=await this.client.getObject(xe(this.keyPrefix,t));let n=await vt(r);return n=Buffer.from(n,"base64"),n=Pc.unzipSync(n).toString(),JSON.parse(n)}catch(r){if(r.name==="NoSuchKey"||r.name==="NotFound")return null;throw r}}async _del(t){return await this.client.deleteObject(xe(this.keyPrefix,t)),!0}async _clear(){const t=await this.client.getAllKeys({prefix:this.keyPrefix});for(const r of t)await this.client.deleteObject(r)}async size(){return(await this.keys()).length}async keys(){const t=await this.client.getAllKeys({prefix:this.keyPrefix}),r=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return t.map(n=>n.startsWith(r)?n.slice(r.length):n)}}class jc extends R{async setup(t){}async start(){}async stop(){}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 Cp={setup(e){},start(){},stop(){}},Dp={async setup(e){this.client=e.client,this.map={PutObjectCommand:"put",GetObjectCommand:"get",HeadObjectCommand:"get",DeleteObjectCommand:"delete",DeleteObjectsCommand:"delete",ListObjectsV2Command:"list"},this.costs={total:0,prices:{put:.005/1e3,copy:.005/1e3,list:.005/1e3,post:.005/1e3,get:4e-4/1e3,select:4e-4/1e3,delete:4e-4/1e3},requests:{total:0,put:0,post:0,copy:0,list:0,get:0,select:0,delete: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.on("command.response",e=>this.addRequest(e,this.map[e]))},addRequest(e,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.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 Mp extends jc{constructor(t={}){super(),this.driver=t.driver}async setup(t){this.database=t,this.driver||(this.driver=new Tc({keyPrefix:"cache",client:t.client})),this.installDatabaseProxy();for(const r of Object.values(t.resources))this.installResourcesProxies(r)}async start(){}async stop(){}installDatabaseProxy(){const t=this.installResourcesProxies.bind(this);this.database._createResource=this.database.createResource,this.database.createResource=async function(...r){const n=await this._createResource(...r);return t(n),n}}installResourcesProxies(t){t.cache=this.driver;let r=`resource=${t.name}`;this.driver.keyPrefix&&(this.driver.keyPrefix=xe(this.driver.keyPrefix,r)),t.cacheKeyFor=async function({params:n={},action:i="list"}){let a=Object.keys(n).sort().map(o=>`${o}:${n[o]}`).join("|")||"empty";return a=await ca(a),a=xe(r,`action=${i}`,`${a}.json.gz`),a},t._count=t.count,t._listIds=t.listIds,t._getMany=t.getMany,t._getAll=t.getAll,t._page=t.page,t.count=async function(){const n=await this.cacheKeyFor({action:"count"});try{const a=await this.cache.get(n);if(a)return a}catch(a){if(a.name!=="NoSuchKey")throw a}const i=await t._count();return await this.cache.set(n,i),i},t.listIds=async function(){const n=await this.cacheKeyFor({action:"listIds"});try{const a=await this.cache.get(n);if(a)return a}catch(a){if(a.name!=="NoSuchKey")throw a}const i=await t._listIds();return await this.cache.set(n,i),i},t.getMany=async function(n){const i=await this.cacheKeyFor({action:"getMany",params:{ids:n}});try{const o=await this.cache.get(i);if(o)return o}catch(o){if(o.name!=="NoSuchKey")throw o}const a=await t._getMany(n);return await this.cache.set(i,a),a},t.getAll=async function(){const n=await this.cacheKeyFor({action:"getAll"});try{const a=await this.cache.get(n);if(a)return a}catch(a){if(a.name!=="NoSuchKey")throw a}const i=await t._getAll();return await this.cache.set(n,i),i},t.page=async function({offset:n,size:i}){const a=await this.cacheKeyFor({action:"page",params:{offset:n,size:i}});try{const s=await this.cache.get(a);if(s)return s}catch(s){if(s.name!=="NoSuchKey")throw s}const o=await t._page({offset:n,size:i});return await this.cache.set(a,o),o},t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,t.insert=async function(...n){const i=await t._insert(...n);return await this.cache.clear(r),i},t.update=async function(...n){const i=await t._update(...n);return await this.cache.clear(r),i},t.delete=async function(...n){const i=await t._delete(...n);return await this.cache.clear(r),i},t.deleteMany=async function(...n){const i=await t._deleteMany(...n);return await this.cache.clear(r),i}}}exports.AVAILABLE_BEHAVIORS=kh,exports.AuthenticationError=yf,exports.BaseError=Xi,exports.Cache=gi,exports.CachePlugin=Mp,exports.Client=sa,exports.ConnectionString=oa,exports.CostsPlugin=Dp,exports.DEFAULT_BEHAVIOR=fs,exports.Database=ls,exports.DatabaseError=df,exports.EncryptionError=vf,exports.ErrorMap=na,exports.InvalidResourceItem=nr,exports.MemoryCache=Oh,exports.MissingMetadata=ta,exports.NoSuchBucket=Qi,exports.NoSuchKey=Hr,exports.NotFound=ea,exports.PermissionError=gf,exports.Plugin=jc,exports.PluginObject=Cp,exports.Resource=mr,exports.ResourceIdsPageReader=is,exports.ResourceIdsReader=ns,exports.ResourceNotFound=wf,exports.ResourceReader=as,exports.ResourceWriter=os,exports.S3Cache=Tc,exports.S3DBError=ie,exports.S3_DEFAULT_ENDPOINT=aa,exports.S3_DEFAULT_REGION=ia,exports.S3db=us,exports.Schema=me,exports.SchemaActions=Hn,exports.UnknownError=ra,exports.ValidationError=pf,exports.Validator=po,exports.ValidatorManager=yo,exports.behaviors=br,exports.calculateAttributeNamesSize=ui,exports.calculateAttributeSizes=Ft,exports.calculateTotalSize=Me,exports.calculateUTF8Bytes=Xe,exports.decrypt=fa,exports.default=us,exports.encrypt=Kr,exports.getBehavior=we,exports.getSizeBreakdown=ih,exports.idGenerator=Zr,exports.passwordGenerator=nf,exports.sha256=ca,exports.streamToString=vt,exports.transformValue=hi;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("nanoid"),e=require("lodash-es"),r=require("@supercharge/promise-pool"),n=require("@aws-sdk/client-s3"),i=require("crypto"),s=require("flat"),o=require("fastest-validator"),a=require("node:stream/web");function c(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 u=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,l=function(t){return u.exec(t).slice(1)};function h(){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=c(m(t.split("/"),function(t){return!!t}),!e).join("/"))||"."}function f(t){var e=d(t),r="/"===y(t,-1);return(t=c(m(t.split("/"),function(t){return!!t}),!e).join("/"))||e||(t="."),t&&r&&(t+="/"),(e?"/":"")+t}function d(t){return"/"===t.charAt(0)}function p(){return f(m(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 g={extname:function(t){return l(t)[3]},basename:function(t,e){var r=l(t)[2];return e&&r.substr(-1*e.length)===e&&(r=r.substr(0,r.length-e.length)),r},dirname:function(t){var e=l(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=h(t).substr(1),e=h(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:p,isAbsolute:d,normalize:f,resolve:h};function m(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 y="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 b=t.customAlphabet(t.urlAlphabet,22),w=t.customAlphabet("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",12);var _;function v(){}function k(){k.init.call(this)}function S(t){return void 0===t._maxListeners?k.defaultMaxListeners:t._maxListeners}function O(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 v,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=S(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 x(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 E(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 R(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}v.prototype=Object.create(null),k.EventEmitter=k,k.usingDomains=!1,k.prototype.domain=void 0,k.prototype._events=void 0,k.prototype._maxListeners=void 0,k.defaultMaxListeners=10,k.init=function(){this.domain=null,k.usingDomains&&(!_.active||this instanceof _.Domain||(this.domain=_.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new v,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},k.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},k.prototype.getMaxListeners=function(){return S(this)},k.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=R(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=R(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=R(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=R(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=R(t,i),o=0;o<i;++o)s[o].apply(r,n)}(r,l,this,i)}return!0},k.prototype.addListener=function(t,e){return O(this,t,e,!1)},k.prototype.on=k.prototype.addListener,k.prototype.prependListener=function(t,e){return O(this,t,e,!0)},k.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,x(this,t,e)),this},k.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,x(this,t,e)),this},k.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 v:(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 v,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},k.prototype.off=function(t,e){return this.removeListener(t,e)},k.prototype.removeAllListeners=function(t){var e,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new v,this._eventsCount=0):r[t]&&(0===--this._eventsCount?this._events=new v: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 v,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},k.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):[]},k.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):E.call(t,e)},k.prototype.listenerCount=E,k.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class A 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 A{constructor(t,e={}){super({message:t,...e})}}class j extends I{constructor({bucket:t,...e}){super(`Bucket does not exists [bucket:${t}]`,{bucket:t,...e})}}class D extends I{constructor({bucket:t,key:e,...r}){super(`Key [${e}] does not exists [bucket:${t}/${e}]`,{bucket:t,key:e,...r})}}class P extends D{}class N extends I{constructor({bucket:t,...e}){super(`Missing metadata for bucket [bucket:${t}]`,{bucket:t,...e})}}class T 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 C extends I{}const M={NotFound:P,NoSuchKey:D,UnknownError:C,NoSuchBucket:j,MissingMetadata:N,InvalidResourceItem:T},L="us-east-1",$="https://s3.us-east-1.amazonaws.com";class U{constructor(t){let e;try{e=new URL(t)}catch(e){throw new Error("Invalid connection string: "+t)}this.region=L,"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=$,["/","",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 z extends k{constructor({verbose:t=!1,id:e=null,AwsS3Client:r,connectionString:n,parallelism:i=10}){super(),this.verbose=t,this.id=e??b(),this.parallelism=i,this.config=new U(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 n.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=M[t.name];return r?new r(e):t}async putObject({key:t,metadata:e,contentType:r,body:i,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?g.join(a,t):t,Metadata:c,Body:i||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 n.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?g.join(e,t):t};try{const t=await this.sendCommand(new n.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?g.join(e,t):t};try{const t=await this.sendCommand(new n.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?g.join(this.config.keyPrefix,e):e,CopySource:g.join(this.config.bucket,this.config.keyPrefix?g.join(this.config.keyPrefix,t):t)};try{const t=await this.client.send(new n.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?g.join(e,t):t};try{const t=await this.sendCommand(new n.DeleteObjectCommand(r));return this.emit("deleteObject",t,r),t}catch(e){throw this.errorProxy(e,{key:t,command:r})}}async deleteObjects(t){const i="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",s=e.chunk(t,1e3),{results:o,errors:a}=await r.PromisePool.for(s).withConcurrency(this.parallelism).process(async t=>{const e={Bucket:this.config.bucket,Delete:{Objects:t.map(t=>({Key:i?g.join(i,t):t}))}};try{return await this.sendCommand(new n.DeleteObjectsCommand(e))}catch(r){throw this.errorProxy(r,{keys:t,command:e})}}),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,i=0;do{const s=new n.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:e?g.join(e,t):t,ContinuationToken:r}),o=await this.client.send(s);if(o.Contents&&o.Contents.length>0){const e=new n.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;i+=s,this.emit("deleteAll",{prefix:t,batch:s,total:i})}r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:t,totalDeleted:i}),i}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 i={Bucket:this.config.bucket,MaxKeys:e,ContinuationToken:r,Prefix:this.config.keyPrefix?g.join(this.config.keyPrefix,t||""):t||""};try{const t=await this.sendCommand(new n.ListObjectsV2Command(i));return this.emit("listObjects",t,i),t}catch(t){throw this.errorProxy(t,{command:i})}}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 n=await this.getAllKeys({prefix:t}),{results:i,errors:s}=await r.PromisePool.for(n).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 F(){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 B(t){const e=await F(),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 q(t,e){const r=await F(),n=r.getRandomValues(new Uint8Array(16)),i=await H(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 V(t,e){const r=await F(),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 H(e,i),c=await r.subtle.decrypt({name:"AES-GCM",iv:s},a,o);return(new TextDecoder).decode(c)}async function H(t,e){const r=await F(),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 K(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Z,W,J,G,Y,Q,X,tt,et,rt,nt,it,st,ot={};function at(){if(W)return Z;var t,e;W=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 Z=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},Z}function ct(){if(G)return J;G=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 J=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 ut(){if(et)return tt;et=1;var t=Object.prototype.toString;return tt=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 lt(){if(nt)return rt;var t;if(nt=1,!Object.keys){var e=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=ut(),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 rt=t}function ht(){if(st)return it;st=1;var t=Array.prototype.slice,e=ut(),r=Object.keys,n=r?function(t){return r(t)}:lt(),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},it=n}var ft,dt,pt,gt,mt,yt,bt,wt,_t,vt,kt,St,Ot,xt,Et,Rt,At,It,jt,Dt,Pt,Nt,Tt,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,xe,Ee,Re,Ae,Ie,je,De,Pe,Ne,Te,Ce,Me,Le,$e,Ue={exports:{}};function ze(){return dt?ft:(dt=1,ft=Object)}function Fe(){return gt?pt:(gt=1,pt=Error)}function Be(){return yt?mt:(yt=1,mt=EvalError)}function qe(){return wt?bt:(wt=1,bt=RangeError)}function Ve(){return vt?_t:(vt=1,_t=ReferenceError)}function He(){return St?kt:(St=1,kt=SyntaxError)}function Ke(){return xt?Ot:(xt=1,Ot=TypeError)}function Ze(){return Rt?Et:(Rt=1,Et=URIError)}function We(){return It?At:(It=1,At=Math.abs)}function Je(){return Dt?jt:(Dt=1,jt=Math.floor)}function Ge(){return Nt?Pt:(Nt=1,Pt=Math.max)}function Ye(){return Ct?Tt:(Ct=1,Tt=Math.min)}function Qe(){return Lt?Mt:(Lt=1,Mt=Math.pow)}function Xe(){return Ut?$t:(Ut=1,$t=Math.round)}function tr(){if(qt)return Bt;qt=1;var t=Ft?zt:(Ft=1,zt=Number.isNaN||function(t){return t!=t});return Bt=function(e){return t(e)||0===e?e:e<0?-1:1}}function er(){if(Zt)return Kt;Zt=1;var t=Ht?Vt:(Ht=1,Vt=Object.getOwnPropertyDescriptor);if(t)try{t([],"length")}catch(e){t=null}return Kt=t}function rr(){if(Jt)return Wt;Jt=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}return Wt=t}function nr(){if(Xt)return Qt;Xt=1;var t="undefined"!=typeof Symbol&&Symbol,e=Yt?Gt:(Yt=1,Gt=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 Qt=function(){return"function"==typeof t&&("function"==typeof Symbol&&("symbol"==typeof t("foo")&&("symbol"==typeof Symbol("bar")&&e())))}}function ir(){return ee?te:(ee=1,te="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function sr(){return ne?re:(ne=1,re=ze().getPrototypeOf||null)}function or(){if(se)return ie;se=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 ie=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},ie}function ar(){if(ae)return oe;ae=1;var t=or();return oe=Function.prototype.bind||t}function cr(){return ue?ce:(ue=1,ce=Function.prototype.call)}function ur(){return he?le:(he=1,le=Function.prototype.apply)}function lr(){if(ge)return pe;ge=1;var t=ar(),e=ur(),r=cr(),n=de?fe:(de=1,fe="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return pe=n||t.call(r,e)}function hr(){if(ye)return me;ye=1;var t=ar(),e=Ke(),r=cr(),n=lr();return me=function(i){if(i.length<1||"function"!=typeof i[0])throw new e("a function is required");return n(t,r,i)}}function fr(){if(we)return be;we=1;var t,e=hr(),r=er();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 be=n&&"function"==typeof n.get?e([n.get]):"function"==typeof s&&function(t){return s(null==t?t:i(t))}}function dr(){if(ve)return _e;ve=1;var t=ir(),e=sr(),r=fr();return _e=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 pr(){if(Se)return ke;Se=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,r=ar();return ke=r.call(t,e)}function gr(){if(xe)return Oe;var t;xe=1;var e=ze(),r=Fe(),n=Be(),i=qe(),s=Ve(),o=He(),a=Ke(),c=Ze(),u=We(),l=Je(),h=Ge(),f=Ye(),d=Qe(),p=Xe(),g=tr(),m=Function,y=function(t){try{return m('"use strict"; return ('+t+").constructor;")()}catch(t){}},b=er(),w=rr(),_=function(){throw new a},v=b?function(){try{return _}catch(t){try{return b(arguments,"callee").get}catch(t){return _}}}():_,k=nr()(),S=dr(),O=sr(),x=ir(),E=ur(),R=cr(),A={},I="undefined"!=typeof Uint8Array&&S?S(Uint8Array):t,j={__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%":I,"%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%":R,"%Function.prototype.apply%":E,"%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%":x};if(S)try{null.error}catch(t){var D=S(S(t));j["%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 j[e]=r,r},N={__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"]},T=ar(),C=pr(),M=T.call(R,Array.prototype.concat),L=T.call(E,Array.prototype.splice),$=T.call(R,String.prototype.replace),U=T.call(R,String.prototype.slice),z=T.call(R,RegExp.prototype.exec),F=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,B=/\\(\\)?/g,q=function(t,e){var r,n=t;if(C(N,n)&&(n="%"+(r=N[n])[0]+"%"),C(j,n)){var i=j[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 Oe=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(j,s="%"+(n+="."+d)+"%"))c=j[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&&(j[s]=c)}}return c},Oe}function mr(){if(Re)return Ee;Re=1;var t=rr(),e=He(),r=Ke(),n=er();return Ee=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}},Ee}function yr(){if(Ie)return Ae;Ie=1;var t=rr(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return 1!==t([],"length",{value:1}).length}catch(t){return!0}},Ae=e}function br(){if(De)return je;De=1;var t=gr(),e=mr(),r=yr()(),n=er(),i=Ke(),s=t("%Math.floor%");return je=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},je}function wr(){if(Ne)return Pe;Ne=1;var t=ar(),e=ur(),r=lr();return Pe=function(){return r(t,e,arguments)},Pe}function _r(){return Te||(Te=1,function(t){var e=br(),r=rr(),n=hr(),i=wr();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}(Ue)),Ue.exports}function vr(){if(Me)return Ce;Me=1;var t=gr(),e=hr(),r=e([t("%String.prototype.indexOf%")]);return Ce=function(n,i){var s=t(n,!!i);return"function"==typeof s&&r(n,".prototype.")>-1?e([s]):s}}var kr=function(){if($e)return Le;$e=1;var t=("undefined"!=typeof JSON?JSON:(Y||(Y=1,ot.parse=at(),ot.stringify=ct()),ot)).stringify,e=function(){if(X)return Q;X=1;var t={}.toString;return Q=Array.isArray||function(e){return"[object Array]"==t.call(e)}}(),r=ht(),n=_r(),i=vr(),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 Le=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 x=c(r(h),y&&y(h));for(k=[],S=0;S<x.length;S++){var E=n(h,l=x[S],h[l],m+1);if(E){var R=t(l)+_+E;k[k.length]=w+f+R}}return a(b,o(b,h),1),v(k,"{}")}}({"":i},"",i,0)},Le}(),Sr=K(kr);async function Or(t,e,r){if(!this.passphrase)return e.push({actual:t,type:"encryptionKeyMissing"}),t;try{return await q(String(t),this.passphrase)}catch(r){e.push({actual:t,type:"encryptionProblem",error:r})}return t}async function xr(t,r,n){return e.isString(t)?t:JSON.stringify(t)}class Er extends o{constructor({options:t,passphrase:r,autoEncrypt:n=!0}={}){super(e.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=r,this.autoEncrypt=n,this.alias("secret",{type:"string",custom:this.autoEncrypt?Or: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?Or:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Or:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?xr:void 0})}}const Rr=new Proxy(Er,{instance:null,construct(t,e){return this.instance||(this.instance=new t(...e)),this.instance}});const Ar={trim:t=>t.trim(),encrypt:(t,{passphrase:e})=>q(t,e),decrypt:async(t,{passphrase:e})=>{try{return await V(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=>e.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:r,name:n,attributes:i,passphrase:o,version:a=1,options:c={}}=t;this.name=n,this.version=a,this.attributes=i||{},this.passphrase=o??"secret",this.options=e.merge({},this.defaultOptions(),c),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const u=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Rr({autoEncrypt:!1}).compile(e.merge({$$async:!0},u)),this.options.generateAutoHooks&&this.generateAutoHooks(),e.isEmpty(r)){const t=s.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:o}=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=o}else this.map=r,this.reversedMap=e.invert(r)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(t,r,n){this.options.hooks[t][r]||(this.options.hooks[t][r]=[]),this.options.hooks[t][r]=e.uniq([...this.options.hooks[t][r],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=s.flatten(e.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:r,name:n,options:i,version:s,attributes:o}=e.isString(t)?JSON.parse(t):t;o=Ir._importAttributes(o);return new Ir({map:r,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,r){for(const[n,i]of Object.entries(this.options.hooks[r]))for(const r of i){const i=e.get(t,n);void 0!==i&&"function"==typeof Ar[r]&&e.set(t,n,await Ar[r](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}}async validate(t,{mutateOriginal:r=!1}={}){let n=r?t:e.cloneDeep(t);return await this.validator(n)}async mapper(t){const r=s.flatten(e.cloneDeep(t),{safe:!0});await this.applyHooksActions(r,"beforeMap");const n={_v:this.version+""};for(const[t,e]of Object.entries(r))n[this.map[t]]=e;return await this.applyHooksActions(n,"afterMap"),n}async unmapper(t){const r=e.cloneDeep(t);delete r._v,await this.applyHooksActions(r,"beforeUnmap");const n={};for(const[t,e]of Object.entries(r))n[this.reversedMap[t]]=e;return await this.applyHooksActions(n,"afterUnmap"),s.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 jr="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Dr=[],Pr=[],Nr="undefined"!=typeof Uint8Array?Uint8Array:Array,Tr=!1;function Cr(){Tr=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0;e<64;++e)Dr[e]=t[e],Pr[t.charCodeAt(e)]=e;Pr["-".charCodeAt(0)]=62,Pr["_".charCodeAt(0)]=63}function Mr(t){return Dr[t>>18&63]+Dr[t>>12&63]+Dr[t>>6&63]+Dr[63&t]}function Lr(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(Mr(n));return i.join("")}function $r(t){var e;Tr||Cr();for(var r=t.length,n=r%3,i="",s=[],o=16383,a=0,c=r-n;a<c;a+=o)s.push(Lr(t,a,a+o>c?c:a+o));return 1===n?(e=t[r-1],i+=Dr[e>>2],i+=Dr[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=Dr[e>>10],i+=Dr[e>>4&63],i+=Dr[e<<2&63],i+="="),s.push(i),s.join("")}function Ur(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 zr(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 Fr={}.toString,Br=Array.isArray||function(t){return"[object Array]"==Fr.call(t)};function qr(){return Hr.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Vr(t,e){if(qr()<e)throw new RangeError("Invalid typed array length");return Hr.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Hr.prototype:(null===t&&(t=new Hr(e)),t.length=e),t}function Hr(t,e,r){if(!(Hr.TYPED_ARRAY_SUPPORT||this instanceof Hr))return new Hr(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 Wr(this,t)}return Kr(this,t,e,r)}function Kr(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);Hr.TYPED_ARRAY_SUPPORT?(t=e).__proto__=Hr.prototype:t=Jr(t,e);return t}(t,e,r,n):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!Hr.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|Qr(e,r);t=Vr(t,n);var i=t.write(e,r);i!==n&&(t=t.slice(0,i));return t}(t,e,r):function(t,e){if(Yr(e)){var r=0|Gr(e.length);return 0===(t=Vr(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?Vr(t,0):Jr(t,e);if("Buffer"===e.type&&Br(e.data))return Jr(t,e.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function Zr(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 Wr(t,e){if(Zr(e),t=Vr(t,e<0?0:0|Gr(e)),!Hr.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function Jr(t,e){var r=e.length<0?0:0|Gr(e.length);t=Vr(t,r);for(var n=0;n<r;n+=1)t[n]=255&e[n];return t}function Gr(t){if(t>=qr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+qr().toString(16)+" bytes");return 0|t}function Yr(t){return!(null==t||!t._isBuffer)}function Qr(t,e){if(Yr(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 En(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Rn(t).length;default:if(n)return En(t).length;e=(""+e).toLowerCase(),n=!0}}function Xr(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 gn(this,e,r);case"utf8":case"utf-8":return hn(this,e,r);case"ascii":return dn(this,e,r);case"latin1":case"binary":return pn(this,e,r);case"base64":return ln(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return mn(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function tn(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function en(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=Hr.from(e,n)),Yr(e))return 0===e.length?-1:rn(t,e,r,n,i);if("number"==typeof e)return e&=255,Hr.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):rn(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function rn(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 nn(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 sn(t,e,r,n){return An(En(e,t.length-r),t,r,n)}function on(t,e,r,n){return An(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function an(t,e,r,n){return on(t,e,r,n)}function cn(t,e,r,n){return An(Rn(e),t,r,n)}function un(t,e,r,n){return An(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 ln(t,e,r){return 0===e&&r===t.length?$r(t):$r(t.slice(e,r))}function hn(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<=fn)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=fn));return r}(n)}Hr.TYPED_ARRAY_SUPPORT=void 0===jr.TYPED_ARRAY_SUPPORT||jr.TYPED_ARRAY_SUPPORT,qr(),Hr.poolSize=8192,Hr._augment=function(t){return t.__proto__=Hr.prototype,t},Hr.from=function(t,e,r){return Kr(null,t,e,r)},Hr.TYPED_ARRAY_SUPPORT&&(Hr.prototype.__proto__=Uint8Array.prototype,Hr.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Hr[Symbol.species]),Hr.alloc=function(t,e,r){return function(t,e,r,n){return Zr(e),e<=0?Vr(t,e):void 0!==r?"string"==typeof n?Vr(t,e).fill(r,n):Vr(t,e).fill(r):Vr(t,e)}(null,t,e,r)},Hr.allocUnsafe=function(t){return Wr(null,t)},Hr.allocUnsafeSlow=function(t){return Wr(null,t)},Hr.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))},Hr.compare=function(t,e){if(!Yr(t)||!Yr(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},Hr.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}},Hr.concat=function(t,e){if(!Br(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Hr.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var n=Hr.allocUnsafe(e),i=0;for(r=0;r<t.length;++r){var s=t[r];if(!Yr(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,i),i+=s.length}return n},Hr.byteLength=Qr,Hr.prototype._isBuffer=!0,Hr.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)tn(this,e,e+1);return this},Hr.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)tn(this,e,e+3),tn(this,e+1,e+2);return this},Hr.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)tn(this,e,e+7),tn(this,e+1,e+6),tn(this,e+2,e+5),tn(this,e+3,e+4);return this},Hr.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?hn(this,0,t):Xr.apply(this,arguments)},Hr.prototype.equals=function(t){if(!Yr(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Hr.compare(this,t)},Hr.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+">"},Hr.prototype.compare=function(t,e,r,n,i){if(!Yr(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},Hr.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},Hr.prototype.indexOf=function(t,e,r){return en(this,t,e,r,!0)},Hr.prototype.lastIndexOf=function(t,e,r){return en(this,t,e,r,!1)},Hr.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 nn(this,t,e,r);case"utf8":case"utf-8":return sn(this,t,e,r);case"ascii":return on(this,t,e,r);case"latin1":case"binary":return an(this,t,e,r);case"base64":return cn(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return un(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},Hr.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var fn=4096;function dn(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 pn(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 gn(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+=xn(t[s]);return i}function mn(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 yn(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 bn(t,e,r,n,i,s){if(!Yr(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 wn(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 _n(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 vn(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 kn(t,e,r,n,i){return i||vn(t,0,r,4),zr(t,e,r,n,23,4),r+4}function Sn(t,e,r,n,i){return i||vn(t,0,r,8),zr(t,e,r,n,52,8),r+8}Hr.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),Hr.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=Hr.prototype;else{var i=e-t;r=new Hr(i,void 0);for(var s=0;s<i;++s)r[s]=this[s+t]}return r},Hr.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||yn(t,e,this.length);for(var n=this[t],i=1,s=0;++s<e&&(i*=256);)n+=this[t+s]*i;return n},Hr.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||yn(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},Hr.prototype.readUInt8=function(t,e){return e||yn(t,1,this.length),this[t]},Hr.prototype.readUInt16LE=function(t,e){return e||yn(t,2,this.length),this[t]|this[t+1]<<8},Hr.prototype.readUInt16BE=function(t,e){return e||yn(t,2,this.length),this[t]<<8|this[t+1]},Hr.prototype.readUInt32LE=function(t,e){return e||yn(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Hr.prototype.readUInt32BE=function(t,e){return e||yn(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Hr.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||yn(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},Hr.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||yn(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},Hr.prototype.readInt8=function(t,e){return e||yn(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Hr.prototype.readInt16LE=function(t,e){e||yn(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Hr.prototype.readInt16BE=function(t,e){e||yn(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Hr.prototype.readInt32LE=function(t,e){return e||yn(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Hr.prototype.readInt32BE=function(t,e){return e||yn(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Hr.prototype.readFloatLE=function(t,e){return e||yn(t,4,this.length),Ur(this,t,!0,23,4)},Hr.prototype.readFloatBE=function(t,e){return e||yn(t,4,this.length),Ur(this,t,!1,23,4)},Hr.prototype.readDoubleLE=function(t,e){return e||yn(t,8,this.length),Ur(this,t,!0,52,8)},Hr.prototype.readDoubleBE=function(t,e){return e||yn(t,8,this.length),Ur(this,t,!1,52,8)},Hr.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||bn(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},Hr.prototype.writeUIntBE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||bn(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},Hr.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,1,255,0),Hr.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Hr.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,2,65535,0),Hr.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):wn(this,t,e,!0),e+2},Hr.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,2,65535,0),Hr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):wn(this,t,e,!1),e+2},Hr.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,4,4294967295,0),Hr.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):_n(this,t,e,!0),e+4},Hr.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,4,4294967295,0),Hr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):_n(this,t,e,!1),e+4},Hr.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);bn(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},Hr.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);bn(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},Hr.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,1,127,-128),Hr.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Hr.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,2,32767,-32768),Hr.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):wn(this,t,e,!0),e+2},Hr.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,2,32767,-32768),Hr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):wn(this,t,e,!1),e+2},Hr.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,4,2147483647,-2147483648),Hr.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):_n(this,t,e,!0),e+4},Hr.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||bn(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Hr.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):_n(this,t,e,!1),e+4},Hr.prototype.writeFloatLE=function(t,e,r){return kn(this,t,e,!0,r)},Hr.prototype.writeFloatBE=function(t,e,r){return kn(this,t,e,!1,r)},Hr.prototype.writeDoubleLE=function(t,e,r){return Sn(this,t,e,!0,r)},Hr.prototype.writeDoubleBE=function(t,e,r){return Sn(this,t,e,!1,r)},Hr.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||!Hr.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},Hr.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&&!Hr.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=Yr(t)?t:En(new Hr(t,n).toString()),a=o.length;for(s=0;s<r-e;++s)this[s+e]=o[s%a]}return this};var On=/[^+\/0-9A-Za-z-_]/g;function xn(t){return t<16?"0"+t.toString(16):t.toString(16)}function En(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 Rn(t){return function(t){var e,r,n,i,s,o;Tr||Cr();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=Pr[t.charCodeAt(e)]<<18|Pr[t.charCodeAt(e+1)]<<12|Pr[t.charCodeAt(e+2)]<<6|Pr[t.charCodeAt(e+3)],o[c++]=i>>16&255,o[c++]=i>>8&255,o[c++]=255&i;return 2===s?(i=Pr[t.charCodeAt(e)]<<2|Pr[t.charCodeAt(e+1)]>>4,o[c++]=255&i):1===s&&(i=Pr[t.charCodeAt(e)]<<10|Pr[t.charCodeAt(e+1)]<<4|Pr[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(On,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function An(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 jn(){throw new Error("setTimeout has not been defined")}function Dn(){throw new Error("clearTimeout has not been defined")}var Pn=jn,Nn=Dn;function Tn(t){if(Pn===setTimeout)return setTimeout(t,0);if((Pn===jn||!Pn)&&setTimeout)return Pn=setTimeout,setTimeout(t,0);try{return Pn(t,0)}catch(e){try{return Pn.call(null,t,0)}catch(e){return Pn.call(this,t,0)}}}"function"==typeof jr.setTimeout&&(Pn=setTimeout),"function"==typeof jr.clearTimeout&&(Nn=clearTimeout);var Cn,Mn=[],Ln=!1,$n=-1;function Un(){Ln&&Cn&&(Ln=!1,Cn.length?Mn=Cn.concat(Mn):$n=-1,Mn.length&&zn())}function zn(){if(!Ln){var t=Tn(Un);Ln=!0;for(var e=Mn.length;e;){for(Cn=Mn,Mn=[];++$n<e;)Cn&&Cn[$n].run();$n=-1,e=Mn.length}Cn=null,Ln=!1,function(t){if(Nn===clearTimeout)return clearTimeout(t);if((Nn===Dn||!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 Fn(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];Mn.push(new Bn(t,e)),1!==Mn.length||Ln||Tn(zn)}function Bn(t,e){this.fun=t,this.array=e}Bn.prototype.run=function(){this.fun.apply(null,this.array)};function qn(){}var Vn=qn,Hn=qn,Kn=qn,Zn=qn,Wn=qn,Jn=qn,Gn=qn;var Yn=jr.performance||{},Qn=Yn.now||Yn.mozNow||Yn.msNow||Yn.oNow||Yn.webkitNow||function(){return(new Date).getTime()};var Xn=new Date;var ti,ei={nextTick:Fn,title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Vn,addListener:Hn,once:Kn,off:Zn,removeListener:Wn,removeAllListeners:Jn,emit:Gn,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*Qn.call(Yn),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-Xn)/1e3}};ti="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 ri=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},ni=/%[sdj%]/g;function ii(t){if(!mi(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(ci(arguments[r]));return e.join(" ")}r=1;for(var n=arguments,i=n.length,s=String(t).replace(ni,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])gi(o)||!wi(o)?s+=" "+o:s+=" "+ci(o);return s}function si(t,e){if(yi(jr.process))return function(){return si(t,e).apply(this,arguments)};if(!0===ei.noDeprecation)return t;var r=!1;return function(){if(!r){if(ei.throwDeprecation)throw new Error(e);ei.traceDeprecation?console.trace(e):console.error(e),r=!0}return t.apply(this,arguments)}}var oi,ai={};function ci(t,e){var r={seen:[],stylize:li};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),pi(e)?r.showHidden=e:e&&function(t,e){if(!e||!wi(e))return t;var r=Object.keys(e),n=r.length;for(;n--;)t[r[n]]=e[r[n]]}(r,e),yi(r.showHidden)&&(r.showHidden=!1),yi(r.depth)&&(r.depth=2),yi(r.colors)&&(r.colors=!1),yi(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=ui),hi(r,t,r.depth)}function ui(t,e){var r=ci.styles[e];return r?"["+ci.colors[r][0]+"m"+t+"["+ci.colors[r][1]+"m":t}function li(t,e){return t}function hi(t,e,r){if(t.customInspect&&e&&ki(e.inspect)&&e.inspect!==ci&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return mi(n)||(n=hi(t,n,r)),n}var i=function(t,e){if(yi(e))return t.stylize("undefined","undefined");if(mi(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(pi(e))return t.stylize(""+e,"boolean");if(gi(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)),vi(e)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return fi(e);if(0===s.length){if(ki(e)){var a=e.name?": "+e.name:"";return t.stylize("[Function"+a+"]","special")}if(bi(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(_i(e))return t.stylize(Date.prototype.toString.call(e),"date");if(vi(e))return fi(e)}var c,u,l="",h=!1,f=["{","}"];(c=e,Array.isArray(c)&&(h=!0,f=["[","]"]),ki(e))&&(l=" [Function"+(e.name?": "+e.name:"")+"]");return bi(e)&&(l=" "+RegExp.prototype.toString.call(e)),_i(e)&&(l=" "+Date.prototype.toUTCString.call(e)),vi(e)&&(l=" "+fi(e)),0!==s.length||h&&0!=e.length?r<0?bi(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)Oi(e,String(o))?s.push(di(t,e,r,n,String(o),!0)):s.push("");return i.forEach(function(i){i.match(/^\d+$/)||s.push(di(t,e,r,n,i,!0))}),s}(t,e,r,o,s):s.map(function(n){return di(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 fi(t){return"["+Error.prototype.toString.call(t)+"]"}function di(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")),Oi(n,i)||(o="["+i+"]"),a||(t.seen.indexOf(c.value)<0?(a=gi(r)?hi(t,c.value,null):hi(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")),yi(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 pi(t){return"boolean"==typeof t}function gi(t){return null===t}function mi(t){return"string"==typeof t}function yi(t){return void 0===t}function bi(t){return wi(t)&&"[object RegExp]"===Si(t)}function wi(t){return"object"==typeof t&&null!==t}function _i(t){return wi(t)&&"[object Date]"===Si(t)}function vi(t){return wi(t)&&("[object Error]"===Si(t)||t instanceof Error)}function ki(t){return"function"==typeof t}function Si(t){return Object.prototype.toString.call(t)}function Oi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}ci.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]},ci.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var xi="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function Ei(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(xi&&t[xi]){var e;if("function"!=typeof(e=t[xi]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,xi,{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)),xi&&Object.defineProperty(e,xi,{value:e,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(e,ri(t))}function Ri(){this.head=null,this.tail=null,this.length=0}Ei.custom=xi,Ri.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},Ri.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Ri.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}},Ri.prototype.clear=function(){this.head=this.tail=null,this.length=0},Ri.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},Ri.prototype.concat=function(t){if(0===this.length)return Hr.alloc(0);if(1===this.length)return this.head.data;for(var e=Hr.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Ai=Hr.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&&!Ai(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=Di;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Pi;break;default:return void(this.write=ji)}this.charBuffer=new Hr(6),this.charReceived=0,this.charLength=0}function ji(t){return t.toString(this.encoding)}function Di(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function Pi(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},Ci.ReadableState=Ti;var Ni=function(t){if(yi(oi)&&(oi=ei.env.NODE_DEBUG||""),t=t.toUpperCase(),!ai[t])if(new RegExp("\\b"+t+"\\b","i").test(oi)){ai[t]=function(){var e=ii.apply(null,arguments);console.error("%s %d: %s",t,0,e)}}else ai[t]=function(){};return ai[t]}("stream");function Ti(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof us&&(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 Ri,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 Ci(t){if(!(this instanceof Ci))return new Ci(t);this._readableState=new Ti(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),k.call(this)}function Mi(t,e,r,n,i){var s=function(t,e){var r=null;Hr.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,Ui(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&&Ui(t))),function(t,e){e.readingMore||(e.readingMore=!0,Fn(Fi,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)}ti(Ci,k),Ci.prototype.push=function(t,e){var r=this._readableState;return r.objectMode||"string"!=typeof t||(e=e||r.defaultEncoding)!==r.encoding&&(t=Hr.from(t,e),e=""),Mi(this,r,t,e,!1)},Ci.prototype.unshift=function(t){return Mi(this,this._readableState,t,"",!0)},Ci.prototype.isPaused=function(){return!1===this._readableState.flowing},Ci.prototype.setEncoding=function(t){return this._readableState.decoder=new Ii(t),this._readableState.encoding=t,this};var Li=8388608;function $i(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>=Li?t=Li:(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 Ui(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Ni("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?Fn(zi,t):zi(t))}function zi(t){Ni("emit readable"),t.emit("readable"),Vi(t)}function Fi(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 Bi(t){Ni("readable nexttick read 0"),t.read(0)}function qi(t,e){e.reading||(Ni("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),Vi(t),e.flowing&&!e.reading&&t.read(0)}function Vi(t){var e=t._readableState;for(Ni("flow",e.flowing);e.flowing&&null!==t.read(););}function Hi(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=Hr.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 Ki(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,Fn(Zi,e,t))}function Zi(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function Wi(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}function Ji(){}function Gi(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function Yi(t,e){Object.defineProperty(this,"buffer",{get:si(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),t=t||{},this.objectMode=!!t.objectMode,e instanceof us&&(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?Fn(i,n):i(n);t._writableState.errorEmitted=!0,t.emit("error",n)}(t,r,n,e,i);else{var s=rs(r);s||r.corked||r.bufferProcessing||!r.bufferedRequest||es(t,r),n?Fn(ts,t,r,s,i):ts(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 ss(this)}function Qi(t){if(!(this instanceof Qi||this instanceof us))return new Qi(t);this._writableState=new Yi(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev)),k.call(this)}function Xi(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 ts(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),is(t,e)}function es(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;Xi(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 ss(e)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(Xi(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 rs(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function ns(t,e){e.prefinished||(e.prefinished=!0,t.emit("prefinish"))}function is(t,e){var r=rs(e);return r&&(0===e.pendingcb?(ns(t,e),e.finished=!0,t.emit("finish")):ns(t,e)),r}function ss(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}}Ci.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?Ki(this):Ui(this),null;if(0===(t=$i(t,e))&&e.ended)return 0===e.length&&Ki(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=$i(r,e))),null===(n=t>0?Hi(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Ki(this)),null!==n&&this.emit("data",n),n},Ci.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Ci.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?Fn(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,Vi(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!==Wi(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},Ci.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=Wi(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},Ci.prototype.on=function(t,e){var r=k.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&&Ui(this):Fn(Bi,this))}return r},Ci.prototype.addListener=Ci.prototype.on,Ci.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ni("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,Fn(qi,t,e))}(this,t)),this},Ci.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},Ci.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},Ci._fromList=Hi,Qi.WritableState=Yi,ti(Qi,k),Yi.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},Qi.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Qi.prototype.write=function(t,e,r){var n=this._writableState,i=!1;return"function"==typeof e&&(r=e,e=null),Hr.isBuffer(t)?e="buffer":e||(e=n.defaultEncoding),"function"!=typeof r&&(r=Ji),n.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),Fn(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"):Hr.isBuffer(r)||"string"==typeof r||void 0===r||e.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(t.emit("error",s),Fn(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=Hr.from(e,r));return e}(e,r,n),Hr.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 Gi(r,n,i),a?a.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else Xi(t,e,!1,s,r,n,i);return o}(this,n,t,e,r)),i},Qi.prototype.cork=function(){this._writableState.corked++},Qi.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||es(this,t))},Qi.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},Qi.prototype._write=function(t,e,r){r(new Error("not implemented"))},Qi.prototype._writev=null,Qi.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,is(t,e),r&&(e.finished?Fn(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},ti(us,Ci);for(var os=Object.keys(Qi.prototype),as=0;as<os.length;as++){var cs=os[as];us.prototype[cs]||(us.prototype[cs]=Qi.prototype[cs])}function us(t){if(!(this instanceof us))return new us(t);Ci.call(this,t),Qi.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",ls)}function ls(){this.allowHalfOpen||this._writableState.ended||Fn(hs,this)}function hs(t){t.end()}function fs(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 ds(t){if(!(this instanceof ds))return new ds(t);us.call(this,t),this._transformState=new fs(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){ps(e,t)}):ps(e)})}function ps(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 gs(t){if(!(this instanceof gs))return new gs(t);ds.call(this,t)}function ms(){k.call(this)}ti(ds,us),ds.prototype.push=function(t,e){return this._transformState.needTransform=!1,us.prototype.push.call(this,t,e)},ds.prototype._transform=function(t,e,r){throw new Error("Not implemented")},ds.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)}},ds.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},ti(gs,ds),gs.prototype._transform=function(t,e,r){r(null,t)},ti(ms,k),ms.Readable=Ci,ms.Writable=Qi,ms.Duplex=us,ms.Transform=ds,ms.PassThrough=gs,ms.Stream=ms,ms.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===k.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 ys extends k{constructor({resource:t}){super(),this.resource=t,this.client=t.client,this.stream=new a.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 bs extends ys{enqueue(t){this.controller.enqueue(t),this.emit("page",t)}}class ws extends k{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 bs({resource:this.resource}),this.transform=new ds({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,n){try{await r.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}),n()}catch(t){n(t)}}resume(){this.input.resume()}}class _s extends k{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 Qi({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 r.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 vs(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 ks(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 Ss(t){let e=0;for(const r of Object.keys(t))e+=ks(r);return e}function Os(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 xs(t){const e={};for(const[r,n]of Object.entries(t)){const t=ks(Os(n));e[r]=t}return e}function Es(t){const e=xs(t);return Object.values(e).reduce((t,e)=>t+e,0)+Ss(t)}const Rs=2048;var As=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:Rs,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=Es(r);if(n>Rs)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=Es(n);if(i>Rs)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=Es(n);if(i>Rs)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=Es(r);return n>Rs&&t.emit("exceedsLimit",{operation:"insert",totalSize:n,limit:Rs,excess:n-Rs,data:e}),{mappedData:r,body:""}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){const i=Es(n);return i>Rs&&t.emit("exceedsLimit",{operation:"update",id:e,totalSize:i,limit:Rs,excess:i-Rs,data:r}),{mappedData:n,body:""}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){const i=Es(n);return i>Rs&&t.emit("exceedsLimit",{operation:"upsert",id:e,totalSize:i,limit:Rs,excess:i-Rs,data:r}),{mappedData:n,body:""}}});const js=ks("...");function Ds({resource:t,data:e,mappedData:r}){const n=xs(r),i=Object.entries(n).sort(([,t],[,e])=>t-e),s={};let o=0;for(const[t,e]of i){const n=Rs-o;if(!(e<=n)){if(n>js){const e=n-js,i=Os(r[t]);let a="",c=0;for(let t=0;t<i.length;t++){const r=i[t],n=ks(r);if(!(c+n<=e))break;a+=r,c+=n}s[t]=a+"...",o=Rs;break}break}s[t]=r[t],o+=e}return{mappedData:s,body:""}}var Ps=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 Ds({resource:t,data:e,mappedData:r})},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){return Ds({resource:t,data:r,mappedData:n})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){return Ds({resource:t,data:r,mappedData:n})}});const Ns="$overflow",Ts="true",Cs=ks(Ns)+ks(Ts);function Ms({resource:t,data:e,mappedData:r}){if(Es(r)<=Rs)return{mappedData:r,body:""};const n=Rs-Cs,i=xs(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]=Ts;return{mappedData:o,body:Object.keys(a).length>0?JSON.stringify(a):""}}const Ls={"user-managed":Is,"enforce-limits":As,"data-truncate":Ps,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){if(e[Ns]===Ts)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 Ms({resource:t,data:e,mappedData:r})},handleUpdate:async function({resource:t,id:e,data:r,mappedData:n}){return Ms({resource:t,data:r,mappedData:n})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:n}){return Ms({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 $s(t){const e=Ls[t];if(!e)throw new Error(`Unknown behavior: ${t}. Available behaviors: ${Object.keys(Ls).join(", ")}`);return e}const Us=Object.keys(Ls),zs="user-managed";function Fs(e){return t.customAlphabet(t.urlAlphabet,e)}class Bs extends k{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=zs,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?Fs(t):"number"==typeof e&&e>0?Fs(e):b}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 r={original:e.cloneDeep(t),isValid:!1,errors:[]},n=await this.schema.validate(t,{mutateOriginal:!0});return!0===n?r.isValid=!0:r.errors=n,r.data=t,r}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 p(`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?p(`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,...r}){this.options.timestamps&&(r.createdAt=(new Date).toISOString(),r.updatedAt=(new Date).toISOString());const n={id:t,...r},i=await this.executeHooks("preInsert",n),{errors:s,isValid:o,data:a}=await this.validate(i);if(!o)throw new T({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=$s(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=e.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=$s(this.behavior);let c="";if(r.ContentLength>0)try{const t=await this.client.getObject(e);c=await vs(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=$s(this.behavior);let a="";if(r.ContentLength>0)try{const t=await this.client.getObject(e);a=await vs(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 T({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=$s(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 r.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 n=e.chunk(t.map(t=>this.getResourceKey(t)),1e3),{results:i}=await r.PromisePool.for(n).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:n,errors:i}=await r.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 n.filter(t=>null!==t)}async processPartitionResults(t,e,n,i){const s=Object.entries(n.fields).sort(([t],[e])=>t.localeCompare(e)),{results:o,errors:a}=await r.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:n}=await r.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:n}=await r.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 ws({resource:this}).build()}writable(){return new _s({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=Sr(t);return`sha256:${i.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=p(`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=p(`resource=${this.name}`,"historical",`id=${t}`),n={...e,_v:e._v||this.version,_historicalTimestamp:(new Date).toISOString()},i=await this.schema.mapper(n),s=$s(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 qs extends k{constructor(t){super(),this.version="1",this.s3dbVersion=(()=>{try{return"6.0.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 z({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 vs(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 Bs({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"},s=Sr(n);return`sha256:${i.createHash("sha256").update(s).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(!e.isEmpty(this.pluginList)){const r=this.pluginList.map(t=>e.isFunction(t)?new t(this):t),n=r.map(async e=>{e.beforeSetup&&await e.beforeSetup(),await e.setup(t),e.afterSetup&&await e.afterSetup()});await Promise.all(n);const i=r.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 Bs({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 Bs({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 Vs extends qs{}class Hs extends k{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 Ks extends Hs{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 Zs={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 Ws(){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 Js(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 Gs=Uint8Array,Ys=Uint16Array,Qs=Int32Array;function Xs(t){for(var e=t.length;--e>=0;)t[e]=0}var to=256,eo=286,ro=30,no=15,io=[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],so=[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],oo=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ao=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],co=new Array(576);Xs(co);var uo=new Array(60);Xs(uo);var lo=new Array(512);Xs(lo);var ho=new Array(256);Xs(ho);var fo=new Array(29);Xs(fo);var po,go,mo,yo=new Array(ro);function bo(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 wo(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function _o(t){return t<256?lo[t]:lo[256+(t>>>7)]}function vo(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function ko(t,e,r){t.bi_valid>16-r?(t.bi_buf|=e<<t.bi_valid&65535,vo(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 So(t,e,r){ko(t,r[2*e],r[2*e+1])}function Oo(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function xo(t,e,r){var n,i,s=new Array(16),o=0;for(n=1;n<=no;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]=Oo(s[a]++,a))}}function Eo(t){var e;for(e=0;e<eo;e++)t.dyn_ltree[2*e]=0;for(e=0;e<ro;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 Ro(t){t.bi_valid>8?vo(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 Ao(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&&Ao(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!Ao(e,n,t.heap[i],t.depth));)t.heap[r]=t.heap[i],r=i,i<<=1;t.heap[r]=n}function jo(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?So(t,i,e):(So(t,(s=ho[i])+to+1,e),0!==(o=io[s])&&ko(t,i-=fo[s],o),So(t,s=_o(--n),r),0!==(o=so[s])&&ko(t,n-=yo[s],o))}while(a<t.last_lit);So(t,256,e)}function Do(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<=no;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),xo(s,u,t.bl_count)}function Po(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{So(t,i,t.bl_tree)}while(0!==--a);else 0!==i?(i!==s&&(So(t,i,t.bl_tree),a--),So(t,16,t.bl_tree),ko(t,a-3,2)):a<=10?(So(t,17,t.bl_tree),ko(t,a-3,3)):(So(t,18,t.bl_tree),ko(t,a-11,7));a=0,s=i,0===o?(c=138,u=3):i===o?(c=6,u=3):(c=7,u=4)}}Xs(yo);var To=!1;function Co(t){To||(!function(){var t,e,r,n,i,s=new Array(16);for(r=0,n=0;n<28;n++)for(fo[n]=r,t=0;t<1<<io[n];t++)ho[r++]=n;for(ho[r-1]=n,i=0,n=0;n<16;n++)for(yo[n]=i,t=0;t<1<<so[n];t++)lo[i++]=n;for(i>>=7;n<ro;n++)for(yo[n]=i<<7,t=0;t<1<<so[n]-7;t++)lo[256+i++]=n;for(e=0;e<=no;e++)s[e]=0;for(t=0;t<=143;)co[2*t+1]=8,t++,s[8]++;for(;t<=255;)co[2*t+1]=9,t++,s[9]++;for(;t<=279;)co[2*t+1]=7,t++,s[7]++;for(;t<=287;)co[2*t+1]=8,t++,s[8]++;for(xo(co,287,s),t=0;t<ro;t++)uo[2*t+1]=5,uo[2*t]=Oo(t,5);po=new bo(co,io,257,eo,no),go=new bo(uo,so,0,ro,no),mo=new bo(new Array(0),oo,0,19,7)}(),To=!0),t.l_desc=new wo(t.dyn_ltree,po),t.d_desc=new wo(t.dyn_dtree,go),t.bl_desc=new wo(t.bl_tree,mo),t.bi_buf=0,t.bi_valid=0,Eo(t)}function Mo(t,e,r,n){ko(t,0+(n?1:0),3),function(t,e,r){Ro(t),vo(t,r),vo(t,~r),Js(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}(t,e,r)}function Lo(t){ko(t,2,3),So(t,256,co),function(t){16===t.bi_valid?(vo(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 $o(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<to;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),Do(t,t.l_desc),Do(t,t.d_desc),o=function(t){var e;for(Po(t,t.dyn_ltree,t.l_desc.max_code),Po(t,t.dyn_dtree,t.d_desc.max_code),Do(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*ao[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?Mo(t,e,r,n):4===t.strategy||s===i?(ko(t,2+(n?1:0),3),jo(t,co,uo)):(ko(t,4+(n?1:0),3),function(t,e,r,n){var i;for(ko(t,e-257,5),ko(t,r-1,5),ko(t,n-4,4),i=0;i<n;i++)ko(t,t.bl_tree[2*ao[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),jo(t,t.dyn_ltree,t.dyn_dtree)),Eo(t),n&&Ro(t)}function Uo(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*(ho[r]+to+1)]++,t.dyn_dtree[2*_o(e)]++),t.last_lit===t.lit_bufsize-1}function zo(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 Fo=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 Bo(t,e,r,n){var i=Fo,s=n+r;t^=-1;for(var o=n;o<s;o++)t=t>>>8^i[255&(t^e[o])];return-1^t}var qo,Vo=-2,Ho=258,Ko=262,Zo=103,Wo=113,Jo=666;function Go(t,e){return t.msg=Zs[e],e}function Yo(t){return(t<<1)-(t>4?9:0)}function Qo(t){for(var e=t.length;--e>=0;)t[e]=0}function Xo(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(Js(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 ta(t,e){$o(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Xo(t.strm)}function ea(t,e){t.pending_buf[t.pending++]=e}function ra(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function na(t,e,r,n){var i=t.avail_in;return i>n&&(i=n),0===i?0:(t.avail_in-=i,Js(e,t.input,t.next_in,i,r),1===t.state.wrap?t.adler=zo(t.adler,e,i,r):2===t.state.wrap&&(t.adler=Bo(t.adler,e,i,r)),t.next_in+=i,t.total_in+=i,i)}function ia(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-Ko?t.strstart-(t.w_size-Ko):0,u=t.window,l=t.w_mask,h=t.prev,f=t.strstart+Ho,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=Ho-(f-s),s=f-Ho,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 sa(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-Ko)){Js(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=na(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<Ko&&0!==t.strm.avail_in)}function oa(t,e){for(var r,n;;){if(t.lookahead<Ko){if(sa(t),t.lookahead<Ko&&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-Ko&&(t.match_length=ia(t,r)),t.match_length>=3)if(n=Uo(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=Uo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(ta(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,4===e?(ta(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ta(t,!1),0===t.strm.avail_out)?1:2}function aa(t,e){for(var r,n,i;;){if(t.lookahead<Ko){if(sa(t),t.lookahead<Ko&&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-Ko&&(t.match_length=ia(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=Uo(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&&(ta(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if((n=Uo(t,0,t.window[t.strstart-1]))&&ta(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=Uo(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,4===e?(ta(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ta(t,!1),0===t.strm.avail_out)?1:2}function ca(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 ua(){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 Ys(1146),this.dyn_dtree=new Ys(122),this.bl_tree=new Ys(78),Qo(this.dyn_ltree),Qo(this.dyn_dtree),Qo(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Ys(16),this.heap=new Ys(573),Qo(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Ys(573),Qo(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 la(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:Wo,t.adler=2===e.wrap?0:1,e.last_flush=0,Co(e),0):Go(t,Vo)}(t);return 0===r&&((e=t.state).window_size=2*e.w_size,Qo(e.head),e.max_lazy_match=qo[e.level].max_lazy,e.good_match=qo[e.level].good_length,e.nice_match=qo[e.level].nice_length,e.max_chain_length=qo[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 ha(t,e){var r,n,i,s;if(!t||!t.state||e>5||e<0)return t?Go(t,Vo):Vo;if(n=t.state,!t.output||!t.input&&0!==t.avail_in||n.status===Jo&&4!==e)return Go(t,0===t.avail_out?-5:Vo);if(n.strm=t,r=n.last_flush,n.last_flush=e,42===n.status)if(2===n.wrap)t.adler=0,ea(n,31),ea(n,139),ea(n,8),n.gzhead?(ea(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)),ea(n,255&n.gzhead.time),ea(n,n.gzhead.time>>8&255),ea(n,n.gzhead.time>>16&255),ea(n,n.gzhead.time>>24&255),ea(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),ea(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(ea(n,255&n.gzhead.extra.length),ea(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=Bo(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(ea(n,0),ea(n,0),ea(n,0),ea(n,0),ea(n,0),ea(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),ea(n,3),n.status=Wo);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=Wo,ra(n,o),0!==n.strstart&&(ra(n,t.adler>>>16),ra(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=Bo(t.adler,n.pending_buf,n.pending-i,i)),Xo(t),i=n.pending,n.pending!==n.pending_buf_size));)ea(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(t.adler=Bo(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=Bo(t.adler,n.pending_buf,n.pending-i,i)),Xo(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,ea(n,s)}while(0!==s);n.gzhead.hcrc&&n.pending>i&&(t.adler=Bo(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=Bo(t.adler,n.pending_buf,n.pending-i,i)),Xo(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,ea(n,s)}while(0!==s);n.gzhead.hcrc&&n.pending>i&&(t.adler=Bo(t.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.status=Zo)}else n.status=Zo;if(n.status===Zo&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Xo(t),n.pending+2<=n.pending_buf_size&&(ea(n,255&t.adler),ea(n,t.adler>>8&255),t.adler=0,n.status=Wo)):n.status=Wo),0!==n.pending){if(Xo(t),0===t.avail_out)return n.last_flush=-1,0}else if(0===t.avail_in&&Yo(e)<=Yo(r)&&4!==e)return Go(t,-5);if(n.status===Jo&&0!==t.avail_in)return Go(t,-5);if(0!==t.avail_in||0!==n.lookahead||0!==e&&n.status!==Jo){var a=2===n.strategy?function(t,e){for(var r;;){if(0===t.lookahead&&(sa(t),0===t.lookahead)){if(0===e)return 1;break}if(t.match_length=0,r=Uo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(ta(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(ta(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ta(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<=Ho){if(sa(t),t.lookahead<=Ho&&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+Ho;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=Ho-(s-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(r=Uo(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=Uo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(ta(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(ta(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ta(t,!1),0===t.strm.avail_out)?1:2}(n,e):qo[n.level].func(n,e);if(3!==a&&4!==a||(n.status=Jo),1===a||3===a)return 0===t.avail_out&&(n.last_flush=-1),0;if(2===a&&(1===e?Lo(n):5!==e&&(Mo(n,0,0,!1),3===e&&(Qo(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),Xo(t),0===t.avail_out))return n.last_flush=-1,0}return 4!==e?0:n.wrap<=0?1:(2===n.wrap?(ea(n,255&t.adler),ea(n,t.adler>>8&255),ea(n,t.adler>>16&255),ea(n,t.adler>>24&255),ea(n,255&t.total_in),ea(n,t.total_in>>8&255),ea(n,t.total_in>>16&255),ea(n,t.total_in>>24&255)):(ra(n,t.adler>>>16),ra(n,65535&t.adler)),Xo(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?0:1)}qo=[new ca(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(sa(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,ta(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-Ko&&(ta(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(ta(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(ta(t,!1),t.strm.avail_out),1)}),new ca(4,4,8,4,oa),new ca(4,5,16,8,oa),new ca(4,6,32,32,oa),new ca(4,4,16,16,aa),new ca(8,16,32,32,aa),new ca(8,16,128,128,aa),new ca(8,32,128,256,aa),new ca(32,128,258,1024,aa),new ca(32,258,258,4096,aa)];function fa(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,x,E;r=t.state,n=t.next_in,x=t.input,i=n+(t.avail_in-5),s=t.next_out,E=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+=x[n++]<<p,p+=8,d+=x[n++]<<p,p+=8),w=g[d&y];e:for(;;){if(d>>>=_=w>>>24,p-=_,0===(_=w>>>16&255))E[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+=x[n++]<<p,p+=8),v+=d&(1<<_)-1,d>>>=_,p-=_),p<15&&(d+=x[n++]<<p,p+=8,d+=x[n++]<<p,p+=8),w=m[d&b];;){if(d>>>=_=w>>>24,p-=_,16&(_=w>>>16&255)){if(k=65535&w,p<(_&=15)&&(d+=x[n++]<<p,(p+=8)<_&&(d+=x[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{E[s++]=f[S++]}while(--_);S=s-k,O=E}}else if(h<_){if(S+=u+h-_,(_-=h)<v){v-=_;do{E[s++]=f[S++]}while(--_);if(S=0,h<v){v-=_=h;do{E[s++]=f[S++]}while(--_);S=s-k,O=E}}}else if(S+=h-_,_<v){v-=_;do{E[s++]=f[S++]}while(--_);S=s-k,O=E}for(;v>2;)E[s++]=O[S++],E[s++]=O[S++],E[s++]=O[S++],v-=3;v&&(E[s++]=O[S++],v>1&&(E[s++]=O[S++]))}else{S=s-k;do{E[s++]=E[S++],E[s++]=E[S++],E[s++]=E[S++],v-=3}while(v>2);v&&(E[s++]=E[S++],v>1&&(E[s++]=E[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 da=15,pa=[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],ga=[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],ma=[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],ya=[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 ba(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,x=0,E=0,R=0,A=null,I=0,j=new Ys(16),D=new Ys(16),P=null,N=0;for(b=0;b<=da;b++)j[b]=0;for(w=0;w<n;w++)j[e[r+w]]++;for(k=y,v=da;v>=1&&0===j[v];v--);if(k>v&&(k=v),0===v)return i[s++]=20971520,i[s++]=20971520,a.bits=1,0;for(_=1;_<v&&0===j[_];_++);for(k<_&&(k=_),x=1,b=1;b<=da;b++)if(x<<=1,(x-=j[b])<0)return-1;if(x>0&&(0===t||1!==v))return-1;for(D[1]=0,b=1;b<da;b++)D[b+1]=D[b]+j[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=pa,I-=257,P=ga,N-=257,d=256):(A=ma,P=ya,d=-1),R=0,w=0,b=_,f=s,S=k,O=0,l=-1,h=(E=1<<k)-1,1===t&&E>852||2===t&&E>592)return 1;for(;;){p=b-O,o[w]<d?(g=0,m=o[w]):o[w]>d?(g=P[N+o[w]],m=A[I+o[w]]):(g=96,m=0),c=1<<b-O,_=u=1<<S;do{i[f+(R>>O)+(u-=c)]=p<<24|g<<16|m}while(0!==u);for(c=1<<b-1;R&c;)c>>=1;if(0!==c?(R&=c-1,R+=c):R=0,w++,0===--j[b]){if(b===v)break;b=e[r+o[w]]}if(b>k&&(R&h)!==l){for(0===O&&(O=k),f+=_,x=1<<(S=b-O);S+O<v&&!((x-=j[S+O])<=0);)S++,x<<=1;if(E+=1<<S,1===t&&E>852||2===t&&E>592)return 1;i[l=R&h]=k<<24|S<<16|f-s}}return 0!==R&&(i[f+R]=b-O<<24|64<<16),a.bits=k,0}var wa=-2,_a=12,va=30;function ka(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function Sa(){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 Ys(320),this.work=new Ys(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Oa(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 Qs(852),e.distcode=e.distdyn=new Qs(592),e.sane=1,e.back=-1,0):wa}(t)):wa}function xa(t,e){var r,n;return t?(n=new Sa,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)?wa:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,Oa(t))):wa}(t,e),0!==r&&(t.state=null),r):wa}var Ea,Ra,Aa=!0;function Ia(t){if(Aa){var e;for(Ea=new Qs(512),Ra=new Qs(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(ba(1,t.lens,0,288,Ea,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ba(2,t.lens,0,32,Ra,0,t.work,{bits:5}),Aa=!1}t.lencode=Ea,t.lenbits=9,t.distcode=Ra,t.distbits=5}function ja(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,x,E=0,R=new Gs(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 wa;(r=t.state).mode===_a&&(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,R[0]=255&u,R[1]=u>>>8&255,r.check=Bo(r.check,R,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=va;break}if(8!=(15&u)){t.msg="unknown compression method",r.mode=va;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=va;break}r.dmax=1<<k,t.adler=r.check=1,r.mode=512&u?10:_a,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=va;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=va;break}r.head&&(r.head.text=u>>8&1),512&r.flags&&(R[0]=255&u,R[1]=u>>>8&255,r.check=Bo(r.check,R,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&&(R[0]=255&u,R[1]=u>>>8&255,R[2]=u>>>16&255,R[3]=u>>>24&255,r.check=Bo(r.check,R,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&&(R[0]=255&u,R[1]=u>>>8&255,r.check=Bo(r.check,R,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&&(R[0]=255&u,R[1]=u>>>8&255,r.check=Bo(r.check,R,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)),Js(r.head.extra,n,s,d,k)),512&r.flags&&(r.check=Bo(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=Bo(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=Bo(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=va;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=_a;break;case 10:for(;l<32;){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}t.adler=r.check=ka(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=_a;case _a: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=va}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=va;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;Js(i,n,s,d,o),a-=d,s+=d,c-=d,o+=d,r.length-=d;break}r.mode=_a;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=va;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=ba(0,r.lens,0,19,r.lencode,0,r.work,O),r.lenbits=O.bits,S){t.msg="invalid code lengths set",r.mode=va;break}r.have=0,r.mode=19;case 19:for(;r.have<r.nlen+r.ndist;){for(;y=(E=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,b=65535&E,!((m=E>>>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(x=m+2;l<x;){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=va;break}k=r.lens[r.have-1],d=3+(3&u),u>>>=2,l-=2}else if(17===b){for(x=m+3;l<x;){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(x=m+7;l<x;){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=va;break}for(;d--;)r.lens[r.have++]=k}}if(r.mode===va)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=va;break}if(r.lenbits=9,O={bits:r.lenbits},S=ba(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=va;break}if(r.distbits=6,r.distcode=r.distdyn,O={bits:r.distbits},S=ba(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=va;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,fa(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===_a&&(r.back=-1);break}for(r.back=0;y=(E=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,b=65535&E,!((m=E>>>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=(E=r.lencode[v+((u&(1<<w+_)-1)>>w)])>>>16&255,b=65535&E,!(w+(m=E>>>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=_a;break}if(64&y){t.msg="invalid literal/length code",r.mode=va;break}r.extra=15&y,r.mode=22;case 22:if(r.extra){for(x=r.extra;l<x;){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=(E=r.distcode[u&(1<<r.distbits)-1])>>>16&255,b=65535&E,!((m=E>>>24)<=l);){if(0===a)break t;a--,u+=n[s++]<<l,l+=8}if(!(240&y)){for(w=m,_=y,v=b;y=(E=r.distcode[v+((u&(1<<w+_)-1)>>w)])>>>16&255,b=65535&E,!(w+(m=E>>>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=va;break}r.offset=b,r.extra=15&y,r.mode=24;case 24:if(r.extra){for(x=r.extra;l<x;){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=va;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=va;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?Bo(r.check,i,f,o-f):zo(r.check,i,f,o-f)),f=c,(r.flags?u:ka(u))!==r.check){t.msg="incorrect data check",r.mode=va;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=va;break}u=0,l=0}r.mode=29;case 29:S=1;break t;case va:S=-3;break t;case 31:return-4;default:return wa}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<va&&(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 Gs(s.wsize)),n>=s.wsize?(Js(s.window,e,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):((i=s.wsize-s.wnext)>n&&(i=n),Js(s.window,e,r-n,i,s.wnext),(n-=i)?(Js(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?Bo(r.check,i,f,t.next_out-f):zo(r.check,i,f,t.next_out-f)),t.data_type=r.bits+(r.last?64:0)+(r.mode===_a?128:0)+(20===r.mode||15===r.mode?256:0),(0===h&&0===f||4===e)&&0===S&&(S=-5),S}var Da;function Pa(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]}Pa.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 Ws,this.mode){case 1:case 3:case 5:s=function(t,e,r,n,i,s){if(!t)return Vo;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 Go(t,Vo);8===n&&(n=9);var a=new ua;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 Gs(2*a.w_size),a.head=new Ys(a.hash_size),a.prev=new Ys(a.w_size),a.lit_bufsize=1<<i+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Gs(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,la(t)}(this.strm,this.level,8,this.windowBits,this.memLevel,this.strategy);break;case 2:case 4:case 6:case 7:s=xa(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)},Pa.prototype.params=function(){throw new Error("deflateParams Not supported")},Pa.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")},Pa.prototype.write=function(t,e,r,n,i,s,o){this._writeCheck(),this.write_in_progress=!0;var a=this;return ei.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},Pa.prototype.writeSync=function(t,e,r,n,i,s,o){return this._writeCheck(),this._write(t,e,r,n,i,s,o)},Pa.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 Hr(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=ha(c,t);break;case 7:case 2:case 4:case 6:a=ja(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]},Pa.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},Pa.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!==Zo&&e!==Wo&&e!==Jo?Go(t,Vo):(t.state=null,e===Wo&&Go(t,-3)))}(this.strm):function(t){if(!t||!t.state)return wa;var e=t.state;e.window&&(e.window=null),t.state=null}(this.strm),this.mode=0)},Pa.prototype.reset=function(){switch(this.mode){case 1:case 5:Da=la(this.strm);break;case 2:case 6:Da=Oa(this.strm)}0!==Da&&this._error(Da)},Pa.prototype._error=function(t){this.onerror(Zs[t]+": "+this.strm.msg,t),this.write_in_progress=!1,this.pending_close&&this.close()};var Ta=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:Pa});var Ca={};Object.keys(Ta).forEach(function(t){Ca[t]=Ta[t]}),Ca.Z_MIN_WINDOWBITS=8,Ca.Z_MAX_WINDOWBITS=15,Ca.Z_DEFAULT_WINDOWBITS=15,Ca.Z_MIN_CHUNK=64,Ca.Z_MAX_CHUNK=1/0,Ca.Z_DEFAULT_CHUNK=16384,Ca.Z_MIN_MEMLEVEL=1,Ca.Z_MAX_MEMLEVEL=9,Ca.Z_DEFAULT_MEMLEVEL=8,Ca.Z_MIN_LEVEL=-1,Ca.Z_MAX_LEVEL=9,Ca.Z_DEFAULT_LEVEL=Ca.Z_DEFAULT_COMPRESSION;var Ma={Z_OK:Ca.Z_OK,Z_STREAM_END:Ca.Z_STREAM_END,Z_NEED_DICT:Ca.Z_NEED_DICT,Z_ERRNO:Ca.Z_ERRNO,Z_STREAM_ERROR:Ca.Z_STREAM_ERROR,Z_DATA_ERROR:Ca.Z_DATA_ERROR,Z_MEM_ERROR:Ca.Z_MEM_ERROR,Z_BUF_ERROR:Ca.Z_BUF_ERROR,Z_VERSION_ERROR:Ca.Z_VERSION_ERROR};function La(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new qa(e),t,r)}function $a(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new Va(e),t,r)}function Ua(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=Hr.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 za(t,e){if("string"==typeof e&&(e=new Hr(e)),!Hr.isBuffer(e))throw new TypeError("Not a string or buffer");var r=Ca.Z_FINISH;return t._processChunk(e,r)}function Fa(t){if(!(this instanceof Fa))return new Fa(t);Wa.call(this,t,Ca.DEFLATE)}function Ba(t){if(!(this instanceof Ba))return new Ba(t);Wa.call(this,t,Ca.INFLATE)}function qa(t){if(!(this instanceof qa))return new qa(t);Wa.call(this,t,Ca.GZIP)}function Va(t){if(!(this instanceof Va))return new Va(t);Wa.call(this,t,Ca.GUNZIP)}function Ha(t){if(!(this instanceof Ha))return new Ha(t);Wa.call(this,t,Ca.DEFLATERAW)}function Ka(t){if(!(this instanceof Ka))return new Ka(t);Wa.call(this,t,Ca.INFLATERAW)}function Za(t){if(!(this instanceof Za))return new Za(t);Wa.call(this,t,Ca.UNZIP)}function Wa(t,e){if(this._opts=t=t||{},this._chunkSize=t.chunkSize||Ca.Z_DEFAULT_CHUNK,ds.call(this,t),t.flush&&t.flush!==Ca.Z_NO_FLUSH&&t.flush!==Ca.Z_PARTIAL_FLUSH&&t.flush!==Ca.Z_SYNC_FLUSH&&t.flush!==Ca.Z_FULL_FLUSH&&t.flush!==Ca.Z_FINISH&&t.flush!==Ca.Z_BLOCK)throw new Error("Invalid flush flag: "+t.flush);if(this._flushFlag=t.flush||Ca.Z_NO_FLUSH,t.chunkSize&&(t.chunkSize<Ca.Z_MIN_CHUNK||t.chunkSize>Ca.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+t.chunkSize);if(t.windowBits&&(t.windowBits<Ca.Z_MIN_WINDOWBITS||t.windowBits>Ca.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+t.windowBits);if(t.level&&(t.level<Ca.Z_MIN_LEVEL||t.level>Ca.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+t.level);if(t.memLevel&&(t.memLevel<Ca.Z_MIN_MEMLEVEL||t.memLevel>Ca.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+t.memLevel);if(t.strategy&&t.strategy!=Ca.Z_FILTERED&&t.strategy!=Ca.Z_HUFFMAN_ONLY&&t.strategy!=Ca.Z_RLE&&t.strategy!=Ca.Z_FIXED&&t.strategy!=Ca.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+t.strategy);if(t.dictionary&&!Hr.isBuffer(t.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new Ca.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=Ma[e],r.emit("error",n)};var n=Ca.Z_DEFAULT_COMPRESSION;"number"==typeof t.level&&(n=t.level);var i=Ca.Z_DEFAULT_STRATEGY;"number"==typeof t.strategy&&(i=t.strategy),this._binding.init(t.windowBits||Ca.Z_DEFAULT_WINDOWBITS,n,t.memLevel||Ca.Z_DEFAULT_MEMLEVEL,i,t.dictionary),this._buffer=new Hr(this._chunkSize),this._offset=0,this._closed=!1,this._level=n,this._strategy=i,this.once("end",this.close)}Object.keys(Ma).forEach(function(t){Ma[Ma[t]]=t}),ti(Wa,ds),Wa.prototype.params=function(t,e,r){if(t<Ca.Z_MIN_LEVEL||t>Ca.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(e!=Ca.Z_FILTERED&&e!=Ca.Z_HUFFMAN_ONLY&&e!=Ca.Z_RLE&&e!=Ca.Z_FIXED&&e!=Ca.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+e);if(this._level!==t||this._strategy!==e){var n=this;this.flush(Ca.Z_SYNC_FLUSH,function(){n._binding.params(t,e),n._hadError||(n._level=t,n._strategy=e,r&&r())})}else ei.nextTick(r)},Wa.prototype.reset=function(){return this._binding.reset()},Wa.prototype._flush=function(t){this._transform(new Hr(0),"",t)},Wa.prototype.flush=function(t,e){var r=this._writableState;if(("function"==typeof t||void 0===t&&!e)&&(e=t,t=Ca.Z_FULL_FLUSH),r.ended)e&&ei.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 Hr(0),"",e)},Wa.prototype.close=function(t){if(t&&ei.nextTick(t),!this._closed){this._closed=!0,this._binding.close();var e=this;ei.nextTick(function(){e.emit("close")})}},Wa.prototype._transform=function(t,e,r){var n,i=this._writableState,s=(i.ending||i.ended)&&(!t||i.length===t.length);if(null===!t&&!Hr.isBuffer(t))return r(new Error("invalid input"));s?n=Ca.Z_FINISH:(n=this._flushFlag,t.length>=i.length&&(this._flushFlag=this._opts.flush||Ca.Z_NO_FLUSH)),this._processChunk(t,n,r)},Wa.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=Hr.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 Hr(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},ti(Fa,Wa),ti(Ba,Wa),ti(qa,Wa),ti(Va,Wa),ti(Ha,Wa),ti(Ka,Wa),ti(Za,Wa);var Ja={codes:Ma,createDeflate:function(t){return new Fa(t)},createInflate:function(t){return new Ba(t)},createDeflateRaw:function(t){return new Ha(t)},createInflateRaw:function(t){return new Ka(t)},createGzip:function(t){return new qa(t)},createGunzip:function(t){return new Va(t)},createUnzip:function(t){return new Za(t)},deflate:function(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new Fa(e),t,r)},deflateSync:function(t,e){return za(new Fa(e),t)},gzip:La,gzipSync:function(t,e){return za(new qa(e),t)},deflateRaw:function(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new Ha(e),t,r)},deflateRawSync:function(t,e){return za(new Ha(e),t)},unzip:function(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new Za(e),t,r)},unzipSync:function(t,e){return za(new Za(e),t)},inflate:function(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new Ba(e),t,r)},inflateSync:function(t,e){return za(new Ba(e),t)},gunzip:$a,gunzipSync:function(t,e){return za(new Va(e),t)},inflateRaw:function(t,e,r){return"function"==typeof e&&(r=e,e={}),Ua(new Ka(e),t,r)},inflateRawSync:function(t,e){return za(new Ka(e),t)},Deflate:Fa,Inflate:Ba,Gzip:qa,Gunzip:Va,DeflateRaw:Ha,InflateRaw:Ka,Unzip:Za,Zlib:Wa};class Ga extends Hs{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=Ja.gzipSync(r).toString("base64"),this.client.putObject({key:p(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(p(this.keyPrefix,t));let r=await vs(e);return r=Buffer.from(r,"base64"),r=Ja.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(p(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 Ya extends k{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 Qa={setup(t){},start(){},stop(){}};const Xa={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 tc extends k{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 ec={s3db:class extends tc{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 Vs(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 tc{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 tc{constructor(t={},e=[]){super(t),this.resources=e,this.projectId=t.projectId,this.datasetId=t.datasetId,this.tableId=t.tableId,this.tableMap=t.tableMap||{},this.bigqueryClient=null,this.credentials=t.credentials,this.location=t.location||"US",this.logOperations=!1!==t.logOperations}validateConfig(){const t=[];return this.projectId||t.push("projectId is required"),this.datasetId||t.push("datasetId is required"),this.tableId||t.push("tableId is required"),{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,tableId:this.tableId})}catch(t){throw this.emit("initialization_error",{replicator:this.name,error:t.message}),t}}getTableForResource(t){return this.tableMap[t]||this.tableId}async replicate(t,e,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};try{const i=this.bigqueryClient.dataset(this.datasetId),s=this.getTableForResource(t),o=i.table(s);let a;if("insert"===e){const t={...r};a=await o.insert([t])}else if("update"===e){const t=Object.keys(r).filter(t=>"id"!==t),e=t.map(t=>`\n ${t}=@${t}\n `).join(", "),i={id:n};t.forEach(t=>{i[t]=r[t]});const o=`UPDATE \`${this.projectId}.${this.datasetId}.${s}\`\n SET ${e}\n WHERE id=@id`,[c]=await this.bigqueryClient.createQueryJob({query:o,params:i});await c.getQueryResults(),a=[c]}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const t=`DELETE FROM \`${this.projectId}.${this.datasetId}.${s}\`\n WHERE id=@id`,[e]=await this.bigqueryClient.createQueryJob({query:t,params:{id:n}});await e.getQueryResults(),a=[e]}}if(this.logOperations){const s=i.table(this.tableId);await s.insert([{resource_name:t,operation:e,record_id:n,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replication"}])}return this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:n,jobId:a[0]?.id,success:!0}),{success:!0,jobId:a[0]?.id}}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(){}shouldReplicateResource(t){return!this.resources||0===this.resources.length||this.resources.includes(t)}},postgres:class extends tc{constructor(t={},e=[]){super(t),this.resources=e,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.tableName=t.tableName||"s3db_replication",this.tableMap=t.tableMap||{},this.client=null,this.ssl=t.ssl,this.logOperations=!1!==t.logOperations}validateConfig(){const t=[];return this.connectionString||this.host&&this.database||t.push("Either connectionString or host+database must be provided"),{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.logOperations&&await this.createTableIfNotExists(),this.emit("initialized",{replicator:this.name,database:this.database||"postgres",table:this.tableName})}catch(t){throw this.emit("initialization_error",{replicator:this.name,error:t.message}),t}}async createTableIfNotExists(){const t=`\n CREATE TABLE IF NOT EXISTS ${this.tableName} (\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.tableName}_resource_name ON ${this.tableName}(resource_name);\n CREATE INDEX IF NOT EXISTS idx_${this.tableName}_operation ON ${this.tableName}(operation);\n CREATE INDEX IF NOT EXISTS idx_${this.tableName}_record_id ON ${this.tableName}(record_id);\n CREATE INDEX IF NOT EXISTS idx_${this.tableName}_timestamp ON ${this.tableName}(timestamp);\n `;await this.client.query(t)}getTableForResource(t){return this.tableMap[t]||t}async replicate(t,e,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};try{const i=this.getTableForResource(t);let s;if("insert"===e){const t=Object.keys(r),e=t.map(t=>r[t]),n=t.map(t=>`"${t}"`).join(", "),o=`INSERT INTO ${i} (${n}) VALUES (${t.map((t,e)=>`$${e+1}`).join(", ")}) ON CONFLICT (id) DO NOTHING RETURNING *`;s=await this.client.query(o,e)}else if("update"===e){const t=Object.keys(r).filter(t=>"id"!==t),e=t.map((t,e)=>`"${t}"=$${e+1}`).join(", "),o=t.map(t=>r[t]);o.push(n);const a=`UPDATE ${i} SET ${e} WHERE id=$${t.length+1} RETURNING *`;s=await this.client.query(a,o)}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const t=`DELETE FROM ${i} WHERE id=$1 RETURNING *`;s=await this.client.query(t,[n])}}return this.logOperations&&await this.client.query(`INSERT INTO ${this.tableName} (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"]),this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:n,result:s.rows,success:!0}),{success:!0,rows:s.rows}}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()}shouldReplicateResource(t){return!this.resources||0===this.resources.length||this.resources.includes(t)}}};function rc(t,e={},r=[]){const n=ec[t];if(!n)throw new Error(`Unknown replicator driver: ${t}. Available drivers: ${Object.keys(ec).join(", ")}`);return new n(e,r)}function nc(t,e,r=[]){return rc(t,e,r).validateConfig()}const ic=Ei(La),sc=Ei($a);exports.AVAILABLE_BEHAVIORS=Us,exports.AuditPlugin=class extends Ya{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}},exports.AuthenticationError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},exports.BaseError=A,exports.Cache=Hs,exports.CachePlugin=class extends Ya{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 Ks(this.config.memoryOptions||{}):this.driver=new Ga(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=p(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 p(...s)+".json.gz"}async hashParams(t){const e=Object.keys(t).sort().map(e=>`${e}:${t[e]}`).join("|")||"empty";return await B(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})}}}},exports.Client=z,exports.ConnectionString=U,exports.CostsPlugin=Xa,exports.DEFAULT_BEHAVIOR=zs,exports.Database=qs,exports.DatabaseError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},exports.EncryptionError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},exports.ErrorMap=M,exports.FullTextPlugin=class extends Ya{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()}},exports.InvalidResourceItem=T,exports.MemoryCache=Ks,exports.MetricsPlugin=class extends Ya{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`)}},exports.MissingMetadata=N,exports.NoSuchBucket=j,exports.NoSuchKey=D,exports.NotFound=P,exports.PermissionError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},exports.Plugin=Ya,exports.PluginObject=Qa,exports.ReplicationPlugin=class extends Ya{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 ic(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 sc(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=nc(e,r,n);if(!i.isValid){this.emit("replicator.validation.failed",{driver:e,errors:i.errors});continue}const s=rc(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,r,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:r,recordId:n,data:e.isPlainObject(i)?i:{raw:i},beforeData:s?e.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 r=`log-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return await this.replicationLog.insert({id:r,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,replicatorId:"all",status:"queued",attempts:0,lastAttempt:(new Date).toISOString(),error:"",data:e.isPlainObject(t.data)?t.data:{raw:t.data},timestamp:(new Date).toISOString()}),r}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})}},exports.Resource=Bs,exports.ResourceIdsPageReader=bs,exports.ResourceIdsReader=ys,exports.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})}},exports.ResourceReader=ws,exports.ResourceWriter=_s,exports.S3Cache=Ga,exports.S3DBError=I,exports.S3_DEFAULT_ENDPOINT=$,exports.S3_DEFAULT_REGION=L,exports.S3db=Vs,exports.Schema=Ir,exports.SchemaActions=Ar,exports.UnknownError=C,exports.ValidationError=class extends I{constructor(t,e={}){super(t,e),Object.assign(this,e)}},exports.Validator=Er,exports.ValidatorManager=Rr,exports.behaviors=Ls,exports.calculateAttributeNamesSize=Ss,exports.calculateAttributeSizes=xs,exports.calculateTotalSize=Es,exports.calculateUTF8Bytes=ks,exports.decrypt=V,exports.default=Vs,exports.encrypt=q,exports.getBehavior=$s,exports.getSizeBreakdown=function(t){const e=xs(t),r=Ss(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}}},exports.idGenerator=b,exports.passwordGenerator=w,exports.sha256=B,exports.streamToString=vs,exports.transformValue=Os;
|