@clockworklabs/spacetimedb-sdk
Advanced tools
+24
-4
@@ -61,2 +61,3 @@ /** | ||
| constructor(size: number); | ||
| toBase64(): string; | ||
| getBuffer(): Uint8Array; | ||
@@ -167,3 +168,6 @@ writeUInt8Array(value: Uint8Array): void; | ||
| serialize: (writer: BinaryWriter, value: object) => void; | ||
| deserialize: (reader: BinaryReader) => any; | ||
| intoMapKey(value: any): ComparablePrimitive; | ||
| deserialize: (reader: BinaryReader) => { | ||
| [key: string]: any; | ||
| }; | ||
| } | ||
@@ -182,2 +186,3 @@ declare class MapType { | ||
| type AnyType = ProductType | SumType | ArrayBaseType | MapType | EnumLabel | TypeRef | None; | ||
| type ComparablePrimitive = number | string | String | boolean | bigint; | ||
| /** | ||
@@ -238,2 +243,10 @@ * The SpacetimeDB Algebraic Type System (SATS) is a structural type system in | ||
| isTimeDuration(): boolean; | ||
| /** | ||
| * Convert a value of the algebraic type into something that can be used as a key in a map. | ||
| * There are no guarantees about being able to order it. | ||
| * This is only guaranteed to be comparable to other values of the same type. | ||
| * @param value A value of the algebraic type | ||
| * @returns Something that can be used as a key in a map. | ||
| */ | ||
| intoMapKey(value: any): ComparablePrimitive; | ||
| serialize(writer: BinaryWriter, value: any): void; | ||
@@ -394,4 +407,8 @@ deserialize(reader: BinaryReader): any; | ||
| rowType: AlgebraicType; | ||
| primaryKey?: string | undefined; | ||
| primaryKeyInfo?: PrimaryKeyInfo; | ||
| } | ||
| interface PrimaryKeyInfo { | ||
| colName: string; | ||
| colType: AlgebraicType; | ||
| } | ||
| interface ReducerRuntimeTypeInfo { | ||
@@ -412,2 +429,5 @@ reducerName: string; | ||
| setReducerFlagsConstructor: () => any; | ||
| versionInfo?: { | ||
| cliVersion: string; | ||
| }; | ||
| } | ||
@@ -954,3 +974,3 @@ | ||
| type: 'insert' | 'delete'; | ||
| rowId: string; | ||
| rowId: ComparablePrimitive; | ||
| row: any; | ||
@@ -990,3 +1010,3 @@ }; | ||
| applyOperations: (operations: Operation[], ctx: EventContextInterface) => PendingCallback[]; | ||
| update: (ctx: EventContextInterface, newDbOp: Operation, oldDbOp: Operation, refCountDelta?: number) => PendingCallback | undefined; | ||
| update: (ctx: EventContextInterface, rowId: ComparablePrimitive, newRow: RowType, refCountDelta?: number) => PendingCallback | undefined; | ||
| insert: (ctx: EventContextInterface, operation: Operation, count?: number) => PendingCallback | undefined; | ||
@@ -993,0 +1013,0 @@ delete: (ctx: EventContextInterface, operation: Operation, count?: number) => PendingCallback | undefined; |
@@ -1,1 +0,1 @@ | ||
| var e=class{#e;#t=0;constructor(e){this.#e=new DataView(e.buffer),this.#t=e.byteOffset}get offset(){return this.#t}readUInt8Array(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e);return this.#t+=e,t}readBool(){const e=this.#e.getUint8(this.#t);return this.#t+=1,0!==e}readByte(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readBytes(e){const t=new DataView(this.#e.buffer,this.#t,e);return this.#t+=e,new Uint8Array(t.buffer)}readI8(){const e=this.#e.getInt8(this.#t);return this.#t+=1,e}readU8(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readI16(){const e=this.#e.getInt16(this.#t,!0);return this.#t+=2,e}readU16(){const e=this.#e.getUint16(this.#t,!0);return this.#t+=2,e}readI32(){const e=this.#e.getInt32(this.#t,!0);return this.#t+=4,e}readU32(){const e=this.#e.getUint32(this.#t,!0);return this.#t+=4,e}readI64(){const e=this.#e.getBigInt64(this.#t,!0);return this.#t+=8,e}readU64(){const e=this.#e.getBigUint64(this.#t,!0);return this.#t+=8,e}readU128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readI128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigInt64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readU256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigUint64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readI256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigInt64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readF32(){const e=this.#e.getFloat32(this.#t,!0);return this.#t+=4,e}readF64(){const e=this.#e.getFloat64(this.#t,!0);return this.#t+=8,e}readString(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e),r=new TextDecoder("utf-8").decode(t);return this.#t+=e,r}},t=class{#e;#r;#t=0;constructor(e){this.#e=new Uint8Array(e),this.#r=new DataView(this.#e.buffer)}#i(e){const t=this.#t+e+1;if(t<=this.#e.length)return;let r=2*this.#e.length;r<t&&(r=t);const i=new Uint8Array(r);i.set(this.#e),this.#e=i,this.#r=new DataView(this.#e.buffer)}getBuffer(){return this.#e.slice(0,this.#t)}writeUInt8Array(e){const t=e.length;this.#i(4+t),this.writeU32(t),this.#e.set(e,this.#t),this.#t+=e.length}writeBool(e){this.#i(1),this.#r.setUint8(this.#t,e?1:0),this.#t+=1}writeByte(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI8(e){this.#i(1),this.#r.setInt8(this.#t,e),this.#t+=1}writeU8(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI16(e){this.#i(2),this.#r.setInt16(this.#t,e,!0),this.#t+=2}writeU16(e){this.#i(2),this.#r.setUint16(this.#t,e,!0),this.#t+=2}writeI32(e){this.#i(4),this.#r.setInt32(this.#t,e,!0),this.#t+=4}writeU32(e){this.#i(4),this.#r.setUint32(this.#t,e,!0),this.#t+=4}writeI64(e){this.#i(8),this.#r.setBigInt64(this.#t,e,!0),this.#t+=8}writeU64(e){this.#i(8),this.#r.setBigUint64(this.#t,e,!0),this.#t+=8}writeU128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigUint64(this.#t,t,!0),this.#r.setBigUint64(this.#t+8,r,!0),this.#t+=16}writeI128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigInt64(this.#t,t,!0),this.#r.setBigInt64(this.#t+8,r,!0),this.#t+=16}writeU256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigUint64(this.#t+24,n,!0),this.#t+=32}writeI256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigInt64(this.#t+24,n,!0),this.#t+=32}writeF32(e){this.#i(4),this.#r.setFloat32(this.#t,e,!0),this.#t+=4}writeF64(e){this.#i(8),this.#r.setFloat64(this.#t,e,!0),this.#t+=8}writeString(e){const t=(new TextEncoder).encode(e);this.writeU32(t.length),this.#i(t.length),this.#e.set(t,this.#t),this.#t+=t.length}};function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(let n of i)if(!s.includes(n)||!r(e[n],t[n]))return!1;return!0}function i(e){return Array.prototype.map.call(e.reverse(),(e=>("00"+e.toString(16)).slice(-2))).join("")}function s(e){e.startsWith("0x")&&(e=e.slice(2));let t=e.match(/.{1,2}/g)||[],r=Uint8Array.from(t.map((e=>parseInt(e,16))));return 32!=r.length?new Uint8Array(0):r.reverse()}function n(t){return function(t){if(16!=t.length)throw new Error(`Uint8Array is not 16 bytes long: ${t}`);return new e(t).readU128()}(s(t))}function a(t){return function(t){if(32!=t.length)throw new Error(`Uint8Array is not 32 bytes long: [${t}]`);return new e(t).readU256()}(s(t))}function c(e){let r=new t(16);return r.writeU128(e),r.getBuffer()}function o(e){let r=new t(32);return r.writeU256(e),r.getBuffer()}var p,u,l=class e{data;get __connection_id__(){return this.data}constructor(e){this.data=e}isZero(){return this.data===BigInt(0)}static nullIfZero(e){return e.isZero()?null:e}static random(){let t=BigInt(0);for(let e=0;e<16;e++)t=t<<BigInt(8)|BigInt(Math.floor(255*Math.random()));return new e(t)}isEqual(e){return this.data==e.data}toHexString(){return i(c(this.data))}toUint8Array(){return c(this.data)}static fromString(t){return new e(n(t))}static fromStringOrNull(t){let r=e.fromString(t);return r.isZero()?null:r}},y=class e{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/e.MICROS_PER_MILLIS)}constructor(e){this.__time_duration_micros__=e}static fromMillis(t){return new e(BigInt(t)*e.MICROS_PER_MILLIS)}},d=class e{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(e){this.__timestamp_micros_since_unix_epoch__=e}static UNIX_EPOCH=new e(0n);static now(){return e.fromDate(new Date)}static fromDate(t){const r=t.getTime(),i=BigInt(r)*e.MICROS_PER_MILLIS;return new e(i)}toDate(){const t=this.__timestamp_micros_since_unix_epoch__/e.MICROS_PER_MILLIS;if(t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError("Timestamp is outside of the representable range of JS's Date");return new Date(Number(t))}},h=class e{data;get __identity__(){return this.data}constructor(e){this.data="string"==typeof e?a(e):e}isEqual(e){return this.toHexString()===e.toHexString()}toHexString(){return i(o(this.data))}toUint8Array(){return o(this.data)}static fromString(t){return new e(t)}};(u=p||(p={})).getAlgebraicType=function(){return U.createSumType([new b("Interval",U.createU64Type()),new b("Time",U.createU64Type())])},u.serialize=function(e){switch(e.tag){case"Interval":return{Interval:e.value};case"Time":return{Time:e.value};default:throw"unreachable"}},u.Interval=e=>({tag:"Interval",value:e}),u.Time=e=>({tag:"Time",value:e}),u.fromValue=function(e){let t=e.asSumValue();switch(t.tag){case 0:return{tag:"Interval",value:t.value.asBigInt()};case 1:return{tag:"Time",value:t.value.asBigInt()};default:throw"unreachable"}};var f,g,T=p,b=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},w=class{variants;constructor(e){this.variants=e}serialize=(e,t)=>{if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name)null!=t?(e.writeByte(0),this.variants[0].algebraicType.serialize(e,t)):e.writeByte(1);else{let r=t.tag;const i=this.variants.findIndex((e=>e.name===r));if(i<0)throw`Can't serialize a sum type, couldn't find ${t.tag} tag`;e.writeU8(i),this.variants[i].algebraicType.serialize(e,t.value)}};deserialize=e=>{let t=e.readU8();if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name){if(0===t)return this.variants[0].algebraicType.deserialize(e);if(1===t)return;throw`Can't deserialize an option type, couldn't find ${t} tag`}{let r=this.variants[t],i=r.algebraicType.deserialize(e);return{tag:r.name,value:i}}}},m=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},S=class{elements;constructor(e){this.elements=e}isEmpty(){return 0===this.elements.length}serialize=(e,t)=>{for(let r of this.elements)r.algebraicType.serialize(e,t[r.name])};deserialize=e=>{let t={};if(1===this.elements.length){if("__time_duration_micros__"===this.elements[0].name)return new y(e.readI64());if("__timestamp_micros_since_unix_epoch__"===this.elements[0].name)return new d(e.readI64());if("__identity__"===this.elements[0].name)return new h(e.readU256());if("__connection_id__"===this.elements[0].name)return new l(e.readU128())}for(let r of this.elements)t[r.name]=r.algebraicType.deserialize(e);return t}},I=class{keyType;valueType;constructor(e,t){this.keyType=e,this.valueType=t}},U=class e{type;type_;#s(e,t){this.type_=t,this.type=void 0===t?ke.None:e}get product(){if(this.type!==ke.ProductType)throw"product type was requested, but the type is not ProductType";return this.type_}set product(e){this.#s(ke.ProductType,e)}get sum(){if(this.type!==ke.SumType)throw"sum type was requested, but the type is not SumType";return this.type_}set sum(e){this.#s(ke.SumType,e)}get array(){if(this.type!==ke.ArrayType)throw"array type was requested, but the type is not ArrayType";return this.type_}set array(e){this.#s(ke.ArrayType,e)}get map(){if(this.type!==ke.MapType)throw"map type was requested, but the type is not MapType";return this.type_}set map(e){this.#s(ke.MapType,e)}static#n(t,r){let i=new e;return i.#s(t,r),i}static createProductType(e){return this.#n(ke.ProductType,new S(e))}static createSumType(e){return this.#n(ke.SumType,new w(e))}static createArrayType(e){return this.#n(ke.ArrayType,e)}static createMapType(e,t){return this.#n(ke.MapType,new I(e,t))}static createBoolType(){return this.#n(ke.Bool,null)}static createI8Type(){return this.#n(ke.I8,null)}static createU8Type(){return this.#n(ke.U8,null)}static createI16Type(){return this.#n(ke.I16,null)}static createU16Type(){return this.#n(ke.U16,null)}static createI32Type(){return this.#n(ke.I32,null)}static createU32Type(){return this.#n(ke.U32,null)}static createI64Type(){return this.#n(ke.I64,null)}static createU64Type(){return this.#n(ke.U64,null)}static createI128Type(){return this.#n(ke.I128,null)}static createU128Type(){return this.#n(ke.U128,null)}static createI256Type(){return this.#n(ke.I256,null)}static createU256Type(){return this.#n(ke.U256,null)}static createF32Type(){return this.#n(ke.F32,null)}static createF64Type(){return this.#n(ke.F64,null)}static createStringType(){return this.#n(ke.String,null)}static createBytesType(){return this.createArrayType(this.createU8Type())}static createOptionType(e){return this.createSumType([new b("some",e),new b("none",this.createProductType([]))])}static createIdentityType(){return this.createProductType([new m("__identity__",this.createU256Type())])}static createConnectionIdType(){return this.createProductType([new m("__connection_id__",this.createU128Type())])}static createScheduleAtType(){return T.getAlgebraicType()}static createTimestampType(){return this.createProductType([new m("__timestamp_micros_since_unix_epoch__",this.createI64Type())])}static createTimeDurationType(){return this.createProductType([new m("__time_duration_micros__",this.createI64Type())])}isProductType(){return this.type===ke.ProductType}isSumType(){return this.type===ke.SumType}isArrayType(){return this.type===ke.ArrayType}isMapType(){return this.type===ke.MapType}#a(){return this.isArrayType()&&this.array.type==ke.U8}#c(e){return this.isProductType()&&1===this.product.elements.length&&(this.product.elements[0].algebraicType.type==ke.U128||this.product.elements[0].algebraicType.type==ke.U256)&&this.product.elements[0].name===e}#o(e){return this.isProductType()&&1===this.product.elements.length&&this.product.elements[0].algebraicType.type===ke.I64&&this.product.elements[0].name===e}isIdentity(){return this.#c("__identity__")}isConnectionId(){return this.#c("__connection_id__")}isScheduleAt(){return this.isSumType()&&2===this.sum.variants.length&&"Interval"===this.sum.variants[0].name&&this.sum.variants[0].algebraicType.type===ke.U64&&"Time"===this.sum.variants[1].name&&this.sum.variants[1].algebraicType.type===ke.U64}isTimestamp(){return this.#o("__timestamp_micros_since_unix_epoch__")}isTimeDuration(){return this.#o("__time_duration_micros__")}serialize(e,t){switch(this.type){case ke.ProductType:this.product.serialize(e,t);break;case ke.SumType:this.sum.serialize(e,t);break;case ke.ArrayType:if(this.#a())e.writeUInt8Array(t);else{const r=this.array;e.writeU32(t.length);for(let i of t)r.serialize(e,i)}break;case ke.MapType:throw new Error("not implemented");case ke.Bool:e.writeBool(t);break;case ke.I8:e.writeI8(t);break;case ke.U8:e.writeU8(t);break;case ke.I16:e.writeI16(t);break;case ke.U16:e.writeU16(t);break;case ke.I32:e.writeI32(t);break;case ke.U32:e.writeU32(t);break;case ke.I64:e.writeI64(t);break;case ke.U64:e.writeU64(t);break;case ke.I128:e.writeI128(t);break;case ke.U128:e.writeU128(t);break;case ke.I256:e.writeI256(t);break;case ke.U256:e.writeU256(t);break;case ke.F32:e.writeF32(t);break;case ke.F64:e.writeF64(t);break;case ke.String:e.writeString(t);break;default:throw new Error(`not implemented, ${this.type}`)}}deserialize(e){switch(this.type){case ke.ProductType:return this.product.deserialize(e);case ke.SumType:return this.sum.deserialize(e);case ke.ArrayType:if(this.#a())return e.readUInt8Array();{const t=this.array,r=e.readU32();let i=[];for(let s=0;s<r;s++)i.push(t.deserialize(e));return i}case ke.MapType:throw new Error("not implemented");case ke.Bool:return e.readBool();case ke.I8:return e.readI8();case ke.U8:return e.readU8();case ke.I16:return e.readI16();case ke.U16:return e.readU16();case ke.I32:return e.readI32();case ke.U32:return e.readU32();case ke.I64:return e.readI64();case ke.U64:return e.readU64();case ke.I128:return e.readI128();case ke.U128:return e.readU128();case ke.U256:return e.readU256();case ke.F32:return e.readF32();case ke.F64:return e.readF64();case ke.String:return e.readString();default:throw new Error(`not implemented, ${this.type}`)}}};f=U||(U={}),(g=f.Type||(f.Type={})).SumType="SumType",g.ProductType="ProductType",g.ArrayType="ArrayType",g.MapType="MapType",g.Bool="Bool",g.I8="I8",g.U8="U8",g.I16="I16",g.U16="U16",g.I32="I32",g.U32="U32",g.I64="I64",g.U64="U64",g.I128="I128",g.U128="U128",g.I256="I256",g.U256="U256",g.F32="F32",g.F64="F64",g.String="String",g.None="None";var A,v,z,_,B,F,M,E,k,x,C,O,q,P,R,D,N,L,$,W,H,Q,V,j,G,Z,K,J,X,Y,ee,te,re,ie,se,ne,ae,ce,oe,pe,ue,le,ye,de,he,fe,ge,Te,be,we,me,Se,Ie,Ue,Ae,ve,ze,_e,Be,Fe,Me,Ee,ke=U.Type,xe=class{tag;value;constructor(e,t){this.tag=e,this.value=t}static deserialize(e,t){return t.readSum(e)}},Ce=class{elements;constructor(e){this.elements=e}static deserialize(e,t){return t.readProduct(e)}},Oe=class{value;constructor(e){if(void 0===e)throw"value is undefined";this.value=e}callMethod(e){return this[e]()}static deserialize(e,t){switch(e.type){case U.Type.ProductType:return new this(Ce.deserialize(e.product,t));case U.Type.SumType:return new this(xe.deserialize(e.sum,t));case U.Type.ArrayType:let r=e.array;return r.type===U.Type.U8?new this(t.readUInt8Array()):new this(t.readArray(r));case U.Type.MapType:let i=e.map;return new this(t.readMap(i.keyType,i.valueType));case U.Type.Bool:return new this(t.readBool());case U.Type.I8:return new this(t.readI8());case U.Type.U8:return new this(t.readU8());case U.Type.I16:return new this(t.readI16());case U.Type.U16:return new this(t.readU16());case U.Type.I32:return new this(t.readI32());case U.Type.U32:return new this(t.readU32());case U.Type.I64:return new this(t.readI64());case U.Type.U64:return new this(t.readU64());case U.Type.I128:return new this(t.readI128());case U.Type.U128:return new this(t.readU128());case U.Type.String:return new this(t.readString());default:throw new Error(`not implemented, ${e.type}`)}}asProductValue(){return this.value}asField(e){return this.asProductValue().elements[e]}asSumValue(){return this.value}asArray(){return this.value}asMap(){return this.value}asString(){return this.value}asBoolean(){return this.value}asNumber(){return this.value}asBytes(){return this.value}asBigInt(){return this.value}asIdentity(){return new h(this.asField(0).asBigInt())}asConnectionId(){return new l(this.asField(0).asBigInt())}asScheduleAt(){return p.fromValue(this)}};(v=A||(A={})).FixedSize=e=>({tag:"FixedSize",value:e}),v.RowOffsets=e=>({tag:"RowOffsets",value:e}),v.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("FixedSize",U.createU16Type()),new b("RowOffsets",U.createArrayType(U.createU64Type()))])},v.serialize=function(e,t){v.getTypeScriptAlgebraicType().serialize(e,t)},v.deserialize=function(e){return v.getTypeScriptAlgebraicType().deserialize(e)},(_=z||(z={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("sizeHint",A.getTypeScriptAlgebraicType()),new m("rowsData",U.createArrayType(U.createU8Type()))])},_.serialize=function(e,t){_.getTypeScriptAlgebraicType().serialize(e,t)},_.deserialize=function(e){return _.getTypeScriptAlgebraicType().deserialize(e)},(F=B||(B={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("reducer",U.createStringType()),new m("args",U.createArrayType(U.createU8Type())),new m("requestId",U.createU32Type()),new m("flags",U.createU8Type())])},F.serialize=function(e,t){F.getTypeScriptAlgebraicType().serialize(e,t)},F.deserialize=function(e){return F.getTypeScriptAlgebraicType().deserialize(e)},(E=M||(M={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("queryStrings",U.createArrayType(U.createStringType())),new m("requestId",U.createU32Type())])},E.serialize=function(e,t){E.getTypeScriptAlgebraicType().serialize(e,t)},E.deserialize=function(e){return E.getTypeScriptAlgebraicType().deserialize(e)},(x=k||(k={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("messageId",U.createArrayType(U.createU8Type())),new m("queryString",U.createStringType())])},x.serialize=function(e,t){x.getTypeScriptAlgebraicType().serialize(e,t)},x.deserialize=function(e){return x.getTypeScriptAlgebraicType().deserialize(e)},(O=C||(C={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("id",U.createU32Type())])},O.serialize=function(e,t){O.getTypeScriptAlgebraicType().serialize(e,t)},O.deserialize=function(e){return O.getTypeScriptAlgebraicType().deserialize(e)},(P=q||(q={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("query",U.createStringType()),new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},P.serialize=function(e,t){P.getTypeScriptAlgebraicType().serialize(e,t)},P.deserialize=function(e){return P.getTypeScriptAlgebraicType().deserialize(e)},(D=R||(R={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("queryStrings",U.createArrayType(U.createStringType())),new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},D.serialize=function(e,t){D.getTypeScriptAlgebraicType().serialize(e,t)},D.deserialize=function(e){return D.getTypeScriptAlgebraicType().deserialize(e)},(L=N||(N={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},L.serialize=function(e,t){L.getTypeScriptAlgebraicType().serialize(e,t)},L.deserialize=function(e){return L.getTypeScriptAlgebraicType().deserialize(e)},(W=$||($={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},W.serialize=function(e,t){W.getTypeScriptAlgebraicType().serialize(e,t)},W.deserialize=function(e){return W.getTypeScriptAlgebraicType().deserialize(e)},(Q=H||(H={})).CallReducer=e=>({tag:"CallReducer",value:e}),Q.Subscribe=e=>({tag:"Subscribe",value:e}),Q.OneOffQuery=e=>({tag:"OneOffQuery",value:e}),Q.SubscribeSingle=e=>({tag:"SubscribeSingle",value:e}),Q.SubscribeMulti=e=>({tag:"SubscribeMulti",value:e}),Q.Unsubscribe=e=>({tag:"Unsubscribe",value:e}),Q.UnsubscribeMulti=e=>({tag:"UnsubscribeMulti",value:e}),Q.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("CallReducer",B.getTypeScriptAlgebraicType()),new b("Subscribe",M.getTypeScriptAlgebraicType()),new b("OneOffQuery",k.getTypeScriptAlgebraicType()),new b("SubscribeSingle",q.getTypeScriptAlgebraicType()),new b("SubscribeMulti",R.getTypeScriptAlgebraicType()),new b("Unsubscribe",N.getTypeScriptAlgebraicType()),new b("UnsubscribeMulti",$.getTypeScriptAlgebraicType())])},Q.serialize=function(e,t){Q.getTypeScriptAlgebraicType().serialize(e,t)},Q.deserialize=function(e){return Q.getTypeScriptAlgebraicType().deserialize(e)},(j=V||(V={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("deletes",z.getTypeScriptAlgebraicType()),new m("inserts",z.getTypeScriptAlgebraicType())])},j.serialize=function(e,t){j.getTypeScriptAlgebraicType().serialize(e,t)},j.deserialize=function(e){return j.getTypeScriptAlgebraicType().deserialize(e)},(Z=G||(G={})).Uncompressed=e=>({tag:"Uncompressed",value:e}),Z.Brotli=e=>({tag:"Brotli",value:e}),Z.Gzip=e=>({tag:"Gzip",value:e}),Z.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("Uncompressed",V.getTypeScriptAlgebraicType()),new b("Brotli",U.createArrayType(U.createU8Type())),new b("Gzip",U.createArrayType(U.createU8Type()))])},Z.serialize=function(e,t){Z.getTypeScriptAlgebraicType().serialize(e,t)},Z.deserialize=function(e){return Z.getTypeScriptAlgebraicType().deserialize(e)},(J=K||(K={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableId",U.createU32Type()),new m("tableName",U.createStringType()),new m("numRows",U.createU64Type()),new m("updates",U.createArrayType(G.getTypeScriptAlgebraicType()))])},J.serialize=function(e,t){J.getTypeScriptAlgebraicType().serialize(e,t)},J.deserialize=function(e){return J.getTypeScriptAlgebraicType().deserialize(e)},(Y=X||(X={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tables",U.createArrayType(K.getTypeScriptAlgebraicType()))])},Y.serialize=function(e,t){Y.getTypeScriptAlgebraicType().serialize(e,t)},Y.deserialize=function(e){return Y.getTypeScriptAlgebraicType().deserialize(e)},(te=ee||(ee={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("quanta",U.createU128Type())])},te.serialize=function(e,t){te.getTypeScriptAlgebraicType().serialize(e,t)},te.deserialize=function(e){return te.getTypeScriptAlgebraicType().deserialize(e)},(ie=re||(re={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("identity",U.createIdentityType()),new m("token",U.createStringType()),new m("connectionId",U.createConnectionIdType())])},ie.serialize=function(e,t){ie.getTypeScriptAlgebraicType().serialize(e,t)},ie.deserialize=function(e){return ie.getTypeScriptAlgebraicType().deserialize(e)},(ne=se||(se={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("databaseUpdate",X.getTypeScriptAlgebraicType()),new m("requestId",U.createU32Type()),new m("totalHostExecutionDuration",U.createTimeDurationType())])},ne.serialize=function(e,t){ne.getTypeScriptAlgebraicType().serialize(e,t)},ne.deserialize=function(e){return ne.getTypeScriptAlgebraicType().deserialize(e)},(ce=ae||(ae={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableName",U.createStringType()),new m("rows",z.getTypeScriptAlgebraicType())])},ce.serialize=function(e,t){ce.getTypeScriptAlgebraicType().serialize(e,t)},ce.deserialize=function(e){return ce.getTypeScriptAlgebraicType().deserialize(e)},(pe=oe||(oe={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("messageId",U.createArrayType(U.createU8Type())),new m("error",U.createOptionType(U.createStringType())),new m("tables",U.createArrayType(ae.getTypeScriptAlgebraicType())),new m("totalHostExecutionDuration",U.createTimeDurationType())])},pe.serialize=function(e,t){pe.getTypeScriptAlgebraicType().serialize(e,t)},pe.deserialize=function(e){return pe.getTypeScriptAlgebraicType().deserialize(e)},(le=ue||(ue={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("reducerName",U.createStringType()),new m("reducerId",U.createU32Type()),new m("args",U.createArrayType(U.createU8Type())),new m("requestId",U.createU32Type())])},le.serialize=function(e,t){le.getTypeScriptAlgebraicType().serialize(e,t)},le.deserialize=function(e){return le.getTypeScriptAlgebraicType().deserialize(e)},(de=ye||(ye={})).Committed=e=>({tag:"Committed",value:e}),de.Failed=e=>({tag:"Failed",value:e}),de.OutOfEnergy={tag:"OutOfEnergy"},de.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("Committed",X.getTypeScriptAlgebraicType()),new b("Failed",U.createStringType()),new b("OutOfEnergy",U.createProductType([]))])},de.serialize=function(e,t){de.getTypeScriptAlgebraicType().serialize(e,t)},de.deserialize=function(e){return de.getTypeScriptAlgebraicType().deserialize(e)},(fe=he||(he={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("status",ye.getTypeScriptAlgebraicType()),new m("timestamp",U.createTimestampType()),new m("callerIdentity",U.createIdentityType()),new m("callerConnectionId",U.createConnectionIdType()),new m("reducerCall",ue.getTypeScriptAlgebraicType()),new m("energyQuantaUsed",ee.getTypeScriptAlgebraicType()),new m("totalHostExecutionDuration",U.createTimeDurationType())])},fe.serialize=function(e,t){fe.getTypeScriptAlgebraicType().serialize(e,t)},fe.deserialize=function(e){return fe.getTypeScriptAlgebraicType().deserialize(e)},(Te=ge||(ge={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("update",X.getTypeScriptAlgebraicType())])},Te.serialize=function(e,t){Te.getTypeScriptAlgebraicType().serialize(e,t)},Te.deserialize=function(e){return Te.getTypeScriptAlgebraicType().deserialize(e)},(we=be||(be={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableId",U.createU32Type()),new m("tableName",U.createStringType()),new m("tableRows",K.getTypeScriptAlgebraicType())])},we.serialize=function(e,t){we.getTypeScriptAlgebraicType().serialize(e,t)},we.deserialize=function(e){return we.getTypeScriptAlgebraicType().deserialize(e)},(Se=me||(me={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("rows",be.getTypeScriptAlgebraicType())])},Se.serialize=function(e,t){Se.getTypeScriptAlgebraicType().serialize(e,t)},Se.deserialize=function(e){return Se.getTypeScriptAlgebraicType().deserialize(e)},(Ue=Ie||(Ie={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("rows",be.getTypeScriptAlgebraicType())])},Ue.serialize=function(e,t){Ue.getTypeScriptAlgebraicType().serialize(e,t)},Ue.deserialize=function(e){return Ue.getTypeScriptAlgebraicType().deserialize(e)},(ve=Ae||(Ae={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("requestId",U.createOptionType(U.createU32Type())),new m("queryId",U.createOptionType(U.createU32Type())),new m("tableId",U.createOptionType(U.createU32Type())),new m("error",U.createStringType())])},ve.serialize=function(e,t){ve.getTypeScriptAlgebraicType().serialize(e,t)},ve.deserialize=function(e){return ve.getTypeScriptAlgebraicType().deserialize(e)},(_e=ze||(ze={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("update",X.getTypeScriptAlgebraicType())])},_e.serialize=function(e,t){_e.getTypeScriptAlgebraicType().serialize(e,t)},_e.deserialize=function(e){return _e.getTypeScriptAlgebraicType().deserialize(e)},(Fe=Be||(Be={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("update",X.getTypeScriptAlgebraicType())])},Fe.serialize=function(e,t){Fe.getTypeScriptAlgebraicType().serialize(e,t)},Fe.deserialize=function(e){return Fe.getTypeScriptAlgebraicType().deserialize(e)},(Ee=Me||(Me={})).InitialSubscription=e=>({tag:"InitialSubscription",value:e}),Ee.TransactionUpdate=e=>({tag:"TransactionUpdate",value:e}),Ee.TransactionUpdateLight=e=>({tag:"TransactionUpdateLight",value:e}),Ee.IdentityToken=e=>({tag:"IdentityToken",value:e}),Ee.OneOffQueryResponse=e=>({tag:"OneOffQueryResponse",value:e}),Ee.SubscribeApplied=e=>({tag:"SubscribeApplied",value:e}),Ee.UnsubscribeApplied=e=>({tag:"UnsubscribeApplied",value:e}),Ee.SubscriptionError=e=>({tag:"SubscriptionError",value:e}),Ee.SubscribeMultiApplied=e=>({tag:"SubscribeMultiApplied",value:e}),Ee.UnsubscribeMultiApplied=e=>({tag:"UnsubscribeMultiApplied",value:e}),Ee.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("InitialSubscription",se.getTypeScriptAlgebraicType()),new b("TransactionUpdate",he.getTypeScriptAlgebraicType()),new b("TransactionUpdateLight",ge.getTypeScriptAlgebraicType()),new b("IdentityToken",re.getTypeScriptAlgebraicType()),new b("OneOffQueryResponse",oe.getTypeScriptAlgebraicType()),new b("SubscribeApplied",me.getTypeScriptAlgebraicType()),new b("UnsubscribeApplied",Ie.getTypeScriptAlgebraicType()),new b("SubscriptionError",Ae.getTypeScriptAlgebraicType()),new b("SubscribeMultiApplied",ze.getTypeScriptAlgebraicType()),new b("UnsubscribeMultiApplied",Be.getTypeScriptAlgebraicType())])},Ee.serialize=function(e,t){Ee.getTypeScriptAlgebraicType().serialize(e,t)},Ee.deserialize=function(e){return Ee.getTypeScriptAlgebraicType().deserialize(e)};var qe=class{#p=new Map;on(e,t){let r=this.#p.get(e);r||(r=new Set,this.#p.set(e,r)),r.add(t)}off(e,t){let r=this.#p.get(e);r&&r.delete(t)}emit(e,...t){let r=this.#p.get(e);if(r)for(let e of r)e(...t)}},Pe=class{#u=[];#l(e,t){return e&&"object"==typeof e&&"isEqual"in e?e.isEqual(t):e===t}set(e,t){const r=this.#u.findIndex((({key:t})=>this.#l(t,e)));r>-1?this.#u[r].value=t:this.#u.push({key:e,value:t})}get(e){const t=this.#u.find((({key:t})=>this.#l(t,e)));return t?t.value:void 0}delete(e){const t=this.#u.findIndex((({key:t})=>this.#l(t,e)));return t>-1&&(this.#u.splice(t,1),!0)}has(e){return this.#u.some((({key:t})=>this.#l(t,e)))}values(){return this.#u.map((e=>e.value))}entries(){return this.#u}[Symbol.iterator](){let e=0;const t=this.#u;return{next:()=>e<t.length?{value:t[e++],done:!1}:{value:null,done:!0}}}},Re={component:"đĻ",info:"âšī¸",warn:"â ī¸",error:"â",debug:"đ"},De={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;"},Ne={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;"},Le=(e,t)=>{console.log(`%c${Re[e]} ${e.toUpperCase()}%c ${t}`,De[e],Ne[e])},$e=class{rows;tableTypeInfo;emitter;constructor(e){this.tableTypeInfo=e,this.rows=new Map,this.emitter=new qe}count(){return this.rows.size}iter(){return Array.from(this.rows.values()).map((([e])=>e))}applyOperations=(e,t)=>{const r=[];if(void 0!==this.tableTypeInfo.primaryKey){const i=this.tableTypeInfo.primaryKey,s=new Pe,n=new Pe;for(const t of e)if("insert"===t.type){const[e,r]=s.get(t.row[i])||[t,0];s.set(t.row[i],[t,r+1])}else{const[e,r]=n.get(t.row[i])||[t,0];n.set(t.row[i],[t,r+1])}for(const{key:e,value:[i,a]}of s){const s=n.get(e);if(s){const[c,o]=s,p=a-o,u=this.update(t,i,c,p);u&&r.push(u),n.delete(e)}else{const e=this.insert(t,i,a);e&&r.push(e)}}for(const[e,i]of n.values()){const s=this.delete(t,e,i);s&&r.push(s)}}else for(const i of e)if("insert"===i.type){const e=this.insert(t,i);e&&r.push(e)}else{const e=this.delete(t,i);e&&r.push(e)}return r};update=(e,t,r,i=0)=>{const[s,n]=this.rows.get(r.rowId)||[r.row,0],a=Math.max(1,n+i);return this.rows.delete(r.rowId),this.rows.set(t.rowId,[t.row,a]),0===n?(Le("error","Updating a row that was not present in the cache"),{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}):(n+i<=0&&Le("error","Negative reference count for row"),{type:"update",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("update",e,s,t.row)}})};insert=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(this.rows.set(t.rowId,[t.row,s+r]),0===s)return{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}};delete=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(0!==s)return s<=r?(this.rows.delete(t.rowId),{type:"delete",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("delete",e,t.row)}}):void this.rows.set(t.rowId,[t.row,s-r]);Le("warn","Deleting a row that was not present in the cache")};onInsert=e=>{this.emitter.on("insert",e)};onDelete=e=>{this.emitter.on("delete",e)};onUpdate=e=>{this.emitter.on("update",e)};removeOnInsert=e=>{this.emitter.off("insert",e)};removeOnDelete=e=>{this.emitter.off("delete",e)};removeOnUpdate=e=>{this.emitter.off("update",e)}},We=class{tables;constructor(){this.tables=new Map}getTable(e){const t=this.tables.get(e);if(!t)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${e} does not exist`);return t}getOrCreateTable(e){let t;return this.tables.has(e.tableName)?t=this.tables.get(e.tableName):(t=new $e(e),this.tables.set(e.tableName,t)),t}};async function He(e,t,r=131072){let i=0;const s=new ReadableStream({pull(t){if(i<e.length){const s=e.subarray(i,Math.min(i+r,e.length));t.enqueue(s),i+=r}else t.close()}}),n=new DecompressionStream(t),a=s.pipeThrough(n).getReader(),c=[];let o,p=0;for(;!(o=await a.read()).done;)c.push(o.value),p+=o.value.length;const u=new Uint8Array(p);let l=0;for(const e of c)u.set(e,l),l+=e.length;return u}var Qe=class e{onclose;onopen;onmessage;onerror;#y;async#d(e){const t=new Uint8Array(e.data);let r;if(0===t[0])r=t.slice(1);else{if(1===t[0])throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");if(2!==t[0])throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`");r=await He(t.slice(1),"gzip")}this.onmessage?.({data:r})}#h(e){this.onopen?.(e)}#f(e){this.onerror?.(e)}send(e){this.#y.send(e)}close(){this.#y.close()}constructor(e){this.onmessage=void 0,this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,e.onmessage=this.#d.bind(this),e.onerror=this.#f.bind(this),e.onclose=this.#f.bind(this),e.onopen=this.#h.bind(this),e.binaryType="arraybuffer",this.#y=e}static async createWebSocketFn({url:t,nameOrAddress:r,wsProtocol:i,authToken:s,compression:n,lightMode:a}){const c=new Headers;let o,p;if(o="false"===import.meta.env.BROWSER?"WebSocket"in globalThis?WebSocket:(await import("undici")).WebSocket:WebSocket,s){c.set("Authorization",`Bearer ${s}`);const e=new URL("v1/identity/websocket-token",t);e.protocol="wss:"===t.protocol?"https:":"http:";const r=await fetch(e,{method:"POST",headers:c});if(!r.ok)return Promise.reject(new Error(`Failed to verify token: ${r.statusText}`));{const{token:e}=await r.json();p=e}}const u=new URL(`v1/database/${r}/subscribe`,t);p&&u.searchParams.set("token",p),u.searchParams.set("compression","gzip"===n?"Gzip":"None"),a&&u.searchParams.set("light","true");const l=new o(u,i);return new e(l)}},Ve=class{constructor(e,t){this.remoteModule=e,this.dbConnectionConstructor=t,this.#g=Qe.createWebSocketFn}#T;#b;#w;#m;#S=new qe;#I="gzip";#U=!1;#g;withUri(e){return this.#T=new URL(e),this}withModuleName(e){return this.#b=e,this}withToken(e){return this.#m=e,this}withWSFn(e){return this.#g=e,this}withCompression(e){return this.#I=e,this}withLightMode(e){return this.#U=e,this}onConnect(e){return this.#S.on("connect",e),this}onConnectError(e){return this.#S.on("connectError",e),this}onDisconnect(e){return this.#S.on("disconnect",e),this}build(){if(!this.#T)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#b)throw new Error("Database name or address is required to connect to SpacetimeDB");return this.dbConnectionConstructor(new Je({uri:this.#T,nameOrAddress:this.#b,identity:this.#w,token:this.#m,emitter:this.#S,compression:this.#I,lightMode:this.#U,createWSFn:this.#g,remoteModule:this.remoteModule}))}},je=class{constructor(e){this.db=e}#A=void 0;#v=void 0;onApplied(e){return this.#A=e,this}onError(e){return this.#v=e,this}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("Subscriptions must have at least one query");return new Ze(this.db,t,this.#A,this.#v)}subscribeToAllTables(){this.subscribe("SELECT * FROM *")}},Ge=class{subscriptions=new Map},Ze=class{constructor(e,t,r,i){this.db=e,this.#S.on("applied",(e=>{this.#z=!0,r&&r(e)})),this.#S.on("error",((e,t)=>{this.#z=!1,this.#_=!0,i&&i(e,t)})),this.#B=this.db.registerSubscription(this,this.#S,t)}#B;#F=!1;#_=!1;#z=!1;#S=new qe;unsubscribe(){if(this.#F)throw new Error("Unsubscribe has already been called");this.#F=!0,this.db.unregisterSubscription(this.#B),this.#S.on("end",(e=>{this.#_=!0,this.#z=!1}))}unsubscribeThen(e){if(this.#_)throw new Error("Subscription has already ended");if(this.#F)throw new Error("Unsubscribe has already been called");this.#F=!0,this.db.unregisterSubscription(this.#B),this.#S.on("end",(t=>{this.#_=!0,this.#z=!1,e(t)}))}isEnded(){return this.#_}isActive(){return this.#z}};function Ke(e){switch(e){case"FullUpdate":return 0;case"NoSuccessNotify":return 1}}var Je=class{isActive=!1;identity=void 0;token=void 0;db;reducers;setReducerFlags;connectionId=l.random();#B=0;#S;#M=new qe;#A;#E;#k=Promise.resolve();#x=new Ge;clientCache;ws;wsPromise;constructor({uri:e,nameOrAddress:t,identity:r,token:i,emitter:s,remoteModule:n,createWSFn:a,compression:c,lightMode:o}){Le("info","Connecting to SpacetimeDB WS...");let p=new URL(e);/^wss?:/.test(e.protocol)||(p.protocol="https:"===p.protocol?"wss:":"ws:"),this.identity=r,this.token=i,this.#E=n,this.#S=s;let u=this.connectionId.toHexString();p.searchParams.set("connection_id",u),this.clientCache=new We,this.db=this.#E.dbViewConstructor(this),this.setReducerFlags=this.#E.setReducerFlagsConstructor(),this.reducers=this.#E.reducersConstructor(this,this.setReducerFlags),this.wsPromise=a({url:p,nameOrAddress:t,wsProtocol:"v1.bsatn.spacetimedb",authToken:i,compression:c,lightMode:o}).then((e=>(this.ws=e,this.ws.onclose=()=>{this.#S.emit("disconnect",this)},this.ws.onerror=e=>{this.#S.emit("connectError",this,e)},this.ws.onopen=this.#h.bind(this),this.ws.onmessage=this.#d.bind(this),e))).catch((e=>{Le("error","Error connecting to SpacetimeDB WS"),this.#S.emit("connectError",this,e)}))}#C=()=>{const e=this.#B;return this.#B+=1,e};subscriptionBuilder=()=>new je(this);registerSubscription(e,t,r){const i=this.#C();return this.#x.subscriptions.set(i,{handle:e,emitter:t}),this.#O(H.SubscribeMulti({queryStrings:r,queryId:{id:i},requestId:0})),i}unregisterSubscription(e){this.#O(H.UnsubscribeMulti({queryId:{id:e},requestId:0}))}async#q(t){const r=(t,r,i)=>{const s=i.rowsData,n=new e(s),a=[],c=this.#E.tables[r].rowType;for(;n.offset<s.length+s.byteOffset;){const e=c.deserialize(n),r=JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));a.push({type:t,rowId:r,row:e})}return a},i=async t=>{const i=t.tableName;let s=[];for(const n of t.updates){let t;if("Gzip"===n.tag){const r=await He(n.value,"gzip");t=V.deserialize(new e(r))}else{if("Brotli"===n.tag)throw new Error("Brotli compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");t=n.value}s=s.concat(r("insert",i,t.inserts)),s=s.concat(r("delete",i,t.deletes))}return{tableName:i,operations:s}},s=async e=>{const t=[];for(const r of e.tables)t.push(await i(r));return t};switch(t.tag){case"InitialSubscription":{const e=t.value.databaseUpdate;return{tag:"InitialSubscription",tableUpdates:await s(e)}}case"TransactionUpdateLight":{const e=t.value.update;return{tag:"TransactionUpdateLight",tableUpdates:await s(e)}}case"TransactionUpdate":{const e=t.value,r=e.callerIdentity,i=l.nullIfZero(e.callerConnectionId),n=e.reducerCall.reducerName,a=e.reducerCall.args,c=e.energyQuantaUsed;let o,p,u="";switch(e.status.tag){case"Committed":o=await s(e.status.value);break;case"Failed":o=[],u=e.status.value;break;case"OutOfEnergy":o=[]}if("<none>"===n){let e=u;return void console.error(`Received an error from the database: ${e}`)}""!==n&&(p={reducerName:n,args:a});return{tag:"TransactionUpdate",tableUpdates:o,identity:r,connectionId:i,reducerInfo:p,status:e.status,energyConsumed:c.quanta,message:u,timestamp:e.timestamp}}case"IdentityToken":return{tag:"IdentityToken",identity:t.value.identity,token:t.value.token,connectionId:t.value.connectionId};case"OneOffQueryResponse":throw new Error(`TypeScript SDK never sends one-off queries, but got OneOffQueryResponse ${t}`);case"SubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"SubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"UnsubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"UnsubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"SubscriptionError":return{tag:"SubscriptionError",queryId:t.value.queryId,error:t.value.error}}}#O(e){this.wsPromise.then((r=>{if(r){const i=new t(1024);H.serialize(i,e);const s=i.getBuffer();r.send(s)}}))}#h(){this.isActive=!0}#P(e,t){const r=[];for(let i of e){const e=i.tableName,s=this.#E.tables[e],n=this.clientCache.getOrCreateTable(s);r.push(...n.applyOperations(i.operations,t))}return r}async#R(t){const r=function(t,r){const i=new e(r);return t.deserialize(i)}(Me,t),i=await this.#q(r);if(i)switch(i.tag){case"InitialSubscription":{let e={tag:"SubscribeApplied"};const t=this.#E.eventContextConstructor(this,e),{event:r,...s}=t,n=this.#P(i.tableUpdates,t);this.#S&&this.#A?.(s);for(const e of n)e.cb();break}case"TransactionUpdateLight":{let e={tag:"UnknownTransaction"};const t=this.#E.eventContextConstructor(this,e),r=this.#P(i.tableUpdates,t);for(const e of r)e.cb();break}case"TransactionUpdate":{let t,r,s=i.reducerInfo,n=!1;if(s){r=this.#E.reducers[s.reducerName];try{const i=new e(s.args);t=r.argsType.deserialize(i)}catch{console.debug("Failed to deserialize reducer arguments"),n=!0}}else n=!0;if(n){const e={tag:"UnknownTransaction"},t=this.#E.eventContextConstructor(this,e),r=this.#P(i.tableUpdates,t);for(const e of r)e.cb();return}const a={callerIdentity:i.identity,status:i.status,callerConnectionId:i.connectionId,timestamp:i.timestamp,energyConsumed:i.energyConsumed,reducer:{name:s.reducerName,args:t}},c={tag:"Reducer",value:a},o=this.#E.eventContextConstructor(this,c),p={...o,event:a},u=this.#P(i.tableUpdates,o),l=[];r.argsType.product.elements.forEach(((e,r)=>{l.push(t[e.name])})),this.#M.emit(s.reducerName,p,...l);for(const e of u)e.cb();break}case"IdentityToken":this.identity=i.identity,!this.token&&i.token&&(this.token=i.token),this.connectionId=i.connectionId,this.#S.emit("connect",this,this.identity,this.token);break;case"SubscribeApplied":{const e=this.#x.subscriptions.get(i.queryId);if(void 0===e){Le("error",`Received SubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"SubscribeApplied"},r=this.#E.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#P(i.tableUpdates,r);e?.emitter.emit("applied",n);for(const e of a)e.cb();break}case"UnsubscribeApplied":{const e=this.#x.subscriptions.get(i.queryId);if(void 0===e){Le("error",`Received UnsubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"UnsubscribeApplied"},r=this.#E.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#P(i.tableUpdates,r);e?.emitter.emit("end",n),this.#x.subscriptions.delete(i.queryId);for(const e of a)e.cb();break}case"SubscriptionError":{const e=Error(i.error),t={tag:"Error",value:e},r={...this.#E.eventContextConstructor(this,t),event:e};void 0!==i.queryId?(this.#x.subscriptions.get(i.queryId)?.emitter.emit("error",r,e),this.#x.subscriptions.delete(i.queryId)):(console.error("Received an error message without a queryId: ",e),this.#x.subscriptions.forEach((({emitter:t})=>{t.emit("error",r,e)})))}}}#d(e){this.#k=this.#k.then((()=>this.#R(e.data)))}callReducer(e,t,r){const i=H.CallReducer({reducer:e,args:t,requestId:0,flags:Ke(r)});this.#O(i)}disconnect(){this.wsPromise.then((e=>{e&&e.close()}))}#D(e,t){this.#S.on(e,t)}#N(e,t){this.#S.off(e,t)}#L(e){this.#S.on("connect",e)}#$(e){this.#S.on("disconnect",e)}#W(e){this.#S.on("connectError",e)}#H(e){this.#S.off("connect",e)}#Q(e){this.#S.off("disconnect",e)}#V(e){this.#S.off("connectError",e)}onReducer(e,t){this.#M.on(e,t)}offReducer(e,t){this.#M.off(e,t)}};export{U as AlgebraicType,Oe as AlgebraicValue,e as BinaryReader,t as BinaryWriter,We as ClientCache,l as ConnectionId,Ve as DbConnectionBuilder,Je as DbConnectionImpl,h as Identity,S as ProductType,m as ProductTypeElement,Ce as ProductValue,p as ScheduleAt,je as SubscriptionBuilderImpl,w as SumType,b as SumTypeVariant,$e as TableCache,y as TimeDuration,d as Timestamp,r as deepEqual};//# sourceMappingURL=index.js.map | ||
| import{fromByteArray as e}from"base64-js";var t=class{#e;#t=0;constructor(e){this.#e=new DataView(e.buffer),this.#t=e.byteOffset}get offset(){return this.#t}readUInt8Array(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e);return this.#t+=e,t}readBool(){const e=this.#e.getUint8(this.#t);return this.#t+=1,0!==e}readByte(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readBytes(e){const t=new DataView(this.#e.buffer,this.#t,e);return this.#t+=e,new Uint8Array(t.buffer)}readI8(){const e=this.#e.getInt8(this.#t);return this.#t+=1,e}readU8(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readI16(){const e=this.#e.getInt16(this.#t,!0);return this.#t+=2,e}readU16(){const e=this.#e.getUint16(this.#t,!0);return this.#t+=2,e}readI32(){const e=this.#e.getInt32(this.#t,!0);return this.#t+=4,e}readU32(){const e=this.#e.getUint32(this.#t,!0);return this.#t+=4,e}readI64(){const e=this.#e.getBigInt64(this.#t,!0);return this.#t+=8,e}readU64(){const e=this.#e.getBigUint64(this.#t,!0);return this.#t+=8,e}readU128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readI128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigInt64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readU256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigUint64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readI256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigInt64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readF32(){const e=this.#e.getFloat32(this.#t,!0);return this.#t+=4,e}readF64(){const e=this.#e.getFloat64(this.#t,!0);return this.#t+=8,e}readString(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e),r=new TextDecoder("utf-8").decode(t);return this.#t+=e,r}},r=class{#e;#r;#t=0;constructor(e){this.#e=new Uint8Array(e),this.#r=new DataView(this.#e.buffer)}#i(e){const t=this.#t+e+1;if(t<=this.#e.length)return;let r=2*this.#e.length;r<t&&(r=t);const i=new Uint8Array(r);i.set(this.#e),this.#e=i,this.#r=new DataView(this.#e.buffer)}toBase64(){return e(this.#e.subarray(0,this.#t))}getBuffer(){return this.#e.slice(0,this.#t)}writeUInt8Array(e){const t=e.length;this.#i(4+t),this.writeU32(t),this.#e.set(e,this.#t),this.#t+=e.length}writeBool(e){this.#i(1),this.#r.setUint8(this.#t,e?1:0),this.#t+=1}writeByte(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI8(e){this.#i(1),this.#r.setInt8(this.#t,e),this.#t+=1}writeU8(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI16(e){this.#i(2),this.#r.setInt16(this.#t,e,!0),this.#t+=2}writeU16(e){this.#i(2),this.#r.setUint16(this.#t,e,!0),this.#t+=2}writeI32(e){this.#i(4),this.#r.setInt32(this.#t,e,!0),this.#t+=4}writeU32(e){this.#i(4),this.#r.setUint32(this.#t,e,!0),this.#t+=4}writeI64(e){this.#i(8),this.#r.setBigInt64(this.#t,e,!0),this.#t+=8}writeU64(e){this.#i(8),this.#r.setBigUint64(this.#t,e,!0),this.#t+=8}writeU128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigUint64(this.#t,t,!0),this.#r.setBigUint64(this.#t+8,r,!0),this.#t+=16}writeI128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigInt64(this.#t,t,!0),this.#r.setBigInt64(this.#t+8,r,!0),this.#t+=16}writeU256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigUint64(this.#t+24,n,!0),this.#t+=32}writeI256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigInt64(this.#t+24,n,!0),this.#t+=32}writeF32(e){this.#i(4),this.#r.setFloat32(this.#t,e,!0),this.#t+=4}writeF64(e){this.#i(8),this.#r.setFloat64(this.#t,e,!0),this.#t+=8}writeString(e){const t=(new TextEncoder).encode(e);this.writeU32(t.length),this.#i(t.length),this.#e.set(t,this.#t),this.#t+=t.length}};function i(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let n of r)if(!s.includes(n)||!i(e[n],t[n]))return!1;return!0}function s(e){return Array.prototype.map.call(e.reverse(),(e=>("00"+e.toString(16)).slice(-2))).join("")}function n(e){e.startsWith("0x")&&(e=e.slice(2));let t=e.match(/.{1,2}/g)||[],r=Uint8Array.from(t.map((e=>parseInt(e,16))));return 32!=r.length?new Uint8Array(0):r.reverse()}function a(e){return function(e){if(16!=e.length)throw new Error(`Uint8Array is not 16 bytes long: ${e}`);return new t(e).readU128()}(n(e))}function o(e){return function(e){if(32!=e.length)throw new Error(`Uint8Array is not 32 bytes long: [${e}]`);return new t(e).readU256()}(n(e))}function c(e){let t=new r(16);return t.writeU128(e),t.getBuffer()}function p(e){let t=new r(32);return t.writeU256(e),t.getBuffer()}var u,l,y=class e{data;get __connection_id__(){return this.data}constructor(e){this.data=e}isZero(){return this.data===BigInt(0)}static nullIfZero(e){return e.isZero()?null:e}static random(){let t=BigInt(0);for(let e=0;e<16;e++)t=t<<BigInt(8)|BigInt(Math.floor(255*Math.random()));return new e(t)}isEqual(e){return this.data==e.data}toHexString(){return s(c(this.data))}toUint8Array(){return c(this.data)}static fromString(t){return new e(a(t))}static fromStringOrNull(t){let r=e.fromString(t);return r.isZero()?null:r}},h=class e{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/e.MICROS_PER_MILLIS)}constructor(e){this.__time_duration_micros__=e}static fromMillis(t){return new e(BigInt(t)*e.MICROS_PER_MILLIS)}},d=class e{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(e){this.__timestamp_micros_since_unix_epoch__=e}static UNIX_EPOCH=new e(0n);static now(){return e.fromDate(new Date)}static fromDate(t){const r=t.getTime(),i=BigInt(r)*e.MICROS_PER_MILLIS;return new e(i)}toDate(){const t=this.__timestamp_micros_since_unix_epoch__/e.MICROS_PER_MILLIS;if(t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError("Timestamp is outside of the representable range of JS's Date");return new Date(Number(t))}},f=class e{data;get __identity__(){return this.data}constructor(e){this.data="string"==typeof e?o(e):e}isEqual(e){return this.toHexString()===e.toHexString()}toHexString(){return s(p(this.data))}toUint8Array(){return p(this.data)}static fromString(t){return new e(t)}};(l=u||(u={})).getAlgebraicType=function(){return A.createSumType([new w("Interval",A.createU64Type()),new w("Time",A.createU64Type())])},l.serialize=function(e){switch(e.tag){case"Interval":return{Interval:e.value};case"Time":return{Time:e.value};default:throw"unreachable"}},l.Interval=e=>({tag:"Interval",value:e}),l.Time=e=>({tag:"Time",value:e}),l.fromValue=function(e){let t=e.asSumValue();switch(t.tag){case 0:return{tag:"Interval",value:t.value.asBigInt()};case 1:return{tag:"Time",value:t.value.asBigInt()};default:throw"unreachable"}};var g,T,b=u,w=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},m=class{variants;constructor(e){this.variants=e}serialize=(e,t)=>{if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name)null!=t?(e.writeByte(0),this.variants[0].algebraicType.serialize(e,t)):e.writeByte(1);else{let r=t.tag;const i=this.variants.findIndex((e=>e.name===r));if(i<0)throw`Can't serialize a sum type, couldn't find ${t.tag} tag`;e.writeU8(i),this.variants[i].algebraicType.serialize(e,t.value)}};deserialize=e=>{let t=e.readU8();if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name){if(0===t)return this.variants[0].algebraicType.deserialize(e);if(1===t)return;throw`Can't deserialize an option type, couldn't find ${t} tag`}{let r=this.variants[t],i=r.algebraicType.deserialize(e);return{tag:r.name,value:i}}}},S=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},I=class{elements;constructor(e){this.elements=e}isEmpty(){return 0===this.elements.length}serialize=(e,t)=>{for(let r of this.elements)r.algebraicType.serialize(e,t[r.name])};intoMapKey(e){if(1===this.elements.length){if("__time_duration_micros__"===this.elements[0].name)return e.__time_duration_micros__;if("__timestamp_micros_since_unix_epoch__"===this.elements[0].name)return e.__timestamp_micros_since_unix_epoch__;if("__identity__"===this.elements[0].name)return e.__identity__;if("__connection_id__"===this.elements[0].name)return e.__connection_id__}const t=new r(10);return this.serialize(t,e),t.toBase64()}deserialize=e=>{let t={};if(1===this.elements.length){if("__time_duration_micros__"===this.elements[0].name)return new h(e.readI64());if("__timestamp_micros_since_unix_epoch__"===this.elements[0].name)return new d(e.readI64());if("__identity__"===this.elements[0].name)return new f(e.readU256());if("__connection_id__"===this.elements[0].name)return new y(e.readU128())}for(let r of this.elements)t[r.name]=r.algebraicType.deserialize(e);return t}},U=class{keyType;valueType;constructor(e,t){this.keyType=e,this.valueType=t}},A=class e{type;type_;#s(e,t){this.type_=t,this.type=void 0===t?Ce.None:e}get product(){if(this.type!==Ce.ProductType)throw"product type was requested, but the type is not ProductType";return this.type_}set product(e){this.#s(Ce.ProductType,e)}get sum(){if(this.type!==Ce.SumType)throw"sum type was requested, but the type is not SumType";return this.type_}set sum(e){this.#s(Ce.SumType,e)}get array(){if(this.type!==Ce.ArrayType)throw"array type was requested, but the type is not ArrayType";return this.type_}set array(e){this.#s(Ce.ArrayType,e)}get map(){if(this.type!==Ce.MapType)throw"map type was requested, but the type is not MapType";return this.type_}set map(e){this.#s(Ce.MapType,e)}static#n(t,r){let i=new e;return i.#s(t,r),i}static createProductType(e){return this.#n(Ce.ProductType,new I(e))}static createSumType(e){return this.#n(Ce.SumType,new m(e))}static createArrayType(e){return this.#n(Ce.ArrayType,e)}static createMapType(e,t){return this.#n(Ce.MapType,new U(e,t))}static createBoolType(){return this.#n(Ce.Bool,null)}static createI8Type(){return this.#n(Ce.I8,null)}static createU8Type(){return this.#n(Ce.U8,null)}static createI16Type(){return this.#n(Ce.I16,null)}static createU16Type(){return this.#n(Ce.U16,null)}static createI32Type(){return this.#n(Ce.I32,null)}static createU32Type(){return this.#n(Ce.U32,null)}static createI64Type(){return this.#n(Ce.I64,null)}static createU64Type(){return this.#n(Ce.U64,null)}static createI128Type(){return this.#n(Ce.I128,null)}static createU128Type(){return this.#n(Ce.U128,null)}static createI256Type(){return this.#n(Ce.I256,null)}static createU256Type(){return this.#n(Ce.U256,null)}static createF32Type(){return this.#n(Ce.F32,null)}static createF64Type(){return this.#n(Ce.F64,null)}static createStringType(){return this.#n(Ce.String,null)}static createBytesType(){return this.createArrayType(this.createU8Type())}static createOptionType(e){return this.createSumType([new w("some",e),new w("none",this.createProductType([]))])}static createIdentityType(){return this.createProductType([new S("__identity__",this.createU256Type())])}static createConnectionIdType(){return this.createProductType([new S("__connection_id__",this.createU128Type())])}static createScheduleAtType(){return b.getAlgebraicType()}static createTimestampType(){return this.createProductType([new S("__timestamp_micros_since_unix_epoch__",this.createI64Type())])}static createTimeDurationType(){return this.createProductType([new S("__time_duration_micros__",this.createI64Type())])}isProductType(){return this.type===Ce.ProductType}isSumType(){return this.type===Ce.SumType}isArrayType(){return this.type===Ce.ArrayType}isMapType(){return this.type===Ce.MapType}#a(){return this.isArrayType()&&this.array.type==Ce.U8}#o(e){return this.isProductType()&&1===this.product.elements.length&&(this.product.elements[0].algebraicType.type==Ce.U128||this.product.elements[0].algebraicType.type==Ce.U256)&&this.product.elements[0].name===e}#c(e){return this.isProductType()&&1===this.product.elements.length&&this.product.elements[0].algebraicType.type===Ce.I64&&this.product.elements[0].name===e}isIdentity(){return this.#o("__identity__")}isConnectionId(){return this.#o("__connection_id__")}isScheduleAt(){return this.isSumType()&&2===this.sum.variants.length&&"Interval"===this.sum.variants[0].name&&this.sum.variants[0].algebraicType.type===Ce.U64&&"Time"===this.sum.variants[1].name&&this.sum.variants[1].algebraicType.type===Ce.U64}isTimestamp(){return this.#c("__timestamp_micros_since_unix_epoch__")}isTimeDuration(){return this.#c("__time_duration_micros__")}intoMapKey(e){switch(this.type){case Ce.U8:case Ce.U16:case Ce.U32:case Ce.U64:case Ce.U128:case Ce.U256:case Ce.I8:case Ce.I16:case Ce.I64:case Ce.I128:case Ce.F32:case Ce.F64:case Ce.String:case Ce.Bool:return e;case Ce.ProductType:return this.product.intoMapKey(e);default:const t=new r(10);return this.serialize(t,e),t.toBase64()}}serialize(e,t){switch(this.type){case Ce.ProductType:this.product.serialize(e,t);break;case Ce.SumType:this.sum.serialize(e,t);break;case Ce.ArrayType:if(this.#a())e.writeUInt8Array(t);else{const r=this.array;e.writeU32(t.length);for(let i of t)r.serialize(e,i)}break;case Ce.MapType:throw new Error("not implemented");case Ce.Bool:e.writeBool(t);break;case Ce.I8:e.writeI8(t);break;case Ce.U8:e.writeU8(t);break;case Ce.I16:e.writeI16(t);break;case Ce.U16:e.writeU16(t);break;case Ce.I32:e.writeI32(t);break;case Ce.U32:e.writeU32(t);break;case Ce.I64:e.writeI64(t);break;case Ce.U64:e.writeU64(t);break;case Ce.I128:e.writeI128(t);break;case Ce.U128:e.writeU128(t);break;case Ce.I256:e.writeI256(t);break;case Ce.U256:e.writeU256(t);break;case Ce.F32:e.writeF32(t);break;case Ce.F64:e.writeF64(t);break;case Ce.String:e.writeString(t);break;default:throw new Error(`not implemented, ${this.type}`)}}deserialize(e){switch(this.type){case Ce.ProductType:return this.product.deserialize(e);case Ce.SumType:return this.sum.deserialize(e);case Ce.ArrayType:if(this.#a())return e.readUInt8Array();{const t=this.array,r=e.readU32();let i=[];for(let s=0;s<r;s++)i.push(t.deserialize(e));return i}case Ce.MapType:throw new Error("not implemented");case Ce.Bool:return e.readBool();case Ce.I8:return e.readI8();case Ce.U8:return e.readU8();case Ce.I16:return e.readI16();case Ce.U16:return e.readU16();case Ce.I32:return e.readI32();case Ce.U32:return e.readU32();case Ce.I64:return e.readI64();case Ce.U64:return e.readU64();case Ce.I128:return e.readI128();case Ce.U128:return e.readU128();case Ce.U256:return e.readU256();case Ce.F32:return e.readF32();case Ce.F64:return e.readF64();case Ce.String:return e.readString();default:throw new Error(`not implemented, ${this.type}`)}}};g=A||(A={}),(T=g.Type||(g.Type={})).SumType="SumType",T.ProductType="ProductType",T.ArrayType="ArrayType",T.MapType="MapType",T.Bool="Bool",T.I8="I8",T.U8="U8",T.I16="I16",T.U16="U16",T.I32="I32",T.U32="U32",T.I64="I64",T.U64="U64",T.I128="I128",T.U128="U128",T.I256="I256",T.U256="U256",T.F32="F32",T.F64="F64",T.String="String",T.None="None";var v,_,z,B,F,M,E,x,C,O,k,P,q,R,N,D,$,L,j,W,H,Q,V,Z,G,K,X,J,Y,ee,te,re,ie,se,ne,ae,oe,ce,pe,ue,le,ye,he,de,fe,ge,Te,be,we,me,Se,Ie,Ue,Ae,ve,_e,ze,Be,Fe,Me,Ee,xe,Ce=A.Type,Oe=class{tag;value;constructor(e,t){this.tag=e,this.value=t}static deserialize(e,t){return t.readSum(e)}},ke=class{elements;constructor(e){this.elements=e}static deserialize(e,t){return t.readProduct(e)}},Pe=class{value;constructor(e){if(void 0===e)throw"value is undefined";this.value=e}callMethod(e){return this[e]()}static deserialize(e,t){switch(e.type){case A.Type.ProductType:return new this(ke.deserialize(e.product,t));case A.Type.SumType:return new this(Oe.deserialize(e.sum,t));case A.Type.ArrayType:let r=e.array;return r.type===A.Type.U8?new this(t.readUInt8Array()):new this(t.readArray(r));case A.Type.MapType:let i=e.map;return new this(t.readMap(i.keyType,i.valueType));case A.Type.Bool:return new this(t.readBool());case A.Type.I8:return new this(t.readI8());case A.Type.U8:return new this(t.readU8());case A.Type.I16:return new this(t.readI16());case A.Type.U16:return new this(t.readU16());case A.Type.I32:return new this(t.readI32());case A.Type.U32:return new this(t.readU32());case A.Type.I64:return new this(t.readI64());case A.Type.U64:return new this(t.readU64());case A.Type.I128:return new this(t.readI128());case A.Type.U128:return new this(t.readU128());case A.Type.String:return new this(t.readString());default:throw new Error(`not implemented, ${e.type}`)}}asProductValue(){return this.value}asField(e){return this.asProductValue().elements[e]}asSumValue(){return this.value}asArray(){return this.value}asMap(){return this.value}asString(){return this.value}asBoolean(){return this.value}asNumber(){return this.value}asBytes(){return this.value}asBigInt(){return this.value}asIdentity(){return new f(this.asField(0).asBigInt())}asConnectionId(){return new y(this.asField(0).asBigInt())}asScheduleAt(){return u.fromValue(this)}};(_=v||(v={})).FixedSize=e=>({tag:"FixedSize",value:e}),_.RowOffsets=e=>({tag:"RowOffsets",value:e}),_.getTypeScriptAlgebraicType=function(){return A.createSumType([new w("FixedSize",A.createU16Type()),new w("RowOffsets",A.createArrayType(A.createU64Type()))])},_.serialize=function(e,t){_.getTypeScriptAlgebraicType().serialize(e,t)},_.deserialize=function(e){return _.getTypeScriptAlgebraicType().deserialize(e)},(B=z||(z={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("sizeHint",v.getTypeScriptAlgebraicType()),new S("rowsData",A.createArrayType(A.createU8Type()))])},B.serialize=function(e,t){B.getTypeScriptAlgebraicType().serialize(e,t)},B.deserialize=function(e){return B.getTypeScriptAlgebraicType().deserialize(e)},(M=F||(F={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("reducer",A.createStringType()),new S("args",A.createArrayType(A.createU8Type())),new S("requestId",A.createU32Type()),new S("flags",A.createU8Type())])},M.serialize=function(e,t){M.getTypeScriptAlgebraicType().serialize(e,t)},M.deserialize=function(e){return M.getTypeScriptAlgebraicType().deserialize(e)},(x=E||(E={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("queryStrings",A.createArrayType(A.createStringType())),new S("requestId",A.createU32Type())])},x.serialize=function(e,t){x.getTypeScriptAlgebraicType().serialize(e,t)},x.deserialize=function(e){return x.getTypeScriptAlgebraicType().deserialize(e)},(O=C||(C={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("messageId",A.createArrayType(A.createU8Type())),new S("queryString",A.createStringType())])},O.serialize=function(e,t){O.getTypeScriptAlgebraicType().serialize(e,t)},O.deserialize=function(e){return O.getTypeScriptAlgebraicType().deserialize(e)},(P=k||(k={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("id",A.createU32Type())])},P.serialize=function(e,t){P.getTypeScriptAlgebraicType().serialize(e,t)},P.deserialize=function(e){return P.getTypeScriptAlgebraicType().deserialize(e)},(R=q||(q={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("query",A.createStringType()),new S("requestId",A.createU32Type()),new S("queryId",k.getTypeScriptAlgebraicType())])},R.serialize=function(e,t){R.getTypeScriptAlgebraicType().serialize(e,t)},R.deserialize=function(e){return R.getTypeScriptAlgebraicType().deserialize(e)},(D=N||(N={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("queryStrings",A.createArrayType(A.createStringType())),new S("requestId",A.createU32Type()),new S("queryId",k.getTypeScriptAlgebraicType())])},D.serialize=function(e,t){D.getTypeScriptAlgebraicType().serialize(e,t)},D.deserialize=function(e){return D.getTypeScriptAlgebraicType().deserialize(e)},(L=$||($={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("queryId",k.getTypeScriptAlgebraicType())])},L.serialize=function(e,t){L.getTypeScriptAlgebraicType().serialize(e,t)},L.deserialize=function(e){return L.getTypeScriptAlgebraicType().deserialize(e)},(W=j||(j={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("queryId",k.getTypeScriptAlgebraicType())])},W.serialize=function(e,t){W.getTypeScriptAlgebraicType().serialize(e,t)},W.deserialize=function(e){return W.getTypeScriptAlgebraicType().deserialize(e)},(Q=H||(H={})).CallReducer=e=>({tag:"CallReducer",value:e}),Q.Subscribe=e=>({tag:"Subscribe",value:e}),Q.OneOffQuery=e=>({tag:"OneOffQuery",value:e}),Q.SubscribeSingle=e=>({tag:"SubscribeSingle",value:e}),Q.SubscribeMulti=e=>({tag:"SubscribeMulti",value:e}),Q.Unsubscribe=e=>({tag:"Unsubscribe",value:e}),Q.UnsubscribeMulti=e=>({tag:"UnsubscribeMulti",value:e}),Q.getTypeScriptAlgebraicType=function(){return A.createSumType([new w("CallReducer",F.getTypeScriptAlgebraicType()),new w("Subscribe",E.getTypeScriptAlgebraicType()),new w("OneOffQuery",C.getTypeScriptAlgebraicType()),new w("SubscribeSingle",q.getTypeScriptAlgebraicType()),new w("SubscribeMulti",N.getTypeScriptAlgebraicType()),new w("Unsubscribe",$.getTypeScriptAlgebraicType()),new w("UnsubscribeMulti",j.getTypeScriptAlgebraicType())])},Q.serialize=function(e,t){Q.getTypeScriptAlgebraicType().serialize(e,t)},Q.deserialize=function(e){return Q.getTypeScriptAlgebraicType().deserialize(e)},(Z=V||(V={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("deletes",z.getTypeScriptAlgebraicType()),new S("inserts",z.getTypeScriptAlgebraicType())])},Z.serialize=function(e,t){Z.getTypeScriptAlgebraicType().serialize(e,t)},Z.deserialize=function(e){return Z.getTypeScriptAlgebraicType().deserialize(e)},(K=G||(G={})).Uncompressed=e=>({tag:"Uncompressed",value:e}),K.Brotli=e=>({tag:"Brotli",value:e}),K.Gzip=e=>({tag:"Gzip",value:e}),K.getTypeScriptAlgebraicType=function(){return A.createSumType([new w("Uncompressed",V.getTypeScriptAlgebraicType()),new w("Brotli",A.createArrayType(A.createU8Type())),new w("Gzip",A.createArrayType(A.createU8Type()))])},K.serialize=function(e,t){K.getTypeScriptAlgebraicType().serialize(e,t)},K.deserialize=function(e){return K.getTypeScriptAlgebraicType().deserialize(e)},(J=X||(X={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("tableId",A.createU32Type()),new S("tableName",A.createStringType()),new S("numRows",A.createU64Type()),new S("updates",A.createArrayType(G.getTypeScriptAlgebraicType()))])},J.serialize=function(e,t){J.getTypeScriptAlgebraicType().serialize(e,t)},J.deserialize=function(e){return J.getTypeScriptAlgebraicType().deserialize(e)},(ee=Y||(Y={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("tables",A.createArrayType(X.getTypeScriptAlgebraicType()))])},ee.serialize=function(e,t){ee.getTypeScriptAlgebraicType().serialize(e,t)},ee.deserialize=function(e){return ee.getTypeScriptAlgebraicType().deserialize(e)},(re=te||(te={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("databaseUpdate",Y.getTypeScriptAlgebraicType()),new S("requestId",A.createU32Type()),new S("totalHostExecutionDuration",A.createTimeDurationType())])},re.serialize=function(e,t){re.getTypeScriptAlgebraicType().serialize(e,t)},re.deserialize=function(e){return re.getTypeScriptAlgebraicType().deserialize(e)},(se=ie||(ie={})).Committed=e=>({tag:"Committed",value:e}),se.Failed=e=>({tag:"Failed",value:e}),se.OutOfEnergy={tag:"OutOfEnergy"},se.getTypeScriptAlgebraicType=function(){return A.createSumType([new w("Committed",Y.getTypeScriptAlgebraicType()),new w("Failed",A.createStringType()),new w("OutOfEnergy",A.createProductType([]))])},se.serialize=function(e,t){se.getTypeScriptAlgebraicType().serialize(e,t)},se.deserialize=function(e){return se.getTypeScriptAlgebraicType().deserialize(e)},(ae=ne||(ne={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("reducerName",A.createStringType()),new S("reducerId",A.createU32Type()),new S("args",A.createArrayType(A.createU8Type())),new S("requestId",A.createU32Type())])},ae.serialize=function(e,t){ae.getTypeScriptAlgebraicType().serialize(e,t)},ae.deserialize=function(e){return ae.getTypeScriptAlgebraicType().deserialize(e)},(ce=oe||(oe={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("quanta",A.createU128Type())])},ce.serialize=function(e,t){ce.getTypeScriptAlgebraicType().serialize(e,t)},ce.deserialize=function(e){return ce.getTypeScriptAlgebraicType().deserialize(e)},(ue=pe||(pe={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("status",ie.getTypeScriptAlgebraicType()),new S("timestamp",A.createTimestampType()),new S("callerIdentity",A.createIdentityType()),new S("callerConnectionId",A.createConnectionIdType()),new S("reducerCall",ne.getTypeScriptAlgebraicType()),new S("energyQuantaUsed",oe.getTypeScriptAlgebraicType()),new S("totalHostExecutionDuration",A.createTimeDurationType())])},ue.serialize=function(e,t){ue.getTypeScriptAlgebraicType().serialize(e,t)},ue.deserialize=function(e){return ue.getTypeScriptAlgebraicType().deserialize(e)},(ye=le||(le={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("update",Y.getTypeScriptAlgebraicType())])},ye.serialize=function(e,t){ye.getTypeScriptAlgebraicType().serialize(e,t)},ye.deserialize=function(e){return ye.getTypeScriptAlgebraicType().deserialize(e)},(de=he||(he={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("identity",A.createIdentityType()),new S("token",A.createStringType()),new S("connectionId",A.createConnectionIdType())])},de.serialize=function(e,t){de.getTypeScriptAlgebraicType().serialize(e,t)},de.deserialize=function(e){return de.getTypeScriptAlgebraicType().deserialize(e)},(ge=fe||(fe={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("tableName",A.createStringType()),new S("rows",z.getTypeScriptAlgebraicType())])},ge.serialize=function(e,t){ge.getTypeScriptAlgebraicType().serialize(e,t)},ge.deserialize=function(e){return ge.getTypeScriptAlgebraicType().deserialize(e)},(be=Te||(Te={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("messageId",A.createArrayType(A.createU8Type())),new S("error",A.createOptionType(A.createStringType())),new S("tables",A.createArrayType(fe.getTypeScriptAlgebraicType())),new S("totalHostExecutionDuration",A.createTimeDurationType())])},be.serialize=function(e,t){be.getTypeScriptAlgebraicType().serialize(e,t)},be.deserialize=function(e){return be.getTypeScriptAlgebraicType().deserialize(e)},(me=we||(we={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("tableId",A.createU32Type()),new S("tableName",A.createStringType()),new S("tableRows",X.getTypeScriptAlgebraicType())])},me.serialize=function(e,t){me.getTypeScriptAlgebraicType().serialize(e,t)},me.deserialize=function(e){return me.getTypeScriptAlgebraicType().deserialize(e)},(Ie=Se||(Se={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("totalHostExecutionDurationMicros",A.createU64Type()),new S("queryId",k.getTypeScriptAlgebraicType()),new S("rows",we.getTypeScriptAlgebraicType())])},Ie.serialize=function(e,t){Ie.getTypeScriptAlgebraicType().serialize(e,t)},Ie.deserialize=function(e){return Ie.getTypeScriptAlgebraicType().deserialize(e)},(Ae=Ue||(Ue={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("totalHostExecutionDurationMicros",A.createU64Type()),new S("queryId",k.getTypeScriptAlgebraicType()),new S("rows",we.getTypeScriptAlgebraicType())])},Ae.serialize=function(e,t){Ae.getTypeScriptAlgebraicType().serialize(e,t)},Ae.deserialize=function(e){return Ae.getTypeScriptAlgebraicType().deserialize(e)},(_e=ve||(ve={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("totalHostExecutionDurationMicros",A.createU64Type()),new S("requestId",A.createOptionType(A.createU32Type())),new S("queryId",A.createOptionType(A.createU32Type())),new S("tableId",A.createOptionType(A.createU32Type())),new S("error",A.createStringType())])},_e.serialize=function(e,t){_e.getTypeScriptAlgebraicType().serialize(e,t)},_e.deserialize=function(e){return _e.getTypeScriptAlgebraicType().deserialize(e)},(Be=ze||(ze={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("totalHostExecutionDurationMicros",A.createU64Type()),new S("queryId",k.getTypeScriptAlgebraicType()),new S("update",Y.getTypeScriptAlgebraicType())])},Be.serialize=function(e,t){Be.getTypeScriptAlgebraicType().serialize(e,t)},Be.deserialize=function(e){return Be.getTypeScriptAlgebraicType().deserialize(e)},(Me=Fe||(Fe={})).getTypeScriptAlgebraicType=function(){return A.createProductType([new S("requestId",A.createU32Type()),new S("totalHostExecutionDurationMicros",A.createU64Type()),new S("queryId",k.getTypeScriptAlgebraicType()),new S("update",Y.getTypeScriptAlgebraicType())])},Me.serialize=function(e,t){Me.getTypeScriptAlgebraicType().serialize(e,t)},Me.deserialize=function(e){return Me.getTypeScriptAlgebraicType().deserialize(e)},(xe=Ee||(Ee={})).InitialSubscription=e=>({tag:"InitialSubscription",value:e}),xe.TransactionUpdate=e=>({tag:"TransactionUpdate",value:e}),xe.TransactionUpdateLight=e=>({tag:"TransactionUpdateLight",value:e}),xe.IdentityToken=e=>({tag:"IdentityToken",value:e}),xe.OneOffQueryResponse=e=>({tag:"OneOffQueryResponse",value:e}),xe.SubscribeApplied=e=>({tag:"SubscribeApplied",value:e}),xe.UnsubscribeApplied=e=>({tag:"UnsubscribeApplied",value:e}),xe.SubscriptionError=e=>({tag:"SubscriptionError",value:e}),xe.SubscribeMultiApplied=e=>({tag:"SubscribeMultiApplied",value:e}),xe.UnsubscribeMultiApplied=e=>({tag:"UnsubscribeMultiApplied",value:e}),xe.getTypeScriptAlgebraicType=function(){return A.createSumType([new w("InitialSubscription",te.getTypeScriptAlgebraicType()),new w("TransactionUpdate",pe.getTypeScriptAlgebraicType()),new w("TransactionUpdateLight",le.getTypeScriptAlgebraicType()),new w("IdentityToken",he.getTypeScriptAlgebraicType()),new w("OneOffQueryResponse",Te.getTypeScriptAlgebraicType()),new w("SubscribeApplied",Se.getTypeScriptAlgebraicType()),new w("UnsubscribeApplied",Ue.getTypeScriptAlgebraicType()),new w("SubscriptionError",ve.getTypeScriptAlgebraicType()),new w("SubscribeMultiApplied",ze.getTypeScriptAlgebraicType()),new w("UnsubscribeMultiApplied",Fe.getTypeScriptAlgebraicType())])},xe.serialize=function(e,t){xe.getTypeScriptAlgebraicType().serialize(e,t)},xe.deserialize=function(e){return xe.getTypeScriptAlgebraicType().deserialize(e)};var qe=class{#p=new Map;on(e,t){let r=this.#p.get(e);r||(r=new Set,this.#p.set(e,r)),r.add(t)}off(e,t){let r=this.#p.get(e);r&&r.delete(t)}emit(e,...t){let r=this.#p.get(e);if(r)for(let e of r)e(...t)}},Re={component:"đĻ",info:"âšī¸",warn:"â ī¸",error:"â",debug:"đ"},Ne={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;"},De={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;"},$e=(e,t)=>{console.log(`%c${Re[e]} ${e.toUpperCase()}%c ${t}`,Ne[e],De[e])},Le=class{rows;tableTypeInfo;emitter;constructor(e){this.tableTypeInfo=e,this.rows=new Map,this.emitter=new qe}count(){return this.rows.size}iter(){return Array.from(this.rows.values()).map((([e])=>e))}applyOperations=(e,t)=>{const r=[];if(void 0!==this.tableTypeInfo.primaryKeyInfo){const i=new Map,s=new Map;for(const t of e)if("insert"===t.type){const[e,r]=i.get(t.rowId)||[t,0];i.set(t.rowId,[t,r+1])}else{const[e,r]=s.get(t.rowId)||[t,0];s.set(t.rowId,[t,r+1])}for(const[e,[n,a]]of i){const i=s.get(e);if(i){const[o,c]=i,p=a-c,u=this.update(t,e,n.row,p);u&&r.push(u),s.delete(e)}else{const e=this.insert(t,n,a);e&&r.push(e)}}for(const[e,i]of s.values()){const s=this.delete(t,e,i);s&&r.push(s)}}else for(const i of e)if("insert"===i.type){const e=this.insert(t,i);e&&r.push(e)}else{const e=this.delete(t,i);e&&r.push(e)}return r};update=(e,t,r,i=0)=>{const s=this.rows.get(t);if(!s)return void $e("error",`Updating a row that was not present in the cache. Table: ${this.tableTypeInfo.tableName}, RowId: ${t}`);const[n,a]=s,o=Math.max(1,a+i);if(!(a+i<=0))return this.rows.set(t,[r,o]),0===a?($e("error",`Updating a row id in table ${this.tableTypeInfo.tableName} which was not present in the cache (rowId: ${t})`),{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,r)}}):{type:"update",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("update",e,n,r)}};$e("error",`Negative reference count for in table ${this.tableTypeInfo.tableName} row ${t} (${a} + ${i})`)};insert=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(this.rows.set(t.rowId,[t.row,s+r]),0===s)return{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}};delete=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(0!==s)return s<=r?(this.rows.delete(t.rowId),{type:"delete",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("delete",e,t.row)}}):void this.rows.set(t.rowId,[t.row,s-r]);$e("warn","Deleting a row that was not present in the cache")};onInsert=e=>{this.emitter.on("insert",e)};onDelete=e=>{this.emitter.on("delete",e)};onUpdate=e=>{this.emitter.on("update",e)};removeOnInsert=e=>{this.emitter.off("insert",e)};removeOnDelete=e=>{this.emitter.off("delete",e)};removeOnUpdate=e=>{this.emitter.off("update",e)}},je=class{tables;constructor(){this.tables=new Map}getTable(e){const t=this.tables.get(e);if(!t)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${e} does not exist`);return t}getOrCreateTable(e){let t;return this.tables.has(e.tableName)?t=this.tables.get(e.tableName):(t=new Le(e),this.tables.set(e.tableName,t)),t}};var We=class e{major;minor;patch;preRelease;buildInfo;constructor(e,t,r,i=null,s=null){this.major=e,this.minor=t,this.patch=r,this.preRelease=i,this.buildInfo=s}toString(){let e=`${this.major}.${this.minor}.${this.patch}`;return this.preRelease&&(e+=`-${this.preRelease.join(".")}`),this.buildInfo&&(e+=`+${this.buildInfo}`),e}compare(e){return this.major!==e.major?this.major-e.major:this.minor!==e.minor?this.minor-e.minor:this.patch!==e.patch?this.patch-e.patch:this.preRelease&&e.preRelease?function(e,t){const r=Math.min(e.length,t.length);for(let i=0;i<r;i++){const r=e[i],s=t[i];if(r!==s)return"number"==typeof r&&"number"==typeof s?r-s:"string"==typeof r&&"string"==typeof s?r.localeCompare(s):"string"==typeof r?1:-1}return e.length-t.length}(this.preRelease,e.preRelease):this.preRelease||e.preRelease?-1:0}clone(){return new e(this.major,this.minor,this.patch,this.preRelease?[...this.preRelease]:null,this.buildInfo)}static parseVersionString(t){const r=t.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/);if(!r)throw new Error(`Invalid version string: ${t}`);const i=parseInt(r[1],10),s=parseInt(r[2],10),n=parseInt(r[3],10),a=r[4]?r[4].split(".").map((e=>isNaN(Number(e))?e:Number(e))):null,o=r[5]||null;return new e(i,s,n,a,o)}},He=new We(1,2,0);function Qe(e){return`Module code was generated with an incompatible version of the spacetimedb cli (${e}). Update the cli version to at least ${He.toString()} and regenerate the bindings. You can upgrade to the latest cli version by running: spacetime version upgrade`}async function Ve(e,t,r=131072){let i=0;const s=new ReadableStream({pull(t){if(i<e.length){const s=e.subarray(i,Math.min(i+r,e.length));t.enqueue(s),i+=r}else t.close()}}),n=new DecompressionStream(t),a=s.pipeThrough(n).getReader(),o=[];let c,p=0;for(;!(c=await a.read()).done;)o.push(c.value),p+=c.value.length;const u=new Uint8Array(p);let l=0;for(const e of o)u.set(e,l),l+=e.length;return u}var Ze=class e{onclose;onopen;onmessage;onerror;#u;async#l(e){const t=new Uint8Array(e.data);let r;if(0===t[0])r=t.slice(1);else{if(1===t[0])throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");if(2!==t[0])throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`");r=await Ve(t.slice(1),"gzip")}this.onmessage?.({data:r})}#y(e){this.onopen?.(e)}#h(e){this.onerror?.(e)}send(e){this.#u.send(e)}close(){this.#u.close()}constructor(e){this.onmessage=void 0,this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,e.onmessage=this.#l.bind(this),e.onerror=this.#h.bind(this),e.onclose=this.#h.bind(this),e.onopen=this.#y.bind(this),e.binaryType="arraybuffer",this.#u=e}static async createWebSocketFn({url:t,nameOrAddress:r,wsProtocol:i,authToken:s,compression:n,lightMode:a}){const o=new Headers;let c,p;if(c="false"===import.meta.env.BROWSER?"WebSocket"in globalThis?WebSocket:(await import("undici")).WebSocket:WebSocket,s){o.set("Authorization",`Bearer ${s}`);const e=new URL("v1/identity/websocket-token",t);e.protocol="wss:"===t.protocol?"https:":"http:";const r=await fetch(e,{method:"POST",headers:o});if(!r.ok)return Promise.reject(new Error(`Failed to verify token: ${r.statusText}`));{const{token:e}=await r.json();p=e}}const u=new URL(`v1/database/${r}/subscribe`,t);p&&u.searchParams.set("token",p),u.searchParams.set("compression","gzip"===n?"Gzip":"None"),a&&u.searchParams.set("light","true");const l=new c(u.toString(),i);return new e(l)}},Ge=class{constructor(e,t){this.remoteModule=e,this.dbConnectionConstructor=t,this.#d=Ze.createWebSocketFn}#f;#g;#T;#b;#w=new qe;#m="gzip";#S=!1;#d;withUri(e){return this.#f=new URL(e),this}withModuleName(e){return this.#g=e,this}withToken(e){return this.#b=e,this}withWSFn(e){return this.#d=e,this}withCompression(e){return this.#m=e,this}withLightMode(e){return this.#S=e,this}onConnect(e){return this.#w.on("connect",e),this}onConnectError(e){return this.#w.on("connectError",e),this}onDisconnect(e){return this.#w.on("disconnect",e),this}build(){if(!this.#f)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#g)throw new Error("Database name or address is required to connect to SpacetimeDB");return function(e){if(void 0===e)throw new Error(Qe(e));if(We.parseVersionString(e).compare(He)<0)throw new Error(Qe(e))}(this.remoteModule.versionInfo?.cliVersion),this.dbConnectionConstructor(new et({uri:this.#f,nameOrAddress:this.#g,identity:this.#T,token:this.#b,emitter:this.#w,compression:this.#m,lightMode:this.#S,createWSFn:this.#d,remoteModule:this.remoteModule}))}},Ke=class{constructor(e){this.db=e}#I=void 0;#U=void 0;onApplied(e){return this.#I=e,this}onError(e){return this.#U=e,this}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("Subscriptions must have at least one query");return new Je(this.db,t,this.#I,this.#U)}subscribeToAllTables(){this.subscribe("SELECT * FROM *")}},Xe=class{subscriptions=new Map},Je=class{constructor(e,t,r,i){this.db=e,this.#w.on("applied",(e=>{this.#A=!0,r&&r(e)})),this.#w.on("error",((e,t)=>{this.#A=!1,this.#v=!0,i&&i(e,t)})),this.#_=this.db.registerSubscription(this,this.#w,t)}#_;#z=!1;#v=!1;#A=!1;#w=new qe;unsubscribe(){if(this.#z)throw new Error("Unsubscribe has already been called");this.#z=!0,this.db.unregisterSubscription(this.#_),this.#w.on("end",(e=>{this.#v=!0,this.#A=!1}))}unsubscribeThen(e){if(this.#v)throw new Error("Subscription has already ended");if(this.#z)throw new Error("Unsubscribe has already been called");this.#z=!0,this.db.unregisterSubscription(this.#_),this.#w.on("end",(t=>{this.#v=!0,this.#A=!1,e(t)}))}isEnded(){return this.#v}isActive(){return this.#A}};function Ye(e){switch(e){case"FullUpdate":return 0;case"NoSuccessNotify":return 1}}var et=class{isActive=!1;identity=void 0;token=void 0;db;reducers;setReducerFlags;connectionId=y.random();#_=0;#w;#B=new qe;#I;#F;#M=Promise.resolve();#E=new Xe;clientCache;ws;wsPromise;constructor({uri:e,nameOrAddress:t,identity:r,token:i,emitter:s,remoteModule:n,createWSFn:a,compression:o,lightMode:c}){$e("info","Connecting to SpacetimeDB WS...");let p=new URL(e);/^wss?:/.test(e.protocol)||(p.protocol="https:"===p.protocol?"wss:":"ws:"),this.identity=r,this.token=i,this.#F=n,this.#w=s;let u=this.connectionId.toHexString();p.searchParams.set("connection_id",u),this.clientCache=new je,this.db=this.#F.dbViewConstructor(this),this.setReducerFlags=this.#F.setReducerFlagsConstructor(),this.reducers=this.#F.reducersConstructor(this,this.setReducerFlags),this.wsPromise=a({url:p,nameOrAddress:t,wsProtocol:"v1.bsatn.spacetimedb",authToken:i,compression:o,lightMode:c}).then((e=>(this.ws=e,this.ws.onclose=()=>{this.#w.emit("disconnect",this)},this.ws.onerror=e=>{this.#w.emit("connectError",this,e)},this.ws.onopen=this.#y.bind(this),this.ws.onmessage=this.#l.bind(this),e))).catch((e=>{$e("error","Error connecting to SpacetimeDB WS"),this.#w.emit("connectError",this,e)}))}#x=()=>{const e=this.#_;return this.#_+=1,e};subscriptionBuilder=()=>new Ke(this);registerSubscription(e,t,r){const i=this.#x();return this.#E.subscriptions.set(i,{handle:e,emitter:t}),this.#C(H.SubscribeMulti({queryStrings:r,queryId:{id:i},requestId:0})),i}unregisterSubscription(e){this.#C(H.UnsubscribeMulti({queryId:{id:e},requestId:0}))}async#O(r){const i=(r,i,s)=>{const n=s.rowsData,a=new t(n),o=[],c=this.#F.tables[i].rowType,p=this.#F.tables[i].primaryKeyInfo;for(;a.offset<n.length+n.byteOffset;){const t=a.offset,i=c.deserialize(a);let s;if(void 0!==p)s=p.colType.intoMapKey(i[p.colName]);else{const r=n.subarray(t-n.byteOffset,a.offset-n.byteOffset);s=e(r)}o.push({type:r,rowId:s,row:i})}return o},s=async e=>{const r=e.tableName;let s=[];for(const n of e.updates){let e;if("Gzip"===n.tag){const r=await Ve(n.value,"gzip");e=V.deserialize(new t(r))}else{if("Brotli"===n.tag)throw new Error("Brotli compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");e=n.value}s=s.concat(i("insert",r,e.inserts)),s=s.concat(i("delete",r,e.deletes))}return{tableName:r,operations:s}},n=async e=>{const t=[];for(const r of e.tables)t.push(await s(r));return t};switch(r.tag){case"InitialSubscription":{const e=r.value.databaseUpdate;return{tag:"InitialSubscription",tableUpdates:await n(e)}}case"TransactionUpdateLight":{const e=r.value.update;return{tag:"TransactionUpdateLight",tableUpdates:await n(e)}}case"TransactionUpdate":{const e=r.value,t=e.callerIdentity,i=y.nullIfZero(e.callerConnectionId),s=e.reducerCall.reducerName,a=e.reducerCall.args,o=e.energyQuantaUsed;let c,p,u="";switch(e.status.tag){case"Committed":c=await n(e.status.value);break;case"Failed":c=[],u=e.status.value;break;case"OutOfEnergy":c=[]}if("<none>"===s){let e=u;return void console.error(`Received an error from the database: ${e}`)}""!==s&&(p={reducerName:s,args:a});return{tag:"TransactionUpdate",tableUpdates:c,identity:t,connectionId:i,reducerInfo:p,status:e.status,energyConsumed:o.quanta,message:u,timestamp:e.timestamp}}case"IdentityToken":return{tag:"IdentityToken",identity:r.value.identity,token:r.value.token,connectionId:r.value.connectionId};case"OneOffQueryResponse":throw new Error(`TypeScript SDK never sends one-off queries, but got OneOffQueryResponse ${r}`);case"SubscribeMultiApplied":{const e=await n(r.value.update);return{tag:"SubscribeApplied",queryId:r.value.queryId.id,tableUpdates:e}}case"UnsubscribeMultiApplied":{const e=await n(r.value.update);return{tag:"UnsubscribeApplied",queryId:r.value.queryId.id,tableUpdates:e}}case"SubscriptionError":return{tag:"SubscriptionError",queryId:r.value.queryId,error:r.value.error}}}#C(e){this.wsPromise.then((t=>{if(t){const i=new r(1024);H.serialize(i,e);const s=i.getBuffer();t.send(s)}}))}#y(){this.isActive=!0}#k(e,t){let r=[];for(let i of e){const e=i.tableName,s=this.#F.tables[e],n=this.clientCache.getOrCreateTable(s).applyOperations(i.operations,t);for(const e of n)r.push(e)}return r}async#P(e){const r=function(e,r){const i=new t(r);return e.deserialize(i)}(Ee,e),i=await this.#O(r);if(i)switch(i.tag){case"InitialSubscription":{let e={tag:"SubscribeApplied"};const t=this.#F.eventContextConstructor(this,e),{event:r,...s}=t,n=this.#k(i.tableUpdates,t);this.#w&&this.#I?.(s);for(const e of n)e.cb();break}case"TransactionUpdateLight":{let e={tag:"UnknownTransaction"};const t=this.#F.eventContextConstructor(this,e),r=this.#k(i.tableUpdates,t);for(const e of r)e.cb();break}case"TransactionUpdate":{let e,r,s=i.reducerInfo,n=!1;if(s){r=this.#F.reducers[s.reducerName];try{const i=new t(s.args);e=r.argsType.deserialize(i)}catch{console.debug("Failed to deserialize reducer arguments"),n=!0}}else n=!0;if(n){const e={tag:"UnknownTransaction"},t=this.#F.eventContextConstructor(this,e),r=this.#k(i.tableUpdates,t);for(const e of r)e.cb();return}const a={callerIdentity:i.identity,status:i.status,callerConnectionId:i.connectionId,timestamp:i.timestamp,energyConsumed:i.energyConsumed,reducer:{name:s.reducerName,args:e}},o={tag:"Reducer",value:a},c=this.#F.eventContextConstructor(this,o),p={...c,event:a},u=this.#k(i.tableUpdates,c),l=[];r.argsType.product.elements.forEach(((t,r)=>{l.push(e[t.name])})),this.#B.emit(s.reducerName,p,...l);for(const e of u)e.cb();break}case"IdentityToken":this.identity=i.identity,!this.token&&i.token&&(this.token=i.token),this.connectionId=i.connectionId,this.#w.emit("connect",this,this.identity,this.token);break;case"SubscribeApplied":{const e=this.#E.subscriptions.get(i.queryId);if(void 0===e){$e("error",`Received SubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"SubscribeApplied"},r=this.#F.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#k(i.tableUpdates,r);e?.emitter.emit("applied",n);for(const e of a)e.cb();break}case"UnsubscribeApplied":{const e=this.#E.subscriptions.get(i.queryId);if(void 0===e){$e("error",`Received UnsubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"UnsubscribeApplied"},r=this.#F.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#k(i.tableUpdates,r);e?.emitter.emit("end",n),this.#E.subscriptions.delete(i.queryId);for(const e of a)e.cb();break}case"SubscriptionError":{const e=Error(i.error),t={tag:"Error",value:e},r={...this.#F.eventContextConstructor(this,t),event:e};void 0!==i.queryId?(this.#E.subscriptions.get(i.queryId)?.emitter.emit("error",r,e),this.#E.subscriptions.delete(i.queryId)):(console.error("Received an error message without a queryId: ",e),this.#E.subscriptions.forEach((({emitter:t})=>{t.emit("error",r,e)})))}}}#l(e){this.#M=this.#M.then((()=>this.#P(e.data)))}callReducer(e,t,r){const i=H.CallReducer({reducer:e,args:t,requestId:0,flags:Ye(r)});this.#C(i)}disconnect(){this.wsPromise.then((e=>{e&&e.close()}))}#q(e,t){this.#w.on(e,t)}#R(e,t){this.#w.off(e,t)}#N(e){this.#w.on("connect",e)}#D(e){this.#w.on("disconnect",e)}#$(e){this.#w.on("connectError",e)}#L(e){this.#w.off("connect",e)}#j(e){this.#w.off("disconnect",e)}#W(e){this.#w.off("connectError",e)}onReducer(e,t){this.#B.on(e,t)}offReducer(e,t){this.#B.off(e,t)}};export{A as AlgebraicType,Pe as AlgebraicValue,t as BinaryReader,r as BinaryWriter,je as ClientCache,y as ConnectionId,Ge as DbConnectionBuilder,et as DbConnectionImpl,f as Identity,I as ProductType,S as ProductTypeElement,ke as ProductValue,u as ScheduleAt,Ke as SubscriptionBuilderImpl,m as SumType,w as SumTypeVariant,Le as TableCache,h as TimeDuration,d as Timestamp,i as deepEqual};//# sourceMappingURL=index.js.map |
+4
-1
| { | ||
| "name": "@clockworklabs/spacetimedb-sdk", | ||
| "version": "1.2.1", | ||
| "version": "1.2.2", | ||
| "description": "SDK for SpacetimeDB", | ||
@@ -44,2 +44,5 @@ "author": { | ||
| }, | ||
| "dependencies": { | ||
| "base64-js": "^1.5.1" | ||
| }, | ||
| "scripts": { | ||
@@ -46,0 +49,0 @@ "compile": "tsup", |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
634436
3.85%8509
3.33%2
100%+ Added
+ Added