",i);var e=this.schema({exportAttrs:!0,noDeref:!0});return typeof e=="object"&&!a.isType(this,"logical")&&(e.type=void 0),R("<%s %j>",i,e)},a.prototype.isValid=function(t,i){var e=(i&&i.noUndeclaredFields)|0,r=i&&i.errorHook,n,o;return r&&(o=[],n=function(s,f){r.call(this,o.slice(),s,f,t)}),this._check(t,e,n,o)},a.prototype.random=h.abstractFunction,a.prototype.schema=function(t){return this._attrs({exportAttrs:!!(t&&t.exportAttrs),noDeref:!!(t&&t.noDeref)})},a.prototype.toBuffer=function(t){Q.pos=0,this._write(Q,t);var i=h.newBuffer(Q.pos);return Q.isValid()?Q.buf.copy(i,0,0,Q.pos):this._write(new T(i),t),i},a.prototype.toJSON=function(){return this.schema({exportAttrs:!0})},a.prototype.toString=function(t){return JSON.stringify(t===void 0?this.schema({noDeref:!0}):this._copy(t,{coerce:3}))},a.prototype.wrap=function(t){var i=this._branchConstructor;return i===null?null:new i(t)},a.prototype._attrs=function(t){t.derefed=t.derefed||{};var i=this.name;if(i!==void 0){if(t.noDeref||t.derefed[i])return i;t.derefed[i]=!0}var e={};this.name!==void 0&&(e.name=i),e.type=this.typeName;var r=this._deref(e,t);return r!==void 0&&(e=r),t.exportAttrs&&(this.aliases&&this.aliases.length&&(e.aliases=this.aliases),this.doc!==void 0&&(e.doc=this.doc)),e},a.prototype._createBranchConstructor=function(){var t=this.branchName;if(t==="null")return null;var i=~t.indexOf(".")?"this['"+t+"']":"this."+t,e="return function Branch$(val) { "+i+" = val; };",r=new Function(e)();return r.type=this,r.prototype.unwrap=new Function("return "+i+";"),r.prototype.unwrapped=r.prototype.unwrap,r},a.prototype._peek=function(t){var i=t.pos,e=this._read(t);return t.pos=i,e},a.prototype._check=h.abstractFunction,a.prototype._copy=h.abstractFunction,a.prototype._deref=h.abstractFunction,a.prototype._match=h.abstractFunction,a.prototype._read=h.abstractFunction,a.prototype._skip=h.abstractFunction,a.prototype._update=h.abstractFunction,a.prototype._write=h.abstractFunction,a.prototype.getAliases=function(){return this.aliases},a.prototype.getFingerprint=a.prototype.fingerprint,a.prototype.getName=function(t){return this.name||!t?this.name:this.branchName},a.prototype.getSchema=a.prototype.schema,a.prototype.getTypeName=function(){return this.typeName};function w(t){a.call(this),this._branchConstructor=this._createBranchConstructor(),t||Object.freeze(this)}_.inherits(w,a),w.prototype._update=function(t,i){i.typeName===this.typeName&&(t._read=this._read)},w.prototype._copy=function(t){return this._check(t,void 0,ue),t},w.prototype._deref=function(){return this.typeName},w.prototype.compare=h.compare;function j(){w.call(this)}_.inherits(j,w),j.prototype._check=function(t,i,e){var r=t===null;return!r&&e&&e(t,this),r},j.prototype._read=function(){return null},j.prototype._skip=function(){},j.prototype._write=function(t,i){i!==null&&ue(i,this)},j.prototype._match=function(){return 0},j.prototype.compare=j.prototype._match,j.prototype.typeName="null",j.prototype.random=j.prototype._read;function z(){w.call(this)}_.inherits(z,w),z.prototype._check=function(t,i,e){var r=typeof t=="boolean";return!r&&e&&e(t,this),r},z.prototype._read=function(t){return t.readBoolean()},z.prototype._skip=function(t){t.skipBoolean()},z.prototype._write=function(t,i){typeof i!="boolean"&&ue(i,this),t.writeBoolean(i)},z.prototype._match=function(t,i){return t.matchBoolean(i)},z.prototype.typeName="boolean",z.prototype.random=function(){return P.nextBoolean()};function te(){w.call(this)}_.inherits(te,w),te.prototype._check=function(t,i,e){var r=t===(t|0);return!r&&e&&e(t,this),r},te.prototype._read=function(t){return t.readInt()},te.prototype._skip=function(t){t.skipInt()},te.prototype._write=function(t,i){i!==(i|0)&&ue(i,this),t.writeInt(i)},te.prototype._match=function(t,i){return t.matchInt(i)},te.prototype.typeName="int",te.prototype.random=function(){return P.nextInt(1e3)|0};function M(){w.call(this)}_.inherits(M,w),M.prototype._check=function(t,i,e){var r=typeof t=="number"&&t%1===0&&$e(t);return!r&&e&&e(t,this),r},M.prototype._read=function(t){var i=t.readLong();if(!$e(i))throw new Error("potential precision loss");return i},M.prototype._skip=function(t){t.skipLong()},M.prototype._write=function(t,i){(typeof i!="number"||i%1||!$e(i))&&ue(i,this),t.writeLong(i)},M.prototype._match=function(t,i){return t.matchLong(i)},M.prototype._update=function(t,i){switch(i.typeName){case"int":t._read=i._read;break;case"abstract:long":case"long":t._read=this._read}},M.prototype.typeName="long",M.prototype.random=function(){return P.nextInt()},M.__with=function(t,i){t=t||{};var e={toBuffer:"_toBuffer",fromBuffer:"_fromBuffer",fromJSON:"_fromJSON",toJSON:"_toJSON",isValid:"_isValid",compare:"compare"},r=new b(i);return Object.keys(e).forEach(function(n){if(t[n]===void 0)throw new Error(R("missing method implementation: %s",n));r[e[n]]=t[n]}),Object.freeze(r)};function G(){w.call(this)}_.inherits(G,w),G.prototype._check=function(t,i,e){var r=typeof t=="number";return!r&&e&&e(t,this),r},G.prototype._read=function(t){return t.readFloat()},G.prototype._skip=function(t){t.skipFloat()},G.prototype._write=function(t,i){typeof i!="number"&&ue(i,this),t.writeFloat(i)},G.prototype._match=function(t,i){return t.matchFloat(i)},G.prototype._update=function(t,i){switch(i.typeName){case"float":case"int":t._read=i._read;break;case"abstract:long":case"long":t._read=function(e){return e.readLong()}}},G.prototype.typeName="float",G.prototype.random=function(){return P.nextFloat(1e3)};function D(){w.call(this)}_.inherits(D,w),D.prototype._check=function(t,i,e){var r=typeof t=="number";return!r&&e&&e(t,this),r},D.prototype._read=function(t){return t.readDouble()},D.prototype._skip=function(t){t.skipDouble()},D.prototype._write=function(t,i){typeof i!="number"&&ue(i,this),t.writeDouble(i)},D.prototype._match=function(t,i){return t.matchDouble(i)},D.prototype._update=function(t,i){switch(i.typeName){case"double":case"float":case"int":t._read=i._read;break;case"abstract:long":case"long":t._read=function(e){return e.readLong()}}},D.prototype.typeName="double",D.prototype.random=function(){return P.nextFloat()};function X(){w.call(this)}_.inherits(X,w),X.prototype._check=function(t,i,e){var r=typeof t=="string";return!r&&e&&e(t,this),r},X.prototype._read=function(t){return t.readString()},X.prototype._skip=function(t){t.skipString()},X.prototype._write=function(t,i){typeof i!="string"&&ue(i,this),t.writeString(i)},X.prototype._match=function(t,i){return t.matchString(i)},X.prototype._update=function(t,i){switch(i.typeName){case"bytes":case"string":t._read=this._read}},X.prototype.typeName="string",X.prototype.random=function(){return P.nextString(P.nextInt(32))};function U(){w.call(this)}_.inherits(U,w),U.prototype._check=function(t,i,e){var r=g.isBuffer(t);return!r&&e&&e(t,this),r},U.prototype._read=function(t){return t.readBytes()},U.prototype._skip=function(t){t.skipBytes()},U.prototype._write=function(t,i){g.isBuffer(i)||ue(i,this),t.writeBytes(i)},U.prototype._match=function(t,i){return t.matchBytes(i)},U.prototype._update=X.prototype._update,U.prototype._copy=function(t,i){var e;switch((i&&i.coerce)|0){case 3:return this._check(t,void 0,ue),t.toString("binary");case 2:if(typeof t!="string")throw new Error(R("cannot coerce to buffer: %j",t));return e=h.bufferFrom(t,"binary"),this._check(e,void 0,ue),e;case 1:if(!je(t))throw new Error(R("cannot coerce to buffer: %j",t));return e=h.bufferFrom(t.data),this._check(e,void 0,ue),e;default:return this._check(t,void 0,ue),h.bufferFrom(t)}},U.prototype.compare=g.compare,U.prototype.typeName="bytes",U.prototype.random=function(){return P.nextBuffer(P.nextInt(32))};function oe(t,i){if(a.call(this),!Array.isArray(t))throw new Error(R("non-array union schema: %j",t));if(!t.length)throw new Error("empty union");this.types=Object.freeze(t.map(function(e){return a.forSchema(e,i)})),this._branchIndices={},this.types.forEach(function(e,r){if(a.isType(e,"union"))throw new Error("unions cannot be directly nested");var n=e.branchName;if(this._branchIndices[n]!==void 0)throw new Error(R("duplicate union branch name: %j",n));this._branchIndices[n]=r},this)}_.inherits(oe,a),oe.prototype._branchConstructor=function(){throw new Error("unions cannot be directly wrapped")},oe.prototype._skip=function(t){this.types[t.readLong()]._skip(t)},oe.prototype._match=function(t,i){var e=t.readLong(),r=i.readLong();return e===r?this.types[e]._match(t,i):efunction(){return l||(0,u[bt(u)[0]])((l={exports:{}}).exports,l),l.exports},Bt=(u,l,h,d)=>{if(l&&typeof l=="object"||typeof l=="function")for(let _ of bt(l))!Pt.call(u,_)&&_!==h&&wt(u,_,{get:()=>l[_],enumerable:!(d=Ct(l,_))||d.enumerable});return u},Lt=(u,l,h)=>(h=u!=null?It($t(u)):{},Bt(l||!u||!u.__esModule?wt(h,"default",{value:u,enumerable:!0}):h,u)),ze=Ie({"node_modules/avsc/lib/utils.js"(u,l){"use strict";var h=Ue,d=xt,_=De,g=h.Buffer,O=new S(4096),T=/^[A-Za-z_][A-Za-z0-9_]*$/,v=_.format;function R(c){return typeof g.alloc=="function"?g.alloc(c):new g(c)}function $(c,p){return typeof g.from=="function"?g.from(c,p):new g(c,p)}function P(c){return c.charAt(0).toUpperCase()+c.slice(1)}function Y(c,p){return c===p?0:c=0)return-2;b=A}return b}function w(c,p){var b={},A,V;for(A=0;Ap?R(c):(this._pos+c>p&&(this._slab=R(p),this._pos=0),this._slab.slice(this._pos,this._pos+=c))};function N(c){var p=1103515245,b=12345,A=Math.pow(2,31),V=Math.floor(c||Math.random()*(A-1));this._max=A,this._nextInt=function(){return V=(p*V+b)%A}}N.prototype.nextBoolean=function(){return!!(this._nextInt()%2)},N.prototype.nextInt=function(c,p){return p===void 0&&(p=c,c=0),p=p===void 0?this._max:p,c+Math.floor(this.nextFloat()*(p-c))},N.prototype.nextFloat=function(c,p){return p===void 0&&(p=c,c=0),p=p===void 0?1:p,c+(p-c)*this._nextInt()/this._max},N.prototype.nextString=function(c,p){c|=0,p=p||"aA";var b="";p.indexOf("a")>-1&&(b+="abcdefghijklmnopqrstuvwxyz"),p.indexOf("A")>-1&&(b+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),p.indexOf("#")>-1&&(b+="0123456789"),p.indexOf("!")>-1&&(b+="~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\");for(var A=[],V=0;V0&&p[b].index>1].index;)c=p[b],p[b]=p[A],p[A]=c,b=A},x.prototype.pop=function(){var c=this._items,p=c.length-1|0,b=c[0];if(!b||b.index>this._index)return null;if(this._index++,!p)return c.pop(),b;c[0]=c.pop();for(var A=p>>1,V=0,Z,K,ce,pe,he,ge,ve;V=pe.index));)c[ce]=pe,c[V]=he,V=ce;return b};function I(c,p){if(this.buf=c,this.pos=p|0,this.pos<0)throw new Error("negative offset")}I.prototype.isValid=function(){return this.pos<=this.buf.length},I.prototype._invalidate=function(){this.pos=this.buf.length+1},I.prototype.readBoolean=function(){return!!this.buf[this.pos++]},I.prototype.skipBoolean=function(){this.pos++},I.prototype.writeBoolean=function(c){this.buf[this.pos++]=!!c},I.prototype.readInt=I.prototype.readLong=function(){var c=0,p=0,b=this.buf,A,V,Z,K;do A=b[this.pos++],V=A&128,c|=(A&127)<>1^-(c&1)},I.prototype.skipInt=I.prototype.skipLong=function(){for(var c=this.buf;c[this.pos++]&128;);},I.prototype.writeInt=I.prototype.writeLong=function(c){var p=this.buf,b,A;if(c>=-1073741824&&c<1073741824){A=c>=0?c<<1:~c<<1|1;do p[this.pos]=A&127,A>>=7;while(A&&(p[this.pos++]|=128))}else{b=c>=0?c*2:-c*2-1;do p[this.pos]=b&127,b/=128;while(b>=1&&(p[this.pos++]|=128))}this.pos++},I.prototype.readFloat=function(){var c=this.buf,p=this.pos;return this.pos+=4,this.pos>c.length?0:this.buf.readFloatLE(p)},I.prototype.skipFloat=function(){this.pos+=4},I.prototype.writeFloat=function(c){var p=this.buf,b=this.pos;if(this.pos+=4,!(this.pos>p.length))return this.buf.writeFloatLE(c,b)},I.prototype.readDouble=function(){var c=this.buf,p=this.pos;return this.pos+=8,this.pos>c.length?0:this.buf.readDoubleLE(p)},I.prototype.skipDouble=function(){this.pos+=8},I.prototype.writeDouble=function(c){var p=this.buf,b=this.pos;if(this.pos+=8,!(this.pos>p.length))return this.buf.writeDoubleLE(c,b)},I.prototype.readFixed=function(c){var p=this.pos;if(this.pos+=c,!(this.pos>this.buf.length)){var b=O.alloc(c);return this.buf.copy(b,0,p,p+c),b}},I.prototype.skipFixed=function(c){this.pos+=c},I.prototype.writeFixed=function(c,p){p=p||c.length;var b=this.pos;this.pos+=p,!(this.pos>this.buf.length)&&c.copy(this.buf,b,0,p)},I.prototype.readBytes=function(){var c=this.readLong();if(c<0){this._invalidate();return}return this.readFixed(c)},I.prototype.skipBytes=function(){var c=this.readLong();if(c<0){this._invalidate();return}this.pos+=c},I.prototype.writeBytes=function(c){var p=c.length;this.writeLong(p),this.writeFixed(c,p)},typeof g.prototype.utf8Slice=="function"?I.prototype.readString=function(){var c=this.readLong();if(c<0)return this._invalidate(),"";var p=this.pos,b=this.buf;if(this.pos+=c,!(this.pos>b.length))return this.buf.utf8Slice(p,p+c)}:I.prototype.readString=function(){var c=this.readLong();if(c<0)return this._invalidate(),"";var p=this.pos,b=this.buf;if(this.pos+=c,!(this.pos>b.length))return this.buf.slice(p,p+c).toString()},I.prototype.skipString=function(){var c=this.readLong();if(c<0){this._invalidate();return}this.pos+=c},I.prototype.writeString=function(c){var p=g.byteLength(c),b=this.buf;this.writeLong(p);var A=this.pos;if(this.pos+=p,!(this.pos>b.length))if(p>64&&typeof g.prototype.utf8Write=="function")b.utf8Write(c,A,p);else{var V,Z,K,ce;for(V=0,Z=p;V>6|192,b[A++]=K&63|128):(K&64512)===55296&&((ce=c.charCodeAt(V+1))&64512)===56320?(K=65536+((K&1023)<<10)+(ce&1023),V++,b[A++]=K>>18|240,b[A++]=K>>12&63|128,b[A++]=K>>6&63|128,b[A++]=K&63|128):(b[A++]=K>>12|224,b[A++]=K>>6&63|128,b[A++]=K&63|128)}},typeof g.prototype.latin1Write=="function"?I.prototype.writeBinary=function(c,p){var b=this.pos;this.pos+=p,!(this.pos>this.buf.length)&&this.buf.latin1Write(c,b,p)}:typeof g.prototype.binaryWrite=="function"?I.prototype.writeBinary=function(c,p){var b=this.pos;this.pos+=p,!(this.pos>this.buf.length)&&this.buf.binaryWrite(c,b,p)}:I.prototype.writeBinary=function(c,p){var b=this.pos;this.pos+=p,!(this.pos>this.buf.length)&&this.buf.write(c,b,p,"binary")},I.prototype.matchBoolean=function(c){return this.buf[this.pos++]-c.buf[c.pos++]},I.prototype.matchInt=I.prototype.matchLong=function(c){var p=this.readLong(),b=c.readLong();return p===b?0:p>1;Z&128;)Z=V[this.pos++],p|=(Z&127)<=8&&(A-=8,c[b++]=p,p>>=8);return c[b]=p,K&&X(c,8),c},I.prototype.packLongBytes=function(c){var p=(c[7]&128)>>7,b=this.buf,A=1,V=0,Z=3,K;p?(X(c,8),K=1):K=0;for(var ce=[c.readUIntLE(0,3),c.readUIntLE(3,3),c.readUIntLE(6,2)];Z&&!ce[--Z];);for(;V7;)b[this.pos++]=K&127|128,K>>=7,A-=7;K|=ce[Z]<>=7;while(K&&(b[this.pos++]|=128));this.pos++,p&&X(c,8)};function X(c,p){for(;p--;)c[p]=~c[p]}l.exports={abstractFunction:ne,addDeprecatedGetters:E,bufferFrom:$,capitalize:P,copyOwnProperties:ee,getHash:m,compare:Y,getOption:te,impliedNamespace:Q,isValidName:M,jsonEnd:q,newBuffer:R,objectValues:j,qualify:G,toMap:w,singleIndexOf:a,hasDuplicates:z,unqualify:D,BufferPool:S,Lcg:N,OrderedQueue:x,Tap:I}}}),ot=Ie({"node_modules/avsc/lib/types.js"(u,l){"use strict";var h=ze(),d=Ue,_=De,g=d.Buffer,O=d.SlowBuffer,T=h.Tap,v=_.debuglog("avsc:types"),R=_.format,$={array:X,boolean:z,bytes:q,double:D,enum:N,error:c,fixed:x,float:G,int:ee,long:M,map:I,null:j,record:c,string:Q},P=new h.Lcg,Y=new T(new O(1024)),te=null,m=[];function a(t,i){var e;if(te?(e=te,m.push([te,this]),te=null):e=this,this._hash=new Z,this.name=void 0,this.aliases=void 0,this.doc=t&&t.doc?""+t.doc:void 0,t){var r=t.name,n=t.namespace===void 0?i&&i.namespace:t.namespace;if(r!==void 0){if(r=ke(r,n),he(r))throw new Error(R("cannot rename primitive type: %j",r));var o=i&&i.registry;if(o){if(o[r]!==void 0)throw new Error(R("duplicate type name: %s",r));o[r]=e}}else if(i&&i.noAnonymousTypes)throw new Error(R("missing name property in schema: %j",t));this.name=r,this.aliases=t.aliases?t.aliases.map(function(s){return ke(s,n)}):[]}}a.forSchema=function(t,i){i=i||{},i.registry=i.registry||{};var e=function(k){switch(k===!0?k="always":k===!1?k="never":k===void 0?k="auto":typeof k=="string"&&(k=k.toLowerCase()),k){case"always":return S;case"never":return E;case"auto":return;default:throw new Error(R("invalid wrap unions option: %j",k))}}(i.wrapUnions);if(t===null)throw new Error('invalid type: null (did you mean "null"?)');if(a.isType(t))return t;var r;if(i.typeHook&&(r=i.typeHook(t,i))){if(!a.isType(r))throw new Error(R("invalid typehook return value: %j",r));return r}if(typeof t=="string"){if(t=ke(t,i.namespace),r=i.registry[t],r)return r;if(he(t))return i.registry[t]=a.forSchema({type:t},i);throw new Error(R("undefined type name: %s",t))}if(t.logicalType&&i.logicalTypes&&!te){var n=i.logicalTypes[t.logicalType];if(n){var o=i.namespace,s={};Object.keys(i.registry).forEach(function(k){s[k]=i.registry[k]});try{return v("instantiating logical type for %s",t.logicalType),new n(t,i)}catch(k){if(v("failed to instantiate logical type for %s",t.logicalType),i.assertLogicalTypes)throw k;te=null,i.namespace=o,i.registry=s}}}if(Array.isArray(t)){var f=te;te=null;var y=t.map(function(k){return a.forSchema(k,i)});e||(e=Te(y)?S:E),te=f,r=new e(y,i)}else r=function(k){var C=$[k];if(C===void 0)throw new Error(R("unknown type: %j",k));return new C(t,i)}(t.type);return r},a.forValue=function(t,i){if(i=i||{},i.emptyArrayType=i.emptyArrayType||a.forSchema({type:"array",items:"null"}),i.valueHook){var e=i.valueHook(t,i);if(e!==void 0){if(!a.isType(e))throw new Error(R("invalid value hook return value: %j",e));return e}}switch(typeof t){case"string":return a.forSchema("string",i);case"boolean":return a.forSchema("boolean",i);case"number":return(t|0)===t?a.forSchema("int",i):Math.abs(t)<9007199254740991?a.forSchema("float",i):a.forSchema("double",i);case"object":if(t===null)return a.forSchema("null",i);if(Array.isArray(t))return t.length?a.forSchema({type:"array",items:a.forTypes(t.map(function(n){return a.forValue(n,i)}),i)},i):i.emptyArrayType;if(g.isBuffer(t))return a.forSchema("bytes",i);var r=Object.keys(t);return r.some(function(n){return!h.isValidName(n)})?a.forSchema({type:"map",values:a.forTypes(r.map(function(n){return a.forValue(t[n],i)}),i)},i):a.forSchema({type:"record",fields:r.map(function(n){return{name:n,type:a.forValue(t[n],i)}})},i);default:throw new Error(R("cannot infer type from: %j",t))}},a.forTypes=function(t,i){if(!t.length)throw new Error("no types to combine");if(t.length===1)return t[0];i=i||{};var e=[],r=0,n=!0;if(t.forEach(function(L){switch(L.typeName){case"union:unwrapped":n=!1,e=e.concat(L.types);break;case"union:wrapped":r++,e=e.concat(L.types);break;case"null":e.push(L);break;default:n=!1,e.push(L)}}),r){if(!n)throw new Error("cannot combine wrapped union");var o={};e.forEach(function(L){var F=L.branchName,J=o[F];if(!J)o[F]=L;else if(!L.equals(J))throw new Error("inconsistent branch type")});var s=i.wrapUnions,f;i.wrapUnions=!0;try{f=a.forSchema(Object.keys(o).map(function(L){return o[L]}),i)}catch(L){throw i.wrapUnions=s,L}return i.wrapUnions=s,f}var y={};e.forEach(function(L){var F=$e(L),J=y[F];J||(y[F]=J=[]),J.push(L)});var k=Object.keys(y),C=k.map(function(L){var F=y[L];if(F.length===1)return F[0];switch(L){case"null":case"boolean":return F[0];case"number":return Fe(F);case"string":return Ge(F,i);case"buffer":return Ke(F,i);case"array":return F=F.filter(function(J){return J!==i.emptyArrayType}),F.length?a.forSchema({type:"array",items:a.forTypes(F.map(function(J){return J.itemsType}),i)},i):i.emptyArrayType;default:return Je(F,i)}});return C.length===1?C[0]:a.forSchema(C,i)},a.isType=function(){var t=arguments.length;if(!t)return!1;var i=arguments[0];if(!i||typeof i._update!="function"||typeof i.fingerprint!="function")return!1;if(t===1)return!0;var e=i.typeName,r;for(r=1;r",i);var e=this.schema({exportAttrs:!0,noDeref:!0});return typeof e=="object"&&!a.isType(this,"logical")&&(e.type=void 0),R("<%s %j>",i,e)},a.prototype.isValid=function(t,i){var e=(i&&i.noUndeclaredFields)|0,r=i&&i.errorHook,n,o;return r&&(o=[],n=function(s,f){r.call(this,o.slice(),s,f,t)}),this._check(t,e,n,o)},a.prototype.random=h.abstractFunction,a.prototype.schema=function(t){return this._attrs({exportAttrs:!!(t&&t.exportAttrs),noDeref:!!(t&&t.noDeref)})},a.prototype.toBuffer=function(t){Y.pos=0,this._write(Y,t);var i=h.newBuffer(Y.pos);return Y.isValid()?Y.buf.copy(i,0,0,Y.pos):this._write(new T(i),t),i},a.prototype.toJSON=function(){return this.schema({exportAttrs:!0})},a.prototype.toString=function(t){return JSON.stringify(t===void 0?this.schema({noDeref:!0}):this._copy(t,{coerce:3}))},a.prototype.wrap=function(t){var i=this._branchConstructor;return i===null?null:new i(t)},a.prototype._attrs=function(t){t.derefed=t.derefed||{};var i=this.name;if(i!==void 0){if(t.noDeref||t.derefed[i])return i;t.derefed[i]=!0}var e={};this.name!==void 0&&(e.name=i),e.type=this.typeName;var r=this._deref(e,t);return r!==void 0&&(e=r),t.exportAttrs&&(this.aliases&&this.aliases.length&&(e.aliases=this.aliases),this.doc!==void 0&&(e.doc=this.doc)),e},a.prototype._createBranchConstructor=function(){var t=this.branchName;if(t==="null")return null;var i=~t.indexOf(".")?"this['"+t+"']":"this."+t,e="return function Branch$(val) { "+i+" = val; };",r=new Function(e)();return r.type=this,r.prototype.unwrap=new Function("return "+i+";"),r.prototype.unwrapped=r.prototype.unwrap,r},a.prototype._peek=function(t){var i=t.pos,e=this._read(t);return t.pos=i,e},a.prototype._check=h.abstractFunction,a.prototype._copy=h.abstractFunction,a.prototype._deref=h.abstractFunction,a.prototype._match=h.abstractFunction,a.prototype._read=h.abstractFunction,a.prototype._skip=h.abstractFunction,a.prototype._update=h.abstractFunction,a.prototype._write=h.abstractFunction,a.prototype.getAliases=function(){return this.aliases},a.prototype.getFingerprint=a.prototype.fingerprint,a.prototype.getName=function(t){return this.name||!t?this.name:this.branchName},a.prototype.getSchema=a.prototype.schema,a.prototype.getTypeName=function(){return this.typeName};function w(t){a.call(this),this._branchConstructor=this._createBranchConstructor(),t||Object.freeze(this)}_.inherits(w,a),w.prototype._update=function(t,i){i.typeName===this.typeName&&(t._read=this._read)},w.prototype._copy=function(t){return this._check(t,void 0,ae),t},w.prototype._deref=function(){return this.typeName},w.prototype.compare=h.compare;function j(){w.call(this)}_.inherits(j,w),j.prototype._check=function(t,i,e){var r=t===null;return!r&&e&&e(t,this),r},j.prototype._read=function(){return null},j.prototype._skip=function(){},j.prototype._write=function(t,i){i!==null&&ae(i,this)},j.prototype._match=function(){return 0},j.prototype.compare=j.prototype._match,j.prototype.typeName="null",j.prototype.random=j.prototype._read;function z(){w.call(this)}_.inherits(z,w),z.prototype._check=function(t,i,e){var r=typeof t=="boolean";return!r&&e&&e(t,this),r},z.prototype._read=function(t){return t.readBoolean()},z.prototype._skip=function(t){t.skipBoolean()},z.prototype._write=function(t,i){typeof i!="boolean"&&ae(i,this),t.writeBoolean(i)},z.prototype._match=function(t,i){return t.matchBoolean(i)},z.prototype.typeName="boolean",z.prototype.random=function(){return P.nextBoolean()};function ee(){w.call(this)}_.inherits(ee,w),ee.prototype._check=function(t,i,e){var r=t===(t|0);return!r&&e&&e(t,this),r},ee.prototype._read=function(t){return t.readInt()},ee.prototype._skip=function(t){t.skipInt()},ee.prototype._write=function(t,i){i!==(i|0)&&ae(i,this),t.writeInt(i)},ee.prototype._match=function(t,i){return t.matchInt(i)},ee.prototype.typeName="int",ee.prototype.random=function(){return P.nextInt(1e3)|0};function M(){w.call(this)}_.inherits(M,w),M.prototype._check=function(t,i,e){var r=typeof t=="number"&&t%1===0&&Ce(t);return!r&&e&&e(t,this),r},M.prototype._read=function(t){var i=t.readLong();if(!Ce(i))throw new Error("potential precision loss");return i},M.prototype._skip=function(t){t.skipLong()},M.prototype._write=function(t,i){(typeof i!="number"||i%1||!Ce(i))&&ae(i,this),t.writeLong(i)},M.prototype._match=function(t,i){return t.matchLong(i)},M.prototype._update=function(t,i){switch(i.typeName){case"int":t._read=i._read;break;case"abstract:long":case"long":t._read=this._read}},M.prototype.typeName="long",M.prototype.random=function(){return P.nextInt()},M.__with=function(t,i){t=t||{};var e={toBuffer:"_toBuffer",fromBuffer:"_fromBuffer",fromJSON:"_fromJSON",toJSON:"_toJSON",isValid:"_isValid",compare:"compare"},r=new b(i);return Object.keys(e).forEach(function(n){if(t[n]===void 0)throw new Error(R("missing method implementation: %s",n));r[e[n]]=t[n]}),Object.freeze(r)};function G(){w.call(this)}_.inherits(G,w),G.prototype._check=function(t,i,e){var r=typeof t=="number";return!r&&e&&e(t,this),r},G.prototype._read=function(t){return t.readFloat()},G.prototype._skip=function(t){t.skipFloat()},G.prototype._write=function(t,i){typeof i!="number"&&ae(i,this),t.writeFloat(i)},G.prototype._match=function(t,i){return t.matchFloat(i)},G.prototype._update=function(t,i){switch(i.typeName){case"float":case"int":t._read=i._read;break;case"abstract:long":case"long":t._read=function(e){return e.readLong()}}},G.prototype.typeName="float",G.prototype.random=function(){return P.nextFloat(1e3)};function D(){w.call(this)}_.inherits(D,w),D.prototype._check=function(t,i,e){var r=typeof t=="number";return!r&&e&&e(t,this),r},D.prototype._read=function(t){return t.readDouble()},D.prototype._skip=function(t){t.skipDouble()},D.prototype._write=function(t,i){typeof i!="number"&&ae(i,this),t.writeDouble(i)},D.prototype._match=function(t,i){return t.matchDouble(i)},D.prototype._update=function(t,i){switch(i.typeName){case"double":case"float":case"int":t._read=i._read;break;case"abstract:long":case"long":t._read=function(e){return e.readLong()}}},D.prototype.typeName="double",D.prototype.random=function(){return P.nextFloat()};function Q(){w.call(this)}_.inherits(Q,w),Q.prototype._check=function(t,i,e){var r=typeof t=="string";return!r&&e&&e(t,this),r},Q.prototype._read=function(t){return t.readString()},Q.prototype._skip=function(t){t.skipString()},Q.prototype._write=function(t,i){typeof i!="string"&&ae(i,this),t.writeString(i)},Q.prototype._match=function(t,i){return t.matchString(i)},Q.prototype._update=function(t,i){switch(i.typeName){case"bytes":case"string":t._read=this._read}},Q.prototype.typeName="string",Q.prototype.random=function(){return P.nextString(P.nextInt(32))};function q(){w.call(this)}_.inherits(q,w),q.prototype._check=function(t,i,e){var r=g.isBuffer(t);return!r&&e&&e(t,this),r},q.prototype._read=function(t){return t.readBytes()},q.prototype._skip=function(t){t.skipBytes()},q.prototype._write=function(t,i){g.isBuffer(i)||ae(i,this),t.writeBytes(i)},q.prototype._match=function(t,i){return t.matchBytes(i)},q.prototype._update=Q.prototype._update,q.prototype._copy=function(t,i){var e;switch((i&&i.coerce)|0){case 3:return this._check(t,void 0,ae),t.toString("binary");case 2:if(typeof t!="string")throw new Error(R("cannot coerce to buffer: %j",t));return e=h.bufferFrom(t,"binary"),this._check(e,void 0,ae),e;case 1:if(!je(t))throw new Error(R("cannot coerce to buffer: %j",t));return e=h.bufferFrom(t.data),this._check(e,void 0,ae),e;default:return this._check(t,void 0,ae),h.bufferFrom(t)}},q.prototype.compare=g.compare,q.prototype.typeName="bytes",q.prototype.random=function(){return P.nextBuffer(P.nextInt(32))};function ne(t,i){if(a.call(this),!Array.isArray(t))throw new Error(R("non-array union schema: %j",t));if(!t.length)throw new Error("empty union");this.types=Object.freeze(t.map(function(e){return a.forSchema(e,i)})),this._branchIndices={},this.types.forEach(function(e,r){if(a.isType(e,"union"))throw new Error("unions cannot be directly nested");var n=e.branchName;if(this._branchIndices[n]!==void 0)throw new Error(R("duplicate union branch name: %j",n));this._branchIndices[n]=r},this)}_.inherits(ne,a),ne.prototype._branchConstructor=function(){throw new Error("unions cannot be directly wrapped")},ne.prototype._skip=function(t){this.types[t.readLong()]._skip(t)},ne.prototype._match=function(t,i){var e=t.readLong(),r=i.readLong();return e===r?this.types[e]._match(t,i):e1)throw new Error(R("ambiguous aliasing for %s.%s (%s)",i.name,$.name,W));if(W.length)L=W[0],B={resolver:$.type.createResolver(o[L].type,e),name:"_"+$.name},f[L]?f[L].push(B):f[L]=[B],s.push(B.name);else{if($.defaultValue()===void 0)throw new Error(R("no matching field for default-less %s.%s",i.name,$.name));s.push("undefined")}}var H=-1;for(y=n.length;y&&f[n[--y].name]===void 0;)H=y;var Y=this._getConstructorName(),ne=[Y],ae=[this.recordConstructor],ce=" return function read"+Y+`(t, b) {
-`;for(y=0;y=H?" ":" ",ne.push("r"+y),ae.push($.type),ce+="r"+y+`._skip(t);
-`;else for(S=f[L].length;S--;)ce+=~H&&y>=H?" ":" ",ne.push("r"+y+"f"+S),B=f[L][S],ae.push(B.resolver),ce+="var "+B.name+" = ",ce+="r"+y+"f"+S+"._"+(S?"peek":"read")+`(t);
-`;~H&&(ce+=` }
-`),ce+=" return new "+Y+"("+s.join()+`);
-};`,t._read=new Function(ne.join(),ce).apply(void 0,ae)},c.prototype._match=function(t,i){var e=this.fields,r,n,o,s,f;for(r=0,n=e.length;r"};function ee(){this.str=void 0}function J(t,i,e,r){if(e){if(e._readerType!==t)throw new Error("invalid resolver");return e._read(i,r)}else return t._read(i)}function he(t){var i={};t.name&&(i[t.name]=!0);var e=t.aliases,r,n;for(r=0,n=e.length;r=-9007199254740990&&t<=9007199254740990}function je(t){return t&&t.type==="Buffer"&&Array.isArray(t.data)}function ue(t,i){throw new Error(R("invalid %j: %j",i.schema(),t))}function ke(t,i){var e=h.unqualify(t);return fe(e)?e:h.qualify(t,i)}function Ce(t){var i=t.typeName;switch(i){case"double":case"float":case"int":case"long":return"number";case"bytes":case"fixed":return"buffer";case"enum":return"string";case"map":case"error":case"record":return"object";default:return i}}function Se(t){if(t===null)return"null";var i=typeof t;if(i==="object"){if(Array.isArray(t))return"array";if(g.isBuffer(t))return"buffer"}return i}function Te(t){var i={},e,r,n,o;for(e=0,r=t.length;ee&&(e=f,r=s);return r}function Ge(t,i){var e={},r,n,o,s;for(r=0,n=t.length;r0){var St=ye[0];ye[0]=ye[be],ye[be]=St,ce=a.forSchema(ye,i)}}return{name:ae,type:ce,default:n[ae]}})}:ne={type:"map",values:a.forTypes(e,i)},a.forSchema(ne,i)}l.exports={Type:a,getTypeBucket:Ce,getValueBucket:Se,isPrimitive:fe,builtins:function(){var t={LogicalType:p,UnwrappedUnionType:E,WrappedUnionType:k},i=Object.keys(C),e,r,n;for(e=0,r=i.length;eI.length&&(x.buf=d.newBuffer(2*c)),x.pos=0,this._writeValue(x,E)}N()},te.prototype._flush=function(E){var k=this._tap,N=k.pos;N&&this.push(k.buf.slice(0,N)),E()};function M(E,k){k=k||{},g.Duplex.call(this,{allowHalfOpen:!0,writableObjectMode:!0});var N;if(h.Type.isType(E)?(N=E,E=void 0):N=h.Type.forSchema(E),this._schema=E,this._type=N,this._writeValue=function(I,Z){try{this._type._write(I,Z)}catch(c){return this.emit("typeError",c,Z,this._type),!1}return!0},this._blockSize=k.blockSize||65536,this._tap=new w(d.newBuffer(this._blockSize)),this._codecs=k.codecs,this._codec=k.codec||"null",this._blockCount=0,this._syncMarker=k.syncMarker||new d.Lcg().nextBuffer(16),this._queue=new d.OrderedQueue,this._pending=0,this._finished=!1,this._needHeader=!1,this._needPush=!1,this._metadata=k.metadata||{},!P.isValid(this._metadata))throw new Error("invalid metadata");var x=this._codec;if(this._compress=(this._codecs||M.getDefaultCodecs())[x],!this._compress)throw new Error(a("unsupported codec: %s",x));switch(k.omitHeader!==void 0&&(k.writeHeader=k.omitHeader?"never":"auto"),k.writeHeader){case!1:case"never":break;case void 0:case"auto":this._needHeader=!0;break;default:this._writeHeader()}this.on("finish",function(){this._finished=!0,this._blockCount?this._flushChunk():this._finished&&this._needPush&&this.push(null)}),this.on("typeError",function(I){this.emit("error",I)})}O.inherits(M,g.Duplex),M.defaultCodecs=function(){return{null:function(E,k){k(null,E)},deflate:T.deflateRaw}},M.getDefaultCodecs=M.defaultCodecs,M.prototype._writeHeader=function(){var E=JSON.stringify(this._schema?this._schema:this._type.getSchema({exportAttrs:!0})),k=d.copyOwnProperties(this._metadata,{"avro.schema":d.bufferFrom(E),"avro.codec":d.bufferFrom(this._codec)},!0),N=Q.getRecordConstructor(),x=new N(m,k,this._syncMarker);this.push(x.toBuffer())},M.prototype._write=function(E,k,N){this._needHeader&&(this._writeHeader(),this._needHeader=!1);var x=this._tap,I=x.pos,Z=!1;if(this._writeValue(x,E)){if(!x.isValid()){I&&(this._flushChunk(I,N),Z=!0);var c=x.pos-I;c>this._blockSize&&(this._blockSize=c*2),x.buf=d.newBuffer(this._blockSize),x.pos=0,this._writeValue(x,E)}this._blockCount++}else x.pos=I;Z||N()},M.prototype._flushChunk=function(E,k){var N=this._tap;E=E||N.pos,this._compress(N.buf.slice(0,E),this._createBlockCallback(E,k)),this._blockCount=0},M.prototype._read=function(){var E=this,k=this._queue.pop();if(!k){this._finished&&!this._pending?process.nextTick(function(){E.push(null)}):this._needPush=!0;return}this.push(C.toBuffer(k.count,!0)),this.push(C.toBuffer(k.buf.length,!0)),this.push(k.buf),this.push(this._syncMarker),this._finished||k.cb()},M.prototype._createBlockCallback=function(E,k){var N=this,x=this._index++,I=this._blockCount;return this._pending++,function(Z,c){if(Z){var p=new Error(a("%s codec compression error",N._codec));p.cause=Z,N.emit("error",p);return}N._pending--,N.emit("block",new G(I,E,c.length)),N._queue.push(new D(x,c,k,I)),N._needPush&&(N._needPush=!1,N._read())}};function G(E,k,N){this.valueCount=E,this.rawDataLength=k,this.compressedDataLength=N}function D(E,k,N,x){this.index=E,this.buf=k,this.cb=N,this.count=x|0}function X(E){var k=E.pos,N=re._read(E);return E.isValid()?N:(E.pos=k,null)}function U(E,k,N){if(E)return function(I){return function(Z){var c=Z.pos;return I(Z),Z.buf.slice(c,Z.pos)}}(k._skip);if(N){var x=N.createResolver(k);return function(I){return x._read(I)}}else return function(I){return k._read(I)}}function oe(E,k,N){var x=d.newBuffer(N);return E.copy(x,0,k,k+N),x}l.exports={BLOCK_TYPE:re,HEADER_TYPE:Q,MAGIC_BYTES:m,streams:{BlockDecoder:z,BlockEncoder:M,RawDecoder:j,RawEncoder:te}}}}),jt=Ie({"node_modules/avsc/lib/services.js"(u,l){"use strict";var h=ot(),d=ze(),_=Ue,g=At,O=vt,T=De,v=_.Buffer,R=d.Tap,C=h.Type,P=T.debuglog("avsc:services"),Q=T.format,re={namespace:"org.apache.avro.ipc"},m=C.forSchema("boolean",re),a=C.forSchema({type:"map",values:"bytes"},re),w=C.forSchema("string",re),j=C.forSchema({name:"HandshakeRequest",type:"record",fields:[{name:"clientHash",type:{name:"MD5",type:"fixed",size:16}},{name:"clientProtocol",type:["null","string"],default:null},{name:"serverHash",type:"MD5"},{name:"meta",type:["null",a],default:null}]},re),z=C.forSchema({name:"HandshakeResponse",type:"record",fields:[{name:"match",type:{name:"HandshakeMatch",type:"enum",symbols:["BOTH","CLIENT","NONE"]}},{name:"serverProtocol",type:["null","string"],default:null},{name:"serverHash",type:["null","MD5"],default:null},{name:"meta",type:["null",a],default:null}]},re),te=16,M=new G("",C.forSchema({name:"PingRequest",type:"record",fields:[]},re),C.forSchema(["string"],re),C.forSchema("null",re));function G(e,r,n,o,s,f){if(this.name=e,!C.isType(r,"record"))throw new Error("invalid request type");if(this.requestType=r,!C.isType(n,"union")||!C.isType(n.getTypes()[0],"string"))throw new Error("invalid error type");if(this.errorType=n,s&&(!C.isType(o,"null")||n.getTypes().length>1))throw new Error("inapplicable one-way parameter");this.responseType=o,this.oneWay=!!s,this.doc=f!==void 0?""+f:void 0,Object.freeze(this)}G.forSchema=function(e,r,n){if(n=n||{},!d.isValidName(e))throw new Error(Q("invalid message name: %s",e));if(!Array.isArray(r.request))throw new Error(Q("invalid message request: %s",e));var o=Q("%s.%sRequest",re.namespace,d.capitalize(e)),s=C.forSchema({name:o,type:"record",namespace:n.namespace||"",fields:r.request},n);if(delete n.registry[o],!r.response)throw new Error(Q("invalid message response: %s",e));var f=C.forSchema(r.response,n);if(r.errors!==void 0&&!Array.isArray(r.errors))throw new Error(Q("invalid message errors: %s",e));var y=C.forSchema(["string"].concat(r.errors||[]),n),S=!!r["one-way"];return new G(e,s,y,f,S,r.doc)},G.prototype.schema=C.prototype.getSchema,G.prototype._attrs=function(e){var r=this.requestType._attrs(e),n={request:r.fields,response:this.responseType._attrs(e)},o=this.doc;o!==void 0&&(n.doc=o);var s=this.errorType._attrs(e);return s.length>1&&(n.errors=s.slice(1)),this.oneWay&&(n["one-way"]=!0),n},d.addDeprecatedGetters(G,["name","errorType","requestType","responseType"]),G.prototype.isOneWay=T.deprecate(function(){return this.oneWay},"use `.oneWay` directly instead of `.isOneWay()`");function D(e,r,n,o,s){if(typeof e!="string")return D.forProtocol(e,r);this.name=e,this._messagesByName=r||{},this.messages=Object.freeze(d.objectValues(this._messagesByName)),this._typesByName=n||{},this.types=Object.freeze(d.objectValues(this._typesByName)),this.protocol=o,this._hashStr=d.getHash(JSON.stringify(o)).toString("binary"),this.doc=o.doc?""+o.doc:void 0,this._server=s||this.createServer({silent:!0}),Object.freeze(this)}D.Client=U,D.Server=oe,D.compatible=function(e,r){try{$e(e,r)}catch{return!1}return!0},D.forProtocol=function(e,r){r=r||{};var n=e.protocol;if(!n)throw new Error("missing protocol name");if(e.namespace!==void 0)r.namespace=e.namespace;else{var o=/^(.*)\.[^.]+$/.exec(n);o&&(r.namespace=o[1])}n=d.qualify(n,r.namespace),e.types&&e.types.forEach(function(f){C.forSchema(f,r)});var s;return e.messages&&(s={},Object.keys(e.messages).forEach(function(f){s[f]=G.forSchema(f,e.messages[f],r)})),new D(n,s,r.registry,e)},D.isService=function(e){return!!e&&e.hasOwnProperty("_hashStr")},D.prototype.createClient=function(e){var r=new U(this,e);return process.nextTick(function(){if(e&&e.server){var n={objectMode:!0},o=[new O.PassThrough(n),new O.PassThrough(n)];e.server.createChannel({readable:o[0],writable:o[1]},n),r.createChannel({readable:o[1],writable:o[0]},n)}else e&&e.transport&&r.createChannel(e.transport)}),r},D.prototype.createServer=function(e){return new oe(this,e)},Object.defineProperty(D.prototype,"hash",{enumerable:!0,get:function(){return d.bufferFrom(this._hashStr,"binary")}}),D.prototype.message=function(e){return this._messagesByName[e]},D.prototype.type=function(e){return this._typesByName[e]},D.prototype.inspect=function(){return Q("",this.name)},d.addDeprecatedGetters(D,["message","messages","name","type","types"]),D.prototype.createEmitter=T.deprecate(function(e,r){r=r||{};var n=this.createClient({cache:r.cache,buffering:!1,strictTypes:r.strictErrors,timeout:r.timeout}),o=n.createChannel(e,r);return Ce(n,o),o},"use `.createClient()` instead of `.createEmitter()`"),D.prototype.createListener=T.deprecate(function(e,r){if(r&&r.strictErrors)throw new Error("use `.createServer()` to support strict errors");return this._server.createChannel(e,r)},"use `.createServer().createChannel()` instead of `.createListener()`"),D.prototype.emit=T.deprecate(function(e,r,n,o){if(!n||!this.equals(n.client._svc$))throw new Error("invalid emitter");var s=n.client;return U.prototype.emitMessage.call(s,e,r,o&&o.bind(this)),n.getPending()},"create a client via `.createClient()` to emit messages instead of `.emit()`"),D.prototype.equals=T.deprecate(function(e){return D.isService(e)&&this.getFingerprint().equals(e.getFingerprint())},"equality testing is deprecated, compare the `.protocol`s instead"),D.prototype.getFingerprint=T.deprecate(function(e){return d.getHash(JSON.stringify(this.protocol),e)},"use `.hash` instead of `.getFingerprint()`"),D.prototype.getSchema=T.deprecate(C.prototype.getSchema,"use `.protocol` instead of `.getSchema()`"),D.prototype.on=T.deprecate(function(e,r){var n=this;return this._server.onMessage(e,function(o,s){return r.call(n,o,this.channel,s)}),this},"use `.createServer().onMessage()` instead of `.on()`"),D.prototype.subprotocol=T.deprecate(function(){var e=this._server,r={strictTypes:e._strict,cache:e._cache},n=new oe(e.service,r);return n._handlers=Object.create(e._handlers),new D(this.name,this._messagesByName,this._typesByName,this.protocol,n)},"`.subprotocol()` will be removed in 5.1"),D.prototype._attrs=function(e){var r={protocol:this.name},n=[];this.types.forEach(function(s){if(s.getName()!==void 0){var f=s._attrs(e);typeof f!="string"&&n.push(f)}}),n.length&&(r.types=n);var o=Object.keys(this._messagesByName);return o.length&&(r.messages={},o.forEach(function(s){r.messages[s]=this._messagesByName[s]._attrs(e)},this)),e&&e.exportAttrs&&this.doc!==void 0&&(r.doc=this.doc),r};function X(e,r,n){n===void 0&&typeof r=="function"&&(n=r,r=void 0);var o=new D({protocol:"Empty"},re),s;o.createClient({timeout:r&&r.timeout}).createChannel(e,{scope:r&&r.scope,endWritable:typeof e=="function"}).once("handshake",function(f,y){s=y.serverProtocol,this.destroy(!0)}).once("eot",function(f,y){y&&!/interrupted/.test(y)?n(y):n(null,JSON.parse(s))})}function U(e,r){r=r||{},g.EventEmitter.call(this),this._svc$=e,this._channels$=[],this._fns$=[],this._buffering$=!!r.buffering,this._cache$=r.cache||{},this._policy$=r.channelPolicy,this._strict$=!!r.strictTypes,this._timeout$=d.getOption(r,"timeout",1e4),r.remoteProtocols&&je(this._cache$,r.remoteProtocols,e,!0),this._svc$.messages.forEach(function(n){this[n.name]=this._createMessageHandler$(n)},this)}T.inherits(U,g.EventEmitter),U.prototype.activeChannels=function(){return this._channels$.slice()},U.prototype.createChannel=function(e,r){var n=r&&r.objectMode,o;if(typeof e=="function"){var s;n?s=e:s=function(F){var W=new J,B=e(function(H,Y){if(H){F(H);return}var ne=new ee().once("error",function(ae){o.destroy(ae)});F(null,Y.pipe(ne))});if(B)return W.pipe(B),W},o=new k(this,s,r)}else{var f,y;if(Je(e)?f=y=e:(f=e.readable,y=e.writable),!n){var S=new he;f=f.pipe(S);var $=new pe;$.pipe(y),y=$}o=new N(this,f,y,r),n||(o.once("eot",function(){f.unpipe(S),$.unpipe(y)}),S.once("error",function(F){o.destroy(F)}))}var L=this._channels$;return L.push(o),o.once("_drain",function(){L.splice(L.indexOf(this),1)}),this._buffering$=!1,this.emit("channel",o),o},U.prototype.destroyChannels=function(e){this._channels$.forEach(function(r){r.destroy(e&&e.noWait)})},U.prototype.emitMessage=function(e,r,n,o){var s=t(this._svc$,e),f=new c(s,{},r);this._emitMessage$(f,n,o)},U.prototype.remoteProtocols=function(){return ue(this._cache$,!0)},Object.defineProperty(U.prototype,"service",{enumerable:!0,get:function(){return this._svc$}}),U.prototype.use=function(){var e,r,n;for(e=0,r=arguments.length;e1)throw new Error(R("ambiguous aliasing for %s.%s (%s)",i.name,C.name,J));if(J.length)L=J[0],B={resolver:C.type.createResolver(o[L].type,e),name:"_"+C.name},f[L]?f[L].push(B):f[L]=[B],s.push(B.name);else{if(C.defaultValue()===void 0)throw new Error(R("no matching field for default-less %s.%s",i.name,C.name));s.push("undefined")}}var H=-1;for(y=n.length;y&&f[n[--y].name]===void 0;)H=y;var W=this._getConstructorName(),ie=[W],se=[this.recordConstructor],ue=" return function read"+W+`(t, b) {
+`;for(y=0;y=H?" ":" ",ie.push("r"+y),se.push(C.type),ue+="r"+y+`._skip(t);
+`;else for(k=f[L].length;k--;)ue+=~H&&y>=H?" ":" ",ie.push("r"+y+"f"+k),B=f[L][k],se.push(B.resolver),ue+="var "+B.name+" = ",ue+="r"+y+"f"+k+"._"+(k?"peek":"read")+`(t);
+`;~H&&(ue+=` }
+`),ue+=" return new "+W+"("+s.join()+`);
+};`,t._read=new Function(ie.join(),ue).apply(void 0,se)},c.prototype._match=function(t,i){var e=this.fields,r,n,o,s,f;for(r=0,n=e.length;r"};function Z(){this.str=void 0}function K(t,i,e,r){if(e){if(e._readerType!==t)throw new Error("invalid resolver");return e._read(i,r)}else return t._read(i)}function ce(t){var i={};t.name&&(i[t.name]=!0);var e=t.aliases,r,n;for(r=0,n=e.length;r=-9007199254740990&&t<=9007199254740990}function je(t){return t&&t.type==="Buffer"&&Array.isArray(t.data)}function ae(t,i){throw new Error(R("invalid %j: %j",i.schema(),t))}function ke(t,i){var e=h.unqualify(t);return he(e)?e:h.qualify(t,i)}function $e(t){var i=t.typeName;switch(i){case"double":case"float":case"int":case"long":return"number";case"bytes":case"fixed":return"buffer";case"enum":return"string";case"map":case"error":case"record":return"object";default:return i}}function xe(t){if(t===null)return"null";var i=typeof t;if(i==="object"){if(Array.isArray(t))return"array";if(g.isBuffer(t))return"buffer"}return i}function Te(t){var i={},e,r,n,o;for(e=0,r=t.length;ee&&(e=f,r=s);return r}function Ge(t,i){var e={},r,n,o,s;for(r=0,n=t.length;r0){var kt=ye[0];ye[0]=ye[be],ye[be]=kt,ue=a.forSchema(ye,i)}}return{name:se,type:ue,default:n[se]}})}:ie={type:"map",values:a.forTypes(e,i)},a.forSchema(ie,i)}l.exports={Type:a,getTypeBucket:$e,getValueBucket:xe,isPrimitive:he,builtins:function(){var t={LogicalType:p,UnwrappedUnionType:E,WrappedUnionType:S},i=Object.keys($),e,r,n;for(e=0,r=i.length;eI.length&&(x.buf=d.newBuffer(2*c)),x.pos=0,this._writeValue(x,E)}N()},ee.prototype._flush=function(E){var S=this._tap,N=S.pos;N&&this.push(S.buf.slice(0,N)),E()};function M(E,S){S=S||{},g.Duplex.call(this,{allowHalfOpen:!0,writableObjectMode:!0});var N;if(h.Type.isType(E)?(N=E,E=void 0):N=h.Type.forSchema(E),this._schema=E,this._type=N,this._writeValue=function(I,X){try{this._type._write(I,X)}catch(c){return this.emit("typeError",c,X,this._type),!1}return!0},this._blockSize=S.blockSize||65536,this._tap=new w(d.newBuffer(this._blockSize)),this._codecs=S.codecs,this._codec=S.codec||"null",this._blockCount=0,this._syncMarker=S.syncMarker||new d.Lcg().nextBuffer(16),this._queue=new d.OrderedQueue,this._pending=0,this._finished=!1,this._needHeader=!1,this._needPush=!1,this._metadata=S.metadata||{},!P.isValid(this._metadata))throw new Error("invalid metadata");var x=this._codec;if(this._compress=(this._codecs||M.getDefaultCodecs())[x],!this._compress)throw new Error(a("unsupported codec: %s",x));switch(S.omitHeader!==void 0&&(S.writeHeader=S.omitHeader?"never":"auto"),S.writeHeader){case!1:case"never":break;case void 0:case"auto":this._needHeader=!0;break;default:this._writeHeader()}this.on("finish",function(){this._finished=!0,this._blockCount?this._flushChunk():this._finished&&this._needPush&&this.push(null)}),this.on("typeError",function(I){this.emit("error",I)})}O.inherits(M,g.Duplex),M.defaultCodecs=function(){return{null:function(E,S){S(null,E)},deflate:T.deflateRaw}},M.getDefaultCodecs=M.defaultCodecs,M.prototype._writeHeader=function(){var E=JSON.stringify(this._schema?this._schema:this._type.getSchema({exportAttrs:!0})),S=d.copyOwnProperties(this._metadata,{"avro.schema":d.bufferFrom(E),"avro.codec":d.bufferFrom(this._codec)},!0),N=Y.getRecordConstructor(),x=new N(m,S,this._syncMarker);this.push(x.toBuffer())},M.prototype._write=function(E,S,N){this._needHeader&&(this._writeHeader(),this._needHeader=!1);var x=this._tap,I=x.pos,X=!1;if(this._writeValue(x,E)){if(!x.isValid()){I&&(this._flushChunk(I,N),X=!0);var c=x.pos-I;c>this._blockSize&&(this._blockSize=c*2),x.buf=d.newBuffer(this._blockSize),x.pos=0,this._writeValue(x,E)}this._blockCount++}else x.pos=I;X||N()},M.prototype._flushChunk=function(E,S){var N=this._tap;E=E||N.pos,this._compress(N.buf.slice(0,E),this._createBlockCallback(E,S)),this._blockCount=0},M.prototype._read=function(){var E=this,S=this._queue.pop();if(!S){this._finished&&!this._pending?process.nextTick(function(){E.push(null)}):this._needPush=!0;return}this.push($.toBuffer(S.count,!0)),this.push($.toBuffer(S.buf.length,!0)),this.push(S.buf),this.push(this._syncMarker),this._finished||S.cb()},M.prototype._createBlockCallback=function(E,S){var N=this,x=this._index++,I=this._blockCount;return this._pending++,function(X,c){if(X){var p=new Error(a("%s codec compression error",N._codec));p.cause=X,N.emit("error",p);return}N._pending--,N.emit("block",new G(I,E,c.length)),N._queue.push(new D(x,c,S,I)),N._needPush&&(N._needPush=!1,N._read())}};function G(E,S,N){this.valueCount=E,this.rawDataLength=S,this.compressedDataLength=N}function D(E,S,N,x){this.index=E,this.buf=S,this.cb=N,this.count=x|0}function Q(E){var S=E.pos,N=te._read(E);return E.isValid()?N:(E.pos=S,null)}function q(E,S,N){if(E)return function(I){return function(X){var c=X.pos;return I(X),X.buf.slice(c,X.pos)}}(S._skip);if(N){var x=N.createResolver(S);return function(I){return x._read(I)}}else return function(I){return S._read(I)}}function ne(E,S,N){var x=d.newBuffer(N);return E.copy(x,0,S,S+N),x}l.exports={BLOCK_TYPE:te,HEADER_TYPE:Y,MAGIC_BYTES:m,streams:{BlockDecoder:z,BlockEncoder:M,RawDecoder:j,RawEncoder:ee}}}}),jt=Ie({"node_modules/avsc/lib/services.js"(u,l){"use strict";var h=ot(),d=ze(),_=Ue,g=At,O=vt,T=De,v=_.Buffer,R=d.Tap,$=h.Type,P=T.debuglog("avsc:services"),Y=T.format,te={namespace:"org.apache.avro.ipc"},m=$.forSchema("boolean",te),a=$.forSchema({type:"map",values:"bytes"},te),w=$.forSchema("string",te),j=$.forSchema({name:"HandshakeRequest",type:"record",fields:[{name:"clientHash",type:{name:"MD5",type:"fixed",size:16}},{name:"clientProtocol",type:["null","string"],default:null},{name:"serverHash",type:"MD5"},{name:"meta",type:["null",a],default:null}]},te),z=$.forSchema({name:"HandshakeResponse",type:"record",fields:[{name:"match",type:{name:"HandshakeMatch",type:"enum",symbols:["BOTH","CLIENT","NONE"]}},{name:"serverProtocol",type:["null","string"],default:null},{name:"serverHash",type:["null","MD5"],default:null},{name:"meta",type:["null",a],default:null}]},te),ee=16,M=new G("",$.forSchema({name:"PingRequest",type:"record",fields:[]},te),$.forSchema(["string"],te),$.forSchema("null",te));function G(e,r,n,o,s,f){if(this.name=e,!$.isType(r,"record"))throw new Error("invalid request type");if(this.requestType=r,!$.isType(n,"union")||!$.isType(n.getTypes()[0],"string"))throw new Error("invalid error type");if(this.errorType=n,s&&(!$.isType(o,"null")||n.getTypes().length>1))throw new Error("inapplicable one-way parameter");this.responseType=o,this.oneWay=!!s,this.doc=f!==void 0?""+f:void 0,Object.freeze(this)}G.forSchema=function(e,r,n){if(n=n||{},!d.isValidName(e))throw new Error(Y("invalid message name: %s",e));if(!Array.isArray(r.request))throw new Error(Y("invalid message request: %s",e));var o=Y("%s.%sRequest",te.namespace,d.capitalize(e)),s=$.forSchema({name:o,type:"record",namespace:n.namespace||"",fields:r.request},n);if(delete n.registry[o],!r.response)throw new Error(Y("invalid message response: %s",e));var f=$.forSchema(r.response,n);if(r.errors!==void 0&&!Array.isArray(r.errors))throw new Error(Y("invalid message errors: %s",e));var y=$.forSchema(["string"].concat(r.errors||[]),n),k=!!r["one-way"];return new G(e,s,y,f,k,r.doc)},G.prototype.schema=$.prototype.getSchema,G.prototype._attrs=function(e){var r=this.requestType._attrs(e),n={request:r.fields,response:this.responseType._attrs(e)},o=this.doc;o!==void 0&&(n.doc=o);var s=this.errorType._attrs(e);return s.length>1&&(n.errors=s.slice(1)),this.oneWay&&(n["one-way"]=!0),n},d.addDeprecatedGetters(G,["name","errorType","requestType","responseType"]),G.prototype.isOneWay=T.deprecate(function(){return this.oneWay},"use `.oneWay` directly instead of `.isOneWay()`");function D(e,r,n,o,s){if(typeof e!="string")return D.forProtocol(e,r);this.name=e,this._messagesByName=r||{},this.messages=Object.freeze(d.objectValues(this._messagesByName)),this._typesByName=n||{},this.types=Object.freeze(d.objectValues(this._typesByName)),this.protocol=o,this._hashStr=d.getHash(JSON.stringify(o)).toString("binary"),this.doc=o.doc?""+o.doc:void 0,this._server=s||this.createServer({silent:!0}),Object.freeze(this)}D.Client=q,D.Server=ne,D.compatible=function(e,r){try{Ce(e,r)}catch{return!1}return!0},D.forProtocol=function(e,r){r=r||{};var n=e.protocol;if(!n)throw new Error("missing protocol name");if(e.namespace!==void 0)r.namespace=e.namespace;else{var o=/^(.*)\.[^.]+$/.exec(n);o&&(r.namespace=o[1])}n=d.qualify(n,r.namespace),e.types&&e.types.forEach(function(f){$.forSchema(f,r)});var s;return e.messages&&(s={},Object.keys(e.messages).forEach(function(f){s[f]=G.forSchema(f,e.messages[f],r)})),new D(n,s,r.registry,e)},D.isService=function(e){return!!e&&e.hasOwnProperty("_hashStr")},D.prototype.createClient=function(e){var r=new q(this,e);return process.nextTick(function(){if(e&&e.server){var n={objectMode:!0},o=[new O.PassThrough(n),new O.PassThrough(n)];e.server.createChannel({readable:o[0],writable:o[1]},n),r.createChannel({readable:o[1],writable:o[0]},n)}else e&&e.transport&&r.createChannel(e.transport)}),r},D.prototype.createServer=function(e){return new ne(this,e)},Object.defineProperty(D.prototype,"hash",{enumerable:!0,get:function(){return d.bufferFrom(this._hashStr,"binary")}}),D.prototype.message=function(e){return this._messagesByName[e]},D.prototype.type=function(e){return this._typesByName[e]},D.prototype.inspect=function(){return Y("",this.name)},d.addDeprecatedGetters(D,["message","messages","name","type","types"]),D.prototype.createEmitter=T.deprecate(function(e,r){r=r||{};var n=this.createClient({cache:r.cache,buffering:!1,strictTypes:r.strictErrors,timeout:r.timeout}),o=n.createChannel(e,r);return $e(n,o),o},"use `.createClient()` instead of `.createEmitter()`"),D.prototype.createListener=T.deprecate(function(e,r){if(r&&r.strictErrors)throw new Error("use `.createServer()` to support strict errors");return this._server.createChannel(e,r)},"use `.createServer().createChannel()` instead of `.createListener()`"),D.prototype.emit=T.deprecate(function(e,r,n,o){if(!n||!this.equals(n.client._svc$))throw new Error("invalid emitter");var s=n.client;return q.prototype.emitMessage.call(s,e,r,o&&o.bind(this)),n.getPending()},"create a client via `.createClient()` to emit messages instead of `.emit()`"),D.prototype.equals=T.deprecate(function(e){return D.isService(e)&&this.getFingerprint().equals(e.getFingerprint())},"equality testing is deprecated, compare the `.protocol`s instead"),D.prototype.getFingerprint=T.deprecate(function(e){return d.getHash(JSON.stringify(this.protocol),e)},"use `.hash` instead of `.getFingerprint()`"),D.prototype.getSchema=T.deprecate($.prototype.getSchema,"use `.protocol` instead of `.getSchema()`"),D.prototype.on=T.deprecate(function(e,r){var n=this;return this._server.onMessage(e,function(o,s){return r.call(n,o,this.channel,s)}),this},"use `.createServer().onMessage()` instead of `.on()`"),D.prototype.subprotocol=T.deprecate(function(){var e=this._server,r={strictTypes:e._strict,cache:e._cache},n=new ne(e.service,r);return n._handlers=Object.create(e._handlers),new D(this.name,this._messagesByName,this._typesByName,this.protocol,n)},"`.subprotocol()` will be removed in 5.1"),D.prototype._attrs=function(e){var r={protocol:this.name},n=[];this.types.forEach(function(s){if(s.getName()!==void 0){var f=s._attrs(e);typeof f!="string"&&n.push(f)}}),n.length&&(r.types=n);var o=Object.keys(this._messagesByName);return o.length&&(r.messages={},o.forEach(function(s){r.messages[s]=this._messagesByName[s]._attrs(e)},this)),e&&e.exportAttrs&&this.doc!==void 0&&(r.doc=this.doc),r};function Q(e,r,n){n===void 0&&typeof r=="function"&&(n=r,r=void 0);var o=new D({protocol:"Empty"},te),s;o.createClient({timeout:r&&r.timeout}).createChannel(e,{scope:r&&r.scope,endWritable:typeof e=="function"}).once("handshake",function(f,y){s=y.serverProtocol,this.destroy(!0)}).once("eot",function(f,y){y&&!/interrupted/.test(y)?n(y):n(null,JSON.parse(s))})}function q(e,r){r=r||{},g.EventEmitter.call(this),this._svc$=e,this._channels$=[],this._fns$=[],this._buffering$=!!r.buffering,this._cache$=r.cache||{},this._policy$=r.channelPolicy,this._strict$=!!r.strictTypes,this._timeout$=d.getOption(r,"timeout",1e4),r.remoteProtocols&&je(this._cache$,r.remoteProtocols,e,!0),this._svc$.messages.forEach(function(n){this[n.name]=this._createMessageHandler$(n)},this)}T.inherits(q,g.EventEmitter),q.prototype.activeChannels=function(){return this._channels$.slice()},q.prototype.createChannel=function(e,r){var n=r&&r.objectMode,o;if(typeof e=="function"){var s;n?s=e:s=function(F){var J=new K,B=e(function(H,W){if(H){F(H);return}var ie=new Z().once("error",function(se){o.destroy(se)});F(null,W.pipe(ie))});if(B)return J.pipe(B),J},o=new S(this,s,r)}else{var f,y;if(Je(e)?f=y=e:(f=e.readable,y=e.writable),!n){var k=new ce;f=f.pipe(k);var C=new pe;C.pipe(y),y=C}o=new N(this,f,y,r),n||(o.once("eot",function(){f.unpipe(k),C.unpipe(y)}),k.once("error",function(F){o.destroy(F)}))}var L=this._channels$;return L.push(o),o.once("_drain",function(){L.splice(L.indexOf(this),1)}),this._buffering$=!1,this.emit("channel",o),o},q.prototype.destroyChannels=function(e){this._channels$.forEach(function(r){r.destroy(e&&e.noWait)})},q.prototype.emitMessage=function(e,r,n,o){var s=t(this._svc$,e),f=new c(s,{},r);this._emitMessage$(f,n,o)},q.prototype.remoteProtocols=function(){return ae(this._cache$,!0)},Object.defineProperty(q.prototype,"service",{enumerable:!0,get:function(){return this._svc$}}),q.prototype.use=function(){var e,r,n;for(e=0,r=arguments.length;e "+o+`) {
`,f+=" return this.onMessage('"+r+`', function (req, cb) {
`,f+=" return handler.call(this"+s+`, cb);
@@ -63,19 +63,19 @@ import Ue from"buffer";import xt from"crypto";import De from"util";import vt fro
`,f+=` });
`,f+=` }
`,f+=`};
-`,new Function(f)()},oe.prototype._onError=function(e){!this._silent&&e.rpcCode!=="UNKNOWN_PROTOCOL"&&(console.error(),e.rpcCode?(console.error(e.rpcCode),console.error(e.cause)):(console.error("INTERNAL_SERVER_ERROR"),console.error(e)))};function E(e,r){r=r||{},g.EventEmitter.call(this),this.client=e,this.timeout=d.getOption(r,"timeout",e._timeout$),this._endWritable=!!d.getOption(r,"endWritable",!0),this._prefix=Ge(r.scope);var n=e._cache$,o=e._svc$,s=r.serverHash;s||(s=o.hash);var f=n[s];f||(s=o.hash,f=n[s]=new V(o,o,s)),this._adapter=f,this._registry=new A(this,te),this.pending=0,this.destroyed=!1,this.draining=!1,this.once("_eot",function(y,S){P("client channel EOT"),this.destroyed=!0,this.emit("eot",y,S)})}T.inherits(E,g.EventEmitter),E.prototype.destroy=function(e){P("destroying client channel"),this.draining||(this.draining=!0,this.emit("_drain"));var r=this._registry,n=this.pending;e&&r.clear(),e||!n?ke(e)?(P("fatal client channel error: %s",e),this.emit("_eot",n,e)):this.emit("_eot",n):P("client channel entering drain mode (%s pending)",n)},E.prototype.ping=function(e,r){!r&&typeof e=="function"&&(r=e,e=void 0);var n=this,o=new c(M);this._emit(o,{timeout:e},function(s){r?r.call(n,s):s&&n.destroy(s)})},E.prototype._createHandshakeRequest=function(e,r){var n=this.client._svc$;return{clientHash:n.hash,clientProtocol:r?null:JSON.stringify(n.protocol),serverHash:e._hash}},E.prototype._emit=function(e,r,n){var o=e._msg,s=o.oneWay?void 0:new p(o,{}),f=new b(o,this),y=this;this.pending++,process.nextTick(function(){if(!o.name)S(e,s,$);else{y.emit("outgoingCall",f,r);var F=y.client._fns$;P("starting client middleware chain (%s middleware)",F.length),i({fns:F,ctx:f,wreq:e,wres:s,onTransition:S,onCompletion:$,onError:L})}});function S(F,W,B){var H,Y;if(y.destroyed)H=new Error("channel destroyed");else try{Y=F.toBuffer()}catch{H=Fe(Q("invalid %j request",o.name),F,[{name:"headers",type:a},{name:"request",type:o.requestType}])}if(H){B(H);return}var ne=r&&r.timeout!==void 0?r.timeout:y.timeout,ae=y._registry.add(ne,function(ce,we,ye){if(!ce&&!o.oneWay)try{ye._decodeResponse(we,W,o)}catch(be){ce=be}B(ce)});ae|=y._prefix,P("sending message %s",ae),y._send(ae,Y,!!o&&o.oneWay)}function $(F){y.pending--,n.call(f,F,s),y.draining&&!y.destroyed&&!y.pending&&y.destroy()}function L(F){y.client.emit("error",F,y)}},E.prototype._getAdapter=function(e){var r=e.serverHash,n=this.client._cache$,o=n[r];if(o)return o;var s=JSON.parse(e.serverProtocol),f=D.forProtocol(s);return o=new V(this.client._svc$,f,r,!0),n[r]=o},E.prototype._matchesPrefix=function(e){return Ke(e,this._prefix)},E.prototype._send=d.abstractFunction,d.addDeprecatedGetters(E,["pending","timeout"]),E.prototype.getCache=T.deprecate(function(){return this.client._cache$},"use `.remoteProtocols()` instead of `.getCache()`"),E.prototype.getProtocol=T.deprecate(function(){return this.client._svc$},"use `.service` instead or `.getProtocol()`"),E.prototype.isDestroyed=T.deprecate(function(){return this.destroyed},"use `.destroyed` instead of `.isDestroyed`");function k(e,r,n){E.call(this,e,n),this._writableFactory=r,(!n||!n.noPing)&&(P("emitting ping request"),this.ping())}T.inherits(k,E),k.prototype._send=function(e,r){var n=this._registry.get(e),o=this._adapter,s=this;return process.nextTick(f),!0;function f(y){if(!s.destroyed){var S=s._createHandshakeRequest(o,!y),$=s._writableFactory.call(s,function(L,F){if(L){n(L);return}F.on("data",function(W){P("received response %s",W.id);var B=v.concat(W.payload);try{var H=ge(z,B),Y=H.head;Y.serverHash&&(o=s._getAdapter(Y))}catch(ae){n(ae);return}var ne=Y.match;P("handshake match: %s",ne),s.emit("handshake",S,Y),ne==="NONE"?process.nextTick(function(){f(!0)}):(s._adapter=o,n(null,H.tail,o))})});if(!$){n(new Error("invalid writable stream"));return}$.write({id:e,payload:[j.toBuffer(S),r]}),s._endWritable&&$.end()}}};function N(e,r,n,o){E.call(this,e,o),this._readable=r,this._writable=n,this._connected=!!(o&&o.noPing),this._readable.on("end",F),this._writable.on("finish",W);var s=this,f=null;this.once("eot",function(){f&&(clearTimeout(f),f=null),s._connected||s.emit("_ready"),this._writable.removeListener("finish",W),this._endWritable&&(P("ending transport"),this._writable.end()),this._readable.removeListener("data",$).removeListener("data",L).removeListener("end",F)});var y;this._connected?this._readable.on("data",L):(this._readable.on("data",$),process.nextTick(S),s.timeout&&(f=setTimeout(function(){s.destroy(new Error("timeout"))},s.timeout)));function S(B){if(!s.destroyed){y=s._createHandshakeRequest(s._adapter,!B);var H=[j.toBuffer(y),d.bufferFrom([0,0])];s._writable.write({id:s._prefix,payload:H})}}function $(B){if(!s._matchesPrefix(B.id)){P("discarding unscoped response %s (still connecting)",B.id);return}var H=v.concat(B.payload);try{var Y=ge(z,H).head;Y.serverHash&&(s._adapter=s._getAdapter(Y))}catch(ae){s.destroy(ae);return}var ne=Y.match;P("handshake match: %s",ne),s.emit("handshake",y,Y),ne==="NONE"?process.nextTick(function(){S(!0)}):(P("successfully connected"),f&&(clearTimeout(f),f=null),s._readable.removeListener("data",$).on("data",L),s._connected=!0,s.emit("_ready"),y=null)}function L(B){var H=B.id;if(!s._matchesPrefix(H)){P("discarding unscoped message %s",H);return}var Y=s._registry.get(H);Y&&process.nextTick(function(){P("received message %s",H),Y(null,v.concat(B.payload),s._adapter)})}function F(){s.destroy(!0)}function W(){s.destroy()}}T.inherits(N,E),N.prototype._emit=function(){if(this._connected||this.draining)E.prototype._emit.apply(this,arguments);else{P("queuing request");var e=[],r,n;for(r=0,n=arguments.length;r>>(r|0),this._id=0,this._n=0,this._cbs={}}A.prototype.get=function(e){return this._cbs[e&this._mask]},A.prototype.add=function(e,r){this._id=this._id+1&this._mask;var n=this,o=this._id,s;return e>0&&(s=setTimeout(function(){f(new Error("timeout"))},e)),this._cbs[o]=f,this._n++,o;function f(){n._cbs[o]&&(delete n._cbs[o],n._n--,s&&clearTimeout(s),r.apply(n._ctx,arguments))}},A.prototype.clear=function(){Object.keys(this._cbs).forEach(function(e){this._cbs[e](new Error("interrupted"))},this)};function V(e,r,n,o){this._clientSvc=e,this._serverSvc=r,this._hash=n,this._isRemote=!!o,this._readers=$e(e,r)}V.prototype._decodeRequest=function(e){var r=new R(e),n=a._read(r),o=w._read(r),s,f;if(o?(s=this._serverSvc.message(o),f=this._readers[o+"?"]._read(r)):s=M,!r.isValid())throw new Error(Q("truncated %s request",o||"ping$"));return new c(s,n,f)},V.prototype._decodeResponse=function(e,r,n){var o=new R(e);d.copyOwnProperties(a._read(o),r.headers,!0);var s=m._read(o),f=n.name;if(f){var y=this._readers[f+(s?"*":"!")];if(n=this._clientSvc.message(f),s?r.error=y._read(o):r.response=y._read(o),!o.isValid())throw new Error(Q("truncated %s response",f))}else n=M};function ee(){O.Transform.call(this,{readableObjectMode:!0}),this._id=void 0,this._buf=d.newBuffer(0),this._bufs=[],this.on("finish",function(){this.push(null)})}T.inherits(ee,O.Transform),ee.prototype._transform=function(e,r,n){e=v.concat([this._buf,e]);for(var o;e.length>=4&&e.length>=(o=e.readInt32BE(0))+4;){if(o)this._bufs.push(e.slice(4,o+4));else{var s=this._bufs;this._bufs=[],this.push({id:null,payload:s})}e=e.slice(o+4)}this._buf=e,n()},ee.prototype._flush=function(e){if(this._buf.length||this._bufs.length){var r=this._bufs.slice();r.unshift(this._buf);var n=Te("TRAILING_DATA");n.trailingData=v.concat(r).toString(),this.emit("error",n)}e()};function J(){O.Transform.call(this,{writableObjectMode:!0}),this.on("finish",function(){this.push(null)})}T.inherits(J,O.Transform),J.prototype._transform=function(e,r,n){var o=e.payload,s,f,y;for(s=0,f=o.length;s=4&&e.length>=(o=e.readInt32BE(0))+4;)this._frameCount--,this._bufs.push(e.slice(4,o+4)),e=e.slice(o+4);if(this._frameCount){this._buf=e,n();return}else{var s={id:this._id,payload:this._bufs};this._bufs=[],this._id=void 0,this.push(s)}}},he.prototype._flush=ee.prototype._flush;function pe(){O.Transform.call(this,{writableObjectMode:!0}),this.on("finish",function(){this.push(null)})}T.inherits(pe,O.Transform),pe.prototype._transform=function(e,r,n){var o=e.payload,s=o.length,f;f=d.newBuffer(8),f.writeInt32BE(e.id,0),f.writeInt32BE(s,4),this.push(f);var y;for(y=0;y>32-te===0}function Je(e){return!!(e&&e.pipe)}function t(e,r){var n=e.message(r);if(!n)throw new Error(Q("unknown message: %s",r));return n}function i(e){var r=[e.wreq,e.wres],n=[],o;s(0);function s(y){var S=!1;y1)throw new Error("union annotations are not supported");return this._readUnion();default:var w=this._typeRefs[m.type];return w&&(delete m.type,d.copyOwnProperties(w,m)),Object.keys(m).length>1?m:m.type}},C.prototype._readFixed=function(m){var a=this._tk;return a.next({val:"(",silent:!0})||(m.name=a.next({id:"name"}).val,a.next({val:"("})),m.size=parseInt(a.next({id:"number"}).val),a.next({val:")"}),m},C.prototype._readMap=function(m){var a=this._tk,w=this._implicitTags,j=a.next({val:"<",silent:w})===void 0;return m.values=this._readType(),a.next({val:">",silent:j}),m},C.prototype._readArray=function(m){var a=this._tk,w=this._implicitTags,j=a.next({val:"<",silent:w})===void 0;return m.items=this._readType(),a.next({val:">",silent:j}),m},C.prototype._readEnum=function(m,a){var w=this._tk;w.next({val:"{",silent:!0})||(m.name=w.next({id:"name"}).val,w.next({val:"{"})),m.symbols=[];do m.symbols.push(w.next().val);while(!w.next({val:"}",silent:!0})&&w.next({val:","}));return a&&w.next({val:"=",silent:!0})&&(m.default=w.next().val,w.next({val:";"})),m},C.prototype._readUnion=function(){var m=this._tk,a=[];m.next({val:"{"});do a.push(this._readType());while(!m.next({val:"}",silent:!0})&&m.next({val:","}));return a},C.prototype._readRecord=function(m){var a=this._tk;for(a.next({val:"{",silent:!0})||(m.name=a.next({id:"name"}).val,a.next({val:"{"})),m.fields=[];!a.next({val:"}",silent:!0});)m.fields.push(this._readField()),a.next({val:";"});return m},C.prototype._readImports=function(m,a){for(var w=this._tk,j=0,z=w.pos;w.next({val:"import",silent:!0});){if(!j&&a&&w.next({val:"(",silent:!0})){w.pos=z;return}var te=w.next({id:"name"}).val,M=JSON.parse(w.next({id:"string"}).val);w.next({val:";"}),m.push({kind:te,name:M}),j++}return j};function P(m){this._str=m,this.pos=0}P.prototype.next=function(m){var a={pos:this.pos,id:void 0,val:void 0},w=this._skip(m&&m.emitJavadoc);if(typeof w=="string")a.id="javadoc",a.val=w;else{var j=this.pos,z=this._str,te=z.charAt(j);if(!te)a.id="(eof)";else if(m&&m.id==="json"?(a.id="json",this.pos=this._endOfJson()):te==='"'?(a.id="string",this.pos=this._endOfString()):/[0-9]/.test(te)?(a.id="number",this.pos=this._endOf(/[0-9]/)):/[`A-Za-z_.]/.test(te)?(a.id="name",this.pos=this._endOf(/[`A-Za-z0-9_.]/)):(a.id="operator",this.pos=j+1),a.val=z.slice(j,this.pos),a.id==="json")try{a.val=JSON.parse(a.val)}catch{throw this.error("invalid JSON",a)}else a.id==="name"&&(a.val=a.val.replace(/`/g,""))}var M;if(m&&m.id&&m.id!==a.id?M=this.error(O("expected ID %s",m.id),a):m&&m.val&&m.val!==a.val&&(M=this.error(O("expected value %s",m.val),a)),M)if(m&&m.silent){this.pos=a.pos;return}else throw M;else return a},P.prototype.error=function(m,a){var w=typeof a!="number",j=w?a.pos:a,z=this._str,te=1,M=0,G;for(G=0;G>>(r|0),this._id=0,this._n=0,this._cbs={}}A.prototype.get=function(e){return this._cbs[e&this._mask]},A.prototype.add=function(e,r){this._id=this._id+1&this._mask;var n=this,o=this._id,s;return e>0&&(s=setTimeout(function(){f(new Error("timeout"))},e)),this._cbs[o]=f,this._n++,o;function f(){n._cbs[o]&&(delete n._cbs[o],n._n--,s&&clearTimeout(s),r.apply(n._ctx,arguments))}},A.prototype.clear=function(){Object.keys(this._cbs).forEach(function(e){this._cbs[e](new Error("interrupted"))},this)};function V(e,r,n,o){this._clientSvc=e,this._serverSvc=r,this._hash=n,this._isRemote=!!o,this._readers=Ce(e,r)}V.prototype._decodeRequest=function(e){var r=new R(e),n=a._read(r),o=w._read(r),s,f;if(o?(s=this._serverSvc.message(o),f=this._readers[o+"?"]._read(r)):s=M,!r.isValid())throw new Error(Y("truncated %s request",o||"ping$"));return new c(s,n,f)},V.prototype._decodeResponse=function(e,r,n){var o=new R(e);d.copyOwnProperties(a._read(o),r.headers,!0);var s=m._read(o),f=n.name;if(f){var y=this._readers[f+(s?"*":"!")];if(n=this._clientSvc.message(f),s?r.error=y._read(o):r.response=y._read(o),!o.isValid())throw new Error(Y("truncated %s response",f))}else n=M};function Z(){O.Transform.call(this,{readableObjectMode:!0}),this._id=void 0,this._buf=d.newBuffer(0),this._bufs=[],this.on("finish",function(){this.push(null)})}T.inherits(Z,O.Transform),Z.prototype._transform=function(e,r,n){e=v.concat([this._buf,e]);for(var o;e.length>=4&&e.length>=(o=e.readInt32BE(0))+4;){if(o)this._bufs.push(e.slice(4,o+4));else{var s=this._bufs;this._bufs=[],this.push({id:null,payload:s})}e=e.slice(o+4)}this._buf=e,n()},Z.prototype._flush=function(e){if(this._buf.length||this._bufs.length){var r=this._bufs.slice();r.unshift(this._buf);var n=Te("TRAILING_DATA");n.trailingData=v.concat(r).toString(),this.emit("error",n)}e()};function K(){O.Transform.call(this,{writableObjectMode:!0}),this.on("finish",function(){this.push(null)})}T.inherits(K,O.Transform),K.prototype._transform=function(e,r,n){var o=e.payload,s,f,y;for(s=0,f=o.length;s=4&&e.length>=(o=e.readInt32BE(0))+4;)this._frameCount--,this._bufs.push(e.slice(4,o+4)),e=e.slice(o+4);if(this._frameCount){this._buf=e,n();return}else{var s={id:this._id,payload:this._bufs};this._bufs=[],this._id=void 0,this.push(s)}}},ce.prototype._flush=Z.prototype._flush;function pe(){O.Transform.call(this,{writableObjectMode:!0}),this.on("finish",function(){this.push(null)})}T.inherits(pe,O.Transform),pe.prototype._transform=function(e,r,n){var o=e.payload,s=o.length,f;f=d.newBuffer(8),f.writeInt32BE(e.id,0),f.writeInt32BE(s,4),this.push(f);var y;for(y=0;y>32-ee===0}function Je(e){return!!(e&&e.pipe)}function t(e,r){var n=e.message(r);if(!n)throw new Error(Y("unknown message: %s",r));return n}function i(e){var r=[e.wreq,e.wres],n=[],o;s(0);function s(y){var k=!1;y1)throw new Error("union annotations are not supported");return this._readUnion();default:var w=this._typeRefs[m.type];return w&&(delete m.type,d.copyOwnProperties(w,m)),Object.keys(m).length>1?m:m.type}},$.prototype._readFixed=function(m){var a=this._tk;return a.next({val:"(",silent:!0})||(m.name=a.next({id:"name"}).val,a.next({val:"("})),m.size=parseInt(a.next({id:"number"}).val),a.next({val:")"}),m},$.prototype._readMap=function(m){var a=this._tk,w=this._implicitTags,j=a.next({val:"<",silent:w})===void 0;return m.values=this._readType(),a.next({val:">",silent:j}),m},$.prototype._readArray=function(m){var a=this._tk,w=this._implicitTags,j=a.next({val:"<",silent:w})===void 0;return m.items=this._readType(),a.next({val:">",silent:j}),m},$.prototype._readEnum=function(m,a){var w=this._tk;w.next({val:"{",silent:!0})||(m.name=w.next({id:"name"}).val,w.next({val:"{"})),m.symbols=[];do m.symbols.push(w.next().val);while(!w.next({val:"}",silent:!0})&&w.next({val:","}));return a&&w.next({val:"=",silent:!0})&&(m.default=w.next().val,w.next({val:";"})),m},$.prototype._readUnion=function(){var m=this._tk,a=[];m.next({val:"{"});do a.push(this._readType());while(!m.next({val:"}",silent:!0})&&m.next({val:","}));return a},$.prototype._readRecord=function(m){var a=this._tk;for(a.next({val:"{",silent:!0})||(m.name=a.next({id:"name"}).val,a.next({val:"{"})),m.fields=[];!a.next({val:"}",silent:!0});)m.fields.push(this._readField()),a.next({val:";"});return m},$.prototype._readImports=function(m,a){for(var w=this._tk,j=0,z=w.pos;w.next({val:"import",silent:!0});){if(!j&&a&&w.next({val:"(",silent:!0})){w.pos=z;return}var ee=w.next({id:"name"}).val,M=JSON.parse(w.next({id:"string"}).val);w.next({val:";"}),m.push({kind:ee,name:M}),j++}return j};function P(m){this._str=m,this.pos=0}P.prototype.next=function(m){var a={pos:this.pos,id:void 0,val:void 0},w=this._skip(m&&m.emitJavadoc);if(typeof w=="string")a.id="javadoc",a.val=w;else{var j=this.pos,z=this._str,ee=z.charAt(j);if(!ee)a.id="(eof)";else if(m&&m.id==="json"?(a.id="json",this.pos=this._endOfJson()):ee==='"'?(a.id="string",this.pos=this._endOfString()):/[0-9]/.test(ee)?(a.id="number",this.pos=this._endOf(/[0-9]/)):/[`A-Za-z_.]/.test(ee)?(a.id="name",this.pos=this._endOf(/[`A-Za-z0-9_.]/)):(a.id="operator",this.pos=j+1),a.val=z.slice(j,this.pos),a.id==="json")try{a.val=JSON.parse(a.val)}catch{throw this.error("invalid JSON",a)}else a.id==="name"&&(a.val=a.val.replace(/`/g,""))}var M;if(m&&m.id&&m.id!==a.id?M=this.error(O("expected ID %s",m.id),a):m&&m.val&&m.val!==a.val&&(M=this.error(O("expected value %s",m.val),a)),M)if(m&&m.silent){this.pos=a.pos;return}else throw M;else return a},P.prototype.error=function(m,a){var w=typeof a!="number",j=w?a.pos:a,z=this._str,ee=1,M=0,G;for(G=0;G"u"&&typeof Tt>"u"&&console.error("ultralight-S3 Module: Crypto functions are not available, please report the issue with necessary description: https://github.com/sentienhq/ultralight-s3/issues");var Xt={contents:!0},Zt=u=>`%${u.charCodeAt(0).toString(16).toUpperCase()}`,it=u=>encodeURIComponent(u).replace(/[!'()*]/g,Zt),me=u=>it(u).replace(/%2F/g,"/"),er=class{constructor({accessKeyId:u,secretAccessKey:l,endpoint:h,bucketName:d,region:_="auto",maxRequestSizeInBytes:g=5242880,requestAbortTimeout:O=void 0,logger:T=void 0}){this.getBucketName=()=>this.bucketName,this.setBucketName=v=>{this.bucketName=v},this.getRegion=()=>this.region,this.setRegion=v=>{this.region=v},this.getEndpoint=()=>this.endpoint,this.setEndpoint=v=>{this.endpoint=v},this.getMaxRequestSizeInBytes=()=>this.maxRequestSizeInBytes,this.setMaxRequestSizeInBytes=v=>{this.maxRequestSizeInBytes=v},this.sanitizeETag=v=>Ve(v),this.getProps=()=>({accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey,region:this.region,bucket:this.bucketName,endpoint:this.endpoint,maxRequestSizeInBytes:this.maxRequestSizeInBytes,requestAbortTimeout:this.requestAbortTimeout,logger:this.logger}),this.setProps=v=>{this._validateConstructorParams(v.accessKeyId,v.secretAccessKey,v.bucketName,v.endpoint),this.accessKeyId=v.accessKeyId,this.secretAccessKey=v.secretAccessKey,this.region=v.region||"auto",this.bucketName=v.bucketName,this.endpoint=v.endpoint,this.maxRequestSizeInBytes=v.maxRequestSizeInBytes||5242880,this.requestAbortTimeout=v.requestAbortTimeout,this.logger=v.logger},this._validateConstructorParams(u,l,h,d),this.accessKeyId=u,this.secretAccessKey=l,this.endpoint=h,this.bucketName=d,this.region=_,this.maxRequestSizeInBytes=g,this.requestAbortTimeout=O,this.logger=T}_validateConstructorParams(u,l,h,d){if(typeof u!="string"||u.trim().length===0)throw new TypeError(Jt);if(typeof l!="string"||l.trim().length===0)throw new TypeError(Wt);if(typeof h!="string"||h.trim().length===0)throw new TypeError(Yt);if(typeof d!="string"||d.trim().length===0)throw new TypeError(Qt)}_checkMethodHeadnGet(u){if(u!=="GET"&&u!=="HEAD")throw this._log("error",`${se}method must be either GET or HEAD`),new Error("method must be either GET or HEAD")}_checkKey(u){if(typeof u!="string"||u.trim().length===0)throw this._log("error",ht),new TypeError(ht)}_checkDelimiter(u){if(typeof u!="string"||u.trim().length===0)throw this._log("error",yt),new TypeError(yt)}_checkPrefix(u){if(typeof u!="string")throw this._log("error",pt),new TypeError(pt)}_checkMaxKeys(u){if(typeof u!="number"||u<=0)throw this._log("error",dt),new TypeError(dt)}_checkOpts(u){if(typeof u!="object")throw this._log("error",`${se}opts must be an object`),new TypeError(`${se}opts must be an object`)}_log(u,l,h={}){if(this.logger&&typeof this.logger[u]=="function"){let d=O=>typeof O!="object"||O===null?O:Object.keys(O).reduce((T,v)=>(Ut.includes(v.toLowerCase())?T[v]="[REDACTED]":typeof O[v]=="object"&&O[v]!==null?T[v]=d(O[v]):T[v]=O[v],T),Array.isArray(O)?[]:{}),_=d(h),g={timestamp:new Date().toISOString(),level:u,message:l,..._,context:d({bucketName:this.bucketName,region:this.region,endpoint:this.endpoint,accessKeyId:this.accessKeyId?`${this.accessKeyId.substring(0,4)}...`:void 0})};this.logger[u](g)}}async getContentLength(u){this._checkKey(u);let l={[de]:_e},h=me(u),{url:d,headers:_}=await this._sign("HEAD",h,{},l,""),g=(await this._sendRequest(d,"HEAD",_)).headers.get(Ne);return g?parseInt(g,10):0}async bucketExists(){let u={[de]:_e},{url:l,headers:h}=await this._sign("HEAD","",{},u,""),d=await this._sendRequest(l,"HEAD",h,"",[200,404,403]);return this._log("error",`Response status: ${d.status,d.statusText}`),!!(d.ok&&d.status===200)}async createBucket(){let u=`
+`)}function te(m){if(m.namespace)return m.namespace;var a=/^(.*)\.[^.]+$/.exec(m.protocol);return a?a[1]:void 0}l.exports={Tokenizer:P,assembleProtocol:v,read:R,readProtocol:$.readProtocol,readSchema:$.readSchema}}}),Ht=Ie({"node_modules/avsc/lib/index.js"(u,l){"use strict";var h=Dt(),d=jt(),_=Mt(),g=ot(),O=ze(),T=Ue,v=mt,R=De,$=T.Buffer;function P(a,w){var j=_.read(a);return j.protocol?d.Service.forProtocol(j,w):g.Type.forSchema(j,w)}function Y(a,w){w=w||{};var j=w.decode===void 0?!0:!!w.decode,z=Math.max(w.size||4096,4),ee=O.newBuffer(z),M=v.openSync(a,"r");try{var G=v.readSync(M,ee,0,z);if(G<4||!h.MAGIC_BYTES.equals(ee.slice(0,4)))return null;var D=new O.Tap(ee),Q=null;do Q=h.HEADER_TYPE._read(D);while(!ne());if(j!==!1){var q=Q.meta;q["avro.schema"]=JSON.parse(q["avro.schema"].toString()),q["avro.codec"]!==void 0&&(q["avro.codec"]=q["avro.codec"].toString())}return Q}finally{v.closeSync(M)}function ne(){if(D.isValid())return!0;var E=2*D.buf.length,S=O.newBuffer(E);return E=v.readSync(M,S,0,E),D.buf=$.concat([D.buf,S]),D.pos=0,!1}}function te(a,w){return v.createReadStream(a).pipe(new h.streams.BlockDecoder(w))}function m(a,w,j){var z=new h.streams.BlockEncoder(w,j);return z.pipe(v.createWriteStream(a,{defaultEncoding:"binary"})),z}l.exports={Service:d.Service,Type:g.Type,assembleProtocol:_.assembleProtocol,createFileDecoder:te,createFileEncoder:m,discoverProtocol:d.discoverProtocol,extractFileHeader:Y,parse:P,readProtocol:_.readProtocol,readSchema:_.readSchema,streams:h.streams,types:g.builtins,Protocol:d.Service,assemble:R.deprecate(_.assembleProtocol,"use `assembleProtocol` instead"),combine:R.deprecate(g.Type.forTypes,"use `Type.forTypes` intead"),infer:R.deprecate(g.Type.forValue,"use `Type.forValue` instead")}}}),at="AWS4-HMAC-SHA256",Xe="aws4_request",Ze="s3",Vt="2",_e="UNSIGNED-PAYLOAD",qt="application/octet-stream",et="application/xml",Ne="application/json",Ut=["accessKeyId","secretAccessKey","sessionToken","password"],de="x-amz-content-sha256",zt="x-amz-date",Gt="host",Kt="Authorization",Ee="Content-Type",Ae="Content-Length",ut="etag",ct="last-modified",oe="ultralight-s3 Module: ",Jt=`${oe}accessKeyId must be a non-empty string`,Wt=`${oe}secretAccessKey must be a non-empty string`,Yt=`${oe}endpoint must be a non-empty string`,Qt=`${oe}bucketName must be a non-empty string`,ht=`${oe}key must be a non-empty string`,Pe=`${oe}uploadId must be a non-empty string`,ft=`${oe}parts must be a non-empty array`,lt=`${oe}Each part must have a partNumber (number) and ETag (string)`,We=`${oe}data must be a Buffer or string`,pt=`${oe}prefix must be a string`,dt=`${oe}maxKeys must be a positive integer`,yt=`${oe}delimiter must be a string`,Et=crypto.createHmac||(await import("node:crypto")).createHmac,Tt=crypto.createHash||(await import("node:crypto")).createHash;typeof Et>"u"&&typeof Tt>"u"&&console.error("ultralight-S3 Module: Crypto functions are not available, please report the issue with necessary description: https://github.com/sentienhq/ultralight-s3/issues");var Xt={contents:!0},Zt=u=>`%${u.charCodeAt(0).toString(16).toUpperCase()}`,it=u=>encodeURIComponent(u).replace(/[!'()*]/g,Zt),me=u=>it(u).replace(/%2F/g,"/"),er=class{constructor({accessKeyId:u,secretAccessKey:l,endpoint:h,bucketName:d,region:_="auto",maxRequestSizeInBytes:g=5242880,requestAbortTimeout:O=void 0,logger:T=void 0}){this.getBucketName=()=>this.bucketName,this.setBucketName=v=>{this.bucketName=v},this.getRegion=()=>this.region,this.setRegion=v=>{this.region=v},this.getEndpoint=()=>this.endpoint,this.setEndpoint=v=>{this.endpoint=v},this.getMaxRequestSizeInBytes=()=>this.maxRequestSizeInBytes,this.setMaxRequestSizeInBytes=v=>{this.maxRequestSizeInBytes=v},this.sanitizeETag=v=>Ve(v),this.getProps=()=>({accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey,region:this.region,bucket:this.bucketName,endpoint:this.endpoint,maxRequestSizeInBytes:this.maxRequestSizeInBytes,requestAbortTimeout:this.requestAbortTimeout,logger:this.logger}),this.setProps=v=>{this._validateConstructorParams(v.accessKeyId,v.secretAccessKey,v.bucketName,v.endpoint),this.accessKeyId=v.accessKeyId,this.secretAccessKey=v.secretAccessKey,this.region=v.region||"auto",this.bucketName=v.bucketName,this.endpoint=v.endpoint,this.maxRequestSizeInBytes=v.maxRequestSizeInBytes||5242880,this.requestAbortTimeout=v.requestAbortTimeout,this.logger=v.logger},this._validateConstructorParams(u,l,h,d),this.accessKeyId=u,this.secretAccessKey=l,this.endpoint=h,this.bucketName=d,this.region=_,this.maxRequestSizeInBytes=g,this.requestAbortTimeout=O,this.logger=T}_validateConstructorParams(u,l,h,d){if(typeof u!="string"||u.trim().length===0)throw new TypeError(Jt);if(typeof l!="string"||l.trim().length===0)throw new TypeError(Wt);if(typeof h!="string"||h.trim().length===0)throw new TypeError(Yt);if(typeof d!="string"||d.trim().length===0)throw new TypeError(Qt)}_checkMethodHeadnGet(u){if(u!=="GET"&&u!=="HEAD")throw this._log("error",`${oe}method must be either GET or HEAD`),new Error("method must be either GET or HEAD")}_checkKey(u){if(typeof u!="string"||u.trim().length===0)throw this._log("error",ht),new TypeError(ht)}_checkDelimiter(u){if(typeof u!="string"||u.trim().length===0)throw this._log("error",yt),new TypeError(yt)}_checkPrefix(u){if(typeof u!="string")throw this._log("error",pt),new TypeError(pt)}_checkMaxKeys(u){if(typeof u!="number"||u<=0)throw this._log("error",dt),new TypeError(dt)}_checkOpts(u){if(typeof u!="object")throw this._log("error",`${oe}opts must be an object`),new TypeError(`${oe}opts must be an object`)}_log(u,l,h={}){if(this.logger&&typeof this.logger[u]=="function"){let d=O=>typeof O!="object"||O===null?O:Object.keys(O).reduce((T,v)=>(Ut.includes(v.toLowerCase())?T[v]="[REDACTED]":typeof O[v]=="object"&&O[v]!==null?T[v]=d(O[v]):T[v]=O[v],T),Array.isArray(O)?[]:{}),_=d(h),g={timestamp:new Date().toISOString(),level:u,message:l,..._,context:d({bucketName:this.bucketName,region:this.region,endpoint:this.endpoint,accessKeyId:this.accessKeyId?`${this.accessKeyId.substring(0,4)}...`:void 0})};this.logger[u](g)}}async getContentLength(u){this._checkKey(u);let l={[de]:_e},h=me(u),{url:d,headers:_}=await this._sign("HEAD",h,{},l,""),g=(await this._sendRequest(d,"HEAD",_)).headers.get(Ae);return g?parseInt(g,10):0}async bucketExists(){let u={[de]:_e},{url:l,headers:h}=await this._sign("HEAD","",{},u,""),d=await this._sendRequest(l,"HEAD",h,"",[200,404,403]);return this._log("error",`Response status: ${d.status,d.statusText}`),!!(d.ok&&d.status===200)}async createBucket(){let u=`
${this.region}
- `,l={[Ee]:et,[Ne]:Buffer.byteLength(u).toString(),[de]:await Me(u)},h=encodeURI(""),{url:d,headers:_}=await this._sign("PUT",h,{},l,""),g=await this._sendRequest(d,"PUT",_,u,[200,404,403]);return!!(g.ok&&g.status===200)}async fileExists(u,l={}){this._checkKey(u);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("HEAD",g,h,_,"");try{let v=await this._sendRequest(O,"HEAD",T,"",[200,404,412,304]);return v.status===404?!1:v.status===412||v.status===304?null:v.ok&&v.status===200?!0:(this._handleErrorResponse(v),!1)}catch(v){let R=v instanceof Error?v.message:String(v);throw this._log("error",`${se}Failed to check if file exists: ${R}`),new Error(`${se}Failed to check if file exists: ${R}`)}}async _sign(u,l,h={},d,_){let g=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),O=typeof l=="string"&&l.length>0?new URL(l,this.endpoint):new URL(this.endpoint);O.pathname=`/${encodeURI(this.bucketName)}${O.pathname}`,d[de]=_?await Me(_):_e,d[zt]=g,d[Gt]=O.host;let T=this._buildCanonicalHeaders(d),v=Object.keys(d).map(re=>re.toLowerCase()).sort().join(";"),R=await this._buildCanonicalRequest(u,O,h,T,v,_),C=await this._buildStringToSign(g,R),P=await this._calculateSignature(g,C),Q=this._buildAuthorizationHeader(g,v,P);return d[Kt]=Q,{url:O.toString(),headers:d}}_buildCanonicalHeaders(u){return Object.entries(u).map(([l,h])=>`${l.toLowerCase()}:${String(h).trim()}`).sort().join(`
+ `,l={[Ee]:et,[Ae]:Buffer.byteLength(u).toString(),[de]:await Me(u)},h=encodeURI(""),{url:d,headers:_}=await this._sign("PUT",h,{},l,""),g=await this._sendRequest(d,"PUT",_,u,[200,404,403]);return!!(g.ok&&g.status===200)}async fileExists(u,l={}){this._checkKey(u);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("HEAD",g,h,_,"");try{let v=await this._sendRequest(O,"HEAD",T,"",[200,404,412,304]);return v.status===404?!1:v.status===412||v.status===304?null:v.ok&&v.status===200?!0:(this._handleErrorResponse(v),!1)}catch(v){let R=v instanceof Error?v.message:String(v);throw this._log("error",`${oe}Failed to check if file exists: ${R}`),new Error(`${oe}Failed to check if file exists: ${R}`)}}async _sign(u,l,h={},d,_){let g=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),O=typeof l=="string"&&l.length>0?new URL(l,this.endpoint):new URL(this.endpoint);O.pathname=`/${encodeURI(this.bucketName)}${O.pathname}`,d[de]=_?await Me(_):_e,d[zt]=g,d[Gt]=O.host;let T=this._buildCanonicalHeaders(d),v=Object.keys(d).map(te=>te.toLowerCase()).sort().join(";"),R=await this._buildCanonicalRequest(u,O,h,T,v,_),$=await this._buildStringToSign(g,R),P=await this._calculateSignature(g,$),Y=this._buildAuthorizationHeader(g,v,P);return d[Kt]=Y,{url:O.toString(),headers:d}}_buildCanonicalHeaders(u){return Object.entries(u).map(([l,h])=>`${l.toLowerCase()}:${String(h).trim()}`).sort().join(`
`)}async _buildCanonicalRequest(u,l,h,d,_,g){return[u,l.pathname,this._buildCanonicalQueryString(h),`${d}
`,_,g?await Me(g):_e].join(`
`)}async _buildStringToSign(u,l){let h=[u.slice(0,8),this.region,Ze,Xe].join("/");return[at,u,h,await Me(l)].join(`
-`)}async _calculateSignature(u,l){let h=await this._getSignatureKey(u.slice(0,8));return He(h,l,"hex")}_buildAuthorizationHeader(u,l,h){let d=[u.slice(0,8),this.region,Ze,Xe].join("/");return[`${at} Credential=${this.accessKeyId}/${d}`,`SignedHeaders=${l}`,`Signature=${h}`].join(", ")}_filterIfHeaders(u){let l={},h={},d=["if-match","if-none-match","if-modified-since","if-unmodified-since"];for(let[_,g]of Object.entries(u))d.includes(_)?h[_]=g:l[_]=g;return{filteredOpts:l,conditionalHeaders:h}}async list(u="/",l="",h=1e3,d="GET",_={}){this._checkDelimiter(u),this._checkPrefix(l),this._checkMaxKeys(h),this._checkMethodHeadnGet(d),this._checkOpts(_),this._log("info",`Listing objects in ${l}`);let g={"list-type":Vt,"max-keys":String(h),..._};l.length>0&&(g.prefix=l);let O={[Ee]:xe,[de]:_e},T=u==="/"?u:it(u),{url:v,headers:R}=await this._sign("GET",T,g,O,""),C=`${v}?${new URLSearchParams(g)}`,P=await this._sendRequest(C,"GET",R),Q=await P.text();if(d==="HEAD"){let a=P.headers.get(Ne),w=P.headers.get(ct),j=P.headers.get(ut);return{size:a?+a:void 0,mtime:w?new Date(w):void 0,ETag:j||void 0}}let re=Be(Q),m=re.listBucketResult||re.error||re;return m.contents||m}async listMultiPartUploads(u="/",l="",h="GET",d={}){var _,g,O;this._checkDelimiter(u),this._checkPrefix(l),this._checkMethodHeadnGet(h),this._checkOpts(d),this._log("info",`Listing multipart uploads in ${l}`);let T={uploads:"",...d},v={[Ee]:xe,[de]:_e},R=u==="/"?u:it(u),{url:C,headers:P}=await this._sign("GET",R,T,v,""),Q=`${C}?${new URLSearchParams(T)}`,re=await this._sendRequest(Q,"GET",P),m=await re.text();if(h==="HEAD")return{size:+((_=re.headers.get(Ne))!==null&&_!==void 0?_:"0"),mtime:new Date((g=re.headers.get(ct))!==null&&g!==void 0?g:""),ETag:(O=re.headers.get(ut))!==null&&O!==void 0?O:""};let a=Be(m),w=a.listMultipartUploadsResult||a.error||a;return w.uploads||w}async get(u,l={}){this._checkKey(u),this._log("info",`Getting object ${u}`);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[Ee]:xe,[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("GET",g,h,_,""),v=await this._sendRequest(O,"GET",T,"",[200,404,412,304]);if(v.status===404||v.status===412||v.status===304)return this._log("error",`Failed to get object. Status: ${v.status}`),null;if(!v.ok)throw this._log("error",`Failed to get object. Status: ${v.status}`),new Error(`Failed to get object. Status: ${v.status}`);return v}async getObjectWithETag(u,l={}){this._checkKey(u),this._log("info",`Getting object ${u}`);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[Ee]:xe,[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("GET",g,h,_,"");try{let v=await this._sendRequest(O,"GET",T,"",[200,404,412,304]);if(v.status===404||v.status===412||v.status===304)return this._log("error",`Failed to get object. Status: ${v.status}`),{etag:null,data:null};if(!v.ok)throw this._log("error",`Failed to get object. Status: ${v.status}`),new Error(`Failed to get object. Status: ${v.status}`);let R=v.headers.get("etag");if(!R)throw new Error("ETag not found in response headers");let C=await v.text();return{etag:Ve(R),data:C}}catch(v){throw this._log("error",`Error getting object ${u} with ETag: ${v}`),v}}async getEtag(u,l={}){this._checkKey(u),this._log("info",`Getting etag object ${u}`);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[Ee]:xe,[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("HEAD",g,h,_,""),v=await this._sendRequest(O,"HEAD",T,"",[200,412,304]);if(this._log("info",`Response status: ${v.status,v.statusText}`),v.status===412||v.status===304)return null;let R=v.headers.get("etag");if(!R)throw this._log("error","ETag not found in response headers"),new Error("ETag not found in response headers");return Ve(R)}async getResponse(u,l=!0,h=0,d=this.maxRequestSizeInBytes,_={}){this._checkKey(u);let{filteredOpts:g,conditionalHeaders:O}=this._filterIfHeaders({..._}),T={[Ee]:xe,[de]:_e,...l?{}:{range:`bytes=${h}-${d-1}`},...O},v=me(u),{url:R,headers:C}=await this._sign("GET",v,g,T,""),P=`${R}?${new URLSearchParams(g)}`;return this._sendRequest(P,"GET",C)}async put(u,l){if(this._checkKey(u),!(l instanceof Buffer||typeof l=="string"))throw this._log("error",We),new TypeError(We);this._log("info",`Uploading object ${u}`);let h=typeof l=="string"?Buffer.byteLength(l):l.length,d={[Ne]:h},_=me(u),{url:g,headers:O}=await this._sign("PUT",_,{},d,l);return this._sendRequest(g,"PUT",O,l,[200])}async getMultipartUploadId(u,l=qt){if(this._checkKey(u),typeof l!="string")throw this._log("error",`${se}fileType must be a string`),new TypeError(`${se}fileType must be a string`);this._log("info",`Initiating multipart upload for object ${u}`);let h={uploads:""},d={[Ee]:l,[de]:_e},_=me(u),{url:g,headers:O}=await this._sign("POST",_,h,d,""),T=`${g}?${new URLSearchParams(h)}`,v=await(await this._sendRequest(T,"POST",O)).text(),R=Be(v);if(typeof R=="object"&&R!==null&&"error"in R&&typeof R.error=="object"&&R.error!==null&&"message"in R.error){let C=String(R.error.message);throw this._log("error",`${se}Failed to abort multipart upload: ${C}`),new Error(`${se}Failed to abort multipart upload: ${C}`)}if(typeof R=="object"&&R!==null){if(!R.initiateMultipartUploadResult||!R.initiateMultipartUploadResult.uploadId)throw this._log("error",`${se}Failed to create multipart upload: no uploadId in response`),new Error(`${se}Failed to create multipart upload: Missing upload ID in response`);return R.initiateMultipartUploadResult.uploadId}else throw this._log("error",`${se}Failed to create multipart upload: unexpected response format`),new Error(`${se}Failed to create multipart upload: Unexpected response format`)}async uploadPart(u,l,h,d,_={}){this._validateUploadPartParams(u,l,h,d,_);let g={uploadId:h,partNumber:d,..._},O={[Ne]:l.length},T=me(u),{url:v,headers:R}=await this._sign("PUT",T,g,O,l),C=`${v}?${new URLSearchParams(g)}`,P=await this._sendRequest(C,"PUT",R,l),Q=Ve(P.headers.get("etag")||"");return{partNumber:d,ETag:Q}}_validateUploadPartParams(u,l,h,d,_){if(this._checkKey(u),!(l instanceof Buffer||typeof l=="string"))throw this._log("error",We),new TypeError(We);if(typeof h!="string"||h.trim().length===0)throw this._log("error",Pe),new TypeError(Pe);if(!Number.isInteger(d)||d<=0)throw this._log("error",`${se}partNumber must be a positive integer`),new TypeError(`${se}partNumber must be a positive integer`);this._checkOpts(_)}async completeMultipartUpload(u,l,h){if(this._checkKey(u),typeof l!="string"||l.trim().length===0)throw this._log("error",Pe),new TypeError(Pe);if(!Array.isArray(h)||h.length===0)throw this._log("error",ft),new TypeError(ft);if(!h.every(Q=>typeof Q.partNumber=="number"&&typeof Q.ETag=="string"))throw this._log("error",lt),new TypeError(lt);this._log("info",`Complete multipart upload ${l} for object ${u}`);let d={uploadId:l},_=this._buildCompleteMultipartUploadXml(h),g={[Ee]:et,[Ne]:Buffer.byteLength(_).toString(),[de]:await Me(_)},O=me(u),{url:T,headers:v}=await this._sign("POST",O,d,g,_),R=`${T}?${new URLSearchParams(d)}`,C=await(await this._sendRequest(R,"POST",v,_)).text(),P=Be(C);if(typeof P=="object"&&P!==null&&"error"in P&&typeof P.error=="object"&&P.error!==null&&"message"in P.error){let Q=String(P.error.message);throw this._log("error",`${se}Failed to abort multipart upload: ${Q}`),new Error(`${se}Failed to abort multipart upload: ${Q}`)}return P.completeMultipartUploadResult}async abortMultipartUpload(u,l){if(this._checkKey(u),typeof l!="string"||l.trim().length===0)throw this._log("error",Pe),new TypeError(Pe);this._log("info",`Aborting multipart upload ${l} for object ${u}`);let h={uploadId:l},d={[Ee]:et,[de]:_e};try{let _=me(u),{url:g,headers:O}=await this._sign("DELETE",_,h,d,""),T=`${g}?${new URLSearchParams(h)}`,v=await this._sendRequest(T,"DELETE",O);if(v.ok){let R=await v.text(),C=Be(R);if(typeof C=="object"&&C!==null&&"error"in C&&typeof C.error=="object"&&C.error!==null&&"message"in C.error){let P=String(C.error.message);throw this._log("error",`${se}Failed to abort multipart upload: ${P}`),new Error(`${se}Failed to abort multipart upload: ${P}`)}return{status:"Aborted",key:u,uploadId:l,response:C}}else throw this._log("error",`${se}Abort request failed with status ${v.status}`),new Error(`${se}Abort request failed with status ${v.status}`)}catch(_){let g=_ instanceof Error?_.message:String(_);throw this._log("error",`${se}Failed to abort multipart upload for key ${u}: ${g}`),new Error(`${se}Failed to abort multipart upload for key ${u}: ${g}`)}}_buildCompleteMultipartUploadXml(u){return`
+`)}async _calculateSignature(u,l){let h=await this._getSignatureKey(u.slice(0,8));return He(h,l,"hex")}_buildAuthorizationHeader(u,l,h){let d=[u.slice(0,8),this.region,Ze,Xe].join("/");return[`${at} Credential=${this.accessKeyId}/${d}`,`SignedHeaders=${l}`,`Signature=${h}`].join(", ")}_filterIfHeaders(u){let l={},h={},d=["if-match","if-none-match","if-modified-since","if-unmodified-since"];for(let[_,g]of Object.entries(u))d.includes(_)?h[_]=g:l[_]=g;return{filteredOpts:l,conditionalHeaders:h}}async list(u="/",l="",h=1e3,d="GET",_={}){this._checkDelimiter(u),this._checkPrefix(l),this._checkMaxKeys(h),this._checkMethodHeadnGet(d),this._checkOpts(_),this._log("info",`Listing objects in ${l}`);let g={"list-type":Vt,"max-keys":String(h),..._};l.length>0&&(g.prefix=l);let O={[Ee]:Ne,[de]:_e},T=u==="/"?u:it(u),{url:v,headers:R}=await this._sign("GET",T,g,O,""),$=`${v}?${new URLSearchParams(g)}`,P=await this._sendRequest($,"GET",R),Y=await P.text();if(d==="HEAD"){let a=P.headers.get(Ae),w=P.headers.get(ct),j=P.headers.get(ut);return{size:a?+a:void 0,mtime:w?new Date(w):void 0,ETag:j||void 0}}let te=Be(Y),m=te.listBucketResult||te.error||te;return m.contents||m}async listMultiPartUploads(u="/",l="",h="GET",d={}){var _,g,O;this._checkDelimiter(u),this._checkPrefix(l),this._checkMethodHeadnGet(h),this._checkOpts(d),this._log("info",`Listing multipart uploads in ${l}`);let T={uploads:"",...d},v={[Ee]:Ne,[de]:_e},R=u==="/"?u:it(u),{url:$,headers:P}=await this._sign("GET",R,T,v,""),Y=`${$}?${new URLSearchParams(T)}`,te=await this._sendRequest(Y,"GET",P),m=await te.text();if(h==="HEAD")return{size:+((_=te.headers.get(Ae))!==null&&_!==void 0?_:"0"),mtime:new Date((g=te.headers.get(ct))!==null&&g!==void 0?g:""),ETag:(O=te.headers.get(ut))!==null&&O!==void 0?O:""};let a=Be(m),w=a.listMultipartUploadsResult||a.error||a;return w.uploads||w}async get(u,l={}){this._checkKey(u),this._log("info",`Getting object ${u}`);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[Ee]:Ne,[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("GET",g,h,_,""),v=await this._sendRequest(O,"GET",T,"",[200,404,412,304]);if(v.status===404||v.status===412||v.status===304)return this._log("error",`Failed to get object. Status: ${v.status}`),null;if(!v.ok)throw this._log("error",`Failed to get object. Status: ${v.status}`),new Error(`Failed to get object. Status: ${v.status}`);return v}async getObjectWithETag(u,l={}){this._checkKey(u),this._log("info",`Getting object ${u}`);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[Ee]:Ne,[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("GET",g,h,_,"");try{let v=await this._sendRequest(O,"GET",T,"",[200,404,412,304]);if(v.status===404||v.status===412||v.status===304)return this._log("error",`Failed to get object. Status: ${v.status}`),{etag:null,data:null};if(!v.ok)throw this._log("error",`Failed to get object. Status: ${v.status}`),new Error(`Failed to get object. Status: ${v.status}`);let R=v.headers.get("etag");if(!R)throw new Error("ETag not found in response headers");let $=await v.text();return{etag:Ve(R),data:$}}catch(v){throw this._log("error",`Error getting object ${u} with ETag: ${v}`),v}}async getEtag(u,l={}){this._checkKey(u),this._log("info",`Getting etag object ${u}`);let{filteredOpts:h,conditionalHeaders:d}=this._filterIfHeaders(l),_={[Ee]:Ne,[de]:_e,...d},g=me(u),{url:O,headers:T}=await this._sign("HEAD",g,h,_,""),v=await this._sendRequest(O,"HEAD",T,"",[200,412,304]);if(this._log("info",`Response status: ${v.status,v.statusText}`),v.status===412||v.status===304)return null;let R=v.headers.get("etag");if(!R)throw this._log("error","ETag not found in response headers"),new Error("ETag not found in response headers");return Ve(R)}async getResponse(u,l=!0,h=0,d=this.maxRequestSizeInBytes,_={}){this._checkKey(u);let{filteredOpts:g,conditionalHeaders:O}=this._filterIfHeaders({..._}),T={[Ee]:Ne,[de]:_e,...l?{}:{range:`bytes=${h}-${d-1}`},...O},v=me(u),{url:R,headers:$}=await this._sign("GET",v,g,T,""),P=`${R}?${new URLSearchParams(g)}`;return this._sendRequest(P,"GET",$)}async put(u,l){if(this._checkKey(u),!(l instanceof Buffer||typeof l=="string"))throw this._log("error",We),new TypeError(We);this._log("info",`Uploading object ${u}`);let h=typeof l=="string"?Buffer.byteLength(l):l.length,d={[Ae]:h},_=me(u),{url:g,headers:O}=await this._sign("PUT",_,{},d,l);return this._sendRequest(g,"PUT",O,l,[200])}async getMultipartUploadId(u,l=qt){if(this._checkKey(u),typeof l!="string")throw this._log("error",`${oe}fileType must be a string`),new TypeError(`${oe}fileType must be a string`);this._log("info",`Initiating multipart upload for object ${u}`);let h={uploads:""},d={[Ee]:l,[de]:_e},_=me(u),{url:g,headers:O}=await this._sign("POST",_,h,d,""),T=`${g}?${new URLSearchParams(h)}`,v=await(await this._sendRequest(T,"POST",O)).text(),R=Be(v);if(typeof R=="object"&&R!==null&&"error"in R&&typeof R.error=="object"&&R.error!==null&&"message"in R.error){let $=String(R.error.message);throw this._log("error",`${oe}Failed to abort multipart upload: ${$}`),new Error(`${oe}Failed to abort multipart upload: ${$}`)}if(typeof R=="object"&&R!==null){if(!R.initiateMultipartUploadResult||!R.initiateMultipartUploadResult.uploadId)throw this._log("error",`${oe}Failed to create multipart upload: no uploadId in response`),new Error(`${oe}Failed to create multipart upload: Missing upload ID in response`);return R.initiateMultipartUploadResult.uploadId}else throw this._log("error",`${oe}Failed to create multipart upload: unexpected response format`),new Error(`${oe}Failed to create multipart upload: Unexpected response format`)}async uploadPart(u,l,h,d,_={}){this._validateUploadPartParams(u,l,h,d,_);let g={uploadId:h,partNumber:d,..._},O={[Ae]:l.length},T=me(u),{url:v,headers:R}=await this._sign("PUT",T,g,O,l),$=`${v}?${new URLSearchParams(g)}`,P=await this._sendRequest($,"PUT",R,l),Y=Ve(P.headers.get("etag")||"");return{partNumber:d,ETag:Y}}_validateUploadPartParams(u,l,h,d,_){if(this._checkKey(u),!(l instanceof Buffer||typeof l=="string"))throw this._log("error",We),new TypeError(We);if(typeof h!="string"||h.trim().length===0)throw this._log("error",Pe),new TypeError(Pe);if(!Number.isInteger(d)||d<=0)throw this._log("error",`${oe}partNumber must be a positive integer`),new TypeError(`${oe}partNumber must be a positive integer`);this._checkOpts(_)}async completeMultipartUpload(u,l,h){if(this._checkKey(u),typeof l!="string"||l.trim().length===0)throw this._log("error",Pe),new TypeError(Pe);if(!Array.isArray(h)||h.length===0)throw this._log("error",ft),new TypeError(ft);if(!h.every(Y=>typeof Y.partNumber=="number"&&typeof Y.ETag=="string"))throw this._log("error",lt),new TypeError(lt);this._log("info",`Complete multipart upload ${l} for object ${u}`);let d={uploadId:l},_=this._buildCompleteMultipartUploadXml(h),g={[Ee]:et,[Ae]:Buffer.byteLength(_).toString(),[de]:await Me(_)},O=me(u),{url:T,headers:v}=await this._sign("POST",O,d,g,_),R=`${T}?${new URLSearchParams(d)}`,$=await(await this._sendRequest(R,"POST",v,_)).text(),P=Be($);if(typeof P=="object"&&P!==null&&"error"in P&&typeof P.error=="object"&&P.error!==null&&"message"in P.error){let Y=String(P.error.message);throw this._log("error",`${oe}Failed to abort multipart upload: ${Y}`),new Error(`${oe}Failed to abort multipart upload: ${Y}`)}return P.completeMultipartUploadResult}async abortMultipartUpload(u,l){if(this._checkKey(u),typeof l!="string"||l.trim().length===0)throw this._log("error",Pe),new TypeError(Pe);this._log("info",`Aborting multipart upload ${l} for object ${u}`);let h={uploadId:l},d={[Ee]:et,[de]:_e};try{let _=me(u),{url:g,headers:O}=await this._sign("DELETE",_,h,d,""),T=`${g}?${new URLSearchParams(h)}`,v=await this._sendRequest(T,"DELETE",O);if(v.ok){let R=await v.text(),$=Be(R);if(typeof $=="object"&&$!==null&&"error"in $&&typeof $.error=="object"&&$.error!==null&&"message"in $.error){let P=String($.error.message);throw this._log("error",`${oe}Failed to abort multipart upload: ${P}`),new Error(`${oe}Failed to abort multipart upload: ${P}`)}return{status:"Aborted",key:u,uploadId:l,response:$}}else throw this._log("error",`${oe}Abort request failed with status ${v.status}`),new Error(`${oe}Abort request failed with status ${v.status}`)}catch(_){let g=_ instanceof Error?_.message:String(_);throw this._log("error",`${oe}Failed to abort multipart upload for key ${u}: ${g}`),new Error(`${oe}Failed to abort multipart upload for key ${u}: ${g}`)}}_buildCompleteMultipartUploadXml(u){return`
${u.map(l=>`
@@ -84,5 +84,5 @@ import Ue from"buffer";import xt from"crypto";import De from"util";import vt fro
`).join("")}
- `}async delete(u){this._checkKey(u),this._log("info",`Deleting object ${u}`);let l={[Ee]:xe,[de]:_e},h=me(u),{url:d,headers:_}=await this._sign("DELETE",h,{},l,""),g=await this._sendRequest(d,"DELETE",_);return g.status===204||g.status===200}async _sendRequest(u,l,h,d,_=[]){this._log("info",`Sending ${l} request to ${u}, headers: ${JSON.stringify(h)}`);let g=await fetch(u,{method:l,headers:h,body:["GET","HEAD"].includes(l)?void 0:d,signal:this.requestAbortTimeout!==void 0?AbortSignal.timeout(this.requestAbortTimeout):void 0});return this._log("info",`Response status: ${g.status,_}`),!g.ok&&!_.includes(g.status)&&await this._handleErrorResponse(g),g}async _handleErrorResponse(u){let l=await u.text(),h=u.headers.get("x-amz-error-code")||"Unknown",d=u.headers.get("x-amz-error-message")||u.statusText;throw this._log("error",`${se}Request failed with status ${u.status}: ${h} - ${d},err body: ${l}`),new Error(`${se}Request failed with status ${u.status}: ${h} - ${d}, err body: ${l}`)}_buildCanonicalQueryString(u){return Object.keys(u).length<1?"":Object.keys(u).sort().map(l=>`${encodeURIComponent(l)}=${encodeURIComponent(u[l])}`).join("&")}async _getSignatureKey(u){let l=await He(`AWS4${this.secretAccessKey}`,u),h=await He(l,this.region),d=await He(h,Ze);return He(d,Xe)}},Me=async u=>{let l=Tt("sha256");return l.update(u),l.digest("hex")},He=async(u,l,h)=>{let d=Et("sha256",u);return d.update(l),d.digest(h)},Ve=u=>{let l={'"':"",""":"",""":"",""":"",""":""};return u.replace(/^("|"|")|("|"|")$/g,h=>l[h])},Be=u=>{let l=g=>g.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),h={},d=/<(\w)([-\w]+)(?:\/|[^>]*>((?:(?!<\1)[\s\S])*)<\/\1\2)>/gm,_;for(;_=d.exec(u);){let[,g,O,T]=_,v=g.toLowerCase()+O,R=T!=null?Be(T):!0;typeof R=="string"?h[v]=Ve(l(R)):Array.isArray(h[v])?h[v].push(R):h[v]=h[v]!=null?[h[v],R]:Xt[v]?[R]:R}return Object.keys(h).length?h:l(u)},Ot=Lt(Ht(),1),q={MISSING_ARGUMENT:"MISSING_ARGUMENT",COLLECTION_EXISTS:"COLLECTION_EXISTS",CREATE_COLLECTION_ERROR:"CREATE_COLLECTION_ERROR",RENAME_COLLECTION_ERROR:"RENAME_COLLECTION_ERROR",REMOVE_COLLECTION_ERROR:"REMOVE_COLLECTION_ERROR",UPDATE_COLLECTION_SCHEMA_ERROR:"UPDATE_COLLECTION_SCHEMA_ERROR",COLLECTION_NOT_FOUND:"COLLECTION_NOT_FOUND",SCHEMA_VALIDATION_ERROR:"SCHEMA_VALIDATION_ERROR",DOCUMENT_VALIDATION_ERROR:"DOCUMENT_VALIDATION_ERROR",S3_OPERATION_ERROR:"S3_OPERATION_ERROR",FIND_ERROR:"FIND_ERROR",FIND_ONE_ERROR:"FIND_ONE_ERROR",SAVE_DATA_ERROR:"SAVE_DATA_ERROR",INSERT_ERROR:"INSERT_ERROR",UPDATE_ERROR:"UPDATE_ERROR",UPDATE_ONE_ERROR:"UPDATE_ONE_ERROR",DELETE_ERROR:"DELETE_ERROR",COUNT_ERROR:"COUNT_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},ie=class extends Error{constructor(u,l=q.UNKNOWN_ERROR){super(`lowstorageError: ${u} :: code: ${l}`),this.name=this.constructor.name,this.code=l,Error.captureStackTrace(this,this.constructor)}},Ae=class extends ie{constructor(u,l=q.SCHEMA_VALIDATION_ERROR){super(u,q.SCHEMA_VALIDATION_ERROR)}},Le=class extends ie{constructor(u,l=q.DOCUMENT_VALIDATION_ERROR){super(u,q.DOCUMENT_VALIDATION_ERROR)}},le=class extends ie{constructor(u,l){super(`S3 ${l} operation failed: ${u}`,q.S3_OPERATION_ERROR)}},Ye=(u,l)=>Object.keys(l).every(h=>u[h]===l[h]),tr=async()=>typeof tt<"u"&&typeof tt=="function"?tt():typeof crypto<"u"&&typeof crypto=="object"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(u){var l=Math.random()*16|0,h=u==="x"?l:l&3|8;return h.toString(16)}),Qe=u=>{let l={name:"_id",type:"string",size:16,logicalType:"UUID"};return typeof u>"u"||u===null||("type"in u&&u.type==="record"&&"fields"in u&&Array.isArray(u.fields)?u.fields.some(d=>d.name==="_id")||u.fields.unshift(l):"type"in u&&u.type==="array"&&"items"in u&&u.items!==null&&typeof u.items=="object"&&"type"in u.items&&u.items.type==="record"&&"fields"in u.items&&Array.isArray(u.items.fields)&&(u.items.fields.some(d=>d.name==="_id")||u.items.fields.unshift(l))),u},K="lowstorage",Oe="/",Rt="lowstorage",Re=".avro",rr=1024*1024,_t=5*rr,nt=Buffer.from("","utf8"),rt=(u=q.DOCUMENT_VALIDATION_ERROR)=>{throw new Le(`${K}: Invalid document or schema ${u}`)},qe=(u="")=>{if(u.trim()===""||u===null||typeof u>"u"||u.length>255||u===null)throw new ie(`${K}: Collection name is required, null or too long`,q.MISSING_ARGUMENT)},yr=class{constructor(u){this._checkArgs=l=>{let h=["accessKeyId","secretAccessKey","endpoint","bucketName"];for(let d of h)if(!l[d])throw new ie(`${K}: ${d} is required`,q.MISSING_ARGUMENT)},this.s3=()=>this._s3,this._checkArgs(u),this._schemas=new Map,this._s3=new er(u),this._dirPrefix=u.dirPrefix||Rt,this._avroParse=Ot.Type}async checkIfStorageExists(){try{return!!await this._s3.bucketExists()}catch(u){if(u.message.includes("Not Found"))return!1;throw new ie(`${K}: ${u.message}`,q.S3_OPERATION_ERROR)}}async createStorage(){try{let u=await this.checkIfStorageExists();return u||await this._s3.createBucket()}catch(u){throw u instanceof ie?u:new ie(`${K}: ${u.message}`,q.S3_OPERATION_ERROR)}}async listCollections(){try{let u=await this._s3.list(Oe,this._dirPrefix);return Array.isArray(u)?u.map(l=>l.key.slice(this._dirPrefix.length+1,-Re.length)):typeof u=="object"&&u!==null&&"keyCount"in u&&u.keyCount==="0"?[]:[]}catch(u){throw new le(`${K}: ${u.message}`,q.S3_OPERATION_ERROR)}}async collectionExists(u=""){try{return qe(u),!!await this._s3.fileExists(`${this._dirPrefix}${Oe}${u}${Re}`)}catch(l){if(l.message.includes("Not Found"))return!1;throw new ie(`${K}: ${l.message}`,q.COLLECTION_NOT_FOUND)}}async createCollection(u="",l,h=[]){try{if(qe(u),!await this.collectionExists(u)){if(typeof l<"u"&&l!==null)try{if(this._avroParse.forSchema(l))this._schemas.set(u,l);else throw new Ae(`${K}: Schema is invalid: ${l} ${q.SCHEMA_VALIDATION_ERROR}`)}catch{throw new Ae(`${K}: Schema is invalid: ${l}`,q.SCHEMA_VALIDATION_ERROR)}if(h.length>0&&l){let _=this._avroParse.forSchema({type:"array",items:l});await this._s3.put(`${this._dirPrefix}${Oe}${u}${Re}`,_.toBuffer(h))}else await this._s3.put(`${this._dirPrefix}${Oe}${u}${Re}`,nt);return this.collection(u,l,!1)}throw new ie(`${K}: Collection ${u} already exists`,q.COLLECTION_EXISTS)}catch(d){throw d instanceof ie?d:new ie(`${K}: ${d.message}`,q.CREATE_COLLECTION_ERROR)}}async removeCollection(u=""){try{if(qe(u),await this.collectionExists(u)){await this._s3.delete(`${this._dirPrefix}${Oe}${u}${Re}`);let h=await this.collectionExists(u);if(typeof h=="boolean"){if(!h)return this._schemas.delete(u),!0;throw new ie(`${K}: Failed to delete collection ${u}`,q.S3_OPERATION_ERROR)}throw new le(`${K}: Failed to delete collection ${u}`,q.S3_OPERATION_ERROR)}throw new ie(`${K}: Collection ${u} does not exist`,q.REMOVE_COLLECTION_ERROR)}catch(l){throw l instanceof le?l:new ie(`${K}: Failed to remove collection: ${l.message}`,q.REMOVE_COLLECTION_ERROR)}}async collection(u="",l,h=!0){try{qe(u);let d=`${this._dirPrefix}${Oe}${u}${Re}`;if(!await this._s3.fileExists(d)){if(!h)throw new ie(`${K}: Collection ${u} does not exist`,q.COLLECTION_NOT_FOUND);await this._s3.put(d,nt)}let g=l||this._schemas.get(u)||void 0;return new ir(u,g,this._s3,this._dirPrefix)}catch(d){throw d.message.includes("unknown type")?new Ae(`${K}: Schema input is invalid: ${d.message}`,q.SCHEMA_VALIDATION_ERROR):new ie(`${K}: ${d.message}`,q.COLLECTION_NOT_FOUND)}}},ir=class kt{constructor(l="",h,d,_=Rt,g=!1,O=_t){this.getProps=()=>({colName:this._colName,s3:this._s3,schema:this._schema,avroParse:this._avroParse,avroType:this._avroType,dirPrefix:this._dirPrefix,safeWrite:this._safeWrite,chunkSize:this._chunkSize}),this.setProps=T=>{this._colName=T.colName,this._schema=T.schema,this._s3=T.s3,this._avroParse=T.avroParse,this._avroType=T.avroType,this._dirPrefix=T.dirPrefix,this._safeWrite=T.safeWrite,this._chunkSize=T.chunkSize},this.setSafeWrite=T=>{this._safeWrite=T},this.getSafeWrite=()=>this._safeWrite,this.getAvroSchema=()=>this._schema,this.setAvroSchema=T=>{try{this._schema=Qe(T),this._avroType=typeof T>"u"?null:this._avroParse.forSchema(T)}catch(v){throw new ie(`${K}: ${v.message}`,q.SCHEMA_VALIDATION_ERROR)}},this.getCollectionETag=()=>this._lastETag,this.inferAvroSchema=(T,v="record")=>{Array.isArray(T)&&(T=T[0]);let C=this._avroParse.forValue(T).schema();return Qe(C)},this._colName=l.trim(),this._s3=d,this._schema=Qe(h),this._dirPrefix=_,this._safeWrite=g,this._chunkSize=O||_t,this._s3.setMaxRequestSizeInBytes(this._chunkSize),this._avroParse=Ot.Type,this._lastETag="",this._dataCache=[],this._avroType=typeof h>"u"?null:this._avroParse.forSchema(h),this._key=`${this._dirPrefix}${Oe}${this._colName}${Re}`}async forceLoadData(){try{this._lastETag="";let l=await this._loadData();return this._dataCache=l,!0}catch(l){throw new ie(`${K}: Failed to force update data: ${l.message}`,q.S3_OPERATION_ERROR)}}async _loadData(){try{if(this._avroType===null||typeof this._avroType>"u")throw new ie(`${K}: Missing type definition. Configure before operations `,q.SCHEMA_VALIDATION_ERROR);let{etag:l,data:h}=await this._s3.getObjectWithETag(this._key,{"if-none-match":this._lastETag});if(h===null)return this._dataCache;this._lastETag=l===null?this._lastETag:l;let d=this._avroParse.forSchema({type:"array",items:this._avroType});if(h.length0?d.fromBuffer(Buffer.from(h,"utf8")):[],this._dataCache;let _=this._chunkSize,g=[Buffer.from(h,"utf8")],O=!0;for(;O;){let v=await this._s3.getResponse(this._key,!1,_,_+this._chunkSize),R=await v.text();g.push(Buffer.from(R,"utf8")),_+=this._chunkSize,parseInt(v.headers.get("content-length")||R.length.toString())-1)return this._dataCache=[],this._dataCache;throw new le(`${K}: Failed to load data: ${l.message}`,q.S3_OPERATION_ERROR)}}async _saveData(l){try{if(this._avroType===null||typeof this._avroType>"u")throw new ie(`${K}: Missing type definition. Configure before operations `,q.SCHEMA_VALIDATION_ERROR);let h=this._avroParse.forSchema({type:"array",items:this._avroType}),d=l.length>0?h.toBuffer(l):nt;if(this._safeWrite&&this._lastETag!==""){let O=await this._s3.getEtag(this._key);if(O!==null&&O!==this._lastETag)return!1}let _=await this._s3.put(this._key,d);if(typeof _=="object"&&"status"in _&&_.status!==200)throw new le(`${K}: Failed to save data`,q.S3_OPERATION_ERROR);let g=_.headers?.get("etag")||"";return g&&g.length>0&&(this._lastETag=this._s3.sanitizeETag(g),this._dataCache=l),!0}catch(h){throw h instanceof le?h:new ie(`${K}: ${h.message}`,q.SAVE_DATA_ERROR)}}async insert(l,h){try{if(l==null)throw new ie(`${K}: Document is required for insert`,q.INSERT_ERROR);if(typeof l!="object"&&!Array.isArray(l))throw new Le(`${K}: Document must be an object or an array`,q.DOCUMENT_VALIDATION_ERROR);let d=Array.isArray(l)?l:[l],_=h?Qe(h):this._schema||this.inferAvroSchema(d[0]),g=this._avroParse.forSchema(_);if(!g)throw new Ae(`${K}: Schema is required - Pass a schema to the insert method`,q.SCHEMA_VALIDATION_ERROR);this._avroType=g;let O=await this._loadData();for(let v of d){if(typeof v!="object"||v===null)throw new Le(`${K}: Invalid input: input must be an object or an array of objects`,q.DOCUMENT_VALIDATION_ERROR);if(v._id=v._id||await tr(),this._avroType.isValid(v,{errorHook:rt,noUndeclaredFields:!0})===!0)O.push(v);else throw new Le(`${K}: Invalid document or schema`,q.DOCUMENT_VALIDATION_ERROR)}if(!await this._saveData(O))throw new le(`${K}: Failed to insert document`,q.S3_OPERATION_ERROR);return this.setAvroSchema(_),d}catch(d){throw d.message.includes("unknown type")?new Ae(`${K}: Schema input is invalid: ${d.message}`,q.SCHEMA_VALIDATION_ERROR):d instanceof ie?d:new ie(`${K} Insert operation failed: ${d.message}`,q.INSERT_ERROR)}}async find(l={},h={}){try{if(l==null)throw new ie(`${K}: Query is required for update`,q.MISSING_ARGUMENT);let d=await this._loadData(),_=h.skip!==void 0?parseInt(String(h.skip),10):0,g=h.limit!==void 0?_+parseInt(String(h.limit),10):void 0;return d.filter(T=>Ye(T,l)).slice(_,g)}catch(d){throw new ie(`${K}: Find operation failed: ${d.message}`,q.FIND_ERROR)}}async findOne(l={}){try{if(l===null)throw new ie(`${K}: Query cannot be null`,q.INVALID_ARGUMENT);return(await this.find(l,{limit:1}))[0]||null}catch(h){throw h instanceof ie?h:new ie(`${K}: FindOne operation failed: ${h.message}`,q.FIND_ONE_ERROR)}}async update(l={},h={},d={}){try{if(l==null||h===void 0||h===null)throw new ie(`${K}: Query and update values are required for update`,q.MISSING_ARGUMENT);if(!this._avroType)throw new Ae(`${K}: Schema is not defined for this collection`,q.SCHEMA_VALIDATION_ERROR);let _=await this._loadData();if(_.length===0)return 0;let g=0;for(let O=0;O<_.length;O++)if(Ye(_[O],l)){let T={..._[O],...h};if(this._avroType.isValid(T,{errorHook:rt,noUndeclaredFields:!0})===!0)_[O]=T,g++;else throw new Le(`${K}: Invalid document or schema`,q.DOCUMENT_VALIDATION_ERROR)}if(g>0){if(!await this._saveData(_))throw new le(`${K}: Failed to update document`,q.S3_OPERATION_ERROR)}else if(d&&"upsert"in d&&d.upsert){if(!await this.insert(h))throw new le(`${K}: Failed to update document`,q.S3_OPERATION_ERROR);g=1}return g}catch(_){throw _ instanceof le?_:new ie(`${K}: Update operation failed: ${_.message}`,q.UPDATE_ERROR)}}async updateOne(l={},h={},d={}){try{if(l==null||h===void 0||h===null)throw new ie(`${K}: Query is required`,q.MISSING_ARGUMENT);if(!this._avroType)throw new Ae(`${K}: Schema is not defined for this collection`,q.SCHEMA_VALIDATION_ERROR);let _=await this._loadData();if(_.length===0)return 0;let g=_.findIndex(O=>Ye(O,l));if(g!==-1){let O={..._[g],...h};if(this._avroType.isValid(O,{errorHook:rt,noUndeclaredFields:!0})===!0){if(_[g]=O,!await this._saveData(_))throw new le(`${K}: Failed to update document`,q.S3_OPERATION_ERROR);return 1}else throw new Le(`${K}: Invalid document or schema`,q.DOCUMENT_VALIDATION_ERROR)}if(d&&"upsert"in d&&d.upsert){if(!await this.insert(h))throw new le(`${K}: Failed to update document`,q.S3_OPERATION_ERROR);return 1}return 0}catch(_){throw _ instanceof ie?_:new ie(`${K}: UpdateOne operation failed: ${_.message}`,q.UPDATE_ONE_ERROR)}}async delete(l={}){try{if(l==null)throw new ie(`${K}: Query is required`,q.MISSING_ARGUMENT);let h=await this._loadData();if(h.length===0)return 0;let d=h.length,_=h.filter(O=>!Ye(O,l));if(!await this._saveData(_))throw new le(`${K}: Failed to delete document`,q.S3_OPERATION_ERROR);return d-_.length}catch(h){throw h instanceof le?h:new ie(`${K}: Delete operation failed: ${h.message}`,q.DELETE_ERROR)}}async deleteAll(){try{let h=(await this._loadData()).length;if(!await this._saveData([]))throw new le(`${K}: Failed to delete document`,q.S3_OPERATION_ERROR);return h}catch(l){throw l instanceof le?l:new ie(`${K}: Delete operation failed: ${l.message}`,q.DELETE_ERROR)}}async count(l={}){try{return(await this.find(l)).length}catch(h){throw new ie(`${K}: Count operation failed: ${h.message}`,q.COUNT_ERROR)}}async renameCollection(l,h=this._schema){try{if(qe(l),await this._s3.fileExists(`${this._dirPrefix}${Oe}${l}${Re}`))throw new ie(`${K}: Collection ${l} already exists`,q.COLLECTION_EXISTS);let _=h||this.getAvroSchema(),g=await this._loadData(),O=new kt(l,_,this._s3,this._dirPrefix,this._safeWrite,this._chunkSize);return await O._saveData(g),await this._s3.delete(`${this._dirPrefix}${Oe}${this._colName}${Re}`),O}catch(d){throw d instanceof ie?d:new ie(`${K}: Rename collection failed: ${d.message}`,q.RENAME_COLLECTION_ERROR)}}};export{yr as lowstorage,ie as lowstorageError,q as lowstorage_ERROR_CODES};
+ `}async delete(u){this._checkKey(u),this._log("info",`Deleting object ${u}`);let l={[Ee]:Ne,[de]:_e},h=me(u),{url:d,headers:_}=await this._sign("DELETE",h,{},l,""),g=await this._sendRequest(d,"DELETE",_);return g.status===204||g.status===200}async _sendRequest(u,l,h,d,_=[]){this._log("info",`Sending ${l} request to ${u}, headers: ${JSON.stringify(h)}`);let g=await fetch(u,{method:l,headers:h,body:["GET","HEAD"].includes(l)?void 0:d,signal:this.requestAbortTimeout!==void 0?AbortSignal.timeout(this.requestAbortTimeout):void 0});return this._log("info",`Response status: ${g.status,_}`),!g.ok&&!_.includes(g.status)&&await this._handleErrorResponse(g),g}async _handleErrorResponse(u){let l=await u.text(),h=u.headers.get("x-amz-error-code")||"Unknown",d=u.headers.get("x-amz-error-message")||u.statusText;throw this._log("error",`${oe}Request failed with status ${u.status}: ${h} - ${d},err body: ${l}`),new Error(`${oe}Request failed with status ${u.status}: ${h} - ${d}, err body: ${l}`)}_buildCanonicalQueryString(u){return Object.keys(u).length<1?"":Object.keys(u).sort().map(l=>`${encodeURIComponent(l)}=${encodeURIComponent(u[l])}`).join("&")}async _getSignatureKey(u){let l=await He(`AWS4${this.secretAccessKey}`,u),h=await He(l,this.region),d=await He(h,Ze);return He(d,Xe)}},Me=async u=>{let l=Tt("sha256");return l.update(u),l.digest("hex")},He=async(u,l,h)=>{let d=Et("sha256",u);return d.update(l),d.digest(h)},Ve=u=>{let l={'"':"",""":"",""":"",""":"",""":""};return u.replace(/^("|"|")|("|"|")$/g,h=>l[h])},Be=u=>{let l=g=>g.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),h={},d=/<(\w)([-\w]+)(?:\/|[^>]*>((?:(?!<\1)[\s\S])*)<\/\1\2)>/gm,_;for(;_=d.exec(u);){let[,g,O,T]=_,v=g.toLowerCase()+O,R=T!=null?Be(T):!0;typeof R=="string"?h[v]=Ve(l(R)):Array.isArray(h[v])?h[v].push(R):h[v]=h[v]!=null?[h[v],R]:Xt[v]?[R]:R}return Object.keys(h).length?h:l(u)},Ot=Lt(Ht(),1),U={MISSING_ARGUMENT:"MISSING_ARGUMENT",COLLECTION_EXISTS:"COLLECTION_EXISTS",CREATE_COLLECTION_ERROR:"CREATE_COLLECTION_ERROR",LIST_COLLECTIONS_ERROR:"LIST_COLLECTIONS_ERROR",RENAME_COLLECTION_ERROR:"RENAME_COLLECTION_ERROR",REMOVE_COLLECTION_ERROR:"REMOVE_COLLECTION_ERROR",UPDATE_COLLECTION_SCHEMA_ERROR:"UPDATE_COLLECTION_SCHEMA_ERROR",COLLECTION_NOT_FOUND:"COLLECTION_NOT_FOUND",SCHEMA_VALIDATION_ERROR:"SCHEMA_VALIDATION_ERROR",DOCUMENT_VALIDATION_ERROR:"DOCUMENT_VALIDATION_ERROR",S3_OPERATION_ERROR:"S3_OPERATION_ERROR",FIND_ERROR:"FIND_ERROR",FIND_ONE_ERROR:"FIND_ONE_ERROR",SAVE_DATA_ERROR:"SAVE_DATA_ERROR",INSERT_ERROR:"INSERT_ERROR",UPDATE_ERROR:"UPDATE_ERROR",UPDATE_ONE_ERROR:"UPDATE_ONE_ERROR",DELETE_ERROR:"DELETE_ERROR",COUNT_ERROR:"COUNT_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},re=class extends Error{constructor(u,l=U.UNKNOWN_ERROR){super(`lowstorageError: ${u} :: code: ${l}`),this.name=this.constructor.name,this.code=l,Error.captureStackTrace(this,this.constructor)}},Se=class extends re{constructor(u,l=U.SCHEMA_VALIDATION_ERROR){super(u,U.SCHEMA_VALIDATION_ERROR)}},Le=class extends re{constructor(u,l=U.DOCUMENT_VALIDATION_ERROR){super(u,U.DOCUMENT_VALIDATION_ERROR)}},le=class extends re{constructor(u,l){super(`S3 ${l} operation failed: ${u}`,U.S3_OPERATION_ERROR)}},Ye=(u,l)=>Object.keys(l).every(h=>u[h]===l[h]),tr=async()=>typeof tt<"u"&&typeof tt=="function"?tt():typeof crypto<"u"&&typeof crypto=="object"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(u){var l=Math.random()*16|0,h=u==="x"?l:l&3|8;return h.toString(16)}),Qe=u=>{let l={name:"_id",type:"string",size:16,logicalType:"UUID"};return(typeof u>"u"||u===null)&&(typeof u!="object"||!Array.isArray(u))||("type"in u&&u.type==="record"&&"fields"in u&&Array.isArray(u.fields)?u.fields.some(d=>d.name==="_id")||u.fields.unshift(l):"type"in u&&u.type==="array"&&"items"in u&&u.items!==null&&typeof u.items=="object"&&"type"in u.items&&u.items.type==="record"&&"fields"in u.items&&Array.isArray(u.items.fields)&&(u.items.fields.some(d=>d.name==="_id")||u.items.fields.unshift(l))),u},fe="lowstorage",Oe="/",Rt="lowstorage",Re=".avro",rr=1024*1024,_t=5*rr,nt=Buffer.from("","utf8"),rt=(u=U.DOCUMENT_VALIDATION_ERROR)=>{throw new Le(`${fe}: Invalid document or schema ${u}`)},qe=(u="")=>{if(u.trim()===""||u===null||typeof u>"u"||u.length>255)throw new re("Collection name is required, null or too long",U.MISSING_ARGUMENT)},yr=class{constructor(u){this._checkArgs=l=>{let h=["accessKeyId","secretAccessKey","endpoint","bucketName"];for(let d of h)if(!l[d])throw new re(`${d} is required`,U.MISSING_ARGUMENT)},this.s3=()=>this._s3,this._checkArgs(u),this._schemas=new Map,this._s3=new er(u),this._dirPrefix=u.dirPrefix||Rt,this._avroParse=Ot.Type}async checkIfStorageExists(){try{return!!await this._s3.bucketExists()}catch(u){if(u.message.includes("Not Found"))return!1;throw new re(`${u.message}`,U.S3_OPERATION_ERROR)}}async createStorage(){try{let u=await this.checkIfStorageExists();return u||!!await this._s3.createBucket()}catch(u){throw u instanceof re?u:new re(`${u.message}`,U.S3_OPERATION_ERROR)}}async listCollections(){try{let u=await this._s3.list(Oe,this._dirPrefix);return Array.isArray(u)?u.map(l=>l.key.slice(this._dirPrefix.length+1,-Re.length)):typeof u=="object"&&u!==null&&"keyCount"in u&&u.keyCount==="0"?[]:[]}catch(u){throw u instanceof le?u:new re(`${u.message}`,U.LIST_COLLECTIONS_ERROR)}}async collectionExists(u=""){try{return qe(u),!!await this._s3.fileExists(`${this._dirPrefix}${Oe}${u}${Re}`)}catch(l){if(l.message.includes("Not Found"))return!1;throw new re(`${l.message}`,U.COLLECTION_NOT_FOUND)}}async createCollection(u="",l,h=[]){try{if(qe(u),!await this.collectionExists(u)){if(typeof l<"u"&&l!==null)try{if(this._avroParse.forSchema(l))this._schemas.set(u,l);else throw new Se(`Schema is invalid: ${l}`,U.SCHEMA_VALIDATION_ERROR)}catch(_){throw new Se(`Schema is invalid: ${_.message} in ${l} `,U.SCHEMA_VALIDATION_ERROR)}if(h.length>0&&l){let _=this._avroParse.forSchema({type:"array",items:l});await this._s3.put(`${this._dirPrefix}${Oe}${u}${Re}`,_.toBuffer(h))}else await this._s3.put(`${this._dirPrefix}${Oe}${u}${Re}`,nt);return this.collection(u,l,!1)}throw new re(`Collection ${u} already exists`,U.COLLECTION_EXISTS)}catch(d){throw d instanceof Se?d:new re(`${d.message}`,U.CREATE_COLLECTION_ERROR)}}async removeCollection(u=""){try{if(qe(u),await this.collectionExists(u)){await this._s3.delete(`${this._dirPrefix}${Oe}${u}${Re}`);let h=await this.collectionExists(u);if(typeof h=="boolean"){if(!h)return this._schemas.delete(u),!0;throw new re(`Failed to delete collection ${u}`,U.S3_OPERATION_ERROR)}throw new le(`${fe}: Failed to delete collection ${u}`,U.S3_OPERATION_ERROR)}throw new re(`Collection ${u} does not exist`,U.REMOVE_COLLECTION_ERROR)}catch(l){throw l instanceof le?l:new re(`Failed to remove collection: ${l.message}`,U.REMOVE_COLLECTION_ERROR)}}async collection(u="",l,h=!0){try{qe(u);let d=`${this._dirPrefix}${Oe}${u}${Re}`;if(!await this._s3.fileExists(d)){if(!h)throw new re(`Collection ${u} does not exist`,U.COLLECTION_NOT_FOUND);await this._s3.put(d,nt)}let g=l||this._schemas.get(u)||void 0;return new ir(u,g,this._s3,this._dirPrefix)}catch(d){throw d.message.includes("unknown type")?new Se(`Schema input is invalid: ${d.message}`,U.SCHEMA_VALIDATION_ERROR):d instanceof re?d:new re(`${d.message}`,U.COLLECTION_NOT_FOUND)}}},ir=class St{constructor(l="",h,d,_=Rt,g=!1,O=_t){this.getProps=()=>({colName:this._colName,s3:this._s3,schema:this._schema,avroParse:this._avroParse,avroType:this._avroType,dirPrefix:this._dirPrefix,safeWrite:this._safeWrite,chunkSize:this._chunkSize}),this.setProps=T=>{this._colName=T.colName,this._schema=T.schema,this._s3=T.s3,this._avroParse=T.avroParse,this._avroType=T.avroType,this._dirPrefix=T.dirPrefix,this._safeWrite=T.safeWrite,this._chunkSize=T.chunkSize},this.setSafeWrite=T=>{this._safeWrite=T},this.getSafeWrite=()=>this._safeWrite,this.getAvroSchema=()=>this._schema,this.setAvroSchema=T=>{try{this._schema=Qe(T),this._avroType=typeof T>"u"?null:this._avroParse.forSchema(T)}catch(v){throw new Se(`Schema is invalid: ${v.message}`,U.SCHEMA_VALIDATION_ERROR)}},this.getCollectionETag=()=>this._lastETag,this.inferAvroSchema=(T,v="record")=>{Array.isArray(T)&&(T=T[0]);let $=this._avroParse.forValue(T).schema();return Qe($)},this._colName=l.trim(),this._s3=d,this._schema=Qe(h),this._dirPrefix=_,this._safeWrite=g,this._chunkSize=O||_t,this._s3.setMaxRequestSizeInBytes(this._chunkSize),this._avroParse=Ot.Type,this._lastETag="",this._dataCache=[],this._avroType=typeof h>"u"?null:this._avroParse.forSchema(h),this._key=`${this._dirPrefix}${Oe}${this._colName}${Re}`}async forceLoadData(){try{this._lastETag="";let l=await this._loadData();return this._dataCache=l,!0}catch(l){throw new re(`Failed to force update data: ${l.message}`,U.S3_OPERATION_ERROR)}}async _loadData(){try{if(this._avroType===null||typeof this._avroType>"u")throw new re("Missing type definition. Configure before operations ",U.SCHEMA_VALIDATION_ERROR);let{etag:l,data:h}=await this._s3.getObjectWithETag(this._key,{"if-none-match":this._lastETag});if(h===null)return this._dataCache;this._lastETag=l===null?this._lastETag:l;let d=this._avroParse.forSchema({type:"array",items:this._avroType});if(h.length0?d.fromBuffer(Buffer.from(h,"utf8")):[],this._dataCache;let _=this._chunkSize,g=[Buffer.from(h,"utf8")],O=!0;for(;O;){let v=await this._s3.getResponse(this._key,!1,_,_+this._chunkSize),R=await v.text();g.push(Buffer.from(R,"utf8")),_+=this._chunkSize,parseInt(v.headers.get("content-length")||R.length.toString())-1)return this._dataCache=[],this._dataCache;throw new le(`${fe}: Failed to load data: ${l.message}`,U.S3_OPERATION_ERROR)}}async _saveData(l){try{if(this._avroType===null||typeof this._avroType>"u")throw new re("Missing type definition. Configure before operations ",U.SCHEMA_VALIDATION_ERROR);let h=this._avroParse.forSchema({type:"array",items:this._avroType}),d=l.length>0?h.toBuffer(l):nt;if(this._safeWrite&&this._lastETag!==""){let O=await this._s3.getEtag(this._key);if(O!==null&&O!==this._lastETag)return!1}let _=await this._s3.put(this._key,d);if(typeof _=="object"&&"status"in _&&_.status!==200)throw new le(`${fe}: Failed to save data`,U.S3_OPERATION_ERROR);let g=_.headers?.get("etag")||"";return g&&g.length>0&&(this._lastETag=this._s3.sanitizeETag(g),this._dataCache=l),!0}catch(h){throw h instanceof le||h instanceof re?h:new re(`${h.message}`,U.SAVE_DATA_ERROR)}}async insert(l,h){try{if(l==null)throw new re("Document is required for insert",U.INSERT_ERROR);if(typeof l!="object"&&!Array.isArray(l))throw new Le(`${fe}: Document must be an object or an array`,U.DOCUMENT_VALIDATION_ERROR);let d=Array.isArray(l)?l:[l],_=h?Qe(h):this._schema||this.inferAvroSchema(d[0]),g=this._avroParse.forSchema(_);if(!g)throw new Se("Schema is required - Pass a schema to the insert method",U.SCHEMA_VALIDATION_ERROR);this._avroType=g;let O=await this._loadData();for(let v of d){if(typeof v!="object"||v===null)throw new Le(`${fe}: Invalid input: input must be an object or an array of objects`,U.DOCUMENT_VALIDATION_ERROR);if(v._id=v._id||await tr(),this._avroType.isValid(v,{errorHook:rt,noUndeclaredFields:!0})===!0)O.push(v);else throw new Le(`${fe}: Invalid document or schema`,U.DOCUMENT_VALIDATION_ERROR)}if(!await this._saveData(O))throw new le(`${fe}: Failed to insert document`,U.S3_OPERATION_ERROR);return this.setAvroSchema(_),d}catch(d){throw d.message.includes("unknown type")?new Se(`Schema input is invalid: ${d.message}`,U.SCHEMA_VALIDATION_ERROR):d instanceof re?d:new re(`Insert operation failed: ${d.message}`,U.INSERT_ERROR)}}async find(l={},h={}){try{if(l==null)throw new re("Query is required for update",U.MISSING_ARGUMENT);let d=await this._loadData(),_=h.skip!==void 0?parseInt(String(h.skip),10):0,g=h.limit!==void 0?_+parseInt(String(h.limit),10):void 0;return d.filter(T=>Ye(T,l)).slice(_,g)}catch(d){throw new re(`Find operation failed: ${d.message}`,U.FIND_ERROR)}}async findOne(l={}){try{if(l===null)throw new re(`${fe}: Query cannot be null`,U.INVALID_ARGUMENT);return(await this.find(l,{limit:1}))[0]||null}catch(h){throw h instanceof re?h:new re(`${fe}: FindOne operation failed: ${h.message}`,U.FIND_ONE_ERROR)}}async update(l={},h={},d={}){try{if(l==null||h===void 0||h===null)throw new re("Query and update values are required for update",U.MISSING_ARGUMENT);if(!this._avroType)throw new Se("Schema is not defined for this collection",U.SCHEMA_VALIDATION_ERROR);let _=await this._loadData();if(_.length===0)return 0;let g=0;for(let O=0;O<_.length;O++)if(Ye(_[O],l)){let T={..._[O],...h};if(this._avroType.isValid(T,{errorHook:rt,noUndeclaredFields:!0})===!0)_[O]=T,g++;else throw new Le(`${fe}: Invalid document or schema`,U.DOCUMENT_VALIDATION_ERROR)}if(g>0){if(!await this._saveData(_))throw new le(`${fe}: Failed to update document`,U.S3_OPERATION_ERROR)}else if(d&&"upsert"in d&&d.upsert){if(!await this.insert(h))throw new le(`${fe}: Failed to update document`,U.S3_OPERATION_ERROR);g=1}return g}catch(_){throw _ instanceof le?_:new re(`Update operation failed: ${_.message}`,U.UPDATE_ERROR)}}async updateOne(l={},h={},d={}){try{if(l==null||h===void 0||h===null)throw new re("Query is required",U.MISSING_ARGUMENT);if(!this._avroType)throw new Se("Schema is not defined for this collection",U.SCHEMA_VALIDATION_ERROR);let _=await this._loadData();if(_.length===0)return 0;let g=_.findIndex(O=>Ye(O,l));if(g!==-1){let O={..._[g],...h};if(this._avroType.isValid(O,{errorHook:rt,noUndeclaredFields:!0})===!0){if(_[g]=O,!await this._saveData(_))throw new le(`${fe}: Failed to update document`,U.S3_OPERATION_ERROR);return 1}else throw new Le(`${fe}: Invalid document or schema`,U.DOCUMENT_VALIDATION_ERROR)}if(d&&"upsert"in d&&d.upsert){if(!await this.insert(h))throw new le(`${fe}: Failed to update document`,U.S3_OPERATION_ERROR);return 1}return 0}catch(_){throw _ instanceof re?_:new re(`UpdateOne operation failed: ${_.message}`,U.UPDATE_ONE_ERROR)}}async delete(l={}){try{if(l==null)throw new re("Query is required",U.MISSING_ARGUMENT);let h=await this._loadData();if(h.length===0)return 0;let d=h.length,_=h.filter(O=>!Ye(O,l));if(!await this._saveData(_))throw new le(`${fe}: Failed to delete document`,U.S3_OPERATION_ERROR);return d-_.length}catch(h){throw h instanceof le?h:new re(`Delete operation failed: ${h.message}`,U.DELETE_ERROR)}}async deleteAll(){try{let h=(await this._loadData()).length;if(!await this._saveData([]))throw new le(`${fe}: Failed to delete document`,U.S3_OPERATION_ERROR);return h}catch(l){throw l instanceof le?l:new re(`Delete operation failed: ${l.message}`,U.DELETE_ERROR)}}async count(l={}){try{return(await this.find(l)).length}catch(h){throw new re(`Count operation failed: ${h.message}`,U.COUNT_ERROR)}}async renameCollection(l,h=this._schema){try{if(qe(l),await this._s3.fileExists(`${this._dirPrefix}${Oe}${l}${Re}`))throw new re(`${fe}: Collection ${l} already exists`,U.COLLECTION_EXISTS);let _=h||this.getAvroSchema(),g=await this._loadData(),O=new St(l,_,this._s3,this._dirPrefix,this._safeWrite,this._chunkSize);return await O._saveData(g),await this._s3.delete(`${this._dirPrefix}${Oe}${this._colName}${Re}`),O}catch(d){throw d instanceof re?d:new re(`Rename collection failed: ${d.message}`,U.RENAME_COLLECTION_ERROR)}}};export{yr as lowstorage,re as lowstorageError,U as lowstorage_ERROR_CODES};
//# sourceMappingURL=lowstorage.min.js.map
diff --git a/build/lowstorage.min.js.map b/build/lowstorage.min.js.map
index 08bab5d..d823949 100644
--- a/build/lowstorage.min.js.map
+++ b/build/lowstorage.min.js.map
@@ -1,7 +1,7 @@
{
"version": 3,
"sources": [""],
- "sourcesContent": ["import __import_BUFFER from \"buffer\";\nimport __import_CRYPTO from \"crypto\";\nimport __import_UTIL from \"util\";\nimport __import_STREAM from \"stream\";\nimport __import_ZLIB from \"zlib\";\nimport __import_EVENTS from \"events\";\nimport __import_FS from \"fs\";\nimport __import_PATH from \"path\";\n\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __require = /* @__PURE__ */ ((x2) => typeof require !== \"undefined\" ? require : typeof Proxy !== \"undefined\" ? new Proxy(x2, {\n get: (a, b2) => (typeof require !== \"undefined\" ? require : a)[b2]\n}) : x2)(function(x2) {\n if (typeof require !== \"undefined\") return require.apply(this, arguments);\n throw Error('Dynamic require of \"' + x2 + '\" is not supported');\n});\nvar __commonJS = (cb, mod) => function __require2() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\n\n// node_modules/avsc/lib/utils.js\nvar require_utils = __commonJS({\n \"node_modules/avsc/lib/utils.js\"(exports, module) {\n \"use strict\";\n var buffer = __import_BUFFER;\n var crypto2 = __import_CRYPTO;\n var util = __import_UTIL;\n var Buffer2 = buffer.Buffer;\n var POOL = new BufferPool(4096);\n var NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n var f2 = util.format;\n function newBuffer(size) {\n if (typeof Buffer2.alloc == \"function\") {\n return Buffer2.alloc(size);\n } else {\n return new Buffer2(size);\n }\n }\n function bufferFrom(data, enc) {\n if (typeof Buffer2.from == \"function\") {\n return Buffer2.from(data, enc);\n } else {\n return new Buffer2(data, enc);\n }\n }\n function capitalize(s) {\n return s.charAt(0).toUpperCase() + s.slice(1);\n }\n function compare(n1, n2) {\n return n1 === n2 ? 0 : n1 < n2 ? -1 : 1;\n }\n function getOption(opts, key, def) {\n var value = opts[key];\n return value === void 0 ? def : value;\n }\n function getHash(str, algorithm) {\n algorithm = algorithm || \"md5\";\n var hash = crypto2.createHash(algorithm);\n hash.end(str);\n return hash.read();\n }\n function singleIndexOf(arr, v2) {\n var pos = -1;\n var i, l;\n if (!arr) {\n return -1;\n }\n for (i = 0, l = arr.length; i < l; i++) {\n if (arr[i] === v2) {\n if (pos >= 0) {\n return -2;\n }\n pos = i;\n }\n }\n return pos;\n }\n function toMap(arr, fn) {\n var obj = {};\n var i, elem;\n for (i = 0; i < arr.length; i++) {\n elem = arr[i];\n obj[fn(elem)] = elem;\n }\n return obj;\n }\n function objectValues(obj) {\n return Object.keys(obj).map(function(key) {\n return obj[key];\n });\n }\n function hasDuplicates(arr, fn) {\n var obj = /* @__PURE__ */ Object.create(null);\n var i, l, elem;\n for (i = 0, l = arr.length; i < l; i++) {\n elem = arr[i];\n if (fn) {\n elem = fn(elem);\n }\n if (obj[elem]) {\n return true;\n }\n obj[elem] = true;\n }\n return false;\n }\n function copyOwnProperties(src, dst, overwrite) {\n var names = Object.getOwnPropertyNames(src);\n var i, l, name;\n for (i = 0, l = names.length; i < l; i++) {\n name = names[i];\n if (!dst.hasOwnProperty(name) || overwrite) {\n var descriptor = Object.getOwnPropertyDescriptor(src, name);\n Object.defineProperty(dst, name, descriptor);\n }\n }\n return dst;\n }\n function isValidName(str) {\n return NAME_PATTERN.test(str);\n }\n function qualify(name, namespace) {\n if (~name.indexOf(\".\")) {\n name = name.replace(/^\\./, \"\");\n } else if (namespace) {\n name = namespace + \".\" + name;\n }\n name.split(\".\").forEach(function(part) {\n if (!isValidName(part)) {\n throw new Error(f2(\"invalid name: %j\", name));\n }\n });\n return name;\n }\n function unqualify(name) {\n var parts = name.split(\".\");\n return parts[parts.length - 1];\n }\n function impliedNamespace(name) {\n var match = /^(.*)\\.[^.]+$/.exec(name);\n return match ? match[1] : void 0;\n }\n function jsonEnd(str, pos) {\n pos = pos | 0;\n var c = str.charAt(pos++);\n if (/[\\d-]/.test(c)) {\n while (/[eE\\d.+-]/.test(str.charAt(pos))) {\n pos++;\n }\n return pos;\n } else if (/true|null/.test(str.slice(pos - 1, pos + 3))) {\n return pos + 3;\n } else if (/false/.test(str.slice(pos - 1, pos + 4))) {\n return pos + 4;\n }\n var depth = 0;\n var literal = false;\n do {\n switch (c) {\n case \"{\":\n case \"[\":\n if (!literal) {\n depth++;\n }\n break;\n case \"}\":\n case \"]\":\n if (!literal && !--depth) {\n return pos;\n }\n break;\n case '\"':\n literal = !literal;\n if (!depth && !literal) {\n return pos;\n }\n break;\n case \"\\\\\":\n pos++;\n }\n } while (c = str.charAt(pos++));\n return -1;\n }\n function abstractFunction() {\n throw new Error(\"abstract\");\n }\n function addDeprecatedGetters(obj, props) {\n var proto = obj.prototype;\n var i, l, prop, getter;\n for (i = 0, l = props.length; i < l; i++) {\n prop = props[i];\n getter = \"get\" + capitalize(prop);\n proto[getter] = util.deprecate(\n createGetter(prop),\n \"use `.\" + prop + \"` instead of `.\" + getter + \"()`\"\n );\n }\n function createGetter(prop2) {\n return function() {\n var delegate = this[prop2];\n return typeof delegate == \"function\" ? delegate.apply(this, arguments) : delegate;\n };\n }\n }\n function BufferPool(len) {\n this._len = len | 0;\n this._pos = 0;\n this._slab = newBuffer(this._len);\n }\n BufferPool.prototype.alloc = function(len) {\n if (len < 0) {\n throw new Error(\"negative length\");\n }\n var maxLen = this._len;\n if (len > maxLen) {\n return newBuffer(len);\n }\n if (this._pos + len > maxLen) {\n this._slab = newBuffer(maxLen);\n this._pos = 0;\n }\n return this._slab.slice(this._pos, this._pos += len);\n };\n function Lcg(seed) {\n var a = 1103515245;\n var c = 12345;\n var m2 = Math.pow(2, 31);\n var state = Math.floor(seed || Math.random() * (m2 - 1));\n this._max = m2;\n this._nextInt = function() {\n return state = (a * state + c) % m2;\n };\n }\n Lcg.prototype.nextBoolean = function() {\n return !!(this._nextInt() % 2);\n };\n Lcg.prototype.nextInt = function(start, end) {\n if (end === void 0) {\n end = start;\n start = 0;\n }\n end = end === void 0 ? this._max : end;\n return start + Math.floor(this.nextFloat() * (end - start));\n };\n Lcg.prototype.nextFloat = function(start, end) {\n if (end === void 0) {\n end = start;\n start = 0;\n }\n end = end === void 0 ? 1 : end;\n return start + (end - start) * this._nextInt() / this._max;\n };\n Lcg.prototype.nextString = function(len, flags) {\n len |= 0;\n flags = flags || \"aA\";\n var mask = \"\";\n if (flags.indexOf(\"a\") > -1) {\n mask += \"abcdefghijklmnopqrstuvwxyz\";\n }\n if (flags.indexOf(\"A\") > -1) {\n mask += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n }\n if (flags.indexOf(\"#\") > -1) {\n mask += \"0123456789\";\n }\n if (flags.indexOf(\"!\") > -1) {\n mask += \"~`!@#$%^&*()_+-={}[]:\\\";'<>?,./|\\\\\";\n }\n var result = [];\n for (var i = 0; i < len; i++) {\n result.push(this.choice(mask));\n }\n return result.join(\"\");\n };\n Lcg.prototype.nextBuffer = function(len) {\n var arr = [];\n var i;\n for (i = 0; i < len; i++) {\n arr.push(this.nextInt(256));\n }\n return bufferFrom(arr);\n };\n Lcg.prototype.choice = function(arr) {\n var len = arr.length;\n if (!len) {\n throw new Error(\"choosing from empty array\");\n }\n return arr[this.nextInt(len)];\n };\n function OrderedQueue() {\n this._index = 0;\n this._items = [];\n }\n OrderedQueue.prototype.push = function(item) {\n var items = this._items;\n var i = items.length | 0;\n var j2;\n items.push(item);\n while (i > 0 && items[i].index < items[j2 = i - 1 >> 1].index) {\n item = items[i];\n items[i] = items[j2];\n items[j2] = item;\n i = j2;\n }\n };\n OrderedQueue.prototype.pop = function() {\n var items = this._items;\n var len = items.length - 1 | 0;\n var first = items[0];\n if (!first || first.index > this._index) {\n return null;\n }\n this._index++;\n if (!len) {\n items.pop();\n return first;\n }\n items[0] = items.pop();\n var mid = len >> 1;\n var i = 0;\n var i1, i2, j2, item, c, c1, c2;\n while (i < mid) {\n item = items[i];\n i1 = (i << 1) + 1;\n i2 = i + 1 << 1;\n c1 = items[i1];\n c2 = items[i2];\n if (!c2 || c1.index <= c2.index) {\n c = c1;\n j2 = i1;\n } else {\n c = c2;\n j2 = i2;\n }\n if (c.index >= item.index) {\n break;\n }\n items[j2] = item;\n items[i] = c;\n i = j2;\n }\n return first;\n };\n function Tap(buf, pos) {\n this.buf = buf;\n this.pos = pos | 0;\n if (this.pos < 0) {\n throw new Error(\"negative offset\");\n }\n }\n Tap.prototype.isValid = function() {\n return this.pos <= this.buf.length;\n };\n Tap.prototype._invalidate = function() {\n this.pos = this.buf.length + 1;\n };\n Tap.prototype.readBoolean = function() {\n return !!this.buf[this.pos++];\n };\n Tap.prototype.skipBoolean = function() {\n this.pos++;\n };\n Tap.prototype.writeBoolean = function(b2) {\n this.buf[this.pos++] = !!b2;\n };\n Tap.prototype.readInt = Tap.prototype.readLong = function() {\n var n = 0;\n var k2 = 0;\n var buf = this.buf;\n var b2, h, f3, fk;\n do {\n b2 = buf[this.pos++];\n h = b2 & 128;\n n |= (b2 & 127) << k2;\n k2 += 7;\n } while (h && k2 < 28);\n if (h) {\n f3 = n;\n fk = 268435456;\n do {\n b2 = buf[this.pos++];\n f3 += (b2 & 127) * fk;\n fk *= 128;\n } while (b2 & 128);\n return (f3 % 2 ? -(f3 + 1) : f3) / 2;\n }\n return n >> 1 ^ -(n & 1);\n };\n Tap.prototype.skipInt = Tap.prototype.skipLong = function() {\n var buf = this.buf;\n while (buf[this.pos++] & 128) {\n }\n };\n Tap.prototype.writeInt = Tap.prototype.writeLong = function(n) {\n var buf = this.buf;\n var f3, m2;\n if (n >= -1073741824 && n < 1073741824) {\n m2 = n >= 0 ? n << 1 : ~n << 1 | 1;\n do {\n buf[this.pos] = m2 & 127;\n m2 >>= 7;\n } while (m2 && (buf[this.pos++] |= 128));\n } else {\n f3 = n >= 0 ? n * 2 : -n * 2 - 1;\n do {\n buf[this.pos] = f3 & 127;\n f3 /= 128;\n } while (f3 >= 1 && (buf[this.pos++] |= 128));\n }\n this.pos++;\n };\n Tap.prototype.readFloat = function() {\n var buf = this.buf;\n var pos = this.pos;\n this.pos += 4;\n if (this.pos > buf.length) {\n return 0;\n }\n return this.buf.readFloatLE(pos);\n };\n Tap.prototype.skipFloat = function() {\n this.pos += 4;\n };\n Tap.prototype.writeFloat = function(f3) {\n var buf = this.buf;\n var pos = this.pos;\n this.pos += 4;\n if (this.pos > buf.length) {\n return;\n }\n return this.buf.writeFloatLE(f3, pos);\n };\n Tap.prototype.readDouble = function() {\n var buf = this.buf;\n var pos = this.pos;\n this.pos += 8;\n if (this.pos > buf.length) {\n return 0;\n }\n return this.buf.readDoubleLE(pos);\n };\n Tap.prototype.skipDouble = function() {\n this.pos += 8;\n };\n Tap.prototype.writeDouble = function(d) {\n var buf = this.buf;\n var pos = this.pos;\n this.pos += 8;\n if (this.pos > buf.length) {\n return;\n }\n return this.buf.writeDoubleLE(d, pos);\n };\n Tap.prototype.readFixed = function(len) {\n var pos = this.pos;\n this.pos += len;\n if (this.pos > this.buf.length) {\n return;\n }\n var fixed = POOL.alloc(len);\n this.buf.copy(fixed, 0, pos, pos + len);\n return fixed;\n };\n Tap.prototype.skipFixed = function(len) {\n this.pos += len;\n };\n Tap.prototype.writeFixed = function(buf, len) {\n len = len || buf.length;\n var pos = this.pos;\n this.pos += len;\n if (this.pos > this.buf.length) {\n return;\n }\n buf.copy(this.buf, pos, 0, len);\n };\n Tap.prototype.readBytes = function() {\n var len = this.readLong();\n if (len < 0) {\n this._invalidate();\n return;\n }\n return this.readFixed(len);\n };\n Tap.prototype.skipBytes = function() {\n var len = this.readLong();\n if (len < 0) {\n this._invalidate();\n return;\n }\n this.pos += len;\n };\n Tap.prototype.writeBytes = function(buf) {\n var len = buf.length;\n this.writeLong(len);\n this.writeFixed(buf, len);\n };\n if (typeof Buffer2.prototype.utf8Slice == \"function\") {\n Tap.prototype.readString = function() {\n var len = this.readLong();\n if (len < 0) {\n this._invalidate();\n return \"\";\n }\n var pos = this.pos;\n var buf = this.buf;\n this.pos += len;\n if (this.pos > buf.length) {\n return;\n }\n return this.buf.utf8Slice(pos, pos + len);\n };\n } else {\n Tap.prototype.readString = function() {\n var len = this.readLong();\n if (len < 0) {\n this._invalidate();\n return \"\";\n }\n var pos = this.pos;\n var buf = this.buf;\n this.pos += len;\n if (this.pos > buf.length) {\n return;\n }\n return this.buf.slice(pos, pos + len).toString();\n };\n }\n Tap.prototype.skipString = function() {\n var len = this.readLong();\n if (len < 0) {\n this._invalidate();\n return;\n }\n this.pos += len;\n };\n Tap.prototype.writeString = function(s) {\n var len = Buffer2.byteLength(s);\n var buf = this.buf;\n this.writeLong(len);\n var pos = this.pos;\n this.pos += len;\n if (this.pos > buf.length) {\n return;\n }\n if (len > 64 && typeof Buffer2.prototype.utf8Write == \"function\") {\n buf.utf8Write(s, pos, len);\n } else {\n var i, l, c1, c2;\n for (i = 0, l = len; i < l; i++) {\n c1 = s.charCodeAt(i);\n if (c1 < 128) {\n buf[pos++] = c1;\n } else if (c1 < 2048) {\n buf[pos++] = c1 >> 6 | 192;\n buf[pos++] = c1 & 63 | 128;\n } else if ((c1 & 64512) === 55296 && ((c2 = s.charCodeAt(i + 1)) & 64512) === 56320) {\n c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023);\n i++;\n buf[pos++] = c1 >> 18 | 240;\n buf[pos++] = c1 >> 12 & 63 | 128;\n buf[pos++] = c1 >> 6 & 63 | 128;\n buf[pos++] = c1 & 63 | 128;\n } else {\n buf[pos++] = c1 >> 12 | 224;\n buf[pos++] = c1 >> 6 & 63 | 128;\n buf[pos++] = c1 & 63 | 128;\n }\n }\n }\n };\n if (typeof Buffer2.prototype.latin1Write == \"function\") {\n Tap.prototype.writeBinary = function(str, len) {\n var pos = this.pos;\n this.pos += len;\n if (this.pos > this.buf.length) {\n return;\n }\n this.buf.latin1Write(str, pos, len);\n };\n } else if (typeof Buffer2.prototype.binaryWrite == \"function\") {\n Tap.prototype.writeBinary = function(str, len) {\n var pos = this.pos;\n this.pos += len;\n if (this.pos > this.buf.length) {\n return;\n }\n this.buf.binaryWrite(str, pos, len);\n };\n } else {\n Tap.prototype.writeBinary = function(s, len) {\n var pos = this.pos;\n this.pos += len;\n if (this.pos > this.buf.length) {\n return;\n }\n this.buf.write(s, pos, len, \"binary\");\n };\n }\n Tap.prototype.matchBoolean = function(tap) {\n return this.buf[this.pos++] - tap.buf[tap.pos++];\n };\n Tap.prototype.matchInt = Tap.prototype.matchLong = function(tap) {\n var n1 = this.readLong();\n var n2 = tap.readLong();\n return n1 === n2 ? 0 : n1 < n2 ? -1 : 1;\n };\n Tap.prototype.matchFloat = function(tap) {\n var n1 = this.readFloat();\n var n2 = tap.readFloat();\n return n1 === n2 ? 0 : n1 < n2 ? -1 : 1;\n };\n Tap.prototype.matchDouble = function(tap) {\n var n1 = this.readDouble();\n var n2 = tap.readDouble();\n return n1 === n2 ? 0 : n1 < n2 ? -1 : 1;\n };\n Tap.prototype.matchFixed = function(tap, len) {\n return this.readFixed(len).compare(tap.readFixed(len));\n };\n Tap.prototype.matchBytes = Tap.prototype.matchString = function(tap) {\n var l1 = this.readLong();\n var p1 = this.pos;\n this.pos += l1;\n var l2 = tap.readLong();\n var p2 = tap.pos;\n tap.pos += l2;\n var b1 = this.buf.slice(p1, this.pos);\n var b2 = tap.buf.slice(p2, tap.pos);\n return b1.compare(b2);\n };\n Tap.prototype.unpackLongBytes = function() {\n var res = newBuffer(8);\n var n = 0;\n var i = 0;\n var j2 = 6;\n var buf = this.buf;\n var b2, neg;\n b2 = buf[this.pos++];\n neg = b2 & 1;\n res.fill(0);\n n |= (b2 & 127) >> 1;\n while (b2 & 128) {\n b2 = buf[this.pos++];\n n |= (b2 & 127) << j2;\n j2 += 7;\n if (j2 >= 8) {\n j2 -= 8;\n res[i++] = n;\n n >>= 8;\n }\n }\n res[i] = n;\n if (neg) {\n invert(res, 8);\n }\n return res;\n };\n Tap.prototype.packLongBytes = function(buf) {\n var neg = (buf[7] & 128) >> 7;\n var res = this.buf;\n var j2 = 1;\n var k2 = 0;\n var m2 = 3;\n var n;\n if (neg) {\n invert(buf, 8);\n n = 1;\n } else {\n n = 0;\n }\n var parts = [\n buf.readUIntLE(0, 3),\n buf.readUIntLE(3, 3),\n buf.readUIntLE(6, 2)\n ];\n while (m2 && !parts[--m2]) {\n }\n while (k2 < m2) {\n n |= parts[k2++] << j2;\n j2 += 24;\n while (j2 > 7) {\n res[this.pos++] = n & 127 | 128;\n n >>= 7;\n j2 -= 7;\n }\n }\n n |= parts[m2] << j2;\n do {\n res[this.pos] = n & 127;\n n >>= 7;\n } while (n && (res[this.pos++] |= 128));\n this.pos++;\n if (neg) {\n invert(buf, 8);\n }\n };\n function invert(buf, len) {\n while (len--) {\n buf[len] = ~buf[len];\n }\n }\n module.exports = {\n abstractFunction,\n addDeprecatedGetters,\n bufferFrom,\n capitalize,\n copyOwnProperties,\n getHash,\n compare,\n getOption,\n impliedNamespace,\n isValidName,\n jsonEnd,\n newBuffer,\n objectValues,\n qualify,\n toMap,\n singleIndexOf,\n hasDuplicates,\n unqualify,\n BufferPool,\n Lcg,\n OrderedQueue,\n Tap\n };\n }\n});\n\n// node_modules/avsc/lib/types.js\nvar require_types = __commonJS({\n \"node_modules/avsc/lib/types.js\"(exports, module) {\n \"use strict\";\n var utils = require_utils();\n var buffer = __import_BUFFER;\n var util = __import_UTIL;\n var Buffer2 = buffer.Buffer;\n var SlowBuffer = buffer.SlowBuffer;\n var Tap = utils.Tap;\n var debug = util.debuglog(\"avsc:types\");\n var f2 = util.format;\n var TYPES = {\n \"array\": ArrayType,\n \"boolean\": BooleanType,\n \"bytes\": BytesType,\n \"double\": DoubleType,\n \"enum\": EnumType,\n \"error\": RecordType,\n \"fixed\": FixedType,\n \"float\": FloatType,\n \"int\": IntType,\n \"long\": LongType,\n \"map\": MapType,\n \"null\": NullType,\n \"record\": RecordType,\n \"string\": StringType\n };\n var RANDOM = new utils.Lcg();\n var TAP = new Tap(new SlowBuffer(1024));\n var LOGICAL_TYPE = null;\n var UNDERLYING_TYPES = [];\n function Type(schema, opts) {\n var type;\n if (LOGICAL_TYPE) {\n type = LOGICAL_TYPE;\n UNDERLYING_TYPES.push([LOGICAL_TYPE, this]);\n LOGICAL_TYPE = null;\n } else {\n type = this;\n }\n this._hash = new Hash();\n this.name = void 0;\n this.aliases = void 0;\n this.doc = schema && schema.doc ? \"\" + schema.doc : void 0;\n if (schema) {\n var name = schema.name;\n var namespace = schema.namespace === void 0 ? opts && opts.namespace : schema.namespace;\n if (name !== void 0) {\n name = maybeQualify(name, namespace);\n if (isPrimitive(name)) {\n throw new Error(f2(\"cannot rename primitive type: %j\", name));\n }\n var registry = opts && opts.registry;\n if (registry) {\n if (registry[name] !== void 0) {\n throw new Error(f2(\"duplicate type name: %s\", name));\n }\n registry[name] = type;\n }\n } else if (opts && opts.noAnonymousTypes) {\n throw new Error(f2(\"missing name property in schema: %j\", schema));\n }\n this.name = name;\n this.aliases = schema.aliases ? schema.aliases.map(function(s) {\n return maybeQualify(s, namespace);\n }) : [];\n }\n }\n Type.forSchema = function(schema, opts) {\n opts = opts || {};\n opts.registry = opts.registry || {};\n var UnionType2 = function(wrapUnions) {\n if (wrapUnions === true) {\n wrapUnions = \"always\";\n } else if (wrapUnions === false) {\n wrapUnions = \"never\";\n } else if (wrapUnions === void 0) {\n wrapUnions = \"auto\";\n } else if (typeof wrapUnions == \"string\") {\n wrapUnions = wrapUnions.toLowerCase();\n }\n switch (wrapUnions) {\n case \"always\":\n return WrappedUnionType;\n case \"never\":\n return UnwrappedUnionType;\n case \"auto\":\n return void 0;\n default:\n throw new Error(f2(\"invalid wrap unions option: %j\", wrapUnions));\n }\n }(opts.wrapUnions);\n if (schema === null) {\n throw new Error('invalid type: null (did you mean \"null\"?)');\n }\n if (Type.isType(schema)) {\n return schema;\n }\n var type;\n if (opts.typeHook && (type = opts.typeHook(schema, opts))) {\n if (!Type.isType(type)) {\n throw new Error(f2(\"invalid typehook return value: %j\", type));\n }\n return type;\n }\n if (typeof schema == \"string\") {\n schema = maybeQualify(schema, opts.namespace);\n type = opts.registry[schema];\n if (type) {\n return type;\n }\n if (isPrimitive(schema)) {\n return opts.registry[schema] = Type.forSchema({ type: schema }, opts);\n }\n throw new Error(f2(\"undefined type name: %s\", schema));\n }\n if (schema.logicalType && opts.logicalTypes && !LOGICAL_TYPE) {\n var DerivedType = opts.logicalTypes[schema.logicalType];\n if (DerivedType) {\n var namespace = opts.namespace;\n var registry = {};\n Object.keys(opts.registry).forEach(function(key) {\n registry[key] = opts.registry[key];\n });\n try {\n debug(\"instantiating logical type for %s\", schema.logicalType);\n return new DerivedType(schema, opts);\n } catch (err) {\n debug(\"failed to instantiate logical type for %s\", schema.logicalType);\n if (opts.assertLogicalTypes) {\n throw err;\n }\n LOGICAL_TYPE = null;\n opts.namespace = namespace;\n opts.registry = registry;\n }\n }\n }\n if (Array.isArray(schema)) {\n var logicalType = LOGICAL_TYPE;\n LOGICAL_TYPE = null;\n var types = schema.map(function(obj) {\n return Type.forSchema(obj, opts);\n });\n if (!UnionType2) {\n UnionType2 = isAmbiguous(types) ? WrappedUnionType : UnwrappedUnionType;\n }\n LOGICAL_TYPE = logicalType;\n type = new UnionType2(types, opts);\n } else {\n type = function(typeName) {\n var Type2 = TYPES[typeName];\n if (Type2 === void 0) {\n throw new Error(f2(\"unknown type: %j\", typeName));\n }\n return new Type2(schema, opts);\n }(schema.type);\n }\n return type;\n };\n Type.forValue = function(val, opts) {\n opts = opts || {};\n opts.emptyArrayType = opts.emptyArrayType || Type.forSchema({\n type: \"array\",\n items: \"null\"\n });\n if (opts.valueHook) {\n var type = opts.valueHook(val, opts);\n if (type !== void 0) {\n if (!Type.isType(type)) {\n throw new Error(f2(\"invalid value hook return value: %j\", type));\n }\n return type;\n }\n }\n switch (typeof val) {\n case \"string\":\n return Type.forSchema(\"string\", opts);\n case \"boolean\":\n return Type.forSchema(\"boolean\", opts);\n case \"number\":\n if ((val | 0) === val) {\n return Type.forSchema(\"int\", opts);\n } else if (Math.abs(val) < 9007199254740991) {\n return Type.forSchema(\"float\", opts);\n }\n return Type.forSchema(\"double\", opts);\n case \"object\":\n if (val === null) {\n return Type.forSchema(\"null\", opts);\n } else if (Array.isArray(val)) {\n if (!val.length) {\n return opts.emptyArrayType;\n }\n return Type.forSchema({\n type: \"array\",\n items: Type.forTypes(\n val.map(function(v2) {\n return Type.forValue(v2, opts);\n }),\n opts\n )\n }, opts);\n } else if (Buffer2.isBuffer(val)) {\n return Type.forSchema(\"bytes\", opts);\n }\n var fieldNames = Object.keys(val);\n if (fieldNames.some(function(s) {\n return !utils.isValidName(s);\n })) {\n return Type.forSchema({\n type: \"map\",\n values: Type.forTypes(fieldNames.map(function(s) {\n return Type.forValue(val[s], opts);\n }), opts)\n }, opts);\n }\n return Type.forSchema({\n type: \"record\",\n fields: fieldNames.map(function(s) {\n return { name: s, type: Type.forValue(val[s], opts) };\n })\n }, opts);\n default:\n throw new Error(f2(\"cannot infer type from: %j\", val));\n }\n };\n Type.forTypes = function(types, opts) {\n if (!types.length) {\n throw new Error(\"no types to combine\");\n }\n if (types.length === 1) {\n return types[0];\n }\n opts = opts || {};\n var expanded = [];\n var numWrappedUnions = 0;\n var isValidWrappedUnion = true;\n types.forEach(function(type) {\n switch (type.typeName) {\n case \"union:unwrapped\":\n isValidWrappedUnion = false;\n expanded = expanded.concat(type.types);\n break;\n case \"union:wrapped\":\n numWrappedUnions++;\n expanded = expanded.concat(type.types);\n break;\n case \"null\":\n expanded.push(type);\n break;\n default:\n isValidWrappedUnion = false;\n expanded.push(type);\n }\n });\n if (numWrappedUnions) {\n if (!isValidWrappedUnion) {\n throw new Error(\"cannot combine wrapped union\");\n }\n var branchTypes = {};\n expanded.forEach(function(type) {\n var name = type.branchName;\n var branchType = branchTypes[name];\n if (!branchType) {\n branchTypes[name] = type;\n } else if (!type.equals(branchType)) {\n throw new Error(\"inconsistent branch type\");\n }\n });\n var wrapUnions = opts.wrapUnions;\n var unionType;\n opts.wrapUnions = true;\n try {\n unionType = Type.forSchema(Object.keys(branchTypes).map(function(name) {\n return branchTypes[name];\n }), opts);\n } catch (err) {\n opts.wrapUnions = wrapUnions;\n throw err;\n }\n opts.wrapUnions = wrapUnions;\n return unionType;\n }\n var bucketized = {};\n expanded.forEach(function(type) {\n var bucket = getTypeBucket(type);\n var bucketTypes = bucketized[bucket];\n if (!bucketTypes) {\n bucketized[bucket] = bucketTypes = [];\n }\n bucketTypes.push(type);\n });\n var buckets = Object.keys(bucketized);\n var augmented = buckets.map(function(bucket) {\n var bucketTypes = bucketized[bucket];\n if (bucketTypes.length === 1) {\n return bucketTypes[0];\n } else {\n switch (bucket) {\n case \"null\":\n case \"boolean\":\n return bucketTypes[0];\n case \"number\":\n return combineNumbers(bucketTypes);\n case \"string\":\n return combineStrings(bucketTypes, opts);\n case \"buffer\":\n return combineBuffers(bucketTypes, opts);\n case \"array\":\n bucketTypes = bucketTypes.filter(function(t) {\n return t !== opts.emptyArrayType;\n });\n if (!bucketTypes.length) {\n return opts.emptyArrayType;\n }\n return Type.forSchema({\n type: \"array\",\n items: Type.forTypes(bucketTypes.map(function(t) {\n return t.itemsType;\n }), opts)\n }, opts);\n default:\n return combineObjects(bucketTypes, opts);\n }\n }\n });\n if (augmented.length === 1) {\n return augmented[0];\n } else {\n return Type.forSchema(augmented, opts);\n }\n };\n Type.isType = function() {\n var l = arguments.length;\n if (!l) {\n return false;\n }\n var any = arguments[0];\n if (!any || typeof any._update != \"function\" || typeof any.fingerprint != \"function\") {\n return false;\n }\n if (l === 1) {\n return true;\n }\n var typeName = any.typeName;\n var i;\n for (i = 1; i < l; i++) {\n if (typeName.indexOf(arguments[i]) === 0) {\n return true;\n }\n }\n return false;\n };\n Type.__reset = function(size) {\n debug(\"resetting type buffer to %d\", size);\n TAP.buf = new SlowBuffer(size);\n };\n Object.defineProperty(Type.prototype, \"branchName\", {\n enumerable: true,\n get: function() {\n var type = Type.isType(this, \"logical\") ? this.underlyingType : this;\n if (type.name) {\n return type.name;\n }\n if (Type.isType(type, \"abstract\")) {\n return type._concreteTypeName;\n }\n return Type.isType(type, \"union\") ? void 0 : type.typeName;\n }\n });\n Type.prototype.clone = function(val, opts) {\n if (opts) {\n opts = {\n coerce: !!opts.coerceBuffers | 0,\n // Coerce JSON to Buffer.\n fieldHook: opts.fieldHook,\n qualifyNames: !!opts.qualifyNames,\n skip: !!opts.skipMissingFields,\n wrap: !!opts.wrapUnions | 0\n // Wrap first match into union.\n };\n return this._copy(val, opts);\n } else {\n return this.fromBuffer(this.toBuffer(val));\n }\n };\n Type.prototype.compare = utils.abstractFunction;\n Type.prototype.compareBuffers = function(buf1, buf2) {\n return this._match(new Tap(buf1), new Tap(buf2));\n };\n Type.prototype.createResolver = function(type, opts) {\n if (!Type.isType(type)) {\n throw new Error(f2(\"not a type: %j\", type));\n }\n if (!Type.isType(this, \"union\", \"logical\") && Type.isType(type, \"logical\")) {\n return this.createResolver(type.underlyingType, opts);\n }\n opts = opts || {};\n opts.registry = opts.registry || {};\n var resolver, key;\n if (Type.isType(this, \"record\", \"error\") && Type.isType(type, \"record\", \"error\")) {\n key = this.name + \":\" + type.name;\n resolver = opts.registry[key];\n if (resolver) {\n return resolver;\n }\n }\n resolver = new Resolver(this);\n if (key) {\n opts.registry[key] = resolver;\n }\n if (Type.isType(type, \"union\")) {\n var resolvers = type.types.map(function(t) {\n return this.createResolver(t, opts);\n }, this);\n resolver._read = function(tap) {\n var index = tap.readLong();\n var resolver2 = resolvers[index];\n if (resolver2 === void 0) {\n throw new Error(f2(\"invalid union index: %s\", index));\n }\n return resolvers[index]._read(tap);\n };\n } else {\n this._update(resolver, type, opts);\n }\n if (!resolver._read) {\n throw new Error(f2(\"cannot read %s as %s\", type, this));\n }\n return Object.freeze(resolver);\n };\n Type.prototype.decode = function(buf, pos, resolver) {\n var tap = new Tap(buf, pos);\n var val = readValue(this, tap, resolver);\n if (!tap.isValid()) {\n return { value: void 0, offset: -1 };\n }\n return { value: val, offset: tap.pos };\n };\n Type.prototype.encode = function(val, buf, pos) {\n var tap = new Tap(buf, pos);\n this._write(tap, val);\n if (!tap.isValid()) {\n return buf.length - tap.pos;\n }\n return tap.pos;\n };\n Type.prototype.equals = function(type, opts) {\n var canon = (\n // Canonical equality.\n Type.isType(type) && this.fingerprint().equals(type.fingerprint())\n );\n if (!canon || !(opts && opts.strict)) {\n return canon;\n }\n return JSON.stringify(this.schema({ exportAttrs: true })) === JSON.stringify(type.schema({ exportAttrs: true }));\n };\n Type.prototype.fingerprint = function(algorithm) {\n if (!algorithm) {\n if (!this._hash.str) {\n var schemaStr = JSON.stringify(this.schema());\n this._hash.str = utils.getHash(schemaStr).toString(\"binary\");\n }\n return utils.bufferFrom(this._hash.str, \"binary\");\n } else {\n return utils.getHash(JSON.stringify(this.schema()), algorithm);\n }\n };\n Type.prototype.fromBuffer = function(buf, resolver, noCheck) {\n var tap = new Tap(buf);\n var val = readValue(this, tap, resolver, noCheck);\n if (!tap.isValid()) {\n throw new Error(\"truncated buffer\");\n }\n if (!noCheck && tap.pos < buf.length) {\n throw new Error(\"trailing data\");\n }\n return val;\n };\n Type.prototype.fromString = function(str) {\n return this._copy(JSON.parse(str), { coerce: 2 });\n };\n Type.prototype.inspect = function() {\n var typeName = this.typeName;\n var className = getClassName(typeName);\n if (isPrimitive(typeName)) {\n return f2(\"<%s>\", className);\n } else {\n var obj = this.schema({ exportAttrs: true, noDeref: true });\n if (typeof obj == \"object\" && !Type.isType(this, \"logical\")) {\n obj.type = void 0;\n }\n return f2(\"<%s %j>\", className, obj);\n }\n };\n Type.prototype.isValid = function(val, opts) {\n var flags = (opts && opts.noUndeclaredFields) | 0;\n var errorHook = opts && opts.errorHook;\n var hook, path;\n if (errorHook) {\n path = [];\n hook = function(any, type) {\n errorHook.call(this, path.slice(), any, type, val);\n };\n }\n return this._check(val, flags, hook, path);\n };\n Type.prototype.random = utils.abstractFunction;\n Type.prototype.schema = function(opts) {\n return this._attrs({\n exportAttrs: !!(opts && opts.exportAttrs),\n noDeref: !!(opts && opts.noDeref)\n });\n };\n Type.prototype.toBuffer = function(val) {\n TAP.pos = 0;\n this._write(TAP, val);\n var buf = utils.newBuffer(TAP.pos);\n if (TAP.isValid()) {\n TAP.buf.copy(buf, 0, 0, TAP.pos);\n } else {\n this._write(new Tap(buf), val);\n }\n return buf;\n };\n Type.prototype.toJSON = function() {\n return this.schema({ exportAttrs: true });\n };\n Type.prototype.toString = function(val) {\n if (val === void 0) {\n return JSON.stringify(this.schema({ noDeref: true }));\n }\n return JSON.stringify(this._copy(val, { coerce: 3 }));\n };\n Type.prototype.wrap = function(val) {\n var Branch = this._branchConstructor;\n return Branch === null ? null : new Branch(val);\n };\n Type.prototype._attrs = function(opts) {\n opts.derefed = opts.derefed || {};\n var name = this.name;\n if (name !== void 0) {\n if (opts.noDeref || opts.derefed[name]) {\n return name;\n }\n opts.derefed[name] = true;\n }\n var schema = {};\n if (this.name !== void 0) {\n schema.name = name;\n }\n schema.type = this.typeName;\n var derefedSchema = this._deref(schema, opts);\n if (derefedSchema !== void 0) {\n schema = derefedSchema;\n }\n if (opts.exportAttrs) {\n if (this.aliases && this.aliases.length) {\n schema.aliases = this.aliases;\n }\n if (this.doc !== void 0) {\n schema.doc = this.doc;\n }\n }\n return schema;\n };\n Type.prototype._createBranchConstructor = function() {\n var name = this.branchName;\n if (name === \"null\") {\n return null;\n }\n var attr = ~name.indexOf(\".\") ? \"this['\" + name + \"']\" : \"this.\" + name;\n var body = \"return function Branch$(val) { \" + attr + \" = val; };\";\n var Branch = new Function(body)();\n Branch.type = this;\n Branch.prototype.unwrap = new Function(\"return \" + attr + \";\");\n Branch.prototype.unwrapped = Branch.prototype.unwrap;\n return Branch;\n };\n Type.prototype._peek = function(tap) {\n var pos = tap.pos;\n var val = this._read(tap);\n tap.pos = pos;\n return val;\n };\n Type.prototype._check = utils.abstractFunction;\n Type.prototype._copy = utils.abstractFunction;\n Type.prototype._deref = utils.abstractFunction;\n Type.prototype._match = utils.abstractFunction;\n Type.prototype._read = utils.abstractFunction;\n Type.prototype._skip = utils.abstractFunction;\n Type.prototype._update = utils.abstractFunction;\n Type.prototype._write = utils.abstractFunction;\n Type.prototype.getAliases = function() {\n return this.aliases;\n };\n Type.prototype.getFingerprint = Type.prototype.fingerprint;\n Type.prototype.getName = function(asBranch) {\n return this.name || !asBranch ? this.name : this.branchName;\n };\n Type.prototype.getSchema = Type.prototype.schema;\n Type.prototype.getTypeName = function() {\n return this.typeName;\n };\n function PrimitiveType(noFreeze) {\n Type.call(this);\n this._branchConstructor = this._createBranchConstructor();\n if (!noFreeze) {\n Object.freeze(this);\n }\n }\n util.inherits(PrimitiveType, Type);\n PrimitiveType.prototype._update = function(resolver, type) {\n if (type.typeName === this.typeName) {\n resolver._read = this._read;\n }\n };\n PrimitiveType.prototype._copy = function(val) {\n this._check(val, void 0, throwInvalidError);\n return val;\n };\n PrimitiveType.prototype._deref = function() {\n return this.typeName;\n };\n PrimitiveType.prototype.compare = utils.compare;\n function NullType() {\n PrimitiveType.call(this);\n }\n util.inherits(NullType, PrimitiveType);\n NullType.prototype._check = function(val, flags, hook) {\n var b2 = val === null;\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n NullType.prototype._read = function() {\n return null;\n };\n NullType.prototype._skip = function() {\n };\n NullType.prototype._write = function(tap, val) {\n if (val !== null) {\n throwInvalidError(val, this);\n }\n };\n NullType.prototype._match = function() {\n return 0;\n };\n NullType.prototype.compare = NullType.prototype._match;\n NullType.prototype.typeName = \"null\";\n NullType.prototype.random = NullType.prototype._read;\n function BooleanType() {\n PrimitiveType.call(this);\n }\n util.inherits(BooleanType, PrimitiveType);\n BooleanType.prototype._check = function(val, flags, hook) {\n var b2 = typeof val == \"boolean\";\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n BooleanType.prototype._read = function(tap) {\n return tap.readBoolean();\n };\n BooleanType.prototype._skip = function(tap) {\n tap.skipBoolean();\n };\n BooleanType.prototype._write = function(tap, val) {\n if (typeof val != \"boolean\") {\n throwInvalidError(val, this);\n }\n tap.writeBoolean(val);\n };\n BooleanType.prototype._match = function(tap1, tap2) {\n return tap1.matchBoolean(tap2);\n };\n BooleanType.prototype.typeName = \"boolean\";\n BooleanType.prototype.random = function() {\n return RANDOM.nextBoolean();\n };\n function IntType() {\n PrimitiveType.call(this);\n }\n util.inherits(IntType, PrimitiveType);\n IntType.prototype._check = function(val, flags, hook) {\n var b2 = val === (val | 0);\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n IntType.prototype._read = function(tap) {\n return tap.readInt();\n };\n IntType.prototype._skip = function(tap) {\n tap.skipInt();\n };\n IntType.prototype._write = function(tap, val) {\n if (val !== (val | 0)) {\n throwInvalidError(val, this);\n }\n tap.writeInt(val);\n };\n IntType.prototype._match = function(tap1, tap2) {\n return tap1.matchInt(tap2);\n };\n IntType.prototype.typeName = \"int\";\n IntType.prototype.random = function() {\n return RANDOM.nextInt(1e3) | 0;\n };\n function LongType() {\n PrimitiveType.call(this);\n }\n util.inherits(LongType, PrimitiveType);\n LongType.prototype._check = function(val, flags, hook) {\n var b2 = typeof val == \"number\" && val % 1 === 0 && isSafeLong(val);\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n LongType.prototype._read = function(tap) {\n var n = tap.readLong();\n if (!isSafeLong(n)) {\n throw new Error(\"potential precision loss\");\n }\n return n;\n };\n LongType.prototype._skip = function(tap) {\n tap.skipLong();\n };\n LongType.prototype._write = function(tap, val) {\n if (typeof val != \"number\" || val % 1 || !isSafeLong(val)) {\n throwInvalidError(val, this);\n }\n tap.writeLong(val);\n };\n LongType.prototype._match = function(tap1, tap2) {\n return tap1.matchLong(tap2);\n };\n LongType.prototype._update = function(resolver, type) {\n switch (type.typeName) {\n case \"int\":\n resolver._read = type._read;\n break;\n case \"abstract:long\":\n case \"long\":\n resolver._read = this._read;\n }\n };\n LongType.prototype.typeName = \"long\";\n LongType.prototype.random = function() {\n return RANDOM.nextInt();\n };\n LongType.__with = function(methods, noUnpack) {\n methods = methods || {};\n var mapping = {\n toBuffer: \"_toBuffer\",\n fromBuffer: \"_fromBuffer\",\n fromJSON: \"_fromJSON\",\n toJSON: \"_toJSON\",\n isValid: \"_isValid\",\n compare: \"compare\"\n };\n var type = new AbstractLongType(noUnpack);\n Object.keys(mapping).forEach(function(name) {\n if (methods[name] === void 0) {\n throw new Error(f2(\"missing method implementation: %s\", name));\n }\n type[mapping[name]] = methods[name];\n });\n return Object.freeze(type);\n };\n function FloatType() {\n PrimitiveType.call(this);\n }\n util.inherits(FloatType, PrimitiveType);\n FloatType.prototype._check = function(val, flags, hook) {\n var b2 = typeof val == \"number\";\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n FloatType.prototype._read = function(tap) {\n return tap.readFloat();\n };\n FloatType.prototype._skip = function(tap) {\n tap.skipFloat();\n };\n FloatType.prototype._write = function(tap, val) {\n if (typeof val != \"number\") {\n throwInvalidError(val, this);\n }\n tap.writeFloat(val);\n };\n FloatType.prototype._match = function(tap1, tap2) {\n return tap1.matchFloat(tap2);\n };\n FloatType.prototype._update = function(resolver, type) {\n switch (type.typeName) {\n case \"float\":\n case \"int\":\n resolver._read = type._read;\n break;\n case \"abstract:long\":\n case \"long\":\n resolver._read = function(tap) {\n return tap.readLong();\n };\n }\n };\n FloatType.prototype.typeName = \"float\";\n FloatType.prototype.random = function() {\n return RANDOM.nextFloat(1e3);\n };\n function DoubleType() {\n PrimitiveType.call(this);\n }\n util.inherits(DoubleType, PrimitiveType);\n DoubleType.prototype._check = function(val, flags, hook) {\n var b2 = typeof val == \"number\";\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n DoubleType.prototype._read = function(tap) {\n return tap.readDouble();\n };\n DoubleType.prototype._skip = function(tap) {\n tap.skipDouble();\n };\n DoubleType.prototype._write = function(tap, val) {\n if (typeof val != \"number\") {\n throwInvalidError(val, this);\n }\n tap.writeDouble(val);\n };\n DoubleType.prototype._match = function(tap1, tap2) {\n return tap1.matchDouble(tap2);\n };\n DoubleType.prototype._update = function(resolver, type) {\n switch (type.typeName) {\n case \"double\":\n case \"float\":\n case \"int\":\n resolver._read = type._read;\n break;\n case \"abstract:long\":\n case \"long\":\n resolver._read = function(tap) {\n return tap.readLong();\n };\n }\n };\n DoubleType.prototype.typeName = \"double\";\n DoubleType.prototype.random = function() {\n return RANDOM.nextFloat();\n };\n function StringType() {\n PrimitiveType.call(this);\n }\n util.inherits(StringType, PrimitiveType);\n StringType.prototype._check = function(val, flags, hook) {\n var b2 = typeof val == \"string\";\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n StringType.prototype._read = function(tap) {\n return tap.readString();\n };\n StringType.prototype._skip = function(tap) {\n tap.skipString();\n };\n StringType.prototype._write = function(tap, val) {\n if (typeof val != \"string\") {\n throwInvalidError(val, this);\n }\n tap.writeString(val);\n };\n StringType.prototype._match = function(tap1, tap2) {\n return tap1.matchString(tap2);\n };\n StringType.prototype._update = function(resolver, type) {\n switch (type.typeName) {\n case \"bytes\":\n case \"string\":\n resolver._read = this._read;\n }\n };\n StringType.prototype.typeName = \"string\";\n StringType.prototype.random = function() {\n return RANDOM.nextString(RANDOM.nextInt(32));\n };\n function BytesType() {\n PrimitiveType.call(this);\n }\n util.inherits(BytesType, PrimitiveType);\n BytesType.prototype._check = function(val, flags, hook) {\n var b2 = Buffer2.isBuffer(val);\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n BytesType.prototype._read = function(tap) {\n return tap.readBytes();\n };\n BytesType.prototype._skip = function(tap) {\n tap.skipBytes();\n };\n BytesType.prototype._write = function(tap, val) {\n if (!Buffer2.isBuffer(val)) {\n throwInvalidError(val, this);\n }\n tap.writeBytes(val);\n };\n BytesType.prototype._match = function(tap1, tap2) {\n return tap1.matchBytes(tap2);\n };\n BytesType.prototype._update = StringType.prototype._update;\n BytesType.prototype._copy = function(obj, opts) {\n var buf;\n switch ((opts && opts.coerce) | 0) {\n case 3:\n this._check(obj, void 0, throwInvalidError);\n return obj.toString(\"binary\");\n case 2:\n if (typeof obj != \"string\") {\n throw new Error(f2(\"cannot coerce to buffer: %j\", obj));\n }\n buf = utils.bufferFrom(obj, \"binary\");\n this._check(buf, void 0, throwInvalidError);\n return buf;\n case 1:\n if (!isJsonBuffer(obj)) {\n throw new Error(f2(\"cannot coerce to buffer: %j\", obj));\n }\n buf = utils.bufferFrom(obj.data);\n this._check(buf, void 0, throwInvalidError);\n return buf;\n default:\n this._check(obj, void 0, throwInvalidError);\n return utils.bufferFrom(obj);\n }\n };\n BytesType.prototype.compare = Buffer2.compare;\n BytesType.prototype.typeName = \"bytes\";\n BytesType.prototype.random = function() {\n return RANDOM.nextBuffer(RANDOM.nextInt(32));\n };\n function UnionType(schema, opts) {\n Type.call(this);\n if (!Array.isArray(schema)) {\n throw new Error(f2(\"non-array union schema: %j\", schema));\n }\n if (!schema.length) {\n throw new Error(\"empty union\");\n }\n this.types = Object.freeze(schema.map(function(obj) {\n return Type.forSchema(obj, opts);\n }));\n this._branchIndices = {};\n this.types.forEach(function(type, i) {\n if (Type.isType(type, \"union\")) {\n throw new Error(\"unions cannot be directly nested\");\n }\n var branch = type.branchName;\n if (this._branchIndices[branch] !== void 0) {\n throw new Error(f2(\"duplicate union branch name: %j\", branch));\n }\n this._branchIndices[branch] = i;\n }, this);\n }\n util.inherits(UnionType, Type);\n UnionType.prototype._branchConstructor = function() {\n throw new Error(\"unions cannot be directly wrapped\");\n };\n UnionType.prototype._skip = function(tap) {\n this.types[tap.readLong()]._skip(tap);\n };\n UnionType.prototype._match = function(tap1, tap2) {\n var n1 = tap1.readLong();\n var n2 = tap2.readLong();\n if (n1 === n2) {\n return this.types[n1]._match(tap1, tap2);\n } else {\n return n1 < n2 ? -1 : 1;\n }\n };\n UnionType.prototype._deref = function(schema, opts) {\n return this.types.map(function(t) {\n return t._attrs(opts);\n });\n };\n UnionType.prototype.getTypes = function() {\n return this.types;\n };\n function UnwrappedUnionType(schema, opts) {\n UnionType.call(this, schema, opts);\n this._dynamicBranches = null;\n this._bucketIndices = {};\n this.types.forEach(function(type, index) {\n if (Type.isType(type, \"abstract\", \"logical\")) {\n if (!this._dynamicBranches) {\n this._dynamicBranches = [];\n }\n this._dynamicBranches.push({ index, type });\n } else {\n var bucket = getTypeBucket(type);\n if (this._bucketIndices[bucket] !== void 0) {\n throw new Error(f2(\"ambiguous unwrapped union: %j\", this));\n }\n this._bucketIndices[bucket] = index;\n }\n }, this);\n Object.freeze(this);\n }\n util.inherits(UnwrappedUnionType, UnionType);\n UnwrappedUnionType.prototype._getIndex = function(val) {\n var index = this._bucketIndices[getValueBucket(val)];\n if (this._dynamicBranches) {\n index = this._getBranchIndex(val, index);\n }\n return index;\n };\n UnwrappedUnionType.prototype._getBranchIndex = function(any, index) {\n var logicalBranches = this._dynamicBranches;\n var i, l, branch;\n for (i = 0, l = logicalBranches.length; i < l; i++) {\n branch = logicalBranches[i];\n if (branch.type._check(any)) {\n if (index === void 0) {\n index = branch.index;\n } else {\n throw new Error(\"ambiguous conversion\");\n }\n }\n }\n return index;\n };\n UnwrappedUnionType.prototype._check = function(val, flags, hook, path) {\n var index = this._getIndex(val);\n var b2 = index !== void 0;\n if (b2) {\n return this.types[index]._check(val, flags, hook, path);\n }\n if (hook) {\n hook(val, this);\n }\n return b2;\n };\n UnwrappedUnionType.prototype._read = function(tap) {\n var index = tap.readLong();\n var branchType = this.types[index];\n if (branchType) {\n return branchType._read(tap);\n } else {\n throw new Error(f2(\"invalid union index: %s\", index));\n }\n };\n UnwrappedUnionType.prototype._write = function(tap, val) {\n var index = this._getIndex(val);\n if (index === void 0) {\n throwInvalidError(val, this);\n }\n tap.writeLong(index);\n if (val !== null) {\n this.types[index]._write(tap, val);\n }\n };\n UnwrappedUnionType.prototype._update = function(resolver, type, opts) {\n var i, l, typeResolver;\n for (i = 0, l = this.types.length; i < l; i++) {\n try {\n typeResolver = this.types[i].createResolver(type, opts);\n } catch (err) {\n continue;\n }\n resolver._read = function(tap) {\n return typeResolver._read(tap);\n };\n return;\n }\n };\n UnwrappedUnionType.prototype._copy = function(val, opts) {\n var coerce = opts && opts.coerce | 0;\n var wrap = opts && opts.wrap | 0;\n var index;\n if (wrap === 2) {\n index = 0;\n } else {\n switch (coerce) {\n case 1:\n if (isJsonBuffer(val) && this._bucketIndices.buffer !== void 0) {\n index = this._bucketIndices.buffer;\n } else {\n index = this._getIndex(val);\n }\n break;\n case 2:\n if (val === null) {\n index = this._bucketIndices[\"null\"];\n } else if (typeof val === \"object\") {\n var keys = Object.keys(val);\n if (keys.length === 1) {\n index = this._branchIndices[keys[0]];\n val = val[keys[0]];\n }\n }\n break;\n default:\n index = this._getIndex(val);\n }\n if (index === void 0) {\n throwInvalidError(val, this);\n }\n }\n var type = this.types[index];\n if (val === null || wrap === 3) {\n return type._copy(val, opts);\n } else {\n switch (coerce) {\n case 3:\n var obj = {};\n obj[type.branchName] = type._copy(val, opts);\n return obj;\n default:\n return type._copy(val, opts);\n }\n }\n };\n UnwrappedUnionType.prototype.compare = function(val1, val2) {\n var index1 = this._getIndex(val1);\n var index2 = this._getIndex(val2);\n if (index1 === void 0) {\n throwInvalidError(val1, this);\n } else if (index2 === void 0) {\n throwInvalidError(val2, this);\n } else if (index1 === index2) {\n return this.types[index1].compare(val1, val2);\n } else {\n return utils.compare(index1, index2);\n }\n };\n UnwrappedUnionType.prototype.typeName = \"union:unwrapped\";\n UnwrappedUnionType.prototype.random = function() {\n var index = RANDOM.nextInt(this.types.length);\n return this.types[index].random();\n };\n function WrappedUnionType(schema, opts) {\n UnionType.call(this, schema, opts);\n Object.freeze(this);\n }\n util.inherits(WrappedUnionType, UnionType);\n WrappedUnionType.prototype._check = function(val, flags, hook, path) {\n var b2 = false;\n if (val === null) {\n b2 = this._branchIndices[\"null\"] !== void 0;\n } else if (typeof val == \"object\") {\n var keys = Object.keys(val);\n if (keys.length === 1) {\n var name = keys[0];\n var index = this._branchIndices[name];\n if (index !== void 0) {\n if (hook) {\n path.push(name);\n b2 = this.types[index]._check(val[name], flags, hook, path);\n path.pop();\n return b2;\n } else {\n return this.types[index]._check(val[name], flags);\n }\n }\n }\n }\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n WrappedUnionType.prototype._read = function(tap) {\n var type = this.types[tap.readLong()];\n if (!type) {\n throw new Error(f2(\"invalid union index\"));\n }\n var Branch = type._branchConstructor;\n if (Branch === null) {\n return null;\n } else {\n return new Branch(type._read(tap));\n }\n };\n WrappedUnionType.prototype._write = function(tap, val) {\n var index, keys, name;\n if (val === null) {\n index = this._branchIndices[\"null\"];\n if (index === void 0) {\n throwInvalidError(val, this);\n }\n tap.writeLong(index);\n } else {\n keys = Object.keys(val);\n if (keys.length === 1) {\n name = keys[0];\n index = this._branchIndices[name];\n }\n if (index === void 0) {\n throwInvalidError(val, this);\n }\n tap.writeLong(index);\n this.types[index]._write(tap, val[name]);\n }\n };\n WrappedUnionType.prototype._update = function(resolver, type, opts) {\n var i, l, typeResolver, Branch;\n for (i = 0, l = this.types.length; i < l; i++) {\n try {\n typeResolver = this.types[i].createResolver(type, opts);\n } catch (err) {\n continue;\n }\n Branch = this.types[i]._branchConstructor;\n if (Branch) {\n resolver._read = function(tap) {\n return new Branch(typeResolver._read(tap));\n };\n } else {\n resolver._read = function() {\n return null;\n };\n }\n return;\n }\n };\n WrappedUnionType.prototype._copy = function(val, opts) {\n var wrap = opts && opts.wrap | 0;\n if (wrap === 2) {\n var firstType = this.types[0];\n if (val === null && firstType.typeName === \"null\") {\n return null;\n }\n return new firstType._branchConstructor(firstType._copy(val, opts));\n }\n if (val === null && this._branchIndices[\"null\"] !== void 0) {\n return null;\n }\n var i, l, obj;\n if (typeof val == \"object\") {\n var keys = Object.keys(val);\n if (keys.length === 1) {\n var name = keys[0];\n i = this._branchIndices[name];\n if (i === void 0 && opts.qualifyNames) {\n var j2, type;\n for (j2 = 0, l = this.types.length; j2 < l; j2++) {\n type = this.types[j2];\n if (type.name && name === utils.unqualify(type.name)) {\n i = j2;\n break;\n }\n }\n }\n if (i !== void 0) {\n obj = this.types[i]._copy(val[name], opts);\n }\n }\n }\n if (wrap === 1 && obj === void 0) {\n i = 0;\n l = this.types.length;\n while (i < l && obj === void 0) {\n try {\n obj = this.types[i]._copy(val, opts);\n } catch (err) {\n i++;\n }\n }\n }\n if (obj !== void 0) {\n return wrap === 3 ? obj : new this.types[i]._branchConstructor(obj);\n }\n throwInvalidError(val, this);\n };\n WrappedUnionType.prototype.compare = function(val1, val2) {\n var name1 = val1 === null ? \"null\" : Object.keys(val1)[0];\n var name2 = val2 === null ? \"null\" : Object.keys(val2)[0];\n var index = this._branchIndices[name1];\n if (name1 === name2) {\n return name1 === \"null\" ? 0 : this.types[index].compare(val1[name1], val2[name1]);\n } else {\n return utils.compare(index, this._branchIndices[name2]);\n }\n };\n WrappedUnionType.prototype.typeName = \"union:wrapped\";\n WrappedUnionType.prototype.random = function() {\n var index = RANDOM.nextInt(this.types.length);\n var type = this.types[index];\n var Branch = type._branchConstructor;\n if (!Branch) {\n return null;\n }\n return new Branch(type.random());\n };\n function EnumType(schema, opts) {\n Type.call(this, schema, opts);\n if (!Array.isArray(schema.symbols) || !schema.symbols.length) {\n throw new Error(f2(\"invalid enum symbols: %j\", schema.symbols));\n }\n this.symbols = Object.freeze(schema.symbols.slice());\n this._indices = {};\n this.symbols.forEach(function(symbol, i) {\n if (!utils.isValidName(symbol)) {\n throw new Error(f2(\"invalid %s symbol: %j\", this, symbol));\n }\n if (this._indices[symbol] !== void 0) {\n throw new Error(f2(\"duplicate %s symbol: %j\", this, symbol));\n }\n this._indices[symbol] = i;\n }, this);\n this.default = schema.default;\n if (this.default !== void 0 && this._indices[this.default] === void 0) {\n throw new Error(f2(\"invalid %s default: %j\", this, this.default));\n }\n this._branchConstructor = this._createBranchConstructor();\n Object.freeze(this);\n }\n util.inherits(EnumType, Type);\n EnumType.prototype._check = function(val, flags, hook) {\n var b2 = this._indices[val] !== void 0;\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n EnumType.prototype._read = function(tap) {\n var index = tap.readLong();\n var symbol = this.symbols[index];\n if (symbol === void 0) {\n throw new Error(f2(\"invalid %s enum index: %s\", this.name, index));\n }\n return symbol;\n };\n EnumType.prototype._skip = function(tap) {\n tap.skipLong();\n };\n EnumType.prototype._write = function(tap, val) {\n var index = this._indices[val];\n if (index === void 0) {\n throwInvalidError(val, this);\n }\n tap.writeLong(index);\n };\n EnumType.prototype._match = function(tap1, tap2) {\n return tap1.matchLong(tap2);\n };\n EnumType.prototype.compare = function(val1, val2) {\n return utils.compare(this._indices[val1], this._indices[val2]);\n };\n EnumType.prototype._update = function(resolver, type, opts) {\n var symbols = this.symbols;\n if (type.typeName === \"enum\" && hasCompatibleName(this, type, !opts.ignoreNamespaces) && (type.symbols.every(function(s) {\n return ~symbols.indexOf(s);\n }) || this.default !== void 0)) {\n resolver.symbols = type.symbols.map(function(s) {\n return this._indices[s] === void 0 ? this.default : s;\n }, this);\n resolver._read = type._read;\n }\n };\n EnumType.prototype._copy = function(val) {\n this._check(val, void 0, throwInvalidError);\n return val;\n };\n EnumType.prototype._deref = function(schema) {\n schema.symbols = this.symbols;\n };\n EnumType.prototype.getSymbols = function() {\n return this.symbols;\n };\n EnumType.prototype.typeName = \"enum\";\n EnumType.prototype.random = function() {\n return RANDOM.choice(this.symbols);\n };\n function FixedType(schema, opts) {\n Type.call(this, schema, opts);\n if (schema.size !== (schema.size | 0) || schema.size < 0) {\n throw new Error(f2(\"invalid %s size\", this.branchName));\n }\n this.size = schema.size | 0;\n this._branchConstructor = this._createBranchConstructor();\n Object.freeze(this);\n }\n util.inherits(FixedType, Type);\n FixedType.prototype._check = function(val, flags, hook) {\n var b2 = Buffer2.isBuffer(val) && val.length === this.size;\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n FixedType.prototype._read = function(tap) {\n return tap.readFixed(this.size);\n };\n FixedType.prototype._skip = function(tap) {\n tap.skipFixed(this.size);\n };\n FixedType.prototype._write = function(tap, val) {\n if (!Buffer2.isBuffer(val) || val.length !== this.size) {\n throwInvalidError(val, this);\n }\n tap.writeFixed(val, this.size);\n };\n FixedType.prototype._match = function(tap1, tap2) {\n return tap1.matchFixed(tap2, this.size);\n };\n FixedType.prototype.compare = Buffer2.compare;\n FixedType.prototype._update = function(resolver, type, opts) {\n if (type.typeName === \"fixed\" && this.size === type.size && hasCompatibleName(this, type, !opts.ignoreNamespaces)) {\n resolver.size = this.size;\n resolver._read = this._read;\n }\n };\n FixedType.prototype._copy = BytesType.prototype._copy;\n FixedType.prototype._deref = function(schema) {\n schema.size = this.size;\n };\n FixedType.prototype.getSize = function() {\n return this.size;\n };\n FixedType.prototype.typeName = \"fixed\";\n FixedType.prototype.random = function() {\n return RANDOM.nextBuffer(this.size);\n };\n function MapType(schema, opts) {\n Type.call(this);\n if (!schema.values) {\n throw new Error(f2(\"missing map values: %j\", schema));\n }\n this.valuesType = Type.forSchema(schema.values, opts);\n this._branchConstructor = this._createBranchConstructor();\n Object.freeze(this);\n }\n util.inherits(MapType, Type);\n MapType.prototype._check = function(val, flags, hook, path) {\n if (!val || typeof val != \"object\" || Array.isArray(val)) {\n if (hook) {\n hook(val, this);\n }\n return false;\n }\n var keys = Object.keys(val);\n var b2 = true;\n var i, l, j2, key;\n if (hook) {\n j2 = path.length;\n path.push(\"\");\n for (i = 0, l = keys.length; i < l; i++) {\n key = path[j2] = keys[i];\n if (!this.valuesType._check(val[key], flags, hook, path)) {\n b2 = false;\n }\n }\n path.pop();\n } else {\n for (i = 0, l = keys.length; i < l; i++) {\n if (!this.valuesType._check(val[keys[i]], flags)) {\n return false;\n }\n }\n }\n return b2;\n };\n MapType.prototype._read = function(tap) {\n var values = this.valuesType;\n var val = {};\n var n;\n while (n = readArraySize(tap)) {\n while (n--) {\n var key = tap.readString();\n val[key] = values._read(tap);\n }\n }\n return val;\n };\n MapType.prototype._skip = function(tap) {\n var values = this.valuesType;\n var len, n;\n while (n = tap.readLong()) {\n if (n < 0) {\n len = tap.readLong();\n tap.pos += len;\n } else {\n while (n--) {\n tap.skipString();\n values._skip(tap);\n }\n }\n }\n };\n MapType.prototype._write = function(tap, val) {\n if (!val || typeof val != \"object\" || Array.isArray(val)) {\n throwInvalidError(val, this);\n }\n var values = this.valuesType;\n var keys = Object.keys(val);\n var n = keys.length;\n var i, key;\n if (n) {\n tap.writeLong(n);\n for (i = 0; i < n; i++) {\n key = keys[i];\n tap.writeString(key);\n values._write(tap, val[key]);\n }\n }\n tap.writeLong(0);\n };\n MapType.prototype._match = function() {\n throw new Error(\"maps cannot be compared\");\n };\n MapType.prototype._update = function(rsv, type, opts) {\n if (type.typeName === \"map\") {\n rsv.valuesType = this.valuesType.createResolver(type.valuesType, opts);\n rsv._read = this._read;\n }\n };\n MapType.prototype._copy = function(val, opts) {\n if (val && typeof val == \"object\" && !Array.isArray(val)) {\n var values = this.valuesType;\n var keys = Object.keys(val);\n var i, l, key;\n var copy = {};\n for (i = 0, l = keys.length; i < l; i++) {\n key = keys[i];\n copy[key] = values._copy(val[key], opts);\n }\n return copy;\n }\n throwInvalidError(val, this);\n };\n MapType.prototype.compare = MapType.prototype._match;\n MapType.prototype.typeName = \"map\";\n MapType.prototype.getValuesType = function() {\n return this.valuesType;\n };\n MapType.prototype.random = function() {\n var val = {};\n var i, l;\n for (i = 0, l = RANDOM.nextInt(10); i < l; i++) {\n val[RANDOM.nextString(RANDOM.nextInt(20))] = this.valuesType.random();\n }\n return val;\n };\n MapType.prototype._deref = function(schema, opts) {\n schema.values = this.valuesType._attrs(opts);\n };\n function ArrayType(schema, opts) {\n Type.call(this);\n if (!schema.items) {\n throw new Error(f2(\"missing array items: %j\", schema));\n }\n this.itemsType = Type.forSchema(schema.items, opts);\n this._branchConstructor = this._createBranchConstructor();\n Object.freeze(this);\n }\n util.inherits(ArrayType, Type);\n ArrayType.prototype._check = function(val, flags, hook, path) {\n if (!Array.isArray(val)) {\n if (hook) {\n hook(val, this);\n }\n return false;\n }\n var items = this.itemsType;\n var b2 = true;\n var i, l, j2;\n if (hook) {\n j2 = path.length;\n path.push(\"\");\n for (i = 0, l = val.length; i < l; i++) {\n path[j2] = \"\" + i;\n if (!items._check(val[i], flags, hook, path)) {\n b2 = false;\n }\n }\n path.pop();\n } else {\n for (i = 0, l = val.length; i < l; i++) {\n if (!items._check(val[i], flags)) {\n return false;\n }\n }\n }\n return b2;\n };\n ArrayType.prototype._read = function(tap) {\n var items = this.itemsType;\n var i = 0;\n var val, n;\n while (n = tap.readLong()) {\n if (n < 0) {\n n = -n;\n tap.skipLong();\n }\n val = val || new Array(n);\n while (n--) {\n val[i++] = items._read(tap);\n }\n }\n return val || [];\n };\n ArrayType.prototype._skip = function(tap) {\n var items = this.itemsType;\n var len, n;\n while (n = tap.readLong()) {\n if (n < 0) {\n len = tap.readLong();\n tap.pos += len;\n } else {\n while (n--) {\n items._skip(tap);\n }\n }\n }\n };\n ArrayType.prototype._write = function(tap, val) {\n if (!Array.isArray(val)) {\n throwInvalidError(val, this);\n }\n var items = this.itemsType;\n var n = val.length;\n var i;\n if (n) {\n tap.writeLong(n);\n for (i = 0; i < n; i++) {\n items._write(tap, val[i]);\n }\n }\n tap.writeLong(0);\n };\n ArrayType.prototype._match = function(tap1, tap2) {\n var n1 = tap1.readLong();\n var n2 = tap2.readLong();\n var f3;\n while (n1 && n2) {\n f3 = this.itemsType._match(tap1, tap2);\n if (f3) {\n return f3;\n }\n if (!--n1) {\n n1 = readArraySize(tap1);\n }\n if (!--n2) {\n n2 = readArraySize(tap2);\n }\n }\n return utils.compare(n1, n2);\n };\n ArrayType.prototype._update = function(resolver, type, opts) {\n if (type.typeName === \"array\") {\n resolver.itemsType = this.itemsType.createResolver(type.itemsType, opts);\n resolver._read = this._read;\n }\n };\n ArrayType.prototype._copy = function(val, opts) {\n if (!Array.isArray(val)) {\n throwInvalidError(val, this);\n }\n var items = new Array(val.length);\n var i, l;\n for (i = 0, l = val.length; i < l; i++) {\n items[i] = this.itemsType._copy(val[i], opts);\n }\n return items;\n };\n ArrayType.prototype._deref = function(schema, opts) {\n schema.items = this.itemsType._attrs(opts);\n };\n ArrayType.prototype.compare = function(val1, val2) {\n var n1 = val1.length;\n var n2 = val2.length;\n var i, l, f3;\n for (i = 0, l = Math.min(n1, n2); i < l; i++) {\n if (f3 = this.itemsType.compare(val1[i], val2[i])) {\n return f3;\n }\n }\n return utils.compare(n1, n2);\n };\n ArrayType.prototype.getItemsType = function() {\n return this.itemsType;\n };\n ArrayType.prototype.typeName = \"array\";\n ArrayType.prototype.random = function() {\n var arr = [];\n var i, l;\n for (i = 0, l = RANDOM.nextInt(10); i < l; i++) {\n arr.push(this.itemsType.random());\n }\n return arr;\n };\n function RecordType(schema, opts) {\n opts = opts || {};\n var namespace = opts.namespace;\n if (schema.namespace !== void 0) {\n opts.namespace = schema.namespace;\n } else if (schema.name) {\n var ns = utils.impliedNamespace(schema.name);\n if (ns !== void 0) {\n opts.namespace = ns;\n }\n }\n Type.call(this, schema, opts);\n if (!Array.isArray(schema.fields)) {\n throw new Error(f2(\"non-array record fields: %j\", schema.fields));\n }\n if (utils.hasDuplicates(schema.fields, function(f3) {\n return f3.name;\n })) {\n throw new Error(f2(\"duplicate field name: %j\", schema.fields));\n }\n this._fieldsByName = {};\n this.fields = Object.freeze(schema.fields.map(function(f3) {\n var field = new Field(f3, opts);\n this._fieldsByName[field.name] = field;\n return field;\n }, this));\n this._branchConstructor = this._createBranchConstructor();\n this._isError = schema.type === \"error\";\n this.recordConstructor = this._createConstructor(\n opts.errorStackTraces,\n opts.omitRecordMethods\n );\n this._read = this._createReader();\n this._skip = this._createSkipper();\n this._write = this._createWriter();\n this._check = this._createChecker();\n opts.namespace = namespace;\n Object.freeze(this);\n }\n util.inherits(RecordType, Type);\n RecordType.prototype._getConstructorName = function() {\n return this.name ? utils.capitalize(utils.unqualify(this.name)) : this._isError ? \"Error$\" : \"Record$\";\n };\n RecordType.prototype._createConstructor = function(errorStack, plainRecords) {\n var outerArgs = [];\n var innerArgs = [];\n var ds = [];\n var innerBody = \"\";\n var i, l, field, name, defaultValue, hasDefault, stackField;\n for (i = 0, l = this.fields.length; i < l; i++) {\n field = this.fields[i];\n defaultValue = field.defaultValue;\n hasDefault = defaultValue() !== void 0;\n name = field.name;\n if (errorStack && this._isError && name === \"stack\" && Type.isType(field.type, \"string\") && !hasDefault) {\n stackField = field;\n }\n innerArgs.push(\"v\" + i);\n innerBody += \" \";\n if (!hasDefault) {\n innerBody += \"this.\" + name + \" = v\" + i + \";\\n\";\n } else {\n innerBody += \"if (v\" + i + \" === undefined) { \";\n innerBody += \"this.\" + name + \" = d\" + ds.length + \"(); \";\n innerBody += \"} else { this.\" + name + \" = v\" + i + \"; }\\n\";\n outerArgs.push(\"d\" + ds.length);\n ds.push(defaultValue);\n }\n }\n if (stackField) {\n innerBody += \" if (this.stack === undefined) { \";\n if (typeof Error.captureStackTrace == \"function\") {\n innerBody += \"Error.captureStackTrace(this, this.constructor);\";\n } else {\n innerBody += \"this.stack = Error().stack;\";\n }\n innerBody += \" }\\n\";\n }\n var outerBody = \"return function \" + this._getConstructorName() + \"(\";\n outerBody += innerArgs.join() + \") {\\n\" + innerBody + \"};\";\n var Record = new Function(outerArgs.join(), outerBody).apply(void 0, ds);\n if (plainRecords) {\n return Record;\n }\n var self = this;\n Record.getType = function() {\n return self;\n };\n Record.type = self;\n if (this._isError) {\n util.inherits(Record, Error);\n Record.prototype.name = this._getConstructorName();\n }\n Record.prototype.clone = function(o) {\n return self.clone(this, o);\n };\n Record.prototype.compare = function(v2) {\n return self.compare(this, v2);\n };\n Record.prototype.isValid = function(o) {\n return self.isValid(this, o);\n };\n Record.prototype.toBuffer = function() {\n return self.toBuffer(this);\n };\n Record.prototype.toString = function() {\n return self.toString(this);\n };\n Record.prototype.wrap = function() {\n return self.wrap(this);\n };\n Record.prototype.wrapped = Record.prototype.wrap;\n return Record;\n };\n RecordType.prototype._createChecker = function() {\n var names = [];\n var values = [];\n var name = this._getConstructorName();\n var body = \"return function check\" + name + \"(v, f, h, p) {\\n\";\n body += \" if (\\n\";\n body += \" v === null ||\\n\";\n body += \" typeof v != 'object' ||\\n\";\n body += \" (f && !this._checkFields(v))\\n\";\n body += \" ) {\\n\";\n body += \" if (h) { h(v, this); }\\n\";\n body += \" return false;\\n\";\n body += \" }\\n\";\n if (!this.fields.length) {\n body += \" return true;\\n\";\n } else {\n for (i = 0, l = this.fields.length; i < l; i++) {\n field = this.fields[i];\n names.push(\"t\" + i);\n values.push(field.type);\n if (field.defaultValue() !== void 0) {\n body += \" var v\" + i + \" = v.\" + field.name + \";\\n\";\n }\n }\n body += \" if (h) {\\n\";\n body += \" var b = 1;\\n\";\n body += \" var j = p.length;\\n\";\n body += \" p.push('');\\n\";\n var i, l, field;\n for (i = 0, l = this.fields.length; i < l; i++) {\n field = this.fields[i];\n body += \" p[j] = '\" + field.name + \"';\\n\";\n body += \" b &= \";\n if (field.defaultValue() === void 0) {\n body += \"t\" + i + \"._check(v.\" + field.name + \", f, h, p);\\n\";\n } else {\n body += \"v\" + i + \" === undefined || \";\n body += \"t\" + i + \"._check(v\" + i + \", f, h, p);\\n\";\n }\n }\n body += \" p.pop();\\n\";\n body += \" return !!b;\\n\";\n body += \" } else {\\n return (\\n \";\n body += this.fields.map(function(field2, i2) {\n return field2.defaultValue() === void 0 ? \"t\" + i2 + \"._check(v.\" + field2.name + \", f)\" : \"(v\" + i2 + \" === undefined || t\" + i2 + \"._check(v\" + i2 + \", f))\";\n }).join(\" &&\\n \");\n body += \"\\n );\\n }\\n\";\n }\n body += \"};\";\n return new Function(names.join(), body).apply(void 0, values);\n };\n RecordType.prototype._createReader = function() {\n var names = [];\n var values = [this.recordConstructor];\n var i, l;\n for (i = 0, l = this.fields.length; i < l; i++) {\n names.push(\"t\" + i);\n values.push(this.fields[i].type);\n }\n var name = this._getConstructorName();\n var body = \"return function read\" + name + \"(t) {\\n\";\n body += \" return new \" + name + \"(\\n \";\n body += names.map(function(s) {\n return s + \"._read(t)\";\n }).join(\",\\n \");\n body += \"\\n );\\n};\";\n names.unshift(name);\n return new Function(names.join(), body).apply(void 0, values);\n };\n RecordType.prototype._createSkipper = function() {\n var args = [];\n var body = \"return function skip\" + this._getConstructorName() + \"(t) {\\n\";\n var values = [];\n var i, l;\n for (i = 0, l = this.fields.length; i < l; i++) {\n args.push(\"t\" + i);\n values.push(this.fields[i].type);\n body += \" t\" + i + \"._skip(t);\\n\";\n }\n body += \"}\";\n return new Function(args.join(), body).apply(void 0, values);\n };\n RecordType.prototype._createWriter = function() {\n var args = [];\n var name = this._getConstructorName();\n var body = \"return function write\" + name + \"(t, v) {\\n\";\n var values = [];\n var i, l, field, value;\n for (i = 0, l = this.fields.length; i < l; i++) {\n field = this.fields[i];\n args.push(\"t\" + i);\n values.push(field.type);\n body += \" \";\n if (field.defaultValue() === void 0) {\n body += \"t\" + i + \"._write(t, v.\" + field.name + \");\\n\";\n } else {\n value = field.type.toBuffer(field.defaultValue()).toString(\"binary\");\n args.push(\"d\" + i);\n values.push(value);\n body += \"var v\" + i + \" = v.\" + field.name + \";\\n\";\n body += \"if (v\" + i + \" === undefined) {\\n\";\n body += \" t.writeBinary(d\" + i + \", \" + value.length + \");\\n\";\n body += \" } else {\\n t\" + i + \"._write(t, v\" + i + \");\\n }\\n\";\n }\n }\n body += \"}\";\n return new Function(args.join(), body).apply(void 0, values);\n };\n RecordType.prototype._update = function(resolver, type, opts) {\n if (!hasCompatibleName(this, type, !opts.ignoreNamespaces)) {\n throw new Error(f2(\"no alias found for %s\", type.name));\n }\n var rFields = this.fields;\n var wFields = type.fields;\n var wFieldsMap = utils.toMap(wFields, function(f3) {\n return f3.name;\n });\n var innerArgs = [];\n var resolvers = {};\n var i, j2, field, name, names, matches, fieldResolver;\n for (i = 0; i < rFields.length; i++) {\n field = rFields[i];\n names = getAliases(field);\n matches = [];\n for (j2 = 0; j2 < names.length; j2++) {\n name = names[j2];\n if (wFieldsMap[name]) {\n matches.push(name);\n }\n }\n if (matches.length > 1) {\n throw new Error(\n f2(\"ambiguous aliasing for %s.%s (%s)\", type.name, field.name, matches)\n );\n }\n if (!matches.length) {\n if (field.defaultValue() === void 0) {\n throw new Error(\n f2(\"no matching field for default-less %s.%s\", type.name, field.name)\n );\n }\n innerArgs.push(\"undefined\");\n } else {\n name = matches[0];\n fieldResolver = {\n resolver: field.type.createResolver(wFieldsMap[name].type, opts),\n name: \"_\" + field.name\n // Reader field name.\n };\n if (!resolvers[name]) {\n resolvers[name] = [fieldResolver];\n } else {\n resolvers[name].push(fieldResolver);\n }\n innerArgs.push(fieldResolver.name);\n }\n }\n var lazyIndex = -1;\n i = wFields.length;\n while (i && resolvers[wFields[--i].name] === void 0) {\n lazyIndex = i;\n }\n var uname = this._getConstructorName();\n var args = [uname];\n var values = [this.recordConstructor];\n var body = \" return function read\" + uname + \"(t, b) {\\n\";\n for (i = 0; i < wFields.length; i++) {\n if (i === lazyIndex) {\n body += \" if (!b) {\\n\";\n }\n field = type.fields[i];\n name = field.name;\n if (resolvers[name] === void 0) {\n body += ~lazyIndex && i >= lazyIndex ? \" \" : \" \";\n args.push(\"r\" + i);\n values.push(field.type);\n body += \"r\" + i + \"._skip(t);\\n\";\n } else {\n j2 = resolvers[name].length;\n while (j2--) {\n body += ~lazyIndex && i >= lazyIndex ? \" \" : \" \";\n args.push(\"r\" + i + \"f\" + j2);\n fieldResolver = resolvers[name][j2];\n values.push(fieldResolver.resolver);\n body += \"var \" + fieldResolver.name + \" = \";\n body += \"r\" + i + \"f\" + j2 + \"._\" + (j2 ? \"peek\" : \"read\") + \"(t);\\n\";\n }\n }\n }\n if (~lazyIndex) {\n body += \" }\\n\";\n }\n body += \" return new \" + uname + \"(\" + innerArgs.join() + \");\\n};\";\n resolver._read = new Function(args.join(), body).apply(void 0, values);\n };\n RecordType.prototype._match = function(tap1, tap2) {\n var fields = this.fields;\n var i, l, field, order, type;\n for (i = 0, l = fields.length; i < l; i++) {\n field = fields[i];\n order = field._order;\n type = field.type;\n if (order) {\n order *= type._match(tap1, tap2);\n if (order) {\n return order;\n }\n } else {\n type._skip(tap1);\n type._skip(tap2);\n }\n }\n return 0;\n };\n RecordType.prototype._checkFields = function(obj) {\n var keys = Object.keys(obj);\n var i, l;\n for (i = 0, l = keys.length; i < l; i++) {\n if (!this._fieldsByName[keys[i]]) {\n return false;\n }\n }\n return true;\n };\n RecordType.prototype._copy = function(val, opts) {\n var hook = opts && opts.fieldHook;\n var values = [void 0];\n var i, l, field, value;\n for (i = 0, l = this.fields.length; i < l; i++) {\n field = this.fields[i];\n value = val[field.name];\n if (value === void 0 && field.hasOwnProperty(\"defaultValue\")) {\n value = field.defaultValue();\n }\n if (opts && !opts.skip || value !== void 0) {\n value = field.type._copy(value, opts);\n }\n if (hook) {\n value = hook(field, value, this);\n }\n values.push(value);\n }\n var Record = this.recordConstructor;\n return new (Record.bind.apply(Record, values))();\n };\n RecordType.prototype._deref = function(schema, opts) {\n schema.fields = this.fields.map(function(field) {\n var fieldType = field.type;\n var fieldSchema = {\n name: field.name,\n type: fieldType._attrs(opts)\n };\n if (opts.exportAttrs) {\n var val = field.defaultValue();\n if (val !== void 0) {\n fieldSchema[\"default\"] = fieldType._copy(val, { coerce: 3, wrap: 3 });\n }\n var fieldOrder = field.order;\n if (fieldOrder !== \"ascending\") {\n fieldSchema.order = fieldOrder;\n }\n var fieldAliases = field.aliases;\n if (fieldAliases.length) {\n fieldSchema.aliases = fieldAliases;\n }\n var fieldDoc = field.doc;\n if (fieldDoc !== void 0) {\n fieldSchema.doc = fieldDoc;\n }\n }\n return fieldSchema;\n });\n };\n RecordType.prototype.compare = function(val1, val2) {\n var fields = this.fields;\n var i, l, field, name, order, type;\n for (i = 0, l = fields.length; i < l; i++) {\n field = fields[i];\n name = field.name;\n order = field._order;\n type = field.type;\n if (order) {\n order *= type.compare(val1[name], val2[name]);\n if (order) {\n return order;\n }\n }\n }\n return 0;\n };\n RecordType.prototype.random = function() {\n var fields = this.fields.map(function(f3) {\n return f3.type.random();\n });\n fields.unshift(void 0);\n var Record = this.recordConstructor;\n return new (Record.bind.apply(Record, fields))();\n };\n RecordType.prototype.field = function(name) {\n return this._fieldsByName[name];\n };\n RecordType.prototype.getField = RecordType.prototype.field;\n RecordType.prototype.getFields = function() {\n return this.fields;\n };\n RecordType.prototype.getRecordConstructor = function() {\n return this.recordConstructor;\n };\n Object.defineProperty(RecordType.prototype, \"typeName\", {\n enumerable: true,\n get: function() {\n return this._isError ? \"error\" : \"record\";\n }\n });\n function LogicalType(schema, opts) {\n this._logicalTypeName = schema.logicalType;\n Type.call(this);\n LOGICAL_TYPE = this;\n try {\n this._underlyingType = Type.forSchema(schema, opts);\n } finally {\n LOGICAL_TYPE = null;\n var l = UNDERLYING_TYPES.length;\n if (l && UNDERLYING_TYPES[l - 1][0] === this) {\n UNDERLYING_TYPES.pop();\n }\n }\n if (Type.isType(this.underlyingType, \"union\")) {\n this._branchConstructor = this.underlyingType._branchConstructor;\n } else {\n this._branchConstructor = this.underlyingType._createBranchConstructor();\n }\n }\n util.inherits(LogicalType, Type);\n Object.defineProperty(LogicalType.prototype, \"typeName\", {\n enumerable: true,\n get: function() {\n return \"logical:\" + this._logicalTypeName;\n }\n });\n Object.defineProperty(LogicalType.prototype, \"underlyingType\", {\n enumerable: true,\n get: function() {\n if (this._underlyingType) {\n return this._underlyingType;\n }\n var i, l, arr;\n for (i = 0, l = UNDERLYING_TYPES.length; i < l; i++) {\n arr = UNDERLYING_TYPES[i];\n if (arr[0] === this) {\n return arr[1];\n }\n }\n }\n });\n LogicalType.prototype.getUnderlyingType = function() {\n return this.underlyingType;\n };\n LogicalType.prototype._read = function(tap) {\n return this._fromValue(this.underlyingType._read(tap));\n };\n LogicalType.prototype._write = function(tap, any) {\n this.underlyingType._write(tap, this._toValue(any));\n };\n LogicalType.prototype._check = function(any, flags, hook, path) {\n try {\n var val = this._toValue(any);\n } catch (err) {\n }\n if (val === void 0) {\n if (hook) {\n hook(any, this);\n }\n return false;\n }\n return this.underlyingType._check(val, flags, hook, path);\n };\n LogicalType.prototype._copy = function(any, opts) {\n var type = this.underlyingType;\n switch (opts && opts.coerce) {\n case 3:\n return type._copy(this._toValue(any), opts);\n case 2:\n return this._fromValue(type._copy(any, opts));\n default:\n return this._fromValue(type._copy(this._toValue(any), opts));\n }\n };\n LogicalType.prototype._update = function(resolver, type, opts) {\n var _fromValue = this._resolve(type, opts);\n if (_fromValue) {\n resolver._read = function(tap) {\n return _fromValue(type._read(tap));\n };\n }\n };\n LogicalType.prototype.compare = function(obj1, obj2) {\n var val1 = this._toValue(obj1);\n var val2 = this._toValue(obj2);\n return this.underlyingType.compare(val1, val2);\n };\n LogicalType.prototype.random = function() {\n return this._fromValue(this.underlyingType.random());\n };\n LogicalType.prototype._deref = function(schema, opts) {\n var type = this.underlyingType;\n var isVisited = type.name !== void 0 && opts.derefed[type.name];\n schema = type._attrs(opts);\n if (!isVisited && opts.exportAttrs) {\n if (typeof schema == \"string\") {\n schema = { type: schema };\n }\n schema.logicalType = this._logicalTypeName;\n this._export(schema);\n }\n return schema;\n };\n LogicalType.prototype._skip = function(tap) {\n this.underlyingType._skip(tap);\n };\n LogicalType.prototype._export = function() {\n };\n LogicalType.prototype._fromValue = utils.abstractFunction;\n LogicalType.prototype._toValue = utils.abstractFunction;\n LogicalType.prototype._resolve = utils.abstractFunction;\n function AbstractLongType(noUnpack) {\n this._concreteTypeName = \"long\";\n PrimitiveType.call(this, true);\n this._noUnpack = !!noUnpack;\n }\n util.inherits(AbstractLongType, LongType);\n AbstractLongType.prototype.typeName = \"abstract:long\";\n AbstractLongType.prototype._check = function(val, flags, hook) {\n var b2 = this._isValid(val);\n if (!b2 && hook) {\n hook(val, this);\n }\n return b2;\n };\n AbstractLongType.prototype._read = function(tap) {\n var buf, pos;\n if (this._noUnpack) {\n pos = tap.pos;\n tap.skipLong();\n buf = tap.buf.slice(pos, tap.pos);\n } else {\n buf = tap.unpackLongBytes(tap);\n }\n if (tap.isValid()) {\n return this._fromBuffer(buf);\n }\n };\n AbstractLongType.prototype._write = function(tap, val) {\n if (!this._isValid(val)) {\n throwInvalidError(val, this);\n }\n var buf = this._toBuffer(val);\n if (this._noUnpack) {\n tap.writeFixed(buf);\n } else {\n tap.packLongBytes(buf);\n }\n };\n AbstractLongType.prototype._copy = function(val, opts) {\n switch (opts && opts.coerce) {\n case 3:\n return this._toJSON(val);\n case 2:\n return this._fromJSON(val);\n default:\n return this._fromJSON(this._toJSON(val));\n }\n };\n AbstractLongType.prototype._deref = function() {\n return \"long\";\n };\n AbstractLongType.prototype._update = function(resolver, type) {\n var self = this;\n switch (type.typeName) {\n case \"int\":\n resolver._read = function(tap) {\n return self._fromJSON(type._read(tap));\n };\n break;\n case \"abstract:long\":\n case \"long\":\n resolver._read = function(tap) {\n return self._read(tap);\n };\n }\n };\n AbstractLongType.prototype.random = function() {\n return this._fromJSON(LongType.prototype.random());\n };\n AbstractLongType.prototype._fromBuffer = utils.abstractFunction;\n AbstractLongType.prototype._toBuffer = utils.abstractFunction;\n AbstractLongType.prototype._fromJSON = utils.abstractFunction;\n AbstractLongType.prototype._toJSON = utils.abstractFunction;\n AbstractLongType.prototype._isValid = utils.abstractFunction;\n AbstractLongType.prototype.compare = utils.abstractFunction;\n function Field(schema, opts) {\n var name = schema.name;\n if (typeof name != \"string\" || !utils.isValidName(name)) {\n throw new Error(f2(\"invalid field name: %s\", name));\n }\n this.name = name;\n this.type = Type.forSchema(schema.type, opts);\n this.aliases = schema.aliases || [];\n this.doc = schema.doc !== void 0 ? \"\" + schema.doc : void 0;\n this._order = function(order) {\n switch (order) {\n case \"ascending\":\n return 1;\n case \"descending\":\n return -1;\n case \"ignore\":\n return 0;\n default:\n throw new Error(f2(\"invalid order: %j\", order));\n }\n }(schema.order === void 0 ? \"ascending\" : schema.order);\n var value = schema[\"default\"];\n if (value !== void 0) {\n var type = this.type;\n var val;\n try {\n val = type._copy(value, { coerce: 2, wrap: 2 });\n } catch (err) {\n var msg = f2(\"incompatible field default %j (%s)\", value, err.message);\n if (Type.isType(type, \"union\")) {\n msg += f2(\n \", union defaults must match the first branch's type (%j)\",\n type.types[0]\n );\n }\n throw new Error(msg);\n }\n if (isPrimitive(type.typeName) && type.typeName !== \"bytes\") {\n this.defaultValue = function() {\n return val;\n };\n } else {\n this.defaultValue = function() {\n return type._copy(val);\n };\n }\n }\n Object.freeze(this);\n }\n Field.prototype.defaultValue = function() {\n };\n Object.defineProperty(Field.prototype, \"order\", {\n enumerable: true,\n get: function() {\n return [\"descending\", \"ignore\", \"ascending\"][this._order + 1];\n }\n });\n Field.prototype.getAliases = function() {\n return this.aliases;\n };\n Field.prototype.getDefault = Field.prototype.defaultValue;\n Field.prototype.getName = function() {\n return this.name;\n };\n Field.prototype.getOrder = function() {\n return this.order;\n };\n Field.prototype.getType = function() {\n return this.type;\n };\n function Resolver(readerType) {\n this._readerType = readerType;\n this._read = null;\n this.itemsType = null;\n this.size = 0;\n this.symbols = null;\n this.valuesType = null;\n }\n Resolver.prototype._peek = Type.prototype._peek;\n Resolver.prototype.inspect = function() {\n return \"\";\n };\n function Hash() {\n this.str = void 0;\n }\n function readValue(type, tap, resolver, lazy) {\n if (resolver) {\n if (resolver._readerType !== type) {\n throw new Error(\"invalid resolver\");\n }\n return resolver._read(tap, lazy);\n } else {\n return type._read(tap);\n }\n }\n function getAliases(obj) {\n var names = {};\n if (obj.name) {\n names[obj.name] = true;\n }\n var aliases = obj.aliases;\n var i, l;\n for (i = 0, l = aliases.length; i < l; i++) {\n names[aliases[i]] = true;\n }\n return Object.keys(names);\n }\n function hasCompatibleName(reader, writer, strict) {\n if (!writer.name) {\n return true;\n }\n var name = strict ? writer.name : utils.unqualify(writer.name);\n var aliases = getAliases(reader);\n var i, l, alias;\n for (i = 0, l = aliases.length; i < l; i++) {\n alias = aliases[i];\n if (!strict) {\n alias = utils.unqualify(alias);\n }\n if (alias === name) {\n return true;\n }\n }\n return false;\n }\n function isPrimitive(typeName) {\n var type = TYPES[typeName];\n return type && type.prototype instanceof PrimitiveType;\n }\n function getClassName(typeName) {\n if (typeName === \"error\") {\n typeName = \"record\";\n } else {\n var match = /^([^:]+):(.*)$/.exec(typeName);\n if (match) {\n if (match[1] === \"union\") {\n typeName = match[2] + \"Union\";\n } else {\n typeName = match[1];\n }\n }\n }\n return utils.capitalize(typeName) + \"Type\";\n }\n function readArraySize(tap) {\n var n = tap.readLong();\n if (n < 0) {\n n = -n;\n tap.skipLong();\n }\n return n;\n }\n function isSafeLong(n) {\n return n >= -9007199254740990 && n <= 9007199254740990;\n }\n function isJsonBuffer(obj) {\n return obj && obj.type === \"Buffer\" && Array.isArray(obj.data);\n }\n function throwInvalidError(val, type) {\n throw new Error(f2(\"invalid %j: %j\", type.schema(), val));\n }\n function maybeQualify(name, ns) {\n var unqualified = utils.unqualify(name);\n return isPrimitive(unqualified) ? unqualified : utils.qualify(name, ns);\n }\n function getTypeBucket(type) {\n var typeName = type.typeName;\n switch (typeName) {\n case \"double\":\n case \"float\":\n case \"int\":\n case \"long\":\n return \"number\";\n case \"bytes\":\n case \"fixed\":\n return \"buffer\";\n case \"enum\":\n return \"string\";\n case \"map\":\n case \"error\":\n case \"record\":\n return \"object\";\n default:\n return typeName;\n }\n }\n function getValueBucket(val) {\n if (val === null) {\n return \"null\";\n }\n var bucket = typeof val;\n if (bucket === \"object\") {\n if (Array.isArray(val)) {\n return \"array\";\n } else if (Buffer2.isBuffer(val)) {\n return \"buffer\";\n }\n }\n return bucket;\n }\n function isAmbiguous(types) {\n var buckets = {};\n var i, l, bucket, type;\n for (i = 0, l = types.length; i < l; i++) {\n type = types[i];\n if (!Type.isType(type, \"logical\")) {\n bucket = getTypeBucket(type);\n if (buckets[bucket]) {\n return true;\n }\n buckets[bucket] = true;\n }\n }\n return false;\n }\n function combineNumbers(types) {\n var typeNames = [\"int\", \"long\", \"float\", \"double\"];\n var superIndex = -1;\n var superType = null;\n var i, l, type, index;\n for (i = 0, l = types.length; i < l; i++) {\n type = types[i];\n index = typeNames.indexOf(type.typeName);\n if (index > superIndex) {\n superIndex = index;\n superType = type;\n }\n }\n return superType;\n }\n function combineStrings(types, opts) {\n var symbols = {};\n var i, l, type, typeSymbols;\n for (i = 0, l = types.length; i < l; i++) {\n type = types[i];\n if (type.typeName === \"string\") {\n return type;\n }\n typeSymbols = type.symbols;\n var j2, m2;\n for (j2 = 0, m2 = typeSymbols.length; j2 < m2; j2++) {\n symbols[typeSymbols[j2]] = true;\n }\n }\n return Type.forSchema({ type: \"enum\", symbols: Object.keys(symbols) }, opts);\n }\n function combineBuffers(types, opts) {\n var size = -1;\n var i, l, type;\n for (i = 0, l = types.length; i < l; i++) {\n type = types[i];\n if (type.typeName === \"bytes\") {\n return type;\n }\n if (size === -1) {\n size = type.size;\n } else if (type.size !== size) {\n size = -2;\n }\n }\n return size < 0 ? Type.forSchema(\"bytes\", opts) : types[0];\n }\n function combineObjects(types, opts) {\n var allTypes = [];\n var fieldTypes = {};\n var fieldDefaults = {};\n var isValidRecord = true;\n var i, l, type, fields;\n for (i = 0, l = types.length; i < l; i++) {\n type = types[i];\n if (type.typeName === \"map\") {\n isValidRecord = false;\n allTypes.push(type.valuesType);\n } else {\n fields = type.fields;\n var j2, m2, field, fieldDefault, fieldName, fieldType;\n for (j2 = 0, m2 = fields.length; j2 < m2; j2++) {\n field = fields[j2];\n fieldName = field.name;\n fieldType = field.type;\n allTypes.push(fieldType);\n if (isValidRecord) {\n if (!fieldTypes[fieldName]) {\n fieldTypes[fieldName] = [];\n }\n fieldTypes[fieldName].push(fieldType);\n fieldDefault = field.defaultValue();\n if (fieldDefault !== void 0) {\n fieldDefaults[fieldName] = fieldDefault;\n }\n }\n }\n }\n }\n if (isValidRecord) {\n var fieldNames = Object.keys(fieldTypes);\n for (i = 0, l = fieldNames.length; i < l; i++) {\n fieldName = fieldNames[i];\n if (fieldTypes[fieldName].length < types.length && fieldDefaults[fieldName] === void 0) {\n if (opts && opts.strictDefaults) {\n isValidRecord = false;\n } else {\n fieldTypes[fieldName].unshift(Type.forSchema(\"null\", opts));\n fieldDefaults[fieldName] = null;\n }\n }\n }\n }\n var schema;\n if (isValidRecord) {\n schema = {\n type: \"record\",\n fields: fieldNames.map(function(s) {\n var fieldType2 = Type.forTypes(fieldTypes[s], opts);\n var fieldDefault2 = fieldDefaults[s];\n if (fieldDefault2 !== void 0 && ~fieldType2.typeName.indexOf(\"union\")) {\n var unionTypes = fieldType2.types.slice();\n var i2, l2;\n for (i2 = 0, l2 = unionTypes.length; i2 < l2; i2++) {\n if (unionTypes[i2].isValid(fieldDefault2)) {\n break;\n }\n }\n if (i2 > 0) {\n var unionType = unionTypes[0];\n unionTypes[0] = unionTypes[i2];\n unionTypes[i2] = unionType;\n fieldType2 = Type.forSchema(unionTypes, opts);\n }\n }\n return {\n name: s,\n type: fieldType2,\n \"default\": fieldDefaults[s]\n };\n })\n };\n } else {\n schema = {\n type: \"map\",\n values: Type.forTypes(allTypes, opts)\n };\n }\n return Type.forSchema(schema, opts);\n }\n module.exports = {\n Type,\n getTypeBucket,\n getValueBucket,\n isPrimitive,\n builtins: function() {\n var types = {\n LogicalType,\n UnwrappedUnionType,\n WrappedUnionType\n };\n var typeNames = Object.keys(TYPES);\n var i, l, typeName;\n for (i = 0, l = typeNames.length; i < l; i++) {\n typeName = typeNames[i];\n types[getClassName(typeName)] = TYPES[typeName];\n }\n return types;\n }()\n };\n }\n});\n\n// node_modules/avsc/lib/containers.js\nvar require_containers = __commonJS({\n \"node_modules/avsc/lib/containers.js\"(exports, module) {\n \"use strict\";\n var types = require_types();\n var utils = require_utils();\n var buffer = __import_BUFFER;\n var stream = __import_STREAM;\n var util = __import_UTIL;\n var zlib = __import_ZLIB;\n var Buffer2 = buffer.Buffer;\n var OPTS = { namespace: \"org.apache.avro.file\" };\n var LONG_TYPE = types.Type.forSchema(\"long\", OPTS);\n var MAP_BYTES_TYPE = types.Type.forSchema({ type: \"map\", values: \"bytes\" }, OPTS);\n var HEADER_TYPE = types.Type.forSchema({\n name: \"Header\",\n type: \"record\",\n fields: [\n { name: \"magic\", type: { type: \"fixed\", name: \"Magic\", size: 4 } },\n { name: \"meta\", type: MAP_BYTES_TYPE },\n { name: \"sync\", type: { type: \"fixed\", name: \"Sync\", size: 16 } }\n ]\n }, OPTS);\n var BLOCK_TYPE = types.Type.forSchema({\n name: \"Block\",\n type: \"record\",\n fields: [\n { name: \"count\", type: \"long\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"sync\", type: \"Sync\" }\n ]\n }, OPTS);\n var MAGIC_BYTES = utils.bufferFrom(\"Obj\u0001\");\n var f2 = util.format;\n var Tap = utils.Tap;\n function RawDecoder(schema, opts) {\n opts = opts || {};\n var noDecode = !!opts.noDecode;\n stream.Duplex.call(this, {\n readableObjectMode: !noDecode,\n allowHalfOpen: false\n });\n this._type = types.Type.forSchema(schema);\n this._tap = new Tap(utils.newBuffer(0));\n this._writeCb = null;\n this._needPush = false;\n this._readValue = createReader(noDecode, this._type);\n this._finished = false;\n this.on(\"finish\", function() {\n this._finished = true;\n this._read();\n });\n }\n util.inherits(RawDecoder, stream.Duplex);\n RawDecoder.prototype._write = function(chunk, encoding, cb) {\n this._writeCb = cb;\n var tap = this._tap;\n tap.buf = Buffer2.concat([tap.buf.slice(tap.pos), chunk]);\n tap.pos = 0;\n if (this._needPush) {\n this._needPush = false;\n this._read();\n }\n };\n RawDecoder.prototype._read = function() {\n this._needPush = false;\n var tap = this._tap;\n var pos = tap.pos;\n var val = this._readValue(tap);\n if (tap.isValid()) {\n this.push(val);\n } else if (!this._finished) {\n tap.pos = pos;\n this._needPush = true;\n if (this._writeCb) {\n this._writeCb();\n }\n } else {\n this.push(null);\n }\n };\n function BlockDecoder(opts) {\n opts = opts || {};\n var noDecode = !!opts.noDecode;\n stream.Duplex.call(this, {\n allowHalfOpen: true,\n // For async decompressors.\n readableObjectMode: !noDecode\n });\n this._rType = opts.readerSchema !== void 0 ? types.Type.forSchema(opts.readerSchema) : void 0;\n this._wType = null;\n this._codecs = opts.codecs;\n this._codec = void 0;\n this._parseHook = opts.parseHook;\n this._tap = new Tap(utils.newBuffer(0));\n this._blockTap = new Tap(utils.newBuffer(0));\n this._syncMarker = null;\n this._readValue = null;\n this._noDecode = noDecode;\n this._queue = new utils.OrderedQueue();\n this._decompress = null;\n this._index = 0;\n this._remaining = void 0;\n this._needPush = false;\n this._finished = false;\n this.on(\"finish\", function() {\n this._finished = true;\n if (this._needPush) {\n this._read();\n }\n });\n }\n util.inherits(BlockDecoder, stream.Duplex);\n BlockDecoder.defaultCodecs = function() {\n return {\n \"null\": function(buf, cb) {\n cb(null, buf);\n },\n \"deflate\": zlib.inflateRaw\n };\n };\n BlockDecoder.getDefaultCodecs = BlockDecoder.defaultCodecs;\n BlockDecoder.prototype._decodeHeader = function() {\n var tap = this._tap;\n if (tap.buf.length < MAGIC_BYTES.length) {\n return false;\n }\n if (!MAGIC_BYTES.equals(tap.buf.slice(0, MAGIC_BYTES.length))) {\n this.emit(\"error\", new Error(\"invalid magic bytes\"));\n return false;\n }\n var header = HEADER_TYPE._read(tap);\n if (!tap.isValid()) {\n return false;\n }\n this._codec = (header.meta[\"avro.codec\"] || \"null\").toString();\n var codecs = this._codecs || BlockDecoder.getDefaultCodecs();\n this._decompress = codecs[this._codec];\n if (!this._decompress) {\n this.emit(\"error\", new Error(f2(\"unknown codec: %s\", this._codec)));\n return;\n }\n try {\n var schema = JSON.parse(header.meta[\"avro.schema\"].toString());\n if (this._parseHook) {\n schema = this._parseHook(schema);\n }\n this._wType = types.Type.forSchema(schema);\n } catch (err) {\n this.emit(\"error\", err);\n return;\n }\n try {\n this._readValue = createReader(this._noDecode, this._wType, this._rType);\n } catch (err) {\n this.emit(\"error\", err);\n return;\n }\n this._syncMarker = header.sync;\n this.emit(\"metadata\", this._wType, this._codec, header);\n return true;\n };\n BlockDecoder.prototype._write = function(chunk, encoding, cb) {\n var tap = this._tap;\n tap.buf = Buffer2.concat([tap.buf, chunk]);\n tap.pos = 0;\n if (!this._decodeHeader()) {\n process.nextTick(cb);\n return;\n }\n this._write = this._writeChunk;\n this._write(utils.newBuffer(0), encoding, cb);\n };\n BlockDecoder.prototype._writeChunk = function(chunk, encoding, cb) {\n var tap = this._tap;\n tap.buf = Buffer2.concat([tap.buf.slice(tap.pos), chunk]);\n tap.pos = 0;\n var nBlocks = 1;\n var block;\n while (block = tryReadBlock(tap)) {\n if (!this._syncMarker.equals(block.sync)) {\n this.emit(\"error\", new Error(\"invalid sync marker\"));\n return;\n }\n nBlocks++;\n this._decompress(\n block.data,\n this._createBlockCallback(block.data.length, block.count, chunkCb)\n );\n }\n chunkCb();\n function chunkCb() {\n if (!--nBlocks) {\n cb();\n }\n }\n };\n BlockDecoder.prototype._createBlockCallback = function(size, count, cb) {\n var self = this;\n var index = this._index++;\n return function(cause, data) {\n if (cause) {\n var err = new Error(f2(\"%s codec decompression error\", self._codec));\n err.cause = cause;\n self.emit(\"error\", err);\n cb();\n } else {\n self.emit(\"block\", new BlockInfo(count, data.length, size));\n self._queue.push(new BlockData(index, data, cb, count));\n if (self._needPush) {\n self._read();\n }\n }\n };\n };\n BlockDecoder.prototype._read = function() {\n this._needPush = false;\n var tap = this._blockTap;\n if (!this._remaining) {\n var data = this._queue.pop();\n if (!data || !data.count) {\n if (this._finished) {\n this.push(null);\n } else {\n this._needPush = true;\n }\n if (data) {\n data.cb();\n }\n return;\n }\n data.cb();\n this._remaining = data.count;\n tap.buf = data.buf;\n tap.pos = 0;\n }\n this._remaining--;\n var val;\n try {\n val = this._readValue(tap);\n if (!tap.isValid()) {\n throw new Error(\"truncated block\");\n }\n } catch (err) {\n this._remaining = 0;\n this.emit(\"error\", err);\n return;\n }\n this.push(val);\n };\n function RawEncoder(schema, opts) {\n opts = opts || {};\n stream.Transform.call(this, {\n writableObjectMode: true,\n allowHalfOpen: false\n });\n this._type = types.Type.forSchema(schema);\n this._writeValue = function(tap, val) {\n try {\n this._type._write(tap, val);\n } catch (err) {\n this.emit(\"typeError\", err, val, this._type);\n }\n };\n this._tap = new Tap(utils.newBuffer(opts.batchSize || 65536));\n this.on(\"typeError\", function(err) {\n this.emit(\"error\", err);\n });\n }\n util.inherits(RawEncoder, stream.Transform);\n RawEncoder.prototype._transform = function(val, encoding, cb) {\n var tap = this._tap;\n var buf = tap.buf;\n var pos = tap.pos;\n this._writeValue(tap, val);\n if (!tap.isValid()) {\n if (pos) {\n this.push(copyBuffer(tap.buf, 0, pos));\n }\n var len = tap.pos - pos;\n if (len > buf.length) {\n tap.buf = utils.newBuffer(2 * len);\n }\n tap.pos = 0;\n this._writeValue(tap, val);\n }\n cb();\n };\n RawEncoder.prototype._flush = function(cb) {\n var tap = this._tap;\n var pos = tap.pos;\n if (pos) {\n this.push(tap.buf.slice(0, pos));\n }\n cb();\n };\n function BlockEncoder(schema, opts) {\n opts = opts || {};\n stream.Duplex.call(this, {\n allowHalfOpen: true,\n // To support async compressors.\n writableObjectMode: true\n });\n var type;\n if (types.Type.isType(schema)) {\n type = schema;\n schema = void 0;\n } else {\n type = types.Type.forSchema(schema);\n }\n this._schema = schema;\n this._type = type;\n this._writeValue = function(tap, val) {\n try {\n this._type._write(tap, val);\n } catch (err) {\n this.emit(\"typeError\", err, val, this._type);\n return false;\n }\n return true;\n };\n this._blockSize = opts.blockSize || 65536;\n this._tap = new Tap(utils.newBuffer(this._blockSize));\n this._codecs = opts.codecs;\n this._codec = opts.codec || \"null\";\n this._blockCount = 0;\n this._syncMarker = opts.syncMarker || new utils.Lcg().nextBuffer(16);\n this._queue = new utils.OrderedQueue();\n this._pending = 0;\n this._finished = false;\n this._needHeader = false;\n this._needPush = false;\n this._metadata = opts.metadata || {};\n if (!MAP_BYTES_TYPE.isValid(this._metadata)) {\n throw new Error(\"invalid metadata\");\n }\n var codec = this._codec;\n this._compress = (this._codecs || BlockEncoder.getDefaultCodecs())[codec];\n if (!this._compress) {\n throw new Error(f2(\"unsupported codec: %s\", codec));\n }\n if (opts.omitHeader !== void 0) {\n opts.writeHeader = opts.omitHeader ? \"never\" : \"auto\";\n }\n switch (opts.writeHeader) {\n case false:\n case \"never\":\n break;\n case void 0:\n case \"auto\":\n this._needHeader = true;\n break;\n default:\n this._writeHeader();\n }\n this.on(\"finish\", function() {\n this._finished = true;\n if (this._blockCount) {\n this._flushChunk();\n } else if (this._finished && this._needPush) {\n this.push(null);\n }\n });\n this.on(\"typeError\", function(err) {\n this.emit(\"error\", err);\n });\n }\n util.inherits(BlockEncoder, stream.Duplex);\n BlockEncoder.defaultCodecs = function() {\n return {\n \"null\": function(buf, cb) {\n cb(null, buf);\n },\n \"deflate\": zlib.deflateRaw\n };\n };\n BlockEncoder.getDefaultCodecs = BlockEncoder.defaultCodecs;\n BlockEncoder.prototype._writeHeader = function() {\n var schema = JSON.stringify(\n this._schema ? this._schema : this._type.getSchema({ exportAttrs: true })\n );\n var meta = utils.copyOwnProperties(\n this._metadata,\n { \"avro.schema\": utils.bufferFrom(schema), \"avro.codec\": utils.bufferFrom(this._codec) },\n true\n // Overwrite.\n );\n var Header = HEADER_TYPE.getRecordConstructor();\n var header = new Header(MAGIC_BYTES, meta, this._syncMarker);\n this.push(header.toBuffer());\n };\n BlockEncoder.prototype._write = function(val, encoding, cb) {\n if (this._needHeader) {\n this._writeHeader();\n this._needHeader = false;\n }\n var tap = this._tap;\n var pos = tap.pos;\n var flushing = false;\n if (this._writeValue(tap, val)) {\n if (!tap.isValid()) {\n if (pos) {\n this._flushChunk(pos, cb);\n flushing = true;\n }\n var len = tap.pos - pos;\n if (len > this._blockSize) {\n this._blockSize = len * 2;\n }\n tap.buf = utils.newBuffer(this._blockSize);\n tap.pos = 0;\n this._writeValue(tap, val);\n }\n this._blockCount++;\n } else {\n tap.pos = pos;\n }\n if (!flushing) {\n cb();\n }\n };\n BlockEncoder.prototype._flushChunk = function(pos, cb) {\n var tap = this._tap;\n pos = pos || tap.pos;\n this._compress(tap.buf.slice(0, pos), this._createBlockCallback(pos, cb));\n this._blockCount = 0;\n };\n BlockEncoder.prototype._read = function() {\n var self = this;\n var data = this._queue.pop();\n if (!data) {\n if (this._finished && !this._pending) {\n process.nextTick(function() {\n self.push(null);\n });\n } else {\n this._needPush = true;\n }\n return;\n }\n this.push(LONG_TYPE.toBuffer(data.count, true));\n this.push(LONG_TYPE.toBuffer(data.buf.length, true));\n this.push(data.buf);\n this.push(this._syncMarker);\n if (!this._finished) {\n data.cb();\n }\n };\n BlockEncoder.prototype._createBlockCallback = function(size, cb) {\n var self = this;\n var index = this._index++;\n var count = this._blockCount;\n this._pending++;\n return function(cause, data) {\n if (cause) {\n var err = new Error(f2(\"%s codec compression error\", self._codec));\n err.cause = cause;\n self.emit(\"error\", err);\n return;\n }\n self._pending--;\n self.emit(\"block\", new BlockInfo(count, size, data.length));\n self._queue.push(new BlockData(index, data, cb, count));\n if (self._needPush) {\n self._needPush = false;\n self._read();\n }\n };\n };\n function BlockInfo(count, raw, compressed) {\n this.valueCount = count;\n this.rawDataLength = raw;\n this.compressedDataLength = compressed;\n }\n function BlockData(index, buf, cb, count) {\n this.index = index;\n this.buf = buf;\n this.cb = cb;\n this.count = count | 0;\n }\n function tryReadBlock(tap) {\n var pos = tap.pos;\n var block = BLOCK_TYPE._read(tap);\n if (!tap.isValid()) {\n tap.pos = pos;\n return null;\n }\n return block;\n }\n function createReader(noDecode, writerType, readerType) {\n if (noDecode) {\n return /* @__PURE__ */ function(skipper) {\n return function(tap) {\n var pos = tap.pos;\n skipper(tap);\n return tap.buf.slice(pos, tap.pos);\n };\n }(writerType._skip);\n } else if (readerType) {\n var resolver = readerType.createResolver(writerType);\n return function(tap) {\n return resolver._read(tap);\n };\n } else {\n return function(tap) {\n return writerType._read(tap);\n };\n }\n }\n function copyBuffer(buf, pos, len) {\n var copy = utils.newBuffer(len);\n buf.copy(copy, 0, pos, pos + len);\n return copy;\n }\n module.exports = {\n BLOCK_TYPE,\n // For tests.\n HEADER_TYPE,\n // Idem.\n MAGIC_BYTES,\n // Idem.\n streams: {\n BlockDecoder,\n BlockEncoder,\n RawDecoder,\n RawEncoder\n }\n };\n }\n});\n\n// node_modules/avsc/lib/services.js\nvar require_services = __commonJS({\n \"node_modules/avsc/lib/services.js\"(exports, module) {\n \"use strict\";\n var types = require_types();\n var utils = require_utils();\n var buffer = __import_BUFFER;\n var events = __import_EVENTS;\n var stream = __import_STREAM;\n var util = __import_UTIL;\n var Buffer2 = buffer.Buffer;\n var Tap = utils.Tap;\n var Type = types.Type;\n var debug = util.debuglog(\"avsc:services\");\n var f2 = util.format;\n var OPTS = { namespace: \"org.apache.avro.ipc\" };\n var BOOLEAN_TYPE = Type.forSchema(\"boolean\", OPTS);\n var MAP_BYTES_TYPE = Type.forSchema({ type: \"map\", values: \"bytes\" }, OPTS);\n var STRING_TYPE = Type.forSchema(\"string\", OPTS);\n var HANDSHAKE_REQUEST_TYPE = Type.forSchema({\n name: \"HandshakeRequest\",\n type: \"record\",\n fields: [\n { name: \"clientHash\", type: { name: \"MD5\", type: \"fixed\", size: 16 } },\n { name: \"clientProtocol\", type: [\"null\", \"string\"], \"default\": null },\n { name: \"serverHash\", type: \"MD5\" },\n { name: \"meta\", type: [\"null\", MAP_BYTES_TYPE], \"default\": null }\n ]\n }, OPTS);\n var HANDSHAKE_RESPONSE_TYPE = Type.forSchema({\n name: \"HandshakeResponse\",\n type: \"record\",\n fields: [\n {\n name: \"match\",\n type: {\n name: \"HandshakeMatch\",\n type: \"enum\",\n symbols: [\"BOTH\", \"CLIENT\", \"NONE\"]\n }\n },\n { name: \"serverProtocol\", type: [\"null\", \"string\"], \"default\": null },\n { name: \"serverHash\", type: [\"null\", \"MD5\"], \"default\": null },\n { name: \"meta\", type: [\"null\", MAP_BYTES_TYPE], \"default\": null }\n ]\n }, OPTS);\n var PREFIX_LENGTH = 16;\n var PING_MESSAGE = new Message(\n \"\",\n // Empty name (invalid for other \"normal\" messages).\n Type.forSchema({ name: \"PingRequest\", type: \"record\", fields: [] }, OPTS),\n Type.forSchema([\"string\"], OPTS),\n Type.forSchema(\"null\", OPTS)\n );\n function Message(name, reqType, errType, resType, oneWay, doc) {\n this.name = name;\n if (!Type.isType(reqType, \"record\")) {\n throw new Error(\"invalid request type\");\n }\n this.requestType = reqType;\n if (!Type.isType(errType, \"union\") || !Type.isType(errType.getTypes()[0], \"string\")) {\n throw new Error(\"invalid error type\");\n }\n this.errorType = errType;\n if (oneWay) {\n if (!Type.isType(resType, \"null\") || errType.getTypes().length > 1) {\n throw new Error(\"inapplicable one-way parameter\");\n }\n }\n this.responseType = resType;\n this.oneWay = !!oneWay;\n this.doc = doc !== void 0 ? \"\" + doc : void 0;\n Object.freeze(this);\n }\n Message.forSchema = function(name, schema, opts) {\n opts = opts || {};\n if (!utils.isValidName(name)) {\n throw new Error(f2(\"invalid message name: %s\", name));\n }\n if (!Array.isArray(schema.request)) {\n throw new Error(f2(\"invalid message request: %s\", name));\n }\n var recordName = f2(\"%s.%sRequest\", OPTS.namespace, utils.capitalize(name));\n var reqType = Type.forSchema({\n name: recordName,\n type: \"record\",\n namespace: opts.namespace || \"\",\n // Don't leak request namespace.\n fields: schema.request\n }, opts);\n delete opts.registry[recordName];\n if (!schema.response) {\n throw new Error(f2(\"invalid message response: %s\", name));\n }\n var resType = Type.forSchema(schema.response, opts);\n if (schema.errors !== void 0 && !Array.isArray(schema.errors)) {\n throw new Error(f2(\"invalid message errors: %s\", name));\n }\n var errType = Type.forSchema([\"string\"].concat(schema.errors || []), opts);\n var oneWay = !!schema[\"one-way\"];\n return new Message(name, reqType, errType, resType, oneWay, schema.doc);\n };\n Message.prototype.schema = Type.prototype.getSchema;\n Message.prototype._attrs = function(opts) {\n var reqSchema = this.requestType._attrs(opts);\n var schema = {\n request: reqSchema.fields,\n response: this.responseType._attrs(opts)\n };\n var msgDoc = this.doc;\n if (msgDoc !== void 0) {\n schema.doc = msgDoc;\n }\n var errSchema = this.errorType._attrs(opts);\n if (errSchema.length > 1) {\n schema.errors = errSchema.slice(1);\n }\n if (this.oneWay) {\n schema[\"one-way\"] = true;\n }\n return schema;\n };\n utils.addDeprecatedGetters(\n Message,\n [\"name\", \"errorType\", \"requestType\", \"responseType\"]\n );\n Message.prototype.isOneWay = util.deprecate(\n function() {\n return this.oneWay;\n },\n \"use `.oneWay` directly instead of `.isOneWay()`\"\n );\n function Service(name, messages, types2, ptcl, server) {\n if (typeof name != \"string\") {\n return Service.forProtocol(name, messages);\n }\n this.name = name;\n this._messagesByName = messages || {};\n this.messages = Object.freeze(utils.objectValues(this._messagesByName));\n this._typesByName = types2 || {};\n this.types = Object.freeze(utils.objectValues(this._typesByName));\n this.protocol = ptcl;\n this._hashStr = utils.getHash(JSON.stringify(ptcl)).toString(\"binary\");\n this.doc = ptcl.doc ? \"\" + ptcl.doc : void 0;\n this._server = server || this.createServer({ silent: true });\n Object.freeze(this);\n }\n Service.Client = Client;\n Service.Server = Server;\n Service.compatible = function(clientSvc, serverSvc) {\n try {\n createReaders(clientSvc, serverSvc);\n } catch (err) {\n return false;\n }\n return true;\n };\n Service.forProtocol = function(ptcl, opts) {\n opts = opts || {};\n var name = ptcl.protocol;\n if (!name) {\n throw new Error(\"missing protocol name\");\n }\n if (ptcl.namespace !== void 0) {\n opts.namespace = ptcl.namespace;\n } else {\n var match = /^(.*)\\.[^.]+$/.exec(name);\n if (match) {\n opts.namespace = match[1];\n }\n }\n name = utils.qualify(name, opts.namespace);\n if (ptcl.types) {\n ptcl.types.forEach(function(obj) {\n Type.forSchema(obj, opts);\n });\n }\n var msgs;\n if (ptcl.messages) {\n msgs = {};\n Object.keys(ptcl.messages).forEach(function(key) {\n msgs[key] = Message.forSchema(key, ptcl.messages[key], opts);\n });\n }\n return new Service(name, msgs, opts.registry, ptcl);\n };\n Service.isService = function(any) {\n return !!any && any.hasOwnProperty(\"_hashStr\");\n };\n Service.prototype.createClient = function(opts) {\n var client = new Client(this, opts);\n process.nextTick(function() {\n if (opts && opts.server) {\n var obj = { objectMode: true };\n var pts = [new stream.PassThrough(obj), new stream.PassThrough(obj)];\n opts.server.createChannel({ readable: pts[0], writable: pts[1] }, obj);\n client.createChannel({ readable: pts[1], writable: pts[0] }, obj);\n } else if (opts && opts.transport) {\n client.createChannel(opts.transport);\n }\n });\n return client;\n };\n Service.prototype.createServer = function(opts) {\n return new Server(this, opts);\n };\n Object.defineProperty(Service.prototype, \"hash\", {\n enumerable: true,\n get: function() {\n return utils.bufferFrom(this._hashStr, \"binary\");\n }\n });\n Service.prototype.message = function(name) {\n return this._messagesByName[name];\n };\n Service.prototype.type = function(name) {\n return this._typesByName[name];\n };\n Service.prototype.inspect = function() {\n return f2(\"\", this.name);\n };\n utils.addDeprecatedGetters(\n Service,\n [\"message\", \"messages\", \"name\", \"type\", \"types\"]\n );\n Service.prototype.createEmitter = util.deprecate(\n function(transport, opts) {\n opts = opts || {};\n var client = this.createClient({\n cache: opts.cache,\n buffering: false,\n strictTypes: opts.strictErrors,\n timeout: opts.timeout\n });\n var channel = client.createChannel(transport, opts);\n forwardErrors(client, channel);\n return channel;\n },\n \"use `.createClient()` instead of `.createEmitter()`\"\n );\n Service.prototype.createListener = util.deprecate(\n function(transport, opts) {\n if (opts && opts.strictErrors) {\n throw new Error(\"use `.createServer()` to support strict errors\");\n }\n return this._server.createChannel(transport, opts);\n },\n \"use `.createServer().createChannel()` instead of `.createListener()`\"\n );\n Service.prototype.emit = util.deprecate(\n function(name, req, channel, cb) {\n if (!channel || !this.equals(channel.client._svc$)) {\n throw new Error(\"invalid emitter\");\n }\n var client = channel.client;\n Client.prototype.emitMessage.call(client, name, req, cb && cb.bind(this));\n return channel.getPending();\n },\n \"create a client via `.createClient()` to emit messages instead of `.emit()`\"\n );\n Service.prototype.equals = util.deprecate(\n function(any) {\n return Service.isService(any) && this.getFingerprint().equals(any.getFingerprint());\n },\n \"equality testing is deprecated, compare the `.protocol`s instead\"\n );\n Service.prototype.getFingerprint = util.deprecate(\n function(algorithm) {\n return utils.getHash(JSON.stringify(this.protocol), algorithm);\n },\n \"use `.hash` instead of `.getFingerprint()`\"\n );\n Service.prototype.getSchema = util.deprecate(\n Type.prototype.getSchema,\n \"use `.protocol` instead of `.getSchema()`\"\n );\n Service.prototype.on = util.deprecate(\n function(name, handler) {\n var self = this;\n this._server.onMessage(name, function(req, cb) {\n return handler.call(self, req, this.channel, cb);\n });\n return this;\n },\n \"use `.createServer().onMessage()` instead of `.on()`\"\n );\n Service.prototype.subprotocol = util.deprecate(\n function() {\n var parent = this._server;\n var opts = { strictTypes: parent._strict, cache: parent._cache };\n var server = new Server(parent.service, opts);\n server._handlers = Object.create(parent._handlers);\n return new Service(\n this.name,\n this._messagesByName,\n this._typesByName,\n this.protocol,\n server\n );\n },\n \"`.subprotocol()` will be removed in 5.1\"\n );\n Service.prototype._attrs = function(opts) {\n var ptcl = { protocol: this.name };\n var types2 = [];\n this.types.forEach(function(t) {\n if (t.getName() === void 0) {\n return;\n }\n var typeSchema = t._attrs(opts);\n if (typeof typeSchema != \"string\") {\n types2.push(typeSchema);\n }\n });\n if (types2.length) {\n ptcl.types = types2;\n }\n var msgNames = Object.keys(this._messagesByName);\n if (msgNames.length) {\n ptcl.messages = {};\n msgNames.forEach(function(name) {\n ptcl.messages[name] = this._messagesByName[name]._attrs(opts);\n }, this);\n }\n if (opts && opts.exportAttrs && this.doc !== void 0) {\n ptcl.doc = this.doc;\n }\n return ptcl;\n };\n function discoverProtocol(transport, opts, cb) {\n if (cb === void 0 && typeof opts == \"function\") {\n cb = opts;\n opts = void 0;\n }\n var svc = new Service({ protocol: \"Empty\" }, OPTS);\n var ptclStr;\n svc.createClient({ timeout: opts && opts.timeout }).createChannel(transport, {\n scope: opts && opts.scope,\n endWritable: typeof transport == \"function\"\n // Stateless transports only.\n }).once(\"handshake\", function(hreq, hres) {\n ptclStr = hres.serverProtocol;\n this.destroy(true);\n }).once(\"eot\", function(pending, err) {\n if (err && !/interrupted/.test(err)) {\n cb(err);\n } else {\n cb(null, JSON.parse(ptclStr));\n }\n });\n }\n function Client(svc, opts) {\n opts = opts || {};\n events.EventEmitter.call(this);\n this._svc$ = svc;\n this._channels$ = [];\n this._fns$ = [];\n this._buffering$ = !!opts.buffering;\n this._cache$ = opts.cache || {};\n this._policy$ = opts.channelPolicy;\n this._strict$ = !!opts.strictTypes;\n this._timeout$ = utils.getOption(opts, \"timeout\", 1e4);\n if (opts.remoteProtocols) {\n insertRemoteProtocols(this._cache$, opts.remoteProtocols, svc, true);\n }\n this._svc$.messages.forEach(function(msg) {\n this[msg.name] = this._createMessageHandler$(msg);\n }, this);\n }\n util.inherits(Client, events.EventEmitter);\n Client.prototype.activeChannels = function() {\n return this._channels$.slice();\n };\n Client.prototype.createChannel = function(transport, opts) {\n var objectMode = opts && opts.objectMode;\n var channel;\n if (typeof transport == \"function\") {\n var writableFactory;\n if (objectMode) {\n writableFactory = transport;\n } else {\n writableFactory = function(cb) {\n var encoder2 = new FrameEncoder();\n var writable2 = transport(function(err, readable2) {\n if (err) {\n cb(err);\n return;\n }\n var decoder2 = new FrameDecoder().once(\"error\", function(err2) {\n channel.destroy(err2);\n });\n cb(null, readable2.pipe(decoder2));\n });\n if (writable2) {\n encoder2.pipe(writable2);\n return encoder2;\n }\n };\n }\n channel = new StatelessClientChannel(this, writableFactory, opts);\n } else {\n var readable, writable;\n if (isStream(transport)) {\n readable = writable = transport;\n } else {\n readable = transport.readable;\n writable = transport.writable;\n }\n if (!objectMode) {\n var decoder = new NettyDecoder();\n readable = readable.pipe(decoder);\n var encoder = new NettyEncoder();\n encoder.pipe(writable);\n writable = encoder;\n }\n channel = new StatefulClientChannel(this, readable, writable, opts);\n if (!objectMode) {\n channel.once(\"eot\", function() {\n readable.unpipe(decoder);\n encoder.unpipe(writable);\n });\n decoder.once(\"error\", function(err) {\n channel.destroy(err);\n });\n }\n }\n var channels = this._channels$;\n channels.push(channel);\n channel.once(\"_drain\", function() {\n channels.splice(channels.indexOf(this), 1);\n });\n this._buffering$ = false;\n this.emit(\"channel\", channel);\n return channel;\n };\n Client.prototype.destroyChannels = function(opts) {\n this._channels$.forEach(function(channel) {\n channel.destroy(opts && opts.noWait);\n });\n };\n Client.prototype.emitMessage = function(name, req, opts, cb) {\n var msg = getExistingMessage(this._svc$, name);\n var wreq = new WrappedRequest(msg, {}, req);\n this._emitMessage$(wreq, opts, cb);\n };\n Client.prototype.remoteProtocols = function() {\n return getRemoteProtocols(this._cache$, true);\n };\n Object.defineProperty(Client.prototype, \"service\", {\n enumerable: true,\n get: function() {\n return this._svc$;\n }\n });\n Client.prototype.use = function() {\n var i, l, fn;\n for (i = 0, l = arguments.length; i < l; i++) {\n fn = arguments[i];\n this._fns$.push(fn.length < 3 ? fn(this) : fn);\n }\n return this;\n };\n Client.prototype._emitMessage$ = function(wreq, opts, cb) {\n if (!cb && typeof opts === \"function\") {\n cb = opts;\n opts = void 0;\n }\n var self = this;\n var channels = this._channels$;\n var numChannels = channels.length;\n if (!numChannels) {\n if (this._buffering$) {\n debug(\"no active client channels, buffering call\");\n this.once(\"channel\", function() {\n this._emitMessage$(wreq, opts, cb);\n });\n } else {\n var err = new Error(\"no active channels\");\n process.nextTick(function() {\n if (cb) {\n cb.call(new CallContext(wreq._msg), err);\n } else {\n self.emit(\"error\", err);\n }\n });\n }\n return;\n }\n opts = opts || {};\n if (opts.timeout === void 0) {\n opts.timeout = this._timeout$;\n }\n var channel;\n if (numChannels === 1) {\n channel = channels[0];\n } else if (this._policy$) {\n channel = this._policy$(this._channels$.slice());\n if (!channel) {\n debug(\"policy returned no channel, skipping call\");\n return;\n }\n } else {\n channel = channels[Math.floor(Math.random() * numChannels)];\n }\n channel._emit(wreq, opts, function(err2, wres) {\n var ctx = this;\n var errType = ctx.message.errorType;\n if (err2) {\n if (self._strict$) {\n err2 = errType.clone(err2.message, { wrapUnions: true });\n }\n done(err2);\n return;\n }\n if (!wres) {\n done();\n return;\n }\n err2 = wres.error;\n if (!self._strict$) {\n if (err2 === void 0) {\n err2 = null;\n } else {\n if (Type.isType(errType, \"union:unwrapped\")) {\n if (typeof err2 == \"string\") {\n err2 = new Error(err2);\n }\n } else if (err2 && err2.string && typeof err2.string == \"string\") {\n err2 = new Error(err2.string);\n }\n }\n }\n done(err2, wres.response);\n function done(err3, res) {\n if (cb) {\n cb.call(ctx, err3, res);\n } else if (err3) {\n self.emit(\"error\", err3);\n }\n }\n });\n };\n Client.prototype._createMessageHandler$ = function(msg) {\n var fields = msg.requestType.getFields();\n var names = fields.map(function(f3) {\n return f3.getName();\n });\n var body = \"return function \" + msg.name + \"(\";\n if (names.length) {\n body += names.join(\", \") + \", \";\n }\n body += \"opts, cb) {\\n\";\n body += \" var req = {\";\n body += names.map(function(n) {\n return n + \": \" + n;\n }).join(\", \");\n body += \"};\\n\";\n body += \" return this.emitMessage('\" + msg.name + \"', req, opts, cb);\\n\";\n body += \"};\";\n return new Function(body)();\n };\n function Server(svc, opts) {\n opts = opts || {};\n events.EventEmitter.call(this);\n this.service = svc;\n this._handlers = {};\n this._fns = [];\n this._channels = {};\n this._nextChannelId = 1;\n this._cache = opts.cache || {};\n this._defaultHandler = opts.defaultHandler;\n this._sysErrFormatter = opts.systemErrorFormatter;\n this._silent = !!opts.silent;\n this._strict = !!opts.strictTypes;\n if (opts.remoteProtocols) {\n insertRemoteProtocols(this._cache, opts.remoteProtocols, svc, false);\n }\n svc.messages.forEach(function(msg) {\n var name = msg.name;\n if (!opts.noCapitalize) {\n name = utils.capitalize(name);\n }\n this[\"on\" + name] = this._createMessageHandler(msg);\n }, this);\n }\n util.inherits(Server, events.EventEmitter);\n Server.prototype.activeChannels = function() {\n return utils.objectValues(this._channels);\n };\n Server.prototype.createChannel = function(transport, opts) {\n var objectMode = opts && opts.objectMode;\n var channel;\n if (typeof transport == \"function\") {\n var readableFactory;\n if (objectMode) {\n readableFactory = transport;\n } else {\n readableFactory = function(cb) {\n var decoder2 = new FrameDecoder().once(\"error\", function(err) {\n channel.destroy(err);\n });\n return transport(function(err, writable2) {\n if (err) {\n cb(err);\n return;\n }\n var encoder2 = new FrameEncoder();\n encoder2.pipe(writable2);\n cb(null, encoder2);\n }).pipe(decoder2);\n };\n }\n channel = new StatelessServerChannel(this, readableFactory, opts);\n } else {\n var readable, writable;\n if (isStream(transport)) {\n readable = writable = transport;\n } else {\n readable = transport.readable;\n writable = transport.writable;\n }\n if (!objectMode) {\n var decoder = new NettyDecoder();\n readable = readable.pipe(decoder);\n var encoder = new NettyEncoder();\n encoder.pipe(writable);\n writable = encoder;\n }\n channel = new StatefulServerChannel(this, readable, writable, opts);\n if (!objectMode) {\n channel.once(\"eot\", function() {\n readable.unpipe(decoder);\n encoder.unpipe(writable);\n });\n decoder.once(\"error\", function(err) {\n channel.destroy(err);\n });\n }\n }\n if (!this.listeners(\"error\").length) {\n this.on(\"error\", this._onError);\n }\n var channelId = this._nextChannelId++;\n var channels = this._channels;\n channels[channelId] = channel.once(\"eot\", function() {\n delete channels[channelId];\n });\n this.emit(\"channel\", channel);\n return channel;\n };\n Server.prototype.onMessage = function(name, handler) {\n getExistingMessage(this.service, name);\n this._handlers[name] = handler;\n return this;\n };\n Server.prototype.remoteProtocols = function() {\n return getRemoteProtocols(this._cache, false);\n };\n Server.prototype.use = function() {\n var i, l, fn;\n for (i = 0, l = arguments.length; i < l; i++) {\n fn = arguments[i];\n this._fns.push(fn.length < 3 ? fn(this) : fn);\n }\n return this;\n };\n Server.prototype._createMessageHandler = function(msg) {\n var name = msg.name;\n var fields = msg.requestType.fields;\n var numArgs = fields.length;\n var args = fields.length ? \", \" + fields.map(function(f3) {\n return \"req.\" + f3.name;\n }).join(\", \") : \"\";\n var body = \"return function (handler) {\\n\";\n body += \" if (handler.length > \" + numArgs + \") {\\n\";\n body += \" return this.onMessage('\" + name + \"', function (req, cb) {\\n\";\n body += \" return handler.call(this\" + args + \", cb);\\n\";\n body += \" });\\n\";\n body += \" } else {\\n\";\n body += \" return this.onMessage('\" + name + \"', function (req) {\\n\";\n body += \" return handler.call(this\" + args + \");\\n\";\n body += \" });\\n\";\n body += \" }\\n\";\n body += \"};\\n\";\n return new Function(body)();\n };\n Server.prototype._onError = function(err) {\n if (!this._silent && err.rpcCode !== \"UNKNOWN_PROTOCOL\") {\n console.error();\n if (err.rpcCode) {\n console.error(err.rpcCode);\n console.error(err.cause);\n } else {\n console.error(\"INTERNAL_SERVER_ERROR\");\n console.error(err);\n }\n }\n };\n function ClientChannel(client, opts) {\n opts = opts || {};\n events.EventEmitter.call(this);\n this.client = client;\n this.timeout = utils.getOption(opts, \"timeout\", client._timeout$);\n this._endWritable = !!utils.getOption(opts, \"endWritable\", true);\n this._prefix = normalizedPrefix(opts.scope);\n var cache = client._cache$;\n var clientSvc = client._svc$;\n var hash = opts.serverHash;\n if (!hash) {\n hash = clientSvc.hash;\n }\n var adapter = cache[hash];\n if (!adapter) {\n hash = clientSvc.hash;\n adapter = cache[hash] = new Adapter(clientSvc, clientSvc, hash);\n }\n this._adapter = adapter;\n this._registry = new Registry(this, PREFIX_LENGTH);\n this.pending = 0;\n this.destroyed = false;\n this.draining = false;\n this.once(\"_eot\", function(pending, err) {\n debug(\"client channel EOT\");\n this.destroyed = true;\n this.emit(\"eot\", pending, err);\n });\n }\n util.inherits(ClientChannel, events.EventEmitter);\n ClientChannel.prototype.destroy = function(noWait) {\n debug(\"destroying client channel\");\n if (!this.draining) {\n this.draining = true;\n this.emit(\"_drain\");\n }\n var registry = this._registry;\n var pending = this.pending;\n if (noWait) {\n registry.clear();\n }\n if (noWait || !pending) {\n if (isError(noWait)) {\n debug(\"fatal client channel error: %s\", noWait);\n this.emit(\"_eot\", pending, noWait);\n } else {\n this.emit(\"_eot\", pending);\n }\n } else {\n debug(\"client channel entering drain mode (%s pending)\", pending);\n }\n };\n ClientChannel.prototype.ping = function(timeout, cb) {\n if (!cb && typeof timeout == \"function\") {\n cb = timeout;\n timeout = void 0;\n }\n var self = this;\n var wreq = new WrappedRequest(PING_MESSAGE);\n this._emit(wreq, { timeout }, function(err) {\n if (cb) {\n cb.call(self, err);\n } else if (err) {\n self.destroy(err);\n }\n });\n };\n ClientChannel.prototype._createHandshakeRequest = function(adapter, noSvc) {\n var svc = this.client._svc$;\n return {\n clientHash: svc.hash,\n clientProtocol: noSvc ? null : JSON.stringify(svc.protocol),\n serverHash: adapter._hash\n };\n };\n ClientChannel.prototype._emit = function(wreq, opts, cb) {\n var msg = wreq._msg;\n var wres = msg.oneWay ? void 0 : new WrappedResponse(msg, {});\n var ctx = new CallContext(msg, this);\n var self = this;\n this.pending++;\n process.nextTick(function() {\n if (!msg.name) {\n onTransition(wreq, wres, onCompletion);\n } else {\n self.emit(\"outgoingCall\", ctx, opts);\n var fns = self.client._fns$;\n debug(\"starting client middleware chain (%s middleware)\", fns.length);\n chainMiddleware({\n fns,\n ctx,\n wreq,\n wres,\n onTransition,\n onCompletion,\n onError\n });\n }\n });\n function onTransition(wreq2, wres2, prev) {\n var err, reqBuf;\n if (self.destroyed) {\n err = new Error(\"channel destroyed\");\n } else {\n try {\n reqBuf = wreq2.toBuffer();\n } catch (cause) {\n err = serializationError(\n f2(\"invalid %j request\", msg.name),\n wreq2,\n [\n { name: \"headers\", type: MAP_BYTES_TYPE },\n { name: \"request\", type: msg.requestType }\n ]\n );\n }\n }\n if (err) {\n prev(err);\n return;\n }\n var timeout = opts && opts.timeout !== void 0 ? opts.timeout : self.timeout;\n var id = self._registry.add(timeout, function(err2, resBuf, adapter) {\n if (!err2 && !msg.oneWay) {\n try {\n adapter._decodeResponse(resBuf, wres2, msg);\n } catch (cause) {\n err2 = cause;\n }\n }\n prev(err2);\n });\n id |= self._prefix;\n debug(\"sending message %s\", id);\n self._send(id, reqBuf, !!msg && msg.oneWay);\n }\n function onCompletion(err) {\n self.pending--;\n cb.call(ctx, err, wres);\n if (self.draining && !self.destroyed && !self.pending) {\n self.destroy();\n }\n }\n function onError(err) {\n self.client.emit(\"error\", err, self);\n }\n };\n ClientChannel.prototype._getAdapter = function(hres) {\n var hash = hres.serverHash;\n var cache = this.client._cache$;\n var adapter = cache[hash];\n if (adapter) {\n return adapter;\n }\n var ptcl = JSON.parse(hres.serverProtocol);\n var serverSvc = Service.forProtocol(ptcl);\n adapter = new Adapter(this.client._svc$, serverSvc, hash, true);\n return cache[hash] = adapter;\n };\n ClientChannel.prototype._matchesPrefix = function(id) {\n return matchesPrefix(id, this._prefix);\n };\n ClientChannel.prototype._send = utils.abstractFunction;\n utils.addDeprecatedGetters(ClientChannel, [\"pending\", \"timeout\"]);\n ClientChannel.prototype.getCache = util.deprecate(\n function() {\n return this.client._cache$;\n },\n \"use `.remoteProtocols()` instead of `.getCache()`\"\n );\n ClientChannel.prototype.getProtocol = util.deprecate(\n function() {\n return this.client._svc$;\n },\n \"use `.service` instead or `.getProtocol()`\"\n );\n ClientChannel.prototype.isDestroyed = util.deprecate(\n function() {\n return this.destroyed;\n },\n \"use `.destroyed` instead of `.isDestroyed`\"\n );\n function StatelessClientChannel(client, writableFactory, opts) {\n ClientChannel.call(this, client, opts);\n this._writableFactory = writableFactory;\n if (!opts || !opts.noPing) {\n debug(\"emitting ping request\");\n this.ping();\n }\n }\n util.inherits(StatelessClientChannel, ClientChannel);\n StatelessClientChannel.prototype._send = function(id, reqBuf) {\n var cb = this._registry.get(id);\n var adapter = this._adapter;\n var self = this;\n process.nextTick(emit);\n return true;\n function emit(retry) {\n if (self.destroyed) {\n return;\n }\n var hreq = self._createHandshakeRequest(adapter, !retry);\n var writable = self._writableFactory.call(self, function(err, readable) {\n if (err) {\n cb(err);\n return;\n }\n readable.on(\"data\", function(obj) {\n debug(\"received response %s\", obj.id);\n var buf = Buffer2.concat(obj.payload);\n try {\n var parts = readHead(HANDSHAKE_RESPONSE_TYPE, buf);\n var hres = parts.head;\n if (hres.serverHash) {\n adapter = self._getAdapter(hres);\n }\n } catch (cause) {\n cb(cause);\n return;\n }\n var match = hres.match;\n debug(\"handshake match: %s\", match);\n self.emit(\"handshake\", hreq, hres);\n if (match === \"NONE\") {\n process.nextTick(function() {\n emit(true);\n });\n } else {\n self._adapter = adapter;\n cb(null, parts.tail, adapter);\n }\n });\n });\n if (!writable) {\n cb(new Error(\"invalid writable stream\"));\n return;\n }\n writable.write({\n id,\n payload: [HANDSHAKE_REQUEST_TYPE.toBuffer(hreq), reqBuf]\n });\n if (self._endWritable) {\n writable.end();\n }\n }\n };\n function StatefulClientChannel(client, readable, writable, opts) {\n ClientChannel.call(this, client, opts);\n this._readable = readable;\n this._writable = writable;\n this._connected = !!(opts && opts.noPing);\n this._readable.on(\"end\", onEnd);\n this._writable.on(\"finish\", onFinish);\n var self = this;\n var timer = null;\n this.once(\"eot\", function() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (!self._connected) {\n self.emit(\"_ready\");\n }\n this._writable.removeListener(\"finish\", onFinish);\n if (this._endWritable) {\n debug(\"ending transport\");\n this._writable.end();\n }\n this._readable.removeListener(\"data\", onPing).removeListener(\"data\", onMessage).removeListener(\"end\", onEnd);\n });\n var hreq;\n if (this._connected) {\n this._readable.on(\"data\", onMessage);\n } else {\n this._readable.on(\"data\", onPing);\n process.nextTick(ping);\n if (self.timeout) {\n timer = setTimeout(function() {\n self.destroy(new Error(\"timeout\"));\n }, self.timeout);\n }\n }\n function ping(retry) {\n if (self.destroyed) {\n return;\n }\n hreq = self._createHandshakeRequest(self._adapter, !retry);\n var payload = [\n HANDSHAKE_REQUEST_TYPE.toBuffer(hreq),\n utils.bufferFrom([0, 0])\n // No header, no data (empty message name).\n ];\n self._writable.write({ id: self._prefix, payload });\n }\n function onPing(obj) {\n if (!self._matchesPrefix(obj.id)) {\n debug(\"discarding unscoped response %s (still connecting)\", obj.id);\n return;\n }\n var buf = Buffer2.concat(obj.payload);\n try {\n var hres = readHead(HANDSHAKE_RESPONSE_TYPE, buf).head;\n if (hres.serverHash) {\n self._adapter = self._getAdapter(hres);\n }\n } catch (cause) {\n self.destroy(cause);\n return;\n }\n var match = hres.match;\n debug(\"handshake match: %s\", match);\n self.emit(\"handshake\", hreq, hres);\n if (match === \"NONE\") {\n process.nextTick(function() {\n ping(true);\n });\n } else {\n debug(\"successfully connected\");\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n self._readable.removeListener(\"data\", onPing).on(\"data\", onMessage);\n self._connected = true;\n self.emit(\"_ready\");\n hreq = null;\n }\n }\n function onMessage(obj) {\n var id = obj.id;\n if (!self._matchesPrefix(id)) {\n debug(\"discarding unscoped message %s\", id);\n return;\n }\n var cb = self._registry.get(id);\n if (cb) {\n process.nextTick(function() {\n debug(\"received message %s\", id);\n cb(null, Buffer2.concat(obj.payload), self._adapter);\n });\n }\n }\n function onEnd() {\n self.destroy(true);\n }\n function onFinish() {\n self.destroy();\n }\n }\n util.inherits(StatefulClientChannel, ClientChannel);\n StatefulClientChannel.prototype._emit = function() {\n if (this._connected || this.draining) {\n ClientChannel.prototype._emit.apply(this, arguments);\n } else {\n debug(\"queuing request\");\n var args = [];\n var i, l;\n for (i = 0, l = arguments.length; i < l; i++) {\n args.push(arguments[i]);\n }\n this.once(\"_ready\", function() {\n this._emit.apply(this, args);\n });\n }\n };\n StatefulClientChannel.prototype._send = function(id, reqBuf, oneWay) {\n if (oneWay) {\n var self = this;\n process.nextTick(function() {\n self._registry.get(id)(null, utils.bufferFrom([0, 0, 0]), self._adapter);\n });\n }\n return this._writable.write({ id, payload: [reqBuf] });\n };\n function ServerChannel(server, opts) {\n opts = opts || {};\n events.EventEmitter.call(this);\n this.server = server;\n this._endWritable = !!utils.getOption(opts, \"endWritable\", true);\n this._prefix = normalizedPrefix(opts.scope);\n var cache = server._cache;\n var svc = server.service;\n var hash = svc.hash;\n if (!cache[hash]) {\n cache[hash] = new Adapter(svc, svc, hash);\n }\n this._adapter = null;\n this.destroyed = false;\n this.draining = false;\n this.pending = 0;\n this.once(\"_eot\", function(pending, err) {\n debug(\"server channel EOT\");\n this.emit(\"eot\", pending, err);\n });\n }\n util.inherits(ServerChannel, events.EventEmitter);\n ServerChannel.prototype.destroy = function(noWait) {\n if (!this.draining) {\n this.draining = true;\n this.emit(\"_drain\");\n }\n if (noWait || !this.pending) {\n this.destroyed = true;\n if (isError(noWait)) {\n debug(\"fatal server channel error: %s\", noWait);\n this.emit(\"_eot\", this.pending, noWait);\n } else {\n this.emit(\"_eot\", this.pending);\n }\n }\n };\n ServerChannel.prototype._createHandshakeResponse = function(err, hreq) {\n var svc = this.server.service;\n var buf = svc.hash;\n var serverMatch = hreq && hreq.serverHash.equals(buf);\n return {\n match: err ? \"NONE\" : serverMatch ? \"BOTH\" : \"CLIENT\",\n serverProtocol: serverMatch ? null : JSON.stringify(svc.protocol),\n serverHash: serverMatch ? null : buf\n };\n };\n ServerChannel.prototype._getAdapter = function(hreq) {\n var hash = hreq.clientHash;\n var adapter = this.server._cache[hash];\n if (adapter) {\n return adapter;\n }\n if (!hreq.clientProtocol) {\n throw toRpcError(\"UNKNOWN_PROTOCOL\");\n }\n var ptcl = JSON.parse(hreq.clientProtocol);\n var clientSvc = Service.forProtocol(ptcl);\n adapter = new Adapter(clientSvc, this.server.service, hash, true);\n return this.server._cache[hash] = adapter;\n };\n ServerChannel.prototype._matchesPrefix = function(id) {\n return matchesPrefix(id, this._prefix);\n };\n ServerChannel.prototype._receive = function(reqBuf, adapter, cb) {\n var self = this;\n var wreq;\n try {\n wreq = adapter._decodeRequest(reqBuf);\n } catch (cause) {\n cb(self._encodeSystemError(toRpcError(\"INVALID_REQUEST\", cause)));\n return;\n }\n var msg = wreq._msg;\n var wres = new WrappedResponse(msg, {});\n if (!msg.name) {\n wres.response = null;\n cb(wres.toBuffer(), false);\n return;\n }\n var ctx = new CallContext(msg, this);\n self.emit(\"incomingCall\", ctx);\n var fns = this.server._fns;\n debug(\"starting server middleware chain (%s middleware)\", fns.length);\n self.pending++;\n chainMiddleware({\n fns,\n ctx,\n wreq,\n wres,\n onTransition,\n onCompletion,\n onError\n });\n function onTransition(wreq2, wres2, prev) {\n var handler = self.server._handlers[msg.name];\n if (!handler) {\n var defaultHandler = self.server._defaultHandler;\n if (defaultHandler) {\n defaultHandler.call(ctx, wreq2, wres2, prev);\n } else {\n var cause = new Error(f2(\"no handler for %s\", msg.name));\n prev(toRpcError(\"NOT_IMPLEMENTED\", cause));\n }\n } else {\n var pending = !msg.oneWay;\n try {\n if (pending) {\n handler.call(ctx, wreq2.request, function(err, res) {\n pending = false;\n wres2.error = err;\n wres2.response = res;\n prev();\n });\n } else {\n handler.call(ctx, wreq2.request);\n prev();\n }\n } catch (err) {\n if (pending) {\n pending = false;\n prev(err);\n } else {\n onError(err);\n }\n }\n }\n }\n function onCompletion(err) {\n self.pending--;\n var server = self.server;\n var resBuf;\n if (!err) {\n var resErr = wres.error;\n var isStrict = server._strict;\n if (!isStrict) {\n if (isError(resErr)) {\n wres.error = msg.errorType.clone(resErr.message, { wrapUnions: true });\n } else if (resErr === null) {\n resErr = wres.error = void 0;\n }\n if (resErr === void 0 && wres.response === void 0 && msg.responseType.isValid(null)) {\n wres.response = null;\n }\n }\n try {\n resBuf = wres.toBuffer();\n } catch (cause) {\n if (wres.error !== void 0) {\n err = serializationError(\n f2(\"invalid %j error\", msg.name),\n // Sic.\n wres,\n [\n { name: \"headers\", type: MAP_BYTES_TYPE },\n { name: \"error\", type: msg.errorType }\n ]\n );\n } else {\n err = serializationError(\n f2(\"invalid %j response\", msg.name),\n wres,\n [\n { name: \"headers\", type: MAP_BYTES_TYPE },\n { name: \"response\", type: msg.responseType }\n ]\n );\n }\n }\n }\n if (!resBuf) {\n resBuf = self._encodeSystemError(err, wres.headers);\n } else if (resErr !== void 0) {\n server.emit(\"error\", toRpcError(\"APPLICATION_ERROR\", resErr));\n }\n cb(resBuf, msg.oneWay);\n if (self.draining && !self.pending) {\n self.destroy();\n }\n }\n function onError(err) {\n self.server.emit(\"error\", err, self);\n }\n };\n utils.addDeprecatedGetters(ServerChannel, [\"pending\"]);\n ServerChannel.prototype.getCache = util.deprecate(\n function() {\n return this.server._cache;\n },\n \"use `.remoteProtocols()` instead of `.getCache()`\"\n );\n ServerChannel.prototype.getProtocol = util.deprecate(\n function() {\n return this.server.service;\n },\n \"use `.service` instead of `.getProtocol()`\"\n );\n ServerChannel.prototype.isDestroyed = util.deprecate(\n function() {\n return this.destroyed;\n },\n \"use `.destroyed` instead of `.isDestroyed`\"\n );\n ServerChannel.prototype._encodeSystemError = function(err, header) {\n var server = this.server;\n server.emit(\"error\", err, this);\n var errStr;\n if (server._sysErrFormatter) {\n errStr = server._sysErrFormatter.call(this, err);\n } else if (err.rpcCode) {\n errStr = err.message;\n }\n var hdrBuf;\n if (header) {\n try {\n hdrBuf = MAP_BYTES_TYPE.toBuffer(header);\n } catch (cause) {\n server.emit(\"error\", cause, this);\n }\n }\n return Buffer2.concat([\n hdrBuf || utils.bufferFrom([0]),\n utils.bufferFrom([1, 0]),\n // Error flag and first union index.\n STRING_TYPE.toBuffer(errStr || \"internal server error\")\n ]);\n };\n function StatelessServerChannel(server, readableFactory, opts) {\n ServerChannel.call(this, server, opts);\n this._writable = void 0;\n var self = this;\n var readable;\n process.nextTick(function() {\n readable = readableFactory.call(self, function(err, writable) {\n process.nextTick(function() {\n if (err) {\n onFinish(err);\n return;\n }\n self._writable = writable.on(\"finish\", onFinish);\n self.emit(\"_writable\");\n });\n }).on(\"data\", onRequest).on(\"end\", onEnd);\n });\n function onRequest(obj) {\n var id = obj.id;\n var buf = Buffer2.concat(obj.payload);\n var err;\n try {\n var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf);\n var hreq = parts.head;\n var adapter = self._getAdapter(hreq);\n } catch (cause) {\n err = toRpcError(\"INVALID_HANDSHAKE_REQUEST\", cause);\n }\n var hres = self._createHandshakeResponse(err, hreq);\n self.emit(\"handshake\", hreq, hres);\n if (err) {\n done(self._encodeSystemError(err));\n } else {\n self._receive(parts.tail, adapter, done);\n }\n function done(resBuf) {\n if (!self.destroyed) {\n if (!self._writable) {\n self.once(\"_writable\", function() {\n done(resBuf);\n });\n return;\n }\n self._writable.write({\n id,\n payload: [HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf]\n });\n }\n if (self._writable && self._endWritable) {\n self._writable.end();\n }\n }\n }\n function onEnd() {\n self.destroy();\n }\n function onFinish(err) {\n readable.removeListener(\"data\", onRequest).removeListener(\"end\", onEnd);\n self.destroy(err || true);\n }\n }\n util.inherits(StatelessServerChannel, ServerChannel);\n function StatefulServerChannel(server, readable, writable, opts) {\n ServerChannel.call(this, server, opts);\n this._adapter = void 0;\n this._writable = writable.on(\"finish\", onFinish);\n this._readable = readable.on(\"data\", onHandshake).on(\"end\", onEnd);\n this.once(\"_drain\", function() {\n this._readable.removeListener(\"data\", onHandshake).removeListener(\"data\", onRequest).removeListener(\"end\", onEnd);\n }).once(\"eot\", function() {\n this._writable.removeListener(\"finish\", onFinish);\n if (this._endWritable) {\n this._writable.end();\n }\n });\n var self = this;\n function onHandshake(obj) {\n var id = obj.id;\n if (!self._matchesPrefix(id)) {\n return;\n }\n var buf = Buffer2.concat(obj.payload);\n var err;\n try {\n var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf);\n var hreq = parts.head;\n self._adapter = self._getAdapter(hreq);\n } catch (cause) {\n err = toRpcError(\"INVALID_HANDSHAKE_REQUEST\", cause);\n }\n var hres = self._createHandshakeResponse(err, hreq);\n self.emit(\"handshake\", hreq, hres);\n if (err) {\n done(self._encodeSystemError(err));\n } else {\n self._readable.removeListener(\"data\", onHandshake).on(\"data\", onRequest);\n self._receive(parts.tail, self._adapter, done);\n }\n function done(resBuf) {\n if (self.destroyed) {\n return;\n }\n self._writable.write({\n id,\n payload: [HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf]\n });\n }\n }\n function onRequest(obj) {\n var id = obj.id;\n if (!self._matchesPrefix(id)) {\n return;\n }\n var reqBuf = Buffer2.concat(obj.payload);\n self._receive(reqBuf, self._adapter, function(resBuf, oneWay) {\n if (self.destroyed || oneWay) {\n return;\n }\n self._writable.write({ id, payload: [resBuf] });\n });\n }\n function onEnd() {\n self.destroy();\n }\n function onFinish() {\n self.destroy(true);\n }\n }\n util.inherits(StatefulServerChannel, ServerChannel);\n function WrappedRequest(msg, hdrs, req) {\n this._msg = msg;\n this.headers = hdrs || {};\n this.request = req || {};\n }\n WrappedRequest.prototype.toBuffer = function() {\n var msg = this._msg;\n return Buffer2.concat([\n MAP_BYTES_TYPE.toBuffer(this.headers),\n STRING_TYPE.toBuffer(msg.name),\n msg.requestType.toBuffer(this.request)\n ]);\n };\n function WrappedResponse(msg, hdr, err, res) {\n this._msg = msg;\n this.headers = hdr;\n this.error = err;\n this.response = res;\n }\n WrappedResponse.prototype.toBuffer = function() {\n var hdr = MAP_BYTES_TYPE.toBuffer(this.headers);\n var hasError = this.error !== void 0;\n return Buffer2.concat([\n hdr,\n BOOLEAN_TYPE.toBuffer(hasError),\n hasError ? this._msg.errorType.toBuffer(this.error) : this._msg.responseType.toBuffer(this.response)\n ]);\n };\n function CallContext(msg, channel) {\n this.channel = channel;\n this.locals = {};\n this.message = msg;\n Object.freeze(this);\n }\n function Registry(ctx, prefixLength) {\n this._ctx = ctx;\n this._mask = ~0 >>> (prefixLength | 0);\n this._id = 0;\n this._n = 0;\n this._cbs = {};\n }\n Registry.prototype.get = function(id) {\n return this._cbs[id & this._mask];\n };\n Registry.prototype.add = function(timeout, fn) {\n this._id = this._id + 1 & this._mask;\n var self = this;\n var id = this._id;\n var timer;\n if (timeout > 0) {\n timer = setTimeout(function() {\n cb(new Error(\"timeout\"));\n }, timeout);\n }\n this._cbs[id] = cb;\n this._n++;\n return id;\n function cb() {\n if (!self._cbs[id]) {\n return;\n }\n delete self._cbs[id];\n self._n--;\n if (timer) {\n clearTimeout(timer);\n }\n fn.apply(self._ctx, arguments);\n }\n };\n Registry.prototype.clear = function() {\n Object.keys(this._cbs).forEach(function(id) {\n this._cbs[id](new Error(\"interrupted\"));\n }, this);\n };\n function Adapter(clientSvc, serverSvc, hash, isRemote) {\n this._clientSvc = clientSvc;\n this._serverSvc = serverSvc;\n this._hash = hash;\n this._isRemote = !!isRemote;\n this._readers = createReaders(clientSvc, serverSvc);\n }\n Adapter.prototype._decodeRequest = function(buf) {\n var tap = new Tap(buf);\n var hdr = MAP_BYTES_TYPE._read(tap);\n var name = STRING_TYPE._read(tap);\n var msg, req;\n if (name) {\n msg = this._serverSvc.message(name);\n req = this._readers[name + \"?\"]._read(tap);\n } else {\n msg = PING_MESSAGE;\n }\n if (!tap.isValid()) {\n throw new Error(f2(\"truncated %s request\", name || \"ping$\"));\n }\n return new WrappedRequest(msg, hdr, req);\n };\n Adapter.prototype._decodeResponse = function(buf, wres, msg) {\n var tap = new Tap(buf);\n utils.copyOwnProperties(MAP_BYTES_TYPE._read(tap), wres.headers, true);\n var isError2 = BOOLEAN_TYPE._read(tap);\n var name = msg.name;\n if (name) {\n var reader = this._readers[name + (isError2 ? \"*\" : \"!\")];\n msg = this._clientSvc.message(name);\n if (isError2) {\n wres.error = reader._read(tap);\n } else {\n wres.response = reader._read(tap);\n }\n if (!tap.isValid()) {\n throw new Error(f2(\"truncated %s response\", name));\n }\n } else {\n msg = PING_MESSAGE;\n }\n };\n function FrameDecoder() {\n stream.Transform.call(this, { readableObjectMode: true });\n this._id = void 0;\n this._buf = utils.newBuffer(0);\n this._bufs = [];\n this.on(\"finish\", function() {\n this.push(null);\n });\n }\n util.inherits(FrameDecoder, stream.Transform);\n FrameDecoder.prototype._transform = function(buf, encoding, cb) {\n buf = Buffer2.concat([this._buf, buf]);\n var frameLength;\n while (buf.length >= 4 && buf.length >= (frameLength = buf.readInt32BE(0)) + 4) {\n if (frameLength) {\n this._bufs.push(buf.slice(4, frameLength + 4));\n } else {\n var bufs = this._bufs;\n this._bufs = [];\n this.push({ id: null, payload: bufs });\n }\n buf = buf.slice(frameLength + 4);\n }\n this._buf = buf;\n cb();\n };\n FrameDecoder.prototype._flush = function(cb) {\n if (this._buf.length || this._bufs.length) {\n var bufs = this._bufs.slice();\n bufs.unshift(this._buf);\n var err = toRpcError(\"TRAILING_DATA\");\n err.trailingData = Buffer2.concat(bufs).toString();\n this.emit(\"error\", err);\n }\n cb();\n };\n function FrameEncoder() {\n stream.Transform.call(this, { writableObjectMode: true });\n this.on(\"finish\", function() {\n this.push(null);\n });\n }\n util.inherits(FrameEncoder, stream.Transform);\n FrameEncoder.prototype._transform = function(obj, encoding, cb) {\n var bufs = obj.payload;\n var i, l, buf;\n for (i = 0, l = bufs.length; i < l; i++) {\n buf = bufs[i];\n this.push(intBuffer(buf.length));\n this.push(buf);\n }\n this.push(intBuffer(0));\n cb();\n };\n function NettyDecoder() {\n stream.Transform.call(this, { readableObjectMode: true });\n this._id = void 0;\n this._frameCount = 0;\n this._buf = utils.newBuffer(0);\n this._bufs = [];\n this.on(\"finish\", function() {\n this.push(null);\n });\n }\n util.inherits(NettyDecoder, stream.Transform);\n NettyDecoder.prototype._transform = function(buf, encoding, cb) {\n buf = Buffer2.concat([this._buf, buf]);\n while (true) {\n if (this._id === void 0) {\n if (buf.length < 8) {\n this._buf = buf;\n cb();\n return;\n }\n this._id = buf.readInt32BE(0);\n this._frameCount = buf.readInt32BE(4);\n buf = buf.slice(8);\n }\n var frameLength;\n while (this._frameCount && buf.length >= 4 && buf.length >= (frameLength = buf.readInt32BE(0)) + 4) {\n this._frameCount--;\n this._bufs.push(buf.slice(4, frameLength + 4));\n buf = buf.slice(frameLength + 4);\n }\n if (this._frameCount) {\n this._buf = buf;\n cb();\n return;\n } else {\n var obj = { id: this._id, payload: this._bufs };\n this._bufs = [];\n this._id = void 0;\n this.push(obj);\n }\n }\n };\n NettyDecoder.prototype._flush = FrameDecoder.prototype._flush;\n function NettyEncoder() {\n stream.Transform.call(this, { writableObjectMode: true });\n this.on(\"finish\", function() {\n this.push(null);\n });\n }\n util.inherits(NettyEncoder, stream.Transform);\n NettyEncoder.prototype._transform = function(obj, encoding, cb) {\n var bufs = obj.payload;\n var l = bufs.length;\n var buf;\n buf = utils.newBuffer(8);\n buf.writeInt32BE(obj.id, 0);\n buf.writeInt32BE(l, 4);\n this.push(buf);\n var i;\n for (i = 0; i < l; i++) {\n buf = bufs[i];\n this.push(intBuffer(buf.length));\n this.push(buf);\n }\n cb();\n };\n function intBuffer(n) {\n var buf = utils.newBuffer(4);\n buf.writeInt32BE(n);\n return buf;\n }\n function readHead(type, buf) {\n var tap = new Tap(buf);\n var head = type._read(tap);\n if (!tap.isValid()) {\n throw new Error(f2(\"truncated %j\", type.schema()));\n }\n return { head, tail: tap.buf.slice(tap.pos) };\n }\n function createReader(rtype, wtype) {\n return rtype.equals(wtype) ? rtype : rtype.createResolver(wtype);\n }\n function createReaders(clientSvc, serverSvc) {\n var obj = {};\n clientSvc.messages.forEach(function(c) {\n var n = c.name;\n var s = serverSvc.message(n);\n try {\n if (!s) {\n throw new Error(f2(\"missing server message: %s\", n));\n }\n if (s.oneWay !== c.oneWay) {\n throw new Error(f2(\"inconsistent one-way message: %s\", n));\n }\n obj[n + \"?\"] = createReader(s.requestType, c.requestType);\n obj[n + \"*\"] = createReader(c.errorType, s.errorType);\n obj[n + \"!\"] = createReader(c.responseType, s.responseType);\n } catch (cause) {\n throw toRpcError(\"INCOMPATIBLE_PROTOCOL\", cause);\n }\n });\n return obj;\n }\n function insertRemoteProtocols(cache, ptcls, svc, isClient) {\n Object.keys(ptcls).forEach(function(hash) {\n var ptcl = ptcls[hash];\n var clientSvc, serverSvc;\n if (isClient) {\n clientSvc = svc;\n serverSvc = Service.forProtocol(ptcl);\n } else {\n clientSvc = Service.forProtocol(ptcl);\n serverSvc = svc;\n }\n cache[hash] = new Adapter(clientSvc, serverSvc, hash, true);\n });\n }\n function getRemoteProtocols(cache, isClient) {\n var ptcls = {};\n Object.keys(cache).forEach(function(hs) {\n var adapter = cache[hs];\n if (adapter._isRemote) {\n var svc = isClient ? adapter._serverSvc : adapter._clientSvc;\n ptcls[hs] = svc.protocol;\n }\n });\n return ptcls;\n }\n function isError(any) {\n return !!any && Object.prototype.toString.call(any) === \"[object Error]\";\n }\n function forwardErrors(src, dst) {\n return src.on(\"error\", function(err) {\n dst.emit(\"error\", err, src);\n });\n }\n function toError(msg, cause) {\n var err = new Error(msg);\n err.cause = cause;\n return err;\n }\n function toRpcError(rpcCode, cause) {\n var err = toError(rpcCode.toLowerCase().replace(/_/g, \" \"), cause);\n err.rpcCode = cause && cause.rpcCode ? cause.rpcCode : rpcCode;\n return err;\n }\n function serializationError(msg, obj, fields) {\n var details = [];\n var i, l, field;\n for (i = 0, l = fields.length; i < l; i++) {\n field = fields[i];\n field.type.isValid(obj[field.name], { errorHook });\n }\n var detailsStr = details.map(function(obj2) {\n return f2(\"%s = %j but expected %s\", obj2.path, obj2.value, obj2.type);\n }).join(\", \");\n var err = new Error(f2(\"%s (%s)\", msg, detailsStr));\n err.details = details;\n return err;\n function errorHook(parts, any, type) {\n var strs = [];\n var i2, l2, part;\n for (i2 = 0, l2 = parts.length; i2 < l2; i2++) {\n part = parts[i2];\n if (isNaN(part)) {\n strs.push(\".\" + part);\n } else {\n strs.push(\"[\" + part + \"]\");\n }\n }\n details.push({\n path: field.name + strs.join(\"\"),\n value: any,\n type\n });\n }\n }\n function normalizedPrefix(scope) {\n return scope ? utils.getHash(scope).readInt16BE(0) << 32 - PREFIX_LENGTH : 0;\n }\n function matchesPrefix(id, prefix) {\n return (id ^ prefix) >> 32 - PREFIX_LENGTH === 0;\n }\n function isStream(any) {\n return !!(any && any.pipe);\n }\n function getExistingMessage(svc, name) {\n var msg = svc.message(name);\n if (!msg) {\n throw new Error(f2(\"unknown message: %s\", name));\n }\n return msg;\n }\n function chainMiddleware(params) {\n var args = [params.wreq, params.wres];\n var cbs = [];\n var cause;\n forward(0);\n function forward(pos) {\n var isDone = false;\n if (pos < params.fns.length) {\n params.fns[pos].apply(params.ctx, args.concat(function(err, cb) {\n if (isDone) {\n params.onError(toError(\"duplicate forward middleware call\", err));\n return;\n }\n isDone = true;\n if (err || params.wres && // Non one-way messages.\n (params.wres.error !== void 0 || params.wres.response !== void 0)) {\n cause = err;\n backward();\n return;\n }\n if (cb) {\n cbs.push(cb);\n }\n forward(++pos);\n }));\n } else {\n params.onTransition.apply(params.ctx, args.concat(function(err) {\n if (isDone) {\n params.onError(toError(\"duplicate handler call\", err));\n return;\n }\n isDone = true;\n cause = err;\n process.nextTick(backward);\n }));\n }\n }\n function backward() {\n var cb = cbs.pop();\n if (cb) {\n var isDone = false;\n cb.call(params.ctx, cause, function(err) {\n if (isDone) {\n params.onError(toError(\"duplicate backward middleware call\", err));\n return;\n }\n cause = err;\n isDone = true;\n backward();\n });\n } else {\n params.onCompletion.call(params.ctx, cause);\n }\n }\n }\n module.exports = {\n Adapter,\n HANDSHAKE_REQUEST_TYPE,\n HANDSHAKE_RESPONSE_TYPE,\n Message,\n Registry,\n Service,\n discoverProtocol,\n streams: {\n FrameDecoder,\n FrameEncoder,\n NettyDecoder,\n NettyEncoder\n }\n };\n }\n});\n\n// node_modules/avsc/lib/files.js\nvar require_files = __commonJS({\n \"node_modules/avsc/lib/files.js\"(exports, module) {\n \"use strict\";\n var fs = __import_FS;\n var path = __import_PATH;\n function createImportHook() {\n var imports = {};\n return function(fpath, kind, cb) {\n fpath = path.resolve(fpath);\n if (imports[fpath]) {\n process.nextTick(cb);\n return;\n }\n imports[fpath] = true;\n fs.readFile(fpath, { encoding: \"utf8\" }, cb);\n };\n }\n function createSyncImportHook() {\n var imports = {};\n return function(fpath, kind, cb) {\n fpath = path.resolve(fpath);\n if (imports[fpath]) {\n cb();\n } else {\n imports[fpath] = true;\n cb(null, fs.readFileSync(fpath, { encoding: \"utf8\" }));\n }\n };\n }\n module.exports = {\n createImportHook,\n createSyncImportHook,\n // Proxy a few methods to better shim them for browserify.\n existsSync: fs.existsSync,\n readFileSync: fs.readFileSync\n };\n }\n});\n\n// node_modules/avsc/lib/specs.js\nvar require_specs = __commonJS({\n \"node_modules/avsc/lib/specs.js\"(exports, module) {\n \"use strict\";\n var files = require_files();\n var utils = require_utils();\n var path = __import_PATH;\n var util = __import_UTIL;\n var f2 = util.format;\n var TYPE_REFS = {\n date: { type: \"int\", logicalType: \"date\" },\n decimal: { type: \"bytes\", logicalType: \"decimal\" },\n time_ms: { type: \"long\", logicalType: \"time-millis\" },\n timestamp_ms: { type: \"long\", logicalType: \"timestamp-millis\" }\n };\n function assembleProtocol(fpath, opts, cb) {\n if (!cb && typeof opts == \"function\") {\n cb = opts;\n opts = void 0;\n }\n opts = opts || {};\n if (!opts.importHook) {\n opts.importHook = files.createImportHook();\n }\n importFile(fpath, function(err, protocol) {\n if (err) {\n cb(err);\n return;\n }\n if (!protocol) {\n cb(new Error(\"empty root import\"));\n return;\n }\n var schemas = protocol.types;\n if (schemas) {\n var namespace = protocolNamespace(protocol) || \"\";\n schemas.forEach(function(schema) {\n if (schema.namespace === namespace) {\n delete schema.namespace;\n }\n });\n }\n cb(null, protocol);\n });\n function importFile(fpath2, cb2) {\n opts.importHook(fpath2, \"idl\", function(err, str) {\n if (err) {\n cb2(err);\n return;\n }\n if (str === void 0) {\n cb2();\n return;\n }\n try {\n var reader = new Reader(str, opts);\n var obj = reader._readProtocol(str, opts);\n } catch (err2) {\n err2.path = fpath2;\n cb2(err2);\n return;\n }\n fetchImports(obj.protocol, obj.imports, path.dirname(fpath2), cb2);\n });\n }\n function fetchImports(protocol, imports, dpath, cb2) {\n var importedProtocols = [];\n next();\n function next() {\n var info = imports.shift();\n if (!info) {\n importedProtocols.reverse();\n try {\n importedProtocols.forEach(function(imported) {\n mergeImport(protocol, imported);\n });\n } catch (err) {\n cb2(err);\n return;\n }\n cb2(null, protocol);\n return;\n }\n var importPath = path.join(dpath, info.name);\n if (info.kind === \"idl\") {\n importFile(importPath, function(err, imported) {\n if (err) {\n cb2(err);\n return;\n }\n if (imported) {\n importedProtocols.push(imported);\n }\n next();\n });\n } else {\n opts.importHook(importPath, info.kind, function(err, str) {\n if (err) {\n cb2(err);\n return;\n }\n switch (info.kind) {\n case \"protocol\":\n case \"schema\":\n if (str === void 0) {\n next();\n return;\n }\n try {\n var obj = JSON.parse(str);\n } catch (err2) {\n err2.path = importPath;\n cb2(err2);\n return;\n }\n var imported = info.kind === \"schema\" ? { types: [obj] } : obj;\n importedProtocols.push(imported);\n next();\n return;\n default:\n cb2(new Error(f2(\"invalid import kind: %s\", info.kind)));\n }\n });\n }\n }\n }\n function mergeImport(protocol, imported) {\n var schemas = imported.types || [];\n schemas.reverse();\n schemas.forEach(function(schema) {\n if (!protocol.types) {\n protocol.types = [];\n }\n if (schema.namespace === void 0) {\n schema.namespace = protocolNamespace(imported) || \"\";\n }\n protocol.types.unshift(schema);\n });\n Object.keys(imported.messages || {}).forEach(function(name) {\n if (!protocol.messages) {\n protocol.messages = {};\n }\n if (protocol.messages[name]) {\n throw new Error(f2(\"duplicate message: %s\", name));\n }\n protocol.messages[name] = imported.messages[name];\n });\n }\n }\n function read(str) {\n var schema;\n if (typeof str == \"string\" && ~str.indexOf(path.sep) && files.existsSync(str)) {\n var contents = files.readFileSync(str, { encoding: \"utf8\" });\n try {\n return JSON.parse(contents);\n } catch (err) {\n var opts = { importHook: files.createSyncImportHook() };\n assembleProtocol(str, opts, function(err2, protocolSchema) {\n schema = err2 ? contents : protocolSchema;\n });\n }\n } else {\n schema = str;\n }\n if (typeof schema != \"string\" || schema === \"null\") {\n return schema;\n }\n try {\n return JSON.parse(schema);\n } catch (err) {\n try {\n return Reader.readProtocol(schema);\n } catch (err2) {\n try {\n return Reader.readSchema(schema);\n } catch (err3) {\n return schema;\n }\n }\n }\n }\n function Reader(str, opts) {\n opts = opts || {};\n this._tk = new Tokenizer(str);\n this._ackVoidMessages = !!opts.ackVoidMessages;\n this._implicitTags = !opts.delimitedCollections;\n this._typeRefs = opts.typeRefs || TYPE_REFS;\n }\n Reader.readProtocol = function(str, opts) {\n var reader = new Reader(str, opts);\n var protocol = reader._readProtocol();\n if (protocol.imports.length) {\n throw new Error(\"unresolvable import\");\n }\n return protocol.protocol;\n };\n Reader.readSchema = function(str, opts) {\n var reader = new Reader(str, opts);\n var doc = reader._readJavadoc();\n var schema = reader._readType(doc === void 0 ? {} : { doc }, true);\n reader._tk.next({ id: \"(eof)\" });\n return schema;\n };\n Reader.prototype._readProtocol = function() {\n var tk = this._tk;\n var imports = [];\n var types = [];\n var messages = {};\n var pos;\n this._readImports(imports);\n var protocolSchema = {};\n var protocolJavadoc = this._readJavadoc();\n if (protocolJavadoc !== void 0) {\n protocolSchema.doc = protocolJavadoc;\n }\n this._readAnnotations(protocolSchema);\n tk.next({ val: \"protocol\" });\n if (!tk.next({ val: \"{\", silent: true })) {\n protocolSchema.protocol = tk.next({ id: \"name\" }).val;\n tk.next({ val: \"{\" });\n }\n while (!tk.next({ val: \"}\", silent: true })) {\n if (!this._readImports(imports)) {\n var javadoc = this._readJavadoc();\n var typeSchema = this._readType({}, true);\n var numImports = this._readImports(imports, true);\n var message = void 0;\n pos = tk.pos;\n if (!numImports && (message = this._readMessage(typeSchema))) {\n if (javadoc !== void 0 && message.schema.doc === void 0) {\n message.schema.doc = javadoc;\n }\n var oneWay = false;\n if (message.schema.response === \"void\" || message.schema.response.type === \"void\") {\n oneWay = !this._ackVoidMessages && !message.schema.errors;\n if (message.schema.response === \"void\") {\n message.schema.response = \"null\";\n } else {\n message.schema.response.type = \"null\";\n }\n }\n if (oneWay) {\n message.schema[\"one-way\"] = true;\n }\n if (messages[message.name]) {\n throw new Error(f2(\"duplicate message: %s\", message.name));\n }\n messages[message.name] = message.schema;\n } else {\n if (javadoc) {\n if (typeof typeSchema == \"string\") {\n typeSchema = { doc: javadoc, type: typeSchema };\n } else if (typeSchema.doc === void 0) {\n typeSchema.doc = javadoc;\n }\n }\n types.push(typeSchema);\n tk.pos = pos;\n tk.next({ val: \";\", silent: true });\n }\n javadoc = void 0;\n }\n }\n tk.next({ id: \"(eof)\" });\n if (types.length) {\n protocolSchema.types = types;\n }\n if (Object.keys(messages).length) {\n protocolSchema.messages = messages;\n }\n return { protocol: protocolSchema, imports };\n };\n Reader.prototype._readAnnotations = function(schema) {\n var tk = this._tk;\n while (tk.next({ val: \"@\", silent: true })) {\n var parts = [];\n while (!tk.next({ val: \"(\", silent: true })) {\n parts.push(tk.next().val);\n }\n schema[parts.join(\"\")] = tk.next({ id: \"json\" }).val;\n tk.next({ val: \")\" });\n }\n };\n Reader.prototype._readMessage = function(responseSchema) {\n var tk = this._tk;\n var schema = { request: [], response: responseSchema };\n this._readAnnotations(schema);\n var name = tk.next().val;\n if (tk.next().val !== \"(\") {\n return;\n }\n if (!tk.next({ val: \")\", silent: true })) {\n do {\n schema.request.push(this._readField());\n } while (!tk.next({ val: \")\", silent: true }) && tk.next({ val: \",\" }));\n }\n var token = tk.next();\n switch (token.val) {\n case \"throws\":\n schema.errors = [];\n do {\n schema.errors.push(this._readType());\n } while (!tk.next({ val: \";\", silent: true }) && tk.next({ val: \",\" }));\n break;\n case \"oneway\":\n schema[\"one-way\"] = true;\n tk.next({ val: \";\" });\n break;\n case \";\":\n break;\n default:\n throw tk.error(\"invalid message suffix\", token);\n }\n return { name, schema };\n };\n Reader.prototype._readJavadoc = function() {\n var token = this._tk.next({ id: \"javadoc\", emitJavadoc: true, silent: true });\n if (token) {\n return token.val;\n }\n };\n Reader.prototype._readField = function() {\n var tk = this._tk;\n var javadoc = this._readJavadoc();\n var schema = { type: this._readType() };\n if (javadoc !== void 0 && schema.doc === void 0) {\n schema.doc = javadoc;\n }\n this._readAnnotations(schema);\n schema.name = tk.next({ id: \"name\" }).val;\n if (tk.next({ val: \"=\", silent: true })) {\n schema[\"default\"] = tk.next({ id: \"json\" }).val;\n }\n return schema;\n };\n Reader.prototype._readType = function(schema, top) {\n schema = schema || {};\n this._readAnnotations(schema);\n schema.type = this._tk.next({ id: \"name\" }).val;\n switch (schema.type) {\n case \"record\":\n case \"error\":\n return this._readRecord(schema);\n case \"fixed\":\n return this._readFixed(schema);\n case \"enum\":\n return this._readEnum(schema, top);\n case \"map\":\n return this._readMap(schema);\n case \"array\":\n return this._readArray(schema);\n case \"union\":\n if (Object.keys(schema).length > 1) {\n throw new Error(\"union annotations are not supported\");\n }\n return this._readUnion();\n default:\n var ref = this._typeRefs[schema.type];\n if (ref) {\n delete schema.type;\n utils.copyOwnProperties(ref, schema);\n }\n return Object.keys(schema).length > 1 ? schema : schema.type;\n }\n };\n Reader.prototype._readFixed = function(schema) {\n var tk = this._tk;\n if (!tk.next({ val: \"(\", silent: true })) {\n schema.name = tk.next({ id: \"name\" }).val;\n tk.next({ val: \"(\" });\n }\n schema.size = parseInt(tk.next({ id: \"number\" }).val);\n tk.next({ val: \")\" });\n return schema;\n };\n Reader.prototype._readMap = function(schema) {\n var tk = this._tk;\n var silent = this._implicitTags;\n var implicitTags = tk.next({ val: \"<\", silent }) === void 0;\n schema.values = this._readType();\n tk.next({ val: \">\", silent: implicitTags });\n return schema;\n };\n Reader.prototype._readArray = function(schema) {\n var tk = this._tk;\n var silent = this._implicitTags;\n var implicitTags = tk.next({ val: \"<\", silent }) === void 0;\n schema.items = this._readType();\n tk.next({ val: \">\", silent: implicitTags });\n return schema;\n };\n Reader.prototype._readEnum = function(schema, top) {\n var tk = this._tk;\n if (!tk.next({ val: \"{\", silent: true })) {\n schema.name = tk.next({ id: \"name\" }).val;\n tk.next({ val: \"{\" });\n }\n schema.symbols = [];\n do {\n schema.symbols.push(tk.next().val);\n } while (!tk.next({ val: \"}\", silent: true }) && tk.next({ val: \",\" }));\n if (top && tk.next({ val: \"=\", silent: true })) {\n schema.default = tk.next().val;\n tk.next({ val: \";\" });\n }\n return schema;\n };\n Reader.prototype._readUnion = function() {\n var tk = this._tk;\n var arr = [];\n tk.next({ val: \"{\" });\n do {\n arr.push(this._readType());\n } while (!tk.next({ val: \"}\", silent: true }) && tk.next({ val: \",\" }));\n return arr;\n };\n Reader.prototype._readRecord = function(schema) {\n var tk = this._tk;\n if (!tk.next({ val: \"{\", silent: true })) {\n schema.name = tk.next({ id: \"name\" }).val;\n tk.next({ val: \"{\" });\n }\n schema.fields = [];\n while (!tk.next({ val: \"}\", silent: true })) {\n schema.fields.push(this._readField());\n tk.next({ val: \";\" });\n }\n return schema;\n };\n Reader.prototype._readImports = function(imports, maybeMessage) {\n var tk = this._tk;\n var numImports = 0;\n var pos = tk.pos;\n while (tk.next({ val: \"import\", silent: true })) {\n if (!numImports && maybeMessage && tk.next({ val: \"(\", silent: true })) {\n tk.pos = pos;\n return;\n }\n var kind = tk.next({ id: \"name\" }).val;\n var fname = JSON.parse(tk.next({ id: \"string\" }).val);\n tk.next({ val: \";\" });\n imports.push({ kind, name: fname });\n numImports++;\n }\n return numImports;\n };\n function Tokenizer(str) {\n this._str = str;\n this.pos = 0;\n }\n Tokenizer.prototype.next = function(opts) {\n var token = { pos: this.pos, id: void 0, val: void 0 };\n var javadoc = this._skip(opts && opts.emitJavadoc);\n if (typeof javadoc == \"string\") {\n token.id = \"javadoc\";\n token.val = javadoc;\n } else {\n var pos = this.pos;\n var str = this._str;\n var c = str.charAt(pos);\n if (!c) {\n token.id = \"(eof)\";\n } else {\n if (opts && opts.id === \"json\") {\n token.id = \"json\";\n this.pos = this._endOfJson();\n } else if (c === '\"') {\n token.id = \"string\";\n this.pos = this._endOfString();\n } else if (/[0-9]/.test(c)) {\n token.id = \"number\";\n this.pos = this._endOf(/[0-9]/);\n } else if (/[`A-Za-z_.]/.test(c)) {\n token.id = \"name\";\n this.pos = this._endOf(/[`A-Za-z0-9_.]/);\n } else {\n token.id = \"operator\";\n this.pos = pos + 1;\n }\n token.val = str.slice(pos, this.pos);\n if (token.id === \"json\") {\n try {\n token.val = JSON.parse(token.val);\n } catch (err2) {\n throw this.error(\"invalid JSON\", token);\n }\n } else if (token.id === \"name\") {\n token.val = token.val.replace(/`/g, \"\");\n }\n }\n }\n var err;\n if (opts && opts.id && opts.id !== token.id) {\n err = this.error(f2(\"expected ID %s\", opts.id), token);\n } else if (opts && opts.val && opts.val !== token.val) {\n err = this.error(f2(\"expected value %s\", opts.val), token);\n }\n if (!err) {\n return token;\n } else if (opts && opts.silent) {\n this.pos = token.pos;\n return void 0;\n } else {\n throw err;\n }\n };\n Tokenizer.prototype.error = function(reason, context) {\n var isToken = typeof context != \"number\";\n var pos = isToken ? context.pos : context;\n var str = this._str;\n var lineNum = 1;\n var lineStart = 0;\n var i;\n for (i = 0; i < pos; i++) {\n if (str.charAt(i) === \"\\n\") {\n lineNum++;\n lineStart = i;\n }\n }\n var msg = isToken ? f2(\"invalid token %j: %s\", context, reason) : reason;\n var err = new Error(msg);\n err.token = isToken ? context : void 0;\n err.lineNum = lineNum;\n err.colNum = pos - lineStart;\n return err;\n };\n Tokenizer.prototype._skip = function(emitJavadoc) {\n var str = this._str;\n var isJavadoc = false;\n var pos, c;\n while ((c = str.charAt(this.pos)) && /\\s/.test(c)) {\n this.pos++;\n }\n pos = this.pos;\n if (c === \"/\") {\n switch (str.charAt(this.pos + 1)) {\n case \"/\":\n this.pos += 2;\n while ((c = str.charAt(this.pos)) && c !== \"\\n\") {\n this.pos++;\n }\n return this._skip(emitJavadoc);\n case \"*\":\n this.pos += 2;\n if (str.charAt(this.pos) === \"*\") {\n isJavadoc = true;\n }\n while (c = str.charAt(this.pos++)) {\n if (c === \"*\" && str.charAt(this.pos) === \"/\") {\n this.pos++;\n if (isJavadoc && emitJavadoc) {\n return extractJavadoc(str.slice(pos + 3, this.pos - 2));\n }\n return this._skip(emitJavadoc);\n }\n }\n throw this.error(\"unterminated comment\", pos);\n }\n }\n };\n Tokenizer.prototype._endOf = function(pat) {\n var pos = this.pos;\n var str = this._str;\n while (pat.test(str.charAt(pos))) {\n pos++;\n }\n return pos;\n };\n Tokenizer.prototype._endOfString = function() {\n var pos = this.pos + 1;\n var str = this._str;\n var c;\n while (c = str.charAt(pos)) {\n if (c === '\"') {\n return pos + 1;\n }\n if (c === \"\\\\\") {\n pos += 2;\n } else {\n pos++;\n }\n }\n throw this.error(\"unterminated string\", pos - 1);\n };\n Tokenizer.prototype._endOfJson = function() {\n var pos = utils.jsonEnd(this._str, this.pos);\n if (pos < 0) {\n throw this.error(\"invalid JSON\", pos);\n }\n return pos;\n };\n function extractJavadoc(str) {\n var lines = str.replace(/^[ \\t]+|[ \\t]+$/g, \"\").split(\"\\n\").map(function(line, i) {\n return i ? line.replace(/^\\s*\\*\\s?/, \"\") : line;\n });\n while (lines.length && !lines[0]) {\n lines.shift();\n }\n while (lines.length && !lines[lines.length - 1]) {\n lines.pop();\n }\n return lines.join(\"\\n\");\n }\n function protocolNamespace(protocol) {\n if (protocol.namespace) {\n return protocol.namespace;\n }\n var match = /^(.*)\\.[^.]+$/.exec(protocol.protocol);\n return match ? match[1] : void 0;\n }\n module.exports = {\n Tokenizer,\n assembleProtocol,\n read,\n readProtocol: Reader.readProtocol,\n readSchema: Reader.readSchema\n };\n }\n});\n\n// node_modules/avsc/lib/index.js\nvar require_lib = __commonJS({\n \"node_modules/avsc/lib/index.js\"(exports, module) {\n \"use strict\";\n var containers = require_containers();\n var services = require_services();\n var specs = require_specs();\n var types = require_types();\n var utils = require_utils();\n var buffer = __import_BUFFER;\n var fs = __import_FS;\n var util = __import_UTIL;\n var Buffer2 = buffer.Buffer;\n function parse2(any, opts) {\n var schemaOrProtocol = specs.read(any);\n return schemaOrProtocol.protocol ? services.Service.forProtocol(schemaOrProtocol, opts) : types.Type.forSchema(schemaOrProtocol, opts);\n }\n function extractFileHeader(path, opts) {\n opts = opts || {};\n var decode = opts.decode === void 0 ? true : !!opts.decode;\n var size = Math.max(opts.size || 4096, 4);\n var buf = utils.newBuffer(size);\n var fd = fs.openSync(path, \"r\");\n try {\n var pos = fs.readSync(fd, buf, 0, size);\n if (pos < 4 || !containers.MAGIC_BYTES.equals(buf.slice(0, 4))) {\n return null;\n }\n var tap = new utils.Tap(buf);\n var header = null;\n do {\n header = containers.HEADER_TYPE._read(tap);\n } while (!isValid());\n if (decode !== false) {\n var meta = header.meta;\n meta[\"avro.schema\"] = JSON.parse(meta[\"avro.schema\"].toString());\n if (meta[\"avro.codec\"] !== void 0) {\n meta[\"avro.codec\"] = meta[\"avro.codec\"].toString();\n }\n }\n return header;\n } finally {\n fs.closeSync(fd);\n }\n function isValid() {\n if (tap.isValid()) {\n return true;\n }\n var len = 2 * tap.buf.length;\n var buf2 = utils.newBuffer(len);\n len = fs.readSync(fd, buf2, 0, len);\n tap.buf = Buffer2.concat([tap.buf, buf2]);\n tap.pos = 0;\n return false;\n }\n }\n function createFileDecoder(path, opts) {\n return fs.createReadStream(path).pipe(new containers.streams.BlockDecoder(opts));\n }\n function createFileEncoder(path, schema, opts) {\n var encoder = new containers.streams.BlockEncoder(schema, opts);\n encoder.pipe(fs.createWriteStream(path, { defaultEncoding: \"binary\" }));\n return encoder;\n }\n module.exports = {\n Service: services.Service,\n Type: types.Type,\n assembleProtocol: specs.assembleProtocol,\n createFileDecoder,\n createFileEncoder,\n discoverProtocol: services.discoverProtocol,\n extractFileHeader,\n parse: parse2,\n readProtocol: specs.readProtocol,\n readSchema: specs.readSchema,\n streams: containers.streams,\n types: types.builtins,\n // Deprecated exports.\n Protocol: services.Service,\n assemble: util.deprecate(\n specs.assembleProtocol,\n \"use `assembleProtocol` instead\"\n ),\n combine: util.deprecate(\n types.Type.forTypes,\n \"use `Type.forTypes` intead\"\n ),\n infer: util.deprecate(\n types.Type.forValue,\n \"use `Type.forValue` instead\"\n )\n };\n }\n});\n\n// node_modules/ultralight-s3/lib/index.min.js\nvar N = \"AWS4-HMAC-SHA256\";\nvar K = \"aws4_request\";\nvar O = \"s3\";\nvar v = \"2\";\nvar f = \"UNSIGNED-PAYLOAD\";\nvar W = \"application/octet-stream\";\nvar q = \"application/xml\";\nvar w = \"application/json\";\nvar X = [\"accessKeyId\", \"secretAccessKey\", \"sessionToken\", \"password\"];\nvar E = \"x-amz-content-sha256\";\nvar Z = \"x-amz-date\";\nvar V = \"host\";\nvar J = \"Authorization\";\nvar m = \"Content-Type\";\nvar R = \"Content-Length\";\nvar P = \"etag\";\nvar M = \"last-modified\";\nvar u = \"ultralight-s3 Module: \";\nvar ee = `${u}accessKeyId must be a non-empty string`;\nvar te = `${u}secretAccessKey must be a non-empty string`;\nvar se = `${u}endpoint must be a non-empty string`;\nvar re = `${u}bucketName must be a non-empty string`;\nvar L = `${u}key must be a non-empty string`;\nvar $ = `${u}uploadId must be a non-empty string`;\nvar j = `${u}parts must be a non-empty array`;\nvar k = `${u}Each part must have a partNumber (number) and ETag (string)`;\nvar U = `${u}data must be a Buffer or string`;\nvar B = `${u}prefix must be a string`;\nvar F = `${u}maxKeys must be a positive integer`;\nvar G = `${u}delimiter must be a string`;\nvar z = crypto.createHmac || (await import(\"node:crypto\")).createHmac;\nvar Q = crypto.createHash || (await import(\"node:crypto\")).createHash;\ntypeof z > \"u\" && typeof Q > \"u\" && console.error(\"ultralight-S3 Module: Crypto functions are not available, please report the issue with necessary description: https://github.com/sentienhq/ultralight-s3/issues\");\nvar ne = { contents: true };\nvar oe = (p) => `%${p.charCodeAt(0).toString(16).toUpperCase()}`;\nvar C = (p) => encodeURIComponent(p).replace(/[!'()*]/g, oe);\nvar y = (p) => C(p).replace(/%2F/g, \"/\");\nvar x = class {\n constructor({ accessKeyId: e, secretAccessKey: t, endpoint: r, bucketName: n, region: o = \"auto\", maxRequestSizeInBytes: i = 5242880, requestAbortTimeout: a = void 0, logger: c = void 0 }) {\n this.getBucketName = () => this.bucketName, this.setBucketName = (s) => {\n this.bucketName = s;\n }, this.getRegion = () => this.region, this.setRegion = (s) => {\n this.region = s;\n }, this.getEndpoint = () => this.endpoint, this.setEndpoint = (s) => {\n this.endpoint = s;\n }, this.getMaxRequestSizeInBytes = () => this.maxRequestSizeInBytes, this.setMaxRequestSizeInBytes = (s) => {\n this.maxRequestSizeInBytes = s;\n }, this.sanitizeETag = (s) => I(s), this.getProps = () => ({ accessKeyId: this.accessKeyId, secretAccessKey: this.secretAccessKey, region: this.region, bucket: this.bucketName, endpoint: this.endpoint, maxRequestSizeInBytes: this.maxRequestSizeInBytes, requestAbortTimeout: this.requestAbortTimeout, logger: this.logger }), this.setProps = (s) => {\n this._validateConstructorParams(s.accessKeyId, s.secretAccessKey, s.bucketName, s.endpoint), this.accessKeyId = s.accessKeyId, this.secretAccessKey = s.secretAccessKey, this.region = s.region || \"auto\", this.bucketName = s.bucketName, this.endpoint = s.endpoint, this.maxRequestSizeInBytes = s.maxRequestSizeInBytes || 5242880, this.requestAbortTimeout = s.requestAbortTimeout, this.logger = s.logger;\n }, this._validateConstructorParams(e, t, r, n), this.accessKeyId = e, this.secretAccessKey = t, this.endpoint = r, this.bucketName = n, this.region = o, this.maxRequestSizeInBytes = i, this.requestAbortTimeout = a, this.logger = c;\n }\n _validateConstructorParams(e, t, r, n) {\n if (typeof e != \"string\" || e.trim().length === 0) throw new TypeError(ee);\n if (typeof t != \"string\" || t.trim().length === 0) throw new TypeError(te);\n if (typeof r != \"string\" || r.trim().length === 0) throw new TypeError(se);\n if (typeof n != \"string\" || n.trim().length === 0) throw new TypeError(re);\n }\n _checkMethodHeadnGet(e) {\n if (e !== \"GET\" && e !== \"HEAD\") throw this._log(\"error\", `${u}method must be either GET or HEAD`), new Error(\"method must be either GET or HEAD\");\n }\n _checkKey(e) {\n if (typeof e != \"string\" || e.trim().length === 0) throw this._log(\"error\", L), new TypeError(L);\n }\n _checkDelimiter(e) {\n if (typeof e != \"string\" || e.trim().length === 0) throw this._log(\"error\", G), new TypeError(G);\n }\n _checkPrefix(e) {\n if (typeof e != \"string\") throw this._log(\"error\", B), new TypeError(B);\n }\n _checkMaxKeys(e) {\n if (typeof e != \"number\" || e <= 0) throw this._log(\"error\", F), new TypeError(F);\n }\n _checkOpts(e) {\n if (typeof e != \"object\") throw this._log(\"error\", `${u}opts must be an object`), new TypeError(`${u}opts must be an object`);\n }\n _log(e, t, r = {}) {\n if (this.logger && typeof this.logger[e] == \"function\") {\n let n = (a) => typeof a != \"object\" || a === null ? a : Object.keys(a).reduce((c, s) => (X.includes(s.toLowerCase()) ? c[s] = \"[REDACTED]\" : typeof a[s] == \"object\" && a[s] !== null ? c[s] = n(a[s]) : c[s] = a[s], c), Array.isArray(a) ? [] : {}), o = n(r), i = { timestamp: (/* @__PURE__ */ new Date()).toISOString(), level: e, message: t, ...o, context: n({ bucketName: this.bucketName, region: this.region, endpoint: this.endpoint, accessKeyId: this.accessKeyId ? `${this.accessKeyId.substring(0, 4)}...` : void 0 }) };\n this.logger[e](i);\n }\n }\n async getContentLength(e) {\n this._checkKey(e);\n let t = { [E]: f }, r = y(e), { url: n, headers: o } = await this._sign(\"HEAD\", r, {}, t, \"\"), a = (await this._sendRequest(n, \"HEAD\", o)).headers.get(R);\n return a ? parseInt(a, 10) : 0;\n }\n async bucketExists() {\n let e = { [E]: f }, { url: t, headers: r } = await this._sign(\"HEAD\", \"\", {}, e, \"\"), n = await this._sendRequest(t, \"HEAD\", r, \"\", [200, 404, 403]);\n return this._log(\"error\", `Response status: ${n.status, n.statusText}`), !!(n.ok && n.status === 200);\n }\n async createBucket() {\n let e = `\n \n ${this.region}\n \n `, t = { [m]: q, [R]: Buffer.byteLength(e).toString(), [E]: await A(e) }, r = encodeURI(\"\"), { url: n, headers: o } = await this._sign(\"PUT\", r, {}, t, \"\"), i = await this._sendRequest(n, \"PUT\", o, e, [200, 404, 403]);\n return !!(i.ok && i.status === 200);\n }\n async fileExists(e, t = {}) {\n this._checkKey(e);\n let { filteredOpts: r, conditionalHeaders: n } = this._filterIfHeaders(t), o = { [E]: f, ...n }, i = y(e), { url: a, headers: c } = await this._sign(\"HEAD\", i, r, o, \"\");\n try {\n let s = await this._sendRequest(a, \"HEAD\", c, \"\", [200, 404, 412, 304]);\n return s.status === 404 ? false : s.status === 412 || s.status === 304 ? null : s.ok && s.status === 200 ? true : (this._handleErrorResponse(s), false);\n } catch (s) {\n let l = s instanceof Error ? s.message : String(s);\n throw this._log(\"error\", `${u}Failed to check if file exists: ${l}`), new Error(`${u}Failed to check if file exists: ${l}`);\n }\n }\n async _sign(e, t, r = {}, n, o) {\n let i = (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\\.\\d{3}/g, \"\"), a = typeof t == \"string\" && t.length > 0 ? new URL(t, this.endpoint) : new URL(this.endpoint);\n a.pathname = `/${encodeURI(this.bucketName)}${a.pathname}`, n[E] = o ? await A(o) : f, n[Z] = i, n[V] = a.host;\n let c = this._buildCanonicalHeaders(n), s = Object.keys(n).map((_) => _.toLowerCase()).sort().join(\";\"), l = await this._buildCanonicalRequest(e, a, r, c, s, o), h = await this._buildStringToSign(i, l), d = await this._calculateSignature(i, h), g = this._buildAuthorizationHeader(i, s, d);\n return n[J] = g, { url: a.toString(), headers: n };\n }\n _buildCanonicalHeaders(e) {\n return Object.entries(e).map(([t, r]) => `${t.toLowerCase()}:${String(r).trim()}`).sort().join(`\n`);\n }\n async _buildCanonicalRequest(e, t, r, n, o, i) {\n return [e, t.pathname, this._buildCanonicalQueryString(r), `${n}\n`, o, i ? await A(i) : f].join(`\n`);\n }\n async _buildStringToSign(e, t) {\n let r = [e.slice(0, 8), this.region, O, K].join(\"/\");\n return [N, e, r, await A(t)].join(`\n`);\n }\n async _calculateSignature(e, t) {\n let r = await this._getSignatureKey(e.slice(0, 8));\n return H(r, t, \"hex\");\n }\n _buildAuthorizationHeader(e, t, r) {\n let n = [e.slice(0, 8), this.region, O, K].join(\"/\");\n return [`${N} Credential=${this.accessKeyId}/${n}`, `SignedHeaders=${t}`, `Signature=${r}`].join(\", \");\n }\n _filterIfHeaders(e) {\n let t = {}, r = {}, n = [\"if-match\", \"if-none-match\", \"if-modified-since\", \"if-unmodified-since\"];\n for (let [o, i] of Object.entries(e)) n.includes(o) ? r[o] = i : t[o] = i;\n return { filteredOpts: t, conditionalHeaders: r };\n }\n async list(e = \"/\", t = \"\", r = 1e3, n = \"GET\", o = {}) {\n this._checkDelimiter(e), this._checkPrefix(t), this._checkMaxKeys(r), this._checkMethodHeadnGet(n), this._checkOpts(o), this._log(\"info\", `Listing objects in ${t}`);\n let i = { \"list-type\": v, \"max-keys\": String(r), ...o };\n t.length > 0 && (i.prefix = t);\n let a = { [m]: w, [E]: f }, c = e === \"/\" ? e : C(e), { url: s, headers: l } = await this._sign(\"GET\", c, i, a, \"\"), h = `${s}?${new URLSearchParams(i)}`, d = await this._sendRequest(h, \"GET\", l), g = await d.text();\n if (n === \"HEAD\") {\n let T = d.headers.get(R), S = d.headers.get(M), Y = d.headers.get(P);\n return { size: T ? +T : void 0, mtime: S ? new Date(S) : void 0, ETag: Y || void 0 };\n }\n let _ = b(g), D = _.listBucketResult || _.error || _;\n return D.contents || D;\n }\n async listMultiPartUploads(e = \"/\", t = \"\", r = \"GET\", n = {}) {\n var o, i, a;\n this._checkDelimiter(e), this._checkPrefix(t), this._checkMethodHeadnGet(r), this._checkOpts(n), this._log(\"info\", `Listing multipart uploads in ${t}`);\n let c = { uploads: \"\", ...n }, s = { [m]: w, [E]: f }, l = e === \"/\" ? e : C(e), { url: h, headers: d } = await this._sign(\"GET\", l, c, s, \"\"), g = `${h}?${new URLSearchParams(c)}`, _ = await this._sendRequest(g, \"GET\", d), D = await _.text();\n if (r === \"HEAD\") return { size: +((o = _.headers.get(R)) !== null && o !== void 0 ? o : \"0\"), mtime: new Date((i = _.headers.get(M)) !== null && i !== void 0 ? i : \"\"), ETag: (a = _.headers.get(P)) !== null && a !== void 0 ? a : \"\" };\n let T = b(D), S = T.listMultipartUploadsResult || T.error || T;\n return S.uploads || S;\n }\n async get(e, t = {}) {\n this._checkKey(e), this._log(\"info\", `Getting object ${e}`);\n let { filteredOpts: r, conditionalHeaders: n } = this._filterIfHeaders(t), o = { [m]: w, [E]: f, ...n }, i = y(e), { url: a, headers: c } = await this._sign(\"GET\", i, r, o, \"\"), s = await this._sendRequest(a, \"GET\", c, \"\", [200, 404, 412, 304]);\n if (s.status === 404 || s.status === 412 || s.status === 304) return this._log(\"error\", `Failed to get object. Status: ${s.status}`), null;\n if (!s.ok) throw this._log(\"error\", `Failed to get object. Status: ${s.status}`), new Error(`Failed to get object. Status: ${s.status}`);\n return s;\n }\n async getObjectWithETag(e, t = {}) {\n this._checkKey(e), this._log(\"info\", `Getting object ${e}`);\n let { filteredOpts: r, conditionalHeaders: n } = this._filterIfHeaders(t), o = { [m]: w, [E]: f, ...n }, i = y(e), { url: a, headers: c } = await this._sign(\"GET\", i, r, o, \"\");\n try {\n let s = await this._sendRequest(a, \"GET\", c, \"\", [200, 404, 412, 304]);\n if (s.status === 404 || s.status === 412 || s.status === 304) return this._log(\"error\", `Failed to get object. Status: ${s.status}`), { etag: null, data: null };\n if (!s.ok) throw this._log(\"error\", `Failed to get object. Status: ${s.status}`), new Error(`Failed to get object. Status: ${s.status}`);\n let l = s.headers.get(\"etag\");\n if (!l) throw new Error(\"ETag not found in response headers\");\n let h = await s.text();\n return { etag: I(l), data: h };\n } catch (s) {\n throw this._log(\"error\", `Error getting object ${e} with ETag: ${s}`), s;\n }\n }\n async getEtag(e, t = {}) {\n this._checkKey(e), this._log(\"info\", `Getting etag object ${e}`);\n let { filteredOpts: r, conditionalHeaders: n } = this._filterIfHeaders(t), o = { [m]: w, [E]: f, ...n }, i = y(e), { url: a, headers: c } = await this._sign(\"HEAD\", i, r, o, \"\"), s = await this._sendRequest(a, \"HEAD\", c, \"\", [200, 412, 304]);\n if (this._log(\"info\", `Response status: ${s.status, s.statusText}`), s.status === 412 || s.status === 304) return null;\n let l = s.headers.get(\"etag\");\n if (!l) throw this._log(\"error\", \"ETag not found in response headers\"), new Error(\"ETag not found in response headers\");\n return I(l);\n }\n async getResponse(e, t = true, r = 0, n = this.maxRequestSizeInBytes, o = {}) {\n this._checkKey(e);\n let { filteredOpts: i, conditionalHeaders: a } = this._filterIfHeaders({ ...o }), c = { [m]: w, [E]: f, ...t ? {} : { range: `bytes=${r}-${n - 1}` }, ...a }, s = y(e), { url: l, headers: h } = await this._sign(\"GET\", s, i, c, \"\"), d = `${l}?${new URLSearchParams(i)}`;\n return this._sendRequest(d, \"GET\", h);\n }\n async put(e, t) {\n if (this._checkKey(e), !(t instanceof Buffer || typeof t == \"string\")) throw this._log(\"error\", U), new TypeError(U);\n this._log(\"info\", `Uploading object ${e}`);\n let r = typeof t == \"string\" ? Buffer.byteLength(t) : t.length, n = { [R]: r }, o = y(e), { url: i, headers: a } = await this._sign(\"PUT\", o, {}, n, t);\n return this._sendRequest(i, \"PUT\", a, t, [200]);\n }\n async getMultipartUploadId(e, t = W) {\n if (this._checkKey(e), typeof t != \"string\") throw this._log(\"error\", `${u}fileType must be a string`), new TypeError(`${u}fileType must be a string`);\n this._log(\"info\", `Initiating multipart upload for object ${e}`);\n let r = { uploads: \"\" }, n = { [m]: t, [E]: f }, o = y(e), { url: i, headers: a } = await this._sign(\"POST\", o, r, n, \"\"), c = `${i}?${new URLSearchParams(r)}`, l = await (await this._sendRequest(c, \"POST\", a)).text(), h = b(l);\n if (typeof h == \"object\" && h !== null && \"error\" in h && typeof h.error == \"object\" && h.error !== null && \"message\" in h.error) {\n let d = String(h.error.message);\n throw this._log(\"error\", `${u}Failed to abort multipart upload: ${d}`), new Error(`${u}Failed to abort multipart upload: ${d}`);\n }\n if (typeof h == \"object\" && h !== null) {\n if (!h.initiateMultipartUploadResult || !h.initiateMultipartUploadResult.uploadId) throw this._log(\"error\", `${u}Failed to create multipart upload: no uploadId in response`), new Error(`${u}Failed to create multipart upload: Missing upload ID in response`);\n return h.initiateMultipartUploadResult.uploadId;\n } else throw this._log(\"error\", `${u}Failed to create multipart upload: unexpected response format`), new Error(`${u}Failed to create multipart upload: Unexpected response format`);\n }\n async uploadPart(e, t, r, n, o = {}) {\n this._validateUploadPartParams(e, t, r, n, o);\n let i = { uploadId: r, partNumber: n, ...o }, a = { [R]: t.length }, c = y(e), { url: s, headers: l } = await this._sign(\"PUT\", c, i, a, t), h = `${s}?${new URLSearchParams(i)}`, d = await this._sendRequest(h, \"PUT\", l, t), g = I(d.headers.get(\"etag\") || \"\");\n return { partNumber: n, ETag: g };\n }\n _validateUploadPartParams(e, t, r, n, o) {\n if (this._checkKey(e), !(t instanceof Buffer || typeof t == \"string\")) throw this._log(\"error\", U), new TypeError(U);\n if (typeof r != \"string\" || r.trim().length === 0) throw this._log(\"error\", $), new TypeError($);\n if (!Number.isInteger(n) || n <= 0) throw this._log(\"error\", `${u}partNumber must be a positive integer`), new TypeError(`${u}partNumber must be a positive integer`);\n this._checkOpts(o);\n }\n async completeMultipartUpload(e, t, r) {\n if (this._checkKey(e), typeof t != \"string\" || t.trim().length === 0) throw this._log(\"error\", $), new TypeError($);\n if (!Array.isArray(r) || r.length === 0) throw this._log(\"error\", j), new TypeError(j);\n if (!r.every((_) => typeof _.partNumber == \"number\" && typeof _.ETag == \"string\")) throw this._log(\"error\", k), new TypeError(k);\n this._log(\"info\", `Complete multipart upload ${t} for object ${e}`);\n let n = { uploadId: t }, o = this._buildCompleteMultipartUploadXml(r), i = { [m]: q, [R]: Buffer.byteLength(o).toString(), [E]: await A(o) }, a = y(e), { url: c, headers: s } = await this._sign(\"POST\", a, n, i, o), l = `${c}?${new URLSearchParams(n)}`, d = await (await this._sendRequest(l, \"POST\", s, o)).text(), g = b(d);\n if (typeof g == \"object\" && g !== null && \"error\" in g && typeof g.error == \"object\" && g.error !== null && \"message\" in g.error) {\n let _ = String(g.error.message);\n throw this._log(\"error\", `${u}Failed to abort multipart upload: ${_}`), new Error(`${u}Failed to abort multipart upload: ${_}`);\n }\n return g.completeMultipartUploadResult;\n }\n async abortMultipartUpload(e, t) {\n if (this._checkKey(e), typeof t != \"string\" || t.trim().length === 0) throw this._log(\"error\", $), new TypeError($);\n this._log(\"info\", `Aborting multipart upload ${t} for object ${e}`);\n let r = { uploadId: t }, n = { [m]: q, [E]: f };\n try {\n let o = y(e), { url: i, headers: a } = await this._sign(\"DELETE\", o, r, n, \"\"), c = `${i}?${new URLSearchParams(r)}`, s = await this._sendRequest(c, \"DELETE\", a);\n if (s.ok) {\n let l = await s.text(), h = b(l);\n if (typeof h == \"object\" && h !== null && \"error\" in h && typeof h.error == \"object\" && h.error !== null && \"message\" in h.error) {\n let d = String(h.error.message);\n throw this._log(\"error\", `${u}Failed to abort multipart upload: ${d}`), new Error(`${u}Failed to abort multipart upload: ${d}`);\n }\n return { status: \"Aborted\", key: e, uploadId: t, response: h };\n } else throw this._log(\"error\", `${u}Abort request failed with status ${s.status}`), new Error(`${u}Abort request failed with status ${s.status}`);\n } catch (o) {\n let i = o instanceof Error ? o.message : String(o);\n throw this._log(\"error\", `${u}Failed to abort multipart upload for key ${e}: ${i}`), new Error(`${u}Failed to abort multipart upload for key ${e}: ${i}`);\n }\n }\n _buildCompleteMultipartUploadXml(e) {\n return `\n \n ${e.map((t) => `\n \n ${t.partNumber}\n ${t.ETag}\n \n `).join(\"\")}\n \n `;\n }\n async delete(e) {\n this._checkKey(e), this._log(\"info\", `Deleting object ${e}`);\n let t = { [m]: w, [E]: f }, r = y(e), { url: n, headers: o } = await this._sign(\"DELETE\", r, {}, t, \"\"), i = await this._sendRequest(n, \"DELETE\", o);\n return i.status === 204 || i.status === 200;\n }\n async _sendRequest(e, t, r, n, o = []) {\n this._log(\"info\", `Sending ${t} request to ${e}, headers: ${JSON.stringify(r)}`);\n let i = await fetch(e, { method: t, headers: r, body: [\"GET\", \"HEAD\"].includes(t) ? void 0 : n, signal: this.requestAbortTimeout !== void 0 ? AbortSignal.timeout(this.requestAbortTimeout) : void 0 });\n return this._log(\"info\", `Response status: ${i.status, o}`), !i.ok && !o.includes(i.status) && await this._handleErrorResponse(i), i;\n }\n async _handleErrorResponse(e) {\n let t = await e.text(), r = e.headers.get(\"x-amz-error-code\") || \"Unknown\", n = e.headers.get(\"x-amz-error-message\") || e.statusText;\n throw this._log(\"error\", `${u}Request failed with status ${e.status}: ${r} - ${n},err body: ${t}`), new Error(`${u}Request failed with status ${e.status}: ${r} - ${n}, err body: ${t}`);\n }\n _buildCanonicalQueryString(e) {\n return Object.keys(e).length < 1 ? \"\" : Object.keys(e).sort().map((t) => `${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`).join(\"&\");\n }\n async _getSignatureKey(e) {\n let t = await H(`AWS4${this.secretAccessKey}`, e), r = await H(t, this.region), n = await H(r, O);\n return H(n, K);\n }\n};\nvar A = async (p) => {\n let e = Q(\"sha256\");\n return e.update(p), e.digest(\"hex\");\n};\nvar H = async (p, e, t) => {\n let r = z(\"sha256\", p);\n return r.update(e), r.digest(t);\n};\nvar I = (p) => {\n let e = { '\"': \"\", \""\": \"\", \""\": \"\", \""\": \"\", \""\": \"\" };\n return p.replace(/^(\"|"|")|(\"|"|")$/g, (t) => e[t]);\n};\nvar b = (p) => {\n let e = (o) => o.replace(/"/g, '\"').replace(/'/g, \"'\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/&/g, \"&\"), t = {}, r = /<(\\w)([-\\w]+)(?:\\/|[^>]*>((?:(?!<\\1)[\\s\\S])*)<\\/\\1\\2)>/gm, n;\n for (; n = r.exec(p); ) {\n let [, o, i, a] = n, c = o.toLowerCase() + i, s = a != null ? b(a) : true;\n typeof s == \"string\" ? t[c] = I(e(s)) : Array.isArray(t[c]) ? t[c].push(s) : t[c] = t[c] != null ? [t[c], s] : ne[c] ? [s] : s;\n }\n return Object.keys(t).length ? t : e(p);\n};\n\n// src/lowstorage.ts\nvar import_avsc = __toESM(require_lib(), 1);\n\n// src/errors.ts\nvar lowstorage_ERROR_CODES = {\n MISSING_ARGUMENT: \"MISSING_ARGUMENT\",\n COLLECTION_EXISTS: \"COLLECTION_EXISTS\",\n CREATE_COLLECTION_ERROR: \"CREATE_COLLECTION_ERROR\",\n RENAME_COLLECTION_ERROR: \"RENAME_COLLECTION_ERROR\",\n REMOVE_COLLECTION_ERROR: \"REMOVE_COLLECTION_ERROR\",\n UPDATE_COLLECTION_SCHEMA_ERROR: \"UPDATE_COLLECTION_SCHEMA_ERROR\",\n COLLECTION_NOT_FOUND: \"COLLECTION_NOT_FOUND\",\n SCHEMA_VALIDATION_ERROR: \"SCHEMA_VALIDATION_ERROR\",\n DOCUMENT_VALIDATION_ERROR: \"DOCUMENT_VALIDATION_ERROR\",\n S3_OPERATION_ERROR: \"S3_OPERATION_ERROR\",\n FIND_ERROR: \"FIND_ERROR\",\n FIND_ONE_ERROR: \"FIND_ONE_ERROR\",\n SAVE_DATA_ERROR: \"SAVE_DATA_ERROR\",\n INSERT_ERROR: \"INSERT_ERROR\",\n UPDATE_ERROR: \"UPDATE_ERROR\",\n UPDATE_ONE_ERROR: \"UPDATE_ONE_ERROR\",\n DELETE_ERROR: \"DELETE_ERROR\",\n COUNT_ERROR: \"COUNT_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\"\n};\nvar lowstorageError = class extends Error {\n constructor(message, code = lowstorage_ERROR_CODES.UNKNOWN_ERROR) {\n super(`lowstorageError: ${message} :: code: ${code}`);\n this.name = this.constructor.name;\n this.code = code;\n Error.captureStackTrace(this, this.constructor);\n }\n};\nvar SchemaValidationError = class extends lowstorageError {\n constructor(message, code = lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR) {\n super(message, lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR);\n }\n};\nvar DocumentValidationError = class extends lowstorageError {\n constructor(message, code = lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR) {\n super(message, lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR);\n }\n};\nvar S3OperationError = class extends lowstorageError {\n constructor(message, operation) {\n super(`S3 ${operation} operation failed: ${message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n};\n\n// src/helpers.ts\nimport { randomUUID } from \"node:crypto\";\nvar matchesQuery = (document, query) => {\n return Object.keys(query).every((key) => document[key] === query[key]);\n};\nvar generateUUID = async () => {\n if (typeof randomUUID !== \"undefined\" && typeof randomUUID === \"function\") {\n return randomUUID();\n }\n if (typeof crypto !== \"undefined\" && typeof crypto === \"object\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v2 = c === \"x\" ? r : r & 3 | 8;\n return v2.toString(16);\n });\n};\nvar ensureIdFieldInSchema = (schema) => {\n const idField = {\n name: \"_id\",\n type: \"string\",\n size: 16,\n logicalType: \"UUID\"\n };\n if (typeof schema === \"undefined\" || schema === null) {\n return schema;\n }\n if (\"type\" in schema && schema.type === \"record\" && \"fields\" in schema && Array.isArray(schema.fields)) {\n const hasIdField = schema.fields.some((field) => field.name === \"_id\");\n if (!hasIdField) {\n schema.fields.unshift(idField);\n }\n } else if (\"type\" in schema && schema.type === \"array\" && \"items\" in schema && schema.items !== null && typeof schema.items === \"object\" && \"type\" in schema.items && schema.items.type === \"record\" && \"fields\" in schema.items && Array.isArray(schema.items.fields)) {\n const hasIdField = schema.items.fields.some((field) => field.name === \"_id\");\n if (!hasIdField) {\n schema.items.fields.unshift(idField);\n }\n }\n return schema;\n};\n\n// src/lowstorage.ts\nvar MODULE_NAME = \"lowstorage\";\nvar DEFAULT_DELIMITER = \"/\";\nvar PROJECT_DIR_PREFIX = \"lowstorage\";\nvar COL_SUFFIX = \".avro\";\nvar CHUNG_1MB = 1024 * 1024;\nvar CHUNG_5MB = 5 * CHUNG_1MB;\nvar EMPTY_DATA = Buffer.from(\"\", \"utf8\");\nvar errorValidationFn = (errorCode = lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR) => {\n throw new DocumentValidationError(`${MODULE_NAME}: Invalid document or schema ${errorCode}`);\n};\nvar _hasColName = (colName = \"\") => {\n if (colName.trim() === \"\" || colName === null || typeof colName === \"undefined\" || colName.length > 255 || colName === null) {\n throw new lowstorageError(`${MODULE_NAME}: Collection name is required, null or too long`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);\n }\n};\nvar lowstorage = class {\n constructor(options) {\n this._checkArgs = (args) => {\n const requiredFields = [\"accessKeyId\", \"secretAccessKey\", \"endpoint\", \"bucketName\"];\n for (const field of requiredFields) {\n if (!args[field]) {\n throw new lowstorageError(`${MODULE_NAME}: ${field} is required`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);\n }\n }\n };\n /**\n * Get the S3 instance associated with the lowstorage instance.\n * @returns {S3} The S3 instance. Use this to perform S3 operations. Check for ultralight-s3 for more details.\n */\n this.s3 = () => {\n return this._s3;\n };\n this._checkArgs(options);\n this._schemas = /* @__PURE__ */ new Map();\n this._s3 = new x(options);\n this._dirPrefix = options.dirPrefix || PROJECT_DIR_PREFIX;\n this._avroParse = import_avsc.Type;\n }\n /**\n * Check if a bucket exists.\n * @returns {Promise} True if the bucket exists, false otherwise.\n * @throws {lowstorageError} If there's an error.\n */\n async checkIfStorageExists() {\n try {\n const exists = await this._s3.bucketExists();\n return !!exists;\n } catch (error) {\n if (error.message.includes(\"Not Found\")) {\n return false;\n }\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n }\n /**\n * Create a new storage bucket if it doesn't exist.\n * @returns {Promise} A Promise that resolves to true if the bucket was created or already exists, false otherwise.\n * @throws {lowstorageError} If there's an error.\n */\n async createStorage() {\n try {\n const exists = await this.checkIfStorageExists();\n if (!exists) {\n const createdBucket = await this._s3.createBucket();\n return createdBucket;\n }\n return exists;\n throw new lowstorageError(`${MODULE_NAME}: Bucket already exists`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n } catch (error) {\n if (error instanceof lowstorageError) {\n throw error;\n }\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n }\n /**\n * List all collections.\n * @returns {Promise} An array of collection names.\n * @throws {S3OperationError} If there's an error during S3 operation.\n */\n async listCollections() {\n try {\n const listed = await this._s3.list(DEFAULT_DELIMITER, this._dirPrefix);\n if (Array.isArray(listed)) {\n return listed.map((entry) => entry.key.slice(this._dirPrefix.length + 1, -COL_SUFFIX.length));\n } else if (typeof listed === \"object\" && listed !== null && \"keyCount\" in listed && listed.keyCount === \"0\") {\n return [];\n }\n return [];\n } catch (error) {\n throw new S3OperationError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n }\n /**\n * Check if a collection exists.\n * @param {string} colName - The name of the collection.\n * @returns {Promise} True if the collection exists, false otherwise.\n * @throws {lowstorageError} If there's an error.\n */\n async collectionExists(colName = \"\") {\n try {\n _hasColName(colName);\n const exists = await this._s3.fileExists(`${this._dirPrefix}${DEFAULT_DELIMITER}${colName}${COL_SUFFIX}`);\n return !!exists;\n } catch (error) {\n if (error.message.includes(\"Not Found\")) {\n return false;\n }\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.COLLECTION_NOT_FOUND);\n }\n }\n /**\n * Create a new collection.\n * @param {string} colName - The name of the collection.\n * @param {Object} [schema] - The schema for the collection.\n * @param {Array} [data=[]] - The initial data for the collection.\n * @returns {Promise} A Promise that resolves to a Collection object.\n * @throws {lowstorageError} If there's an error.\n */\n async createCollection(colName = \"\", schema, data = []) {\n try {\n _hasColName(colName);\n const exists = await this.collectionExists(colName);\n if (!exists) {\n if (typeof schema !== \"undefined\" && schema !== null) {\n try {\n const type = this._avroParse.forSchema(schema);\n if (!type) {\n throw new SchemaValidationError(\n `${MODULE_NAME}: Schema is invalid: ${schema} ${lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR}`\n );\n } else {\n this._schemas.set(colName, schema);\n }\n } catch (error) {\n throw new SchemaValidationError(`${MODULE_NAME}: Schema is invalid: ${schema}`, lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR);\n }\n }\n if (data.length > 0 && schema) {\n const wrapperType = this._avroParse.forSchema({ type: \"array\", items: schema });\n await this._s3.put(`${this._dirPrefix}${DEFAULT_DELIMITER}${colName}${COL_SUFFIX}`, wrapperType.toBuffer(data));\n } else {\n await this._s3.put(`${this._dirPrefix}${DEFAULT_DELIMITER}${colName}${COL_SUFFIX}`, EMPTY_DATA);\n }\n return this.collection(colName, schema, false);\n }\n throw new lowstorageError(`${MODULE_NAME}: Collection ${colName} already exists`, lowstorage_ERROR_CODES.COLLECTION_EXISTS);\n } catch (error) {\n if (error instanceof lowstorageError) {\n throw error;\n }\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.CREATE_COLLECTION_ERROR);\n }\n }\n /**\n * Remove a collection.\n * @param {string} colName - The name of the collection.\n * @returns {Promise} A Promise that resolves to true if the collection is removed, false otherwise.\n * @throws {lowstorageError} If there's an error.\n */\n async removeCollection(colName = \"\") {\n try {\n _hasColName(colName);\n const exists = await this.collectionExists(colName);\n if (exists) {\n await this._s3.delete(`${this._dirPrefix}${DEFAULT_DELIMITER}${colName}${COL_SUFFIX}`);\n const exists2 = await this.collectionExists(colName);\n if (typeof exists2 === \"boolean\") {\n if (!exists2) {\n this._schemas.delete(colName);\n return true;\n }\n throw new lowstorageError(`${MODULE_NAME}: Failed to delete collection ${colName}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n throw new S3OperationError(`${MODULE_NAME}: Failed to delete collection ${colName}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n throw new lowstorageError(`${MODULE_NAME}: Collection ${colName} does not exist`, lowstorage_ERROR_CODES.REMOVE_COLLECTION_ERROR);\n } catch (error) {\n if (error instanceof S3OperationError) {\n throw error;\n }\n throw new lowstorageError(\n `${MODULE_NAME}: Failed to remove collection: ${error.message}`,\n lowstorage_ERROR_CODES.REMOVE_COLLECTION_ERROR\n );\n }\n }\n /**\n * Get or create a collection.\n * @param {string} colName - The name of the collection.\n * @param {Object} [schema] - The schema for the collection.\n * @param {boolean} [autoCreate=true] - Whether to automatically create the collection if it doesn't exist.\n * @returns {Promise} A Promise that resolves to a Collection object.\n * @throws {lowstorageError} If there's an error.\n */\n async collection(colName = \"\", schema, autoCreate = true) {\n try {\n _hasColName(colName);\n const colPath = `${this._dirPrefix}${DEFAULT_DELIMITER}${colName}${COL_SUFFIX}`;\n const exists = await this._s3.fileExists(colPath);\n if (!exists) {\n if (!autoCreate) {\n throw new lowstorageError(`${MODULE_NAME}: Collection ${colName} does not exist`, lowstorage_ERROR_CODES.COLLECTION_NOT_FOUND);\n }\n await this._s3.put(colPath, EMPTY_DATA);\n }\n const colSchema = schema || this._schemas.get(colName) || void 0;\n return new Collection(colName, colSchema, this._s3, this._dirPrefix);\n } catch (error) {\n if (error.message.includes(\"unknown type\")) {\n throw new SchemaValidationError(\n `${MODULE_NAME}: Schema input is invalid: ${error.message}`,\n lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR\n );\n }\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.COLLECTION_NOT_FOUND);\n }\n }\n};\nvar Collection = class _Collection {\n constructor(colName = \"\", schema, s3, dirPrefix = PROJECT_DIR_PREFIX, safeWrite = false, chunkSize = CHUNG_5MB) {\n this.getProps = () => ({\n colName: this._colName,\n s3: this._s3,\n schema: this._schema,\n avroParse: this._avroParse,\n avroType: this._avroType,\n dirPrefix: this._dirPrefix,\n safeWrite: this._safeWrite,\n chunkSize: this._chunkSize\n });\n this.setProps = (props) => {\n this._colName = props.colName;\n this._schema = props.schema;\n this._s3 = props.s3;\n this._avroParse = props.avroParse;\n this._avroType = props.avroType;\n this._dirPrefix = props.dirPrefix;\n this._safeWrite = props.safeWrite;\n this._chunkSize = props.chunkSize;\n };\n this.setSafeWrite = (safeWrite) => {\n this._safeWrite = safeWrite;\n };\n this.getSafeWrite = () => {\n return this._safeWrite;\n };\n this.getAvroSchema = () => {\n return this._schema;\n };\n this.setAvroSchema = (schema) => {\n try {\n this._schema = ensureIdFieldInSchema(schema);\n this._avroType = typeof schema === \"undefined\" ? null : this._avroParse.forSchema(schema);\n } catch (error) {\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR);\n }\n };\n this.getCollectionETag = () => {\n return this._lastETag;\n };\n this.inferAvroSchema = (data, type = \"record\") => {\n if (Array.isArray(data)) {\n data = data[0];\n }\n const inferedType = this._avroParse.forValue(data);\n const schema = inferedType.schema();\n return ensureIdFieldInSchema(schema);\n };\n this._colName = colName.trim();\n this._s3 = s3;\n this._schema = ensureIdFieldInSchema(schema);\n this._dirPrefix = dirPrefix;\n this._safeWrite = safeWrite;\n this._chunkSize = chunkSize || CHUNG_5MB;\n this._s3.setMaxRequestSizeInBytes(this._chunkSize);\n this._avroParse = import_avsc.Type;\n this._lastETag = \"\";\n this._dataCache = [];\n this._avroType = typeof schema === \"undefined\" ? null : this._avroParse.forSchema(schema);\n this._key = `${this._dirPrefix}${DEFAULT_DELIMITER}${this._colName}${COL_SUFFIX}`;\n }\n async forceLoadData() {\n try {\n this._lastETag = \"\";\n const data = await this._loadData();\n this._dataCache = data;\n return true;\n } catch (error) {\n throw new lowstorageError(`${MODULE_NAME}: Failed to force update data: ${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n }\n async _loadData() {\n try {\n if (this._avroType === null || typeof this._avroType === \"undefined\") {\n throw new lowstorageError(\n `${MODULE_NAME}: Missing type definition. Configure before operations `,\n lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR\n );\n }\n const { etag, data } = await this._s3.getObjectWithETag(this._key, { \"if-none-match\": this._lastETag });\n if (data === null) {\n return this._dataCache;\n }\n this._lastETag = etag === null ? this._lastETag : etag;\n const wrapperType = this._avroParse.forSchema({ type: \"array\", items: this._avroType });\n if (data.length < this._chunkSize) {\n this._dataCache = data.length > 0 ? wrapperType.fromBuffer(Buffer.from(data, \"utf8\")) : [];\n return this._dataCache;\n }\n let offset = this._chunkSize;\n let bufferArr = [Buffer.from(data, \"utf8\")];\n let repeat = true;\n while (repeat) {\n const nextDataResponse = await this._s3.getResponse(this._key, false, offset, offset + this._chunkSize);\n const nextDataBody = await nextDataResponse.text();\n bufferArr.push(Buffer.from(nextDataBody, \"utf8\"));\n offset += this._chunkSize;\n const contentLength = parseInt(nextDataResponse.headers.get(\"content-length\") || nextDataBody.length.toString());\n if (contentLength < this._chunkSize) {\n repeat = false;\n }\n }\n const bufferedData = Buffer.concat(bufferArr);\n this._dataCache = wrapperType.fromBuffer(bufferedData);\n return this._dataCache;\n } catch (error) {\n if (error.toString().indexOf(\"status 404: Unknown - Not Found\") > -1) {\n this._dataCache = [];\n return this._dataCache;\n }\n throw new S3OperationError(`${MODULE_NAME}: Failed to load data: ${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n }\n async _saveData(data) {\n try {\n if (this._avroType === null || typeof this._avroType === \"undefined\") {\n throw new lowstorageError(\n `${MODULE_NAME}: Missing type definition. Configure before operations `,\n lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR\n );\n }\n const wrapperType = this._avroParse.forSchema({ type: \"array\", items: this._avroType });\n const dataBuffer = data.length > 0 ? wrapperType.toBuffer(data) : EMPTY_DATA;\n if (this._safeWrite && this._lastETag !== \"\") {\n const currentETag = await this._s3.getEtag(this._key);\n if (currentETag !== null && currentETag !== this._lastETag) {\n return false;\n }\n }\n const resp = await this._s3.put(this._key, dataBuffer);\n if (typeof resp === \"object\" && \"status\" in resp && resp.status !== 200) {\n throw new S3OperationError(`${MODULE_NAME}: Failed to save data`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n const newETag = resp.headers?.get(\"etag\") || \"\";\n if (newETag && newETag.length > 0) {\n this._lastETag = this._s3.sanitizeETag(newETag);\n this._dataCache = data;\n }\n return true;\n } catch (error) {\n if (error instanceof S3OperationError) {\n throw error;\n }\n throw new lowstorageError(`${MODULE_NAME}: ${error.message}`, lowstorage_ERROR_CODES.SAVE_DATA_ERROR);\n }\n }\n /**\n * Insert a document into the collection.\n * @param {Object|Array} doc - The document to insert.\n * @param {Object} [schema=undefined] - The schema for the document.\n * @returns {Promise} A Promise that resolves to the array of inserted document(s).\n * @throws {lowstorageError} If there's an error.\n */\n async insert(doc, schema) {\n try {\n if (doc === void 0 || doc === null) {\n throw new lowstorageError(`${MODULE_NAME}: Document is required for insert`, lowstorage_ERROR_CODES.INSERT_ERROR);\n }\n if (typeof doc !== \"object\" && !Array.isArray(doc)) {\n throw new DocumentValidationError(\n `${MODULE_NAME}: Document must be an object or an array`,\n lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR\n );\n }\n const items = !Array.isArray(doc) ? [doc] : doc;\n const schemaWithId = schema ? ensureIdFieldInSchema(schema) : this._schema || this.inferAvroSchema(items[0]);\n const avroType = this._avroParse.forSchema(schemaWithId);\n if (!avroType) {\n throw new SchemaValidationError(\n `${MODULE_NAME}: Schema is required - Pass a schema to the insert method`,\n lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR\n );\n }\n this._avroType = avroType;\n const data = await this._loadData();\n for (let item of items) {\n if (typeof item !== \"object\" || item === null) {\n throw new DocumentValidationError(\n `${MODULE_NAME}: Invalid input: input must be an object or an array of objects`,\n lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR\n );\n }\n item._id = item._id || await generateUUID();\n const validBuffer = this._avroType.isValid(item, {\n errorHook: errorValidationFn,\n noUndeclaredFields: true\n });\n if (validBuffer === true) {\n data.push(item);\n } else {\n throw new DocumentValidationError(`${MODULE_NAME}: Invalid document or schema`, lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR);\n }\n }\n const success = await this._saveData(data);\n if (!success) {\n throw new S3OperationError(`${MODULE_NAME}: Failed to insert document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);\n }\n this.setAvroSchema(schemaWithId);\n return items;\n } catch (error) {\n if (error.message.includes(\"unknown type\")) {\n throw new SchemaValidationError(\n `${MODULE_NAME}: Schema input is invalid: ${error.message}`,\n lowstorage_ERROR_CODES.SCHEMA_VALIDATION_ERROR\n );\n }\n if (error instanceof lowstorageError) {\n throw error;\n }\n throw new lowstorageError(`${MODULE_NAME} Insert operation failed: ${error.message}`, lowstorage_ERROR_CODES.INSERT_ERROR);\n }\n }\n /**\n * Find documents in the collection.\n * @param {Object} [query={}] - The query to filter documents.\n * @param {Object} [options={}] - The options for pagination.\n * @param {number} [options.skip=0] - The number of documents to skip. Default is 0.\n * @param {number} [options.limit=undefined] - The maximum number of documents to return. Default is undefined, which means no limit.\n * @returns {Promise} A Promise that resolves to an array of matching documents.\n * @throws {lowstorageError} If there's an error.\n */\n async find(query = {}, options = {}) {\n try {\n if (query === void 0 || query === null) {\n throw new lowstorageError(`${MODULE_NAME}: Query is required for update`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);\n }\n const data = await this._loadData();\n const start = options.skip !== void 0 ? parseInt(String(options.skip), 10) : 0;\n const end = options.limit !== void 0 ? start + parseInt(String(options.limit), 10) : void 0;\n const filteredData = data.filter((doc) => matchesQuery(doc, query)).slice(start, end);\n return filteredData;\n } catch (error) {\n throw new lowstorageError(`${MODULE_NAME}: Find operation failed: ${error.message}`, lowstorage_ERROR_CODES.FIND_ERROR);\n }\n }\n /**\n * Find the first document in the collection that matches the query.\n * @param {Object} [query={}] - The query to filter documents.\n * @returns {Promise