@multitapio/multitap 0.0.18 → 0.0.19

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.
Files changed (60) hide show
  1. package/dist/channel.d.ts +6 -6
  2. package/dist/channel.d.ts.map +1 -1
  3. package/dist/crypto.d.ts +12 -0
  4. package/dist/crypto.d.ts.map +1 -1
  5. package/dist/input-graph.d.ts +2 -0
  6. package/dist/input-graph.d.ts.map +1 -1
  7. package/dist/lib.js +268 -118
  8. package/dist/react/components/SyncLoadingScreen.d.ts +27 -0
  9. package/dist/react/components/SyncLoadingScreen.d.ts.map +1 -0
  10. package/dist/react/components/SyncStatusIndicator.d.ts +15 -0
  11. package/dist/react/components/SyncStatusIndicator.d.ts.map +1 -0
  12. package/dist/react/components/index.d.ts +3 -0
  13. package/dist/react/components/index.d.ts.map +1 -0
  14. package/dist/react/hooks/usePlayers.d.ts +2 -0
  15. package/dist/react/hooks/usePlayers.d.ts.map +1 -1
  16. package/dist/react/hooks/useSyncStatus.d.ts +18 -0
  17. package/dist/react/hooks/useSyncStatus.d.ts.map +1 -0
  18. package/dist/react/index.d.ts +2 -0
  19. package/dist/react/index.d.ts.map +1 -1
  20. package/dist/react/providers/ParticipantProvider.d.ts +51 -0
  21. package/dist/react/providers/ParticipantProvider.d.ts.map +1 -0
  22. package/dist/react/providers/SessionProvider.d.ts.map +1 -1
  23. package/dist/react/providers/index.d.ts +2 -0
  24. package/dist/react/providers/index.d.ts.map +1 -1
  25. package/dist/react/stores/syncStatusStore.d.ts +6 -0
  26. package/dist/react/stores/syncStatusStore.d.ts.map +1 -0
  27. package/dist/react/types/session.d.ts +4 -7
  28. package/dist/react/types/session.d.ts.map +1 -1
  29. package/dist/session.d.ts +24 -7
  30. package/dist/session.d.ts.map +1 -1
  31. package/dist/types/channel.d.ts +6 -6
  32. package/dist/types/channel.d.ts.map +1 -1
  33. package/dist/types/crypto.d.ts +12 -0
  34. package/dist/types/crypto.d.ts.map +1 -1
  35. package/dist/types/input-graph.d.ts +2 -0
  36. package/dist/types/input-graph.d.ts.map +1 -1
  37. package/dist/types/react/components/SyncLoadingScreen.d.ts +27 -0
  38. package/dist/types/react/components/SyncLoadingScreen.d.ts.map +1 -0
  39. package/dist/types/react/components/SyncStatusIndicator.d.ts +15 -0
  40. package/dist/types/react/components/SyncStatusIndicator.d.ts.map +1 -0
  41. package/dist/types/react/components/index.d.ts +3 -0
  42. package/dist/types/react/components/index.d.ts.map +1 -0
  43. package/dist/types/react/hooks/usePlayers.d.ts +2 -0
  44. package/dist/types/react/hooks/usePlayers.d.ts.map +1 -1
  45. package/dist/types/react/hooks/useSyncStatus.d.ts +18 -0
  46. package/dist/types/react/hooks/useSyncStatus.d.ts.map +1 -0
  47. package/dist/types/react/index.d.ts +2 -0
  48. package/dist/types/react/index.d.ts.map +1 -1
  49. package/dist/types/react/providers/ParticipantProvider.d.ts +51 -0
  50. package/dist/types/react/providers/ParticipantProvider.d.ts.map +1 -0
  51. package/dist/types/react/providers/SessionProvider.d.ts.map +1 -1
  52. package/dist/types/react/providers/index.d.ts +2 -0
  53. package/dist/types/react/providers/index.d.ts.map +1 -1
  54. package/dist/types/react/stores/syncStatusStore.d.ts +6 -0
  55. package/dist/types/react/stores/syncStatusStore.d.ts.map +1 -0
  56. package/dist/types/react/types/session.d.ts +4 -7
  57. package/dist/types/react/types/session.d.ts.map +1 -1
  58. package/dist/types/session.d.ts +24 -7
  59. package/dist/types/session.d.ts.map +1 -1
  60. package/package.json +1 -1
package/dist/lib.js CHANGED
@@ -2545,6 +2545,21 @@ var GENESIS_HASH_SIZE = 16;
2545
2545
  function generateKeyPair() {
2546
2546
  return utils.randomPrivateKey();
2547
2547
  }
2548
+ function deriveKey(baseKey, index) {
2549
+ if (baseKey.length !== PRIVATE_KEY_SIZE) {
2550
+ throw new Error(`Base key must be ${PRIVATE_KEY_SIZE} bytes`);
2551
+ }
2552
+ if (!Number.isInteger(index) || index < 0 || index > 4294967295) {
2553
+ throw new Error("Index must be a uint32 (0-4294967295)");
2554
+ }
2555
+ const domain = new TextEncoder().encode("multitap:bot:");
2556
+ const input = new Uint8Array(PRIVATE_KEY_SIZE + domain.length + 4);
2557
+ input.set(baseKey, 0);
2558
+ input.set(domain, PRIVATE_KEY_SIZE);
2559
+ const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
2560
+ view.setUint32(PRIVATE_KEY_SIZE + domain.length, index, true);
2561
+ return sha2562(input);
2562
+ }
2548
2563
  function pubKeyFromPrivate(privateKey) {
2549
2564
  return getPublicKey(privateKey, true);
2550
2565
  }
@@ -3931,7 +3946,8 @@ var InputGraph = class {
3931
3946
  }
