{"version":3,"file":"InputHandle.cjs","sources":["../../src/input/InputHandle.ts"],"sourcesContent":["import { encode } from '@colyseus/schema';\nimport { InputEncoder, type InputEncoderOptions, type InputMode } from '@colyseus/schema/input';\nimport { Protocol, ProtocolModifier } from '@colyseus/shared-types';\n\nimport type { Connection } from '../Connection.ts';\nimport { now } from '../core/utils.ts';\nimport { debugOverlayActive } from '../debug-channel.ts';\nimport { metadataOf } from '../core/schema-reflect.ts';\n\n/** Widest a single self-describing number can encode to. */\nconst MAX_VARINT = 9;\n/** Reliable stamp prefix: one delta-coded timeline value (+2 for BOTH's u16). */\nconst RELIABLE_STAMP_MAX = MAX_VARINT;\n/** Unreliable stamp block: `[k][u32 anchor][Δ]×(k−1)`, twice over for BOTH. */\nconst ringStampMax = (historySize: number, both: boolean) =>\n  (both ? 2 : 1) * (MAX_VARINT + 4 + MAX_VARINT * historySize);\n\n/**\n * Minimal structural type the input handle needs from its host (Room). Lets\n * us decouple from the full `Room` class so this module stays import-cycle\n * free, while still picking up the latest `connection` after a reconnect.\n *\n * @internal\n */\nexport interface InputHandleHost {\n  connection?: Connection;\n  /** Room clock — read for the server-clock render timestamp auto-stamped onto\n   *  reliable inputs when render-time lag compensation is enabled. Structural\n   *  to stay import-cycle free (the Room's RoomClockLike satisfies it).\n   *  `lastServerTime`/`smoothedRtt` are optional so a bare `{ serverNow }` clock\n   *  still satisfies it (it just stamps 0 / omits the latency term). */\n  clock?: { serverNow(): number; lastServerTime?(): number; smoothedRtt?(): number };\n}\n\n/**\n * Options accepted by `Room.input()`. Extends {@link InputEncoderOptions}\n * (mode / historySize) with a `type` field for the schema constructor.\n * Inputs are ALWAYS delta-encoded (the codec has no full-snapshot mode):\n * each send carries only changed fields, or a body-less frame on a no-change\n * tick. Every `send()` transmits one input; to skip a tick, just don't call\n * `send()`.\n *\n * Recommended for rollback netcode: `{ mode: \"unreliable\", historySize: 4 }`\n * — small redundant deltas, idempotent across drops via absolute-value wire ops.\n * Each packet re-sends the last `historySize` inputs, so a dropped one is\n * recovered from its successors and the server dedupes by wire seq; only a run\n * of losses longer than `historySize` actually loses input.\n *\n * Lag compensation works on either channel: a room that rewinds\n * (`allowRewindState` + a rewind group) gets a per-input `renderTime`/\n * `reckonTime` stamp here too, and an input recovered redundantly from a later\n * packet still carries the instant it was sampled at. `mode` is purely a\n * delivery choice.\n *\n * **`mode:\"unreliable\"` is only actually unreliable on `@colyseus/h3-transport`\n * (WebTransport), which is experimental.** Every WebSocket transport lacks a\n * datagram channel and sends this traffic on the reliable one instead —\n * correct, and every input still arrives exactly once, but the redundancy ring\n * is then pure overhead (`historySize` duplicate slots the ordered channel\n * didn't need). On WebSocket, prefer `mode:\"reliable\"`.\n *\n * `I` is intentionally unconstrained: pinning it to `Schema` from this\n * SDK's copy of `@colyseus/schema` would reject user-side schemas coming\n * from a different copy of the package (npm hoisting, multi-version\n * installs). Runtime calls duck-type via the encoder, so a structural\n * match is enough.\n */\nexport interface InputOptions<I = any> extends InputEncoderOptions {\n  /**\n   * Schema constructor for the input. Optional when the server room called\n   * `defineInput()` — the schema then arrives via the JOIN handshake's input\n   * reflection and is used automatically (the synthesized class mirrors the\n   * server's fields, but `instanceof YourInput` won't pass on it). An explicit\n   * ctor always wins over reflection — pass one to use your own class.\n   * `room.input()` throws when neither source yields a constructor.\n   */\n  type?: new () => I;\n\n  /**\n   * Your interpolation buffer in ms — how far in the PAST you render remote\n   * entities (e.g. a `Predict` lerp `delay`). It feeds the stamped\n   * `renderDelta = renderDelay + smoothedRtt()/2`, from which the server\n   * derives `renderTime = reckonTime − renderDelta`: this term covers the\n   * interp buffer, and the SDK adds the one-way downstream latency itself. So\n   * pass ONLY your interp buffer, never the latency.\n   *\n   * **Usually omit this.** When you wire the handle through\n   * `predict.reconciler(self, { input })` or `predict.sim({ input })`, the SDK\n   * binds this to the Predict's lerp `delay` automatically, so the interp buffer\n   * the remotes render at and the server's rewind instant are derived from ONE\n   * number and can't drift out of sync. Set it explicitly only to override that\n   * (e.g. you smooth remotes some other way) — an explicit value always wins.\n   *\n   * Default `0` — correct when you dead-reckon remote entities to current server\n   * time (no interp lag). Has no effect unless the Room rewinds a\n   * `mode:\"snapshot\"` group (which auto-enables the renderTime stamp).\n   */\n  renderDelay?: number;\n\n  /**\n   * Predicate selecting which of this client's inputs the server may REWIND to —\n   * i.e. which inputs carry their lag-comp timestamp on the wire. The client-side\n   * mirror of the server room's `allowRewindState`: there the room records history\n   * to rewind into; here you say which inputs are worth rewinding to. Omitted (the\n   * default) stamps EVERY reliable input.\n   *\n   * Return `true` only for inputs the server lag-compensates — e.g. a firing input\n   * that triggers a rewound hit-test — to drop the ~1-byte timestamp on the rest\n   * (typically the majority of frames: moving/aiming without shooting). Evaluated\n   * against the staged {@link InputHandle.data} on each {@link InputHandle.send}.\n   *\n   * A pure client-side bandwidth trim: the server already tolerates mixed\n   * stamped/unstamped reliable inputs (an unstamped one reads `renderTime` 0 and\n   * falls back to live), and the delta-coded stamp baseline self-syncs across the\n   * gaps — no server change. Per-input ONLY: it gates the timestamp, not rewind\n   * itself (that's the room's `allowRewindState`), so `() => false` just keeps the\n   * server live for this client — it never disables rewind.\n   *\n   * **`mode:\"reliable\"` only.** An unreliable packet carries a whole ring of\n   * inputs under one stamp block, which is all-or-nothing: mixing stamped and\n   * unstamped slots would blow up the intra-packet deltas for no saving, since\n   * the block ships either way. The predicate is not evaluated on that channel,\n   * and setting it there warns once.\n   *\n   * ⚠ ONLY safe when the timestamp is consumed SERVER-side (a `mode:\"snapshot\"`\n   * renderTime rewind for hit registration). If the CLIENT reads the stamp for its\n   * OWN prediction — a `mode:\"reckon\"` room whose reconciler hit-tests at\n   * `ctx.reckonTime` every step — every input needs it; do NOT set this there.\n   */\n  allowRewind?: (data: I) => boolean;\n}\n\n/**\n * Per-room input handle returned by `Room.input()`. Mutate {@link data}\n * to stage the next input, then call {@link send} to encode and transmit on\n * the channel chosen at construction (reliable or unreliable).\n *\n * @example\n * ```typescript\n * const input = room.input({ type: MoveInput, mode: \"unreliable\" });\n * input.data.vx = 10;\n * input.data.vy = 20;\n * input.send();\n * ```\n */\nexport interface InputHandle<I = any> {\n  /** Mutable schema instance — mutate, then call {@link send}. */\n  readonly data: I;\n  /** Wire mode this handle was constructed with. */\n  readonly mode: InputMode;\n  /**\n   * Server-advertised fixed simulation/input step rate in Hz, from\n   * `defineInput({ tickRate })` cascaded through the join handshake. Predict at\n   * this exact rate (dt = 1/tickRate) so client rollback-replay stays\n   * deterministic with the server — the single source of truth for the\n   * timestep. `undefined` when the server didn't advertise one (fall back to\n   * your own constant).\n   */\n  readonly tickRate?: number;\n  /**\n   * The fixed step as **seconds** (`1/tickRate`) — the exact dt to predict and\n   * rollback-replay each input with, matching the server's per-input dt. Prefer\n   * this over hand-computing `1/tickRate`. `undefined` when no rate advertised.\n   */\n  readonly stepSeconds?: number;\n  /**\n   * The fixed step as **milliseconds** (`1000/tickRate`), e.g. to drive a\n   * fixed-timestep accumulator. `undefined` when no rate advertised.\n   */\n  readonly stepMs?: number;\n  /**\n   * Server-advertised state-patch interval (ms) from the join handshake = the\n   * reconcile/correction cadence (acks + authoritative state arrive this often).\n   * A reconciler can tune its correction-smoothing window to it. `undefined`\n   * when not advertised.\n   */\n  readonly patchRate?: number;\n  /**\n   * Server-advertised physics sub-steps per input tick, from\n   * `setFixedTimestep(..., { subSteps })` cascaded through the join handshake.\n   * One input still drives ONE predicted/replayed step, but inside it the\n   * simulation integrates this many engine steps of {@link subStepSeconds} —\n   * physics at `tickRate * subSteps` Hz on a `tickRate` input rate. `1` when\n   * the server didn't sub-step. The reconcilers default their step context's\n   * `subSteps`/`subDt` from this.\n   */\n  readonly subSteps: number;\n  /**\n   * The physics sub-step as **seconds** (`stepSeconds / subSteps`) — the exact\n   * engine dt for each sub-step, bit-identical to the server's `ctx.subDt`.\n   * Equals {@link stepSeconds} when `subSteps` is 1; `undefined` when no rate\n   * advertised.\n   */\n  readonly subStepSeconds?: number;\n  /** The physics sub-step as **milliseconds** (`stepMs / subSteps`). `undefined`\n   *  when no rate advertised. */\n  readonly subStepMs?: number;\n  /**\n   * Encode the staged input and send it. Routes to the reliable or\n   * unreliable channel based on {@link mode}.\n   *\n   * A no-op ONLY when the connection isn't open. Otherwise it always\n   * transmits one input — a **body-less** frame when nothing changed since the\n   * last send (the server decodes it as a no-op, holding the last values), so\n   * the server receives exactly one input per `send()` and its consumed/ack\n   * count tracks yours 1:1. To skip a tick entirely, simply don't call `send()`.\n   *\n   * Returns the seq assigned to this input — the same value the reconciler steps,\n   * that {@link at}/{@link reckonTimeAt} key on, and that {@link sentCount} now\n   * reads. It is `0` when nothing was sent (connection closed); seqs are 1-based,\n   * so `const seq = input.send(); if (seq) …` doubles as a \"did it transmit?\" check.\n   */\n  send(): number;\n  /**\n   * Subscribe to sends: `listener(seq)` fires synchronously at the END of each\n   * {@link send} (after the input is buffered for replay and its reckon instant\n   * stamped), with the just-sent seq. Returns an unsubscribe fn.\n   *\n   * This is how the prediction layer OBSERVES your input stream without owning the\n   * send: `predict.reconciler(...)` / `predict.sim(...)` subscribe here and step\n   * their predicted simulation for the sent input — so you mutate + send through\n   * the handle (`input.data.x = …; input.send()`) and prediction stays current\n   * with zero extra calls on your side. `at(seq)` / `reckonTimeAt(seq)` are valid\n   * inside the listener. Empty (no allocation, no dispatch) when nothing subscribes.\n   */\n  onSend(listener: (seq: number) => void): () => void;\n  /**\n   * Reset encoder state. Drops the unreliable ring buffer; re-marks every\n   * populated field as dirty so the next send emits a full snapshot. Useful\n   * on scene transitions; the SDK calls it itself on the reconnect path.\n   * Observing rollback controllers follow a reset automatically (they poll\n   * {@link epoch}) — no manual `Reconciler.reset()` wiring needed.\n   */\n  reset(): void;\n  /**\n   * Monotonic reset counter: increments on every {@link reset}, whatever\n   * triggered it (the SDK's reconnect path or an app call). Rollback\n   * controllers poll it each tick and self-reset when it moves. Compare with\n   * `!==`, never `+1` — multiple resets can land between polls.\n   */\n  readonly epoch: number;\n  /**\n   * Last input the server has acknowledged PROCESSING into its authoritative\n   * state (the server input-buffer's consumed count, echoed via the TIMED\n   * prefix). The canonical server-reconciled-rollback ack — prune your pending\n   * inputs against it (`seq <= lastProcessed`). `0` until the first ack.\n   *\n   * Lives here (not on `room.clock`) because it's an INPUT concern: this is the\n   * channel you send through, so it's the channel that knows what's been acked.\n   */\n  readonly lastProcessed: number;\n  /**\n   * Count of reliable inputs this handle has actually transmitted — equals the\n   * seq the server will ack via {@link lastProcessed}. Key a client-side\n   * prediction/replay buffer by this (read it right AFTER {@link send}).\n   */\n  readonly sentCount: number;\n  /**\n   * Reliable inputs sent but not yet acked (`sentCount − lastProcessed`) — the\n   * in-flight set a reconciler replays on rollback.\n   */\n  readonly pendingCount: number;\n  /**\n   * Capacity (in seqs) of the replay ring backing {@link at} — the in-flight\n   * window this handle can serve. A reconciler sizes its own per-seq state to\n   * this, so both rings cover the same window and age out together.\n   */\n  readonly replayBufferSize: number;\n  /**\n   * The buffered snapshot of the reliable input sent as `seq`, for\n   * reconciliation replay — the client-side mirror of the server's input\n   * buffer. Returns `undefined` if `seq` is already acked, was never sent, or\n   * has aged out of the bounded ring. The returned instance is REUSED — read it\n   * synchronously during replay, don't retain it.\n   */\n  at(seq: number): I | undefined;\n  /**\n   * The reckon instant (server-clock ms) stamped onto reliable input `seq` — the\n   * client's `serverNow()` estimate at send, the SAME value the server reads as\n   * `channel.reckonTime` (and `rewind.lastSeenBy(sid)`). The reconciler surfaces\n   * it as `ctx.reckonTime` so a prediction step hit-tests remote entities at the\n   * exact instant the server rewinds to (live AND replay). Returns the RAW\n   * stamp: `0` when reckon lag-comp isn't enabled (the room never rewinds to\n   * it), or if `seq` is unsent, acked, aged out, or pre-clock-sync — the\n   * reconciler resolves that `0` to the clock's live `serverNow()` before\n   * surfacing it as `ctx.reckonTime` (see `StepContext.reckonTime` /\n   * `lagCompActive`).\n   */\n  reckonTimeAt(seq: number): number;\n}\n\n/** @internal */\nexport class InputHandleImpl<I = any> implements InputHandle<I> {\n  public readonly data: I;\n  private _host: InputHandleHost;\n  private _encoder: InputEncoder<any>;\n  // Reused frame buffer — safe ONLY because every transport copies synchronously\n  // on send (browser ws.send snapshots; H3 frame() copies before write). A\n  // transport that queued the view uncopied would see it overwritten next send.\n  private _scratch: Uint8Array = new Uint8Array(2048);\n  // Cached framed-packet view into `_scratch`; re-made when the packet size\n  // changes (delta bodies vary) or `_scratch` grows — so it mostly pays off on\n  // steady no-change frames.\n  private _framed: Uint8Array | null = null;\n\n  // Input round-trip state (one handle per room).\n  private _sentCount = 0;                       // reliable inputs transmitted\n  private _lastProcessed = 0;                   // server-acked (consumedCount)\n  private _epoch = 0;                           // reset counter — see InputHandle.epoch\n  // RTT send-time ring (seq % size → send time); avoids per-send Map churn.\n  // Sized WITH the replay ring (one seq window — replay and RTT age out together).\n  private _sendTimes: Float64Array;\n\n  // Sent-input replay ring, mirroring the server's per-client input buffer: each reliable send snapshots\n  // `data` into slot `seq % size` via alloc-free `copyInto` so a reconciler can replay unacked inputs.\n  // Size = worst-case in-flight = (RTT + patch interval) × input rate. tickRate/patchRate from the\n  // handshake (ack rides the patch, so lags up to one interval); RTT is budgeted generously. Floored\n  // at 64; grows for high input rates where 64 would silently overflow (aged-out entries warn once).\n  private static readonly BUFFER_FLOOR = 64;\n  private static readonly BUFFER_RTT_BUDGET_MS = 1000;\n  private static readonly BUFFER_HEADROOM = 1.5;\n  private readonly _inputBufferSize: number;\n  private _inputBuffer: I[] | null = null;      // lazily allocated (needs data ctor)\n  // Per-seq reckonTime stamp (server-clock ms), parallel to _inputBuffer — the\n  // reconciler reads it back as ctx.reckonTime on the live step AND on replay, so\n  // both hit-test at the exact instant the server rewinds to. Sized = replay ring.\n  // Lazily allocated AND only when reckon stamping is on (`_stampReckon`): a room\n  // without reckon lag-comp never rewinds to it, so we don't track it (reckonTimeAt\n  // then reads 0 and the controller resolves ctx.reckonTime to serverNow()).\n  private _reckonTimes: Float64Array | null = null;\n  // Reckon instant of the in-flight send() — computed in send() when stamping,\n  // stamped on the wire AND recorded into _reckonTimes by _recordSent (same value\n  // both). 0 when not stamping.\n  private _pendingReckon = 0;\n  // Running baseline for the DELTA-CODED reliable stamp: the last timeline u32\n  // sent. Each stamped send transmits `stamp − _lastStamp` (signed, ≈ one fixed\n  // step per tick → ~1 byte vs a raw 4-byte u32); the server mirrors this baseline\n  // and reliable+in-order keeps the two locked. reset() re-zeros it so the first\n  // delta after a (re)connect carries the absolute, re-syncing with the server's\n  // freshly-allocated baseline.\n  private _lastStamp = 0;\n  // Per-seq timeline stamps for the UNRELIABLE ring, indexed `seq % historySize`\n  // — exactly the slots a packet carries, so the index can't collide. Lazily\n  // allocated, and only when the room asked for stamps. See _writeRingStamps.\n  private _stampRing: Float64Array | null = null;\n  // Parallel to _stampRing, BOTH mode only: the renderDelta each slot was\n  // sampled with, so the block can carry the exact value per slot.\n  private _renderDeltaRing: Uint16Array | null = null;\n  // Slots the encoder's ring currently carries (≤ historySize). Tracked, not\n  // derived from `seq`: `reset()` drops the ring but keeps the seq monotonic.\n  private _ringSlots = 0;\n  private static _warnedBufferOverflow = false;\n  private static _warnedAllowRewindIgnored = false;\n  // Dev diagnostic (see _warnUnknownFields): unknown data keys already warned.\n  private _warnedUnknownKeys: Set<string> | null = null;\n\n  // Lag-comp stamp (server INPUT_OPTIONS handshake): which timeline(s) each\n  // reliable input is prefixed with, DELTA-CODED on the wire (see _lastStamp).\n  // Both → [varint Δreckon][u16 renderDelta]; reckon-only → [varint Δreckon];\n  // render-only → [varint Δrender]; neither → no prefix.\n  private _stampRender = false;\n  private _stampReckon = false;\n  // Optional per-send gate (app `allowRewind`): when set, only inputs it returns\n  // true for carry the stamp — the rest skip it (and the TIMED bit), trimming the\n  // timestamp on frames the server won't rewind (e.g. non-firing inputs). The\n  // delta baseline (`_lastStamp`) only advances on stamped sends, so it stays\n  // locked with the server across the gaps. Absent ⇒ stamp every reliable input.\n  private _allowRewind?: (data: I) => boolean;\n  // Send observers (the prediction layer subscribes here to step its simulation\n  // on each send — see onSend). null until the first subscribe, so a handle used\n  // without prediction pays nothing (no allocation, no per-send dispatch).\n  // COPY-ON-WRITE: subscribe/unsubscribe replace the array (cold path), so the\n  // dispatch loop's captured ref can't skip or double-fire when a listener\n  // mutates the list mid-dispatch.\n  private _sendListeners: Array<(seq: number) => void> | null = null;\n  // The app's interpolation buffer (ms) — how far in the past it renders remote\n  // entities (e.g. a `Predict` lerp `delay`). The stamp subtracts this AND the\n  // one-way latency (smoothedRtt/2) the SDK already tracks, so callers pass only\n  // the interp buffer, never the latency. When the app doesn't set it explicitly,\n  // `predict.reconciler`/`sim` bind `_renderDelayProvider` to the Predict lerp\n  // `delay` (see bindRenderDelay) so the interp buffer and the server's rewind\n  // instant stay ONE value — no two-number \"keep these equal\" footgun.\n  private _renderDelay = 0;\n  private _renderDelayExplicit = false;\n  private _renderDelayProvider: (() => number) | undefined;\n  // Server-advertised rates: fixed step (Hz), patch interval (ms = reconcile\n  // cadence), and physics sub-steps per input tick.\n  private _tickRate?: number;\n  private _patchRate?: number;\n  private _subSteps = 1;\n\n  constructor(\n    host: InputHandleHost,\n    data: I,\n    encoder: InputEncoder<any>,\n    opts?: { stampRender?: boolean; stampReckon?: boolean; renderDelay?: number; tickRate?: number; patchRate?: number; subSteps?: number; allowRewind?: (data: I) => boolean },\n  ) {\n    this._host = host;\n    this.data = data;\n    this._encoder = encoder;\n    this._stampRender = opts?.stampRender ?? false;\n    this._stampReckon = opts?.stampReckon ?? false;\n    this._allowRewind = opts?.allowRewind;\n    // Inert on this channel, and silently so — the predicate is never even\n    // called (see `send`). Say it once rather than let someone watch bandwidth\n    // not move and go looking.\n    if (this._allowRewind !== undefined && encoder.mode === \"unreliable\"\n      && !InputHandleImpl._warnedAllowRewindIgnored) {\n      InputHandleImpl._warnedAllowRewindIgnored = true;\n      console.warn(\n        `@colyseus/sdk: \\`allowRewind\\` is ignored on \\`mode:\"unreliable\"\\` — a packet ` +\n        `stamps its whole redundancy ring or none of it, so excluding one input would ` +\n        `cost bandwidth rather than save it. Use \\`mode:\"reliable\"\\` to gate the ` +\n        `lag-comp stamp per input.`,\n      );\n    }\n    this._renderDelay = opts?.renderDelay ?? 0;\n    this._renderDelayExplicit = opts?.renderDelay !== undefined;\n    this._tickRate = opts?.tickRate;\n    this._patchRate = opts?.patchRate;\n    this._subSteps = opts?.subSteps ?? 1;\n\n    // Size the replay ring to the advertised rates (see field comment).\n    const stepMs = this._tickRate ? 1000 / this._tickRate : (1000 / 60);\n    const window = InputHandleImpl.BUFFER_RTT_BUDGET_MS + (this._patchRate ?? 0);\n    this._inputBufferSize = Math.max(\n      InputHandleImpl.BUFFER_FLOOR,\n      Math.ceil((window / stepMs) * InputHandleImpl.BUFFER_HEADROOM),\n    );\n    this._sendTimes = new Float64Array(this._inputBufferSize);\n  }\n\n  get mode(): InputMode { return this._encoder.mode; }\n  get tickRate(): number | undefined { return this._tickRate; }\n  // `1/hz` is correctly-rounded IEEE-754 → bit-identical to the server's stepSeconds.\n  get stepSeconds(): number | undefined { return this._tickRate ? 1 / this._tickRate : undefined; }\n  get stepMs(): number | undefined { return this._tickRate ? 1000 / this._tickRate : undefined; }\n  get patchRate(): number | undefined { return this._patchRate; }\n  get subSteps(): number { return this._subSteps; }\n  // `(1/hz)/n` — the SAME expression the server's ctx.subDt uses → bit-identical dt.\n  get subStepSeconds(): number | undefined { return this._tickRate ? (1 / this._tickRate) / this._subSteps : undefined; }\n  get subStepMs(): number | undefined { return this._tickRate ? (1000 / this._tickRate) / this._subSteps : undefined; }\n  get lastProcessed(): number { return this._lastProcessed; }\n  get sentCount(): number { return this._sentCount; }\n  get pendingCount(): number { return this._sentCount - this._lastProcessed; }\n  get replayBufferSize(): number { return this._inputBufferSize; }\n  get epoch(): number { return this._epoch; }\n\n  at(seq: number): I | undefined {\n    if (this._inputBuffer === null) return undefined;\n    // Buffered iff sent, not yet acked, and still within the bounded ring window.\n    if (seq <= this._lastProcessed || seq > this._sentCount) return undefined;\n    if (this._sentCount - seq >= this._inputBufferSize) {\n      // Pending input aged out (RTT exceeded the buffer budget); reconcile may drift, so warn once.\n      if (!InputHandleImpl._warnedBufferOverflow) {\n        InputHandleImpl._warnedBufferOverflow = true;\n        console.warn(\n          `@colyseus/sdk: input replay buffer (${this._inputBufferSize}) overflowed — ` +\n          `RTT exceeds its budget at this input rate; reconciliation may drift.`,\n        );\n      }\n      return undefined;\n    }\n    return this._inputBuffer[seq % this._inputBufferSize];\n  }\n\n  reckonTimeAt(seq: number): number {\n    // 0 when reckon stamping is off (no ring) — the controller resolves to serverNow().\n    if (this._reckonTimes === null) return 0;\n    // Same validity window as at(): sent, unacked, still in the ring. Live reads\n    // it for the just-sent seq (== sentCount); replay reads each unacked seq.\n    if (seq <= this._lastProcessed || seq > this._sentCount) return 0;\n    if (this._sentCount - seq >= this._inputBufferSize) return 0;\n    return this._reckonTimes[seq % this._inputBufferSize];\n  }\n\n  reset(): void {\n    this._encoder.reset();\n    // Adopt the encoder's monotonic seq as the baseline: 0 for reliable, the current\n    // framework seq for unreliable (the encoder keeps `_seq` across its reset). pending\n    // starts at 0 so a reconnect doesn't replay already-acked inputs, and unreliable\n    // seqs continue past the server's last-seen seq if the buffer was reused.\n    this._sentCount = this._lastProcessed = this._encoder.seq;\n    this._framed = null;\n    this._lastStamp = 0; // next stamped send ships an absolute delta — re-syncs the server's re-zeroed baseline\n    // The encoder dropped its ring but keeps `_seq`, so the slot count has to be\n    // tracked rather than derived from the seq — else the next packet would\n    // claim slots the ring no longer carries.\n    this._ringSlots = 0;\n    this._sendTimes.fill(0); // stale acks for pre-reset seqs must read as \"unknown\" (-1), not a bogus RTT\n    // _inputBuffer is reused as-is: at() gates on _sentCount/_lastProcessed, so it can't surface stale snapshots.\n    this._epoch++; // observing controllers poll this and follow the reset\n  }\n\n  /**\n   * @internal Bind lag-comp's `renderDelay` to a live provider — the owning\n   * Predict's lerp `delay`. Called by `predict.reconciler`/`predict.sim` when\n   * they wire this handle, so the remote interp buffer and the server's rewind\n   * instant are derived from ONE number and can't drift apart. No-op if the app\n   * passed an explicit `renderDelay` to `room.input()` — an explicit value wins.\n   */\n  bindRenderDelay(provider: () => number): void {\n    if (this._renderDelayExplicit) return;\n    this._renderDelayProvider = provider;\n  }\n\n  /** Effective interp buffer (ms): a bound provider (the Predict lerp `delay`)\n   *  when present, else the static value from `room.input()`. */\n  private _resolveRenderDelay(): number {\n    return this._renderDelayProvider ? this._renderDelayProvider() : this._renderDelay;\n  }\n\n  /** Dev diagnostic (debug overlay only). An assignment to an UNDECLARED field\n   *  lands as a plain own property — declared fields live behind prototype\n   *  setters in the dense `$values` array and never create own keys — so any\n   *  own enumerable string key missing from the schema metadata is a write\n   *  that will never be encoded. Warn once per key. */\n  private _warnUnknownFields(): void {\n    const meta = metadataOf(this.data as object);\n    if (!meta) return;\n    for (const key of Object.keys(this.data as object)) {\n      if (meta[key] !== undefined || this._warnedUnknownKeys?.has(key)) continue;\n      (this._warnedUnknownKeys ??= new Set()).add(key);\n      console.warn(\n        `@colyseus/sdk input: \"${key}\" is not a declared field on ` +\n        `${(this.data as object).constructor.name} — the write is never encoded or sent. ` +\n        `Declare it with @type(...) on the input schema, or remove the write.`,\n      );\n    }\n  }\n\n  send(): number {\n    const conn = this._host.connection;\n    if (!conn?.isOpen) return 0;   // nothing transmitted → seq 0 (seqs are 1-based)\n\n    if (debugOverlayActive()) this._warnUnknownFields();\n\n    // May be 0-length on a no-change delta tick → we still frame + send a\n    // body-less input (server decodes it as a no-op, holding the last values).\n    // Callers skip a tick by not calling send(), not by relying on suppression.\n    const bytes = this._encoder.encode();\n    const reliable = this._encoder.mode === \"reliable\";\n\n    // Lag-comp stamp prefix. The two channels carry different shapes — one\n    // delta-coded stamp vs a self-contained per-slot block; see\n    // ProtocolModifier.TIMED and _writeRingStamps.\n    const stampsEnabled = this._stampReckon || this._stampRender;\n    // Evaluate `allowRewind` at most once: it's app code over live input data.\n    // `allowRewind` gates the RELIABLE channel only — the unreliable ring is\n    // all-or-nothing (see _writeRingStamps), so evaluating the app predicate\n    // there would be misleading as well as wasted.\n    const wantStamp = stampsEnabled && reliable\n      && (this._allowRewind === undefined || this._allowRewind(this.data));\n    const wantRingStamp = stampsEnabled && !reliable;\n    const both = this._stampReckon && this._stampRender;\n    const stampMax = wantStamp\n      ? RELIABLE_STAMP_MAX + (both ? 2 : 0)\n      : (wantRingStamp ? ringStampMax(this._encoder.historySize, both) : 0);\n    const totalMax = 1 + stampMax + bytes.length;\n    if (totalMax > this._scratch.byteLength) {\n      this._scratch = new Uint8Array(Math.max(totalMax, this._scratch.byteLength * 2));\n      this._framed = null;   // cached view points into the old buffer\n    }\n    this._scratch[0] = (reliable ? Protocol.ROOM_INPUT_RELIABLE : Protocol.ROOM_INPUT_UNRELIABLE)\n      | ((wantStamp || wantRingStamp) ? ProtocolModifier.TIMED : 0);\n\n    const it = { offset: 1 };\n    if (wantRingStamp) {\n      this._writeRingStamps(it);\n\n    } else if (wantStamp) {\n      // Delta-coded against the running baseline; BOTH trails the absolute u16.\n      const { stamp, renderDelta } = this._sampleStamp();\n      encode.number(this._scratch, stamp - this._lastStamp, it);\n      this._lastStamp = stamp;\n      if (both) { encode.uint16(this._scratch, renderDelta, it); }\n\n    } else {\n      this._pendingReckon = 0; // not stamping → no reckon instant to record\n    }\n\n    // [stamp?][body] — body continues from the stamp's end offset.\n    this._scratch.set(bytes, it.offset);\n    const total = it.offset + bytes.length;\n\n    if (this._framed === null || this._framed.byteLength !== total) {\n      this._framed = this._scratch.subarray(0, total);   // reused view (size varies only with the stamp prefix)\n    }\n    const framed = this._framed;\n    let seq: number;\n    if (reliable) {\n      conn.send(framed);\n      // Reliable: implicit count seq — the server counts received messages, so\n      // `_sentCount` mirrors its consumed counter for the next TIMED ack.\n      seq = ++this._sentCount;\n    } else {\n      conn.sendUnreliable(framed);\n      // Unreliable: adopt the encoder's framework seq (stamped on the wire) so the\n      // server's seq-value ack and this replay ring line up across packet loss.\n      seq = this._sentCount = this._encoder.seq;\n    }\n    this._recordSent(seq);\n    // Local, not _sentCount: a re-entrant send() from an onSend listener would\n    // have advanced the field before this returns.\n    return seq;\n  }\n\n  /**\n   * @internal Write the unreliable channel's self-contained stamp block, then\n   * leave `it` at the start of the ring body.\n   *\n   *     [varint k][uint32 newest][varint Δ]×(k−1)\n   *     [uint16 rdNewest][varint Δrd]×(k−1)        ← BOTH mode only\n   *\n   * `k` is the slot count of the ring this packet carries (oldest→newest, the\n   * order `InputDecoder.decodeAll` yields). `newest` is THIS send's timeline\n   * instant, absolute — so a packet is readable on its own and no amount of\n   * loss or reordering can desync a baseline. Each Δ walks one slot older\n   * (`stamp[i] = stamp[i+1] − Δ`), which is ≈ one fixed step and so ~1 byte\n   * through the self-describing number codec.\n   *\n   * BOTH mode appends the `renderDelta` series in the same shape, so every slot\n   * carries the interp buffer + one-way latency it was actually sampled with,\n   * rather than the newest slot's value smeared across the ring. Consecutive\n   * values differ by ~0–1 ms (`renderDelay` is app-set and constant,\n   * `smoothedRtt` is smoothed), which lands in the codec's 1-byte fixnum range —\n   * so exactness costs one byte per redundant slot, and a violent RTT swing\n   * degrades to at most 3 (the u16 range), never more.\n   *\n   * All-or-nothing: every slot in the block is stamped, or the room asked for\n   * no stamps and there is no block. `allowRewind` does not apply here — the\n   * block ships whole, so excluding one slot would save nothing while making\n   * its neighbour's delta swing the full absolute value. The one transient\n   * exception is the pre-clock-sync window, where the slots genuinely have no\n   * known instant and ship as 0 for the server to read live.\n   */\n  private _writeRingStamps(it: { offset: number }): void {\n    const { stamp, renderDelta } = this._sampleStamp();\n\n    const historySize = this._encoder.historySize;\n    const seq = this._encoder.seq;   // this send's seq — already advanced by encode()\n    // The packet carries the last `historySize` sends, or fewer while the ring\n    // is still filling (from construction or a reset()).\n    const k = this._ringSlots = Math.min(this._ringSlots + 1, historySize);\n\n    const ring = (this._stampRing ??= new Float64Array(historySize));\n    ring[seq % historySize] = stamp;\n    encode.number(this._scratch, k, it);\n    encode.uint32(this._scratch, stamp, it);\n    this._writeSeriesDeltas(ring, seq, k, it);\n\n    if (this._stampReckon && this._stampRender) {\n      // Uint16Array: renderDelta is already clamped to the u16 range, so the\n      // ring stores it exactly at half the width of the timeline ring.\n      const rdRing = (this._renderDeltaRing ??= new Uint16Array(historySize));\n      rdRing[seq % historySize] = renderDelta;\n      encode.uint16(this._scratch, renderDelta, it);\n      this._writeSeriesDeltas(rdRing, seq, k, it);\n    }\n  }\n\n  /** Walk `k` ring slots newest→oldest, emitting each step as a signed delta. */\n  private _writeSeriesDeltas(\n    ring: Float64Array | Uint16Array,\n    seq: number,\n    k: number,\n    it: { offset: number },\n  ): void {\n    const size = ring.length;\n    for (let i = 1; i < k; i++) {\n      encode.number(this._scratch, ring[(seq - i + 1) % size] - ring[(seq - i) % size], it);\n    }\n  }\n\n  /**\n   * @internal Sample this send's lag-comp instants from the clock, and record\n   * the reckon one for {@link reckonTimeAt}.\n   *\n   * `renderDelta` is the interp buffer (`renderDelay`, app-set) plus the one-way\n   * downstream latency (≈ `smoothedRtt/2`, ours). `stamp` is the timeline this\n   * room actually rewinds on: reckon rooms ship the estimate directly — the\n   * server reads its history at that index, so clock/RTT estimation error\n   * cancels (client displayed f(est), server reads f(est)) — while snapshot\n   * rooms ship `reckonTime − renderDelta`, the instant lerped remotes were on\n   * screen. BOTH ships reckon plus the gap and lets the server subtract.\n   *\n   * Everything is 0 before the clock syncs, or when `allowRewind` excluded this\n   * input: the server then falls back to live positions rather than trusting a\n   * bogus instant.\n   */\n  private _sampleStamp(): { stamp: number; renderDelta: number } {\n    const clock = this._host.clock;\n    const synced = (clock?.lastServerTime?.() ?? 0) > 0;\n    const rk = synced ? Math.max(0, Math.round(clock!.serverNow())) >>> 0 : 0;\n    const renderDelta = synced\n      ? Math.min(0xffff, Math.max(0, Math.round(this._resolveRenderDelay() + (clock!.smoothedRtt?.() ?? 0) / 2)))\n      : 0;\n    this._pendingReckon = rk;\n    // rk is 0 while unsynced, so this floors to 0 on its own.\n    return { stamp: this._stampReckon ? rk : (rk > renderDelta ? rk - renderDelta : 0), renderDelta };\n  }\n\n  /**\n   * @internal Snapshot the just-sent input into the replay ring and stamp its\n   * send time, keyed by `seq`. Lets a reconciler replay unacked inputs via\n   * {@link at} and the TIMED ack sample RTT. The snapshot is alloc-free through\n   * the codec's `copyInto` (no `Object.keys`), which stages every field, so\n   * each slot is a full snapshot independent of the wire delta encoding.\n   */\n  private _recordSent(seq: number): void {\n    if (this._inputBuffer === null) {\n      const Ctor = (this.data as any).constructor;\n      this._inputBuffer = Array.from({ length: this._inputBufferSize }, () => new Ctor() as I);\n    }\n    this._encoder.copyInto(this._inputBuffer[seq % this._inputBufferSize]);\n    this._sendTimes[seq % this._inputBufferSize] = now();\n    // Reckon ring only when reckon stamping is on (see _reckonTimes) — a room\n    // without reckon lag-comp never rewinds to it, so the allocation is skipped.\n    if (this._stampReckon) {\n      (this._reckonTimes ??= new Float64Array(this._inputBufferSize))[seq % this._inputBufferSize] = this._pendingReckon;\n    }\n    // Notify send observers LAST — the replay ring + reckon instant are now\n    // recorded, so a listener can read `at(seq)` / `reckonTimeAt(seq)`.\n    const ls = this._sendListeners;\n    if (ls !== null) for (let i = 0; i < ls.length; i++) ls[i](seq);\n  }\n\n  onSend(listener: (seq: number) => void): () => void {\n    const ls = this._sendListeners;\n    this._sendListeners = ls !== null ? [...ls, listener] : [listener];\n    return () => {\n      const cur = this._sendListeners;\n      if (cur === null) return;\n      const i = cur.indexOf(listener);\n      if (i < 0) return;\n      const next = cur.slice();\n      next.splice(i, 1);\n      this._sendListeners = next.length > 0 ? next : null;\n    };\n  }\n\n  /**\n   * @internal Feed the server's last-PROCESSED input seq (decoded from the\n   * TIMED prefix). Advances {@link lastProcessed} (monotonic) and returns the\n   * round-trip time sample for that ack (`now − sendTime(seq)`), or `-1` if the\n   * send time is unknown. The {@link RoomClockImpl} filters/EMA-smooths the sample.\n   */\n  ackInput(seq: number): number {\n    if (seq <= this._lastProcessed) return -1;\n    // Aged out of the seq ring window → RTT unknown.\n    const aged = this._sentCount - seq >= this._inputBufferSize;\n    this._lastProcessed = seq;\n    if (aged) return -1;\n    const sentAt = this._sendTimes[seq % this._inputBufferSize];\n    return sentAt > 0 ? now() - sentAt : -1;\n  }\n}\n"],"names":["metadataOf","debugOverlayActive","Protocol","ProtocolModifier","encode","now"],"mappings":";;;;;;;;;;;;;;AASA;AACA,MAAM,UAAU,GAAG,CAAC;AACpB;AACA,MAAM,kBAAkB,GAAG,UAAU;AACrC;AACA,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAE,IAAa,KACtD,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,UAAU,GAAG,WAAW,CAAC;AAoR9D;MACa,eAAe,CAAA;AAmG1B,IAAA,WAAA,CACE,IAAqB,EACrB,IAAO,EACP,OAA0B,EAC1B,IAA2K,EAAA;;;;;AAhGrK,QAAA,IAAA,CAAA,QAAQ,GAAe,IAAI,UAAU,CAAC,IAAI,CAAC;;;;QAI3C,IAAA,CAAA,OAAO,GAAsB,IAAI;;AAGjC,QAAA,IAAA,CAAA,UAAU,GAAG,CAAC,CAAC;AACf,QAAA,IAAA,CAAA,cAAc,GAAG,CAAC,CAAC;AACnB,QAAA,IAAA,CAAA,MAAM,GAAG,CAAC,CAAC;AAcX,QAAA,IAAA,CAAA,YAAY,GAAe,IAAI,CAAC;;;;;;;QAOhC,IAAA,CAAA,YAAY,GAAwB,IAAI;;;;QAIxC,IAAA,CAAA,cAAc,GAAG,CAAC;;;;;;;QAOlB,IAAA,CAAA,UAAU,GAAG,CAAC;;;;QAId,IAAA,CAAA,UAAU,GAAwB,IAAI;;;QAGtC,IAAA,CAAA,gBAAgB,GAAuB,IAAI;;;QAG3C,IAAA,CAAA,UAAU,GAAG,CAAC;;QAId,IAAA,CAAA,kBAAkB,GAAuB,IAAI;;;;;QAM7C,IAAA,CAAA,YAAY,GAAG,KAAK;QACpB,IAAA,CAAA,YAAY,GAAG,KAAK;;;;;;;QAapB,IAAA,CAAA,cAAc,GAAwC,IAAI;;;;;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