@multitapio/multitap 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js CHANGED
@@ -4,7 +4,7 @@ var __export = (target, all) => {
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
5
5
  };
6
6
 
7
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
7
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
8
8
  function isBytes(a) {
9
9
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
10
10
  }
@@ -70,7 +70,7 @@ function createHasher(hashCons) {
70
70
  return hashC;
71
71
  }
72
72
 
73
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
73
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
74
74
  function setBigUint64(view, byteOffset, value, isLE) {
75
75
  if (typeof view.setBigUint64 === "function")
76
76
  return view.setBigUint64(byteOffset, value, isLE);
@@ -190,7 +190,7 @@ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
190
190
  1541459225
191
191
  ]);
192
192
 
193
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
193
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
194
194
  var SHA256_K = /* @__PURE__ */ Uint32Array.from([
195
195
  1116352408,
196
196
  1899447441,
@@ -330,10 +330,10 @@ var SHA256 = class extends HashMD {
330
330
  };
331
331
  var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
332
332
 
333
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js
333
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js
334
334
  var sha2562 = sha256;
335
335
 
336
- // node_modules/.pnpm/@noble+secp256k1@2.3.0/node_modules/@noble/secp256k1/index.js
336
+ // ../../node_modules/.pnpm/@noble+secp256k1@2.3.0/node_modules/@noble/secp256k1/index.js
337
337
  var secp256k1_CURVE = {
338
338
  p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,
339
339
  n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,
@@ -919,7 +919,7 @@ var wNAF = (n) => {
919
919
  return { p, f };
920
920
  };
921
921
 
922
- // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
922
+ // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
923
923
  var HMAC = class extends Hash {
924
924
  constructor(hash, _key) {
925
925
  super();
@@ -987,7 +987,7 @@ var HMAC = class extends Hash {
987
987
  var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
988
988
  hmac.create = (hash, key) => new HMAC(hash, key);
989
989
 
990
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/is.js
990
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/is.js
991
991
  var typeofs = [
992
992
  "string",
993
993
  "number",
@@ -1070,7 +1070,7 @@ function getObjectType(value) {
1070
1070
  return void 0;
1071
1071
  }
1072
1072
 
1073
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/token.js
1073
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/token.js
1074
1074
  var Type = class {
1075
1075
  /**
1076
1076
  * @param {number} major
@@ -1127,7 +1127,7 @@ var Token = class {
1127
1127
  }
1128
1128
  };
1129
1129
 
1130
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/byte-utils.js
1130
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/byte-utils.js
1131
1131
  var useBuffer = globalThis.process && // @ts-ignore
1132
1132
  !globalThis.process.browser && // @ts-ignore
1133
1133
  globalThis.Buffer && // @ts-ignore
@@ -1381,7 +1381,7 @@ function decodeCodePointsArray(codePoints) {
1381
1381
  return res;
1382
1382
  }
1383
1383
 
1384
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/bl.js
1384
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/bl.js
1385
1385
  var defaultChunkSize = 256;
1386
1386
  var Bl = class {
1387
1387
  /**
@@ -1462,7 +1462,7 @@ var Bl = class {
1462
1462
  }
1463
1463
  };
1464
1464
 
1465
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/common.js
1465
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/common.js
1466
1466
  var decodeErrPrefix = "CBOR decode error:";
1467
1467
  var encodeErrPrefix = "CBOR encode error:";
1468
1468
  var uintMinorPrefixBytes = [];
@@ -1477,7 +1477,7 @@ function assertEnoughData(data, pos, need) {
1477
1477
  }
1478
1478
  }
1479
1479
 
1480
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/0uint.js
1480
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/0uint.js
1481
1481
  var uintBoundaries = [24, 256, 65536, 4294967296, BigInt("18446744073709551616")];
1482
1482
  function readUint8(data, offset, options) {
1483
1483
  assertEnoughData(data, offset, 1);
@@ -1598,7 +1598,7 @@ encodeUint.compareTokens = function compareTokens(tok1, tok2) {
1598
1598
  );
1599
1599
  };
1600
1600
 
1601
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/1negint.js
1601
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/1negint.js
1602
1602
  function decodeNegint8(data, pos, _minor, options) {
1603
1603
  return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
1604
1604
  }
@@ -1652,7 +1652,7 @@ encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
1652
1652
  );
1653
1653
  };
1654
1654
 
1655
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/2bytes.js
1655
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/2bytes.js
1656
1656
  function toToken(data, pos, prefix, length) {
1657
1657
  assertEnoughData(data, pos, prefix + length);
1658
1658
  const buf2 = slice(data, pos + prefix, pos + prefix + length);
@@ -1699,7 +1699,7 @@ function compareBytes(b1, b2) {
1699
1699
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
1700
1700
  }
1701
1701
 
1702
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/3string.js
1702
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/3string.js
1703
1703
  function toToken2(data, pos, prefix, length, options) {
1704
1704
  const totLength = prefix + length;
1705
1705
  assertEnoughData(data, pos, totLength);
@@ -1730,7 +1730,7 @@ function decodeString64(data, pos, _minor, options) {
1730
1730
  }
1731
1731
  var encodeString = encodeBytes;
1732
1732
 
1733
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/4array.js
1733
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/4array.js
1734
1734
  function toToken3(_data, _pos, prefix, length) {
1735
1735
  return new Token(Type.array, length, prefix);
1736
1736
  }
@@ -1767,7 +1767,7 @@ encodeArray.encodedSize = function encodedSize5(token) {
1767
1767
  return encodeUintValue.encodedSize(token.value);
1768
1768
  };
1769
1769
 
1770
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/5map.js
1770
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/5map.js
1771
1771
  function toToken4(_data, _pos, prefix, length) {
1772
1772
  return new Token(Type.map, length, prefix);
1773
1773
  }
@@ -1804,7 +1804,7 @@ encodeMap.encodedSize = function encodedSize6(token) {
1804
1804
  return encodeUintValue.encodedSize(token.value);
1805
1805
  };
1806
1806
 
1807
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/6tag.js
1807
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/6tag.js
1808
1808
  function decodeTagCompact(_data, _pos, minor, _options) {
1809
1809
  return new Token(Type.tag, minor, 1);
1810
1810
  }
@@ -1828,7 +1828,7 @@ encodeTag.encodedSize = function encodedSize7(token) {
1828
1828
  return encodeUintValue.encodedSize(token.value);
1829
1829
  };
1830
1830
 
1831
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/7float.js
1831
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/7float.js
1832
1832
  var MINOR_FALSE = 20;
1833
1833
  var MINOR_TRUE = 21;
1834
1834
  var MINOR_NULL = 22;
@@ -2004,7 +2004,7 @@ function readFloat64(ui8a2, pos) {
2004
2004
  }
2005
2005
  encodeFloat.compareTokens = encodeUint.compareTokens;
2006
2006
 
2007
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/jump.js
2007
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/jump.js
2008
2008
  function invalidMinor(data, pos, minor) {
2009
2009
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
2010
2010
  }
@@ -2160,7 +2160,7 @@ function quickEncodeToken(token) {
2160
2160
  }
2161
2161
  }
2162
2162
 
2163
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/encode.js
2163
+ // ../../node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/encode.js
2164
2164
  var defaultEncodeOptions = {
2165
2165
  float64: false,
2166
2166
  mapSorter,
@@ -2484,10 +2484,6 @@ function encode(data, options) {
2484
2484
  return encodeCustom(data, cborEncoders, options);
2485
2485
  }
2486
2486
 
2487
- // node_modules/.pnpm/cborg@4.3.2/node_modules/cborg/lib/decode.js
2488
- var DONE = Symbol.for("DONE");
2489
- var BREAK = Symbol.for("BREAK");
2490
-
2491
2487
  // src/utils.ts
2492
2488
  function uint8ArrayToBase64(data) {
2493
2489
  const dataWithToBase64 = data;
@@ -2886,7 +2882,7 @@ var SessionConfig = class _SessionConfig {
2886
2882
  return `multitap://${this.authority}${path}?${params.toString()}`;
2887
2883
  }
2888
2884
  /**
2889
- * Build an HTTPS connection URL (for WebTransport).
2885
+ * Build a connection URL
2890
2886
  * @returns HTTPS URL string
2891
2887
  */
2892
2888
  toHTTPSURL() {
@@ -2978,6 +2974,7 @@ var PONG_PAYLOAD_SIZE = 8;
2978
2974
  var REPLAY_PING_SIZE = 11;
2979
2975
  var MSG_HEADER_SIZE = 3;
2980
2976
  var MAX_INPUTS_PER_TICK = 16;
2977
+ var NULL_INPUT_TARGET_TICK = 4294967295;
2981
2978
  function inputWireSize(payloadLen) {
2982
2979
  return INPUT_HEADER_SIZE2 + payloadLen + SIGNATURE_SIZE2;
2983
2980
  }
@@ -3149,12 +3146,12 @@ var messageCodec = {
3149
3146
  }
3150
3147
  };
3151
3148
 
3152
- // node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs
3153
- var proxyMarker = Symbol("Comlink.proxy");
3154
- var createEndpoint = Symbol("Comlink.endpoint");
3155
- var releaseProxy = Symbol("Comlink.releaseProxy");
3156
- var finalizer = Symbol("Comlink.finalizer");
3157
- var throwMarker = Symbol("Comlink.thrown");
3149
+ // ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs
3150
+ var proxyMarker = /* @__PURE__ */ Symbol("Comlink.proxy");
3151
+ var createEndpoint = /* @__PURE__ */ Symbol("Comlink.endpoint");
3152
+ var releaseProxy = /* @__PURE__ */ Symbol("Comlink.releaseProxy");
3153
+ var finalizer = /* @__PURE__ */ Symbol("Comlink.finalizer");
3154
+ var throwMarker = /* @__PURE__ */ Symbol("Comlink.thrown");
3158
3155
  var isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
3159
3156
  var proxyTransferHandler = {
3160
3157
  canHandle: (val) => isObject(val) && val[proxyMarker],
@@ -4036,6 +4033,589 @@ var RollingCounter = class {
4036
4033
  }
4037
4034
  };
4038
4035
 
4036
+ // src/channel.ts
4037
+ var DEFAULT_ICE_SERVERS = [
4038
+ { urls: "stun:stun.l.google.com:19302" },
4039
+ { urls: "stun:stun1.l.google.com:19302" }
4040
+ ];
4041
+ var Channel = class {
4042
+ connectionURL;
4043
+ serverCertHash;
4044
+ connectionTimeoutMs;
4045
+ // Signing keys - player identity is derived from public key
4046
+ privateKey;
4047
+ publicKey;
4048
+ genesisHash;
4049
+ sessionConfig;
4050
+ peerConnection;
4051
+ dataChannels;
4052
+ replayChannels;
4053
+ roundRobinIndex;
4054
+ connectionGeneration;
4055
+ iceServers;
4056
+ connected;
4057
+ stopped;
4058
+ debug;
4059
+ logSyncTicks;
4060
+ outbox;
4061
+ stateListeners;
4062
+ flushingOutbox;
4063
+ tickRate;
4064
+ inputGraph;
4065
+ // tick deadline tracking
4066
+ tickDeadlineWants = 0;
4067
+ tickDeadlineTimer = null;
4068
+ tickDeadlineGrace = 33;
4069
+ // is a tick is later than this, we trigger a deadline exceeded
4070
+ // stats
4071
+ stats;
4072
+ constructor(config) {
4073
+ this.debug = config.debug ?? false;
4074
+ this.connectionURL = config.connectionURL;
4075
+ this.serverCertHash = config.serverCertHash;
4076
+ this.connectionTimeoutMs = config.connectionTimeoutMs ?? 5e3;
4077
+ this.privateKey = config.privateKey ?? generateKeyPair();
4078
+ this.publicKey = pubKeyFromPrivate(this.privateKey);
4079
+ this.logSyncTicks = config.logSyncTicks ?? false;
4080
+ this.iceServers = config.iceServers ?? DEFAULT_ICE_SERVERS;
4081
+ this.sessionConfig = SessionConfig.fromConnectionURL(config.connectionURL);
4082
+ this.genesisHash = this.sessionConfig.toGenesisHash();
4083
+ this.peerConnection = null;
4084
+ this.dataChannels = [];
4085
+ this.replayChannels = /* @__PURE__ */ new Set();
4086
+ this.roundRobinIndex = 0;
4087
+ this.connectionGeneration = 0;
4088
+ this.connected = false;
4089
+ this.stopped = false;
4090
+ this.outbox = [];
4091
+ this.stateListeners = /* @__PURE__ */ new Set();
4092
+ this.flushingOutbox = false;
4093
+ this.tickRate = 0;
4094
+ this.inputGraph = new InputGraph({
4095
+ genesisHash: this.genesisHash,
4096
+ maxTicks: this.sessionConfig.maxTicks,
4097
+ inputPayloadPredictor: config.inputPayloadPredictor,
4098
+ verificationPubKey: config.relayPubKey,
4099
+ debug: this.debug,
4100
+ logSyncTicks: this.logSyncTicks
4101
+ });
4102
+ this.stats = {
4103
+ messagesRecv: new RollingCounter(),
4104
+ messagesSent: new RollingCounter(),
4105
+ reconnections: 0
4106
+ };
4107
+ if (config.autoConnect !== false) {
4108
+ this._connectLoop().catch(warnUnexpected);
4109
+ }
4110
+ }
4111
+ // Manually start the connection loop (use when autoConnect: false)
4112
+ async connect() {
4113
+ if (this.stopped) {
4114
+ throw new Error("Channel has been stopped");
4115
+ }
4116
+ if (!this.peerConnection && !this.connected) {
4117
+ this._connectLoop().catch(warnUnexpected);
4118
+ }
4119
+ }
4120
+ // Get the player's public key (identity)
4121
+ async getPublicKey() {
4122
+ return this.publicKey;
4123
+ }
4124
+ // Get the genesis hash (16 bytes)
4125
+ async getGenesisHash() {
4126
+ return this.genesisHash;
4127
+ }
4128
+ onStateChange(fn) {
4129
+ this.stateListeners.add(fn);
4130
+ fn(this.connected);
4131
+ return () => {
4132
+ this.stateListeners.delete(fn);
4133
+ };
4134
+ }
4135
+ getStats() {
4136
+ return {
4137
+ activeStreams: this.dataChannels.length,
4138
+ totalStreams: this.dataChannels.length,
4139
+ messagesRecv: this.stats.messagesRecv.rate(),
4140
+ messagesSent: this.stats.messagesSent.rate(),
4141
+ reconnections: this.stats.reconnections
4142
+ };
4143
+ }
4144
+ // Get tick rate (Hz) received from server, 0 if unknown
4145
+ async getTickRate() {
4146
+ return this.tickRate;
4147
+ }
4148
+ // Get participants who joined on or before the given tick, in join order
4149
+ async getParticipantSlots(tick) {
4150
+ return this.inputGraph.getParticipantSlots(tick);
4151
+ }
4152
+ async getSyncHead() {
4153
+ return this.inputGraph.getSyncHead();
4154
+ }
4155
+ async getPredictedHead() {
4156
+ return this.inputGraph.getPredictedHead();
4157
+ }
4158
+ async addSyncTick(msg) {
4159
+ this.inputGraph.addSyncTick(msg);
4160
+ }
4161
+ async addOptimisticInput(input, preVerifiedSigner) {
4162
+ this.inputGraph.addOptimisticInput(input, preVerifiedSigner);
4163
+ }
4164
+ async getPredictionCount() {
4165
+ return this.inputGraph.getPredictionCount();
4166
+ }
4167
+ async getTicksAfter(nodeId, options) {
4168
+ return this.inputGraph.getTicksAfter(nodeId, options);
4169
+ }
4170
+ async setOnParticipantJoined(fn) {
4171
+ this.inputGraph.setOnParticipantJoined(fn);
4172
+ }
4173
+ async expose(port) {
4174
+ expose(this, port);
4175
+ }
4176
+ // shutdown
4177
+ async close() {
4178
+ this.stopped = true;
4179
+ if (this.tickDeadlineTimer) {
4180
+ clearTimeout(this.tickDeadlineTimer);
4181
+ this.tickDeadlineTimer = null;
4182
+ }
4183
+ if (this.peerConnection) {
4184
+ try {
4185
+ this.peerConnection.close();
4186
+ } catch {
4187
+ }
4188
+ }
4189
+ }
4190
+ _setConnected(value) {
4191
+ if (this.connected === value) return;
4192
+ this.connected = value;
4193
+ for (const fn of this.stateListeners) {
4194
+ try {
4195
+ fn(value);
4196
+ } catch {
4197
+ }
4198
+ }
4199
+ }
4200
+ // Send raw bytes (Uint8Array) via DataChannel
4201
+ async _send(data) {
4202
+ if (!(data instanceof Uint8Array)) {
4203
+ throw new Error("send() requires Uint8Array");
4204
+ }
4205
+ if (this.connected && this.dataChannels.length > 0) {
4206
+ for (let i = 0; i < this.dataChannels.length; i++) {
4207
+ const handle = this._nextChannel();
4208
+ if (!handle) break;
4209
+ try {
4210
+ handle.dc.send(data);
4211
+ this.stats.messagesSent.inc();
4212
+ return;
4213
+ } catch {
4214
+ this._dropChannel(handle);
4215
+ if (!this.connected) break;
4216
+ }
4217
+ }
4218
+ }
4219
+ this.outbox.push(data);
4220
+ }
4221
+ // Generate a null input for participant registration (join message)
4222
+ // Null inputs have TargetTick = NULL_INPUT_TARGET_TICK (0xFFFFFFFF) and empty payload.
4223
+ // They bypass the validity window check and are used to register players on connect.
4224
+ _generateNullInput() {
4225
+ const payload = new Uint8Array(0);
4226
+ const msgHash = hashInputMessage(this.genesisHash, NULL_INPUT_TARGET_TICK, payload);
4227
+ const signature = sign2(this.privateKey, msgHash);
4228
+ return messageCodec.encodeInput(NULL_INPUT_TARGET_TICK, payload, signature);
4229
+ }
4230
+ // Send a signed input message
4231
+ // The payload is variable-length (0-255 bytes) and signed with the player's private key
4232
+ // targetTick defaults to predictedHead + 1
4233
+ // Returns the encoded input bytes (for P2P broadcast by Session)
4234
+ async sendSignedInput(payload, targetTick) {
4235
+ if (payload.length > MAX_INPUT_PAYLOAD_SIZE) {
4236
+ throw new Error(`Payload must be ${MAX_INPUT_PAYLOAD_SIZE} bytes or less, got ${payload.length}`);
4237
+ }
4238
+ let tick = targetTick;
4239
+ if (tick === void 0) {
4240
+ tick = this.inputGraph.getPredictedHead().tick + 1;
4241
+ }
4242
+ const msgHash = hashInputMessage(this.genesisHash, tick, payload);
4243
+ const signature = sign2(this.privateKey, msgHash);
4244
+ const selfId = bytesToHex2(this.publicKey);
4245
+ const selfParticipant = this.inputGraph.getParticipantSlots(tick).find((participant) => participant.id === selfId);
4246
+ if (selfParticipant) {
4247
+ this.inputGraph.addOptimisticInput(
4248
+ { targetTick: tick, payload, sig: signature, idx: selfParticipant.slot },
4249
+ this.publicKey
4250
+ );
4251
+ }
4252
+ const encoded = messageCodec.encodeInput(tick, payload, signature);
4253
+ await this._send(encoded);
4254
+ return encoded;
4255
+ }
4256
+ _nextChannel() {
4257
+ if (this.dataChannels.length === 0) return null;
4258
+ if (this.roundRobinIndex >= this.dataChannels.length) {
4259
+ this.roundRobinIndex = 0;
4260
+ }
4261
+ return this.dataChannels[this.roundRobinIndex++] ?? null;
4262
+ }
4263
+ async _connectLoop() {
4264
+ let consecutiveFailures = 0;
4265
+ while (!this.stopped) {
4266
+ try {
4267
+ const joinInput = this._generateNullInput();
4268
+ const joinParam = uint8ArrayToBase64URL(joinInput);
4269
+ const configWithCreds = new SessionConfig({
4270
+ ...this.sessionConfig,
4271
+ credentials: joinParam
4272
+ });
4273
+ const sessionParam = configWithCreds.toBase64EncodedConnectionURL();
4274
+ const base = "https://" + this.sessionConfig.authority;
4275
+ const pc = new RTCPeerConnection({
4276
+ iceServers: this.iceServers
4277
+ });
4278
+ this.peerConnection = pc;
4279
+ this.connectionGeneration++;
4280
+ const generation = this.connectionGeneration;
4281
+ pc.ondatachannel = (event) => {
4282
+ if (generation === this.connectionGeneration) {
4283
+ this._handleDataChannel(event.channel, generation);
4284
+ }
4285
+ };
4286
+ pc.onconnectionstatechange = () => {
4287
+ if (pc.connectionState === "failed" || pc.connectionState === "closed") {
4288
+ if (generation === this.connectionGeneration) {
4289
+ this._setConnected(false);
4290
+ this._cleanupPeerConnection();
4291
+ }
4292
+ }
4293
+ };
4294
+ pc.createDataChannel("negotiation");
4295
+ const offer = await pc.createOffer();
4296
+ await pc.setLocalDescription(offer);
4297
+ await this._waitForIceGathering(pc);
4298
+ const localDesc = pc.localDescription;
4299
+ if (!localDesc) {
4300
+ throw new Error("Failed to get local description");
4301
+ }
4302
+ const pubKeyHex = bytesToHex2(this.publicKey);
4303
+ const sseURL = `${base}/rtc/events?session=${sessionParam}&pubkey=${pubKeyHex}`;
4304
+ const sseController = new AbortController();
4305
+ const ssePromise = this._listenForAnswer(sseURL, sseController.signal);
4306
+ const offerURL = `${base}/rtc/offer?session=${sessionParam}&from=${pubKeyHex}&to=relay`;
4307
+ const offerResponse = await fetch(offerURL, {
4308
+ method: "POST",
4309
+ headers: { "Content-Type": "application/json" },
4310
+ body: JSON.stringify({
4311
+ sdp: localDesc.sdp,
4312
+ type: localDesc.type
4313
+ })
4314
+ });
4315
+ if (!offerResponse.ok) {
4316
+ sseController.abort();
4317
+ throw new Error(`Offer rejected: ${offerResponse.status}`);
4318
+ }
4319
+ const timeoutPromise = new Promise((_, reject) => {
4320
+ setTimeout(() => reject(new Error("SSE timeout")), this.connectionTimeoutMs);
4321
+ });
4322
+ const answerSDP = await Promise.race([ssePromise, timeoutPromise]);
4323
+ sseController.abort();
4324
+ await pc.setRemoteDescription({
4325
+ type: "answer",
4326
+ sdp: answerSDP
4327
+ });
4328
+ this.stats.reconnections++;
4329
+ this._setConnected(true);
4330
+ this.dataChannels = [];
4331
+ this.replayChannels.clear();
4332
+ this.roundRobinIndex = 0;
4333
+ consecutiveFailures = 0;
4334
+ await new Promise((resolve) => {
4335
+ pc.onconnectionstatechange = () => {
4336
+ if (pc.connectionState === "failed" || pc.connectionState === "closed" || pc.connectionState === "disconnected") {
4337
+ resolve();
4338
+ }
4339
+ };
4340
+ });
4341
+ } catch (e) {
4342
+ if (this.debug) {
4343
+ console.warn("connect loop error", e);
4344
+ }
4345
+ consecutiveFailures++;
4346
+ }
4347
+ this._setConnected(false);
4348
+ this._cleanupPeerConnection();
4349
+ if (this.stopped) break;
4350
+ const delay = Math.min(consecutiveFailures * 250, 1e3);
4351
+ await new Promise((resolve) => setTimeout(resolve, delay));
4352
+ }
4353
+ if (this.debug) {
4354
+ console.log("connect loop exited");
4355
+ }
4356
+ }
4357
+ // Wait for ICE gathering to complete
4358
+ async _waitForIceGathering(pc) {
4359
+ if (pc.iceGatheringState === "complete") {
4360
+ return;
4361
+ }
4362
+ return new Promise((resolve) => {
4363
+ pc.onicegatheringstatechange = () => {
4364
+ if (pc.iceGatheringState === "complete") {
4365
+ resolve();
4366
+ }
4367
+ };
4368
+ });
4369
+ }
4370
+ // Listen for answer from SSE
4371
+ async _listenForAnswer(url, signal) {
4372
+ const response = await fetch(url, {
4373
+ headers: { Accept: "text/event-stream", "Cache-Control": "no-cache" },
4374
+ signal
4375
+ });
4376
+ if (!response.ok) {
4377
+ throw new Error(`SSE connection failed: ${response.status}`);
4378
+ }
4379
+ const reader = response.body?.getReader();
4380
+ if (!reader) {
4381
+ throw new Error("SSE response has no body");
4382
+ }
4383
+ const decoder = new TextDecoder();
4384
+ let buffer2 = "";
4385
+ let eventType = "";
4386
+ let eventData = "";
4387
+ try {
4388
+ while (true) {
4389
+ const { value, done } = await reader.read();
4390
+ if (done) break;
4391
+ buffer2 += decoder.decode(value, { stream: true });
4392
+ const lines = buffer2.split("\n");
4393
+ buffer2 = lines.pop() ?? "";
4394
+ for (const line of lines) {
4395
+ if (line.startsWith("event:")) {
4396
+ eventType = line.slice(6).trim();
4397
+ } else if (line.startsWith("data:")) {
4398
+ eventData = line.slice(5).trim();
4399
+ } else if (line === "" && eventData) {
4400
+ if (eventType === "answer") {
4401
+ const answerMsg = JSON.parse(eventData);
4402
+ if (answerMsg.from === "relay" && answerMsg.sdp) {
4403
+ return answerMsg.sdp;
4404
+ }
4405
+ }
4406
+ eventType = "";
4407
+ eventData = "";
4408
+ }
4409
+ }
4410
+ }
4411
+ } finally {
4412
+ reader.releaseLock();
4413
+ }
4414
+ throw new Error("SSE stream closed without receiving answer");
4415
+ }
4416
+ _handleDataChannel(dc, generation) {
4417
+ const handle = {
4418
+ dc,
4419
+ index: this.dataChannels.length,
4420
+ isReplay: false,
4421
+ generation
4422
+ };
4423
+ dc.binaryType = "arraybuffer";
4424
+ dc.onopen = () => {
4425
+ if (generation === this.connectionGeneration) {
4426
+ this.dataChannels.push(handle);
4427
+ if (this.outbox.length > 0) {
4428
+ this._flushOutbox().catch(warnUnexpected);
4429
+ }
4430
+ }
4431
+ };
4432
+ dc.onmessage = (event) => {
4433
+ if (generation === this.connectionGeneration) {
4434
+ this._handleMessage(handle, new Uint8Array(event.data));
4435
+ }
4436
+ };
4437
+ dc.onclose = () => {
4438
+ this._dropChannel(handle);
4439
+ };
4440
+ dc.onerror = () => {
4441
+ this._dropChannel(handle);
4442
+ };
4443
+ }
4444
+ _handleMessage(handle, data) {
4445
+ if (data.length < 3) return;
4446
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
4447
+ const msgType = view.getUint8(0);
4448
+ const msgLen = view.getUint16(1, true);
4449
+ const totalLen = 3 + msgLen;
4450
+ if (data.length < totalLen) return;
4451
+ const msg = data.slice(0, totalLen);
4452
+ this.stats.messagesRecv.inc();
4453
+ if (msgType === MSG_TYPE_PING) {
4454
+ const pingData = messageCodec.decode(msg);
4455
+ this.tickRate = pingData.tickRate;
4456
+ if (pingData.isReplay) {
4457
+ handle.isReplay = true;
4458
+ const idx = this.dataChannels.indexOf(handle);
4459
+ if (idx >= 0 && handle.generation === this.connectionGeneration) {
4460
+ this.dataChannels.splice(idx, 1);
4461
+ if (this.roundRobinIndex > idx) {
4462
+ this.roundRobinIndex--;
4463
+ }
4464
+ this.replayChannels.add(handle);
4465
+ }
4466
+ handle.pongInterval = setInterval(() => {
4467
+ const syncHead2 = this.inputGraph.getSyncHead();
4468
+ const latestHead2 = this.inputGraph.getPredictedHead();
4469
+ const pongData2 = messageCodec.encodePong(syncHead2.tick, latestHead2.tick);
4470
+ try {
4471
+ handle.dc.send(pongData2);
4472
+ } catch {
4473
+ if (handle.pongInterval) {
4474
+ clearInterval(handle.pongInterval);
4475
+ }
4476
+ }
4477
+ }, 1e3);
4478
+ }
4479
+ const syncHead = this.inputGraph.getSyncHead();
4480
+ const latestHead = this.inputGraph.getPredictedHead();
4481
+ const pongData = messageCodec.encodePong(syncHead.tick, latestHead.tick);
4482
+ try {
4483
+ handle.dc.send(pongData);
4484
+ } catch {
4485
+ this._dropChannel(handle);
4486
+ }
4487
+ } else if (msgType === MSG_TYPE_TICK) {
4488
+ const tickData = messageCodec.decode(msg);
4489
+ try {
4490
+ this.inputGraph.addSyncTick(tickData);
4491
+ this._maybeResetDeadline();
4492
+ } catch (err2) {
4493
+ if (this.debug) {
4494
+ console.warn("Failed to process tick message:", err2 instanceof Error ? err2.message : err2, tickData);
4495
+ }
4496
+ }
4497
+ }
4498
+ }
4499
+ _dropChannel(handle) {
4500
+ if (handle.generation !== this.connectionGeneration) {
4501
+ this._cleanupHandle(handle);
4502
+ return;
4503
+ }
4504
+ if (handle.isReplay) {
4505
+ this.replayChannels.delete(handle);
4506
+ this._cleanupHandle(handle);
4507
+ return;
4508
+ }
4509
+ const idx = this.dataChannels.indexOf(handle);
4510
+ if (idx >= 0) {
4511
+ this.dataChannels.splice(idx, 1);
4512
+ if (this.roundRobinIndex > idx) {
4513
+ this.roundRobinIndex--;
4514
+ }
4515
+ }
4516
+ this._cleanupHandle(handle);
4517
+ }
4518
+ _cleanupHandle(handle) {
4519
+ if (handle.pongInterval) {
4520
+ clearInterval(handle.pongInterval);
4521
+ handle.pongInterval = null;
4522
+ }
4523
+ try {
4524
+ handle.dc.close();
4525
+ } catch {
4526
+ }
4527
+ }
4528
+ async _flushOutbox() {
4529
+ if (this.flushingOutbox) return;
4530
+ this.flushingOutbox = true;
4531
+ try {
4532
+ while (this.outbox.length > 0 && this.dataChannels.length > 0 && this.connected && !this.stopped) {
4533
+ const data = this.outbox.shift();
4534
+ if (!data) break;
4535
+ const handle = this._nextChannel();
4536
+ if (!handle) {
4537
+ this.outbox.unshift(data);
4538
+ break;
4539
+ }
4540
+ try {
4541
+ handle.dc.send(data);
4542
+ this.stats.messagesSent.inc();
4543
+ } catch {
4544
+ this._dropChannel(handle);
4545
+ this.outbox.unshift(data);
4546
+ break;
4547
+ }
4548
+ }
4549
+ } finally {
4550
+ this.flushingOutbox = false;
4551
+ }
4552
+ }
4553
+ _cleanupPeerConnection() {
4554
+ const handles = [...this.dataChannels, ...this.replayChannels];
4555
+ this.dataChannels = [];
4556
+ this.replayChannels.clear();
4557
+ this.roundRobinIndex = 0;
4558
+ for (const h of handles) {
4559
+ this._cleanupHandle(h);
4560
+ }
4561
+ const pc = this.peerConnection;
4562
+ this.peerConnection = null;
4563
+ if (pc) {
4564
+ try {
4565
+ pc.close();
4566
+ } catch {
4567
+ }
4568
+ }
4569
+ }
4570
+ _maybeResetDeadline() {
4571
+ const syncHead = this.inputGraph.getSyncHead();
4572
+ if (syncHead.tick >= this.tickDeadlineWants) {
4573
+ this._resetDeadline(syncHead.tick + 1);
4574
+ }
4575
+ }
4576
+ _resetDeadline(wants) {
4577
+ this.tickDeadlineWants = wants;
4578
+ if (this.tickDeadlineTimer) {
4579
+ clearTimeout(this.tickDeadlineTimer);
4580
+ }
4581
+ if (!this.tickRate) {
4582
+ return;
4583
+ }
4584
+ this.tickDeadlineTimer = setTimeout(
4585
+ this._onTickDeadlineExceeded.bind(this),
4586
+ 1e3 / this.tickRate + this.tickDeadlineGrace
4587
+ );
4588
+ }
4589
+ _onTickDeadlineExceeded() {
4590
+ const selfParticipant = this.inputGraph.getParticipantSlots(this.tickDeadlineWants).find((participant) => participant.id === bytesToHex2(this.publicKey));
4591
+ if (selfParticipant) {
4592
+ try {
4593
+ this.inputGraph.addOptimisticInput(
4594
+ {
4595
+ targetTick: this.tickDeadlineWants,
4596
+ payload: new Uint8Array(0),
4597
+ sig: new Uint8Array(0),
4598
+ idx: selfParticipant.slot
4599
+ },
4600
+ this.publicKey
4601
+ );
4602
+ } catch (err2) {
4603
+ if (this.debug) {
4604
+ console.error("failed to add empty optimistic input:", err2 instanceof Error ? err2.message : err2);
4605
+ }
4606
+ }
4607
+ } else {
4608
+ if (this.debug) {
4609
+ console.warn("unable to add empty optimistic input as we do not have a slot assigned yet");
4610
+ }
4611
+ }
4612
+ this._resetDeadline(this.tickDeadlineWants + 1);
4613
+ }
4614
+ };
4615
+ function warnUnexpected(err2) {
4616
+ console.warn("channel unexpected:", err2);
4617
+ }
4618
+
4039
4619
  // src/input-codec.ts
4040
4620
  var input_codec_exports = {};
4041
4621
  __export(input_codec_exports, {
@@ -4956,13 +5536,13 @@ function computeNextStateId(prevStateId, tick, orderedPayloadsHash) {
4956
5536
  buf2.set(prevStateId, 0);
4957
5537
  new DataView(buf2.buffer).setUint32(STATE_ID_SIZE, tick, true);
4958
5538
  buf2.set(orderedPayloadsHash, STATE_ID_SIZE + 4);
4959
- return sha2562(buf2);
5539
+ return sha256(buf2);
4960
5540
  }
4961
5541
  function computeNextStateIdFromPayloads(prevStateId, tick, orderedPayloads) {
4962
5542
  return computeNextStateId(prevStateId, tick, hashPayloads(orderedPayloads));
4963
5543
  }
4964
5544
  function computeGenesisStateId(genesisHash) {
4965
- return sha2562(genesisHash);
5545
+ return sha256(genesisHash);
4966
5546
  }
4967
5547
  function createState(schema, genesisHash, tickRate) {
4968
5548
  const buffer2 = new ArrayBuffer(schema.totalSize);
@@ -6288,7 +6868,7 @@ var Rollback = class {
6288
6868
  return this.getState();
6289
6869
  }
6290
6870
  loop = () => {
6291
- this._loop().catch(warnUnexpected);
6871
+ this._loop().catch(warnUnexpected2);
6292
6872
  };
6293
6873
  // _loop runs hot and attempts to advance the state as far as possible
6294
6874
  // cool it with tickGraceMs
@@ -6558,12 +7138,12 @@ var Rollback = class {
6558
7138
  return null;
6559
7139
  }
6560
7140
  };
6561
- function warnUnexpected(err2) {
7141
+ function warnUnexpected2(err2) {
6562
7142
  console.warn("rollback unexpected:", err2);
6563
7143
  }
6564
7144
 
6565
- // src/channel.worker.ts
6566
- var workerCode = 'var Wr=Object.defineProperty;var jr=(e,t,n)=>t in e?Wr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var y=(e,t,n)=>jr(e,typeof t!="symbol"?t+"":t,n);var Ge=Symbol("Comlink.proxy"),Yr=Symbol("Comlink.endpoint"),qr=Symbol("Comlink.releaseProxy"),me=Symbol("Comlink.finalizer"),Ft=Symbol("Comlink.thrown"),Oe=e=>typeof e=="object"&&e!==null||typeof e=="function",Xr={canHandle:e=>Oe(e)&&e[Ge],serialize(e){let{port1:t,port2:n}=new MessageChannel;return ht(e,t),[n,[n]]},deserialize(e){return e.start(),ei(e)}},Jr={canHandle:e=>Oe(e)&&Ft in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},$e=new Map([["proxy",Xr],["throw",Jr]]);function Qr(e,t){for(let n of e)if(t===n||n==="*"||n instanceof RegExp&&n.test(t))return!0;return!1}function ht(e,t=globalThis,n=["*"]){t.addEventListener("message",function r(i){if(!i||!i.data)return;if(!Qr(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:s,type:o,path:a}=Object.assign({path:[]},i.data),u=(i.data.argumentList||[]).map(et),f;try{let d=a.slice(0,-1).reduce((m,x)=>m[x],e),l=a.reduce((m,x)=>m[x],e);switch(o){case"GET":f=l;break;case"SET":d[a.slice(-1)[0]]=et(i.data.value),f=!0;break;case"APPLY":f=l.apply(d,u);break;case"CONSTRUCT":{let m=new l(...u);f=oi(m)}break;case"ENDPOINT":{let{port1:m,port2:x}=new MessageChannel;ht(e,x),f=si(m,[m])}break;case"RELEASE":f=void 0;break;default:return}}catch(d){f={value:d,[Ft]:0}}Promise.resolve(f).catch(d=>({value:d,[Ft]:0})).then(d=>{let[l,m]=Zt(d);t.postMessage(Object.assign(Object.assign({},l),{id:s}),m),o==="RELEASE"&&(t.removeEventListener("message",r),Fe(t),me in e&&typeof e[me]=="function"&&e[me]())}).catch(d=>{let[l,m]=Zt({value:new TypeError("Unserializable return value"),[Ft]:0});t.postMessage(Object.assign(Object.assign({},l),{id:s}),m)})}),t.start&&t.start()}function ti(e){return e.constructor.name==="MessagePort"}function Fe(e){ti(e)&&e.close()}function ei(e,t){let n=new Map;return e.addEventListener("message",function(i){let{data:s}=i;if(!s||!s.id)return;let o=n.get(s.id);if(o)try{o(s)}finally{n.delete(s.id)}}),xe(e,n,[],t)}function $t(e){if(e)throw new Error("Proxy has been released and is not useable")}function Ke(e){return lt(e,new Map,{type:"RELEASE"}).then(()=>{Fe(e)})}var Kt=new WeakMap,zt="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(Kt.get(e)||0)-1;Kt.set(e,t),t===0&&Ke(e)});function ni(e,t){let n=(Kt.get(t)||0)+1;Kt.set(t,n),zt&&zt.register(e,t,e)}function ri(e){zt&&zt.unregister(e)}function xe(e,t,n=[],r=function(){}){let i=!1,s=new Proxy(r,{get(o,a){if($t(i),a===qr)return()=>{ri(s),Ke(e),t.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>s};let u=lt(e,t,{type:"GET",path:n.map(f=>f.toString())}).then(et);return u.then.bind(u)}return xe(e,t,[...n,a])},set(o,a,u){$t(i);let[f,d]=Zt(u);return lt(e,t,{type:"SET",path:[...n,a].map(l=>l.toString()),value:f},d).then(et)},apply(o,a,u){$t(i);let f=n[n.length-1];if(f===Yr)return lt(e,t,{type:"ENDPOINT"}).then(et);if(f==="bind")return xe(e,t,n.slice(0,-1));let[d,l]=De(u);return lt(e,t,{type:"APPLY",path:n.map(m=>m.toString()),argumentList:d},l).then(et)},construct(o,a){$t(i);let[u,f]=De(a);return lt(e,t,{type:"CONSTRUCT",path:n.map(d=>d.toString()),argumentList:u},f).then(et)}});return ni(s,e),s}function ii(e){return Array.prototype.concat.apply([],e)}function De(e){let t=e.map(Zt);return[t.map(n=>n[0]),ii(t.map(n=>n[1]))]}var ze=new WeakMap;function si(e,t){return ze.set(e,t),e}function oi(e){return Object.assign(e,{[Ge]:!0})}function Zt(e){for(let[t,n]of $e)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},i]}return[{type:"RAW",value:e},ze.get(e)||[]]}function et(e){switch(e.type){case"HANDLER":return $e.get(e.name).deserialize(e.value);case"RAW":return e.value}}function lt(e,t,n,r){return new Promise(i=>{let s=ai();t.set(s,i),e.start&&e.start(),e.postMessage(Object.assign({id:s},n),r)})}function ai(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function ci(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ze(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function yt(e,...t){if(!ci(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ve(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ze(e.outputLen),Ze(e.blockLen)}function gt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function We(e,t){yt(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function nt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Vt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function L(e,t){return e<<32-t|e>>>t}function ui(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ut(e){return typeof e=="string"&&(e=ui(e)),yt(e),e}var pt=class{};function je(e){let t=r=>e().update(Ut(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function fi(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),u=r?4:0,f=r?0:4;e.setUint32(t+u,o,r),e.setUint32(t+f,a,r)}function Ye(e,t,n){return e&t^~e&n}function qe(e,t,n){return e&t^e&n^t&n}var Wt=class extends pt{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Vt(this.buffer)}update(t){gt(this),t=Ut(t),yt(t);let{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let u=Vt(t);for(;i<=s-o;o+=i)this.process(u,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){gt(this),We(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:s}=this,{pos:o}=this;n[o++]=128,nt(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;fi(r,i-8,BigInt(this.length*8),s),this.process(r,0);let a=Vt(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let f=u/4,d=this.get();if(f>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,d[l],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}},K=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var di=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),q=new Uint32Array(64),jt=class extends Wt{constructor(t=32){super(64,t,8,!1),this.A=K[0]|0,this.B=K[1]|0,this.C=K[2]|0,this.D=K[3]|0,this.E=K[4]|0,this.F=K[5]|0,this.G=K[6]|0,this.H=K[7]|0}get(){let{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:u}=this;return[t,n,r,i,s,o,a,u]}set(t,n,r,i,s,o,a,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=u|0}process(t,n){for(let l=0;l<16;l++,n+=4)q[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){let m=q[l-15],x=q[l-2],b=L(m,7)^L(m,18)^m>>>3,A=L(x,17)^L(x,19)^x>>>10;q[l]=A+q[l-7]+b+q[l-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:u,G:f,H:d}=this;for(let l=0;l<64;l++){let m=L(a,6)^L(a,11)^L(a,25),x=d+m+Ye(a,u,f)+di[l]+q[l]|0,A=(L(r,2)^L(r,13)^L(r,22))+qe(r,i,s)|0;d=f,f=u,u=a,a=o+x|0,o=s,s=i,i=r,r=x+A|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,i,s,o,a,u,f,d)}roundClean(){nt(q)}destroy(){this.set(0,0,0,0,0,0,0,0),nt(this.buffer)}};var Xe=je(()=>new jt);var rt=Xe;var li={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:st,n:V,Gx:hi,Gy:pi,b:rn}=li,P=32,xt=64,S=(e="")=>{throw new Error(e)},sn=e=>typeof e=="bigint",on=e=>typeof e=="string",yi=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",at=(e,t)=>!yi(e)||typeof t=="number"&&t>0&&e.length!==t?S("Uint8Array expected"):e,ot=e=>new Uint8Array(e),gi=e=>Uint8Array.from(e),an=(e,t)=>e.toString(16).padStart(t,"0"),Xt=e=>Array.from(at(e)).map(t=>an(t,2)).join(""),z={_0:48,_9:57,A:65,F:70,a:97,f:102},Je=e=>{if(e>=z._0&&e<=z._9)return e-z._0;if(e>=z.A&&e<=z.F)return e-(z.A-10);if(e>=z.a&&e<=z.f)return e-(z.a-10)},ke=e=>{let t="hex invalid";if(!on(e))return S(t);let n=e.length,r=n/2;if(n%2)return S(t);let i=ot(r);for(let s=0,o=0;s<r;s++,o+=2){let a=Je(e.charCodeAt(o)),u=Je(e.charCodeAt(o+1));if(a===void 0||u===void 0)return S(t);i[s]=a*16+u}return i},ct=(e,t)=>at(on(e)?ke(e):gi(at(e)),t),cn=()=>globalThis?.crypto,mi=()=>cn()?.subtle??S("crypto.subtle must be defined"),ut=(...e)=>{let t=ot(e.reduce((r,i)=>r+at(i).length,0)),n=0;return e.forEach(r=>{t.set(r,n),n+=r.length}),t},Se=(e=P)=>cn().getRandomValues(ot(e)),bt=BigInt,Pt=(e,t,n,r="bad number: out of range")=>sn(e)&&t<=e&&e<n?e:S(r),g=(e,t=st)=>{let n=e%t;return n>=0n?n:t+n},Z=e=>g(e,V),Jt=(e,t)=>{(e===0n||t<=0n)&&S("no inverse n="+e+" mod="+t);let n=g(e,t),r=t,i=0n,s=1n,o=1n,a=0n;for(;n!==0n;){let u=r/n,f=r%n,d=i-o*u,l=s-a*u;r=n,n=f,i=o,s=a,o=d,a=l}return r===1n?g(i,t):S("no inverse")},xi=e=>{let t=Bt[e];return typeof t!="function"&&S("hashes."+e+" not set"),t},Qe=e=>e instanceof X?e:S("Point expected"),un=e=>g(g(e*e)*e+rn),tn=e=>Pt(e,0n,st),It=e=>Pt(e,1n,st),be=e=>Pt(e,1n,V),we=e=>(e&1n)===0n,mt=e=>Uint8Array.of(e),fn=e=>mt(we(e)?2:3),bi=e=>{let t=un(It(e)),n=1n;for(let r=t,i=(st+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%st),r=r*r%st;return g(n*n)===t?n:S("sqrt invalid")},G=class G{constructor(t,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=tn(t),this.py=It(n),this.pz=tn(r),Object.freeze(this)}static fromBytes(t){at(t);let n,r=t[0],i=t.subarray(1),s=Yt(i,0,P),o=t.length;if(o===P+1&&[2,3].includes(r)){let a=bi(s),u=we(a);we(bt(r))!==u&&(a=g(-a)),n=new G(s,a,1n)}return o===xt+1&&r===4&&(n=new G(s,Yt(i,P,xt),1n)),n?n.assertValidity():S("bad point: not on curve")}equals(t){let{px:n,py:r,pz:i}=this,{px:s,py:o,pz:a}=Qe(t),u=g(n*a),f=g(s*i),d=g(r*a),l=g(o*i);return u===f&&d===l}is0(){return this.equals(it)}negate(){return new G(this.px,g(-this.py),this.pz)}double(){return this.add(this)}add(t){let{px:n,py:r,pz:i}=this,{px:s,py:o,pz:a}=Qe(t),u=0n,f=rn,d=0n,l=0n,m=0n,x=g(f*3n),b=g(n*s),A=g(r*o),I=g(i*a),E=g(n+r),k=g(s+o);E=g(E*k),k=g(b+A),E=g(E-k),k=g(n+i);let _=g(s+a);return k=g(k*_),_=g(b+I),k=g(k-_),_=g(r+i),d=g(o+a),_=g(_*d),d=g(A+I),_=g(_-d),m=g(u*k),d=g(x*I),m=g(d+m),d=g(A-m),m=g(A+m),l=g(d*m),A=g(b+b),A=g(A+b),I=g(u*I),k=g(x*k),A=g(A+I),I=g(b-I),I=g(u*I),k=g(k+I),b=g(A*k),l=g(l+b),b=g(_*k),d=g(E*d),d=g(d-b),b=g(E*A),m=g(_*m),m=g(m+b),new G(d,l,m)}multiply(t,n=!0){if(!n&&t===0n)return it;if(be(t),t===1n)return this;if(this.equals(O))return _i(t).p;let r=it,i=O;for(let s=this;t>0n;s=s.double(),t>>=1n)t&1n?r=r.add(s):n&&(i=i.add(s));return r}toAffine(){let{px:t,py:n,pz:r}=this;if(this.equals(it))return{x:0n,y:0n};if(r===1n)return{x:t,y:n};let i=Jt(r,st);return g(r*i)!==1n&&S("inverse invalid"),{x:g(t*i),y:g(n*i)}}assertValidity(){let{x:t,y:n}=this.toAffine();return It(t),It(n),g(n*n)===un(t)?this:S("bad point: not on curve")}toBytes(t=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=J(n);return t?ut(fn(r),i):ut(mt(4),i,J(r))}static fromAffine(t){let{x:n,y:r}=t;return n===0n&&r===0n?it:new G(n,r,1n)}toHex(t){return Xt(this.toBytes(t))}static fromPrivateKey(t){return O.multiply(vt(t))}static fromHex(t){return G.fromBytes(ct(t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(t){return this.toBytes(t)}};y(G,"BASE"),y(G,"ZERO");var X=G,O=new X(hi,pi,1n),it=new X(0n,1n,0n);X.BASE=O;X.ZERO=it;var wi=(e,t,n)=>O.multiply(t,!1).add(e.multiply(n,!1)).assertValidity(),Ht=e=>bt("0x"+(Xt(e)||"0")),Yt=(e,t,n)=>Ht(e.subarray(t,n)),Ti=2n**256n,J=e=>ke(an(Pt(e,0n,Ti),xt)),vt=e=>{let t=sn(e)?e:Ht(ct(e,P));return Pt(t,1n,V,"private key invalid 3")},Te=e=>e>V>>1n,dn=(e,t=!0)=>O.multiply(vt(e)).toBytes(t),_t=class e{constructor(t,n,r){y(this,"r");y(this,"s");y(this,"recovery");this.r=be(t),this.s=be(n),r!=null&&(this.recovery=r),Object.freeze(this)}static fromBytes(t){at(t,xt);let n=Yt(t,0,P),r=Yt(t,P,xt);return new e(n,r)}toBytes(){let{r:t,s:n}=this;return ut(J(t),J(n))}addRecoveryBit(t){return new e(this.r,this.s,t)}hasHighS(){return Te(this.s)}toCompactRawBytes(){return this.toBytes()}toCompactHex(){return Xt(this.toBytes())}recoverPublicKey(t){return Si(this,t)}static fromCompact(t){return e.fromBytes(ct(t,xt))}assertValidity(){return this}normalizeS(){let{r:t,s:n,recovery:r}=this;return Te(n)?new e(t,Z(-n),r):this}},ln=e=>{let t=e.length*8-256;t>1024&&S("msg invalid");let n=Ht(e);return t>0?n>>bt(t):n},hn=e=>Z(ln(at(e))),pn={lowS:!0};var Ai=(e,t,n=pn)=>{["der","recovered","canonical"].some(m=>m in n)&&S("option not supported");let{lowS:r,extraEntropy:i}=n;r==null&&(r=!0);let s=J,o=hn(ct(e)),a=s(o),u=vt(t),f=[s(u),a];i&&f.push(i===!0?Se(P):ct(i));let d=o,l=m=>{let x=ln(m);if(!(1n<=x&&x<V))return;let b=O.multiply(x).toAffine(),A=Z(b.x);if(A===0n)return;let I=Jt(x,V),E=Z(I*Z(d+Z(u*A)));if(E===0n)return;let k=E,_=(b.x===A?0:2)|Number(b.y&1n);return r&&Te(E)&&(k=Z(-E),_^=1),new _t(A,k,_)};return{seed:ut(...f),k2sig:l}},ki=e=>{let t=ot(P),n=ot(P),r=0,i=ot(0),s=()=>{t.fill(1),n.fill(0),r=0},o=1e3,a="drbg: tried 1000 values";if(e){let u=(...l)=>Bt.hmacSha256Async(n,t,...l),f=async(l=i)=>{n=await u(mt(0),l),t=await u(),l.length!==0&&(n=await u(mt(1),l),t=await u())},d=async()=>(r++>=o&&S(a),t=await u(),t);return async(l,m)=>{s(),await f(l);let x;for(;!(x=m(await d()));)await f();return s(),x}}else{let u=(...l)=>xi("hmacSha256Sync")(n,t,...l),f=(l=i)=>{n=u(mt(0),l),t=u(),l.length!==0&&(n=u(mt(1),l),t=u())},d=()=>(r++>=o&&S(a),t=u(),t);return(l,m)=>{s(),f(l);let x;for(;!(x=m(d()));)f();return s(),x}}};var yn=(e,t,n=pn)=>{let{seed:r,k2sig:i}=Ai(e,t,n);return ki(!1)(r,i)};var Si=(e,t)=>{let{r:n,s:r,recovery:i}=e;[0,1,2,3].includes(i)||S("recovery id invalid");let s=hn(ct(t,P)),o=i===2||i===3?n+V:n;It(o);let a=fn(bt(i)),u=ut(a,J(o)),f=X.fromBytes(u),d=Jt(o,V),l=Z(-s*d),m=Z(r*d);return wi(f,l,m)};var gn=e=>{e=ct(e),(e.length<P+8||e.length>1024)&&S("expected 40-1024b");let t=g(Ht(e),V-1n);return J(t+1n)},Ei=()=>gn(Se(P+16)),Ui="SHA-256",Bt={hexToBytes:ke,bytesToHex:Xt,concatBytes:ut,bytesToNumberBE:Ht,numberToBytesBE:J,mod:g,invert:Jt,hmacSha256Async:async(e,...t)=>{let n=mi(),r="HMAC",i=await n.importKey("raw",e,{name:r,hash:{name:Ui}},!1,["sign"]);return ot(await n.sign(r,i,ut(...t)))},hmacSha256Sync:void 0,hashToPrivateKey:gn,randomBytes:Se},mn={normPrivateKeyToScalar:vt,isValidPrivateKey:e=>{try{return!!vt(e)}catch{return!1}},randomPrivateKey:Ei,precompute:(e=8,t=O)=>(t.multiply(3n),t)},qt=8,Ii=256,xn=Math.ceil(Ii/qt)+1,Ae=2**(qt-1),vi=()=>{let e=[],t=O,n=t;for(let r=0;r<xn;r++){n=t,e.push(n);for(let i=1;i<Ae;i++)n=n.add(t),e.push(n);t=n.double()}return e},en,nn=(e,t)=>{let n=t.negate();return e?n:t},_i=e=>{let t=en||(en=vi()),n=it,r=O,i=2**qt,s=i,o=bt(i-1),a=bt(qt);for(let u=0;u<xn;u++){let f=Number(e&o);e>>=a,f>Ae&&(f-=s,e+=1n);let d=u*Ae,l=d,m=d+Math.abs(f)-1,x=u%2!==0,b=f<0;f===0?r=r.add(nn(x,t[l])):n=n.add(nn(b,t[m]))}return{p:n,f:r}};var Qt=class extends pt{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Ve(t);let r=Ut(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),nt(s)}update(t){return gt(this),this.iHash.update(t),this}digestInto(t){gt(this),yt(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ee=(e,t,n)=>new Qt(e,t).update(n).digest();Ee.create=(e,t)=>new Qt(e,t);var Hi=["string","number","bigint","symbol"],Bi=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function bn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(e===!0||e===!1)return"boolean";let t=typeof e;if(Hi.includes(t))return t;if(t==="function")return"Function";if(Array.isArray(e))return"Array";if(Ni(e))return"Buffer";let n=Ri(e);return n||"Object"}function Ni(e){return e&&e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer.call(null,e)}function Ri(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(Bi.includes(t))return t}var c=class{constructor(t,n,r){this.major=t,this.majorEncoded=t<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}};c.uint=new c(0,"uint",!0);c.negint=new c(1,"negint",!0);c.bytes=new c(2,"bytes",!0);c.string=new c(3,"string",!0);c.array=new c(4,"array",!1);c.map=new c(5,"map",!1);c.tag=new c(6,"tag",!1);c.float=new c(7,"float",!0);c.false=new c(7,"false",!0);c.true=new c(7,"true",!0);c.null=new c(7,"null",!0);c.undefined=new c(7,"undefined",!0);c.break=new c(7,"break",!0);var p=class{constructor(t,n,r){this.type=t,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var wt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Ci=new TextDecoder,Mi=new TextEncoder;function te(e){return wt&&globalThis.Buffer.isBuffer(e)}function Ue(e){return e instanceof Uint8Array?te(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var kn=wt?(e,t,n)=>n-t>64?globalThis.Buffer.from(e.subarray(t,n)).toString("utf8"):Tn(e,t,n):(e,t,n)=>n-t>64?Ci.decode(e.subarray(t,n)):Tn(e,t,n),Sn=wt?e=>e.length>64?globalThis.Buffer.from(e):wn(e):e=>e.length>64?Mi.encode(e):wn(e),$=e=>Uint8Array.from(e),Tt=wt?(e,t,n)=>te(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),En=wt?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Ue(globalThis.Buffer.concat(e,t))):(e,t)=>{let n=new Uint8Array(t),r=0;for(let i of e)r+i.length>n.length&&(i=i.subarray(0,n.length-r)),n.set(i,r),r+=i.length;return n},Un=wt?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function ee(e,t){if(te(e)&&te(t))return e.compare(t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}function wn(e){let t=[],n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=i&63|128):(i&64512)===55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(e.charCodeAt(++r)&1023),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function Tn(e,t,n){let r=[];for(;t<n;){let i=e[t],s=null,o=i>239?4:i>223?3:i>191?2:1;if(t+o<=n){let a,u,f,d;switch(o){case 1:i<128&&(s=i);break;case 2:a=e[t+1],(a&192)===128&&(d=(i&31)<<6|a&63,d>127&&(s=d));break;case 3:a=e[t+1],u=e[t+2],(a&192)===128&&(u&192)===128&&(d=(i&15)<<12|(a&63)<<6|u&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=e[t+1],u=e[t+2],f=e[t+3],(a&192)===128&&(u&192)===128&&(f&192)===128&&(d=(i&15)<<18|(a&63)<<12|(u&63)<<6|f&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),t+=o}return Li(r)}var An=4096;function Li(e){let t=e.length;if(t<=An)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=An));return n}var Di=256,Nt=class{constructor(t=Di){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let n=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let i=n.length-(this.maxCursor-this.cursor)-1;n.set(t,i)}else{if(n){let i=n.length-(this.maxCursor-this.cursor)-1;i<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,i),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(n=Un(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=Tt(r,0,this.cursor)}else n=En(this.chunks,this.cursor);return t&&this.reset(),n}};var w="CBOR decode error:",Ie="CBOR encode error:",Rt=[];Rt[23]=1;Rt[24]=2;Rt[25]=3;Rt[26]=5;Rt[27]=9;function W(e,t,n){if(e.length-t<n)throw new Error(`${w} not enough data for type`)}var U=[24,256,65536,4294967296,BigInt("18446744073709551616")];function H(e,t,n){W(e,t,1);let r=e[t];if(n.strict===!0&&r<U[0])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return r}function B(e,t,n){W(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<U[1])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return r}function N(e,t,n){W(e,t,4);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(n.strict===!0&&r<U[2])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);return r}function R(e,t,n){W(e,t,8);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],i=e[t+4]*16777216+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],s=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&s<U[3])throw new Error(`${w} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(n.allowBigInt===!0)return s;throw new Error(`${w} integers outside of the safe integer range are not supported`)}function In(e,t,n,r){return new p(c.uint,H(e,t+1,r),2)}function vn(e,t,n,r){return new p(c.uint,B(e,t+1,r),3)}function _n(e,t,n,r){return new p(c.uint,N(e,t+1,r),5)}function Pn(e,t,n,r){return new p(c.uint,R(e,t+1,r),9)}function C(e,t){return v(e,0,t.value)}function v(e,t,n){if(n<U[0]){let r=Number(n);e.push([t|r])}else if(n<U[1]){let r=Number(n);e.push([t|24,r])}else if(n<U[2]){let r=Number(n);e.push([t|25,r>>>8,r&255])}else if(n<U[3]){let r=Number(n);e.push([t|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<U[4]){let i=[t|27,0,0,0,0,0,0,0],s=Number(r&BigInt(4294967295)),o=Number(r>>BigInt(32)&BigInt(4294967295));i[8]=s&255,s=s>>8,i[7]=s&255,s=s>>8,i[6]=s&255,s=s>>8,i[5]=s&255,i[4]=o&255,o=o>>8,i[3]=o&255,o=o>>8,i[2]=o&255,o=o>>8,i[1]=o&255,e.push(i)}else throw new Error(`${w} encountered BigInt larger than allowable range`)}}C.encodedSize=function(t){return v.encodedSize(t.value)};v.encodedSize=function(t){return t<U[0]?1:t<U[1]?2:t<U[2]?3:t<U[3]?5:9};C.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function Hn(e,t,n,r){return new p(c.negint,-1-H(e,t+1,r),2)}function Bn(e,t,n,r){return new p(c.negint,-1-B(e,t+1,r),3)}function Nn(e,t,n,r){return new p(c.negint,-1-N(e,t+1,r),5)}var ve=BigInt(-1),Rn=BigInt(1);function Cn(e,t,n,r){let i=R(e,t+1,r);if(typeof i!="bigint"){let s=-1-i;if(s>=Number.MIN_SAFE_INTEGER)return new p(c.negint,s,9)}if(r.allowBigInt!==!0)throw new Error(`${w} integers outside of the safe integer range are not supported`);return new p(c.negint,ve-BigInt(i),9)}function ne(e,t){let n=t.value,r=typeof n=="bigint"?n*ve-Rn:n*-1-1;v(e,t.type.majorEncoded,r)}ne.encodedSize=function(t){let n=t.value,r=typeof n=="bigint"?n*ve-Rn:n*-1-1;return r<U[0]?1:r<U[1]?2:r<U[2]?3:r<U[3]?5:9};ne.compareTokens=function(t,n){return t.value<n.value?1:t.value>n.value?-1:0};function Ct(e,t,n,r){W(e,t,n+r);let i=Tt(e,t+n,t+n+r);return new p(c.bytes,i,n+r)}function Mn(e,t,n,r){return Ct(e,t,1,n)}function Ln(e,t,n,r){return Ct(e,t,2,H(e,t+1,r))}function Dn(e,t,n,r){return Ct(e,t,3,B(e,t+1,r))}function Gn(e,t,n,r){return Ct(e,t,5,N(e,t+1,r))}function On(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer bytes lengths not supported`);return Ct(e,t,9,i)}function re(e){return e.encodedBytes===void 0&&(e.encodedBytes=e.type===c.string?Sn(e.value):e.value),e.encodedBytes}function At(e,t){let n=re(t);v(e,t.type.majorEncoded,n.length),e.push(n)}At.encodedSize=function(t){let n=re(t);return v.encodedSize(n.length)+n.length};At.compareTokens=function(t,n){return Oi(re(t),re(n))};function Oi(e,t){return e.length<t.length?-1:e.length>t.length?1:ee(e,t)}function Mt(e,t,n,r,i){let s=n+r;W(e,t,s);let o=new p(c.string,kn(e,t+n,t+s),s);return i.retainStringBytes===!0&&(o.byteValue=Tt(e,t+n,t+s)),o}function $n(e,t,n,r){return Mt(e,t,1,n,r)}function Fn(e,t,n,r){return Mt(e,t,2,H(e,t+1,r),r)}function Kn(e,t,n,r){return Mt(e,t,3,B(e,t+1,r),r)}function zn(e,t,n,r){return Mt(e,t,5,N(e,t+1,r),r)}function Zn(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer string lengths not supported`);return Mt(e,t,9,i,r)}var Vn=At;function kt(e,t,n,r){return new p(c.array,r,n)}function Wn(e,t,n,r){return kt(e,t,1,n)}function jn(e,t,n,r){return kt(e,t,2,H(e,t+1,r))}function Yn(e,t,n,r){return kt(e,t,3,B(e,t+1,r))}function qn(e,t,n,r){return kt(e,t,5,N(e,t+1,r))}function Xn(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer array lengths not supported`);return kt(e,t,9,i)}function Jn(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return kt(e,t,1,1/0)}function ie(e,t){v(e,c.array.majorEncoded,t.value)}ie.compareTokens=C.compareTokens;ie.encodedSize=function(t){return v.encodedSize(t.value)};function St(e,t,n,r){return new p(c.map,r,n)}function Qn(e,t,n,r){return St(e,t,1,n)}function tr(e,t,n,r){return St(e,t,2,H(e,t+1,r))}function er(e,t,n,r){return St(e,t,3,B(e,t+1,r))}function nr(e,t,n,r){return St(e,t,5,N(e,t+1,r))}function rr(e,t,n,r){let i=R(e,t+1,r);if(typeof i=="bigint")throw new Error(`${w} 64-bit integer map lengths not supported`);return St(e,t,9,i)}function ir(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return St(e,t,1,1/0)}function se(e,t){v(e,c.map.majorEncoded,t.value)}se.compareTokens=C.compareTokens;se.encodedSize=function(t){return v.encodedSize(t.value)};function sr(e,t,n,r){return new p(c.tag,n,1)}function or(e,t,n,r){return new p(c.tag,H(e,t+1,r),2)}function ar(e,t,n,r){return new p(c.tag,B(e,t+1,r),3)}function cr(e,t,n,r){return new p(c.tag,N(e,t+1,r),5)}function ur(e,t,n,r){return new p(c.tag,R(e,t+1,r),9)}function oe(e,t){v(e,c.tag.majorEncoded,t.value)}oe.compareTokens=C.compareTokens;oe.encodedSize=function(t){return v.encodedSize(t.value)};var Vi=20,Wi=21,ji=22,Yi=23;function fr(e,t,n,r){if(r.allowUndefined===!1)throw new Error(`${w} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new p(c.null,null,1):new p(c.undefined,void 0,1)}function dr(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${w} indefinite length items not allowed`);return new p(c.break,void 0,1)}function _e(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw new Error(`${w} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw new Error(`${w} Infinity values are not supported`)}return new p(c.float,e,t)}function lr(e,t,n,r){return _e(Pe(e,t+1),3,r)}function hr(e,t,n,r){return _e(He(e,t+1),5,r)}function pr(e,t,n,r){return _e(xr(e,t+1),9,r)}function ae(e,t,n){let r=t.value;if(r===!1)e.push([c.float.majorEncoded|Vi]);else if(r===!0)e.push([c.float.majorEncoded|Wi]);else if(r===null)e.push([c.float.majorEncoded|ji]);else if(r===void 0)e.push([c.float.majorEncoded|Yi]);else{let i,s=!1;(!n||n.float64!==!0)&&(gr(r),i=Pe(D,1),r===i||Number.isNaN(r)?(D[0]=249,e.push(D.slice(0,3)),s=!0):(mr(r),i=He(D,1),r===i&&(D[0]=250,e.push(D.slice(0,5)),s=!0))),s||(qi(r),i=xr(D,1),D[0]=251,e.push(D.slice(0,9)))}}ae.encodedSize=function(t,n){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){gr(r);let i=Pe(D,1);if(r===i||Number.isNaN(r))return 3;if(mr(r),i=He(D,1),r===i)return 5}return 9};var yr=new ArrayBuffer(9),M=new DataView(yr,1),D=new Uint8Array(yr,0);function gr(e){if(e===1/0)M.setUint16(0,31744,!1);else if(e===-1/0)M.setUint16(0,64512,!1);else if(Number.isNaN(e))M.setUint16(0,32256,!1);else{M.setFloat32(0,e);let t=M.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)M.setUint16(0,31744,!1);else if(n===0)M.setUint16(0,(e&2147483648)>>16|r>>13,!1);else{let i=n-127;i<-24?M.setUint16(0,0):i<-14?M.setUint16(0,(t&2147483648)>>16|1<<24+i,!1):M.setUint16(0,(t&2147483648)>>16|i+15<<10|r>>13,!1)}}}function Pe(e,t){if(e.length-t<2)throw new Error(`${w} not enough data for float16`);let n=(e[t]<<8)+e[t+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,s;return r===0?s=i*2**-24:r!==31?s=(i+1024)*2**(r-25):s=i===0?1/0:NaN,n&32768?-s:s}function mr(e){M.setFloat32(0,e,!1)}function He(e,t){if(e.length-t<4)throw new Error(`${w} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function qi(e){M.setFloat64(0,e,!1)}function xr(e,t){if(e.length-t<8)throw new Error(`${w} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}ae.compareTokens=C.compareTokens;function T(e,t,n){throw new Error(`${w} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function ce(e){return()=>{throw new Error(`${w} ${e}`)}}var h=[];for(let e=0;e<=23;e++)h[e]=T;h[24]=In;h[25]=vn;h[26]=_n;h[27]=Pn;h[28]=T;h[29]=T;h[30]=T;h[31]=T;for(let e=32;e<=55;e++)h[e]=T;h[56]=Hn;h[57]=Bn;h[58]=Nn;h[59]=Cn;h[60]=T;h[61]=T;h[62]=T;h[63]=T;for(let e=64;e<=87;e++)h[e]=Mn;h[88]=Ln;h[89]=Dn;h[90]=Gn;h[91]=On;h[92]=T;h[93]=T;h[94]=T;h[95]=ce("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)h[e]=$n;h[120]=Fn;h[121]=Kn;h[122]=zn;h[123]=Zn;h[124]=T;h[125]=T;h[126]=T;h[127]=ce("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)h[e]=Wn;h[152]=jn;h[153]=Yn;h[154]=qn;h[155]=Xn;h[156]=T;h[157]=T;h[158]=T;h[159]=Jn;for(let e=160;e<=183;e++)h[e]=Qn;h[184]=tr;h[185]=er;h[186]=nr;h[187]=rr;h[188]=T;h[189]=T;h[190]=T;h[191]=ir;for(let e=192;e<=215;e++)h[e]=sr;h[216]=or;h[217]=ar;h[218]=cr;h[219]=ur;h[220]=T;h[221]=T;h[222]=T;h[223]=T;for(let e=224;e<=243;e++)h[e]=ce("simple values are not supported");h[244]=T;h[245]=T;h[246]=T;h[247]=fr;h[248]=ce("simple values are not supported");h[249]=lr;h[250]=hr;h[251]=pr;h[252]=T;h[253]=T;h[254]=T;h[255]=dr;var F=[];for(let e=0;e<24;e++)F[e]=new p(c.uint,e,1);for(let e=-1;e>=-24;e--)F[31-e]=new p(c.negint,e,1);F[64]=new p(c.bytes,new Uint8Array(0),1);F[96]=new p(c.string,"",1);F[128]=new p(c.array,0,1);F[160]=new p(c.map,0,1);F[244]=new p(c.false,!1,1);F[245]=new p(c.true,!0,1);F[246]=new p(c.null,null,1);function br(e){switch(e.type){case c.false:return $([244]);case c.true:return $([245]);case c.null:return $([246]);case c.bytes:return e.value.length?void 0:$([64]);case c.string:return e.value===""?$([96]):void 0;case c.array:return e.value===0?$([128]):void 0;case c.map:return e.value===0?$([160]):void 0;case c.uint:return e.value<24?$([Number(e.value)]):void 0;case c.negint:if(e.value>=-24)return $([31-Number(e.value)])}}var Tr=Object.freeze({float64:!0,mapSorter:es,quickEncodeToken:br});function Ji(){let e=[];return e[c.uint.major]=C,e[c.negint.major]=ne,e[c.bytes.major]=At,e[c.string.major]=Vn,e[c.array.major]=ie,e[c.map.major]=se,e[c.tag.major]=oe,e[c.float.major]=ae,e}var Qi=Ji(),Be=new Nt,fe=class e{constructor(t,n){this.obj=t,this.parent=n}includes(t){let n=this;do if(n.obj===t)return!0;while(n=n.parent);return!1}static createCheck(t,n){if(t&&t.includes(n))throw new Error(`${Ie} object contains circular references`);return new e(n,t)}},Q={null:new p(c.null,null),undefined:new p(c.undefined,void 0),true:new p(c.true,!0),false:new p(c.false,!1),emptyArray:new p(c.array,0),emptyMap:new p(c.map,0)},tt={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new p(c.float,e):e>=0?new p(c.uint,e):new p(c.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new p(c.uint,e):new p(c.negint,e)},Uint8Array(e,t,n,r){return new p(c.bytes,e)},string(e,t,n,r){return new p(c.string,e)},boolean(e,t,n,r){return e?Q.true:Q.false},null(e,t,n,r){return Q.null},undefined(e,t,n,r){return Q.undefined},ArrayBuffer(e,t,n,r){return new p(c.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new p(c.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[Q.emptyArray,new p(c.break)]:Q.emptyArray;r=fe.createCheck(r,e);let i=[],s=0;for(let o of e)i[s++]=ue(o,n,r);return n.addBreakTokens?[new p(c.array,e.length),i,new p(c.break)]:[new p(c.array,e.length),i]},Object(e,t,n,r){let i=t!=="Object",s=i?e.keys():Object.keys(e),o=i?e.size:s.length;if(!o)return n.addBreakTokens===!0?[Q.emptyMap,new p(c.break)]:Q.emptyMap;r=fe.createCheck(r,e);let a=[],u=0;for(let f of s)a[u++]=[ue(f,n,r),ue(i?e.get(f):e[f],n,r)];return ts(a,n),n.addBreakTokens?[new p(c.map,o),a,new p(c.break)]:[new p(c.map,o),a]}};tt.Map=tt.Object;tt.Buffer=tt.Uint8Array;for(let e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))tt[`${e}Array`]=tt.DataView;function ue(e,t={},n){let r=bn(e),i=t&&t.typeEncoders&&t.typeEncoders[r]||tt[r];if(typeof i=="function"){let o=i(e,r,t,n);if(o!=null)return o}let s=tt[r];if(!s)throw new Error(`${Ie} unsupported type: ${r}`);return s(e,r,t,n)}function ts(e,t){t.mapSorter&&e.sort(t.mapSorter)}function es(e,t){if(e[0]instanceof p&&t[0]instanceof p){let n=e[0],r=t[0];return n._keyBytes||(n._keyBytes=wr(n.value)),r._keyBytes||(r._keyBytes=wr(r.value)),ee(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function wr(e){return ns(e,Qi,Tr)}function Ar(e,t,n,r){if(Array.isArray(t))for(let i of t)Ar(e,i,n,r);else n[t.type.major](e,t,r)}function ns(e,t,n){let r=ue(e,n);if(!Array.isArray(r)&&n.quickEncodeToken){let i=n.quickEncodeToken(r);if(i)return i;let s=t[r.type.major];if(s.encodedSize){let o=s.encodedSize(r,n),a=new Nt(o);if(s(a,r,n),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${r} was wrong`);return Ue(a.chunks[0])}}return Be.reset(),Ar(Be,r,t,n),Be.toBytes(!0)}var ko=Symbol.for("DONE"),So=Symbol.for("BREAK");function is(e){let t=e;if(typeof t.toBase64=="function")return t.toBase64();let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return btoa(n)}function Ne(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function de(e){return is(e).replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=+$/,"")}function kr(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return Ne(t)}function Sr(e){let n=new TextEncoder().encode(e);return de(n)}function Er(e){let t=kr(e);return new TextDecoder().decode(t)}function le(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}Bt.hmacSha256Sync=(e,...t)=>Ee(rt,e,Bt.concatBytes(...t));var Et=65;var Re=32,Ur=5,Ir=16;function vr(){return mn.randomPrivateKey()}function _r(e){return dn(e,!0)}function Ce(e,t){let n=yn(t,e,{lowS:!0}),r=n.recovery;if(r===void 0)throw new Error("Recovery ID not available");let i=new Uint8Array(Et),s=n.toCompactRawBytes();return i.set(s,0),i[64]=r,i}function Me(e,t){if(t.length!==Et)throw new Error(`Signature must be ${Et} bytes`);let n=t[64];if(n===void 0||n>3)throw new Error(`Invalid recovery ID: ${n}, must be 0-3`);let r=t.subarray(0,64);return _t.fromCompact(r).addRecoveryBit(n).recoverPublicKey(e).toRawBytes(!0)}function Pr(e,t,n){try{let r=Me(t,n);return le(r,e)}catch{return!1}}function Lt(e,t,n){let r=new Uint8Array(20+n.length);return r.set(e,0),new DataView(r.buffer).setUint32(16,t,!0),r.set(n,20),rt(r)}function Hr(e,t,n,r){let i=new Uint8Array(20+Re+Et);return i.set(e,0),new DataView(i.buffer).setUint32(16,t,!0),i.set(n,20),i.set(r,20+Re),rt(i)}function Br(e){if(e.length===0)return new Uint8Array(Re);let t=0;for(let s of e)t+=Ur+s.payload.length+Et;let n=new Uint8Array(t),r=new DataView(n.buffer),i=0;for(let s of e){let o=s.payload.length;r.setUint32(i,s.targetTick,!0),r.setUint8(i+4,o),n.set(s.payload,i+5),n.set(s.sig,i+5+o),i+=Ur+o+Et}return rt(n)}var Nr=253,Rr=8,Cr=32,Mr=1,Lr=60,Dr=1,Gr=255,ss=/^[a-z0-9.-]+$/,os=/^[a-z0-9-]+$/,as=/^[a-zA-Z0-9.-]+(:[0-9]+)?$/;var Dt=class e{constructor(t){y(this,"version");y(this,"authority");y(this,"appID");y(this,"path");y(this,"tickRate");y(this,"maxParticipants");y(this,"maxTicks");y(this,"startTime");y(this,"credentials");if(this.version=t.version,this.authority=t.authority??"",this.appID=t.appID,typeof t.path=="string"){let n=t.path.replace(/^\\/+|\\/+$/g,"");this.path=n===""?[]:n.split("/")}else this.path=t.path;this.tickRate=t.tickRate,this.maxParticipants=t.maxParticipants,this.maxTicks=t.maxTicks,this.startTime=t.startTime,this.credentials=t.credentials??"",this.validate()}validate(){if(this.version!=="v1")throw new Error(`Invalid version: must be "v1", got "${this.version}"`);if(!this.appID)throw new Error("AppID is required");if(this.appID.length>Nr)throw new Error(`AppID too long: ${this.appID.length} chars (max ${Nr})`);if(!ss.test(this.appID))throw new Error(`Invalid appID format: "${this.appID}" (must be lowercase DNS-style)`);if(this.path.length>Rr)throw new Error(`Too many path segments: ${this.path.length} (max ${Rr})`);for(let t=0;t<this.path.length;t++){let n=this.path[t];if(n==="")throw new Error(`Path segment ${t} is empty`);if(n.length>Cr)throw new Error(`Path segment ${t} too long: ${n.length} chars (max ${Cr})`);if(!os.test(n))throw new Error(`Invalid path segment ${t}: "${n}" (must be [a-z0-9-]+)`)}if(!Number.isInteger(this.tickRate))throw new Error(`Invalid tickRate: must be an integer, got ${this.tickRate}`);if(this.tickRate<Mr||this.tickRate>Lr)throw new Error(`Invalid tickRate: must be ${Mr}-${Lr}, got ${this.tickRate}`);if(!Number.isInteger(this.maxParticipants))throw new Error(`Invalid maxParticipants: must be an integer, got ${this.maxParticipants}`);if(this.maxParticipants<Dr||this.maxParticipants>Gr)throw new Error(`Invalid maxParticipants: must be ${Dr}-${Gr}, got ${this.maxParticipants}`);if(!Number.isInteger(this.maxTicks))throw new Error(`Invalid maxTicks: must be an integer, got ${this.maxTicks}`);if(this.maxTicks<1||this.maxTicks>864e3)throw new Error(`Invalid maxTicks: must be 1-864000, got ${this.maxTicks}`);if(this.maxTicks<this.tickRate)throw new Error(`Invalid maxTicks: must be >= tickRate (${this.tickRate}) for at least 1 second duration, got ${this.maxTicks}`);if(!Number.isInteger(this.startTime))throw new Error(`Invalid startTime: must be an integer, got ${this.startTime}`);if(this.startTime<=0)throw new Error(`Invalid startTime: must be > 0, got ${this.startTime}`)}toGenesisHash(){this.validate();let t=new TextEncoder,n=t.encode("multitap:genesis:v1:"),r=t.encode(this.appID),i=n.length+r.length+1;for(let d of this.path)i+=t.encode(d).length+1;i+=6,i+=8;let s=new Uint8Array(i),o=0;s.set(n,o),o+=n.length,s.set(r,o),o+=r.length,s[o++]=0;for(let d of this.path){let l=t.encode(d);s.set(l,o),o+=l.length,s[o++]=0}s[o++]=this.tickRate,s[o++]=this.maxParticipants,s[o++]=this.maxTicks>>24&255,s[o++]=this.maxTicks>>16&255,s[o++]=this.maxTicks>>8&255,s[o++]=this.maxTicks&255;let a=Math.floor(this.startTime/4294967296),u=this.startTime>>>0;return s[o++]=a>>24&255,s[o++]=a>>16&255,s[o++]=a>>8&255,s[o++]=a&255,s[o++]=u>>24&255,s[o++]=u>>16&255,s[o++]=u>>8&255,s[o++]=u&255,rt(s).slice(0,Ir)}toConnectionURL(){if(this.validate(),!this.authority)throw new Error("Authority is required for connection URL");if(!as.test(this.authority))throw new Error(`Invalid authority format: "${this.authority}"`);let n="/"+["s",this.appID,...this.path].join("/"),r=new URLSearchParams;return this.credentials&&r.set("join",this.credentials),r.set("max",this.maxParticipants.toString()),r.set("rate",this.tickRate.toString()),this.startTime!==0&&r.set("start",this.startTime.toString()),r.set("ticks",this.maxTicks.toString()),`multitap://${this.authority}${n}?${r.toString()}`}toHTTPSURL(){return this.toConnectionURL().replace("multitap://","https://")}toBase64EncodedConnectionURL(){let t=this.toConnectionURL();return Sr(t)}static fromBase64EncodedConnectionURL(t){let n=Er(t);return e.fromConnectionURL(n)}static fromConnectionURL(t){let n=new URL(t);if(n.protocol!=="multitap:"&&n.protocol!=="https:")throw new Error(`Invalid URL scheme: must be multitap:// or https://, got ${n.protocol}`);let r=n.pathname.replace(/^\\/+|\\/+$/g,""),i=r===""?[]:r.split("/");if(i.length<2||i[0]!=="s")throw new Error("Invalid URL path: must start with /s/{appID}");let s=i[1],o=i.slice(2),a=n.searchParams,u=a.get("rate"),f=a.get("max");if(!u)throw new Error("Missing required query parameter: rate");if(!f)throw new Error("Missing required query parameter: max");let d=parseInt(u,10),l=parseInt(f,10),m=a.get("ticks");if(!m)throw new Error("Missing required query parameter: ticks");let x=parseInt(m,10),b=a.get("start"),A=b?parseInt(b,10):0,I=a.get("join")??"",E=new e({version:"v1",authority:n.host,appID:s,path:o,tickRate:d,maxParticipants:l,maxTicks:x,startTime:A,credentials:I});return E.validate(),E}};function Or(e){return 5+e+65}function Le(e){return 5+e+65+1}var dt={encodeInput(e,t,n){if(t.length>255)throw new Error(`Payload must be 255 bytes or less, got ${t.length}`);if(n.length!==65)throw new Error(`Signature must be 65 bytes, got ${n.length}`);let r=Or(t.length),i=new ArrayBuffer(3+r),s=new DataView(i),o=new Uint8Array(i);return s.setUint8(0,3),s.setUint16(1,r,!0),s.setUint32(3,e,!0),s.setUint8(7,t.length),o.set(t,8),o.set(n,8+t.length),o},encodePong(e,t){let n=new ArrayBuffer(11),r=new DataView(n);return r.setUint8(0,2),r.setUint16(1,8,!0),r.setUint32(3,e,!0),r.setUint32(7,t,!0),new Uint8Array(n)},encodeTick(e){let t=Math.min(e.inputs.length,16),n=0;for(let u=0;u<t;u++)n+=Le(e.inputs[u].payload.length);let r=70+n,i=new ArrayBuffer(3+r),s=new DataView(i),o=new Uint8Array(i);s.setUint8(0,4),s.setUint16(1,r,!0),s.setUint32(3,e.tick,!0),o.set(e.sig,7),s.setUint8(72,t);let a=73;for(let u=0;u<t;u++){let f=e.inputs[u],d=f.payload.length;s.setUint32(a,f.targetTick,!0),s.setUint8(a+4,d),o.set(f.payload,a+5),o.set(f.sig,a+5+d),s.setUint8(a+5+d+65,f.idx),a+=Le(d)}return o},decode(e){if(e.length<3)throw new Error("Message too short");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint8(0),r=t.getUint16(1,!0);if(e.length<3+r)throw new Error("Message truncated");switch(n){case 1:{let i={type:"ping",tickRate:t.getUint16(3,!0),isReplay:!1,replayStart:0,replayEnd:0};return r>=11&&(i.isReplay=t.getUint8(5)===1,i.isReplay&&(i.replayStart=t.getUint32(6,!0),i.replayEnd=t.getUint32(10,!0))),i}case 4:return this.decodeTick(e.subarray(3,3+r));case 3:return this.decodeInput(e);default:throw new Error(`Unknown message type: ${n}`)}},decodeTick(e){if(e.length<70)throw new Error("Tick payload too short");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=e.subarray(4,69),i=Math.min(t.getUint8(69),16),s=[],o=70;for(let a=0;a<i;a++){if(o+5>e.length)throw new Error(`Tick payload truncated at input ${a} header`);let u=t.getUint32(o,!0),f=t.getUint8(o+4),d=Le(f);if(o+d>e.length)throw new Error(`Tick payload truncated at input ${a} (need ${d} bytes)`);let l=t.getUint8(o+5+f+65);s.push({targetTick:u,payload:e.subarray(o+5,o+5+f),sig:e.subarray(o+5+f,o+5+f+65),idx:l}),o+=d}return{type:"tick",tick:n,sig:r,inputs:s}},decodeInput(e){if(e.length<73)throw new Error("Input message too short");let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint8(0)!==3)throw new Error(`Not an input message: type=${t.getUint8(0)}`);let n=t.getUint16(1,!0);if(n<70)throw new Error(`Input message too short: ${n} bytes, minimum 70`);if(e.length<3+n)throw new Error("Input message truncated");let r=t.getUint32(3,!0),i=t.getUint8(7),s=Or(i);if(n<s)throw new Error(`Input payload truncated: claimed ${i} bytes, only ${n-5-65} available`);return{type:"input",targetTick:r,payload:e.subarray(8,8+i),signature:e.subarray(8+i,8+i+65)}}};var j=!0;var Gt=()=>{},he={log:(...e)=>{j&&console.log(...e)},warn:(...e)=>{j&&console.warn(...e)},error:(...e)=>{j&&console.error(...e)},info:(...e)=>{j&&console.info(...e)},debug:(...e)=>{j&&console.debug(...e)},group:e=>{j&&console.group(e)},groupEnd:()=>{j&&console.groupEnd()},table:e=>{j&&console.table(e)},get raw(){return j?console:{log:Gt,warn:Gt,error:Gt,info:Gt,debug:Gt}}};function Y(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var pe=class{constructor(t){y(this,"debug");y(this,"genesisHash");y(this,"genesis");y(this,"syncNodesById",new Map);y(this,"syncHead");y(this,"predictedHead");y(this,"pendingSyncMessages",new Map);y(this,"nodeIdSequence",0);y(this,"optimisticInputs",[]);y(this,"participantBySlot",new Map);y(this,"inputPayloadPredictor",null);y(this,"verificationPubKey",null);y(this,"maxTicks");y(this,"logSyncTicks");y(this,"onParticipantJoined",null);this.genesisHash=t.genesisHash,this.genesis={id:this.generateNodeId(),parent:null,syncPrev:null,syncNext:null,tick:0,sig:new Uint8Array(65),payloads:[],sync:!0},this.syncHead=this.genesis,this.predictedHead=this.syncHead,this.syncNodesById.set(this.genesis.id,this.genesis),this.maxTicks=t.maxTicks,this.inputPayloadPredictor=t.inputPayloadPredictor??null,this.verificationPubKey=t.verificationPubKey||null,this.debug=t.debug??!1,this.logSyncTicks=t.logSyncTicks??!1,this.logSyncNodeForTests(this.genesis)}setOnParticipantJoined(t){this.onParticipantJoined=t}getSyncHead(){return this.syncHead}getPredictedHead(){return this.predictedHead}addSyncTick(t){if(t.tick<=this.syncHead.tick){this.debug&&he.warn("skipping sync tick that is older than the sync head (duplicate?)",t.tick,this.syncHead.tick);return}this.pendingSyncMessages.set(t.tick,t),this.optimisticInputs=this.optimisticInputs.filter(n=>{for(let r of t.inputs)if(le(r.sig,n.sig))return!1;return!0}),this.updateHeads()}recoverInputPubKey(t){let n=Lt(this.genesisHash,t.targetTick,t.payload);return Me(n,t.sig)}addOptimisticInput(t,n){if(t.targetTick>=this.maxTicks||!Kr(t.targetTick,this.syncHead.tick))return;let r=this.predictedHead.tick-this.syncHead.tick;if(r>=20){this.debug&&he.warn(`unable to add optimistic input as we are already ${r} ticks ahead of the sync chain`);return}let i=n??this.recoverInputPubKey(t),s=Array.from(this.participantBySlot.values()).find(o=>o.id===Y(i));if(!s){this.debug&&he.warn("skipping optimistic tick from unknown participant",t.targetTick,Y(i));return}this.optimisticInputs.push({...t,idx:s.slot}),this.updateHeads()}getParticipantSlots(t){let n=Array.from(this.participantBySlot.values()).filter(r=>r.joined<=t).sort((r,i)=>r.slot-i.slot);for(let r=0;r<n.length;r++){let i=n[r];if(i===void 0)throw new Error(`invariant: participant slot ${r} is undefined`);if(i.slot!==r)throw new Error(`invariant: participant slot ${r} is not sequential`)}return n}getTicksAfter(t,n){let r=this.getSyncChainForkPointFromNodeId(t),i=n?.limit,s=[],o=this.predictedHead,a=n?.lag??0;for(;o&&(o.sync&&(a=0),a>0?a--:n?.sync&&!o.sync||s.push({id:o.id,tick:o.tick,payloads:o.payloads,sync:o.sync}),o!==r);)o=o.parent;return i&&s.length>=i?s.reverse().slice(0,i):s.reverse()}getPredictionCount(){let t=0,n=this.predictedHead;for(;n&&!n.sync;)n.pending||t++,n=n.parent;return t}getSyncTicksAfter(t){let n=t?this.syncNodesById.get(t):this.genesis;if(!n)throw new Error(`invalid nodeId ${t} not found in graph`);if(!n.sync)throw new Error(`node ${t} is not on the sync chain`);let r=[],i=this.syncHead;for(;i;){if(i===n){t===null&&r.push(i);break}r.push(i),i=i.parent}return r.reverse()}getSyncChainForkPointFromNodeId(t){if(!t)return this.genesis;if(t.includes("/")){let n=t.split("/")[0];return this.syncNodesById.get(n)??this.genesis}return this.syncNodesById.get(t)??this.genesis}getPendingSyncMessages(){return Array.from(this.pendingSyncMessages.entries()).sort((t,n)=>t[0]-n[0])}verifyTickSignature(t,n,r,i){if(!this.verificationPubKey)return!1;let s=Br(n.map(a=>({targetTick:a.targetTick,payload:a.payload,sig:a.sig,idx:a.idx}))),o=Hr(this.genesisHash,t,s,i);if(!Pr(this.verificationPubKey,o,r))throw new Error(`Invalid relay signature for tick ${t}. `);return!0}getOrderedPayloadsAtTick(t,n){return this.getParticipantSlots(t).map(r=>r?n.find(s=>s.idx===r.slot)?.payload??new Uint8Array(0):new Uint8Array(0))}updateHeads(){let t=this.syncHead.tick;for(let[n,r]of this.getPendingSyncMessages()){if(n<=this.syncHead.tick){this.pendingSyncMessages.delete(n);continue}if(n>t&&(t=n),n===this.syncHead.tick+1){let i=this.verifyTickSignature(r.tick,r.inputs,r.sig,this.syncHead.sig);for(let o of r.inputs)this.ensureParticipantJoined(r.tick,o);let s={id:this.generateNodeId(),parent:this.syncHead,syncPrev:this.syncHead,syncNext:null,tick:r.tick,sig:r.sig,payloads:this.getOrderedPayloadsAtTick(r.tick,r.inputs),sync:!0,verified:i};this.syncHead.syncNext=s,this.syncHead=s,this.pendingSyncMessages.delete(n),this.syncNodesById.set(s.id,s),this.logSyncNodeForTests(s);continue}else break}if(this.optimisticInputs=this.optimisticInputs.filter(n=>n.targetTick>this.syncHead.tick),t=Math.max(t,this.optimisticInputs.reduce((n,r)=>r.targetTick>n?r.targetTick:n,this.syncHead.tick)),this.predictedHead=this.syncHead,t>this.syncHead.tick){let n=this.optimisticInputs.slice().sort((i,s)=>i.targetTick-s.targetTick),r=this.syncHead;for(let i=this.syncHead.tick+1;i<=t;i++){let s=!1,o=this.pendingSyncMessages.get(i);o?s=!0:o=this.dequeuePrediction(i,n,this.predictedHead);let a={id:this.generateNodeId(r),parent:this.predictedHead,syncPrev:r,syncNext:null,tick:i,sig:o.sig,payloads:this.getOrderedPayloadsAtTick(i,o.inputs),sync:!1,pending:s};this.predictedHead=a}}}ensureParticipantJoined(t,n){if(n.idx<0)throw new Error(`invariant: participant slot ${n.idx} is invalid`);if(!this.participantBySlot.get(n.idx)){let i=this.recoverInputPubKey(n),s={id:Y(i),pubKey:i,slot:n.idx,joined:t};this.participantBySlot.set(n.idx,s),this.onParticipantJoined&&this.onParticipantJoined(s)}}logSyncNodeForTests(t){this.logSyncTicks&&console.log(`SYNC ${JSON.stringify({tick:t.tick,sig:Y(t.sig),payloads:t.payloads.map(n=>Y(n)),participants:this.getParticipantSlots(t.tick).map(n=>n?.id??""),sync:!0})}`)}dequeuePrediction(t,n,r){let i=this.getParticipantSlots(t).map(a=>{if(!a||a.slot<0)throw new Error(`invariant: participant slot "${a?.slot}" invalid`);return{targetTick:t,payload:this.inputPayloadPredictor?this.inputPayloadPredictor(t,a.slot,r):new Uint8Array(0),sig:new Uint8Array(0),idx:a.slot}}),s=0,o=[];for(let a of n.slice()){if(s>=i.length)break;if(a.targetTick>t||!Kr(a.targetTick,t))continue;let u=i[a.idx];if(!u)throw new Error(`invariant: participant slot ${a.idx} not found in inputs`);if(!(u.payload.length>0)){u.payload=a.payload,o.push(a),s++;break}}for(let a of o)n.splice(n.indexOf(a),1);return{type:"tick",tick:t,inputs:i,sig:new Uint8Array(65)}}generateNodeId(t){return this.nodeIdSequence++,t?`${t.id}/${this.nodeIdSequence}`:`${this.nodeIdSequence}`}};function Kr(e,t){let n=Math.max(0,t-10),r=t+10;return e>=n&&e<=r}var Ot=class{constructor(t=1e3,n=1024){y(this,"buffer");y(this,"windowMs");y(this,"head",0);y(this,"tail",0);y(this,"size",0);this.windowMs=t,this.buffer=new Float64Array(n)}inc(){let t=performance.now();this.buffer[this.head]=t,this.head=(this.head+1)%this.buffer.length,this.size<this.buffer.length?this.size++:this.tail=(this.tail+1)%this.buffer.length}count(t=performance.now()){let n=t-this.windowMs;for(;this.size>0&&!(this.buffer[this.tail]>=n);)this.tail=(this.tail+1)%this.buffer.length,this.size--;return this.size}rate(t=performance.now()){return this.count(t)*(1e3/this.windowMs)}};var ge=class{constructor(t){y(this,"connectionURL");y(this,"serverCertHash");y(this,"connectionTimeoutMs");y(this,"privateKey");y(this,"publicKey");y(this,"genesisHash");y(this,"sessionConfig");y(this,"transport");y(this,"streams");y(this,"replayStreams");y(this,"roundRobinIndex");y(this,"connectionGeneration");y(this,"connected");y(this,"stopped");y(this,"debug");y(this,"logSyncTicks");y(this,"outbox");y(this,"stateListeners");y(this,"flushingOutbox");y(this,"tickRate");y(this,"inputGraph");y(this,"tickDeadlineWants",0);y(this,"tickDeadlineTimer",null);y(this,"tickDeadlineGrace",33);y(this,"stats");this.debug=t.debug??!1,this.connectionURL=t.connectionURL,this.serverCertHash=t.serverCertHash,this.connectionTimeoutMs=t.connectionTimeoutMs??5e3,this.privateKey=t.privateKey??vr(),this.publicKey=_r(this.privateKey),this.logSyncTicks=t.logSyncTicks??!1,this.sessionConfig=Dt.fromConnectionURL(t.connectionURL),this.genesisHash=this.sessionConfig.toGenesisHash(),this.transport=null,this.streams=[],this.replayStreams=new Set,this.roundRobinIndex=0,this.connectionGeneration=0,this.connected=!1,this.stopped=!1,this.outbox=[],this.stateListeners=new Set,this.flushingOutbox=!1,this.tickRate=0,this.inputGraph=new pe({genesisHash:this.genesisHash,maxTicks:this.sessionConfig.maxTicks,inputPayloadPredictor:t.inputPayloadPredictor,verificationPubKey:t.relayPubKey,debug:this.debug,logSyncTicks:this.logSyncTicks}),this.stats={messagesRecv:new Ot,messagesSent:new Ot,reconnections:0},t.autoConnect!==!1&&this._connectLoop().catch(ye)}async connect(){if(this.stopped)throw new Error("Channel has been stopped");!this.transport&&!this.connected&&this._connectLoop().catch(ye)}async getPublicKey(){return this.publicKey}async getGenesisHash(){return this.genesisHash}onStateChange(t){return this.stateListeners.add(t),t(this.connected),()=>{this.stateListeners.delete(t)}}getStats(){return{activeStreams:this.streams.length,totalStreams:this.streams.length,messagesRecv:this.stats.messagesRecv.rate(),messagesSent:this.stats.messagesSent.rate(),reconnections:this.stats.reconnections}}async getTickRate(){return this.tickRate}async getParticipantSlots(t){return this.inputGraph.getParticipantSlots(t)}async getSyncHead(){return this.inputGraph.getSyncHead()}async getPredictedHead(){return this.inputGraph.getPredictedHead()}async addSyncTick(t){this.inputGraph.addSyncTick(t)}async addOptimisticInput(t,n){this.inputGraph.addOptimisticInput(t,n)}async getPredictionCount(){return this.inputGraph.getPredictionCount()}async getTicksAfter(t,n){return this.inputGraph.getTicksAfter(t,n)}async setOnParticipantJoined(t){this.inputGraph.setOnParticipantJoined(t)}async expose(t){ht(this,t)}async close(){if(this.stopped=!0,this.tickDeadlineTimer&&(clearTimeout(this.tickDeadlineTimer),this.tickDeadlineTimer=null),this.transport)try{this.transport.close({closeCode:0,reason:"stopped"})}catch{}}_setConnected(t){if(this.connected!==t){this.connected=t;for(let n of this.stateListeners)try{n(t)}catch{}}}async _send(t){if(!(t instanceof Uint8Array))throw new Error("send() requires Uint8Array");if(this.connected&&this.streams.length>0)for(let n=0;n<this.streams.length;n++){let r=this._nextStream();if(!r)break;try{await r.writer.write(t),this.stats.messagesSent.inc();return}catch{if(this._dropStream(r),!this.connected)break}}this.outbox.push(t)}_generateNullInput(){let t=new Uint8Array(0),n=Lt(this.genesisHash,4294967295,t),r=Ce(this.privateKey,n);return dt.encodeInput(4294967295,t,r)}async sendSignedInput(t,n){if(t.length>255)throw new Error(`Payload must be ${255} bytes or less, got ${t.length}`);let r=n;r===void 0&&(r=this.inputGraph.getPredictedHead().tick+1);let i=Lt(this.genesisHash,r,t),s=Ce(this.privateKey,i),o=Y(this.publicKey),a=this.inputGraph.getParticipantSlots(r).find(f=>f.id===o);a&&this.inputGraph.addOptimisticInput({targetTick:r,payload:t,sig:s,idx:a.slot},this.publicKey);let u=dt.encodeInput(r,t,s);return await this._send(u),u}_nextStream(){return this.streams.length===0?null:(this.roundRobinIndex>=this.streams.length&&(this.roundRobinIndex=0),this.streams[this.roundRobinIndex++]??null)}async _connectLoop(){let t=0;for(;!this.stopped;){try{let r=this._generateNullInput(),i=de(r),o=new Dt({...this.sessionConfig,credentials:i}).toBase64EncodedConnectionURL(),a="https://"+this.sessionConfig.authority,u=new URL(`${a}/connect?session=${o}`),f={};if(this.serverCertHash){let b=Ne(this.serverCertHash);f.serverCertificateHashes=[{algorithm:"sha-256",value:b.buffer}]}let d=new AbortController,l=setTimeout(()=>d.abort(),this.connectionTimeoutMs),m=await fetch(u.toString(),{method:"HEAD",signal:d.signal});if(clearTimeout(l),!m.ok){console.warn("server not reachable, retry in 1s"),await new Promise(b=>setTimeout(b,1e3));continue}let x=new WebTransport(u.toString(),f);await x.ready,this.transport=x,this.stats.reconnections++,this._setConnected(!0),this.connectionGeneration++,this.streams=[],this.replayStreams.clear(),this.roundRobinIndex=0,t=0,this._acceptStreamsLoop(x,this.connectionGeneration).catch(ye),await x.closed}catch(r){console.warn("connect loop error",r),t++}if(this._setConnected(!1),this._cleanupTransport(),this.stopped)break;let n=Math.min(t*250,1e3);await new Promise(r=>setTimeout(r,n))}console.log("connect loop exited")}async _acceptStreamsLoop(t,n){let r=t.incomingBidirectionalStreams.getReader(),i=0;try{for(;;){let{value:s,done:o}=await r.read();if(o)break;let a=s;if(a){if(this.connectionGeneration!==n||this.transport!==t||this.stopped){try{a.readable.cancel().catch(()=>{})}catch{}try{a.writable.getWriter().close().catch(()=>{})}catch{}break}this._addStream(a,i++,n)}}}catch{try{t.close()}catch{}}finally{try{r.releaseLock()}catch{}}}_addStream(t,n,r){let i=t.writable.getWriter(),s=t.readable.getReader(),o={stream:t,writer:i,reader:s,index:n,isReplay:!1,generation:r};this.streams.push(o),this._readLoop(o).catch(()=>{this._dropStream(o)}),this.outbox.length>0&&this._flushOutbox().catch(ye)}_dropStream(t){if(t.generation!==this.connectionGeneration){this._cleanupHandle(t);return}if(t.isReplay){this.replayStreams.delete(t),this._cleanupHandle(t);return}let n=this.streams.indexOf(t);n>=0&&(this.streams.splice(n,1),this.roundRobinIndex>n&&this.roundRobinIndex--),this._cleanupHandle(t)}_cleanupHandle(t){t.pongInterval&&(clearInterval(t.pongInterval),t.pongInterval=null);try{t.reader.cancel().catch(()=>{})}catch{}try{t.writer.releaseLock()}catch{}}async _flushOutbox(){if(!this.flushingOutbox){this.flushingOutbox=!0;try{for(;this.outbox.length>0&&this.streams.length>0&&this.connected&&!this.stopped;){let t=this.outbox.shift();if(!t)break;let n=this._nextStream();if(!n){this.outbox.unshift(t);break}try{await n.writer.write(t),this.stats.messagesSent.inc()}catch{this._dropStream(n),this.outbox.unshift(t);break}}}finally{this.flushingOutbox=!1}}}_cleanupTransport(){let t=[...this.streams,...this.replayStreams];this.streams=[],this.replayStreams.clear(),this.roundRobinIndex=0;for(let r of t)this._cleanupHandle(r);let n=this.transport;if(this.transport=null,n)try{n.close({closeCode:0,reason:"cleanup"})}catch{}}async _readLoop(t){let r=new Uint8Array(0);for(;;){let i=await t.reader.read(),{value:s,done:o}=i;if(o)break;if(!s)continue;r=this._concatBuffers(r,s);let a=0;for(;r.length>=3;){let u=new DataView(r.buffer,r.byteOffset,r.byteLength),f=u.getUint8(0),l=3+u.getUint16(1,!0);if(r.length<l)break;let m=r.slice(0,l);if(r=r.slice(l),a++,this.stats.messagesRecv.inc(),f===1){let x=dt.decode(m);if(this.tickRate=x.tickRate,x.isReplay){t.isReplay=!0;let E=this.streams.indexOf(t);E>=0&&t.generation===this.connectionGeneration&&(this.streams.splice(E,1),this.roundRobinIndex>E&&this.roundRobinIndex--,this.replayStreams.add(t)),t.pongInterval=setInterval(()=>{let k=this.inputGraph.getSyncHead(),_=this.inputGraph.getPredictedHead(),Vr=dt.encodePong(k.tick,_.tick);t.writer.write(Vr).catch(()=>{t.pongInterval&&clearInterval(t.pongInterval)})},1e3)}let b=this.inputGraph.getSyncHead(),A=this.inputGraph.getPredictedHead(),I=dt.encodePong(b.tick,A.tick);t.writer.write(I).catch(()=>{this._dropStream(t)})}else if(f===4){let x=dt.decode(m);try{this.inputGraph.addSyncTick(x),this._maybeResetDeadline()}catch(b){this.debug&&console.warn("Failed to process tick message:",b instanceof Error?b.message:b,x)}}else this.debug&&console.warn("dropped unknown message type:",f);if(a>=256&&(await new Promise(x=>setTimeout(x,0)),a=0,t.generation!==this.connectionGeneration))return}}}_maybeResetDeadline(){let t=this.inputGraph.getSyncHead();t.tick>=this.tickDeadlineWants&&this._resetDeadline(t.tick+1)}_resetDeadline(t){this.tickDeadlineWants=t,this.tickDeadlineTimer&&clearTimeout(this.tickDeadlineTimer),this.tickRate&&(this.tickDeadlineTimer=setTimeout(this._onTickDeadlineExceeded.bind(this),1e3/this.tickRate+this.tickDeadlineGrace))}_onTickDeadlineExceeded(){let t=this.inputGraph.getParticipantSlots(this.tickDeadlineWants).find(n=>n.id===Y(this.publicKey));if(t)try{this.inputGraph.addOptimisticInput({targetTick:this.tickDeadlineWants,payload:new Uint8Array(0),sig:new Uint8Array(0),idx:t.slot},this.publicKey)}catch(n){this.debug&&console.error("failed to add empty optimistic input:",n instanceof Error?n.message:n)}else this.debug&&console.warn("unable to add empty optimistic input as we do not have a slot assigned yet");this._resetDeadline(this.tickDeadlineWants+1)}_concatBuffers(t,n){let r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r}};function ye(e){console.warn("channel unexpected:",e)}ht(ge);var ma=null;globalThis.onerror=e=>(console.error("\\u{1F534} FATAL CHANNEL WORKER ERROR (Uncaught Exception):",e),!0);export{ma as default};\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n\n@noble/hashes/esm/utils.js:\n (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)\n\n@noble/secp256k1/index.js:\n (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)\n*/\n';
7145
+ // src/rollback.worker.ts
7146
+ var workerCode = 'var Or=Object.defineProperty;var Fr=(t,e,n)=>e in t?Or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>Fr(t,typeof e!="symbol"?e+"":e,n);var Dt=Symbol("Comlink.proxy"),Nr=Symbol("Comlink.endpoint"),Rr=Symbol("Comlink.releaseProxy"),ut=Symbol("Comlink.finalizer"),ve=Symbol("Comlink.thrown"),Lt=t=>typeof t=="object"&&t!==null||typeof t=="function",Dr={canHandle:t=>Lt(t)&&t[Dt],serialize(t){let{port1:e,port2:n}=new MessageChannel;return Be(t,e),[n,[n]]},deserialize(t){return t.start(),lt(t)}},Lr={canHandle:t=>Lt(t)&&ve in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},Ht=new Map([["proxy",Dr],["throw",Lr]]);function Hr(t,e){for(let n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function Be(t,e=globalThis,n=["*"]){e.addEventListener("message",function r(i){if(!i||!i.data)return;if(!Hr(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:o,type:s,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(W),u;try{let f=a.slice(0,-1).reduce((g,S)=>g[S],t),p=a.reduce((g,S)=>g[S],t);switch(s){case"GET":u=p;break;case"SET":f[a.slice(-1)[0]]=W(i.data.value),u=!0;break;case"APPLY":u=p.apply(f,c);break;case"CONSTRUCT":{let g=new p(...c);u=qr(g)}break;case"ENDPOINT":{let{port1:g,port2:S}=new MessageChannel;Be(t,S),u=Zr(g,[g])}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,[ve]:0}}Promise.resolve(u).catch(f=>({value:f,[ve]:0})).then(f=>{let[p,g]=Ie(f);e.postMessage(Object.assign(Object.assign({},p),{id:o}),g),s==="RELEASE"&&(e.removeEventListener("message",r),Mt(e),ut in t&&typeof t[ut]=="function"&&t[ut]())}).catch(f=>{let[p,g]=Ie({value:new TypeError("Unserializable return value"),[ve]:0});e.postMessage(Object.assign(Object.assign({},p),{id:o}),g)})}),e.start&&e.start()}function Mr(t){return t.constructor.name==="MessagePort"}function Mt(t){Mr(t)&&t.close()}function lt(t,e){let n=new Map;return t.addEventListener("message",function(i){let{data:o}=i;if(!o||!o.id)return;let s=n.get(o.id);if(s)try{s(o)}finally{n.delete(o.id)}}),ft(t,n,[],e)}function Ae(t){if(t)throw new Error("Proxy has been released and is not useable")}function zt(t){return te(t,new Map,{type:"RELEASE"}).then(()=>{Mt(t)})}var Ue=new WeakMap,Ce="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(Ue.get(t)||0)-1;Ue.set(t,e),e===0&&zt(t)});function zr(t,e){let n=(Ue.get(e)||0)+1;Ue.set(e,n),Ce&&Ce.register(t,e,t)}function Vr(t){Ce&&Ce.unregister(t)}function ft(t,e,n=[],r=function(){}){let i=!1,o=new Proxy(r,{get(s,a){if(Ae(i),a===Rr)return()=>{Vr(o),zt(t),e.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>o};let c=te(t,e,{type:"GET",path:n.map(u=>u.toString())}).then(W);return c.then.bind(c)}return ft(t,e,[...n,a])},set(s,a,c){Ae(i);let[u,f]=Ie(c);return te(t,e,{type:"SET",path:[...n,a].map(p=>p.toString()),value:u},f).then(W)},apply(s,a,c){Ae(i);let u=n[n.length-1];if(u===Nr)return te(t,e,{type:"ENDPOINT"}).then(W);if(u==="bind")return ft(t,e,n.slice(0,-1));let[f,p]=Rt(c);return te(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:f},p).then(W)},construct(s,a){Ae(i);let[c,u]=Rt(a);return te(t,e,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:c},u).then(W)}});return zr(o,t),o}function Gr(t){return Array.prototype.concat.apply([],t)}function Rt(t){let e=t.map(Ie);return[e.map(n=>n[0]),Gr(e.map(n=>n[1]))]}var Vt=new WeakMap;function Zr(t,e){return Vt.set(t,e),t}function qr(t){return Object.assign(t,{[Dt]:!0})}function Ie(t){for(let[e,n]of Ht)if(n.canHandle(t)){let[r,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:r},i]}return[{type:"RAW",value:t},Vt.get(t)||[]]}function W(t){switch(t.type){case"HANDLER":return Ht.get(t.name).deserialize(t.value);case"RAW":return t.value}}function te(t,e,n,r){return new Promise(i=>{let o=Kr();e.set(o,i),t.start&&t.start(),t.postMessage(Object.assign({id:o},n),r)})}function Kr(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Wr={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:Y,n:ht,Gx:jr,Gy:Yr,b:Yt}=Wr,ne=32,dt=64,U=(t="")=>{throw new Error(t)},Xt=t=>typeof t=="bigint",Jt=t=>typeof t=="string",Xr=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",me=(t,e)=>!Xr(t)||typeof e=="number"&&e>0&&t.length!==e?U("Uint8Array expected"):t,Ne=t=>new Uint8Array(t),Jr=t=>Uint8Array.from(t),Qt=(t,e)=>t.toString(16).padStart(e,"0"),yt=t=>Array.from(me(t)).map(e=>Qt(e,2)).join(""),z={_0:48,_9:57,A:65,F:70,a:97,f:102},Gt=t=>{if(t>=z._0&&t<=z._9)return t-z._0;if(t>=z.A&&t<=z.F)return t-(z.A-10);if(t>=z.a&&t<=z.f)return t-(z.a-10)},gt=t=>{let e="hex invalid";if(!Jt(t))return U(e);let n=t.length,r=n/2;if(n%2)return U(e);let i=Ne(r);for(let o=0,s=0;o<r;o++,s+=2){let a=Gt(t.charCodeAt(s)),c=Gt(t.charCodeAt(s+1));if(a===void 0||c===void 0)return U(e);i[o]=a*16+c}return i},bt=(t,e)=>me(Jt(t)?gt(t):Jr(me(t)),e),en=()=>globalThis?.crypto,Qr=()=>en()?.subtle??U("crypto.subtle must be defined"),Pe=(...t)=>{let e=Ne(t.reduce((r,i)=>r+me(i).length,0)),n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},ei=(t=ne)=>en().getRandomValues(Ne(t)),$e=BigInt,he=(t,e,n,r="bad number: out of range")=>Xt(t)&&e<=t&&t<n?t:U(r),h=(t,e=Y)=>{let n=t%e;return n>=0n?n:e+n};var tn=(t,e)=>{(t===0n||e<=0n)&&U("no inverse n="+t+" mod="+e);let n=h(t,e),r=e,i=0n,o=1n,s=1n,a=0n;for(;n!==0n;){let c=r/n,u=r%n,f=i-s*c,p=o-a*c;r=n,n=u,i=s,o=a,s=f,a=p}return r===1n?h(i,e):U("no inverse")};var Zt=t=>t instanceof X?t:U("Point expected"),nn=t=>h(h(t*t)*t+Yt),qt=t=>he(t,0n,Y),_e=t=>he(t,1n,Y),ti=t=>he(t,1n,ht),pt=t=>(t&1n)===0n,rn=t=>Uint8Array.of(t),ni=t=>rn(pt(t)?2:3),ri=t=>{let e=nn(_e(t)),n=1n;for(let r=e,i=(Y+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%Y),r=r*r%Y;return h(n*n)===e?n:U("sqrt invalid")},D=class D{constructor(e,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=qt(e),this.py=_e(n),this.pz=qt(r),Object.freeze(this)}static fromBytes(e){me(e);let n,r=e[0],i=e.subarray(1),o=Kt(i,0,ne),s=e.length;if(s===ne+1&&[2,3].includes(r)){let a=ri(o),c=pt(a);pt($e(r))!==c&&(a=h(-a)),n=new D(o,a,1n)}return s===dt+1&&r===4&&(n=new D(o,Kt(i,ne,dt),1n)),n?n.assertValidity():U("bad point: not on curve")}equals(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Zt(e),c=h(n*a),u=h(o*i),f=h(r*a),p=h(s*i);return c===u&&f===p}is0(){return this.equals(j)}negate(){return new D(this.px,h(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Zt(e),c=0n,u=Yt,f=0n,p=0n,g=0n,S=h(u*3n),k=h(n*o),A=h(r*s),O=h(i*a),ee=h(n+r),v=h(o+s);ee=h(ee*v),v=h(k+A),ee=h(ee-v),v=h(n+i);let R=h(o+a);return v=h(v*R),R=h(k+O),v=h(v-R),R=h(r+i),f=h(s+a),R=h(R*f),f=h(A+O),R=h(R-f),g=h(c*v),f=h(S*O),g=h(f+g),f=h(A-g),g=h(A+g),p=h(f*g),A=h(k+k),A=h(A+k),O=h(c*O),v=h(S*v),A=h(A+O),O=h(k-O),O=h(c*O),v=h(v+O),k=h(A*v),p=h(p+k),k=h(R*v),f=h(ee*f),f=h(f-k),k=h(ee*A),g=h(R*g),g=h(g+k),new D(f,p,g)}multiply(e,n=!0){if(!n&&e===0n)return j;if(ti(e),e===1n)return this;if(this.equals(re))return fi(e).p;let r=j,i=re;for(let o=this;e>0n;o=o.double(),e>>=1n)e&1n?r=r.add(o):n&&(i=i.add(o));return r}toAffine(){let{px:e,py:n,pz:r}=this;if(this.equals(j))return{x:0n,y:0n};if(r===1n)return{x:e,y:n};let i=tn(r,Y);return h(r*i)!==1n&&U("inverse invalid"),{x:h(e*i),y:h(n*i)}}assertValidity(){let{x:e,y:n}=this.toAffine();return _e(e),_e(n),h(n*n)===nn(e)?this:U("bad point: not on curve")}toBytes(e=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=Oe(n);return e?Pe(ni(r),i):Pe(rn(4),i,Oe(r))}static fromAffine(e){let{x:n,y:r}=e;return n===0n&&r===0n?j:new D(n,r,1n)}toHex(e){return yt(this.toBytes(e))}static fromPrivateKey(e){return re.multiply(oi(e))}static fromHex(e){return D.fromBytes(bt(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(e){return this.toBytes(e)}};y(D,"BASE"),y(D,"ZERO");var X=D,re=new X(jr,Yr,1n),j=new X(0n,1n,0n);X.BASE=re;X.ZERO=j;var Re=t=>$e("0x"+(yt(t)||"0")),Kt=(t,e,n)=>Re(t.subarray(e,n)),ii=2n**256n,Oe=t=>gt(Qt(he(t,0n,ii),dt)),oi=t=>{let e=Xt(t)?t:Re(bt(t,ne));return he(e,1n,ht,"private key invalid 3")};var si=t=>{t=bt(t),(t.length<ne+8||t.length>1024)&&U("expected 40-1024b");let e=h(Re(t),ht-1n);return Oe(e+1n)};var ai="SHA-256",xt={hexToBytes:gt,bytesToHex:yt,concatBytes:Pe,bytesToNumberBE:Re,numberToBytesBE:Oe,mod:h,invert:tn,hmacSha256Async:async(t,...e)=>{let n=Qr(),r="HMAC",i=await n.importKey("raw",t,{name:r,hash:{name:ai}},!1,["sign"]);return Ne(await n.sign(r,i,Pe(...e)))},hmacSha256Sync:void 0,hashToPrivateKey:si,randomBytes:ei};var Fe=8,ci=256,on=Math.ceil(ci/Fe)+1,mt=2**(Fe-1),ui=()=>{let t=[],e=re,n=e;for(let r=0;r<on;r++){n=e,t.push(n);for(let i=1;i<mt;i++)n=n.add(e),t.push(n);e=n.double()}return t},Wt,jt=(t,e)=>{let n=e.negate();return t?n:e},fi=t=>{let e=Wt||(Wt=ui()),n=j,r=re,i=2**Fe,o=i,s=$e(i-1),a=$e(Fe);for(let c=0;c<on;c++){let u=Number(t&s);t>>=a,u>mt&&(u-=o,t+=1n);let f=c*mt,p=f,g=f+Math.abs(u)-1,S=c%2!==0,k=u<0;u===0?r=r.add(jt(S,e[p])):n=n.add(jt(k,e[g]))}return{p:n,f:r}};function di(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function oe(t,...e){if(!di(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function an(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");sn(t.outputLen),sn(t.blockLen)}function se(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function cn(t,e){oe(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function J(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function De(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function F(t,e){return t<<32-e|t>>>e}function pi(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ye(t){return typeof t=="string"&&(t=pi(t)),oe(t),t}var ie=class{};function un(t){let e=r=>t().update(ye(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mi(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}function fn(t,e,n){return t&e^~t&n}function ln(t,e,n){return t&e^t&n^e&n}var Le=class extends ie{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=De(this.buffer)}update(e){se(this),e=ye(e),oe(e);let{view:n,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=De(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){se(this),cn(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;n[s++]=128,J(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let p=s;p<i;p++)n[p]=0;mi(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=De(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)a.setUint32(4*p,f[p],o)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},V=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=new Uint32Array(64),He=class extends Le{constructor(e=32){super(64,e,8,!1),this.A=V[0]|0,this.B=V[1]|0,this.C=V[2]|0,this.D=V[3]|0,this.E=V[4]|0,this.F=V[5]|0,this.G=V[6]|0,this.H=V[7]|0}get(){let{A:e,B:n,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[e,n,r,i,o,s,a,c]}set(e,n,r,i,o,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let p=0;p<16;p++,n+=4)Z[p]=e.getUint32(n,!1);for(let p=16;p<64;p++){let g=Z[p-15],S=Z[p-2],k=F(g,7)^F(g,18)^g>>>3,A=F(S,17)^F(S,19)^S>>>10;Z[p]=A+Z[p-7]+k+Z[p-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let p=0;p<64;p++){let g=F(a,6)^F(a,11)^F(a,25),S=f+g+fn(a,c,u)+hi[p]+Z[p]|0,A=(F(r,2)^F(r,13)^F(r,22))+ln(r,i,o)|0;f=u,u=c,c=a,a=s+S|0,s=o,o=i,i=r,r=S+A|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,o,s,a,c,u,f)}roundClean(){J(Z)}destroy(){this.set(0,0,0,0,0,0,0,0),J(this.buffer)}};var ge=un(()=>new He);var wt=ge;var Me=class extends ie{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,an(e);let r=ye(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),J(o)}update(e){return se(this),this.iHash.update(e),this}digestInto(e){se(this),oe(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},St=(t,e,n)=>new Me(t,e).update(n).digest();St.create=(t,e)=>new Me(t,e);var yi=["string","number","bigint","symbol"],gi=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function dn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(yi.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(bi(t))return"Buffer";let n=xi(t);return n||"Object"}function bi(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function xi(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(gi.includes(e))return e}var l=class{constructor(e,n,r){this.major=e,this.majorEncoded=e<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};l.uint=new l(0,"uint",!0);l.negint=new l(1,"negint",!0);l.bytes=new l(2,"bytes",!0);l.string=new l(3,"string",!0);l.array=new l(4,"array",!1);l.map=new l(5,"map",!1);l.tag=new l(6,"tag",!1);l.float=new l(7,"float",!0);l.false=new l(7,"false",!0);l.true=new l(7,"true",!0);l.null=new l(7,"null",!0);l.undefined=new l(7,"undefined",!0);l.break=new l(7,"break",!0);var m=class{constructor(e,n,r){this.type=e,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ae=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",wi=new TextDecoder,Si=new TextEncoder;function ze(t){return ae&&globalThis.Buffer.isBuffer(t)}function Et(t){return t instanceof Uint8Array?ze(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var yn=ae?(t,e,n)=>n-e>64?globalThis.Buffer.from(t.subarray(e,n)).toString("utf8"):mn(t,e,n):(t,e,n)=>n-e>64?wi.decode(t.subarray(e,n)):mn(t,e,n),gn=ae?t=>t.length>64?globalThis.Buffer.from(t):pn(t):t=>t.length>64?Si.encode(t):pn(t),L=t=>Uint8Array.from(t),ce=ae?(t,e,n)=>ze(t)?new Uint8Array(t.subarray(e,n)):t.slice(e,n):(t,e,n)=>t.slice(e,n),bn=ae?(t,e)=>(t=t.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Et(globalThis.Buffer.concat(t,e))):(t,e)=>{let n=new Uint8Array(e),r=0;for(let i of t)r+i.length>n.length&&(i=i.subarray(0,n.length-r)),n.set(i,r),r+=i.length;return n},xn=ae?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ve(t,e){if(ze(t)&&ze(e))return t.compare(e);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return 0}function pn(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e}function mn(t,e,n){let r=[];for(;e<n;){let i=t[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=n){let a,c,u,f;switch(s){case 1:i<128&&(o=i);break;case 2:a=t[e+1],(a&192)===128&&(f=(i&31)<<6|a&63,f>127&&(o=f));break;case 3:a=t[e+1],c=t[e+2],(a&192)===128&&(c&192)===128&&(f=(i&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:a=t[e+1],c=t[e+2],u=t[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(f=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),e+=s}return Ei(r)}var hn=4096;function Ei(t){let e=t.length;if(e<=hn)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=hn));return n}var ki=256,be=class{constructor(e=ki){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let n=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=n.length-(this.maxCursor-this.cursor)-1;n.set(e,i)}else{if(n){let i=n.length-(this.maxCursor-this.cursor)-1;i<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(n=xn(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];e&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=ce(r,0,this.cursor)}else n=bn(this.chunks,this.cursor);return e&&this.reset(),n}};var b="CBOR decode error:",kt="CBOR encode error:",xe=[];xe[23]=1;xe[24]=2;xe[25]=3;xe[26]=5;xe[27]=9;function G(t,e,n){if(t.length-e<n)throw new Error(`${b} not enough data for type`)}var E=[24,256,65536,4294967296,BigInt("18446744073709551616")];function C(t,e,n){G(t,e,1);let r=t[e];if(n.strict===!0&&r<E[0])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function I(t,e,n){G(t,e,2);let r=t[e]<<8|t[e+1];if(n.strict===!0&&r<E[1])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function B(t,e,n){G(t,e,4);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(n.strict===!0&&r<E[2])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function _(t,e,n){G(t,e,8);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],i=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],o=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&o<E[3])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(n.allowBigInt===!0)return o;throw new Error(`${b} integers outside of the safe integer range are not supported`)}function wn(t,e,n,r){return new m(l.uint,C(t,e+1,r),2)}function Sn(t,e,n,r){return new m(l.uint,I(t,e+1,r),3)}function En(t,e,n,r){return new m(l.uint,B(t,e+1,r),5)}function kn(t,e,n,r){return new m(l.uint,_(t,e+1,r),9)}function P(t,e){return T(t,0,e.value)}function T(t,e,n){if(n<E[0]){let r=Number(n);t.push([e|r])}else if(n<E[1]){let r=Number(n);t.push([e|24,r])}else if(n<E[2]){let r=Number(n);t.push([e|25,r>>>8,r&255])}else if(n<E[3]){let r=Number(n);t.push([e|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<E[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(r&BigInt(4294967295)),s=Number(r>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,t.push(i)}else throw new Error(`${b} encountered BigInt larger than allowable range`)}}P.encodedSize=function(e){return T.encodedSize(e.value)};T.encodedSize=function(e){return e<E[0]?1:e<E[1]?2:e<E[2]?3:e<E[3]?5:9};P.compareTokens=function(e,n){return e.value<n.value?-1:e.value>n.value?1:0};function Tn(t,e,n,r){return new m(l.negint,-1-C(t,e+1,r),2)}function An(t,e,n,r){return new m(l.negint,-1-I(t,e+1,r),3)}function vn(t,e,n,r){return new m(l.negint,-1-B(t,e+1,r),5)}var Tt=BigInt(-1),Un=BigInt(1);function Cn(t,e,n,r){let i=_(t,e+1,r);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new m(l.negint,o,9)}if(r.allowBigInt!==!0)throw new Error(`${b} integers outside of the safe integer range are not supported`);return new m(l.negint,Tt-BigInt(i),9)}function Ge(t,e){let n=e.value,r=typeof n=="bigint"?n*Tt-Un:n*-1-1;T(t,e.type.majorEncoded,r)}Ge.encodedSize=function(e){let n=e.value,r=typeof n=="bigint"?n*Tt-Un:n*-1-1;return r<E[0]?1:r<E[1]?2:r<E[2]?3:r<E[3]?5:9};Ge.compareTokens=function(e,n){return e.value<n.value?1:e.value>n.value?-1:0};function we(t,e,n,r){G(t,e,n+r);let i=ce(t,e+n,e+n+r);return new m(l.bytes,i,n+r)}function In(t,e,n,r){return we(t,e,1,n)}function Bn(t,e,n,r){return we(t,e,2,C(t,e+1,r))}function _n(t,e,n,r){return we(t,e,3,I(t,e+1,r))}function Pn(t,e,n,r){return we(t,e,5,B(t,e+1,r))}function $n(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer bytes lengths not supported`);return we(t,e,9,i)}function Ze(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===l.string?gn(t.value):t.value),t.encodedBytes}function ue(t,e){let n=Ze(e);T(t,e.type.majorEncoded,n.length),t.push(n)}ue.encodedSize=function(e){let n=Ze(e);return T.encodedSize(n.length)+n.length};ue.compareTokens=function(e,n){return Ai(Ze(e),Ze(n))};function Ai(t,e){return t.length<e.length?-1:t.length>e.length?1:Ve(t,e)}function Se(t,e,n,r,i){let o=n+r;G(t,e,o);let s=new m(l.string,yn(t,e+n,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=ce(t,e+n,e+o)),s}function On(t,e,n,r){return Se(t,e,1,n,r)}function Fn(t,e,n,r){return Se(t,e,2,C(t,e+1,r),r)}function Nn(t,e,n,r){return Se(t,e,3,I(t,e+1,r),r)}function Rn(t,e,n,r){return Se(t,e,5,B(t,e+1,r),r)}function Dn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer string lengths not supported`);return Se(t,e,9,i,r)}var Ln=ue;function fe(t,e,n,r){return new m(l.array,r,n)}function Hn(t,e,n,r){return fe(t,e,1,n)}function Mn(t,e,n,r){return fe(t,e,2,C(t,e+1,r))}function zn(t,e,n,r){return fe(t,e,3,I(t,e+1,r))}function Vn(t,e,n,r){return fe(t,e,5,B(t,e+1,r))}function Gn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer array lengths not supported`);return fe(t,e,9,i)}function Zn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return fe(t,e,1,1/0)}function qe(t,e){T(t,l.array.majorEncoded,e.value)}qe.compareTokens=P.compareTokens;qe.encodedSize=function(e){return T.encodedSize(e.value)};function le(t,e,n,r){return new m(l.map,r,n)}function qn(t,e,n,r){return le(t,e,1,n)}function Kn(t,e,n,r){return le(t,e,2,C(t,e+1,r))}function Wn(t,e,n,r){return le(t,e,3,I(t,e+1,r))}function jn(t,e,n,r){return le(t,e,5,B(t,e+1,r))}function Yn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer map lengths not supported`);return le(t,e,9,i)}function Xn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return le(t,e,1,1/0)}function Ke(t,e){T(t,l.map.majorEncoded,e.value)}Ke.compareTokens=P.compareTokens;Ke.encodedSize=function(e){return T.encodedSize(e.value)};function Jn(t,e,n,r){return new m(l.tag,n,1)}function Qn(t,e,n,r){return new m(l.tag,C(t,e+1,r),2)}function er(t,e,n,r){return new m(l.tag,I(t,e+1,r),3)}function tr(t,e,n,r){return new m(l.tag,B(t,e+1,r),5)}function nr(t,e,n,r){return new m(l.tag,_(t,e+1,r),9)}function We(t,e){T(t,l.tag.majorEncoded,e.value)}We.compareTokens=P.compareTokens;We.encodedSize=function(e){return T.encodedSize(e.value)};var _i=20,Pi=21,$i=22,Oi=23;function rr(t,e,n,r){if(r.allowUndefined===!1)throw new Error(`${b} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new m(l.null,null,1):new m(l.undefined,void 0,1)}function ir(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return new m(l.break,void 0,1)}function At(t,e,n){if(n){if(n.allowNaN===!1&&Number.isNaN(t))throw new Error(`${b} NaN values are not supported`);if(n.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${b} Infinity values are not supported`)}return new m(l.float,t,e)}function or(t,e,n,r){return At(vt(t,e+1),3,r)}function sr(t,e,n,r){return At(Ut(t,e+1),5,r)}function ar(t,e,n,r){return At(lr(t,e+1),9,r)}function je(t,e,n){let r=e.value;if(r===!1)t.push([l.float.majorEncoded|_i]);else if(r===!0)t.push([l.float.majorEncoded|Pi]);else if(r===null)t.push([l.float.majorEncoded|$i]);else if(r===void 0)t.push([l.float.majorEncoded|Oi]);else{let i,o=!1;(!n||n.float64!==!0)&&(ur(r),i=vt(N,1),r===i||Number.isNaN(r)?(N[0]=249,t.push(N.slice(0,3)),o=!0):(fr(r),i=Ut(N,1),r===i&&(N[0]=250,t.push(N.slice(0,5)),o=!0))),o||(Fi(r),i=lr(N,1),N[0]=251,t.push(N.slice(0,9)))}}je.encodedSize=function(e,n){let r=e.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){ur(r);let i=vt(N,1);if(r===i||Number.isNaN(r))return 3;if(fr(r),i=Ut(N,1),r===i)return 5}return 9};var cr=new ArrayBuffer(9),$=new DataView(cr,1),N=new Uint8Array(cr,0);function ur(t){if(t===1/0)$.setUint16(0,31744,!1);else if(t===-1/0)$.setUint16(0,64512,!1);else if(Number.isNaN(t))$.setUint16(0,32256,!1);else{$.setFloat32(0,t);let e=$.getUint32(0),n=(e&2139095040)>>23,r=e&8388607;if(n===255)$.setUint16(0,31744,!1);else if(n===0)$.setUint16(0,(t&2147483648)>>16|r>>13,!1);else{let i=n-127;i<-24?$.setUint16(0,0):i<-14?$.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):$.setUint16(0,(e&2147483648)>>16|i+15<<10|r>>13,!1)}}}function vt(t,e){if(t.length-e<2)throw new Error(`${b} not enough data for float16`);let n=(t[e]<<8)+t[e+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,o;return r===0?o=i*2**-24:r!==31?o=(i+1024)*2**(r-25):o=i===0?1/0:NaN,n&32768?-o:o}function fr(t){$.setFloat32(0,t,!1)}function Ut(t,e){if(t.length-e<4)throw new Error(`${b} not enough data for float32`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,4).getFloat32(0,!1)}function Fi(t){$.setFloat64(0,t,!1)}function lr(t,e){if(t.length-e<8)throw new Error(`${b} not enough data for float64`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,8).getFloat64(0,!1)}je.compareTokens=P.compareTokens;function x(t,e,n){throw new Error(`${b} encountered invalid minor (${n}) for major ${t[e]>>>5}`)}function Ye(t){return()=>{throw new Error(`${b} ${t}`)}}var d=[];for(let t=0;t<=23;t++)d[t]=x;d[24]=wn;d[25]=Sn;d[26]=En;d[27]=kn;d[28]=x;d[29]=x;d[30]=x;d[31]=x;for(let t=32;t<=55;t++)d[t]=x;d[56]=Tn;d[57]=An;d[58]=vn;d[59]=Cn;d[60]=x;d[61]=x;d[62]=x;d[63]=x;for(let t=64;t<=87;t++)d[t]=In;d[88]=Bn;d[89]=_n;d[90]=Pn;d[91]=$n;d[92]=x;d[93]=x;d[94]=x;d[95]=Ye("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)d[t]=On;d[120]=Fn;d[121]=Nn;d[122]=Rn;d[123]=Dn;d[124]=x;d[125]=x;d[126]=x;d[127]=Ye("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)d[t]=Hn;d[152]=Mn;d[153]=zn;d[154]=Vn;d[155]=Gn;d[156]=x;d[157]=x;d[158]=x;d[159]=Zn;for(let t=160;t<=183;t++)d[t]=qn;d[184]=Kn;d[185]=Wn;d[186]=jn;d[187]=Yn;d[188]=x;d[189]=x;d[190]=x;d[191]=Xn;for(let t=192;t<=215;t++)d[t]=Jn;d[216]=Qn;d[217]=er;d[218]=tr;d[219]=nr;d[220]=x;d[221]=x;d[222]=x;d[223]=x;for(let t=224;t<=243;t++)d[t]=Ye("simple values are not supported");d[244]=x;d[245]=x;d[246]=x;d[247]=rr;d[248]=Ye("simple values are not supported");d[249]=or;d[250]=sr;d[251]=ar;d[252]=x;d[253]=x;d[254]=x;d[255]=ir;var H=[];for(let t=0;t<24;t++)H[t]=new m(l.uint,t,1);for(let t=-1;t>=-24;t--)H[31-t]=new m(l.negint,t,1);H[64]=new m(l.bytes,new Uint8Array(0),1);H[96]=new m(l.string,"",1);H[128]=new m(l.array,0,1);H[160]=new m(l.map,0,1);H[244]=new m(l.false,!1,1);H[245]=new m(l.true,!0,1);H[246]=new m(l.null,null,1);function dr(t){switch(t.type){case l.false:return L([244]);case l.true:return L([245]);case l.null:return L([246]);case l.bytes:return t.value.length?void 0:L([64]);case l.string:return t.value===""?L([96]):void 0;case l.array:return t.value===0?L([128]):void 0;case l.map:return t.value===0?L([160]):void 0;case l.uint:return t.value<24?L([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return L([31-Number(t.value)])}}var mr=Object.freeze({float64:!0,mapSorter:Hi,quickEncodeToken:dr});function Ri(){let t=[];return t[l.uint.major]=P,t[l.negint.major]=Ge,t[l.bytes.major]=ue,t[l.string.major]=Ln,t[l.array.major]=qe,t[l.map.major]=Ke,t[l.tag.major]=We,t[l.float.major]=je,t}var Di=Ri(),Ct=new be,Je=class t{constructor(e,n){this.obj=e,this.parent=n}includes(e){let n=this;do if(n.obj===e)return!0;while(n=n.parent);return!1}static createCheck(e,n){if(e&&e.includes(n))throw new Error(`${kt} object contains circular references`);return new t(n,e)}},q={null:new m(l.null,null),undefined:new m(l.undefined,void 0),true:new m(l.true,!0),false:new m(l.false,!1),emptyArray:new m(l.array,0),emptyMap:new m(l.map,0)},K={number(t,e,n,r){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new m(l.float,t):t>=0?new m(l.uint,t):new m(l.negint,t)},bigint(t,e,n,r){return t>=BigInt(0)?new m(l.uint,t):new m(l.negint,t)},Uint8Array(t,e,n,r){return new m(l.bytes,t)},string(t,e,n,r){return new m(l.string,t)},boolean(t,e,n,r){return t?q.true:q.false},null(t,e,n,r){return q.null},undefined(t,e,n,r){return q.undefined},ArrayBuffer(t,e,n,r){return new m(l.bytes,new Uint8Array(t))},DataView(t,e,n,r){return new m(l.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,n,r){if(!t.length)return n.addBreakTokens===!0?[q.emptyArray,new m(l.break)]:q.emptyArray;r=Je.createCheck(r,t);let i=[],o=0;for(let s of t)i[o++]=Xe(s,n,r);return n.addBreakTokens?[new m(l.array,t.length),i,new m(l.break)]:[new m(l.array,t.length),i]},Object(t,e,n,r){let i=e!=="Object",o=i?t.keys():Object.keys(t),s=i?t.size:o.length;if(!s)return n.addBreakTokens===!0?[q.emptyMap,new m(l.break)]:q.emptyMap;r=Je.createCheck(r,t);let a=[],c=0;for(let u of o)a[c++]=[Xe(u,n,r),Xe(i?t.get(u):t[u],n,r)];return Li(a,n),n.addBreakTokens?[new m(l.map,s),a,new m(l.break)]:[new m(l.map,s),a]}};K.Map=K.Object;K.Buffer=K.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))K[`${t}Array`]=K.DataView;function Xe(t,e={},n){let r=dn(t),i=e&&e.typeEncoders&&e.typeEncoders[r]||K[r];if(typeof i=="function"){let s=i(t,r,e,n);if(s!=null)return s}let o=K[r];if(!o)throw new Error(`${kt} unsupported type: ${r}`);return o(t,r,e,n)}function Li(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Hi(t,e){if(t[0]instanceof m&&e[0]instanceof m){let n=t[0],r=e[0];return n._keyBytes||(n._keyBytes=pr(n.value)),r._keyBytes||(r._keyBytes=pr(r.value)),Ve(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function pr(t){return Mi(t,Di,mr)}function hr(t,e,n,r){if(Array.isArray(e))for(let i of e)hr(t,i,n,r);else n[e.type.major](t,e,r)}function Mi(t,e,n){let r=Xe(t,n);if(!Array.isArray(r)&&n.quickEncodeToken){let i=n.quickEncodeToken(r);if(i)return i;let o=e[r.type.major];if(o.encodedSize){let s=o.encodedSize(r,n),a=new be(s);if(o(a,r,n),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${r} was wrong`);return Et(a.chunks[0])}}return Ct.reset(),hr(Ct,r,e,n),Ct.toBytes(!0)}xt.hmacSha256Sync=(t,...e)=>St(wt,t,xt.concatBytes(...e));var Gi=32;function Qe(t){if(t.length===0)return new Uint8Array(Gi);let e=t.length,n=e*4,r=t.reduce((c,u)=>c+u.length,0),i=4+n+r,o=new Uint8Array(i),s=new DataView(o.buffer,o.byteOffset,o.byteLength);s.setUint32(0,e,!0);let a=4;for(let c of t)s.setUint32(a,c.length,!0),a+=4;for(let c of t)o.set(c,a),a+=c.length;return wt(o)}var It={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,entityRef:4,f32:4,vec2:8,vec3:12,quat:16,enum:1},Ee={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,f32:4,flags8:1,flags16:2,flags32:4,vec2:8,vec3:12,quat:16};var yr=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","f32"]);function Pt(t){let e=t.match(/^(\\w+)\\[(\\d+)\\]$/);if(!e||!e[1]||!e[2])return null;let n=e[1],r=parseInt(e[2],10);if(!yr.has(n))throw new Error(`Invalid array element type \'${n}\': arrays only support primitive scalar types (bool, uint8, int8, uint16, int16, uint32, int32, f32)`);return{elementType:n,length:r}}function gr(t){let e=Pt(t);if(e){let r=Ee[e.elementType];if(r===void 0)throw new Error(`Unknown element type: ${e.elementType}`);return r*e.length}let n=Ee[t];if(n===void 0)throw new Error(`Unknown type: ${t}`);return n}function Zi(t){let e=[],n=[],r=new Map,i=new Map,o=0;for(let s of t.controls){let a=gr(s.type),c=Pt(s.type),u={name:s.name,type:s.type,size:a,offset:0,options:s.options};c&&(u.arrayLength=c.length,u.arrayElementType=c.elementType);let f={name:s.name,index:o++,field:u,hint:s.hint,retain:s.retain==="always"?"always":"tick"};e.push(f),r.set(s.name,f)}for(let s of t.commands){let a=[],c=0;for(let f of s.args){let p=gr(f.type),g=Pt(f.type),S={name:f.name,type:f.type,size:p,offset:c};g&&(S.arrayLength=g.length,S.arrayElementType=g.elementType),a.push(S),c+=p}let u={name:s.name,index:o++,args:a,totalSize:c};n.push(u),i.set(s.name,u)}return{controls:e,commands:n,controlByName:r,commandByName:i}}function Bt(t,e,n,r){switch(n){case"bool":t.setUint8(e,r?1:0);break;case"uint8":case"flags8":t.setUint8(e,r);break;case"int8":t.setInt8(e,r);break;case"uint16":case"flags16":t.setUint16(e,r,!0);break;case"int16":t.setInt16(e,r,!0);break;case"uint32":case"flags32":t.setUint32(e,r,!0);break;case"int32":t.setInt32(e,r,!0);break;case"f32":t.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function _t(t,e,n){switch(n){case"bool":return t.getUint8(e)!==0;case"uint8":case"flags8":return t.getUint8(e);case"int8":return t.getInt8(e);case"uint16":case"flags16":return t.getUint16(e,!0);case"int16":return t.getInt16(e,!0);case"uint32":case"flags32":return t.getUint32(e,!0);case"int32":return t.getInt32(e,!0);case"f32":return t.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}var et=class t{constructor(e){y(this,"schema");y(this,"fields",new Map);y(this,"commandList",[]);this.schema=e}setControl(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);let i=new Uint8Array(r.field.size),o=new DataView(i.buffer);this.encodeValue(o,0,r.field,n),this.fields.set(r.index,i)}setFlags(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(!r.field.options)throw new Error(`Control ${e} is not a flags type`);let i=0;for(let a=0;a<r.field.options.length;a++){let c=r.field.options[a];n[c]&&(i|=1<<a)}let o=new Uint8Array(r.field.size),s=new DataView(o.buffer);Bt(s,0,r.field.type,i),this.fields.set(r.index,o)}setVec2(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let i=new Uint8Array(8),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),this.fields.set(r.index,i)}setVec3(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let i=new Uint8Array(12),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),this.fields.set(r.index,i)}setQuat(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let i=new Uint8Array(16),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),o.setFloat32(12,n[3],!0),this.fields.set(r.index,i)}getControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);let r=this.fields.get(n.index);if(!r)return this.getDefaultValue(n.field);let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return this.decodeValue(i,0,n.field)}getFlags(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(!n.field.options)throw new Error(`Control ${e} is not a flags type`);let r=this.fields.get(n.index),i=0;if(r){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);i=_t(s,0,n.field.type)}let o={};for(let s=0;s<n.field.options.length;s++)o[n.field.options[s]]=(i&1<<s)!==0;return o}getVec2(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let r=this.fields.get(n.index);if(!r)return[0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0)]}getVec3(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let r=this.fields.get(n.index);if(!r)return[0,0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0)]}getQuat(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let r=this.fields.get(n.index);if(!r)return[0,0,0,1];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0),i.getFloat32(12,!0)]}hasControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);return this.fields.has(n.index)}addCommand(e,n){let r=this.schema.commandByName.get(e);if(!r)throw new Error(`Unknown command: ${e}`);let i=new Uint8Array(r.totalSize),o=new DataView(i.buffer);for(let s of r.args){let a=n[s.name];if(a===void 0)throw new Error(`Missing required argument: ${s.name}`);this.encodeValue(o,s.offset,s,a)}this.commandList.push({index:r.index,data:i})}getCommands(){let e=[];for(let{index:n,data:r}of this.commandList){let i=this.schema.commands.find(a=>a.index===n);if(!i)continue;let o=new DataView(r.buffer,r.byteOffset,r.byteLength),s={name:i.name};for(let a of i.args)s[a.name]=this.decodeValue(o,a.offset,a);e.push(s)}return e}encode(){let e=[];for(let[o,s]of this.fields){let a=new Uint8Array(2+s.length);a[0]=o,a[1]=s.length,a.set(s,2),e.push(a)}for(let o of this.commandList){let s=new Uint8Array(2+o.data.length);s[0]=o.index,s[1]=o.data.length,s.set(o.data,2),e.push(s)}let n=e.reduce((o,s)=>o+s.length,0),r=new Uint8Array(n),i=0;for(let o of e)r.set(o,i),i+=o.length;return r}static decode(e,n){let r=new t(e),i=0;for(;i<n.length;){if(i+2>n.length)throw new Error("Truncated TLV field header");let o=n[i],s=n[i+1];if(i+2+s>n.length)throw new Error(`Truncated TLV field data at index ${o}`);let a=n.subarray(i+2,i+2+s);e.controls.find(u=>u.index===o)?r.fields.set(o,new Uint8Array(a)):e.commands.find(f=>f.index===o)&&r.commandList.push({index:o,data:new Uint8Array(a)}),i+=2+s}return r}clear(){this.fields.clear(),this.commandList.length=0}encodeValue(e,n,r,i){if(r.type==="vec2"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0)}else if(r.type==="vec3"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0)}else if(r.type==="quat"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0),e.setFloat32(n+12,o[3],!0)}else if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let o=i,s=Ee[r.arrayElementType];for(let a=0;a<Math.min(o.length,r.arrayLength);a++)Bt(e,n+a*s,r.arrayElementType,o[a])}else Bt(e,n,r.type,i)}decodeValue(e,n,r){if(r.type==="vec2")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0)];if(r.type==="vec3")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0)];if(r.type==="quat")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0),e.getFloat32(n+12,!0)];if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let i=[],o=Ee[r.arrayElementType];for(let s=0;s<r.arrayLength;s++)i.push(_t(e,n+s*o,r.arrayElementType));return i}else return _t(e,n,r.type)}getDefaultValue(e){return e.type==="vec2"?[0,0]:e.type==="vec3"?[0,0,0]:e.type==="quat"?[0,0,0,1]:e.arrayLength!==void 0?new Array(e.arrayLength).fill(0):e.type==="bool"?!1:0}};function br(t){let e=Zi(t);return{create(){return new et(e)},decode(n){return et.decode(e,n)},get schema(){return e}}}function xr(t,e){return((e&65535)<<16|t&65535)>>>0}function ke(t){return t&65535}function Yi(t){return t>>>16&65535}function de(t){return t.subarray(8,40)}function $t(t,e){if(e.length!==32)throw new Error(`stateId must be ${32} bytes, got ${e.length}`);t.set(e,8)}function wr(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint32(40,e,!0)}function rt(t,e,n){let r=new Uint8Array(68);return r.set(t,0),new DataView(r.buffer).setUint32(32,e,!0),r.set(n,36),ge(r)}function Sr(t,e,n){return rt(t,e,Qe(n))}function Ot(t){return ge(t)}function Er(t,e,n){let r=new ArrayBuffer(t.totalSize),i=new Uint8Array(r),o=new DataView(r);if(o.setUint32(0,1297367376,!0),o.setUint16(4,0,!0),i[6]=n??0,i[7]=0,e){let a=Ot(e);i.set(a,8)}let s=t.freeStackOffset;o.setUint16(s,t.maxEntities,!0);for(let a=0;a<t.maxEntities;a++){let c=t.freeStackOffset+2+a*2;o.setUint16(c,a,!0)}return i}function kr(t,e){return t.entityTableOffset+e*t.entityRecordSize}function Ft(t,e,n){let r=kr(t,n);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(r,!0)}function Xi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(4,!0)}function Ji(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(4,e,!0)}function Qi(t,e){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t.freeStackOffset,!0)}function eo(t,e,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t.freeStackOffset,n,!0)}function to(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Qi(t,e);if(r===0)throw new Error(`No free entity slots available (max: ${t.maxEntities})`);let i=t.freeStackOffset+2+(r-1)*2,o=n.getUint16(i,!0);return eo(t,e,r-1),o}function Tr(t,e){let n=to(t,e),r=Ft(t,e,n);return Ji(e,Xi(e)+1),xr(n,r)}function it(t,e,n){if(n===4294967295)return!1;let r=ke(n);if(r>=t.maxEntities)return!1;let i=Yi(n);return Ft(t,e,r)===i}function Nt(t,e,n){if(n<0)throw new Error("Singleton components do not have component bitmask entries");let r=kr(t,e)+2,i=Math.floor(n/8),o=n%8;return{byteOffset:r+i,bitIndex:o}}function Ar(t,e,n,r){if(!it(t,e,n))return!1;let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and is always present`);let o=ke(n),{byteOffset:s,bitIndex:a}=Nt(t,o,i.index);return(e[s]&1<<a)!==0}function vr(t,e,n,r){if(!it(t,e,n)){let c=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${c} is not alive`)}let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and cannot be added to entities`);let o=ke(n),{byteOffset:s,bitIndex:a}=Nt(t,o,i.index);e[s]=(e[s]??0)|1<<a}function Ur(t,e,n,r){let i=ke(e);return n.storageOffset+i*n.size+r.offset}function no(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":return(t[e]??0)!==0;case"uint8":return t[e]??0;case"int8":return r.getInt8(e);case"uint16":return r.getUint16(e,!0);case"int16":return r.getInt16(e,!0);case"uint32":return r.getUint32(e,!0);case"int32":return r.getInt32(e,!0);case"entityRef":return r.getUint32(e,!0);case"f32":return r.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}function Cr(t,e,n,r){let i=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":t[e]=r?1:0;break;case"uint8":t[e]=r&255;break;case"int8":i.setInt8(e,r);break;case"uint16":i.setUint16(e,r,!0);break;case"int16":i.setInt16(e,r,!0);break;case"uint32":i.setUint32(e,r,!0);break;case"int32":i.setInt32(e,r,!0);break;case"entityRef":i.setUint32(e,r,!0);break;case"f32":i.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function ro(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0)}function io(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0)}function oo(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0),r.setFloat32(e+12,n[3],!0)}function Ir(t,e,n,r,i,o){if(!it(t,e,n))return;let s=t.componentByName.get(r);if(!s)throw new Error(`Unknown component: \'${r}\'`);if(s.isSingleton)throw new Error(`Component \'${r}\' is a singleton; use singleton accessors instead`);if(!nt(t,e,n,s))return;let a=s.fields.find(f=>f.name===i);if(!a)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let c=Ur(t,n,s,a),u=a.type;if(a.arrayLength!==void 0&&a.arrayElementType!==void 0){if(o===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(o<0||o>=a.arrayLength)throw new Error(`Array index ${o} out of bounds for ${r}.${i} (length: ${a.arrayLength})`);let f=It[a.arrayElementType];if(f===void 0)throw new Error(`Unknown array element type: ${a.arrayElementType}`);c+=o*f,u=a.arrayElementType}return no(e,c,u)}function w(t,e,n,r,i,o,s){if(!it(t,e,n)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} is not alive`)}let a=t.componentByName.get(r);if(!a)throw new Error(`Unknown component: \'${r}\'`);if(!nt(t,e,n,a)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} does not have component \'${r}\'`)}let c=a.fields.find(p=>p.name===i);if(!c)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let u=Ur(t,n,a,c),f=c.type;if(c.arrayLength!==void 0&&c.arrayElementType!==void 0){if(s===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(s<0||s>=c.arrayLength)throw new Error(`Array index ${s} out of bounds for ${r}.${i} (length: ${c.arrayLength})`);let p=It[c.arrayElementType];if(p===void 0)throw new Error(`Unknown array element type: ${c.arrayElementType}`);u+=s*p,f=c.arrayElementType}Cr(e,u,f,o)}function nt(t,e,n,r){if(r.isSingleton)throw new Error(`Component \'${r.name}\' is a singleton and cannot be queried per entity`);let i=ke(n),{byteOffset:o,bitIndex:s}=Nt(t,i,r.index);return(e[o]&1<<s)!==0}function Br(t,e,n,r){if(n.length===0)throw new Error("Query must include at least one component");let i=[];for(let a of n){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);i.push(c)}let o=[];if(r)for(let a of r){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);o.push(c)}function*s(){for(let a=0;a<t.maxEntities;a++){let c=Ft(t,e,a),u=xr(a,c),f=!0;for(let p of i)if(!nt(t,e,u,p)){f=!1;break}if(f){for(let p of o)if(nt(t,e,u,p)){f=!1;break}f&&(yield u)}}}return s()}function _r(t,e){if(!t.events||!t.eventByName)throw new Error("Schema has no events");let n=t.eventByName.get(e);if(!n)throw new Error(`Unknown event: \'${e}\'`);return n}function Pr(t,e,n){let r=_r(t,n);new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(r.storageOffset,0,!0)}function $r(t,e,n,r){let i=_r(t,n),o=new DataView(e.buffer,e.byteOffset,e.byteLength),s=o.getUint16(i.storageOffset,!0);if(s>=i.maxEvents)return!1;let a=i.storageOffset+2+s*i.recordSize;for(let c of i.fields){let u=r[c.name];if(u===void 0)throw new Error(`Missing required field \'${c.name}\' for event \'${n}\'`);let f=a+c.offset;c.type==="vec2"?ro(e,f,u):c.type==="vec3"?io(e,f,u):c.type==="quat"?oo(e,f,u):Cr(e,f,c.type,u)}return o.setUint16(i.storageOffset,s+1,!0),!0}function ot(t){if(t.length!==32)throw new Error(`stateId must be ${32} bytes, got ${t.length}`);return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var st=class{constructor(e={}){y(this,"cache");y(this,"maxSize");this.cache=new Map,this.maxSize=e.maxSize??100}store(e){let n=de(e),r=ot(n);if(this.cache.size>=this.maxSize&&!this.cache.has(r)){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}this.cache.set(r,e.slice())}getByStateId(e){let n=ot(e),r=this.cache.get(n);return r?r.slice():void 0}getCached(e,n,r){let i=de(e),o=rt(i,n,r);return this.getByStateId(o)}has(e){let n=ot(e);return this.cache.has(n)}hasCached(e,n,r){let i=de(e),o=rt(i,n,r);return this.has(o)}delete(e){let n=ot(e);return this.cache.delete(n)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}};var Te=65536,at=class{constructor(e){y(this,"memory",null);y(this,"plugins",[]);y(this,"options");y(this,"stateSize",null);y(this,"statePtr",null);y(this,"heapPos",0);y(this,"arenaResetMark",0);y(this,"inputCodec",null);y(this,"playerEntities",new Map);y(this,"hostAlloc",(e,n)=>{let r=this.memory;if(!r)throw new Error("Memory not initialized for host_alloc");let i=this.heapPos+n-1&~(n-1),o=i+e,s=r.buffer.byteLength;if(o>s){let c=Math.ceil((o-s)/Te);if(this.options.debug){let u=(s+c*Te)/1048576;console.warn(`[mt] WASM memory grew to ${u.toFixed(1)}MB`)}r.grow(c)}return new Uint8Array(r.buffer).fill(0,i,o),this.heapPos=o,i});this.options=e}markArenaReset(){this.arenaResetMark=this.heapPos}resetArena(){this.heapPos=this.arenaResetMark}async init(){if(this.stateSize=this.options.stateSchema.totalSize,!this.stateSize)throw new Error("State schema total size is required");this.options.inputSchema&&(this.inputCodec=br(this.options.inputSchema));let e=4*1024*1024,n=this.options.plugins??(this.options.moduleBytes?[{name:"main",wasmBytes:this.options.moduleBytes,reservedBytes:e}]:[]);for(let c of n)if(typeof c.reservedBytes!="number"||c.reservedBytes<=0)throw new Error(`Plugin "${c.name}" requires reservedBytes > 0`);let r=n.reduce((c,u)=>{let f=Math.ceil(u.reservedBytes/Te)*Te;return c+f},0),i=1024*1024*5,o=this.stateSize+i+r,s=Math.ceil(o/Te);this.memory=new WebAssembly.Memory({initial:s}),this.heapPos=r;let a={env:{memory:this.memory,host_alloc:this.hostAlloc,abort:()=>{throw new Error("WASM abort called")}}};for(let c of n){let u=c.wasmBytes.slice().buffer,f=await WebAssembly.compile(u),p=await WebAssembly.instantiate(f,a);if(typeof p.exports.apply!="function")throw new Error(`Plugin "${c.name}" missing required apply() export`);this.plugins.push({name:c.name,instance:p,exports:p.exports})}return this.statePtr=this.hostAlloc(this.stateSize,8),this.markArenaReset(),this}findPlayerEntity(e,n){let r=this.options.stateSchema,i=this.playerEntities.get(n);if(i!==void 0){if(Ar(r,e,i,"Player"))return i;this.playerEntities.delete(n)}for(let o of Br(r,e,["Player"]))if(Ir(r,e,o,"Player","index")===n)return this.playerEntities.set(n,o),o}spawnPlayerEntity(e,n){let r=this.options.stateSchema,i=Tr(r,e);return vr(r,e,i,"Player"),w(r,e,i,"Player","index",n),this.playerEntities.set(n,i),i}findOrSpawnPlayerEntity(e,n){let r=this.findPlayerEntity(e,n);return r!==void 0?r:this.spawnPlayerEntity(e,n)}resetPlayerControls(e,n){let r=this.options.stateSchema;if(this.inputCodec)for(let i of this.inputCodec.schema.controls){if(i.retain==="always")continue;let o=i.field.type,s=i.name;if(o==="vec2")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0);else if(o==="vec3")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0);else if(o==="quat")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0),w(r,e,n,"Player",`${s}_w`,1);else if(o.startsWith("flags"))w(r,e,n,"Player",s,0);else if(o.includes("[")){let a=o.match(/\\[(\\d+)\\]/);if(a?.[1]){let c=parseInt(a[1],10);for(let u=0;u<c;u++)w(r,e,n,"Player",s,0,u)}}else w(r,e,n,"Player",s,o==="bool"?!1:0)}}writeControlsToPlayer(e,n,r){let i=this.options.stateSchema,o=this.options.inputSchema;if(o)for(let s of o.controls){if(!r.hasControl(s.name))continue;let a=s.type,c=s.name;if(a==="vec2"){let[u,f]=r.getVec2(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f)}else if(a==="vec3"){let[u,f,p]=r.getVec3(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p)}else if(a==="quat"){let[u,f,p,g]=r.getQuat(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p),w(i,e,n,"Player",`${c}_w`,g)}else if(a.startsWith("flags")){let u=r.getControl(c);w(i,e,n,"Player",c,u)}else if(a.includes("[")){let u=r.getControl(c);for(let f=0;f<u.length;f++)w(i,e,n,"Player",c,u[f],f)}else{let u=r.getControl(c);w(i,e,n,"Player",c,u)}}}pushCommands(e,n,r){let i=this.options.stateSchema,o=r.getCommands();for(let s of o){let a=s.name.charAt(0).toUpperCase()+s.name.slice(1)+"Command",c={player_index:n};for(let[u,f]of Object.entries(s))u!=="name"&&(Array.isArray(f)?f.length===2?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1]):f.length===3?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2]):f.length===4&&(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2],c[`${u}_w`]=f[3]):c[u]=f);$r(i,e,a,c)}}clearCommandEvents(e){let n=this.options.stateSchema,r=this.options.inputSchema;if(!(!r||!n.events))for(let i of r.commands){let o=i.name.charAt(0).toUpperCase()+i.name.slice(1)+"Command";n.eventByName?.has(o)&&Pr(n,e,o)}}decodePayloadsToState(e,n){if(this.inputCodec)for(let r=0;r<n.length;r++){let i=n[r];if(i===void 0)continue;let o=this.findOrSpawnPlayerEntity(e,r);if(this.resetPlayerControls(e,o),i.length===0)continue;let s=this.inputCodec.decode(i);this.writeControlsToPlayer(e,o,s),this.pushCommands(e,r,s)}}transition(e,n){let r=this.stateSize;if(r===null||e.length!==r)throw new Error(`State size mismatch: expected ${this.stateSize}, got ${e.length}`);if(this.plugins.length===0||n.length===0)return e.slice();let i=this.memory;if(!i)throw new Error("WASM memory not initialized");let o=this.statePtr;if(o===null||o<0)throw new Error("State pointer not initialized");let s=new Uint8Array(i.buffer);s.set(e,o);for(let a of n){this.resetArena();let c=new Uint8Array(i.buffer,o,r);wr(c,a.tick),this.clearCommandEvents(c),this.decodePayloadsToState(c,a.payloads);for(let u of this.plugins)u.exports.apply(o),s=new Uint8Array(i.buffer)}return s.slice(o,o+r)}close(){}getStateSize(){let e=this.stateSize;if(e===null||e<0)throw new Error("State size not initialized");return e}};var pe=class{constructor(e=1e3,n=1024){y(this,"buffer");y(this,"windowMs");y(this,"head",0);y(this,"tail",0);y(this,"size",0);this.windowMs=e,this.buffer=new Float64Array(n)}inc(){let e=performance.now();this.buffer[this.head]=e,this.head=(this.head+1)%this.buffer.length,this.size<this.buffer.length?this.size++:this.tail=(this.tail+1)%this.buffer.length}count(e=performance.now()){let n=e-this.windowMs;for(;this.size>0&&!(this.buffer[this.tail]>=n);)this.tail=(this.tail+1)%this.buffer.length,this.size--;return this.size}rate(e=performance.now()){return this.count(e)*(1e3/this.windowMs)}};function so(t){return("moduleBytes"in t||"plugins"in t)&&"stateSchema"in t}function ao(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var ct=class{constructor(e){y(this,"debug");y(this,"stateSchema");y(this,"inputs",null);y(this,"cache");y(this,"executor",null);y(this,"genesisStateId");y(this,"options");y(this,"ticking",!1);y(this,"tickGraceMs");y(this,"tickLag");y(this,"maxBatchSize");y(this,"currentState");y(this,"currentTick");y(this,"currentNodeId");y(this,"prevOnStateUpdateState",null);y(this,"onStateUpdate");y(this,"syncCheckpoint");y(this,"stateHistory",[]);y(this,"maxHistory",64);y(this,"stats");y(this,"loop",()=>{this._loop().catch(co)});y(this,"_loop",async()=>{if(this.ticking)try{let e=await this.tick();if(this.onStateUpdate&&this.currentState!==this.prevOnStateUpdateState&&(this.onStateUpdate(this.currentState),this.prevOnStateUpdateState=this.currentState,this.stats.updates.inc()),e.rolledBack&&this.stats.rollbacks.inc(),e.ticksComputed>0)for(let n=0;n<e.ticksComputed;n++)this.stats.executions.inc()}catch(e){console.error("Error in tick loop:",e)}finally{setTimeout(this.loop,this.tickGraceMs)}});e.log&&(this.inputs=e.log),this.debug=e.debug??!1,this.options=e,this.stateSchema=e.stateSchema,this.cache=e.cache??new st,this.genesisStateId=Ot(e.genesisHash),this.tickGraceMs=e.tickGraceMs??10,this.tickLag=e.tickLag??1,this.maxBatchSize=e.maxBatchSize??200,this.stats={rollbacks:new pe,executions:new pe,updates:new pe},this.currentState=Er(this.stateSchema,e.genesisHash,e.tickRate),this.currentNodeId=null,this.syncCheckpoint=null,this.currentTick=null,this.cache.store(this.currentState)}setLog(e){this.inputs=lt(e)}setOnStateUpdate(e){e===null&&(this.prevOnStateUpdateState=null),this.onStateUpdate=e}async init(){if(!this.inputs)throw new Error("Rollback.init() called before log was configured. Call setLog() first or pass log in options.");let e=this.options.executor;if(so(e)){let r=new at(e);await r.init(),this.executor=r}else this.executor=e;if((await this.tick(0)).ticksComputed===0||this.currentTick===null)throw new Error("Failed to record genesis snapshot");return this.options.disableTicking||(this.ticking=!0,this.loop()),this.getState()}async tick(e){if(!this.inputs)throw new Error("Rollback.tick() called before log was configured. Call setLog() and init() first.");let n=await this.inputs.getTicksAfter(this.currentNodeId,{limit:this.maxBatchSize,lag:this.tickLag});if(e&&(n=n.filter(s=>s.tick<=e)),n.length===0)return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:!1,ticksComputed:0};let r=!1;this.currentTick!==null&&n[0].tick<this.currentTick&&(r=!0,this.rollbackTo(n[0]));let i=n.filter(s=>this.currentTick===null||s.tick>this.currentTick);if(i.length===0)return this.currentNodeId=n[n.length-1].id,{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId,rolledBack:r,ticksComputed:0};let o=this.processTicks(i);return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:r,ticksComputed:o}}async getStats(){return{rollbacks:this.stats.rollbacks.rate(),executions:this.stats.executions.rate(),updates:this.stats.updates.rate()}}processTicks(e){if(!this.executor)throw new Error("Executor not initialized");let n=0,r=0;for(let a=0;a<e.length;a++){let c=e[a],u=Qe(c.payloads),f=this.cache.getCached(this.currentState,c.tick,u);if(f)this.currentState=f,this.currentTick=c.tick,this.currentNodeId=c.id,r=a+1,c.sync&&this.updateSyncCheckpoint(c);else break}let i=e.slice(r);if(i.length===0)return 0;let o=ao(i,a=>a.sync);if(o>=0){let a=i.slice(0,o+1),c=this.executor.transition(this.currentState,a),u=this.computeBatchStateId(this.currentState,a);$t(c,u);let f=a[a.length-1];this.currentState=c,this.currentTick=f.tick,this.currentNodeId=f.id,n+=a.length,this.cache.store(c),this.recordStateSnapshot(this.currentTick,this.currentNodeId,u),this.updateSyncCheckpoint(f)}let s=o>=0?i.slice(o+1):i;if(s.length>0){let a=this.executor.transition(this.currentState,s),c=this.computeBatchStateId(this.currentState,s);$t(a,c);let u=s[s.length-1];this.currentState=a,this.currentTick=u.tick,this.currentNodeId=u.id,n+=s.length,this.cache.store(a),this.recordStateSnapshot(this.currentTick,this.currentNodeId,c)}return n}computeBatchStateId(e,n){let r=de(e);for(let i of n)r=Sr(r,i.tick,i.payloads);return r}getState(){return this.currentState.slice()}getTick(){return this.currentTick}reset(){this.currentTick=0,this.currentNodeId=null,this.syncCheckpoint=null}close(){this.ticking=!1,this.setOnStateUpdate(null),this.executor&&(this.executor.close(),this.executor=null)}rollbackTo(e){if(this.syncCheckpoint&&this.syncCheckpoint.tick>=e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}if(this.syncCheckpoint&&this.syncCheckpoint.tick<e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}let n=e.tick-1,r=this.findSnapshotAtOrBefore(n);if(r){let o=this.cache.getByStateId(r.stateId);if(o){this.currentState=o,this.currentTick=r.tick,this.currentNodeId=r.nodeId;return}}let i=this.cache.getByStateId(this.genesisStateId);if(i){this.currentState=i,this.currentTick=0,this.currentNodeId=null;return}}updateSyncCheckpoint(e){this.syncCheckpoint={state:this.currentState.slice(),tick:e.tick,nodeId:e.id}}recordStateSnapshot(e,n,r){this.stateHistory.push({tick:e,nodeId:n,stateId:r.slice()}),this.stateHistory.length>this.maxHistory&&this.stateHistory.shift()}findSnapshotAtOrBefore(e){for(let n=this.stateHistory.length-1;n>=0;n--){let r=this.stateHistory[n];if(r.tick<=e)return r}return null}};function co(t){console.warn("rollback unexpected:",t)}Be(ct);var Ga=null;globalThis.onerror=t=>(console.error("\\u{1F534} FATAL ROLLBACK WORKER ERROR (Uncaught Exception):",t),!0);export{Ga as default};\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n\n@noble/secp256k1/index.js:\n (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)\n\n@noble/hashes/esm/utils.js:\n (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)\n*/\n';
6567
7147
  function Worker() {
6568
7148
  const blob = new Blob([workerCode], { type: "text/javascript" });
6569
7149
  const url = URL.createObjectURL(blob);
@@ -6572,16 +7152,6 @@ function Worker() {
6572
7152
  return worker;
6573
7153
  }
6574
7154
 
6575
- // src/rollback.worker.ts
6576
- var workerCode2 = 'var Or=Object.defineProperty;var Fr=(t,e,n)=>e in t?Or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>Fr(t,typeof e!="symbol"?e+"":e,n);var Rt=Symbol("Comlink.proxy"),Nr=Symbol("Comlink.endpoint"),Rr=Symbol("Comlink.releaseProxy"),ut=Symbol("Comlink.finalizer"),ve=Symbol("Comlink.thrown"),Dt=t=>typeof t=="object"&&t!==null||typeof t=="function",Dr={canHandle:t=>Dt(t)&&t[Rt],serialize(t){let{port1:e,port2:n}=new MessageChannel;return Be(t,e),[n,[n]]},deserialize(t){return t.start(),lt(t)}},Lr={canHandle:t=>Dt(t)&&ve in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},Lt=new Map([["proxy",Dr],["throw",Lr]]);function Hr(t,e){for(let n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function Be(t,e=globalThis,n=["*"]){e.addEventListener("message",function r(i){if(!i||!i.data)return;if(!Hr(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:o,type:s,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(W),u;try{let f=a.slice(0,-1).reduce((g,S)=>g[S],t),p=a.reduce((g,S)=>g[S],t);switch(s){case"GET":u=p;break;case"SET":f[a.slice(-1)[0]]=W(i.data.value),u=!0;break;case"APPLY":u=p.apply(f,c);break;case"CONSTRUCT":{let g=new p(...c);u=qr(g)}break;case"ENDPOINT":{let{port1:g,port2:S}=new MessageChannel;Be(t,S),u=Zr(g,[g])}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,[ve]:0}}Promise.resolve(u).catch(f=>({value:f,[ve]:0})).then(f=>{let[p,g]=Ie(f);e.postMessage(Object.assign(Object.assign({},p),{id:o}),g),s==="RELEASE"&&(e.removeEventListener("message",r),Ht(e),ut in t&&typeof t[ut]=="function"&&t[ut]())}).catch(f=>{let[p,g]=Ie({value:new TypeError("Unserializable return value"),[ve]:0});e.postMessage(Object.assign(Object.assign({},p),{id:o}),g)})}),e.start&&e.start()}function Mr(t){return t.constructor.name==="MessagePort"}function Ht(t){Mr(t)&&t.close()}function lt(t,e){let n=new Map;return t.addEventListener("message",function(i){let{data:o}=i;if(!o||!o.id)return;let s=n.get(o.id);if(s)try{s(o)}finally{n.delete(o.id)}}),ft(t,n,[],e)}function Ae(t){if(t)throw new Error("Proxy has been released and is not useable")}function Mt(t){return te(t,new Map,{type:"RELEASE"}).then(()=>{Ht(t)})}var Ue=new WeakMap,Ce="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(Ue.get(t)||0)-1;Ue.set(t,e),e===0&&Mt(t)});function zr(t,e){let n=(Ue.get(e)||0)+1;Ue.set(e,n),Ce&&Ce.register(t,e,t)}function Vr(t){Ce&&Ce.unregister(t)}function ft(t,e,n=[],r=function(){}){let i=!1,o=new Proxy(r,{get(s,a){if(Ae(i),a===Rr)return()=>{Vr(o),Mt(t),e.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>o};let c=te(t,e,{type:"GET",path:n.map(u=>u.toString())}).then(W);return c.then.bind(c)}return ft(t,e,[...n,a])},set(s,a,c){Ae(i);let[u,f]=Ie(c);return te(t,e,{type:"SET",path:[...n,a].map(p=>p.toString()),value:u},f).then(W)},apply(s,a,c){Ae(i);let u=n[n.length-1];if(u===Nr)return te(t,e,{type:"ENDPOINT"}).then(W);if(u==="bind")return ft(t,e,n.slice(0,-1));let[f,p]=Nt(c);return te(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:f},p).then(W)},construct(s,a){Ae(i);let[c,u]=Nt(a);return te(t,e,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:c},u).then(W)}});return zr(o,t),o}function Gr(t){return Array.prototype.concat.apply([],t)}function Nt(t){let e=t.map(Ie);return[e.map(n=>n[0]),Gr(e.map(n=>n[1]))]}var zt=new WeakMap;function Zr(t,e){return zt.set(t,e),t}function qr(t){return Object.assign(t,{[Rt]:!0})}function Ie(t){for(let[e,n]of Lt)if(n.canHandle(t)){let[r,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:r},i]}return[{type:"RAW",value:t},zt.get(t)||[]]}function W(t){switch(t.type){case"HANDLER":return Lt.get(t.name).deserialize(t.value);case"RAW":return t.value}}function te(t,e,n,r){return new Promise(i=>{let o=Kr();e.set(o,i),t.start&&t.start(),t.postMessage(Object.assign({id:o},n),r)})}function Kr(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Wr={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:Y,n:ht,Gx:jr,Gy:Yr,b:jt}=Wr,ne=32,dt=64,U=(t="")=>{throw new Error(t)},Yt=t=>typeof t=="bigint",Xt=t=>typeof t=="string",Xr=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",he=(t,e)=>!Xr(t)||typeof e=="number"&&e>0&&t.length!==e?U("Uint8Array expected"):t,Ne=t=>new Uint8Array(t),Jr=t=>Uint8Array.from(t),Jt=(t,e)=>t.toString(16).padStart(e,"0"),yt=t=>Array.from(he(t)).map(e=>Jt(e,2)).join(""),z={_0:48,_9:57,A:65,F:70,a:97,f:102},Vt=t=>{if(t>=z._0&&t<=z._9)return t-z._0;if(t>=z.A&&t<=z.F)return t-(z.A-10);if(t>=z.a&&t<=z.f)return t-(z.a-10)},gt=t=>{let e="hex invalid";if(!Xt(t))return U(e);let n=t.length,r=n/2;if(n%2)return U(e);let i=Ne(r);for(let o=0,s=0;o<r;o++,s+=2){let a=Vt(t.charCodeAt(s)),c=Vt(t.charCodeAt(s+1));if(a===void 0||c===void 0)return U(e);i[o]=a*16+c}return i},bt=(t,e)=>he(Xt(t)?gt(t):Jr(he(t)),e),Qt=()=>globalThis?.crypto,Qr=()=>Qt()?.subtle??U("crypto.subtle must be defined"),Pe=(...t)=>{let e=Ne(t.reduce((r,i)=>r+he(i).length,0)),n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},ei=(t=ne)=>Qt().getRandomValues(Ne(t)),$e=BigInt,ye=(t,e,n,r="bad number: out of range")=>Yt(t)&&e<=t&&t<n?t:U(r),h=(t,e=Y)=>{let n=t%e;return n>=0n?n:e+n};var en=(t,e)=>{(t===0n||e<=0n)&&U("no inverse n="+t+" mod="+e);let n=h(t,e),r=e,i=0n,o=1n,s=1n,a=0n;for(;n!==0n;){let c=r/n,u=r%n,f=i-s*c,p=o-a*c;r=n,n=u,i=s,o=a,s=f,a=p}return r===1n?h(i,e):U("no inverse")};var Gt=t=>t instanceof X?t:U("Point expected"),tn=t=>h(h(t*t)*t+jt),Zt=t=>ye(t,0n,Y),_e=t=>ye(t,1n,Y),ti=t=>ye(t,1n,ht),pt=t=>(t&1n)===0n,nn=t=>Uint8Array.of(t),ni=t=>nn(pt(t)?2:3),ri=t=>{let e=tn(_e(t)),n=1n;for(let r=e,i=(Y+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%Y),r=r*r%Y;return h(n*n)===e?n:U("sqrt invalid")},D=class D{constructor(e,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=Zt(e),this.py=_e(n),this.pz=Zt(r),Object.freeze(this)}static fromBytes(e){he(e);let n,r=e[0],i=e.subarray(1),o=qt(i,0,ne),s=e.length;if(s===ne+1&&[2,3].includes(r)){let a=ri(o),c=pt(a);pt($e(r))!==c&&(a=h(-a)),n=new D(o,a,1n)}return s===dt+1&&r===4&&(n=new D(o,qt(i,ne,dt),1n)),n?n.assertValidity():U("bad point: not on curve")}equals(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Gt(e),c=h(n*a),u=h(o*i),f=h(r*a),p=h(s*i);return c===u&&f===p}is0(){return this.equals(j)}negate(){return new D(this.px,h(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Gt(e),c=0n,u=jt,f=0n,p=0n,g=0n,S=h(u*3n),k=h(n*o),A=h(r*s),O=h(i*a),ee=h(n+r),v=h(o+s);ee=h(ee*v),v=h(k+A),ee=h(ee-v),v=h(n+i);let R=h(o+a);return v=h(v*R),R=h(k+O),v=h(v-R),R=h(r+i),f=h(s+a),R=h(R*f),f=h(A+O),R=h(R-f),g=h(c*v),f=h(S*O),g=h(f+g),f=h(A-g),g=h(A+g),p=h(f*g),A=h(k+k),A=h(A+k),O=h(c*O),v=h(S*v),A=h(A+O),O=h(k-O),O=h(c*O),v=h(v+O),k=h(A*v),p=h(p+k),k=h(R*v),f=h(ee*f),f=h(f-k),k=h(ee*A),g=h(R*g),g=h(g+k),new D(f,p,g)}multiply(e,n=!0){if(!n&&e===0n)return j;if(ti(e),e===1n)return this;if(this.equals(re))return fi(e).p;let r=j,i=re;for(let o=this;e>0n;o=o.double(),e>>=1n)e&1n?r=r.add(o):n&&(i=i.add(o));return r}toAffine(){let{px:e,py:n,pz:r}=this;if(this.equals(j))return{x:0n,y:0n};if(r===1n)return{x:e,y:n};let i=en(r,Y);return h(r*i)!==1n&&U("inverse invalid"),{x:h(e*i),y:h(n*i)}}assertValidity(){let{x:e,y:n}=this.toAffine();return _e(e),_e(n),h(n*n)===tn(e)?this:U("bad point: not on curve")}toBytes(e=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=Oe(n);return e?Pe(ni(r),i):Pe(nn(4),i,Oe(r))}static fromAffine(e){let{x:n,y:r}=e;return n===0n&&r===0n?j:new D(n,r,1n)}toHex(e){return yt(this.toBytes(e))}static fromPrivateKey(e){return re.multiply(oi(e))}static fromHex(e){return D.fromBytes(bt(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(e){return this.toBytes(e)}};y(D,"BASE"),y(D,"ZERO");var X=D,re=new X(jr,Yr,1n),j=new X(0n,1n,0n);X.BASE=re;X.ZERO=j;var Re=t=>$e("0x"+(yt(t)||"0")),qt=(t,e,n)=>Re(t.subarray(e,n)),ii=2n**256n,Oe=t=>gt(Jt(ye(t,0n,ii),dt)),oi=t=>{let e=Yt(t)?t:Re(bt(t,ne));return ye(e,1n,ht,"private key invalid 3")};var si=t=>{t=bt(t),(t.length<ne+8||t.length>1024)&&U("expected 40-1024b");let e=h(Re(t),ht-1n);return Oe(e+1n)};var ai="SHA-256",xt={hexToBytes:gt,bytesToHex:yt,concatBytes:Pe,bytesToNumberBE:Re,numberToBytesBE:Oe,mod:h,invert:en,hmacSha256Async:async(t,...e)=>{let n=Qr(),r="HMAC",i=await n.importKey("raw",t,{name:r,hash:{name:ai}},!1,["sign"]);return Ne(await n.sign(r,i,Pe(...e)))},hmacSha256Sync:void 0,hashToPrivateKey:si,randomBytes:ei};var Fe=8,ci=256,rn=Math.ceil(ci/Fe)+1,mt=2**(Fe-1),ui=()=>{let t=[],e=re,n=e;for(let r=0;r<rn;r++){n=e,t.push(n);for(let i=1;i<mt;i++)n=n.add(e),t.push(n);e=n.double()}return t},Kt,Wt=(t,e)=>{let n=e.negate();return t?n:e},fi=t=>{let e=Kt||(Kt=ui()),n=j,r=re,i=2**Fe,o=i,s=$e(i-1),a=$e(Fe);for(let c=0;c<rn;c++){let u=Number(t&s);t>>=a,u>mt&&(u-=o,t+=1n);let f=c*mt,p=f,g=f+Math.abs(u)-1,S=c%2!==0,k=u<0;u===0?r=r.add(Wt(S,e[p])):n=n.add(Wt(k,e[g]))}return{p:n,f:r}};function di(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function on(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function oe(t,...e){if(!di(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function sn(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");on(t.outputLen),on(t.blockLen)}function se(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function an(t,e){oe(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function J(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function De(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function F(t,e){return t<<32-e|t>>>e}function pi(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ge(t){return typeof t=="string"&&(t=pi(t)),oe(t),t}var ie=class{};function cn(t){let e=r=>t().update(ge(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mi(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}function un(t,e,n){return t&e^~t&n}function fn(t,e,n){return t&e^t&n^e&n}var Le=class extends ie{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=De(this.buffer)}update(e){se(this),e=ge(e),oe(e);let{view:n,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=De(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){se(this),an(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;n[s++]=128,J(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let p=s;p<i;p++)n[p]=0;mi(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=De(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)a.setUint32(4*p,f[p],o)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},V=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=new Uint32Array(64),He=class extends Le{constructor(e=32){super(64,e,8,!1),this.A=V[0]|0,this.B=V[1]|0,this.C=V[2]|0,this.D=V[3]|0,this.E=V[4]|0,this.F=V[5]|0,this.G=V[6]|0,this.H=V[7]|0}get(){let{A:e,B:n,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[e,n,r,i,o,s,a,c]}set(e,n,r,i,o,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let p=0;p<16;p++,n+=4)Z[p]=e.getUint32(n,!1);for(let p=16;p<64;p++){let g=Z[p-15],S=Z[p-2],k=F(g,7)^F(g,18)^g>>>3,A=F(S,17)^F(S,19)^S>>>10;Z[p]=A+Z[p-7]+k+Z[p-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let p=0;p<64;p++){let g=F(a,6)^F(a,11)^F(a,25),S=f+g+un(a,c,u)+hi[p]+Z[p]|0,A=(F(r,2)^F(r,13)^F(r,22))+fn(r,i,o)|0;f=u,u=c,c=a,a=s+S|0,s=o,o=i,i=r,r=S+A|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,o,s,a,c,u,f)}roundClean(){J(Z)}destroy(){this.set(0,0,0,0,0,0,0,0),J(this.buffer)}};var ln=cn(()=>new He);var ae=ln;var Me=class extends ie{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,sn(e);let r=ge(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),J(o)}update(e){return se(this),this.iHash.update(e),this}digestInto(e){se(this),oe(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wt=(t,e,n)=>new Me(t,e).update(n).digest();wt.create=(t,e)=>new Me(t,e);var yi=["string","number","bigint","symbol"],gi=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function dn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(yi.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(bi(t))return"Buffer";let n=xi(t);return n||"Object"}function bi(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function xi(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(gi.includes(e))return e}var l=class{constructor(e,n,r){this.major=e,this.majorEncoded=e<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};l.uint=new l(0,"uint",!0);l.negint=new l(1,"negint",!0);l.bytes=new l(2,"bytes",!0);l.string=new l(3,"string",!0);l.array=new l(4,"array",!1);l.map=new l(5,"map",!1);l.tag=new l(6,"tag",!1);l.float=new l(7,"float",!0);l.false=new l(7,"false",!0);l.true=new l(7,"true",!0);l.null=new l(7,"null",!0);l.undefined=new l(7,"undefined",!0);l.break=new l(7,"break",!0);var m=class{constructor(e,n,r){this.type=e,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ce=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",wi=new TextDecoder,Si=new TextEncoder;function ze(t){return ce&&globalThis.Buffer.isBuffer(t)}function St(t){return t instanceof Uint8Array?ze(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var yn=ce?(t,e,n)=>n-e>64?globalThis.Buffer.from(t.subarray(e,n)).toString("utf8"):mn(t,e,n):(t,e,n)=>n-e>64?wi.decode(t.subarray(e,n)):mn(t,e,n),gn=ce?t=>t.length>64?globalThis.Buffer.from(t):pn(t):t=>t.length>64?Si.encode(t):pn(t),L=t=>Uint8Array.from(t),ue=ce?(t,e,n)=>ze(t)?new Uint8Array(t.subarray(e,n)):t.slice(e,n):(t,e,n)=>t.slice(e,n),bn=ce?(t,e)=>(t=t.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),St(globalThis.Buffer.concat(t,e))):(t,e)=>{let n=new Uint8Array(e),r=0;for(let i of t)r+i.length>n.length&&(i=i.subarray(0,n.length-r)),n.set(i,r),r+=i.length;return n},xn=ce?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ve(t,e){if(ze(t)&&ze(e))return t.compare(e);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return 0}function pn(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e}function mn(t,e,n){let r=[];for(;e<n;){let i=t[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=n){let a,c,u,f;switch(s){case 1:i<128&&(o=i);break;case 2:a=t[e+1],(a&192)===128&&(f=(i&31)<<6|a&63,f>127&&(o=f));break;case 3:a=t[e+1],c=t[e+2],(a&192)===128&&(c&192)===128&&(f=(i&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:a=t[e+1],c=t[e+2],u=t[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(f=(i&15)<<18|(a&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(o=f))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|o&1023),r.push(o),e+=s}return Ei(r)}var hn=4096;function Ei(t){let e=t.length;if(e<=hn)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=hn));return n}var ki=256,be=class{constructor(e=ki){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let n=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=n.length-(this.maxCursor-this.cursor)-1;n.set(e,i)}else{if(n){let i=n.length-(this.maxCursor-this.cursor)-1;i<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(n=xn(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];e&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=ue(r,0,this.cursor)}else n=bn(this.chunks,this.cursor);return e&&this.reset(),n}};var b="CBOR decode error:",Et="CBOR encode error:",xe=[];xe[23]=1;xe[24]=2;xe[25]=3;xe[26]=5;xe[27]=9;function G(t,e,n){if(t.length-e<n)throw new Error(`${b} not enough data for type`)}var E=[24,256,65536,4294967296,BigInt("18446744073709551616")];function C(t,e,n){G(t,e,1);let r=t[e];if(n.strict===!0&&r<E[0])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function I(t,e,n){G(t,e,2);let r=t[e]<<8|t[e+1];if(n.strict===!0&&r<E[1])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function B(t,e,n){G(t,e,4);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(n.strict===!0&&r<E[2])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function _(t,e,n){G(t,e,8);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],i=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],o=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&o<E[3])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(n.allowBigInt===!0)return o;throw new Error(`${b} integers outside of the safe integer range are not supported`)}function wn(t,e,n,r){return new m(l.uint,C(t,e+1,r),2)}function Sn(t,e,n,r){return new m(l.uint,I(t,e+1,r),3)}function En(t,e,n,r){return new m(l.uint,B(t,e+1,r),5)}function kn(t,e,n,r){return new m(l.uint,_(t,e+1,r),9)}function P(t,e){return T(t,0,e.value)}function T(t,e,n){if(n<E[0]){let r=Number(n);t.push([e|r])}else if(n<E[1]){let r=Number(n);t.push([e|24,r])}else if(n<E[2]){let r=Number(n);t.push([e|25,r>>>8,r&255])}else if(n<E[3]){let r=Number(n);t.push([e|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<E[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(r&BigInt(4294967295)),s=Number(r>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,t.push(i)}else throw new Error(`${b} encountered BigInt larger than allowable range`)}}P.encodedSize=function(e){return T.encodedSize(e.value)};T.encodedSize=function(e){return e<E[0]?1:e<E[1]?2:e<E[2]?3:e<E[3]?5:9};P.compareTokens=function(e,n){return e.value<n.value?-1:e.value>n.value?1:0};function Tn(t,e,n,r){return new m(l.negint,-1-C(t,e+1,r),2)}function An(t,e,n,r){return new m(l.negint,-1-I(t,e+1,r),3)}function vn(t,e,n,r){return new m(l.negint,-1-B(t,e+1,r),5)}var kt=BigInt(-1),Un=BigInt(1);function Cn(t,e,n,r){let i=_(t,e+1,r);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new m(l.negint,o,9)}if(r.allowBigInt!==!0)throw new Error(`${b} integers outside of the safe integer range are not supported`);return new m(l.negint,kt-BigInt(i),9)}function Ge(t,e){let n=e.value,r=typeof n=="bigint"?n*kt-Un:n*-1-1;T(t,e.type.majorEncoded,r)}Ge.encodedSize=function(e){let n=e.value,r=typeof n=="bigint"?n*kt-Un:n*-1-1;return r<E[0]?1:r<E[1]?2:r<E[2]?3:r<E[3]?5:9};Ge.compareTokens=function(e,n){return e.value<n.value?1:e.value>n.value?-1:0};function we(t,e,n,r){G(t,e,n+r);let i=ue(t,e+n,e+n+r);return new m(l.bytes,i,n+r)}function In(t,e,n,r){return we(t,e,1,n)}function Bn(t,e,n,r){return we(t,e,2,C(t,e+1,r))}function _n(t,e,n,r){return we(t,e,3,I(t,e+1,r))}function Pn(t,e,n,r){return we(t,e,5,B(t,e+1,r))}function $n(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer bytes lengths not supported`);return we(t,e,9,i)}function Ze(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===l.string?gn(t.value):t.value),t.encodedBytes}function fe(t,e){let n=Ze(e);T(t,e.type.majorEncoded,n.length),t.push(n)}fe.encodedSize=function(e){let n=Ze(e);return T.encodedSize(n.length)+n.length};fe.compareTokens=function(e,n){return Ai(Ze(e),Ze(n))};function Ai(t,e){return t.length<e.length?-1:t.length>e.length?1:Ve(t,e)}function Se(t,e,n,r,i){let o=n+r;G(t,e,o);let s=new m(l.string,yn(t,e+n,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=ue(t,e+n,e+o)),s}function On(t,e,n,r){return Se(t,e,1,n,r)}function Fn(t,e,n,r){return Se(t,e,2,C(t,e+1,r),r)}function Nn(t,e,n,r){return Se(t,e,3,I(t,e+1,r),r)}function Rn(t,e,n,r){return Se(t,e,5,B(t,e+1,r),r)}function Dn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer string lengths not supported`);return Se(t,e,9,i,r)}var Ln=fe;function le(t,e,n,r){return new m(l.array,r,n)}function Hn(t,e,n,r){return le(t,e,1,n)}function Mn(t,e,n,r){return le(t,e,2,C(t,e+1,r))}function zn(t,e,n,r){return le(t,e,3,I(t,e+1,r))}function Vn(t,e,n,r){return le(t,e,5,B(t,e+1,r))}function Gn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer array lengths not supported`);return le(t,e,9,i)}function Zn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return le(t,e,1,1/0)}function qe(t,e){T(t,l.array.majorEncoded,e.value)}qe.compareTokens=P.compareTokens;qe.encodedSize=function(e){return T.encodedSize(e.value)};function de(t,e,n,r){return new m(l.map,r,n)}function qn(t,e,n,r){return de(t,e,1,n)}function Kn(t,e,n,r){return de(t,e,2,C(t,e+1,r))}function Wn(t,e,n,r){return de(t,e,3,I(t,e+1,r))}function jn(t,e,n,r){return de(t,e,5,B(t,e+1,r))}function Yn(t,e,n,r){let i=_(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer map lengths not supported`);return de(t,e,9,i)}function Xn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return de(t,e,1,1/0)}function Ke(t,e){T(t,l.map.majorEncoded,e.value)}Ke.compareTokens=P.compareTokens;Ke.encodedSize=function(e){return T.encodedSize(e.value)};function Jn(t,e,n,r){return new m(l.tag,n,1)}function Qn(t,e,n,r){return new m(l.tag,C(t,e+1,r),2)}function er(t,e,n,r){return new m(l.tag,I(t,e+1,r),3)}function tr(t,e,n,r){return new m(l.tag,B(t,e+1,r),5)}function nr(t,e,n,r){return new m(l.tag,_(t,e+1,r),9)}function We(t,e){T(t,l.tag.majorEncoded,e.value)}We.compareTokens=P.compareTokens;We.encodedSize=function(e){return T.encodedSize(e.value)};var _i=20,Pi=21,$i=22,Oi=23;function rr(t,e,n,r){if(r.allowUndefined===!1)throw new Error(`${b} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new m(l.null,null,1):new m(l.undefined,void 0,1)}function ir(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return new m(l.break,void 0,1)}function Tt(t,e,n){if(n){if(n.allowNaN===!1&&Number.isNaN(t))throw new Error(`${b} NaN values are not supported`);if(n.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${b} Infinity values are not supported`)}return new m(l.float,t,e)}function or(t,e,n,r){return Tt(At(t,e+1),3,r)}function sr(t,e,n,r){return Tt(vt(t,e+1),5,r)}function ar(t,e,n,r){return Tt(lr(t,e+1),9,r)}function je(t,e,n){let r=e.value;if(r===!1)t.push([l.float.majorEncoded|_i]);else if(r===!0)t.push([l.float.majorEncoded|Pi]);else if(r===null)t.push([l.float.majorEncoded|$i]);else if(r===void 0)t.push([l.float.majorEncoded|Oi]);else{let i,o=!1;(!n||n.float64!==!0)&&(ur(r),i=At(N,1),r===i||Number.isNaN(r)?(N[0]=249,t.push(N.slice(0,3)),o=!0):(fr(r),i=vt(N,1),r===i&&(N[0]=250,t.push(N.slice(0,5)),o=!0))),o||(Fi(r),i=lr(N,1),N[0]=251,t.push(N.slice(0,9)))}}je.encodedSize=function(e,n){let r=e.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){ur(r);let i=At(N,1);if(r===i||Number.isNaN(r))return 3;if(fr(r),i=vt(N,1),r===i)return 5}return 9};var cr=new ArrayBuffer(9),$=new DataView(cr,1),N=new Uint8Array(cr,0);function ur(t){if(t===1/0)$.setUint16(0,31744,!1);else if(t===-1/0)$.setUint16(0,64512,!1);else if(Number.isNaN(t))$.setUint16(0,32256,!1);else{$.setFloat32(0,t);let e=$.getUint32(0),n=(e&2139095040)>>23,r=e&8388607;if(n===255)$.setUint16(0,31744,!1);else if(n===0)$.setUint16(0,(t&2147483648)>>16|r>>13,!1);else{let i=n-127;i<-24?$.setUint16(0,0):i<-14?$.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):$.setUint16(0,(e&2147483648)>>16|i+15<<10|r>>13,!1)}}}function At(t,e){if(t.length-e<2)throw new Error(`${b} not enough data for float16`);let n=(t[e]<<8)+t[e+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,o;return r===0?o=i*2**-24:r!==31?o=(i+1024)*2**(r-25):o=i===0?1/0:NaN,n&32768?-o:o}function fr(t){$.setFloat32(0,t,!1)}function vt(t,e){if(t.length-e<4)throw new Error(`${b} not enough data for float32`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,4).getFloat32(0,!1)}function Fi(t){$.setFloat64(0,t,!1)}function lr(t,e){if(t.length-e<8)throw new Error(`${b} not enough data for float64`);let n=(t.byteOffset||0)+e;return new DataView(t.buffer,n,8).getFloat64(0,!1)}je.compareTokens=P.compareTokens;function x(t,e,n){throw new Error(`${b} encountered invalid minor (${n}) for major ${t[e]>>>5}`)}function Ye(t){return()=>{throw new Error(`${b} ${t}`)}}var d=[];for(let t=0;t<=23;t++)d[t]=x;d[24]=wn;d[25]=Sn;d[26]=En;d[27]=kn;d[28]=x;d[29]=x;d[30]=x;d[31]=x;for(let t=32;t<=55;t++)d[t]=x;d[56]=Tn;d[57]=An;d[58]=vn;d[59]=Cn;d[60]=x;d[61]=x;d[62]=x;d[63]=x;for(let t=64;t<=87;t++)d[t]=In;d[88]=Bn;d[89]=_n;d[90]=Pn;d[91]=$n;d[92]=x;d[93]=x;d[94]=x;d[95]=Ye("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)d[t]=On;d[120]=Fn;d[121]=Nn;d[122]=Rn;d[123]=Dn;d[124]=x;d[125]=x;d[126]=x;d[127]=Ye("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)d[t]=Hn;d[152]=Mn;d[153]=zn;d[154]=Vn;d[155]=Gn;d[156]=x;d[157]=x;d[158]=x;d[159]=Zn;for(let t=160;t<=183;t++)d[t]=qn;d[184]=Kn;d[185]=Wn;d[186]=jn;d[187]=Yn;d[188]=x;d[189]=x;d[190]=x;d[191]=Xn;for(let t=192;t<=215;t++)d[t]=Jn;d[216]=Qn;d[217]=er;d[218]=tr;d[219]=nr;d[220]=x;d[221]=x;d[222]=x;d[223]=x;for(let t=224;t<=243;t++)d[t]=Ye("simple values are not supported");d[244]=x;d[245]=x;d[246]=x;d[247]=rr;d[248]=Ye("simple values are not supported");d[249]=or;d[250]=sr;d[251]=ar;d[252]=x;d[253]=x;d[254]=x;d[255]=ir;var H=[];for(let t=0;t<24;t++)H[t]=new m(l.uint,t,1);for(let t=-1;t>=-24;t--)H[31-t]=new m(l.negint,t,1);H[64]=new m(l.bytes,new Uint8Array(0),1);H[96]=new m(l.string,"",1);H[128]=new m(l.array,0,1);H[160]=new m(l.map,0,1);H[244]=new m(l.false,!1,1);H[245]=new m(l.true,!0,1);H[246]=new m(l.null,null,1);function dr(t){switch(t.type){case l.false:return L([244]);case l.true:return L([245]);case l.null:return L([246]);case l.bytes:return t.value.length?void 0:L([64]);case l.string:return t.value===""?L([96]):void 0;case l.array:return t.value===0?L([128]):void 0;case l.map:return t.value===0?L([160]):void 0;case l.uint:return t.value<24?L([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return L([31-Number(t.value)])}}var mr=Object.freeze({float64:!0,mapSorter:Hi,quickEncodeToken:dr});function Ri(){let t=[];return t[l.uint.major]=P,t[l.negint.major]=Ge,t[l.bytes.major]=fe,t[l.string.major]=Ln,t[l.array.major]=qe,t[l.map.major]=Ke,t[l.tag.major]=We,t[l.float.major]=je,t}var Di=Ri(),Ut=new be,Je=class t{constructor(e,n){this.obj=e,this.parent=n}includes(e){let n=this;do if(n.obj===e)return!0;while(n=n.parent);return!1}static createCheck(e,n){if(e&&e.includes(n))throw new Error(`${Et} object contains circular references`);return new t(n,e)}},q={null:new m(l.null,null),undefined:new m(l.undefined,void 0),true:new m(l.true,!0),false:new m(l.false,!1),emptyArray:new m(l.array,0),emptyMap:new m(l.map,0)},K={number(t,e,n,r){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new m(l.float,t):t>=0?new m(l.uint,t):new m(l.negint,t)},bigint(t,e,n,r){return t>=BigInt(0)?new m(l.uint,t):new m(l.negint,t)},Uint8Array(t,e,n,r){return new m(l.bytes,t)},string(t,e,n,r){return new m(l.string,t)},boolean(t,e,n,r){return t?q.true:q.false},null(t,e,n,r){return q.null},undefined(t,e,n,r){return q.undefined},ArrayBuffer(t,e,n,r){return new m(l.bytes,new Uint8Array(t))},DataView(t,e,n,r){return new m(l.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,n,r){if(!t.length)return n.addBreakTokens===!0?[q.emptyArray,new m(l.break)]:q.emptyArray;r=Je.createCheck(r,t);let i=[],o=0;for(let s of t)i[o++]=Xe(s,n,r);return n.addBreakTokens?[new m(l.array,t.length),i,new m(l.break)]:[new m(l.array,t.length),i]},Object(t,e,n,r){let i=e!=="Object",o=i?t.keys():Object.keys(t),s=i?t.size:o.length;if(!s)return n.addBreakTokens===!0?[q.emptyMap,new m(l.break)]:q.emptyMap;r=Je.createCheck(r,t);let a=[],c=0;for(let u of o)a[c++]=[Xe(u,n,r),Xe(i?t.get(u):t[u],n,r)];return Li(a,n),n.addBreakTokens?[new m(l.map,s),a,new m(l.break)]:[new m(l.map,s),a]}};K.Map=K.Object;K.Buffer=K.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))K[`${t}Array`]=K.DataView;function Xe(t,e={},n){let r=dn(t),i=e&&e.typeEncoders&&e.typeEncoders[r]||K[r];if(typeof i=="function"){let s=i(t,r,e,n);if(s!=null)return s}let o=K[r];if(!o)throw new Error(`${Et} unsupported type: ${r}`);return o(t,r,e,n)}function Li(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Hi(t,e){if(t[0]instanceof m&&e[0]instanceof m){let n=t[0],r=e[0];return n._keyBytes||(n._keyBytes=pr(n.value)),r._keyBytes||(r._keyBytes=pr(r.value)),Ve(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function pr(t){return Mi(t,Di,mr)}function hr(t,e,n,r){if(Array.isArray(e))for(let i of e)hr(t,i,n,r);else n[e.type.major](t,e,r)}function Mi(t,e,n){let r=Xe(t,n);if(!Array.isArray(r)&&n.quickEncodeToken){let i=n.quickEncodeToken(r);if(i)return i;let o=e[r.type.major];if(o.encodedSize){let s=o.encodedSize(r,n),a=new be(s);if(o(a,r,n),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${r} was wrong`);return St(a.chunks[0])}}return Ut.reset(),hr(Ut,r,e,n),Ut.toBytes(!0)}var Ss=Symbol.for("DONE"),Es=Symbol.for("BREAK");xt.hmacSha256Sync=(t,...e)=>wt(ae,t,xt.concatBytes(...e));var Gi=32;function Qe(t){if(t.length===0)return new Uint8Array(Gi);let e=t.length,n=e*4,r=t.reduce((c,u)=>c+u.length,0),i=4+n+r,o=new Uint8Array(i),s=new DataView(o.buffer,o.byteOffset,o.byteLength);s.setUint32(0,e,!0);let a=4;for(let c of t)s.setUint32(a,c.length,!0),a+=4;for(let c of t)o.set(c,a),a+=c.length;return ae(o)}var Ct={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,entityRef:4,f32:4,vec2:8,vec3:12,quat:16,enum:1},Ee={bool:1,uint8:1,int8:1,uint16:2,int16:2,uint32:4,int32:4,f32:4,flags8:1,flags16:2,flags32:4,vec2:8,vec3:12,quat:16};var yr=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","f32"]);function _t(t){let e=t.match(/^(\\w+)\\[(\\d+)\\]$/);if(!e||!e[1]||!e[2])return null;let n=e[1],r=parseInt(e[2],10);if(!yr.has(n))throw new Error(`Invalid array element type \'${n}\': arrays only support primitive scalar types (bool, uint8, int8, uint16, int16, uint32, int32, f32)`);return{elementType:n,length:r}}function gr(t){let e=_t(t);if(e){let r=Ee[e.elementType];if(r===void 0)throw new Error(`Unknown element type: ${e.elementType}`);return r*e.length}let n=Ee[t];if(n===void 0)throw new Error(`Unknown type: ${t}`);return n}function Zi(t){let e=[],n=[],r=new Map,i=new Map,o=0;for(let s of t.controls){let a=gr(s.type),c=_t(s.type),u={name:s.name,type:s.type,size:a,offset:0,options:s.options};c&&(u.arrayLength=c.length,u.arrayElementType=c.elementType);let f={name:s.name,index:o++,field:u,hint:s.hint,retain:s.retain==="always"?"always":"tick"};e.push(f),r.set(s.name,f)}for(let s of t.commands){let a=[],c=0;for(let f of s.args){let p=gr(f.type),g=_t(f.type),S={name:f.name,type:f.type,size:p,offset:c};g&&(S.arrayLength=g.length,S.arrayElementType=g.elementType),a.push(S),c+=p}let u={name:s.name,index:o++,args:a,totalSize:c};n.push(u),i.set(s.name,u)}return{controls:e,commands:n,controlByName:r,commandByName:i}}function It(t,e,n,r){switch(n){case"bool":t.setUint8(e,r?1:0);break;case"uint8":case"flags8":t.setUint8(e,r);break;case"int8":t.setInt8(e,r);break;case"uint16":case"flags16":t.setUint16(e,r,!0);break;case"int16":t.setInt16(e,r,!0);break;case"uint32":case"flags32":t.setUint32(e,r,!0);break;case"int32":t.setInt32(e,r,!0);break;case"f32":t.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function Bt(t,e,n){switch(n){case"bool":return t.getUint8(e)!==0;case"uint8":case"flags8":return t.getUint8(e);case"int8":return t.getInt8(e);case"uint16":case"flags16":return t.getUint16(e,!0);case"int16":return t.getInt16(e,!0);case"uint32":case"flags32":return t.getUint32(e,!0);case"int32":return t.getInt32(e,!0);case"f32":return t.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}var et=class t{constructor(e){y(this,"schema");y(this,"fields",new Map);y(this,"commandList",[]);this.schema=e}setControl(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);let i=new Uint8Array(r.field.size),o=new DataView(i.buffer);this.encodeValue(o,0,r.field,n),this.fields.set(r.index,i)}setFlags(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(!r.field.options)throw new Error(`Control ${e} is not a flags type`);let i=0;for(let a=0;a<r.field.options.length;a++){let c=r.field.options[a];n[c]&&(i|=1<<a)}let o=new Uint8Array(r.field.size),s=new DataView(o.buffer);It(s,0,r.field.type,i),this.fields.set(r.index,o)}setVec2(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let i=new Uint8Array(8),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),this.fields.set(r.index,i)}setVec3(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let i=new Uint8Array(12),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),this.fields.set(r.index,i)}setQuat(e,n){let r=this.schema.controlByName.get(e);if(!r)throw new Error(`Unknown control: ${e}`);if(r.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let i=new Uint8Array(16),o=new DataView(i.buffer);o.setFloat32(0,n[0],!0),o.setFloat32(4,n[1],!0),o.setFloat32(8,n[2],!0),o.setFloat32(12,n[3],!0),this.fields.set(r.index,i)}getControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);let r=this.fields.get(n.index);if(!r)return this.getDefaultValue(n.field);let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return this.decodeValue(i,0,n.field)}getFlags(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(!n.field.options)throw new Error(`Control ${e} is not a flags type`);let r=this.fields.get(n.index),i=0;if(r){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);i=Bt(s,0,n.field.type)}let o={};for(let s=0;s<n.field.options.length;s++)o[n.field.options[s]]=(i&1<<s)!==0;return o}getVec2(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec2")throw new Error(`Control ${e} is not a vec2`);let r=this.fields.get(n.index);if(!r)return[0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0)]}getVec3(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="vec3")throw new Error(`Control ${e} is not a vec3`);let r=this.fields.get(n.index);if(!r)return[0,0,0];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0)]}getQuat(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);if(n.field.type!=="quat")throw new Error(`Control ${e} is not a quat`);let r=this.fields.get(n.index);if(!r)return[0,0,0,1];let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return[i.getFloat32(0,!0),i.getFloat32(4,!0),i.getFloat32(8,!0),i.getFloat32(12,!0)]}hasControl(e){let n=this.schema.controlByName.get(e);if(!n)throw new Error(`Unknown control: ${e}`);return this.fields.has(n.index)}addCommand(e,n){let r=this.schema.commandByName.get(e);if(!r)throw new Error(`Unknown command: ${e}`);let i=new Uint8Array(r.totalSize),o=new DataView(i.buffer);for(let s of r.args){let a=n[s.name];if(a===void 0)throw new Error(`Missing required argument: ${s.name}`);this.encodeValue(o,s.offset,s,a)}this.commandList.push({index:r.index,data:i})}getCommands(){let e=[];for(let{index:n,data:r}of this.commandList){let i=this.schema.commands.find(a=>a.index===n);if(!i)continue;let o=new DataView(r.buffer,r.byteOffset,r.byteLength),s={name:i.name};for(let a of i.args)s[a.name]=this.decodeValue(o,a.offset,a);e.push(s)}return e}encode(){let e=[];for(let[o,s]of this.fields){let a=new Uint8Array(2+s.length);a[0]=o,a[1]=s.length,a.set(s,2),e.push(a)}for(let o of this.commandList){let s=new Uint8Array(2+o.data.length);s[0]=o.index,s[1]=o.data.length,s.set(o.data,2),e.push(s)}let n=e.reduce((o,s)=>o+s.length,0),r=new Uint8Array(n),i=0;for(let o of e)r.set(o,i),i+=o.length;return r}static decode(e,n){let r=new t(e),i=0;for(;i<n.length;){if(i+2>n.length)throw new Error("Truncated TLV field header");let o=n[i],s=n[i+1];if(i+2+s>n.length)throw new Error(`Truncated TLV field data at index ${o}`);let a=n.subarray(i+2,i+2+s);e.controls.find(u=>u.index===o)?r.fields.set(o,new Uint8Array(a)):e.commands.find(f=>f.index===o)&&r.commandList.push({index:o,data:new Uint8Array(a)}),i+=2+s}return r}clear(){this.fields.clear(),this.commandList.length=0}encodeValue(e,n,r,i){if(r.type==="vec2"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0)}else if(r.type==="vec3"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0)}else if(r.type==="quat"){let o=i;e.setFloat32(n,o[0],!0),e.setFloat32(n+4,o[1],!0),e.setFloat32(n+8,o[2],!0),e.setFloat32(n+12,o[3],!0)}else if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let o=i,s=Ee[r.arrayElementType];for(let a=0;a<Math.min(o.length,r.arrayLength);a++)It(e,n+a*s,r.arrayElementType,o[a])}else It(e,n,r.type,i)}decodeValue(e,n,r){if(r.type==="vec2")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0)];if(r.type==="vec3")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0)];if(r.type==="quat")return[e.getFloat32(n,!0),e.getFloat32(n+4,!0),e.getFloat32(n+8,!0),e.getFloat32(n+12,!0)];if(r.arrayLength!==void 0&&r.arrayElementType!==void 0){let i=[],o=Ee[r.arrayElementType];for(let s=0;s<r.arrayLength;s++)i.push(Bt(e,n+s*o,r.arrayElementType));return i}else return Bt(e,n,r.type)}getDefaultValue(e){return e.type==="vec2"?[0,0]:e.type==="vec3"?[0,0,0]:e.type==="quat"?[0,0,0,1]:e.arrayLength!==void 0?new Array(e.arrayLength).fill(0):e.type==="bool"?!1:0}};function br(t){let e=Zi(t);return{create(){return new et(e)},decode(n){return et.decode(e,n)},get schema(){return e}}}function xr(t,e){return((e&65535)<<16|t&65535)>>>0}function ke(t){return t&65535}function Yi(t){return t>>>16&65535}function pe(t){return t.subarray(8,40)}function Pt(t,e){if(e.length!==32)throw new Error(`stateId must be ${32} bytes, got ${e.length}`);t.set(e,8)}function wr(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint32(40,e,!0)}function rt(t,e,n){let r=new Uint8Array(68);return r.set(t,0),new DataView(r.buffer).setUint32(32,e,!0),r.set(n,36),ae(r)}function Sr(t,e,n){return rt(t,e,Qe(n))}function $t(t){return ae(t)}function Er(t,e,n){let r=new ArrayBuffer(t.totalSize),i=new Uint8Array(r),o=new DataView(r);if(o.setUint32(0,1297367376,!0),o.setUint16(4,0,!0),i[6]=n??0,i[7]=0,e){let a=$t(e);i.set(a,8)}let s=t.freeStackOffset;o.setUint16(s,t.maxEntities,!0);for(let a=0;a<t.maxEntities;a++){let c=t.freeStackOffset+2+a*2;o.setUint16(c,a,!0)}return i}function kr(t,e){return t.entityTableOffset+e*t.entityRecordSize}function Ot(t,e,n){let r=kr(t,n);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(r,!0)}function Xi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(4,!0)}function Ji(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(4,e,!0)}function Qi(t,e){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t.freeStackOffset,!0)}function eo(t,e,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t.freeStackOffset,n,!0)}function to(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Qi(t,e);if(r===0)throw new Error(`No free entity slots available (max: ${t.maxEntities})`);let i=t.freeStackOffset+2+(r-1)*2,o=n.getUint16(i,!0);return eo(t,e,r-1),o}function Tr(t,e){let n=to(t,e),r=Ot(t,e,n);return Ji(e,Xi(e)+1),xr(n,r)}function it(t,e,n){if(n===4294967295)return!1;let r=ke(n);if(r>=t.maxEntities)return!1;let i=Yi(n);return Ot(t,e,r)===i}function Ft(t,e,n){if(n<0)throw new Error("Singleton components do not have component bitmask entries");let r=kr(t,e)+2,i=Math.floor(n/8),o=n%8;return{byteOffset:r+i,bitIndex:o}}function Ar(t,e,n,r){if(!it(t,e,n))return!1;let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and is always present`);let o=ke(n),{byteOffset:s,bitIndex:a}=Ft(t,o,i.index);return(e[s]&1<<a)!==0}function vr(t,e,n,r){if(!it(t,e,n)){let c=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${c} is not alive`)}let i=t.componentByName.get(r);if(!i)throw new Error(`Unknown component: \'${r}\'`);if(i.isSingleton)throw new Error(`Component \'${r}\' is a singleton and cannot be added to entities`);let o=ke(n),{byteOffset:s,bitIndex:a}=Ft(t,o,i.index);e[s]=(e[s]??0)|1<<a}function Ur(t,e,n,r){let i=ke(e);return n.storageOffset+i*n.size+r.offset}function no(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":return(t[e]??0)!==0;case"uint8":return t[e]??0;case"int8":return r.getInt8(e);case"uint16":return r.getUint16(e,!0);case"int16":return r.getInt16(e,!0);case"uint32":return r.getUint32(e,!0);case"int32":return r.getInt32(e,!0);case"entityRef":return r.getUint32(e,!0);case"f32":return r.getFloat32(e,!0);default:throw new Error(`Cannot read primitive type: ${n}`)}}function Cr(t,e,n,r){let i=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(n){case"bool":t[e]=r?1:0;break;case"uint8":t[e]=r&255;break;case"int8":i.setInt8(e,r);break;case"uint16":i.setUint16(e,r,!0);break;case"int16":i.setInt16(e,r,!0);break;case"uint32":i.setUint32(e,r,!0);break;case"int32":i.setInt32(e,r,!0);break;case"entityRef":i.setUint32(e,r,!0);break;case"f32":i.setFloat32(e,r,!0);break;default:throw new Error(`Cannot write primitive type: ${n}`)}}function ro(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0)}function io(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0)}function oo(t,e,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);r.setFloat32(e,n[0],!0),r.setFloat32(e+4,n[1],!0),r.setFloat32(e+8,n[2],!0),r.setFloat32(e+12,n[3],!0)}function Ir(t,e,n,r,i,o){if(!it(t,e,n))return;let s=t.componentByName.get(r);if(!s)throw new Error(`Unknown component: \'${r}\'`);if(s.isSingleton)throw new Error(`Component \'${r}\' is a singleton; use singleton accessors instead`);if(!nt(t,e,n,s))return;let a=s.fields.find(f=>f.name===i);if(!a)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let c=Ur(t,n,s,a),u=a.type;if(a.arrayLength!==void 0&&a.arrayElementType!==void 0){if(o===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(o<0||o>=a.arrayLength)throw new Error(`Array index ${o} out of bounds for ${r}.${i} (length: ${a.arrayLength})`);let f=Ct[a.arrayElementType];if(f===void 0)throw new Error(`Unknown array element type: ${a.arrayElementType}`);c+=o*f,u=a.arrayElementType}return no(e,c,u)}function w(t,e,n,r,i,o,s){if(!it(t,e,n)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} is not alive`)}let a=t.componentByName.get(r);if(!a)throw new Error(`Unknown component: \'${r}\'`);if(!nt(t,e,n,a)){let p=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${p} does not have component \'${r}\'`)}let c=a.fields.find(p=>p.name===i);if(!c)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let u=Ur(t,n,a,c),f=c.type;if(c.arrayLength!==void 0&&c.arrayElementType!==void 0){if(s===void 0)throw new Error(`Field \'${r}.${i}\' is an array, index required`);if(s<0||s>=c.arrayLength)throw new Error(`Array index ${s} out of bounds for ${r}.${i} (length: ${c.arrayLength})`);let p=Ct[c.arrayElementType];if(p===void 0)throw new Error(`Unknown array element type: ${c.arrayElementType}`);u+=s*p,f=c.arrayElementType}Cr(e,u,f,o)}function nt(t,e,n,r){if(r.isSingleton)throw new Error(`Component \'${r.name}\' is a singleton and cannot be queried per entity`);let i=ke(n),{byteOffset:o,bitIndex:s}=Ft(t,i,r.index);return(e[o]&1<<s)!==0}function Br(t,e,n,r){if(n.length===0)throw new Error("Query must include at least one component");let i=[];for(let a of n){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);i.push(c)}let o=[];if(r)for(let a of r){let c=t.componentByName.get(a);if(!c)throw new Error(`Unknown component: \'${a}\'`);if(c.isSingleton)throw new Error(`Singleton component \'${a}\' cannot be used in queries`);o.push(c)}function*s(){for(let a=0;a<t.maxEntities;a++){let c=Ot(t,e,a),u=xr(a,c),f=!0;for(let p of i)if(!nt(t,e,u,p)){f=!1;break}if(f){for(let p of o)if(nt(t,e,u,p)){f=!1;break}f&&(yield u)}}}return s()}function _r(t,e){if(!t.events||!t.eventByName)throw new Error("Schema has no events");let n=t.eventByName.get(e);if(!n)throw new Error(`Unknown event: \'${e}\'`);return n}function Pr(t,e,n){let r=_r(t,n);new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(r.storageOffset,0,!0)}function $r(t,e,n,r){let i=_r(t,n),o=new DataView(e.buffer,e.byteOffset,e.byteLength),s=o.getUint16(i.storageOffset,!0);if(s>=i.maxEvents)return!1;let a=i.storageOffset+2+s*i.recordSize;for(let c of i.fields){let u=r[c.name];if(u===void 0)throw new Error(`Missing required field \'${c.name}\' for event \'${n}\'`);let f=a+c.offset;c.type==="vec2"?ro(e,f,u):c.type==="vec3"?io(e,f,u):c.type==="quat"?oo(e,f,u):Cr(e,f,c.type,u)}return o.setUint16(i.storageOffset,s+1,!0),!0}function ot(t){if(t.length!==32)throw new Error(`stateId must be ${32} bytes, got ${t.length}`);return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var st=class{constructor(e={}){y(this,"cache");y(this,"maxSize");this.cache=new Map,this.maxSize=e.maxSize??100}store(e){let n=pe(e),r=ot(n);if(this.cache.size>=this.maxSize&&!this.cache.has(r)){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}this.cache.set(r,e.slice())}getByStateId(e){let n=ot(e),r=this.cache.get(n);return r?r.slice():void 0}getCached(e,n,r){let i=pe(e),o=rt(i,n,r);return this.getByStateId(o)}has(e){let n=ot(e);return this.cache.has(n)}hasCached(e,n,r){let i=pe(e),o=rt(i,n,r);return this.has(o)}delete(e){let n=ot(e);return this.cache.delete(n)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}};var Te=65536,at=class{constructor(e){y(this,"memory",null);y(this,"plugins",[]);y(this,"options");y(this,"stateSize",null);y(this,"statePtr",null);y(this,"heapPos",0);y(this,"arenaResetMark",0);y(this,"inputCodec",null);y(this,"playerEntities",new Map);y(this,"hostAlloc",(e,n)=>{let r=this.memory;if(!r)throw new Error("Memory not initialized for host_alloc");let i=this.heapPos+n-1&~(n-1),o=i+e,s=r.buffer.byteLength;if(o>s){let c=Math.ceil((o-s)/Te);if(this.options.debug){let u=(s+c*Te)/1048576;console.warn(`[mt] WASM memory grew to ${u.toFixed(1)}MB`)}r.grow(c)}return new Uint8Array(r.buffer).fill(0,i,o),this.heapPos=o,i});this.options=e}markArenaReset(){this.arenaResetMark=this.heapPos}resetArena(){this.heapPos=this.arenaResetMark}async init(){if(this.stateSize=this.options.stateSchema.totalSize,!this.stateSize)throw new Error("State schema total size is required");this.options.inputSchema&&(this.inputCodec=br(this.options.inputSchema));let e=4*1024*1024,n=this.options.plugins??(this.options.moduleBytes?[{name:"main",wasmBytes:this.options.moduleBytes,reservedBytes:e}]:[]);for(let c of n)if(typeof c.reservedBytes!="number"||c.reservedBytes<=0)throw new Error(`Plugin "${c.name}" requires reservedBytes > 0`);let r=n.reduce((c,u)=>{let f=Math.ceil(u.reservedBytes/Te)*Te;return c+f},0),i=1024*1024*5,o=this.stateSize+i+r,s=Math.ceil(o/Te);this.memory=new WebAssembly.Memory({initial:s}),this.heapPos=r;let a={env:{memory:this.memory,host_alloc:this.hostAlloc,abort:()=>{throw new Error("WASM abort called")}}};for(let c of n){let u=c.wasmBytes.slice().buffer,f=await WebAssembly.compile(u),p=await WebAssembly.instantiate(f,a);if(typeof p.exports.apply!="function")throw new Error(`Plugin "${c.name}" missing required apply() export`);this.plugins.push({name:c.name,instance:p,exports:p.exports})}return this.statePtr=this.hostAlloc(this.stateSize,8),this.markArenaReset(),this}findPlayerEntity(e,n){let r=this.options.stateSchema,i=this.playerEntities.get(n);if(i!==void 0){if(Ar(r,e,i,"Player"))return i;this.playerEntities.delete(n)}for(let o of Br(r,e,["Player"]))if(Ir(r,e,o,"Player","index")===n)return this.playerEntities.set(n,o),o}spawnPlayerEntity(e,n){let r=this.options.stateSchema,i=Tr(r,e);return vr(r,e,i,"Player"),w(r,e,i,"Player","index",n),this.playerEntities.set(n,i),i}findOrSpawnPlayerEntity(e,n){let r=this.findPlayerEntity(e,n);return r!==void 0?r:this.spawnPlayerEntity(e,n)}resetPlayerControls(e,n){let r=this.options.stateSchema;if(this.inputCodec)for(let i of this.inputCodec.schema.controls){if(i.retain==="always")continue;let o=i.field.type,s=i.name;if(o==="vec2")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0);else if(o==="vec3")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0);else if(o==="quat")w(r,e,n,"Player",`${s}_x`,0),w(r,e,n,"Player",`${s}_y`,0),w(r,e,n,"Player",`${s}_z`,0),w(r,e,n,"Player",`${s}_w`,1);else if(o.startsWith("flags"))w(r,e,n,"Player",s,0);else if(o.includes("[")){let a=o.match(/\\[(\\d+)\\]/);if(a?.[1]){let c=parseInt(a[1],10);for(let u=0;u<c;u++)w(r,e,n,"Player",s,0,u)}}else w(r,e,n,"Player",s,o==="bool"?!1:0)}}writeControlsToPlayer(e,n,r){let i=this.options.stateSchema,o=this.options.inputSchema;if(o)for(let s of o.controls){if(!r.hasControl(s.name))continue;let a=s.type,c=s.name;if(a==="vec2"){let[u,f]=r.getVec2(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f)}else if(a==="vec3"){let[u,f,p]=r.getVec3(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p)}else if(a==="quat"){let[u,f,p,g]=r.getQuat(c);w(i,e,n,"Player",`${c}_x`,u),w(i,e,n,"Player",`${c}_y`,f),w(i,e,n,"Player",`${c}_z`,p),w(i,e,n,"Player",`${c}_w`,g)}else if(a.startsWith("flags")){let u=r.getControl(c);w(i,e,n,"Player",c,u)}else if(a.includes("[")){let u=r.getControl(c);for(let f=0;f<u.length;f++)w(i,e,n,"Player",c,u[f],f)}else{let u=r.getControl(c);w(i,e,n,"Player",c,u)}}}pushCommands(e,n,r){let i=this.options.stateSchema,o=r.getCommands();for(let s of o){let a=s.name.charAt(0).toUpperCase()+s.name.slice(1)+"Command",c={player_index:n};for(let[u,f]of Object.entries(s))u!=="name"&&(Array.isArray(f)?f.length===2?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1]):f.length===3?(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2]):f.length===4&&(c[`${u}_x`]=f[0],c[`${u}_y`]=f[1],c[`${u}_z`]=f[2],c[`${u}_w`]=f[3]):c[u]=f);$r(i,e,a,c)}}clearCommandEvents(e){let n=this.options.stateSchema,r=this.options.inputSchema;if(!(!r||!n.events))for(let i of r.commands){let o=i.name.charAt(0).toUpperCase()+i.name.slice(1)+"Command";n.eventByName?.has(o)&&Pr(n,e,o)}}decodePayloadsToState(e,n){if(this.inputCodec)for(let r=0;r<n.length;r++){let i=n[r];if(i===void 0)continue;let o=this.findOrSpawnPlayerEntity(e,r);if(this.resetPlayerControls(e,o),i.length===0)continue;let s=this.inputCodec.decode(i);this.writeControlsToPlayer(e,o,s),this.pushCommands(e,r,s)}}transition(e,n){let r=this.stateSize;if(r===null||e.length!==r)throw new Error(`State size mismatch: expected ${this.stateSize}, got ${e.length}`);if(this.plugins.length===0||n.length===0)return e.slice();let i=this.memory;if(!i)throw new Error("WASM memory not initialized");let o=this.statePtr;if(o===null||o<0)throw new Error("State pointer not initialized");let s=new Uint8Array(i.buffer);s.set(e,o);for(let a of n){this.resetArena();let c=new Uint8Array(i.buffer,o,r);wr(c,a.tick),this.clearCommandEvents(c),this.decodePayloadsToState(c,a.payloads);for(let u of this.plugins)u.exports.apply(o),s=new Uint8Array(i.buffer)}return s.slice(o,o+r)}close(){}getStateSize(){let e=this.stateSize;if(e===null||e<0)throw new Error("State size not initialized");return e}};var me=class{constructor(e=1e3,n=1024){y(this,"buffer");y(this,"windowMs");y(this,"head",0);y(this,"tail",0);y(this,"size",0);this.windowMs=e,this.buffer=new Float64Array(n)}inc(){let e=performance.now();this.buffer[this.head]=e,this.head=(this.head+1)%this.buffer.length,this.size<this.buffer.length?this.size++:this.tail=(this.tail+1)%this.buffer.length}count(e=performance.now()){let n=e-this.windowMs;for(;this.size>0&&!(this.buffer[this.tail]>=n);)this.tail=(this.tail+1)%this.buffer.length,this.size--;return this.size}rate(e=performance.now()){return this.count(e)*(1e3/this.windowMs)}};function so(t){return("moduleBytes"in t||"plugins"in t)&&"stateSchema"in t}function ao(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var ct=class{constructor(e){y(this,"debug");y(this,"stateSchema");y(this,"inputs",null);y(this,"cache");y(this,"executor",null);y(this,"genesisStateId");y(this,"options");y(this,"ticking",!1);y(this,"tickGraceMs");y(this,"tickLag");y(this,"maxBatchSize");y(this,"currentState");y(this,"currentTick");y(this,"currentNodeId");y(this,"prevOnStateUpdateState",null);y(this,"onStateUpdate");y(this,"syncCheckpoint");y(this,"stateHistory",[]);y(this,"maxHistory",64);y(this,"stats");y(this,"loop",()=>{this._loop().catch(co)});y(this,"_loop",async()=>{if(this.ticking)try{let e=await this.tick();if(this.onStateUpdate&&this.currentState!==this.prevOnStateUpdateState&&(this.onStateUpdate(this.currentState),this.prevOnStateUpdateState=this.currentState,this.stats.updates.inc()),e.rolledBack&&this.stats.rollbacks.inc(),e.ticksComputed>0)for(let n=0;n<e.ticksComputed;n++)this.stats.executions.inc()}catch(e){console.error("Error in tick loop:",e)}finally{setTimeout(this.loop,this.tickGraceMs)}});e.log&&(this.inputs=e.log),this.debug=e.debug??!1,this.options=e,this.stateSchema=e.stateSchema,this.cache=e.cache??new st,this.genesisStateId=$t(e.genesisHash),this.tickGraceMs=e.tickGraceMs??10,this.tickLag=e.tickLag??1,this.maxBatchSize=e.maxBatchSize??200,this.stats={rollbacks:new me,executions:new me,updates:new me},this.currentState=Er(this.stateSchema,e.genesisHash,e.tickRate),this.currentNodeId=null,this.syncCheckpoint=null,this.currentTick=null,this.cache.store(this.currentState)}setLog(e){this.inputs=lt(e)}setOnStateUpdate(e){e===null&&(this.prevOnStateUpdateState=null),this.onStateUpdate=e}async init(){if(!this.inputs)throw new Error("Rollback.init() called before log was configured. Call setLog() first or pass log in options.");let e=this.options.executor;if(so(e)){let r=new at(e);await r.init(),this.executor=r}else this.executor=e;if((await this.tick(0)).ticksComputed===0||this.currentTick===null)throw new Error("Failed to record genesis snapshot");return this.options.disableTicking||(this.ticking=!0,this.loop()),this.getState()}async tick(e){if(!this.inputs)throw new Error("Rollback.tick() called before log was configured. Call setLog() and init() first.");let n=await this.inputs.getTicksAfter(this.currentNodeId,{limit:this.maxBatchSize,lag:this.tickLag});if(e&&(n=n.filter(s=>s.tick<=e)),n.length===0)return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:!1,ticksComputed:0};let r=!1;this.currentTick!==null&&n[0].tick<this.currentTick&&(r=!0,this.rollbackTo(n[0]));let i=n.filter(s=>this.currentTick===null||s.tick>this.currentTick);if(i.length===0)return this.currentNodeId=n[n.length-1].id,{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId,rolledBack:r,ticksComputed:0};let o=this.processTicks(i);return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:r,ticksComputed:o}}async getStats(){return{rollbacks:this.stats.rollbacks.rate(),executions:this.stats.executions.rate(),updates:this.stats.updates.rate()}}processTicks(e){if(!this.executor)throw new Error("Executor not initialized");let n=0,r=0;for(let a=0;a<e.length;a++){let c=e[a],u=Qe(c.payloads),f=this.cache.getCached(this.currentState,c.tick,u);if(f)this.currentState=f,this.currentTick=c.tick,this.currentNodeId=c.id,r=a+1,c.sync&&this.updateSyncCheckpoint(c);else break}let i=e.slice(r);if(i.length===0)return 0;let o=ao(i,a=>a.sync);if(o>=0){let a=i.slice(0,o+1),c=this.executor.transition(this.currentState,a),u=this.computeBatchStateId(this.currentState,a);Pt(c,u);let f=a[a.length-1];this.currentState=c,this.currentTick=f.tick,this.currentNodeId=f.id,n+=a.length,this.cache.store(c),this.recordStateSnapshot(this.currentTick,this.currentNodeId,u),this.updateSyncCheckpoint(f)}let s=o>=0?i.slice(o+1):i;if(s.length>0){let a=this.executor.transition(this.currentState,s),c=this.computeBatchStateId(this.currentState,s);Pt(a,c);let u=s[s.length-1];this.currentState=a,this.currentTick=u.tick,this.currentNodeId=u.id,n+=s.length,this.cache.store(a),this.recordStateSnapshot(this.currentTick,this.currentNodeId,c)}return n}computeBatchStateId(e,n){let r=pe(e);for(let i of n)r=Sr(r,i.tick,i.payloads);return r}getState(){return this.currentState.slice()}getTick(){return this.currentTick}reset(){this.currentTick=0,this.currentNodeId=null,this.syncCheckpoint=null}close(){this.ticking=!1,this.setOnStateUpdate(null),this.executor&&(this.executor.close(),this.executor=null)}rollbackTo(e){if(this.syncCheckpoint&&this.syncCheckpoint.tick>=e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}if(this.syncCheckpoint&&this.syncCheckpoint.tick<e.tick){this.currentState=this.syncCheckpoint.state.slice(),this.currentTick=this.syncCheckpoint.tick,this.currentNodeId=this.syncCheckpoint.nodeId;return}let n=e.tick-1,r=this.findSnapshotAtOrBefore(n);if(r){let o=this.cache.getByStateId(r.stateId);if(o){this.currentState=o,this.currentTick=r.tick,this.currentNodeId=r.nodeId;return}}let i=this.cache.getByStateId(this.genesisStateId);if(i){this.currentState=i,this.currentTick=0,this.currentNodeId=null;return}}updateSyncCheckpoint(e){this.syncCheckpoint={state:this.currentState.slice(),tick:e.tick,nodeId:e.id}}recordStateSnapshot(e,n,r){this.stateHistory.push({tick:e,nodeId:n,stateId:r.slice()}),this.stateHistory.length>this.maxHistory&&this.stateHistory.shift()}findSnapshotAtOrBefore(e){for(let n=this.stateHistory.length-1;n>=0;n--){let r=this.stateHistory[n];if(r.tick<=e)return r}return null}};function co(t){console.warn("rollback unexpected:",t)}Be(ct);var qa=null;globalThis.onerror=t=>(console.error("\\u{1F534} FATAL ROLLBACK WORKER ERROR (Uncaught Exception):",t),!0);export{qa as default};\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n\n@noble/secp256k1/index.js:\n (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)\n\n@noble/hashes/esm/utils.js:\n (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)\n*/\n';
6577
- function Worker2() {
6578
- const blob = new Blob([workerCode2], { type: "text/javascript" });
6579
- const url = URL.createObjectURL(blob);
6580
- const worker = new globalThis.Worker(url, { type: "module" });
6581
- URL.revokeObjectURL(url);
6582
- return worker;
6583
- }
6584
-
6585
7155
  // src/peer-mesh.ts
6586
7156
  var ICE_SERVERS = [
6587
7157
  { urls: "stun:stun.l.google.com:19302" },
@@ -6686,7 +7256,7 @@ var PeerMesh = class {
6686
7256
  try {
6687
7257
  const data = JSON.parse(event.data);
6688
7258
  console.log("[PeerMesh]", `SSE: received offer from ${data.from.slice(0, 8)}`);
6689
- this.handleOffer(data.from, { sdp: data.sdp, type: data.type }).catch(warnUnexpected2);
7259
+ this.handleOffer(data.from, { sdp: data.sdp, type: data.type }).catch(warnUnexpected3);
6690
7260
  } catch (err2) {
6691
7261
  console.log("[PeerMesh]", "SSE: failed to handle offer", err2);
6692
7262
  }
@@ -6695,7 +7265,7 @@ var PeerMesh = class {
6695
7265
  try {
6696
7266
  const data = JSON.parse(event.data);
6697
7267
  console.log("[PeerMesh]", `SSE: received answer from ${data.from.slice(0, 8)}`);
6698
- this.handleAnswer(data.from, { sdp: data.sdp, type: data.type }).catch(warnUnexpected2);
7268
+ this.handleAnswer(data.from, { sdp: data.sdp, type: data.type }).catch(warnUnexpected3);
6699
7269
  } catch (err2) {
6700
7270
  console.log("[PeerMesh]", "SSE: failed to handle answer", err2);
6701
7271
  }
@@ -6731,7 +7301,7 @@ var PeerMesh = class {
6731
7301
  }
6732
7302
  if (this.myPubKeyHex < peerPubKey) {
6733
7303
  console.log("[PeerMesh]", `I should offer to ${peerPubKey.slice(0, 8)}`);
6734
- this.createOffer(peerPubKey).catch(warnUnexpected2);
7304
+ this.createOffer(peerPubKey).catch(warnUnexpected3);
6735
7305
  }
6736
7306
  }
6737
7307
  }
@@ -6957,7 +7527,7 @@ var PeerMesh = class {
6957
7527
  });
6958
7528
  }
6959
7529
  };
6960
- function warnUnexpected2(err2) {
7530
+ function warnUnexpected3(err2) {
6961
7531
  console.warn("PeerMesh:", err2);
6962
7532
  }
6963
7533
 
@@ -6970,10 +7540,8 @@ var Session = class {
6970
7540
  initialized = false;
6971
7541
  playerKey;
6972
7542
  compiledStateSchema;
6973
- channelWorkerUrl = null;
6974
7543
  rollbackWorkerUrl = null;
6975
7544
  rollbackWorker = null;
6976
- channelWorker = null;
6977
7545
  maxTicksPerBatch;
6978
7546
  serverCertHash;
6979
7547
  validatorKeys;
@@ -7036,12 +7604,12 @@ var Session = class {
7036
7604
  async init() {
7037
7605
  if (this.initializing || this.initialized) return;
7038
7606
  this.initializing = true;
7039
- const channel = new MessageChannel();
7040
- const channelPort1 = channel.port1;
7041
- const channelPort2 = channel.port2;
7607
+ const messageChannel = new MessageChannel();
7608
+ const channelPort1 = messageChannel.port1;
7609
+ const channelPort2 = messageChannel.port2;
7042
7610
  const connectionURL = this.config.toConnectionURL();
7043
7611
  const genesisHash = this.config.toGenesisHash();
7044
- this.channel = await this.createChannelWorker({
7612
+ this.channel = new Channel({
7045
7613
  connectionURL,
7046
7614
  serverCertHash: this.serverCertHash,
7047
7615
  privateKey: this.playerKey,
@@ -7051,8 +7619,8 @@ var Session = class {
7051
7619
  connectionTimeoutMs: this.connectionTimeoutMs,
7052
7620
  logSyncTicks: this.logSyncTicks
7053
7621
  });
7054
- await this.channel.expose(transfer(channelPort1, [channelPort1]));
7055
- await this.channel.setOnParticipantJoined(proxy(this.onParticipantJoined));
7622
+ await this.channel.expose(channelPort1);
7623
+ await this.channel.setOnParticipantJoined(this.onParticipantJoined);
7056
7624
  this.rollback = await this.createRollbackWorker({
7057
7625
  stateSchema: this.compiledStateSchema,
7058
7626
  genesisHash,
@@ -7078,10 +7646,10 @@ var Session = class {
7078
7646
  publicKey,
7079
7647
  genesisHash,
7080
7648
  onPeerInput: (input, signerPubKey) => {
7081
- this.channel?.addOptimisticInput(input, signerPubKey).catch(warnUnexpected3);
7649
+ this.channel?.addOptimisticInput(input, signerPubKey).catch(warnUnexpected4);
7082
7650
  }
7083
7651
  });
7084
- this.peerMesh.start().catch(warnUnexpected3);
7652
+ this.peerMesh.start().catch(warnUnexpected4);
7085
7653
  }
7086
7654
  this.initialized = true;
7087
7655
  this.initializing = false;
@@ -7174,22 +7742,10 @@ var Session = class {
7174
7742
  await this.rollback.close();
7175
7743
  this.rollback = null;
7176
7744
  }
7177
- if (this.channelWorker) {
7178
- this.channelWorker.terminate();
7179
- this.channelWorker = null;
7180
- }
7181
7745
  if (this.rollbackWorker) {
7182
7746
  this.rollbackWorker.terminate();
7183
7747
  this.rollbackWorker = null;
7184
7748
  }
7185
- if (this.channelWorkerUrl) {
7186
- try {
7187
- URL.revokeObjectURL(this.channelWorkerUrl);
7188
- } catch {
7189
- console.warn("failed to revoke channel worker url", this.channelWorkerUrl);
7190
- }
7191
- this.channelWorkerUrl = null;
7192
- }
7193
7749
  if (this.rollbackWorkerUrl) {
7194
7750
  try {
7195
7751
  URL.revokeObjectURL(this.rollbackWorkerUrl);
@@ -7201,12 +7757,12 @@ var Session = class {
7201
7757
  this.closed = true;
7202
7758
  }
7203
7759
  _collectStats = () => {
7204
- this.collectStats().catch(warnUnexpected3);
7760
+ this.collectStats().catch(warnUnexpected4);
7205
7761
  };
7206
7762
  collectStats = async () => {
7207
7763
  this.statsTimer = null;
7208
7764
  this.stats = {
7209
- inputs: this.channel ? await this.channel.getStats() : {},
7765
+ inputs: this.channel ? this.channel.getStats() : {},
7210
7766
  simulation: this.rollback ? await this.rollback.getStats() : {},
7211
7767
  renderer: this.renderer.getStats?.() ?? {}
7212
7768
  };
@@ -7217,7 +7773,7 @@ var Session = class {
7217
7773
  };
7218
7774
  // create blob url for rollback worker bytes and load it into a worker
7219
7775
  async createRollbackWorker(options) {
7220
- this.rollbackWorker = new Worker2();
7776
+ this.rollbackWorker = new Worker();
7221
7777
  this.rollbackWorker.onerror = (event) => {
7222
7778
  console.error("\u{1F534} FATAL ROLLBACK WORKER ERROR (Script/Init Failed):", event);
7223
7779
  return true;
@@ -7225,16 +7781,6 @@ var Session = class {
7225
7781
  const Klass = wrap(this.rollbackWorker);
7226
7782
  return await new Klass(options);
7227
7783
  }
7228
- // create blob url for channel worker bytes and load it into a worker
7229
- async createChannelWorker(options) {
7230
- this.channelWorker = new Worker();
7231
- this.channelWorker.onerror = (event) => {
7232
- console.error("\u{1F534} FATAL CHANNEL WORKER ERROR (Script/Init Failed):", event);
7233
- return true;
7234
- };
7235
- const Klass = wrap(this.channelWorker);
7236
- return await new Klass(options);
7237
- }
7238
7784
  };
7239
7785
  async function createSession(options) {
7240
7786
  const session = new Session(options);
@@ -7251,7 +7797,7 @@ function concatPluginWasm(plugins) {
7251
7797
  }
7252
7798
  return result;
7253
7799
  }
7254
- function warnUnexpected3(err2) {
7800
+ function warnUnexpected4(err2) {
7255
7801
  console.warn("unexpected:", err2);
7256
7802
  }
7257
7803
 
@@ -7510,15 +8056,7 @@ var TestSession = class _TestSession {
7510
8056
  };
7511
8057
 
7512
8058
  // src/react/providers/SessionProvider.tsx
7513
- import {
7514
- createContext,
7515
- useContext,
7516
- useEffect,
7517
- useState,
7518
- useRef,
7519
- useMemo,
7520
- useCallback
7521
- } from "react";
8059
+ import { createContext, useContext, useEffect, useState, useRef, useMemo, useCallback } from "react";
7522
8060
  import { useFrame as useFiberFrame } from "@react-three/fiber";
7523
8061
  import { Html } from "@react-three/drei";
7524
8062
  import { createStore } from "zustand";
@@ -7531,11 +8069,7 @@ function createPlayerStore(schema) {
7531
8069
  return createStore((_set, get) => ({
7532
8070
  players: [],
7533
8071
  update: (stateView2, allParticipants, currentPlayerId) => {
7534
- const stateBuffer = new Uint8Array(
7535
- stateView2.buffer,
7536
- stateView2.byteOffset,
7537
- stateView2.byteLength
7538
- );
8072
+ const stateBuffer = new Uint8Array(stateView2.buffer, stateView2.byteOffset, stateView2.byteLength);
7539
8073
  const currentTick = getTick(stateBuffer);
7540
8074
  const incoming = allParticipants.filter((p) => p.joined <= currentTick);
7541
8075
  const current = get().players;
@@ -7548,24 +8082,21 @@ function createPlayerStore(schema) {
7548
8082
  const indexB = getField(schema, stateBuffer, b, "Player", "index");
7549
8083
  return indexA - indexB;
7550
8084
  });
7551
- const players = sortedEntities.reduce(
7552
- (acc, entity, index) => {
7553
- if (index >= incoming.length) {
7554
- return acc;
7555
- }
7556
- const participant = incoming[index];
7557
- if (!participant) {
7558
- return acc;
7559
- }
7560
- acc[index] = {
7561
- ...participant,
7562
- entity,
7563
- isCurrentPlayer: participant.id === currentPlayerId
7564
- };
8085
+ const players = sortedEntities.reduce((acc, entity, index) => {
8086
+ if (index >= incoming.length) {
7565
8087
  return acc;
7566
- },
7567
- []
7568
- );
8088
+ }
8089
+ const participant = incoming[index];
8090
+ if (!participant) {
8091
+ return acc;
8092
+ }
8093
+ acc[index] = {
8094
+ ...participant,
8095
+ entity,
8096
+ isCurrentPlayer: participant.id === currentPlayerId
8097
+ };
8098
+ return acc;
8099
+ }, []);
7569
8100
  _set({ players });
7570
8101
  }
7571
8102
  }));
@@ -7574,15 +8105,10 @@ function stateView(state) {
7574
8105
  return new DataView(state.buffer, state.byteOffset, state.byteLength);
7575
8106
  }
7576
8107
  function SessionProvider({ config, children }) {
7577
- const schema = useMemo(
7578
- () => ensureCompiled(config.schema.state),
7579
- [config.schema.state]
7580
- );
8108
+ const schema = useMemo(() => ensureCompiledStateSchema(config.schema.state), [config.schema.state]);
7581
8109
  const sessionRef = useRef(null);
7582
8110
  const [session, setSession] = useState(null);
7583
- const [participants] = useState(
7584
- () => createPlayerStore(schema)
7585
- );
8111
+ const [participants] = useState(() => createPlayerStore(schema));
7586
8112
  const [isReady, setIsReady] = useState(false);
7587
8113
  const [error, setError] = useState(null);
7588
8114
  const [inputBindings, setInputBindings] = useState(null);
@@ -7656,17 +8182,7 @@ function SessionProvider({ config, children }) {
7656
8182
  // TODO
7657
8183
  currentPlayerId
7658
8184
  } : null,
7659
- [
7660
- isReady,
7661
- error,
7662
- sendInput,
7663
- inputBindings,
7664
- config,
7665
- session,
7666
- participants,
7667
- currentPlayerId,
7668
- schema
7669
- ]
8185
+ [isReady, error, sendInput, inputBindings, config, session, participants, currentPlayerId, schema]
7670
8186
  );
7671
8187
  if (error) {
7672
8188
  return /* @__PURE__ */ jsx(FullscreenNotice, { message: error.message });
@@ -9340,6 +9856,7 @@ export {
9340
9856
  bytesToHex2 as bytesToHex,
9341
9857
  clearEvents,
9342
9858
  compileSchema,
9859
+ compileStateSchema,
9343
9860
  computeGenesisStateId,
9344
9861
  computeNextStateId,
9345
9862
  computeNextStateIdFromPayloads,
@@ -9349,6 +9866,7 @@ export {
9349
9866
  createStoreApi,
9350
9867
  despawn,
9351
9868
  ensureCompiled,
9869
+ ensureCompiledStateSchema,
9352
9870
  generateKeyPair,
9353
9871
  genesisHashFromString,
9354
9872
  genesisHashToString,
@@ -9375,6 +9893,7 @@ export {
9375
9893
  hexToSignature,
9376
9894
  isAlive,
9377
9895
  isCompiledSchema,
9896
+ isCompiledStateSchema,
9378
9897
  iterEvents,
9379
9898
  packRef,
9380
9899
  pubKeyFromPrivate,