3932
3947
  return {
3933
3948
  targetTick: tick,
3934
- payload: this.inputPayloadPredictor ? this.inputPayloadPredictor(tick, participant.slot, parent) : new Uint8Array(0),
3949
+ payload: null,
3950
+ // null until filled by optimistic input or predictor fallback
3935
3951
  sig: new Uint8Array(0),
3936
3952
  // no signature required for optimistic tick container
3937
3953
  idx: participant.slot
@@ -3954,13 +3970,17 @@ var InputGraph = class {
3954
3970
  if (!slot) {
3955
3971
  throw new Error(`invariant: participant slot ${prediction.idx} not found in inputs`);
3956
3972
  }
3957
- if (slot.payload.length > 0) {
3973
+ if (slot.payload !== null) {
3958
3974
  continue;
3959
3975
  }
3960
3976
  slot.payload = prediction.payload;
3961
3977
  consumed.push(prediction);
3962
3978
  inputCount++;
3963
- break;
3979
+ }
3980
+ for (const input of inputs) {
3981
+ if (input.payload === null) {
3982
+ input.payload = this.inputPayloadPredictor ? this.inputPayloadPredictor(tick, input.idx, parent) : new Uint8Array(0);
3983
+ }
3964
3984
  }
3965
3985
  for (const msg of consumed) {
3966
3986
  queue.splice(queue.indexOf(msg), 1);
@@ -4023,6 +4043,10 @@ var AsyncInputGraph = class {
4023
4043
  setOnParticipantJoined(fn) {
4024
4044
  return Promise.resolve(this.log.setOnParticipantJoined(fn));
4025
4045
  }
4046
+ // AsyncInputGraph doesn't track replay state - always return true (caught up)
4047
+ isCaughtUp() {
4048
+ return Promise.resolve(true);
4049
+ }
4026
4050
  };
4027
4051
 
4028
4052
  // src/stats.ts
@@ -4082,9 +4106,6 @@ var Channel = class {
4082
4106
  connectionURL;
4083
4107
  serverCertHash;
4084
4108
  connectionTimeoutMs;
4085
- // Signing keys - player identity is derived from public key
4086
- privateKey;
4087
- publicKey;
4088
4109
  genesisHash;
4089
4110
  sessionConfig;
4090
4111
  peerConnection;
@@ -4113,11 +4134,15 @@ var Channel = class {
4113
4134
  optimisticStrategy;
4114
4135
  // auto prediction mode - dynamically set predictedHeadMax based on RTT
4115
4136
  autoPredictedHeadMax = false;
4137
+ // manifest URL for relay status reporting
4138
+ manifestURL;
4116
4139
  // RTT tracking for dynamic input lag calculation
4117
4140
  smoothedRttMs = 0;
4118
4141
  // exponential moving average of RTT
4119
4142
  lastPingId = 0;
4120
4143
  // last received pingId to echo back in pong
4144
+ // Replay tracking - the tick we need to reach to be caught up
4145
+ replayEnd = 0;
4121
4146
  // stats
4122
4147
  stats;
4123
4148
  constructor(config) {
@@ -4125,11 +4150,10 @@ var Channel = class {
4125
4150
  this.connectionURL = config.connectionURL;
4126
4151
  this.serverCertHash = config.serverCertHash;
4127
4152
  this.connectionTimeoutMs = config.connectionTimeoutMs ?? 5e3;
4128
- this.privateKey = config.privateKey ?? generateKeyPair();
4129
- this.publicKey = pubKeyFromPrivate(this.privateKey);
4130
4153
  this.logSyncTicks = config.logSyncTicks ?? false;
4131
4154
  this.iceServers = config.iceServers ?? DEFAULT_ICE_SERVERS;
4132
4155
  this.optimisticStrategy = config.optimisticStrategy;
4156
+ this.manifestURL = config.manifestURL;
4133
4157
  this.sessionConfig = SessionConfig.fromConnectionURL(config.connectionURL);
4134
4158
  this.genesisHash = this.sessionConfig.toGenesisHash();
4135
4159
  this.peerConnection = null;
@@ -4174,10 +4198,6 @@ var Channel = class {
4174
4198
  this._connectLoop().catch(warnUnexpected);
4175
4199
  }
4176
4200
  }
4177
- // Get the player's public key (identity)
4178
- async getPublicKey() {
4179
- return this.publicKey;
4180
- }
4181
4201
  // Get the genesis hash (16 bytes)
4182
4202
  async getGenesisHash() {
4183
4203
  return this.genesisHash;
@@ -4222,6 +4242,18 @@ var Channel = class {
4222
4242
  async getSyncHead() {
4223
4243
  return this.inputGraph.getSyncHead();
4224
4244
  }
4245
+ // Returns true if connection is established and replay is complete.
4246
+ // Requires at least one sync tick to have been received (syncHead.tick > 0).
4247
+ async isCaughtUp() {
4248
+ const syncHead = this.inputGraph.getSyncHead();
4249
+ if (syncHead.tick === 0) {
4250
+ return false;
4251
+ }
4252
+ if (this.replayEnd > 0) {
4253
+ return syncHead.tick >= this.replayEnd;
4254
+ }
4255
+ return true;
4256
+ }
4225
4257
  async getPredictedHead() {
4226
4258
  return this.inputGraph.getPredictedHead();
4227
4259
  }
@@ -4297,23 +4329,24 @@ var Channel = class {
4297
4329
  }
4298
4330
  this.outbox.push(data);
4299
4331
  }
4300
- // Generate a null input for participant registration (join message)
4301
- // Null inputs have TargetTick = NULL_INPUT_TARGET_TICK (0xFFFFFFFF) and empty payload.
4302
- // They bypass the validity window check and are used to register players on connect.
4303
- _generateNullInput() {
4332
+ // Send a join message (null input) to register as a participant
4333
+ // This must be called before sending regular inputs
4334
+ async sendJoinMessage(privateKey) {
4304
4335
  const payload = new Uint8Array(0);
4305
4336
  const msgHash = hashInputMessage(this.genesisHash, NULL_INPUT_TARGET_TICK, payload);
4306
- const signature = sign2(this.privateKey, msgHash);
4307
- return messageCodec.encodeInput(NULL_INPUT_TARGET_TICK, payload, signature);
4337
+ const signature = sign2(privateKey, msgHash);
4338
+ const joinInput = messageCodec.encodeInput(NULL_INPUT_TARGET_TICK, payload, signature);
4339
+ await this._send(joinInput);
4308
4340
  }
4309
4341
  // Send a signed input message
4310
- // The payload is variable-length (0-255 bytes) and signed with the player's private key
4342
+ // The payload is variable-length (0-255 bytes) and signed with the provided private key
4311
4343
  // targetTick defaults to predictedHead + inputLag (calculated from RTT)
4312
4344
  // Returns the encoded input bytes (for P2P broadcast by Session)
4313
- async sendSignedInput(payload) {
4345
+ async sendSignedInput(payload, privateKey) {
4314
4346
  if (payload.length > MAX_INPUT_PAYLOAD_SIZE) {
4315
4347
  throw new Error(`Payload must be ${MAX_INPUT_PAYLOAD_SIZE} bytes or less, got ${payload.length}`);
4316
4348
  }
4349
+ const publicKey = pubKeyFromPrivate(privateKey);
4317
4350
  const inputLag = this.calculateInputLag();
4318
4351
  const tick = this.inputGraph.getCurrentTick() + inputLag;
4319
4352
  if (tick <= this.lastSentTick) {
@@ -4321,13 +4354,13 @@ var Channel = class {
4321
4354
  }
4322
4355
  this.lastSentTick = tick;
4323
4356
  const msgHash = hashInputMessage(this.genesisHash, tick, payload);
4324
- const signature = sign2(this.privateKey, msgHash);
4325
- const selfId = bytesToHex2(this.publicKey);
4357
+ const signature = sign2(privateKey, msgHash);
4358
+ const selfId = bytesToHex2(publicKey);
4326
4359
  const selfParticipant = this.inputGraph.getParticipantSlots(tick).find((participant) => participant.id === selfId);
4327
4360
  if (selfParticipant && this.optimisticStrategy !== OPTIMISTIC_NONE) {
4328
4361
  this.inputGraph.addOptimisticInput(
4329
4362
  { targetTick: tick, payload, sig: signature, idx: selfParticipant.slot },
4330
- this.publicKey
4363
+ publicKey
4331
4364
  );
4332
4365
  }
4333
4366
  const encoded = messageCodec.encodeInput(tick, payload, signature);
@@ -4345,13 +4378,7 @@ var Channel = class {
4345
4378
  let consecutiveFailures = 0;
4346
4379
  while (!this.stopped) {
4347
4380
  try {
4348
- const joinInput = this._generateNullInput();
4349
- const joinParam = uint8ArrayToBase64URL(joinInput);
4350
- const configWithCreds = new SessionConfig({
4351
- ...this.sessionConfig,
4352
- credentials: joinParam
4353
- });
4354
- const sessionParam = configWithCreds.toBase64EncodedConnectionURL();
4381
+ const sessionParam = this.sessionConfig.toBase64EncodedConnectionURL();
4355
4382
  const base = "https://" + this.sessionConfig.authority;
4356
4383
  const pc = new RTCPeerConnection({
4357
4384
  iceServers: this.iceServers
@@ -4389,8 +4416,10 @@ var Channel = class {
4389
4416
  if (!localDesc) {
4390
4417
  throw new Error("Failed to get local description");
4391
4418
  }
4392
- const pubKeyHex = bytesToHex2(this.publicKey);
4393
- const offerURL = `${base}/rtc/offer?session=${sessionParam}&from=${pubKeyHex}&to=relay`;
4419
+ let offerURL = `${base}/rtc/offer?session=${sessionParam}&from=anonymous&to=relay`;
4420
+ if (this.manifestURL) {
4421
+ offerURL += `&manifest=${encodeURIComponent(this.manifestURL)}`;
4422
+ }
4394
4423
  const offerResponse = await fetch(offerURL, {
4395
4424
  method: "POST",
4396
4425
  headers: { "Content-Type": "application/json" },
@@ -4501,6 +4530,7 @@ var Channel = class {
4501
4530
  }
4502
4531
  if (pingData.isReplay) {
4503
4532
  handle.isReplay = true;
4533
+ this.replayEnd = pingData.replayEnd;
4504
4534
  const idx = this.dataChannels.indexOf(handle);
4505
4535
  if (idx >= 0 && handle.generation === this.connectionGeneration) {
4506
4536
  this.dataChannels.splice(idx, 1);
@@ -8089,7 +8119,7 @@ function warnUnexpected2(err2) {
8089
8119
  }
8090
8120
 
8091
8121
  // src/rollback.worker.ts
8092
- var workerCode = 'var Nr=Object.defineProperty;var zr=(t,e,n)=>e in t?Nr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>zr(t,typeof e!="symbol"?e+"":e,n);var Rt=Symbol("Comlink.proxy"),Rr=Symbol("Comlink.endpoint"),Hr=Symbol("Comlink.releaseProxy"),ut=Symbol("Comlink.finalizer"),Ce=Symbol("Comlink.thrown"),Ht=t=>typeof t=="object"&&t!==null||typeof t=="function",Lr={canHandle:t=>Ht(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)}},Vr={canHandle:t=>Ht(t)&&Ce 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",Lr],["throw",Vr]]);function Gr(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(!Gr(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(j),u;try{let f=a.slice(0,-1).reduce((g,E)=>g[E],t),d=a.reduce((g,E)=>g[E],t);switch(s){case"GET":u=d;break;case"SET":f[a.slice(-1)[0]]=j(i.data.value),u=!0;break;case"APPLY":u=d.apply(f,c);break;case"CONSTRUCT":{let g=new d(...c);u=jr(g)}break;case"ENDPOINT":{let{port1:g,port2:E}=new MessageChannel;Be(t,E),u=Wr(g,[g])}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,[Ce]:0}}Promise.resolve(u).catch(f=>({value:f,[Ce]:0})).then(f=>{let[d,g]=Ue(f);e.postMessage(Object.assign(Object.assign({},d),{id:o}),g),s==="RELEASE"&&(e.removeEventListener("message",r),Vt(e),ut in t&&typeof t[ut]=="function"&&t[ut]())}).catch(f=>{let[d,g]=Ue({value:new TypeError("Unserializable return value"),[Ce]:0});e.postMessage(Object.assign(Object.assign({},d),{id:o}),g)})}),e.start&&e.start()}function Zr(t){return t.constructor.name==="MessagePort"}function Vt(t){Zr(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 Gt(t){return ie(t,new Map,{type:"RELEASE"}).then(()=>{Vt(t)})}var Ie=new WeakMap,ve="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(Ie.get(t)||0)-1;Ie.set(t,e),e===0&&Gt(t)});function qr(t,e){let n=(Ie.get(e)||0)+1;Ie.set(e,n),ve&&ve.register(t,e,t)}function Kr(t){ve&&ve.unregister(t)}function ft(t,e,n=[],r=function(){}){let i=!1,o=new Proxy(r,{get(s,a){if(Ae(i),a===Hr)return()=>{Kr(o),Gt(t),e.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>o};let c=ie(t,e,{type:"GET",path:n.map(u=>u.toString())}).then(j);return c.then.bind(c)}return ft(t,e,[...n,a])},set(s,a,c){Ae(i);let[u,f]=Ue(c);return ie(t,e,{type:"SET",path:[...n,a].map(d=>d.toString()),value:u},f).then(j)},apply(s,a,c){Ae(i);let u=n[n.length-1];if(u===Rr)return ie(t,e,{type:"ENDPOINT"}).then(j);if(u==="bind")return ft(t,e,n.slice(0,-1));let[f,d]=zt(c);return ie(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:f},d).then(j)},construct(s,a){Ae(i);let[c,u]=zt(a);return ie(t,e,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:c},u).then(j)}});return qr(o,t),o}function Yr(t){return Array.prototype.concat.apply([],t)}function zt(t){let e=t.map(Ue);return[e.map(n=>n[0]),Yr(e.map(n=>n[1]))]}var Zt=new WeakMap;function Wr(t,e){return Zt.set(t,e),t}function jr(t){return Object.assign(t,{[Rt]:!0})}function Ue(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 j(t){switch(t.type){case"HANDLER":return Lt.get(t.name).deserialize(t.value);case"RAW":return t.value}}function ie(t,e,n,r){return new Promise(i=>{let o=Xr();e.set(o,i),t.start&&t.start(),t.postMessage(Object.assign({id:o},n),r)})}function Xr(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Jr={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:J,n:ht,Gx:Qr,Gy:ei,b:Jt}=Jr,oe=32,dt=64,I=(t="")=>{throw new Error(t)},Qt=t=>typeof t=="bigint",en=t=>typeof t=="string",ti=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",he=(t,e)=>!ti(t)||typeof e=="number"&&e>0&&t.length!==e?I("Uint8Array expected"):t,Oe=t=>new Uint8Array(t),ni=t=>Uint8Array.from(t),tn=(t,e)=>t.toString(16).padStart(e,"0"),yt=t=>Array.from(he(t)).map(e=>tn(e,2)).join(""),V={_0:48,_9:57,A:65,F:70,a:97,f:102},qt=t=>{if(t>=V._0&&t<=V._9)return t-V._0;if(t>=V.A&&t<=V.F)return t-(V.A-10);if(t>=V.a&&t<=V.f)return t-(V.a-10)},gt=t=>{let e="hex invalid";if(!en(t))return I(e);let n=t.length,r=n/2;if(n%2)return I(e);let i=Oe(r);for(let o=0,s=0;o<r;o++,s+=2){let a=qt(t.charCodeAt(s)),c=qt(t.charCodeAt(s+1));if(a===void 0||c===void 0)return I(e);i[o]=a*16+c}return i},bt=(t,e)=>he(en(t)?gt(t):ni(he(t)),e),nn=()=>globalThis?.crypto,ri=()=>nn()?.subtle??I("crypto.subtle must be defined"),_e=(...t)=>{let e=Oe(t.reduce((r,i)=>r+he(i).length,0)),n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},ii=(t=oe)=>nn().getRandomValues(Oe(t)),$e=BigInt,ye=(t,e,n,r="bad number: out of range")=>Qt(t)&&e<=t&&t<n?t:I(r),h=(t,e=J)=>{let n=t%e;return n>=0n?n:e+n};var rn=(t,e)=>{(t===0n||e<=0n)&&I("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,d=o-a*c;r=n,n=u,i=s,o=a,s=f,a=d}return r===1n?h(i,e):I("no inverse")};var Kt=t=>t instanceof Q?t:I("Point expected"),on=t=>h(h(t*t)*t+Jt),Yt=t=>ye(t,0n,J),Pe=t=>ye(t,1n,J),oi=t=>ye(t,1n,ht),pt=t=>(t&1n)===0n,sn=t=>Uint8Array.of(t),si=t=>sn(pt(t)?2:3),ai=t=>{let e=on(Pe(t)),n=1n;for(let r=e,i=(J+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%J),r=r*r%J;return h(n*n)===e?n:I("sqrt invalid")},N=class N{constructor(e,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=Yt(e),this.py=Pe(n),this.pz=Yt(r),Object.freeze(this)}static fromBytes(e){he(e);let n,r=e[0],i=e.subarray(1),o=Wt(i,0,oe),s=e.length;if(s===oe+1&&[2,3].includes(r)){let a=ai(o),c=pt(a);pt($e(r))!==c&&(a=h(-a)),n=new N(o,a,1n)}return s===dt+1&&r===4&&(n=new N(o,Wt(i,oe,dt),1n)),n?n.assertValidity():I("bad point: not on curve")}equals(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Kt(e),c=h(n*a),u=h(o*i),f=h(r*a),d=h(s*i);return c===u&&f===d}is0(){return this.equals(X)}negate(){return new N(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}=Kt(e),c=0n,u=Jt,f=0n,d=0n,g=0n,E=h(u*3n),T=h(n*o),A=h(r*s),F=h(i*a),re=h(n+r),C=h(o+s);re=h(re*C),C=h(T+A),re=h(re-C),C=h(n+i);let M=h(o+a);return C=h(C*M),M=h(T+F),C=h(C-M),M=h(r+i),f=h(s+a),M=h(M*f),f=h(A+F),M=h(M-f),g=h(c*C),f=h(E*F),g=h(f+g),f=h(A-g),g=h(A+g),d=h(f*g),A=h(T+T),A=h(A+T),F=h(c*F),C=h(E*C),A=h(A+F),F=h(T-F),F=h(c*F),C=h(C+F),T=h(A*C),d=h(d+T),T=h(M*C),f=h(re*f),f=h(f-T),T=h(re*A),g=h(M*g),g=h(g+T),new N(f,d,g)}multiply(e,n=!0){if(!n&&e===0n)return X;if(oi(e),e===1n)return this;if(this.equals(se))return mi(e).p;let r=X,i=se;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(X))return{x:0n,y:0n};if(r===1n)return{x:e,y:n};let i=rn(r,J);return h(r*i)!==1n&&I("inverse invalid"),{x:h(e*i),y:h(n*i)}}assertValidity(){let{x:e,y:n}=this.toAffine();return Pe(e),Pe(n),h(n*n)===on(e)?this:I("bad point: not on curve")}toBytes(e=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=Fe(n);return e?_e(si(r),i):_e(sn(4),i,Fe(r))}static fromAffine(e){let{x:n,y:r}=e;return n===0n&&r===0n?X:new N(n,r,1n)}toHex(e){return yt(this.toBytes(e))}static fromPrivateKey(e){return se.multiply(ui(e))}static fromHex(e){return N.fromBytes(bt(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(e){return this.toBytes(e)}};y(N,"BASE"),y(N,"ZERO");var Q=N,se=new Q(Qr,ei,1n),X=new Q(0n,1n,0n);Q.BASE=se;Q.ZERO=X;var Me=t=>$e("0x"+(yt(t)||"0")),Wt=(t,e,n)=>Me(t.subarray(e,n)),ci=2n**256n,Fe=t=>gt(tn(ye(t,0n,ci),dt)),ui=t=>{let e=Qt(t)?t:Me(bt(t,oe));return ye(e,1n,ht,"private key invalid 3")};var fi=t=>{t=bt(t),(t.length<oe+8||t.length>1024)&&I("expected 40-1024b");let e=h(Me(t),ht-1n);return Fe(e+1n)};var li="SHA-256",xt={hexToBytes:gt,bytesToHex:yt,concatBytes:_e,bytesToNumberBE:Me,numberToBytesBE:Fe,mod:h,invert:rn,hmacSha256Async:async(t,...e)=>{let n=ri(),r="HMAC",i=await n.importKey("raw",t,{name:r,hash:{name:li}},!1,["sign"]);return Oe(await n.sign(r,i,_e(...e)))},hmacSha256Sync:void 0,hashToPrivateKey:fi,randomBytes:ii};var De=8,di=256,an=Math.ceil(di/De)+1,mt=2**(De-1),pi=()=>{let t=[],e=se,n=e;for(let r=0;r<an;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},jt,Xt=(t,e)=>{let n=e.negate();return t?n:e},mi=t=>{let e=jt||(jt=pi()),n=X,r=se,i=2**De,o=i,s=$e(i-1),a=$e(De);for(let c=0;c<an;c++){let u=Number(t&s);t>>=a,u>mt&&(u-=o,t+=1n);let f=c*mt,d=f,g=f+Math.abs(u)-1,E=c%2!==0,T=u<0;u===0?r=r.add(Xt(E,e[d])):n=n.add(Xt(T,e[g]))}return{p:n,f:r}};function yi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function cn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ce(t,...e){if(!yi(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 un(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");cn(t.outputLen),cn(t.blockLen)}function ue(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 fn(t,e){ce(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ee(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ne(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function D(t,e){return t<<32-e|t>>>e}function gi(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=gi(t)),ce(t),t}var ae=class{};function ln(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 bi(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 dn(t,e,n){return t&e^~t&n}function pn(t,e,n){return t&e^t&n^e&n}var ze=class extends ae{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=Ne(this.buffer)}update(e){ue(this),e=ge(e),ce(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=Ne(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){ue(this),fn(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;n[s++]=128,ee(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)n[d]=0;bi(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=Ne(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 d=0;d<u;d++)a.setUint32(4*d,f[d],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()}},G=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xi=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),Re=class extends ze{constructor(e=32){super(64,e,8,!1),this.A=G[0]|0,this.B=G[1]|0,this.C=G[2]|0,this.D=G[3]|0,this.E=G[4]|0,this.F=G[5]|0,this.G=G[6]|0,this.H=G[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 d=0;d<16;d++,n+=4)q[d]=e.getUint32(n,!1);for(let d=16;d<64;d++){let g=q[d-15],E=q[d-2],T=D(g,7)^D(g,18)^g>>>3,A=D(E,17)^D(E,19)^E>>>10;q[d]=A+q[d-7]+T+q[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let d=0;d<64;d++){let g=D(a,6)^D(a,11)^D(a,25),E=f+g+dn(a,c,u)+xi[d]+q[d]|0,A=(D(r,2)^D(r,13)^D(r,22))+pn(r,i,o)|0;f=u,u=c,c=a,a=s+E|0,s=o,o=i,i=r,r=E+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(){ee(q)}destroy(){this.set(0,0,0,0,0,0,0,0),ee(this.buffer)}};var te=ln(()=>new Re);var wt=te;var He=class extends ae{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,un(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),ee(o)}update(e){return ue(this),this.iHash.update(e),this}digestInto(e){ue(this),ce(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 He(t,e).update(n).digest();St.create=(t,e)=>new He(t,e);var wi=["string","number","bigint","symbol"],Si=["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 mn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(wi.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(Ei(t))return"Buffer";let n=Ti(t);return n||"Object"}function Ei(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function Ti(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(Si.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 fe=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ki=new TextDecoder,Ai=new TextEncoder;function Le(t){return fe&&globalThis.Buffer.isBuffer(t)}function Et(t){return t instanceof Uint8Array?Le(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var bn=fe?(t,e,n)=>n-e>64?globalThis.Buffer.from(t.subarray(e,n)).toString("utf8"):yn(t,e,n):(t,e,n)=>n-e>64?ki.decode(t.subarray(e,n)):yn(t,e,n),xn=fe?t=>t.length>64?globalThis.Buffer.from(t):hn(t):t=>t.length>64?Ai.encode(t):hn(t),z=t=>Uint8Array.from(t),le=fe?(t,e,n)=>Le(t)?new Uint8Array(t.subarray(e,n)):t.slice(e,n):(t,e,n)=>t.slice(e,n),wn=fe?(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},Sn=fe?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ve(t,e){if(Le(t)&&Le(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 hn(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 yn(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 Ci(r)}var gn=4096;function Ci(t){let e=t.length;if(e<=gn)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=gn));return n}var Ii=256,be=class{constructor(e=Ii){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=Sn(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=le(r,0,this.cursor)}else n=wn(this.chunks,this.cursor);return e&&this.reset(),n}};var b="CBOR decode error:",Tt="CBOR encode error:",xe=[];xe[23]=1;xe[24]=2;xe[25]=3;xe[26]=5;xe[27]=9;function Z(t,e,n){if(t.length-e<n)throw new Error(`${b} not enough data for type`)}var S=[24,256,65536,4294967296,BigInt("18446744073709551616")];function v(t,e,n){Z(t,e,1);let r=t[e];if(n.strict===!0&&r<S[0])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function U(t,e,n){Z(t,e,2);let r=t[e]<<8|t[e+1];if(n.strict===!0&&r<S[1])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function B(t,e,n){Z(t,e,4);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(n.strict===!0&&r<S[2])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function P(t,e,n){Z(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<S[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 En(t,e,n,r){return new m(l.uint,v(t,e+1,r),2)}function Tn(t,e,n,r){return new m(l.uint,U(t,e+1,r),3)}function kn(t,e,n,r){return new m(l.uint,B(t,e+1,r),5)}function An(t,e,n,r){return new m(l.uint,P(t,e+1,r),9)}function _(t,e){return k(t,0,e.value)}function k(t,e,n){if(n<S[0]){let r=Number(n);t.push([e|r])}else if(n<S[1]){let r=Number(n);t.push([e|24,r])}else if(n<S[2]){let r=Number(n);t.push([e|25,r>>>8,r&255])}else if(n<S[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<S[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`)}}_.encodedSize=function(e){return k.encodedSize(e.value)};k.encodedSize=function(e){return e<S[0]?1:e<S[1]?2:e<S[2]?3:e<S[3]?5:9};_.compareTokens=function(e,n){return e.value<n.value?-1:e.value>n.value?1:0};function Cn(t,e,n,r){return new m(l.negint,-1-v(t,e+1,r),2)}function In(t,e,n,r){return new m(l.negint,-1-U(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 Bn(t,e,n,r){let i=P(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;k(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<S[0]?1:r<S[1]?2:r<S[2]?3:r<S[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){Z(t,e,n+r);let i=le(t,e+n,e+n+r);return new m(l.bytes,i,n+r)}function Pn(t,e,n,r){return we(t,e,1,n)}function _n(t,e,n,r){return we(t,e,2,v(t,e+1,r))}function $n(t,e,n,r){return we(t,e,3,U(t,e+1,r))}function Fn(t,e,n,r){return we(t,e,5,B(t,e+1,r))}function Dn(t,e,n,r){let i=P(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?xn(t.value):t.value),t.encodedBytes}function de(t,e){let n=Ze(e);k(t,e.type.majorEncoded,n.length),t.push(n)}de.encodedSize=function(e){let n=Ze(e);return k.encodedSize(n.length)+n.length};de.compareTokens=function(e,n){return Ui(Ze(e),Ze(n))};function Ui(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;Z(t,e,o);let s=new m(l.string,bn(t,e+n,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=le(t,e+n,e+o)),s}function On(t,e,n,r){return Se(t,e,1,n,r)}function Mn(t,e,n,r){return Se(t,e,2,v(t,e+1,r),r)}function Nn(t,e,n,r){return Se(t,e,3,U(t,e+1,r),r)}function zn(t,e,n,r){return Se(t,e,5,B(t,e+1,r),r)}function Rn(t,e,n,r){let i=P(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 Hn=de;function pe(t,e,n,r){return new m(l.array,r,n)}function Ln(t,e,n,r){return pe(t,e,1,n)}function Vn(t,e,n,r){return pe(t,e,2,v(t,e+1,r))}function Gn(t,e,n,r){return pe(t,e,3,U(t,e+1,r))}function Zn(t,e,n,r){return pe(t,e,5,B(t,e+1,r))}function qn(t,e,n,r){let i=P(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer array lengths not supported`);return pe(t,e,9,i)}function Kn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return pe(t,e,1,1/0)}function qe(t,e){k(t,l.array.majorEncoded,e.value)}qe.compareTokens=_.compareTokens;qe.encodedSize=function(e){return k.encodedSize(e.value)};function me(t,e,n,r){return new m(l.map,r,n)}function Yn(t,e,n,r){return me(t,e,1,n)}function Wn(t,e,n,r){return me(t,e,2,v(t,e+1,r))}function jn(t,e,n,r){return me(t,e,3,U(t,e+1,r))}function Xn(t,e,n,r){return me(t,e,5,B(t,e+1,r))}function Jn(t,e,n,r){let i=P(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer map lengths not supported`);return me(t,e,9,i)}function Qn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return me(t,e,1,1/0)}function Ke(t,e){k(t,l.map.majorEncoded,e.value)}Ke.compareTokens=_.compareTokens;Ke.encodedSize=function(e){return k.encodedSize(e.value)};function er(t,e,n,r){return new m(l.tag,n,1)}function tr(t,e,n,r){return new m(l.tag,v(t,e+1,r),2)}function nr(t,e,n,r){return new m(l.tag,U(t,e+1,r),3)}function rr(t,e,n,r){return new m(l.tag,B(t,e+1,r),5)}function ir(t,e,n,r){return new m(l.tag,P(t,e+1,r),9)}function Ye(t,e){k(t,l.tag.majorEncoded,e.value)}Ye.compareTokens=_.compareTokens;Ye.encodedSize=function(e){return k.encodedSize(e.value)};var Di=20,Oi=21,Mi=22,Ni=23;function or(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 sr(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 ar(t,e,n,r){return At(Ct(t,e+1),3,r)}function cr(t,e,n,r){return At(It(t,e+1),5,r)}function ur(t,e,n,r){return At(pr(t,e+1),9,r)}function We(t,e,n){let r=e.value;if(r===!1)t.push([l.float.majorEncoded|Di]);else if(r===!0)t.push([l.float.majorEncoded|Oi]);else if(r===null)t.push([l.float.majorEncoded|Mi]);else if(r===void 0)t.push([l.float.majorEncoded|Ni]);else{let i,o=!1;(!n||n.float64!==!0)&&(lr(r),i=Ct(O,1),r===i||Number.isNaN(r)?(O[0]=249,t.push(O.slice(0,3)),o=!0):(dr(r),i=It(O,1),r===i&&(O[0]=250,t.push(O.slice(0,5)),o=!0))),o||(zi(r),i=pr(O,1),O[0]=251,t.push(O.slice(0,9)))}}We.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){lr(r);let i=Ct(O,1);if(r===i||Number.isNaN(r))return 3;if(dr(r),i=It(O,1),r===i)return 5}return 9};var fr=new ArrayBuffer(9),$=new DataView(fr,1),O=new Uint8Array(fr,0);function lr(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 Ct(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 dr(t){$.setFloat32(0,t,!1)}function It(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 zi(t){$.setFloat64(0,t,!1)}function pr(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)}We.compareTokens=_.compareTokens;function x(t,e,n){throw new Error(`${b} encountered invalid minor (${n}) for major ${t[e]>>>5}`)}function je(t){return()=>{throw new Error(`${b} ${t}`)}}var p=[];for(let t=0;t<=23;t++)p[t]=x;p[24]=En;p[25]=Tn;p[26]=kn;p[27]=An;p[28]=x;p[29]=x;p[30]=x;p[31]=x;for(let t=32;t<=55;t++)p[t]=x;p[56]=Cn;p[57]=In;p[58]=vn;p[59]=Bn;p[60]=x;p[61]=x;p[62]=x;p[63]=x;for(let t=64;t<=87;t++)p[t]=Pn;p[88]=_n;p[89]=$n;p[90]=Fn;p[91]=Dn;p[92]=x;p[93]=x;p[94]=x;p[95]=je("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)p[t]=On;p[120]=Mn;p[121]=Nn;p[122]=zn;p[123]=Rn;p[124]=x;p[125]=x;p[126]=x;p[127]=je("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)p[t]=Ln;p[152]=Vn;p[153]=Gn;p[154]=Zn;p[155]=qn;p[156]=x;p[157]=x;p[158]=x;p[159]=Kn;for(let t=160;t<=183;t++)p[t]=Yn;p[184]=Wn;p[185]=jn;p[186]=Xn;p[187]=Jn;p[188]=x;p[189]=x;p[190]=x;p[191]=Qn;for(let t=192;t<=215;t++)p[t]=er;p[216]=tr;p[217]=nr;p[218]=rr;p[219]=ir;p[220]=x;p[221]=x;p[222]=x;p[223]=x;for(let t=224;t<=243;t++)p[t]=je("simple values are not supported");p[244]=x;p[245]=x;p[246]=x;p[247]=or;p[248]=je("simple values are not supported");p[249]=ar;p[250]=cr;p[251]=ur;p[252]=x;p[253]=x;p[254]=x;p[255]=sr;var R=[];for(let t=0;t<24;t++)R[t]=new m(l.uint,t,1);for(let t=-1;t>=-24;t--)R[31-t]=new m(l.negint,t,1);R[64]=new m(l.bytes,new Uint8Array(0),1);R[96]=new m(l.string,"",1);R[128]=new m(l.array,0,1);R[160]=new m(l.map,0,1);R[244]=new m(l.false,!1,1);R[245]=new m(l.true,!0,1);R[246]=new m(l.null,null,1);function mr(t){switch(t.type){case l.false:return z([244]);case l.true:return z([245]);case l.null:return z([246]);case l.bytes:return t.value.length?void 0:z([64]);case l.string:return t.value===""?z([96]):void 0;case l.array:return t.value===0?z([128]):void 0;case l.map:return t.value===0?z([160]):void 0;case l.uint:return t.value<24?z([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return z([31-Number(t.value)])}}var yr=Object.freeze({float64:!0,mapSorter:Gi,quickEncodeToken:mr});function Hi(){let t=[];return t[l.uint.major]=_,t[l.negint.major]=Ge,t[l.bytes.major]=de,t[l.string.major]=Hn,t[l.array.major]=qe,t[l.map.major]=Ke,t[l.tag.major]=Ye,t[l.float.major]=We,t}var Li=Hi(),vt=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(`${Tt} object contains circular references`);return new t(n,e)}},K={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)},Y={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?K.true:K.false},null(t,e,n,r){return K.null},undefined(t,e,n,r){return K.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?[K.emptyArray,new m(l.break)]:K.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?[K.emptyMap,new m(l.break)]:K.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 Vi(a,n),n.addBreakTokens?[new m(l.map,s),a,new m(l.break)]:[new m(l.map,s),a]}};Y.Map=Y.Object;Y.Buffer=Y.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Y[`${t}Array`]=Y.DataView;function Xe(t,e={},n){let r=mn(t),i=e&&e.typeEncoders&&e.typeEncoders[r]||Y[r];if(typeof i=="function"){let s=i(t,r,e,n);if(s!=null)return s}let o=Y[r];if(!o)throw new Error(`${Tt} unsupported type: ${r}`);return o(t,r,e,n)}function Vi(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Gi(t,e){if(t[0]instanceof m&&e[0]instanceof m){let n=t[0],r=e[0];return n._keyBytes||(n._keyBytes=hr(n.value)),r._keyBytes||(r._keyBytes=hr(r.value)),Ve(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function hr(t){return Zi(t,Li,yr)}function gr(t,e,n,r){if(Array.isArray(e))for(let i of e)gr(t,i,n,r);else n[e.type.major](t,e,r)}function Zi(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 vt.reset(),gr(vt,r,e,n),vt.toBytes(!0)}xt.hmacSha256Sync=(t,...e)=>St(wt,t,xt.concatBytes(...e));var Yi=32;function Qe(t){if(t.length===0)return new Uint8Array(Yi);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)}function Ut(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Ee={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},Bt={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},Wi=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","entityRef","f32"]),br=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","f32"]);function xr(t){let e=t.match(/^(\\w+)\\[(\\d+)\\]$/);if(!e||!e[1]||!e[2])return null;let n=e[1],r=parseInt(e[2],10);return Wi.has(n)?{elementType:n,length:r}:null}var wr=1297369412;function Sr(t){let e=t.match(/^vec3\\[(\\d+)\\]$/);return e?.[1]?{elementType:"vec3",length:parseInt(e[1],10)}:null}function Er(t){let e=t.match(/^vec2\\[(\\d+)\\]$/);return e?.[1]?{elementType:"vec2",length:parseInt(e[1],10)}:null}function Tr(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(!br.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 ji(t){let e=[],n=[],r=new Map,i=new Map;for(let o of t.controls){let s=Tr(o.type),a={name:o.name,type:o.type,size:o.size,offset:0,options:o.options?[...o.options]:void 0};s&&(a.arrayLength=s.length,a.arrayElementType=s.elementType);let c={name:o.name,index:o.index,field:a,hint:o.hint,retain:o.retain};e.push(c),r.set(o.name,c)}for(let o of t.commands){let s=[];for(let c of o.args){let u=Tr(c.type),f={name:c.name,type:c.type,size:c.size,offset:c.offset};u&&(f.arrayLength=u.length,f.arrayElementType=u.elementType),s.push(f)}let a={name:o.name,index:o.index,args:s,totalSize:o.totalSize};n.push(a),i.set(o.name,a)}return{controls:e,commands:n,controlByName:r,commandByName:i}}function Pt(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);Pt(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=Bt[r.arrayElementType];for(let a=0;a<Math.min(o.length,r.arrayLength);a++)Pt(e,n+a*s,r.arrayElementType,o[a])}else Pt(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=Bt[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 kr(t){let e=ji(t);return{create(){return new et(e)},decode(n){return et.decode(e,n)},get schema(){return e}}}function Ar(t,e){return((e&65535)<<16|t&65535)>>>0}function Te(t){return t&65535}function to(t){return t>>>16&65535}function L(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 Ft(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),te(r)}function Dt(t,e,n){return rt(t,e,Qe(n))}function Ot(t){return te(t)}function Cr(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 Ir(t,e){return t.entityTableOffset+e*t.entityRecordSize}function Mt(t,e,n){let r=Ir(t,n);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(r,!0)}function no(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(4,!0)}function ro(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(4,e,!0)}function io(t,e){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t.freeStackOffset,!0)}function oo(t,e,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t.freeStackOffset,n,!0)}function so(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=io(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 oo(t,e,r-1),o}function vr(t,e){let n=so(t,e),r=Mt(t,e,n);return ro(e,no(e)+1),Ar(n,r)}function it(t,e,n){if(n===4294967295)return!1;let r=Te(n);if(r>=t.maxEntities)return!1;let i=to(n);return Mt(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=Ir(t,e)+2,i=Math.floor(n/8),o=n%8;return{byteOffset:r+i,bitIndex:o}}function Ur(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=Te(n),{byteOffset:s,bitIndex:a}=Nt(t,o,i.index);return(e[s]&1<<a)!==0}function Br(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=Te(n),{byteOffset:s,bitIndex:a}=Nt(t,o,i.index);e[s]=(e[s]??0)|1<<a}function Pr(t,e,n,r){let i=Te(e);return n.storageOffset+i*n.size+r.offset}function ao(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 _r(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 co(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 uo(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 fo(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 $r(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=Pr(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=Ee[a.arrayElementType];if(f===void 0)throw new Error(`Unknown array element type: ${a.arrayElementType}`);c+=o*f,u=a.arrayElementType}return ao(e,c,u)}function w(t,e,n,r,i,o,s){if(!it(t,e,n)){let d=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${d} is not alive`)}let a=t.componentByName.get(r);if(!a)throw new Error(`Unknown component: \'${r}\'`);if(!nt(t,e,n,a)){let d=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${d} does not have component \'${r}\'`)}let c=a.fields.find(d=>d.name===i);if(!c)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let u=Pr(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 d=Ee[c.arrayElementType];if(d===void 0)throw new Error(`Unknown array element type: ${c.arrayElementType}`);u+=s*d,f=c.arrayElementType}_r(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=Te(n),{byteOffset:o,bitIndex:s}=Nt(t,i,r.index);return(e[o]&1<<s)!==0}function Fr(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=Mt(t,e,a),u=Ar(a,c),f=!0;for(let d of i)if(!nt(t,e,u,d)){f=!1;break}if(f){for(let d of o)if(nt(t,e,u,d)){f=!1;break}f&&(yield u)}}}return s()}function Dr(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 Or(t,e,n){let r=Dr(t,n);new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(r.storageOffset,0,!0)}function Mr(t,e,n,r){let i=Dr(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"?co(e,f,u):c.type==="vec3"?uo(e,f,u):c.type==="quat"?fo(e,f,u):_r(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=L(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=L(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=L(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 ke=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,"initDataPtr",null);y(this,"initDataSize",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)/ke);if(this.options.debug){let u=(s+c*ke)/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=kr(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/ke)*ke;return c+f},0),i=1024*1024*5,o=this.stateSize+i+r,s=Math.ceil(o/ke);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),d=await WebAssembly.instantiate(f,a);if(typeof d.exports.apply!="function")throw new Error(`Plugin "${c.name}" missing required apply() export`);this.plugins.push({name:c.name,instance:d,exports:d.exports})}if(this.statePtr=this.hostAlloc(this.stateSize,8),this.options.initDataSchema&&this.options.initDataSchema.items.length>0){let c=this.options.initDataSchema,u=this.options.initData;if(!u)throw new Error("initData is required when initDataSchema is provided");this.initDataSize=c.totalSize,this.initDataPtr=this.hostAlloc(this.initDataSize,8),this.writeInitData(c,u);for(let f of this.plugins){let d=f.instance.exports.set_init_data_ptr;typeof d=="function"&&d(this.initDataPtr)}this.options.debug&&console.log(`[mt] Init data allocated at ${this.initDataPtr}, size ${this.initDataSize} bytes`)}return this.markArenaReset(),this}writeInitData(e,n){let r=this.memory;if(!r||this.initDataPtr===null)throw new Error("Memory or init data pointer not initialized");let i=new DataView(r.buffer,this.initDataPtr,e.totalSize);i.setUint32(0,wr,!0),i.setUint32(4,e.totalSize,!0);for(let o of e.items){let s=n[o.name];if(s===void 0)throw new Error(`Missing required init data item: ${o.name}`);o.isBlob?this.writeInitDataBlob(i,o,s):this.writeInitDataCompound(i,o,s)}}writeInitDataBlob(e,n,r){let i;if(typeof r=="string"){let s=atob(r);i=new Uint8Array(s.length);for(let a=0;a<s.length;a++)i[a]=s.charCodeAt(a)}else if(r instanceof Uint8Array)i=r;else throw new Error(`Init data blob "${n.name}" must be a base64 string or Uint8Array`);if(i.length>n.blobMaxSize)throw new Error(`Init data blob "${n.name}" exceeds maxSize: ${i.length} > ${n.blobMaxSize}`);let o=n.storageOffset;e.setUint32(o,i.length,!0);for(let s=0;s<i.length;s++)e.setUint8(o+4+s,i[s])}writeInitDataCompound(e,n,r){for(let i of n.fields){let o=r[i.name];if(o===void 0)throw new Error(`Missing required init data field: ${n.name}.${i.name}`);this.writeInitDataField(e,n.storageOffset,i,o)}}writeInitDataField(e,n,r,i){let o=n+r.offset,s=Sr(r.type);if(s){let u=i;if(!Array.isArray(u))throw new Error(`Expected array for vec3[] field, got ${typeof i}`);for(let f=0;f<u.length&&f<s.length;f++){let d=u[f];Array.isArray(d)?(e.setFloat32(o+f*12,d[0]??0,!0),e.setFloat32(o+f*12+4,d[1]??0,!0),e.setFloat32(o+f*12+8,d[2]??0,!0)):(e.setFloat32(o+f*12,d.x??0,!0),e.setFloat32(o+f*12+4,d.y??0,!0),e.setFloat32(o+f*12+8,d.z??0,!0))}return}let a=Er(r.type);if(a){let u=i;if(!Array.isArray(u))throw new Error(`Expected array for vec2[] field, got ${typeof i}`);for(let f=0;f<u.length&&f<a.length;f++){let d=u[f];Array.isArray(d)?(e.setFloat32(o+f*8,d[0]??0,!0),e.setFloat32(o+f*8+4,d[1]??0,!0)):(e.setFloat32(o+f*8,d.x??0,!0),e.setFloat32(o+f*8+4,d.y??0,!0))}return}if(r.type==="vec3"){let u=i;Array.isArray(u)?(e.setFloat32(o,u[0]??0,!0),e.setFloat32(o+4,u[1]??0,!0),e.setFloat32(o+8,u[2]??0,!0)):(e.setFloat32(o,u.x??0,!0),e.setFloat32(o+4,u.y??0,!0),e.setFloat32(o+8,u.z??0,!0));return}if(r.type==="vec2"){let u=i;Array.isArray(u)?(e.setFloat32(o,u[0]??0,!0),e.setFloat32(o+4,u[1]??0,!0)):(e.setFloat32(o,u.x??0,!0),e.setFloat32(o+4,u.y??0,!0));return}if(r.type==="quat"){let u=i;Array.isArray(u)?(e.setFloat32(o,u[0]??0,!0),e.setFloat32(o+4,u[1]??0,!0),e.setFloat32(o+8,u[2]??0,!0),e.setFloat32(o+12,u[3]??1,!0)):(e.setFloat32(o,u.x??0,!0),e.setFloat32(o+4,u.y??0,!0),e.setFloat32(o+8,u.z??0,!0),e.setFloat32(o+12,u.w??1,!0));return}let c=xr(r.type);if(c&&r.arrayElementType){let u=i;if(!Array.isArray(u))throw new Error(`Expected array for ${r.type} field, got ${typeof i}`);let f=Ee[r.arrayElementType]??1;for(let d=0;d<u.length&&d<c.length;d++)this.writeScalar(e,o+d*f,r.arrayElementType,u[d]??0);return}this.writeScalar(e,o,r.type,i)}writeScalar(e,n,r,i){switch(r){case"bool":e.setUint8(n,i?1:0);break;case"uint8":e.setUint8(n,i);break;case"int8":e.setInt8(n,i);break;case"uint16":e.setUint16(n,i,!0);break;case"int16":e.setInt16(n,i,!0);break;case"uint32":case"entityRef":e.setUint32(n,i,!0);break;case"int32":e.setInt32(n,i,!0);break;case"f32":e.setFloat32(n,i,!0);break;default:throw new Error(`Unknown scalar type: ${r}`)}}findPlayerEntity(e,n){let r=this.options.stateSchema,i=this.playerEntities.get(n);if(i!==void 0){if(Ur(r,e,i,"Player"))return i;this.playerEntities.delete(n)}for(let o of Fr(r,e,["Player"]))if($r(r,e,o,"Player","index")===n)return this.playerEntities.set(n,o),o}spawnPlayerEntity(e,n){let r=this.options.stateSchema,i=vr(r,e);return Br(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,d]=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`,d)}else if(a==="quat"){let[u,f,d,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`,d),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);Mr(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)&&Or(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(n.length===0)return e.slice();if(this.plugins.length===0){let a=e.slice();for(let c of n){Ft(a,c.tick);let u=L(a),f=Dt(u,c.tick,c.payloads);$t(a,f)}return a}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){let c=new Uint8Array(i.buffer,o,r);Ft(c,a.tick),this.clearCommandEvents(c),this.decodePayloadsToState(c,a.payloads);for(let d of this.plugins)d.exports.apply(o),s=new Uint8Array(i.buffer);c=new Uint8Array(i.buffer,o,r);let u=L(c),f=Dt(u,a.tick,a.payloads);if($t(c,f),this.options.logStateHashForTests&&a.sync){let d=s.slice(o,o+r),g=te(d);console.log(`STATE_HASH ${JSON.stringify({tick:a.tick,hash:Ut(g)})}`)}}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 W=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 lo(t){return("moduleBytes"in t||"plugins"in t)&&"stateSchema"in t}function po(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(mo)});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 W,executions:new W,updates:new W,cacheHits:new W,cacheMisses:new W},this.currentState=Cr(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(lo(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(a=>a.tick<=e)),n.length===0)return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:!1,ticksComputed:0};let r=!1,i=null;this.currentTick!==null&&n[0].tick<this.currentTick&&(r=!0,i=this.currentTick,this.rollbackTo(n[0]));let o=n.filter(a=>this.currentTick===null||a.tick>this.currentTick);if(o.length===0)return this.currentNodeId=n[n.length-1].id,{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId,rolledBack:r,ticksComputed:0};let s=this.processTicks(o,r,i);return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:r,ticksComputed:s}}async getStats(){return{rollbacks:this.stats.rollbacks.rate(),executions:this.stats.executions.rate(),updates:this.stats.updates.rate(),cacheHits:this.stats.cacheHits.rate(),cacheMisses:this.stats.cacheMisses.rate()}}processTicks(e,n=!1,r=null){if(!this.executor)throw new Error("Executor not initialized");let i=0,o=0;for(let u=0;u<e.length;u++){let f=e[u],d=Qe(f.payloads),g=this.cache.getCached(this.currentState,f.tick,d);if(g)this.currentState=g,this.currentTick=f.tick,this.currentNodeId=f.id,o=u+1,f.sync&&this.updateSyncCheckpoint(f);else break}if(n&&r!==null&&o>0)for(let u=0;u<o;u++)e[u].tick<=r&&this.stats.cacheHits.inc();let s=e.slice(o);if(s.length===0)return 0;let a=po(s,u=>u.sync);if(a>=0){let u=s.slice(0,a+1),f=this.executor.transition(this.currentState,u),d=L(f),g=u[u.length-1];this.currentState=f,this.currentTick=g.tick,this.currentNodeId=g.id,i+=u.length,this.cache.store(f),this.recordStateSnapshot(this.currentTick,this.currentNodeId,d),this.updateSyncCheckpoint(g)}let c=a>=0?s.slice(a+1):s;if(c.length>0){let u=this.executor.transition(this.currentState,c),f=L(u),d=c[c.length-1];this.currentState=u,this.currentTick=d.tick,this.currentNodeId=d.id,i+=c.length,this.cache.store(u),this.recordStateSnapshot(this.currentTick,this.currentNodeId,f)}if(n&&r!==null)for(let u of s)u.tick<=r&&this.stats.cacheMisses.inc();return i}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 mo(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';
8122
+ var workerCode = 'var Mr=Object.defineProperty;var zr=(t,e,n)=>e in t?Mr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>zr(t,typeof e!="symbol"?e+"":e,n);var Rt=Symbol("Comlink.proxy"),Rr=Symbol("Comlink.endpoint"),Hr=Symbol("Comlink.releaseProxy"),ut=Symbol("Comlink.finalizer"),Ce=Symbol("Comlink.thrown"),Ht=t=>typeof t=="object"&&t!==null||typeof t=="function",Lr={canHandle:t=>Ht(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)}},Vr={canHandle:t=>Ht(t)&&Ce 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",Lr],["throw",Vr]]);function Gr(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(!Gr(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(j),u;try{let f=a.slice(0,-1).reduce((g,E)=>g[E],t),d=a.reduce((g,E)=>g[E],t);switch(s){case"GET":u=d;break;case"SET":f[a.slice(-1)[0]]=j(i.data.value),u=!0;break;case"APPLY":u=d.apply(f,c);break;case"CONSTRUCT":{let g=new d(...c);u=jr(g)}break;case"ENDPOINT":{let{port1:g,port2:E}=new MessageChannel;Be(t,E),u=Wr(g,[g])}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,[Ce]:0}}Promise.resolve(u).catch(f=>({value:f,[Ce]:0})).then(f=>{let[d,g]=Ue(f);e.postMessage(Object.assign(Object.assign({},d),{id:o}),g),s==="RELEASE"&&(e.removeEventListener("message",r),Vt(e),ut in t&&typeof t[ut]=="function"&&t[ut]())}).catch(f=>{let[d,g]=Ue({value:new TypeError("Unserializable return value"),[Ce]:0});e.postMessage(Object.assign(Object.assign({},d),{id:o}),g)})}),e.start&&e.start()}function Zr(t){return t.constructor.name==="MessagePort"}function Vt(t){Zr(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 Gt(t){return ie(t,new Map,{type:"RELEASE"}).then(()=>{Vt(t)})}var ve=new WeakMap,Ie="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(ve.get(t)||0)-1;ve.set(t,e),e===0&&Gt(t)});function qr(t,e){let n=(ve.get(e)||0)+1;ve.set(e,n),Ie&&Ie.register(t,e,t)}function Kr(t){Ie&&Ie.unregister(t)}function ft(t,e,n=[],r=function(){}){let i=!1,o=new Proxy(r,{get(s,a){if(Ae(i),a===Hr)return()=>{Kr(o),Gt(t),e.clear(),i=!0};if(a==="then"){if(n.length===0)return{then:()=>o};let c=ie(t,e,{type:"GET",path:n.map(u=>u.toString())}).then(j);return c.then.bind(c)}return ft(t,e,[...n,a])},set(s,a,c){Ae(i);let[u,f]=Ue(c);return ie(t,e,{type:"SET",path:[...n,a].map(d=>d.toString()),value:u},f).then(j)},apply(s,a,c){Ae(i);let u=n[n.length-1];if(u===Rr)return ie(t,e,{type:"ENDPOINT"}).then(j);if(u==="bind")return ft(t,e,n.slice(0,-1));let[f,d]=zt(c);return ie(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:f},d).then(j)},construct(s,a){Ae(i);let[c,u]=zt(a);return ie(t,e,{type:"CONSTRUCT",path:n.map(f=>f.toString()),argumentList:c},u).then(j)}});return qr(o,t),o}function Yr(t){return Array.prototype.concat.apply([],t)}function zt(t){let e=t.map(Ue);return[e.map(n=>n[0]),Yr(e.map(n=>n[1]))]}var Zt=new WeakMap;function Wr(t,e){return Zt.set(t,e),t}function jr(t){return Object.assign(t,{[Rt]:!0})}function Ue(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 j(t){switch(t.type){case"HANDLER":return Lt.get(t.name).deserialize(t.value);case"RAW":return t.value}}function ie(t,e,n,r){return new Promise(i=>{let o=Xr();e.set(o,i),t.start&&t.start(),t.postMessage(Object.assign({id:o},n),r)})}function Xr(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Jr={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:J,n:ht,Gx:Qr,Gy:ei,b:Jt}=Jr,oe=32,dt=64,v=(t="")=>{throw new Error(t)},Qt=t=>typeof t=="bigint",en=t=>typeof t=="string",ti=t=>t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array",he=(t,e)=>!ti(t)||typeof e=="number"&&e>0&&t.length!==e?v("Uint8Array expected"):t,Oe=t=>new Uint8Array(t),ni=t=>Uint8Array.from(t),tn=(t,e)=>t.toString(16).padStart(e,"0"),yt=t=>Array.from(he(t)).map(e=>tn(e,2)).join(""),V={_0:48,_9:57,A:65,F:70,a:97,f:102},qt=t=>{if(t>=V._0&&t<=V._9)return t-V._0;if(t>=V.A&&t<=V.F)return t-(V.A-10);if(t>=V.a&&t<=V.f)return t-(V.a-10)},gt=t=>{let e="hex invalid";if(!en(t))return v(e);let n=t.length,r=n/2;if(n%2)return v(e);let i=Oe(r);for(let o=0,s=0;o<r;o++,s+=2){let a=qt(t.charCodeAt(s)),c=qt(t.charCodeAt(s+1));if(a===void 0||c===void 0)return v(e);i[o]=a*16+c}return i},bt=(t,e)=>he(en(t)?gt(t):ni(he(t)),e),nn=()=>globalThis?.crypto,ri=()=>nn()?.subtle??v("crypto.subtle must be defined"),_e=(...t)=>{let e=Oe(t.reduce((r,i)=>r+he(i).length,0)),n=0;return t.forEach(r=>{e.set(r,n),n+=r.length}),e},ii=(t=oe)=>nn().getRandomValues(Oe(t)),$e=BigInt,ye=(t,e,n,r="bad number: out of range")=>Qt(t)&&e<=t&&t<n?t:v(r),h=(t,e=J)=>{let n=t%e;return n>=0n?n:e+n};var rn=(t,e)=>{(t===0n||e<=0n)&&v("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,d=o-a*c;r=n,n=u,i=s,o=a,s=f,a=d}return r===1n?h(i,e):v("no inverse")};var Kt=t=>t instanceof Q?t:v("Point expected"),on=t=>h(h(t*t)*t+Jt),Yt=t=>ye(t,0n,J),Pe=t=>ye(t,1n,J),oi=t=>ye(t,1n,ht),pt=t=>(t&1n)===0n,sn=t=>Uint8Array.of(t),si=t=>sn(pt(t)?2:3),ai=t=>{let e=on(Pe(t)),n=1n;for(let r=e,i=(J+1n)/4n;i>0n;i>>=1n)i&1n&&(n=n*r%J),r=r*r%J;return h(n*n)===e?n:v("sqrt invalid")},M=class M{constructor(e,n,r){y(this,"px");y(this,"py");y(this,"pz");this.px=Yt(e),this.py=Pe(n),this.pz=Yt(r),Object.freeze(this)}static fromBytes(e){he(e);let n,r=e[0],i=e.subarray(1),o=Wt(i,0,oe),s=e.length;if(s===oe+1&&[2,3].includes(r)){let a=ai(o),c=pt(a);pt($e(r))!==c&&(a=h(-a)),n=new M(o,a,1n)}return s===dt+1&&r===4&&(n=new M(o,Wt(i,oe,dt),1n)),n?n.assertValidity():v("bad point: not on curve")}equals(e){let{px:n,py:r,pz:i}=this,{px:o,py:s,pz:a}=Kt(e),c=h(n*a),u=h(o*i),f=h(r*a),d=h(s*i);return c===u&&f===d}is0(){return this.equals(X)}negate(){return new M(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}=Kt(e),c=0n,u=Jt,f=0n,d=0n,g=0n,E=h(u*3n),T=h(n*o),A=h(r*s),F=h(i*a),re=h(n+r),C=h(o+s);re=h(re*C),C=h(T+A),re=h(re-C),C=h(n+i);let N=h(o+a);return C=h(C*N),N=h(T+F),C=h(C-N),N=h(r+i),f=h(s+a),N=h(N*f),f=h(A+F),N=h(N-f),g=h(c*C),f=h(E*F),g=h(f+g),f=h(A-g),g=h(A+g),d=h(f*g),A=h(T+T),A=h(A+T),F=h(c*F),C=h(E*C),A=h(A+F),F=h(T-F),F=h(c*F),C=h(C+F),T=h(A*C),d=h(d+T),T=h(N*C),f=h(re*f),f=h(f-T),T=h(re*A),g=h(N*g),g=h(g+T),new M(f,d,g)}multiply(e,n=!0){if(!n&&e===0n)return X;if(oi(e),e===1n)return this;if(this.equals(se))return mi(e).p;let r=X,i=se;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(X))return{x:0n,y:0n};if(r===1n)return{x:e,y:n};let i=rn(r,J);return h(r*i)!==1n&&v("inverse invalid"),{x:h(e*i),y:h(n*i)}}assertValidity(){let{x:e,y:n}=this.toAffine();return Pe(e),Pe(n),h(n*n)===on(e)?this:v("bad point: not on curve")}toBytes(e=!0){let{x:n,y:r}=this.assertValidity().toAffine(),i=Fe(n);return e?_e(si(r),i):_e(sn(4),i,Fe(r))}static fromAffine(e){let{x:n,y:r}=e;return n===0n&&r===0n?X:new M(n,r,1n)}toHex(e){return yt(this.toBytes(e))}static fromPrivateKey(e){return se.multiply(ui(e))}static fromHex(e){return M.fromBytes(bt(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(e){return this.toBytes(e)}};y(M,"BASE"),y(M,"ZERO");var Q=M,se=new Q(Qr,ei,1n),X=new Q(0n,1n,0n);Q.BASE=se;Q.ZERO=X;var Ne=t=>$e("0x"+(yt(t)||"0")),Wt=(t,e,n)=>Ne(t.subarray(e,n)),ci=2n**256n,Fe=t=>gt(tn(ye(t,0n,ci),dt)),ui=t=>{let e=Qt(t)?t:Ne(bt(t,oe));return ye(e,1n,ht,"private key invalid 3")};var fi=t=>{t=bt(t),(t.length<oe+8||t.length>1024)&&v("expected 40-1024b");let e=h(Ne(t),ht-1n);return Fe(e+1n)};var li="SHA-256",xt={hexToBytes:gt,bytesToHex:yt,concatBytes:_e,bytesToNumberBE:Ne,numberToBytesBE:Fe,mod:h,invert:rn,hmacSha256Async:async(t,...e)=>{let n=ri(),r="HMAC",i=await n.importKey("raw",t,{name:r,hash:{name:li}},!1,["sign"]);return Oe(await n.sign(r,i,_e(...e)))},hmacSha256Sync:void 0,hashToPrivateKey:fi,randomBytes:ii};var De=8,di=256,an=Math.ceil(di/De)+1,mt=2**(De-1),pi=()=>{let t=[],e=se,n=e;for(let r=0;r<an;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},jt,Xt=(t,e)=>{let n=e.negate();return t?n:e},mi=t=>{let e=jt||(jt=pi()),n=X,r=se,i=2**De,o=i,s=$e(i-1),a=$e(De);for(let c=0;c<an;c++){let u=Number(t&s);t>>=a,u>mt&&(u-=o,t+=1n);let f=c*mt,d=f,g=f+Math.abs(u)-1,E=c%2!==0,T=u<0;u===0?r=r.add(Xt(E,e[d])):n=n.add(Xt(T,e[g]))}return{p:n,f:r}};function yi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function cn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ce(t,...e){if(!yi(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 un(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");cn(t.outputLen),cn(t.blockLen)}function ue(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 fn(t,e){ce(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ee(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Me(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function D(t,e){return t<<32-e|t>>>e}function gi(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=gi(t)),ce(t),t}var ae=class{};function ln(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 bi(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 dn(t,e,n){return t&e^~t&n}function pn(t,e,n){return t&e^t&n^e&n}var ze=class extends ae{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=Me(this.buffer)}update(e){ue(this),e=ge(e),ce(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=Me(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){ue(this),fn(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;n[s++]=128,ee(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)n[d]=0;bi(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=Me(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 d=0;d<u;d++)a.setUint32(4*d,f[d],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()}},G=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xi=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),Re=class extends ze{constructor(e=32){super(64,e,8,!1),this.A=G[0]|0,this.B=G[1]|0,this.C=G[2]|0,this.D=G[3]|0,this.E=G[4]|0,this.F=G[5]|0,this.G=G[6]|0,this.H=G[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 d=0;d<16;d++,n+=4)q[d]=e.getUint32(n,!1);for(let d=16;d<64;d++){let g=q[d-15],E=q[d-2],T=D(g,7)^D(g,18)^g>>>3,A=D(E,17)^D(E,19)^E>>>10;q[d]=A+q[d-7]+T+q[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let d=0;d<64;d++){let g=D(a,6)^D(a,11)^D(a,25),E=f+g+dn(a,c,u)+xi[d]+q[d]|0,A=(D(r,2)^D(r,13)^D(r,22))+pn(r,i,o)|0;f=u,u=c,c=a,a=s+E|0,s=o,o=i,i=r,r=E+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(){ee(q)}destroy(){this.set(0,0,0,0,0,0,0,0),ee(this.buffer)}};var te=ln(()=>new Re);var wt=te;var He=class extends ae{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,un(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),ee(o)}update(e){return ue(this),this.iHash.update(e),this}digestInto(e){ue(this),ce(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 He(t,e).update(n).digest();St.create=(t,e)=>new He(t,e);var wi=["string","number","bigint","symbol"],Si=["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 mn(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(wi.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(Ei(t))return"Buffer";let n=Ti(t);return n||"Object"}function Ei(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function Ti(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(Si.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 fe=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ki=new TextDecoder,Ai=new TextEncoder;function Le(t){return fe&&globalThis.Buffer.isBuffer(t)}function Et(t){return t instanceof Uint8Array?Le(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var bn=fe?(t,e,n)=>n-e>64?globalThis.Buffer.from(t.subarray(e,n)).toString("utf8"):yn(t,e,n):(t,e,n)=>n-e>64?ki.decode(t.subarray(e,n)):yn(t,e,n),xn=fe?t=>t.length>64?globalThis.Buffer.from(t):hn(t):t=>t.length>64?Ai.encode(t):hn(t),z=t=>Uint8Array.from(t),le=fe?(t,e,n)=>Le(t)?new Uint8Array(t.subarray(e,n)):t.slice(e,n):(t,e,n)=>t.slice(e,n),wn=fe?(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},Sn=fe?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ve(t,e){if(Le(t)&&Le(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 hn(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 yn(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 Ci(r)}var gn=4096;function Ci(t){let e=t.length;if(e<=gn)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=gn));return n}var vi=256,be=class{constructor(e=vi){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=Sn(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=le(r,0,this.cursor)}else n=wn(this.chunks,this.cursor);return e&&this.reset(),n}};var b="CBOR decode error:",Tt="CBOR encode error:",xe=[];xe[23]=1;xe[24]=2;xe[25]=3;xe[26]=5;xe[27]=9;function Z(t,e,n){if(t.length-e<n)throw new Error(`${b} not enough data for type`)}var S=[24,256,65536,4294967296,BigInt("18446744073709551616")];function I(t,e,n){Z(t,e,1);let r=t[e];if(n.strict===!0&&r<S[0])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function U(t,e,n){Z(t,e,2);let r=t[e]<<8|t[e+1];if(n.strict===!0&&r<S[1])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function B(t,e,n){Z(t,e,4);let r=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(n.strict===!0&&r<S[2])throw new Error(`${b} integer encoded in more bytes than necessary (strict decode)`);return r}function P(t,e,n){Z(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<S[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 En(t,e,n,r){return new m(l.uint,I(t,e+1,r),2)}function Tn(t,e,n,r){return new m(l.uint,U(t,e+1,r),3)}function kn(t,e,n,r){return new m(l.uint,B(t,e+1,r),5)}function An(t,e,n,r){return new m(l.uint,P(t,e+1,r),9)}function _(t,e){return k(t,0,e.value)}function k(t,e,n){if(n<S[0]){let r=Number(n);t.push([e|r])}else if(n<S[1]){let r=Number(n);t.push([e|24,r])}else if(n<S[2]){let r=Number(n);t.push([e|25,r>>>8,r&255])}else if(n<S[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<S[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`)}}_.encodedSize=function(e){return k.encodedSize(e.value)};k.encodedSize=function(e){return e<S[0]?1:e<S[1]?2:e<S[2]?3:e<S[3]?5:9};_.compareTokens=function(e,n){return e.value<n.value?-1:e.value>n.value?1:0};function Cn(t,e,n,r){return new m(l.negint,-1-I(t,e+1,r),2)}function vn(t,e,n,r){return new m(l.negint,-1-U(t,e+1,r),3)}function In(t,e,n,r){return new m(l.negint,-1-B(t,e+1,r),5)}var kt=BigInt(-1),Un=BigInt(1);function Bn(t,e,n,r){let i=P(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;k(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<S[0]?1:r<S[1]?2:r<S[2]?3:r<S[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){Z(t,e,n+r);let i=le(t,e+n,e+n+r);return new m(l.bytes,i,n+r)}function Pn(t,e,n,r){return we(t,e,1,n)}function _n(t,e,n,r){return we(t,e,2,I(t,e+1,r))}function $n(t,e,n,r){return we(t,e,3,U(t,e+1,r))}function Fn(t,e,n,r){return we(t,e,5,B(t,e+1,r))}function Dn(t,e,n,r){let i=P(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?xn(t.value):t.value),t.encodedBytes}function de(t,e){let n=Ze(e);k(t,e.type.majorEncoded,n.length),t.push(n)}de.encodedSize=function(e){let n=Ze(e);return k.encodedSize(n.length)+n.length};de.compareTokens=function(e,n){return Ui(Ze(e),Ze(n))};function Ui(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;Z(t,e,o);let s=new m(l.string,bn(t,e+n,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=le(t,e+n,e+o)),s}function On(t,e,n,r){return Se(t,e,1,n,r)}function Nn(t,e,n,r){return Se(t,e,2,I(t,e+1,r),r)}function Mn(t,e,n,r){return Se(t,e,3,U(t,e+1,r),r)}function zn(t,e,n,r){return Se(t,e,5,B(t,e+1,r),r)}function Rn(t,e,n,r){let i=P(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 Hn=de;function pe(t,e,n,r){return new m(l.array,r,n)}function Ln(t,e,n,r){return pe(t,e,1,n)}function Vn(t,e,n,r){return pe(t,e,2,I(t,e+1,r))}function Gn(t,e,n,r){return pe(t,e,3,U(t,e+1,r))}function Zn(t,e,n,r){return pe(t,e,5,B(t,e+1,r))}function qn(t,e,n,r){let i=P(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer array lengths not supported`);return pe(t,e,9,i)}function Kn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return pe(t,e,1,1/0)}function qe(t,e){k(t,l.array.majorEncoded,e.value)}qe.compareTokens=_.compareTokens;qe.encodedSize=function(e){return k.encodedSize(e.value)};function me(t,e,n,r){return new m(l.map,r,n)}function Yn(t,e,n,r){return me(t,e,1,n)}function Wn(t,e,n,r){return me(t,e,2,I(t,e+1,r))}function jn(t,e,n,r){return me(t,e,3,U(t,e+1,r))}function Xn(t,e,n,r){return me(t,e,5,B(t,e+1,r))}function Jn(t,e,n,r){let i=P(t,e+1,r);if(typeof i=="bigint")throw new Error(`${b} 64-bit integer map lengths not supported`);return me(t,e,9,i)}function Qn(t,e,n,r){if(r.allowIndefinite===!1)throw new Error(`${b} indefinite length items not allowed`);return me(t,e,1,1/0)}function Ke(t,e){k(t,l.map.majorEncoded,e.value)}Ke.compareTokens=_.compareTokens;Ke.encodedSize=function(e){return k.encodedSize(e.value)};function er(t,e,n,r){return new m(l.tag,n,1)}function tr(t,e,n,r){return new m(l.tag,I(t,e+1,r),2)}function nr(t,e,n,r){return new m(l.tag,U(t,e+1,r),3)}function rr(t,e,n,r){return new m(l.tag,B(t,e+1,r),5)}function ir(t,e,n,r){return new m(l.tag,P(t,e+1,r),9)}function Ye(t,e){k(t,l.tag.majorEncoded,e.value)}Ye.compareTokens=_.compareTokens;Ye.encodedSize=function(e){return k.encodedSize(e.value)};var Di=20,Oi=21,Ni=22,Mi=23;function or(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 sr(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 ar(t,e,n,r){return At(Ct(t,e+1),3,r)}function cr(t,e,n,r){return At(vt(t,e+1),5,r)}function ur(t,e,n,r){return At(pr(t,e+1),9,r)}function We(t,e,n){let r=e.value;if(r===!1)t.push([l.float.majorEncoded|Di]);else if(r===!0)t.push([l.float.majorEncoded|Oi]);else if(r===null)t.push([l.float.majorEncoded|Ni]);else if(r===void 0)t.push([l.float.majorEncoded|Mi]);else{let i,o=!1;(!n||n.float64!==!0)&&(lr(r),i=Ct(O,1),r===i||Number.isNaN(r)?(O[0]=249,t.push(O.slice(0,3)),o=!0):(dr(r),i=vt(O,1),r===i&&(O[0]=250,t.push(O.slice(0,5)),o=!0))),o||(zi(r),i=pr(O,1),O[0]=251,t.push(O.slice(0,9)))}}We.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){lr(r);let i=Ct(O,1);if(r===i||Number.isNaN(r))return 3;if(dr(r),i=vt(O,1),r===i)return 5}return 9};var fr=new ArrayBuffer(9),$=new DataView(fr,1),O=new Uint8Array(fr,0);function lr(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 Ct(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 dr(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 zi(t){$.setFloat64(0,t,!1)}function pr(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)}We.compareTokens=_.compareTokens;function x(t,e,n){throw new Error(`${b} encountered invalid minor (${n}) for major ${t[e]>>>5}`)}function je(t){return()=>{throw new Error(`${b} ${t}`)}}var p=[];for(let t=0;t<=23;t++)p[t]=x;p[24]=En;p[25]=Tn;p[26]=kn;p[27]=An;p[28]=x;p[29]=x;p[30]=x;p[31]=x;for(let t=32;t<=55;t++)p[t]=x;p[56]=Cn;p[57]=vn;p[58]=In;p[59]=Bn;p[60]=x;p[61]=x;p[62]=x;p[63]=x;for(let t=64;t<=87;t++)p[t]=Pn;p[88]=_n;p[89]=$n;p[90]=Fn;p[91]=Dn;p[92]=x;p[93]=x;p[94]=x;p[95]=je("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)p[t]=On;p[120]=Nn;p[121]=Mn;p[122]=zn;p[123]=Rn;p[124]=x;p[125]=x;p[126]=x;p[127]=je("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)p[t]=Ln;p[152]=Vn;p[153]=Gn;p[154]=Zn;p[155]=qn;p[156]=x;p[157]=x;p[158]=x;p[159]=Kn;for(let t=160;t<=183;t++)p[t]=Yn;p[184]=Wn;p[185]=jn;p[186]=Xn;p[187]=Jn;p[188]=x;p[189]=x;p[190]=x;p[191]=Qn;for(let t=192;t<=215;t++)p[t]=er;p[216]=tr;p[217]=nr;p[218]=rr;p[219]=ir;p[220]=x;p[221]=x;p[222]=x;p[223]=x;for(let t=224;t<=243;t++)p[t]=je("simple values are not supported");p[244]=x;p[245]=x;p[246]=x;p[247]=or;p[248]=je("simple values are not supported");p[249]=ar;p[250]=cr;p[251]=ur;p[252]=x;p[253]=x;p[254]=x;p[255]=sr;var R=[];for(let t=0;t<24;t++)R[t]=new m(l.uint,t,1);for(let t=-1;t>=-24;t--)R[31-t]=new m(l.negint,t,1);R[64]=new m(l.bytes,new Uint8Array(0),1);R[96]=new m(l.string,"",1);R[128]=new m(l.array,0,1);R[160]=new m(l.map,0,1);R[244]=new m(l.false,!1,1);R[245]=new m(l.true,!0,1);R[246]=new m(l.null,null,1);function mr(t){switch(t.type){case l.false:return z([244]);case l.true:return z([245]);case l.null:return z([246]);case l.bytes:return t.value.length?void 0:z([64]);case l.string:return t.value===""?z([96]):void 0;case l.array:return t.value===0?z([128]):void 0;case l.map:return t.value===0?z([160]):void 0;case l.uint:return t.value<24?z([Number(t.value)]):void 0;case l.negint:if(t.value>=-24)return z([31-Number(t.value)])}}var yr=Object.freeze({float64:!0,mapSorter:Gi,quickEncodeToken:mr});function Hi(){let t=[];return t[l.uint.major]=_,t[l.negint.major]=Ge,t[l.bytes.major]=de,t[l.string.major]=Hn,t[l.array.major]=qe,t[l.map.major]=Ke,t[l.tag.major]=Ye,t[l.float.major]=We,t}var Li=Hi(),It=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(`${Tt} object contains circular references`);return new t(n,e)}},K={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)},Y={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?K.true:K.false},null(t,e,n,r){return K.null},undefined(t,e,n,r){return K.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?[K.emptyArray,new m(l.break)]:K.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?[K.emptyMap,new m(l.break)]:K.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 Vi(a,n),n.addBreakTokens?[new m(l.map,s),a,new m(l.break)]:[new m(l.map,s),a]}};Y.Map=Y.Object;Y.Buffer=Y.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Y[`${t}Array`]=Y.DataView;function Xe(t,e={},n){let r=mn(t),i=e&&e.typeEncoders&&e.typeEncoders[r]||Y[r];if(typeof i=="function"){let s=i(t,r,e,n);if(s!=null)return s}let o=Y[r];if(!o)throw new Error(`${Tt} unsupported type: ${r}`);return o(t,r,e,n)}function Vi(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Gi(t,e){if(t[0]instanceof m&&e[0]instanceof m){let n=t[0],r=e[0];return n._keyBytes||(n._keyBytes=hr(n.value)),r._keyBytes||(r._keyBytes=hr(r.value)),Ve(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function hr(t){return Zi(t,Li,yr)}function gr(t,e,n,r){if(Array.isArray(e))for(let i of e)gr(t,i,n,r);else n[e.type.major](t,e,r)}function Zi(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 It.reset(),gr(It,r,e,n),It.toBytes(!0)}xt.hmacSha256Sync=(t,...e)=>St(wt,t,xt.concatBytes(...e));var Yi=32;function Qe(t){if(t.length===0)return new Uint8Array(Yi);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)}function Ut(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Ee={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},Bt={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},Wi=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","entityRef","f32"]),br=new Set(["bool","uint8","int8","uint16","int16","uint32","int32","f32"]);function xr(t){let e=t.match(/^(\\w+)\\[(\\d+)\\]$/);if(!e||!e[1]||!e[2])return null;let n=e[1],r=parseInt(e[2],10);return Wi.has(n)?{elementType:n,length:r}:null}var wr=1297369412;function Sr(t){let e=t.match(/^vec3\\[(\\d+)\\]$/);return e?.[1]?{elementType:"vec3",length:parseInt(e[1],10)}:null}function Er(t){let e=t.match(/^vec2\\[(\\d+)\\]$/);return e?.[1]?{elementType:"vec2",length:parseInt(e[1],10)}:null}function Tr(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(!br.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 ji(t){let e=[],n=[],r=new Map,i=new Map;for(let o of t.controls){let s=Tr(o.type),a={name:o.name,type:o.type,size:o.size,offset:0,options:o.options?[...o.options]:void 0};s&&(a.arrayLength=s.length,a.arrayElementType=s.elementType);let c={name:o.name,index:o.index,field:a,hint:o.hint,retain:o.retain};e.push(c),r.set(o.name,c)}for(let o of t.commands){let s=[];for(let c of o.args){let u=Tr(c.type),f={name:c.name,type:c.type,size:c.size,offset:c.offset};u&&(f.arrayLength=u.length,f.arrayElementType=u.elementType),s.push(f)}let a={name:o.name,index:o.index,args:s,totalSize:o.totalSize};n.push(a),i.set(o.name,a)}return{controls:e,commands:n,controlByName:r,commandByName:i}}function Pt(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);Pt(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=Bt[r.arrayElementType];for(let a=0;a<Math.min(o.length,r.arrayLength);a++)Pt(e,n+a*s,r.arrayElementType,o[a])}else Pt(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=Bt[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 kr(t){let e=ji(t);return{create(){return new et(e)},decode(n){return et.decode(e,n)},get schema(){return e}}}function Ar(t,e){return((e&65535)<<16|t&65535)>>>0}function Te(t){return t&65535}function to(t){return t>>>16&65535}function L(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 Ft(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),te(r)}function Dt(t,e,n){return rt(t,e,Qe(n))}function Ot(t){return te(t)}function Cr(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 vr(t,e){return t.entityTableOffset+e*t.entityRecordSize}function Nt(t,e,n){let r=vr(t,n);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(r,!0)}function no(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(4,!0)}function ro(t,e){new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(4,e,!0)}function io(t,e){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t.freeStackOffset,!0)}function oo(t,e,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t.freeStackOffset,n,!0)}function so(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=io(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 oo(t,e,r-1),o}function Ir(t,e){let n=so(t,e),r=Nt(t,e,n);return ro(e,no(e)+1),Ar(n,r)}function it(t,e,n){if(n===4294967295)return!1;let r=Te(n);if(r>=t.maxEntities)return!1;let i=to(n);return Nt(t,e,r)===i}function Mt(t,e,n){if(n<0)throw new Error("Singleton components do not have component bitmask entries");let r=vr(t,e)+2,i=Math.floor(n/8),o=n%8;return{byteOffset:r+i,bitIndex:o}}function Ur(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=Te(n),{byteOffset:s,bitIndex:a}=Mt(t,o,i.index);return(e[s]&1<<a)!==0}function Br(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=Te(n),{byteOffset:s,bitIndex:a}=Mt(t,o,i.index);e[s]=(e[s]??0)|1<<a}function Pr(t,e,n,r){let i=Te(e);return n.storageOffset+i*n.size+r.offset}function ao(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 _r(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 co(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 uo(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 fo(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 $r(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=Pr(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=Ee[a.arrayElementType];if(f===void 0)throw new Error(`Unknown array element type: ${a.arrayElementType}`);c+=o*f,u=a.arrayElementType}return ao(e,c,u)}function w(t,e,n,r,i,o,s){if(!it(t,e,n)){let d=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${d} is not alive`)}let a=t.componentByName.get(r);if(!a)throw new Error(`Unknown component: \'${r}\'`);if(!nt(t,e,n,a)){let d=n.toString(16).padStart(8,"0").toUpperCase();throw new Error(`Entity 0x${d} does not have component \'${r}\'`)}let c=a.fields.find(d=>d.name===i);if(!c)throw new Error(`Unknown field \'${i}\' in component \'${r}\'`);let u=Pr(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 d=Ee[c.arrayElementType];if(d===void 0)throw new Error(`Unknown array element type: ${c.arrayElementType}`);u+=s*d,f=c.arrayElementType}_r(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=Te(n),{byteOffset:o,bitIndex:s}=Mt(t,i,r.index);return(e[o]&1<<s)!==0}function Fr(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=Nt(t,e,a),u=Ar(a,c),f=!0;for(let d of i)if(!nt(t,e,u,d)){f=!1;break}if(f){for(let d of o)if(nt(t,e,u,d)){f=!1;break}f&&(yield u)}}}return s()}function Dr(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 Or(t,e,n){let r=Dr(t,n);new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(r.storageOffset,0,!0)}function Nr(t,e,n,r){let i=Dr(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"?co(e,f,u):c.type==="vec3"?uo(e,f,u):c.type==="quat"?fo(e,f,u):_r(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=L(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=L(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=L(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 ke=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,"initDataPtr",null);y(this,"initDataSize",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)/ke);if(this.options.debug){let u=(s+c*ke)/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=kr(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/ke)*ke;return c+f},0),i=1024*1024*5,o=this.stateSize+i+r,s=Math.ceil(o/ke);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),d=await WebAssembly.instantiate(f,a);if(typeof d.exports.apply!="function")throw new Error(`Plugin "${c.name}" missing required apply() export`);this.plugins.push({name:c.name,instance:d,exports:d.exports})}if(this.statePtr=this.hostAlloc(this.stateSize,8),this.options.initDataSchema&&this.options.initDataSchema.items.length>0){let c=this.options.initDataSchema,u=this.options.initData;if(!u)throw new Error("initData is required when initDataSchema is provided");this.initDataSize=c.totalSize,this.initDataPtr=this.hostAlloc(this.initDataSize,8),this.writeInitData(c,u);for(let f of this.plugins){let d=f.instance.exports.set_init_data_ptr;typeof d=="function"&&d(this.initDataPtr)}this.options.debug&&console.log(`[mt] Init data allocated at ${this.initDataPtr}, size ${this.initDataSize} bytes`)}return this.markArenaReset(),this}writeInitData(e,n){let r=this.memory;if(!r||this.initDataPtr===null)throw new Error("Memory or init data pointer not initialized");let i=new DataView(r.buffer,this.initDataPtr,e.totalSize);i.setUint32(0,wr,!0),i.setUint32(4,e.totalSize,!0);for(let o of e.items){let s=n[o.name];if(s===void 0)throw new Error(`Missing required init data item: ${o.name}`);o.isBlob?this.writeInitDataBlob(i,o,s):this.writeInitDataCompound(i,o,s)}}writeInitDataBlob(e,n,r){let i;if(typeof r=="string"){let s=atob(r);i=new Uint8Array(s.length);for(let a=0;a<s.length;a++)i[a]=s.charCodeAt(a)}else if(r instanceof Uint8Array)i=r;else throw new Error(`Init data blob "${n.name}" must be a base64 string or Uint8Array`);if(i.length>n.blobMaxSize)throw new Error(`Init data blob "${n.name}" exceeds maxSize: ${i.length} > ${n.blobMaxSize}`);let o=n.storageOffset;e.setUint32(o,i.length,!0);for(let s=0;s<i.length;s++)e.setUint8(o+4+s,i[s])}writeInitDataCompound(e,n,r){for(let i of n.fields){let o=r[i.name];if(o===void 0)throw new Error(`Missing required init data field: ${n.name}.${i.name}`);this.writeInitDataField(e,n.storageOffset,i,o)}}writeInitDataField(e,n,r,i){let o=n+r.offset,s=Sr(r.type);if(s){let u=i;if(!Array.isArray(u))throw new Error(`Expected array for vec3[] field, got ${typeof i}`);for(let f=0;f<u.length&&f<s.length;f++){let d=u[f];Array.isArray(d)?(e.setFloat32(o+f*12,d[0]??0,!0),e.setFloat32(o+f*12+4,d[1]??0,!0),e.setFloat32(o+f*12+8,d[2]??0,!0)):(e.setFloat32(o+f*12,d.x??0,!0),e.setFloat32(o+f*12+4,d.y??0,!0),e.setFloat32(o+f*12+8,d.z??0,!0))}return}let a=Er(r.type);if(a){let u=i;if(!Array.isArray(u))throw new Error(`Expected array for vec2[] field, got ${typeof i}`);for(let f=0;f<u.length&&f<a.length;f++){let d=u[f];Array.isArray(d)?(e.setFloat32(o+f*8,d[0]??0,!0),e.setFloat32(o+f*8+4,d[1]??0,!0)):(e.setFloat32(o+f*8,d.x??0,!0),e.setFloat32(o+f*8+4,d.y??0,!0))}return}if(r.type==="vec3"){let u=i;Array.isArray(u)?(e.setFloat32(o,u[0]??0,!0),e.setFloat32(o+4,u[1]??0,!0),e.setFloat32(o+8,u[2]??0,!0)):(e.setFloat32(o,u.x??0,!0),e.setFloat32(o+4,u.y??0,!0),e.setFloat32(o+8,u.z??0,!0));return}if(r.type==="vec2"){let u=i;Array.isArray(u)?(e.setFloat32(o,u[0]??0,!0),e.setFloat32(o+4,u[1]??0,!0)):(e.setFloat32(o,u.x??0,!0),e.setFloat32(o+4,u.y??0,!0));return}if(r.type==="quat"){let u=i;Array.isArray(u)?(e.setFloat32(o,u[0]??0,!0),e.setFloat32(o+4,u[1]??0,!0),e.setFloat32(o+8,u[2]??0,!0),e.setFloat32(o+12,u[3]??1,!0)):(e.setFloat32(o,u.x??0,!0),e.setFloat32(o+4,u.y??0,!0),e.setFloat32(o+8,u.z??0,!0),e.setFloat32(o+12,u.w??1,!0));return}let c=xr(r.type);if(c&&r.arrayElementType){let u=i;if(!Array.isArray(u))throw new Error(`Expected array for ${r.type} field, got ${typeof i}`);let f=Ee[r.arrayElementType]??1;for(let d=0;d<u.length&&d<c.length;d++)this.writeScalar(e,o+d*f,r.arrayElementType,u[d]??0);return}this.writeScalar(e,o,r.type,i)}writeScalar(e,n,r,i){switch(r){case"bool":e.setUint8(n,i?1:0);break;case"uint8":e.setUint8(n,i);break;case"int8":e.setInt8(n,i);break;case"uint16":e.setUint16(n,i,!0);break;case"int16":e.setInt16(n,i,!0);break;case"uint32":case"entityRef":e.setUint32(n,i,!0);break;case"int32":e.setInt32(n,i,!0);break;case"f32":e.setFloat32(n,i,!0);break;default:throw new Error(`Unknown scalar type: ${r}`)}}findPlayerEntity(e,n){let r=this.options.stateSchema,i=this.playerEntities.get(n);if(i!==void 0){if(Ur(r,e,i,"Player"))return i;this.playerEntities.delete(n)}for(let o of Fr(r,e,["Player"]))if($r(r,e,o,"Player","index")===n)return this.playerEntities.set(n,o),o}spawnPlayerEntity(e,n){let r=this.options.stateSchema,i=Ir(r,e);return Br(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,d]=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`,d)}else if(a==="quat"){let[u,f,d,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`,d),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);Nr(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)&&Or(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(n.length===0)return e.slice();if(this.plugins.length===0){let a=e.slice();for(let c of n){Ft(a,c.tick);let u=L(a),f=Dt(u,c.tick,c.payloads);$t(a,f)}return a}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){let c=new Uint8Array(i.buffer,o,r);Ft(c,a.tick),this.clearCommandEvents(c),this.decodePayloadsToState(c,a.payloads);for(let d of this.plugins)d.exports.apply(o),s=new Uint8Array(i.buffer);c=new Uint8Array(i.buffer,o,r);let u=L(c),f=Dt(u,a.tick,a.payloads);if($t(c,f),this.options.logStateHashForTests&&a.sync){let d=s.slice(o,o+r),g=te(d);console.log(`STATE_HASH ${JSON.stringify({tick:a.tick,hash:Ut(g)})}`)}}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 W=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 lo(t){return("moduleBytes"in t||"plugins"in t)&&"stateSchema"in t}function po(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(mo)});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 W,executions:new W,updates:new W,cacheHits:new W,cacheMisses:new W},this.currentState=Cr(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(lo(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(a=>a.tick<=e)),n.length===0)return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:!1,ticksComputed:0};let r=!1,i=null;this.currentTick!==null&&n[0].tick<this.currentTick&&(r=!0,i=this.currentTick,this.rollbackTo(n[0]));let o=n.filter(a=>this.currentTick===null||a.tick>this.currentTick);if(o.length===0)return this.currentNodeId=n[n.length-1].id,{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId,rolledBack:r,ticksComputed:0};let s=this.processTicks(o,r,i);return{state:this.currentState,tick:this.currentTick,nodeId:this.currentNodeId??"",rolledBack:r,ticksComputed:s}}async getStats(){return{rollbacks:this.stats.rollbacks.rate(),executions:this.stats.executions.rate(),updates:this.stats.updates.rate(),cacheHits:this.stats.cacheHits.rate(),cacheMisses:this.stats.cacheMisses.rate()}}processTicks(e,n=!1,r=null){if(!this.executor)throw new Error("Executor not initialized");let i=0,o=0;for(let u=0;u<e.length;u++){let f=e[u],d=Qe(f.payloads),g=this.cache.getCached(this.currentState,f.tick,d);if(g)this.currentState=g,this.currentTick=f.tick,this.currentNodeId=f.id,o=u+1,f.sync&&this.updateSyncCheckpoint(f);else break}if(n&&r!==null&&o>0)for(let u=0;u<o;u++)e[u].tick<=r&&this.stats.cacheHits.inc();let s=e.slice(o);if(s.length===0)return 0;let a=po(s,u=>u.sync);if(a>=0){let u=s.slice(0,a+1),f=this.executor.transition(this.currentState,u),d=L(f),g=u[u.length-1];this.currentState=f,this.currentTick=g.tick,this.currentNodeId=g.id,i+=u.length,this.cache.store(f),this.recordStateSnapshot(this.currentTick,this.currentNodeId,d),this.updateSyncCheckpoint(g)}let c=a>=0?s.slice(a+1):s;if(c.length>0){let u=this.executor.transition(this.currentState,c),f=L(u),d=c[c.length-1];this.currentState=u,this.currentTick=d.tick,this.currentNodeId=d.id,i+=c.length,this.cache.store(u),this.recordStateSnapshot(this.currentTick,this.currentNodeId,f)}if(n&&r!==null)for(let u of s)u.tick<=r&&this.stats.cacheMisses.inc();return i}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 mo(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';
8093
8123
  function Worker() {
8094
8124
  const blob = new Blob([workerCode], { type: "text/javascript" });
8095
8125
  const url = URL.createObjectURL(blob);
@@ -8481,13 +8511,42 @@ function warnUnexpected3(err2) {
8481
8511
  var OPTIMISTIC_NONE = "NONE";
8482
8512
  var OPTIMISTIC_LOCAL = "LOCAL";
8483
8513
  var OPTIMISTIC_ALL = "ALL";
8514
+ var InputSender = class {
8515
+ channel;
8516
+ privateKey;
8517
+ publicKey;
8518
+ peerMesh;
8519
+ constructor(channel, privateKey, peerMesh) {
8520
+ this.channel = channel;
8521
+ this.privateKey = privateKey;
8522
+ this.publicKey = pubKeyFromPrivate(privateKey);
8523
+ this.peerMesh = peerMesh;
8524
+ }
8525
+ // Send a signed input to the session
8526
+ sendInput(input) {
8527
+ this.channel.sendSignedInput(input, this.privateKey).then((encodedBytes) => {
8528
+ if (this.peerMesh && encodedBytes) {
8529
+ this.peerMesh.broadcast(encodedBytes);
8530
+ }
8531
+ }).catch((err2) => {
8532
+ console.error("error sending input", err2);
8533
+ });
8534
+ }
8535
+ // Get the player's public key (identity) as hex string
8536
+ get currentPlayerId() {
8537
+ return bytesToHex2(this.publicKey);
8538
+ }
8539
+ // Get the raw public key bytes
8540
+ getPublicKey() {
8541
+ return this.publicKey;
8542
+ }
8543
+ };
8484
8544
  var Session = class {
8485
8545
  channel = null;
8486
8546
  rollback = null;
8487
8547
  config;
8488
8548
  initializing = false;
8489
8549
  initialized = false;
8490
- playerKey;
8491
8550
  compiledStateSchema;
8492
8551
  rollbackWorkerUrl = null;
8493
8552
  rollbackWorker = null;
@@ -8497,6 +8556,7 @@ var Session = class {
8497
8556
  debug;
8498
8557
  autoConnect;
8499
8558
  connectionTimeoutMs;
8559
+ joinTimeoutMs;
8500
8560
  tickLag;
8501
8561
  logSyncTicks;
8502
8562
  schema;
@@ -8519,16 +8579,16 @@ var Session = class {
8519
8579
  participantsSorted = Object.freeze([]);
8520
8580
  // WebRTC P2P mesh for optimistic input delivery
8521
8581
  peerMesh = null;
8522
- enableP2P;
8523
8582
  optimisticStrategy;
8524
8583
  predictedHeadMax;
8584
+ manifestURL;
8525
8585
  constructor(options) {
8526
- this.playerKey = options.playerKey;
8527
8586
  this.serverCertHash = options.serverCertHash;
8528
8587
  this.validatorKeys = options.validatorKeys;
8529
8588
  this.debug = options.debug;
8530
8589
  this.autoConnect = options.autoConnect;
8531
8590
  this.connectionTimeoutMs = options.connectionTimeoutMs;
8591
+ this.joinTimeoutMs = options.joinTimeoutMs;
8532
8592
  this.plugins = options.plugins;
8533
8593
  this.schema = options.schema;
8534
8594
  this.initData = options.initData;
@@ -8562,9 +8622,9 @@ var Session = class {
8562
8622
  this.maxTicksPerBatch = options.maxTicksPerBatch ?? 256;
8563
8623
  this.renderer = options.renderer;
8564
8624
  this.enableStatsCollection = options.enableStatsCollection ?? false;
8565
- this.enableP2P = options.enableP2P ?? false;
8566
8625
  this.optimisticStrategy = options.optimisticStrategy;
8567
8626
  this.predictedHeadMax = options.predictedHeadMax ?? 0;
8627
+ this.manifestURL = options.manifestURL;
8568
8628
  }
8569
8629
  async init() {
8570
8630
  if (this.initializing || this.initialized) return;
@@ -8577,14 +8637,14 @@ var Session = class {
8577
8637
  this.channel = new Channel({
8578
8638
  connectionURL,
8579
8639
  serverCertHash: this.serverCertHash,
8580
- privateKey: this.playerKey,
8581
8640
  relayPubKey: this.validatorKeys?.[0],
8582
8641
  debug: this.debug,
8583
8642
  autoConnect: this.autoConnect,
8584
8643
  connectionTimeoutMs: this.connectionTimeoutMs,
8585
8644
  logSyncTicks: this.logSyncTicks,
8586
8645
  optimisticStrategy: this.optimisticStrategy,
8587
- predictedHeadMax: this.predictedHeadMax
8646
+ predictedHeadMax: this.predictedHeadMax,
8647
+ manifestURL: this.manifestURL
8588
8648
  });
8589
8649
  await this.channel.expose(channelPort1);
8590
8650
  await this.channel.setOnParticipantJoined(this.onParticipantJoined);
@@ -8609,20 +8669,6 @@ var Session = class {
8609
8669
  await this.rollback.setLog(transfer(channelPort2, [channelPort2]));
8610
8670
  await this.rollback.setOnStateUpdate(proxy(this.onStateUpdate));
8611
8671
  this.latestState = await this.rollback.init();
8612
- if (this.enableP2P) {
8613
- const publicKey = pubKeyFromPrivate(this.playerKey);
8614
- this.peerMesh = new PeerMesh({
8615
- sessionConfig: this.config,
8616
- publicKey,
8617
- genesisHash,
8618
- onPeerInput: (input, signerPubKey) => {
8619
- if (this.optimisticStrategy === OPTIMISTIC_ALL) {
8620
- this.channel?.addOptimisticInput(input, signerPubKey).catch(warnUnexpected4);
8621
- }
8622
- }
8623
- });
8624
- this.peerMesh.start().catch(warnUnexpected4);
8625
- }
8626
8672
  this.initialized = true;
8627
8673
  this.initializing = false;
8628
8674
  this.renderer.init(this);
@@ -8630,9 +8676,6 @@ var Session = class {
8630
8676
  await this.collectStats();
8631
8677
  }
8632
8678
  }
8633
- getCurrentPlayerId() {
8634
- return bytesToHex2(pubKeyFromPrivate(this.playerKey));
8635
- }
8636
8679
  getParticipants() {
8637
8680
  return this.participantsSorted;
8638
8681
  }
@@ -8656,17 +8699,57 @@ var Session = class {
8656
8699
  getInputBindings() {
8657
8700
  return this.inputCodec;
8658
8701
  }
8659
- // sendInput queues an input to be sent to the session
8660
- // Also broadcasts to P2P peers if enabled (best effort)
8661
- sendInput(input) {
8702
+ // join the session as a participant with the given private key
8703
+ // Returns an InputSender for sending inputs
8704
+ // Waits for join confirmation before returning (participant must appear in list)
8705
+ async join(privateKey, options) {
8662
8706
  if (!this.channel) {
8663
8707
  throw new Error("channel not initialized, call init() first");
8664
8708
  }
8665
- this.channel.sendSignedInput(input).then((encodedBytes) => {
8666
- if (this.peerMesh && encodedBytes) {
8667
- this.peerMesh.broadcast(encodedBytes);
8709
+ const publicKey = pubKeyFromPrivate(privateKey);
8710
+ const playerId = bytesToHex2(publicKey);
8711
+ const enableP2P = options?.enableP2P ?? false;
8712
+ if (enableP2P) {
8713
+ if (this.peerMesh) {
8714
+ throw new Error("P2P already enabled by a previous join - multiple P2P joins not supported");
8668
8715
  }
8669
- }).catch(this.onInputSendError);
8716
+ const genesisHash = this.config.toGenesisHash();
8717
+ this.peerMesh = new PeerMesh({
8718
+ sessionConfig: this.config,
8719
+ publicKey,
8720
+ genesisHash,
8721
+ onPeerInput: (input, signerPubKey) => {
8722
+ if (this.optimisticStrategy === OPTIMISTIC_ALL) {
8723
+ this.channel?.addOptimisticInput(input, signerPubKey).catch(warnUnexpected4);
8724
+ }
8725
+ }
8726
+ });
8727
+ this.peerMesh.start().catch(warnUnexpected4);
8728
+ }
8729
+ await this.channel.sendJoinMessage(privateKey);
8730
+ const sessionLengthMs = this.config.maxTicks / this.config.tickRate * 1e3;
8731
+ const replayTimeout = sessionLengthMs + 5e3;
8732
+ const replayDeadline = Date.now() + replayTimeout;
8733
+ while (Date.now() < replayDeadline) {
8734
+ if (await this.channel.isCaughtUp()) {
8735
+ break;
8736
+ }
8737
+ await new Promise((resolve) => setTimeout(resolve, 50));
8738
+ }
8739
+ if (!await this.channel.isCaughtUp()) {
8740
+ throw new Error("timeout waiting for replay to complete");
8741
+ }
8742
+ const joinTimeout = this.joinTimeoutMs ?? 3e4;
8743
+ const joinDeadline = Date.now() + joinTimeout;
8744
+ while (Date.now() < joinDeadline) {
8745
+ const participants = this.getParticipants();
8746
+ if (participants.some((p) => p.id === playerId)) {
8747
+ const mesh = enableP2P ? this.peerMesh : null;
8748
+ return new InputSender(this.channel, privateKey, mesh);
8749
+ }
8750
+ await new Promise((resolve) => setTimeout(resolve, 10));
8751
+ }
8752
+ throw new Error("timeout waiting for join confirmation");
8670
8753
  }
8671
8754
  // getState synchronously returns the latest copy of the state that we have collected
8672
8755
  getState() {
@@ -8675,9 +8758,6 @@ var Session = class {
8675
8758
  }
8676
8759
  throw new Error("state not initialised, call init() first");
8677
8760
  }
8678
- onInputSendError = (err2) => {
8679
- console.error("error sending input", err2);
8680
- };
8681
8761
  onStateUpdate = (state) => {
8682
8762
  this.latestState = state;
8683
8763
  };
@@ -9084,7 +9164,8 @@ function createPlayerStore(schema) {
9084
9164
  acc[index] = {
9085
9165
  ...participant,
9086
9166
  entity,
9087
- isCurrentPlayer: participant.id === currentPlayerId
9167
+ // currentPlayerId may be empty string if not yet joined - isCurrentPlayer will be false
9168
+ isCurrentPlayer: currentPlayerId !== "" && participant.id === currentPlayerId
9088
9169
  };
9089
9170
  return acc;
9090
9171
  }, []);
@@ -9105,17 +9186,13 @@ function SessionProvider({ config, children }) {
9105
9186
  const [inputBindings, setInputBindings] = useState(null);
9106
9187
  const initRef = useRef(false);
9107
9188
  const currentStateRef = useRef(EMPTY_VIEW);
9108
- const initialPlayerId = bytesToHex2(pubKeyFromPrivate(config.playerKey));
9109
- const currentPlayerIdRef = useRef(initialPlayerId);
9110
- const [currentPlayerId, setCurrentPlayerId] = useState(initialPlayerId);
9189
+ const currentPlayerIdRef = useRef("");
9111
9190
  const onSessionReady = useCallback((s) => {
9112
9191
  sessionRef.current = s;
9113
9192
  setInputBindings(s.getInputBindings());
9114
9193
  currentStateRef.current = stateView(s.getState());
9115
9194
  setSession(s);
9116
9195
  setIsReady(true);
9117
- currentPlayerIdRef.current = s.getCurrentPlayerId();
9118
- setCurrentPlayerId(currentPlayerIdRef.current);
9119
9196
  }, []);
9120
9197
  const onSessionError = useCallback((err2) => {
9121
9198
  console.error("Failed to create session:", err2);
@@ -9141,12 +9218,14 @@ function SessionProvider({ config, children }) {
9141
9218
  }
9142
9219
  };
9143
9220
  }, [config, onSessionReady, onSessionError]);
9144
- const sendInput = useCallback(
9145
- (input) => {
9221
+ const join = useCallback(
9222
+ async (playerKey, options) => {
9146
9223
  if (!session) {
9147
- return;
9224
+ throw new Error("Session not initialized");
9148
9225
  }
9149
- session.sendInput(input);
9226
+ const sender = await session.join(playerKey, options);
9227
+ currentPlayerIdRef.current = sender.currentPlayerId;
9228
+ return sender;
9150
9229
  },
9151
9230
  [session]
9152
9231
  );
@@ -9159,10 +9238,9 @@ function SessionProvider({ config, children }) {
9159
9238
  participants.getState().update(state, session.getParticipants(), currentPlayerIdRef.current);
9160
9239
  }, HIGHEST_USE_FRAME_PRIORITY);
9161
9240
  const value = useMemo(
9162
- () => inputBindings && config && session && currentPlayerId ? {
9241
+ () => inputBindings && config && session ? {
9163
9242
  stateRef: currentStateRef,
9164
9243
  participants,
9165
- sendInput,
9166
9244
  inputBindings,
9167
9245
  config: session.getConfig(),
9168
9246
  schema,
@@ -9171,9 +9249,9 @@ function SessionProvider({ config, children }) {
9171
9249
  error,
9172
9250
  ended: false,
9173
9251
  // TODO
9174
- currentPlayerId
9252
+ join
9175
9253
  } : null,
9176
- [isReady, error, sendInput, inputBindings, config, session, participants, currentPlayerId, schema]
9254
+ [isReady, error, inputBindings, config, session, participants, schema, join]
9177
9255
  );
9178
9256
  if (error) {
9179
9257
  return /* @__PURE__ */ jsx(FullscreenNotice, { message: error.message });
@@ -9211,6 +9289,72 @@ function FullscreenNotice({ message }) {
9211
9289
  ) });
9212
9290
  }
9213
9291
 
9292
+ // src/react/providers/ParticipantProvider.tsx
9293
+ import { createContext as createContext2, useContext as useContext2, useEffect as useEffect2, useState as useState2, useCallback as useCallback2, useMemo as useMemo2 } from "react";
9294
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
9295
+ var ParticipantContext = createContext2(null);
9296
+ function ParticipantProvider({ playerKey, joinOptions, children }) {
9297
+ const session = useSessionContext();
9298
+ const [inputSender, setInputSender] = useState2(null);
9299
+ const [isJoined, setIsJoined] = useState2(false);
9300
+ const [error, setError] = useState2(null);
9301
+ const currentPlayerId = useMemo2(() => bytesToHex2(pubKeyFromPrivate(playerKey)), [playerKey]);
9302
+ useEffect2(() => {
9303
+ if (!session.isReady) return;
9304
+ let cancelled = false;
9305
+ session.join(playerKey, joinOptions).then((sender) => {
9306
+ if (cancelled) return;
9307
+ setInputSender(sender);
9308
+ setIsJoined(true);
9309
+ }).catch((err2) => {
9310
+ if (cancelled) return;
9311
+ console.error("Failed to join session:", err2);
9312
+ setError(err2 instanceof Error ? err2 : new Error(String(err2)));
9313
+ });
9314
+ return () => {
9315
+ cancelled = true;
9316
+ };
9317
+ }, [session, playerKey, joinOptions]);
9318
+ const sendInput = useCallback2(
9319
+ (input) => {
9320
+ if (!inputSender) {
9321
+ console.warn("Cannot send input: not yet joined");
9322
+ return;
9323
+ }
9324
+ inputSender.sendInput(input);
9325
+ },
9326
+ [inputSender]
9327
+ );
9328
+ const value = useMemo2(
9329
+ () => ({
9330
+ sendInput,
9331
+ currentPlayerId,
9332
+ isJoined
9333
+ }),
9334
+ [sendInput, currentPlayerId, isJoined]
9335
+ );
9336
+ if (error) {
9337
+ return /* @__PURE__ */ jsxs("div", { style: { color: "red" }, children: [
9338
+ "Failed to join: ",
9339
+ error.message
9340
+ ] });
9341
+ }
9342
+ return /* @__PURE__ */ jsx2(ParticipantContext.Provider, { value, children });
9343
+ }
9344
+ function useParticipantContext() {
9345
+ const ctx = useContext2(ParticipantContext);
9346
+ if (!ctx) {
9347
+ throw new Error("useParticipant must be used within ParticipantProvider");
9348
+ }
9349
+ return ctx;
9350
+ }
9351
+ function useCurrentPlayerId() {
9352
+ return useParticipantContext().currentPlayerId;
9353
+ }
9354
+ function useSendInput() {
9355
+ return useParticipantContext().sendInput;
9356
+ }
9357
+
9214
9358
  // src/react/hooks/useSession.ts
9215
9359
  function useSession() {
9216
9360
  return useSessionContext();
@@ -9237,7 +9381,7 @@ function useFrame(callback, renderPriority) {
9237
9381
  }
9238
9382
 
9239
9383
  // src/react/hooks/useQuery.ts
9240
- import { useState as useState2, useCallback as useCallback2 } from "react";
9384
+ import { useState as useState3, useCallback as useCallback3 } from "react";
9241
9385
  import { createStore as createStore2, useStore } from "zustand";
9242
9386
  function shallowEqual(a, b) {
9243
9387
  if (a === b) return true;
@@ -9291,8 +9435,8 @@ function createEntityStore() {
9291
9435
  }
9292
9436
  function useQuery(include, exclude, selector) {
9293
9437
  const { schema } = useSession();
9294
- const [entityStore] = useState2(createEntityStore);
9295
- const [selectorStore] = useState2(
9438
+ const [entityStore] = useState3(createEntityStore);
9439
+ const [selectorStore] = useState3(
9296
9440
  () => selector ? createSelectorStore([]) : null
9297
9441
  );
9298
9442
  const entities = useStore(entityStore, (state) => state.entities);
@@ -9301,7 +9445,7 @@ function useQuery(include, exclude, selector) {
9301
9445
  (state) => "result" in state ? state.result : null
9302
9446
  );
9303
9447
  useFrame(
9304
- useCallback2(
9448
+ useCallback3(
9305
9449
  ({ state, players }) => {
9306
9450
  const stateBuffer = new Uint8Array(
9307
9451
  state.buffer,
@@ -9327,8 +9471,8 @@ function useQuery(include, exclude, selector) {
9327
9471
  }
9328
9472
  function useQueryMask(includeMask, excludeMask, selector) {
9329
9473
  const { schema } = useSession();
9330
- const [entityStore] = useState2(createEntityStore);
9331
- const [selectorStore] = useState2(
9474
+ const [entityStore] = useState3(createEntityStore);
9475
+ const [selectorStore] = useState3(
9332
9476
  () => selector ? createSelectorStore([]) : null
9333
9477
  );
9334
9478
  const entities = useStore(entityStore, (state) => state.entities);
@@ -9337,7 +9481,7 @@ function useQueryMask(includeMask, excludeMask, selector) {
9337
9481
  (state) => "result" in state ? state.result : null
9338
9482
  );
9339
9483
  useFrame(
9340
- useCallback2(
9484
+ useCallback3(
9341
9485
  ({ state, players }) => {
9342
9486
  const stateBuffer = new Uint8Array(
9343
9487
  state.buffer,
@@ -9369,13 +9513,13 @@ function usePlayers() {
9369
9513
  return useStore2(participants, (state) => state.players);
9370
9514
  }
9371
9515
  function useCurrentPlayer() {
9372
- const { currentPlayerId } = useSession();
9516
+ const currentPlayerId = useCurrentPlayerId();
9373
9517
  const players = usePlayers();
9374
9518
  return players.find((p) => p.id === currentPlayerId) || null;
9375
9519
  }
9376
9520
 
9377
9521
  // src/react/hooks/useEvent.ts
9378
- import { useRef as useRef3, useReducer, useCallback as useCallback3 } from "react";
9522
+ import { useRef as useRef3, useReducer, useCallback as useCallback4 } from "react";
9379
9523
  function useEvent(iterator, options) {
9380
9524
  const ttl = options?.ttl ?? 1e3;
9381
9525
  const limit = options?.limit ?? 64;
@@ -9388,7 +9532,7 @@ function useEvent(iterator, options) {
9388
9532
  );
9389
9533
  const [, forceUpdate] = useReducer((x) => x + 1, 0);
9390
9534
  useFrame(
9391
- useCallback3(
9535
+ useCallback4(
9392
9536
  ({ state }) => {
9393
9537
  const now2 = performance.now();
9394
9538
  const slots = slotsRef.current;
@@ -9426,9 +9570,9 @@ function useEvent(iterator, options) {
9426
9570
  // src/react/Player.tsx
9427
9571
  import {
9428
9572
  forwardRef,
9429
- useEffect as useEffect2,
9573
+ useEffect as useEffect3,
9430
9574
  useImperativeHandle,
9431
- useMemo as useMemo3,
9575
+ useMemo as useMemo4,
9432
9576
  useRef as useRef5
9433
9577
  } from "react";
9434
9578
  import { useFrame as useFrame3, useThree } from "@react-three/fiber";
@@ -10646,10 +10790,10 @@ function getView(type) {
10646
10790
  }
10647
10791
 
10648
10792
  // src/react/PlayerPoseContext.ts
10649
- import { createContext as createContext2, useContext as useContext2 } from "react";
10650
- var PlayerPoseContext = createContext2(null);
10793
+ import { createContext as createContext3, useContext as useContext3 } from "react";
10794
+ var PlayerPoseContext = createContext3(null);
10651
10795
  function usePlayerPose() {
10652
- const ctx = useContext2(PlayerPoseContext);
10796
+ const ctx = useContext3(PlayerPoseContext);
10653
10797
  if (!ctx) {
10654
10798
  throw new Error("usePlayerPose must be used within a <Player> children tree.");
10655
10799
  }
@@ -10657,16 +10801,16 @@ function usePlayerPose() {
10657
10801
  }
10658
10802
 
10659
10803
  // src/react/Crosshair.tsx
10660
- import { useRef as useRef4, useMemo as useMemo2 } from "react";
10804
+ import { useRef as useRef4, useMemo as useMemo3 } from "react";
10661
10805
  import { Html as Html2 } from "@react-three/drei";
10662
10806
  import { useFrame as useFrame2 } from "@react-three/fiber";
10663
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
10807
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
10664
10808
  var SIZE = 12;
10665
10809
  var LINE_WIDTH = 1;
10666
10810
  var OPACITY = 0.4;
10667
10811
  function Crosshair({ mode, offsetY = 0 }) {
10668
10812
  const crosshairRef = useRef4(null);
10669
- const calculatePosition = useMemo2(
10813
+ const calculatePosition = useMemo3(
10670
10814
  () => (_, __, viewportSize) => [viewportSize.width / 2, viewportSize.height / 2],
10671
10815
  []
10672
10816
  );
@@ -10680,7 +10824,7 @@ function Crosshair({ mode, offsetY = 0 }) {
10680
10824
  });
10681
10825
  if (mode === "none") return null;
10682
10826
  const topPosition = 50 + offsetY;
10683
- return /* @__PURE__ */ jsx2(Html2, { fullscreen: true, calculatePosition, style: { pointerEvents: "none" }, children: /* @__PURE__ */ jsx2(
10827
+ return /* @__PURE__ */ jsx3(Html2, { fullscreen: true, calculatePosition, style: { pointerEvents: "none" }, children: /* @__PURE__ */ jsx3(
10684
10828
  "div",
10685
10829
  {
10686
10830
  style: {
@@ -10689,7 +10833,7 @@ function Crosshair({ mode, offsetY = 0 }) {
10689
10833
  height: "100%",
10690
10834
  pointerEvents: "none"
10691
10835
  },
10692
- children: /* @__PURE__ */ jsx2(
10836
+ children: /* @__PURE__ */ jsx3(
10693
10837
  "div",
10694
10838
  {
10695
10839
  ref: crosshairRef,
@@ -10699,7 +10843,7 @@ function Crosshair({ mode, offsetY = 0 }) {
10699
10843
  top: mode === "center" ? `${topPosition}%` : "50%",
10700
10844
  transform: "translate(-50%, -50%)"
10701
10845
  },
10702
- children: /* @__PURE__ */ jsxs(
10846
+ children: /* @__PURE__ */ jsxs2(
10703
10847
  "div",
10704
10848
  {
10705
10849
  style: {
@@ -10708,7 +10852,7 @@ function Crosshair({ mode, offsetY = 0 }) {
10708
10852
  height: `${SIZE}px`
10709
10853
  },
10710
10854
  children: [
10711
- /* @__PURE__ */ jsx2(
10855
+ /* @__PURE__ */ jsx3(
10712
10856
  "div",
10713
10857
  {
10714
10858
  style: {
@@ -10722,7 +10866,7 @@ function Crosshair({ mode, offsetY = 0 }) {
10722
10866
  }
10723
10867
  }
10724
10868
  ),
10725
- /* @__PURE__ */ jsx2(
10869
+ /* @__PURE__ */ jsx3(
10726
10870
  "div",
10727
10871
  {
10728
10872
  style: {
@@ -10746,7 +10890,7 @@ function Crosshair({ mode, offsetY = 0 }) {
10746
10890
  }
10747
10891
 
10748
10892
  // src/react/Player.tsx
10749
- import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
10893
+ import { Fragment, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
10750
10894
  var DEFAULT_POSITION = [0, 0, 0];
10751
10895
  var DEFAULT_ROTATION = [0, 0, 0, 1];
10752
10896
  var DEFAULT_VIEW = "thirdPerson";
@@ -10782,13 +10926,13 @@ var Player = forwardRef(function Player2({
10782
10926
  const visualRotation = useRef5(toQuaternion(rotation));
10783
10927
  const pendingSnapPosition = useRef5(false);
10784
10928
  const pendingSnapRotation = useRef5(false);
10785
- const inputMapper = useMemo3(
10929
+ const inputMapper = useMemo4(
10786
10930
  () => customInputMapper ?? new DesktopInputMapper(),
10787
10931
  [customInputMapper]
10788
10932
  );
10789
- const currentView = useMemo3(() => getView(view), [view]);
10933
+ const currentView = useMemo4(() => getView(view), [view]);
10790
10934
  const viewStateRef = useRef5(currentView.init());
10791
- const pose = useMemo3(
10935
+ const pose = useMemo4(
10792
10936
  () => ({
10793
10937
  position: new Vector315(),
10794
10938
  body: new Quaternion15(),
@@ -10801,14 +10945,14 @@ var Player = forwardRef(function Player2({
10801
10945
  []
10802
10946
  );
10803
10947
  const invBodyQuat = useRef5(new Quaternion15());
10804
- useEffect2(() => {
10948
+ useEffect3(() => {
10805
10949
  viewStateRef.current = currentView.init(viewStateRef.current);
10806
10950
  const usePointerLock = view !== "map" && view !== "twinStick" && view !== "moba";
10807
10951
  inputMapper.setPointerLockEnabled?.(usePointerLock);
10808
10952
  const lookMode = view === "map" ? "drag" : view === "twinStick" || view === "moba" ? "always" : "pointerLock";
10809
10953
  inputMapper.setLookMode?.(lookMode);
10810
10954
  }, [currentView, view, inputMapper]);
10811
- useEffect2(() => {
10955
+ useEffect3(() => {
10812
10956
  if (view === "map" && mapControlsRef.current && cameraRef.current) {
10813
10957
  const controls = mapControlsRef.current;
10814
10958
  const camera = cameraRef.current;
@@ -10821,21 +10965,21 @@ var Player = forwardRef(function Player2({
10821
10965
  controls.update();
10822
10966
  }
10823
10967
  }, [view]);
10824
- useEffect2(() => {
10968
+ useEffect3(() => {
10825
10969
  if (enableInput) {
10826
10970
  inputMapper.bind();
10827
10971
  return () => inputMapper.unbind();
10828
10972
  }
10829
10973
  }, [enableInput, inputMapper]);
10830
- useEffect2(() => {
10974
+ useEffect3(() => {
10831
10975
  if (enableCamera && cameraRef.current) {
10832
10976
  set({ camera: cameraRef.current });
10833
10977
  }
10834
10978
  }, [enableCamera, set]);
10835
- useEffect2(() => {
10979
+ useEffect3(() => {
10836
10980
  bodyPosition.current.copy(toVector3(position));
10837
10981
  }, [position]);
10838
- useEffect2(() => {
10982
+ useEffect3(() => {
10839
10983
  bodyRotation.current.copy(toQuaternion(rotation));
10840
10984
  }, [rotation]);
10841
10985
  useFrame3((state, delta) => {
@@ -10925,9 +11069,9 @@ var Player = forwardRef(function Player2({
10925
11069
  }),
10926
11070
  []
10927
11071
  );
10928
- return /* @__PURE__ */ jsxs2(Fragment, { children: [
10929
- /* @__PURE__ */ jsx3(PlayerPoseContext.Provider, { value: pose, children: /* @__PURE__ */ jsx3("group", { ref: groupRef, visible: view !== "map" && (view !== "firstPerson" || !enableCamera), children }) }),
10930
- /* @__PURE__ */ jsx3("group", { ref: pivotRef, children: /* @__PURE__ */ jsx3(
11072
+ return /* @__PURE__ */ jsxs3(Fragment, { children: [
11073
+ /* @__PURE__ */ jsx4(PlayerPoseContext.Provider, { value: pose, children: /* @__PURE__ */ jsx4("group", { ref: groupRef, visible: view !== "map" && (view !== "firstPerson" || !enableCamera), children }) }),
11074
+ /* @__PURE__ */ jsx4("group", { ref: pivotRef, children: /* @__PURE__ */ jsx4(
10931
11075
  "perspectiveCamera",
10932
11076
  {
10933
11077
  ref: cameraRef,
@@ -10937,7 +11081,7 @@ var Player = forwardRef(function Player2({
10937
11081
  far: 1e3
10938
11082
  }
10939
11083
  ) }),
10940
- view === "map" && enableCamera && /* @__PURE__ */ jsx3(
11084
+ view === "map" && enableCamera && /* @__PURE__ */ jsx4(
10941
11085
  MapControls,
10942
11086
  {
10943
11087
  ref: mapControlsRef,
@@ -10950,7 +11094,7 @@ var Player = forwardRef(function Player2({
10950
11094
  zoomSpeed: -1
10951
11095
  }
10952
11096
  ),
10953
- crosshair && enableCamera && currentView.crosshairMode && currentView.crosshairMode !== "none" && /* @__PURE__ */ jsx3(Crosshair, { mode: currentView.crosshairMode, offsetY: currentView.crosshairOffsetY })
11097
+ crosshair && enableCamera && currentView.crosshairMode && currentView.crosshairMode !== "none" && /* @__PURE__ */ jsx4(Crosshair, { mode: currentView.crosshairMode, offsetY: currentView.crosshairOffsetY })
10954
11098
  ] });
10955
11099
  });
10956
11100
 
@@ -11044,6 +11188,7 @@ export {
11044
11188
  INPUT_HEADER_SIZE,
11045
11189
  InitDataValidationError,
11046
11190
  InputGraph,
11191
+ InputSender,
11047
11192
  Interpolation,
11048
11193
  IsometricView,
11049
11194
  MAGIC,
@@ -11054,6 +11199,7 @@ export {
11054
11199
  OPTIMISTIC_LOCAL,
11055
11200
  OPTIMISTIC_NONE,
11056
11201
  PRIVATE_KEY_SIZE,
11202
+ ParticipantProvider,
11057
11203
  Player as PlayerController,
11058
11204
  RollingCounter,
11059
11205
  SIGNATURE_SIZE,
@@ -11087,6 +11233,7 @@ export {
11087
11233
  createSession,
11088
11234
  createState,
11089
11235
  createStoreApi,
11236
+ deriveKey,
11090
11237
  despawn,
11091
11238
  encodeInitData,
11092
11239
  ensureCompiled,
@@ -11142,12 +11289,15 @@ export {
11142
11289
  unpackGeneration,
11143
11290
  unpackIndex,
11144
11291
  useCurrentPlayer,
11292
+ useCurrentPlayerId,
11145
11293
  useEvent,
11146
11294
  useFrame,
11295
+ useParticipantContext,
11147
11296
  usePlayerPose,
11148
11297
  usePlayers,
11149
11298
  useQuery,
11150
11299
  useQueryMask,
11300
+ useSendInput,
11151
11301
  useSession,
11152
11302
  useSessionContext,
11153
11303
  validateInitData,