{"version":3,"sources":["../src/core/ErrorType.ts","../src/core/ExceptionCode.ts","../src/core/AsyncException.ts","../src/core/AsyncReply.ts","../src/data/Endian.ts","../src/data/DC.ts","../src/net/sockets/SocketState.ts","../src/net/NetworkBuffer.ts","../src/net/sockets/TcpSocket.ts","../src/index.ts","../src/internal/metadata.ts","../src/core/index.ts","../src/core/ProgressType.ts","../src/core/LogType.ts","../src/core/AsyncStreamReply.ts","../src/data/types/StreamMode.ts","../src/core/AsyncBag.ts","../src/core/AsyncQueue.ts","../src/core/EventHandler.ts","../src/data/index.ts","../src/data/Uuid.ts","../src/data/Int128.ts","../src/data/UInt128.ts","../src/data/Decimal128.ts","../src/data/TduClass.ts","../src/data/TduIdentifier.ts","../src/data/Tdu.ts","../src/data/ParserGuard.ts","../src/data/ParsedTdu.ts","../src/data/PlainTdu.ts","../src/data/NotModified.ts","../src/data/ResourceId.ts","../src/data/ResourceLink.ts","../src/data/widths.ts","../src/data/TruIdentifier.ts","../src/data/Tru.ts","../src/data/types/ITypeDef.ts","../src/data/descriptors.ts","../src/data/Codec.ts","../src/data/DataDeserializer.ts","../src/data/IndexedStructure.ts","../src/data/IndexAttribute.ts","../src/data/IndexedStructureCodec.ts","../src/data/types/TypeDefInfo.ts","../src/data/types/MemberDefInfo.ts","../src/data/types/PropertyDefInfo.ts","../src/data/types/FunctionDefInfo.ts","../src/data/types/EventDefInfo.ts","../src/data/types/ConstantDefInfo.ts","../src/data/types/ArgumentDefInfo.ts","../src/data/gvwie/groupCodec.ts","../src/data/gvwie/GroupInt16Codec.ts","../src/data/gvwie/GroupInt32Codec.ts","../src/data/gvwie/GroupInt64Codec.ts","../src/data/gvwie/GroupUInt16Codec.ts","../src/data/gvwie/GroupUInt32Codec.ts","../src/data/gvwie/GroupUInt64Codec.ts","../src/data/DataSerializer.ts","../src/resource/ResourceOperation.ts","../src/resource/template.ts","../src/resource/decorators.ts","../src/resource/IDynamicResource.ts","../src/resource/Instance.ts","../src/resource/Resource.ts","../src/resource/typedef.ts","../src/resource/records.ts","../src/resource/enums.ts","../src/resource/Warehouse.ts","../src/protocol/EpConnection.ts","../src/net/NetworkConnection.ts","../src/net/packets/EpPacket.ts","../src/net/packets/EpPacketMethod.ts","../src/net/packets/EpPacketRequest.ts","../src/net/packets/EpPacketReply.ts","../src/net/packets/EpPacketNotification.ts","../src/net/sockets/WSocket.ts","../src/net/packets/EpAuthPacket.ts","../src/net/packets/EpAuthPacketCommand.ts","../src/net/packets/EpAuthPacketMethod.ts","../src/security/AuthenticationMode.ts","../src/security/EncryptionMode.ts","../src/net/packets/EpAuthPacketHeader.ts","../src/security/AuthenticationDirection.ts","../src/security/AuthenticationMaterialType.ts","../src/security/AuthenticationResult.ts","../src/security/AuthenticationRuling.ts","../src/security/random.ts","../src/security/management/ResourceManagerContext.ts","../src/security/permissions/ActionType.ts","../src/resource/typeDefInfoCompose.ts","../src/protocol/EpResource.ts","../src/protocol/RemoteTypeDef.ts","../src/protocol/ServerInvocationContext.ts","../src/security/permissions/Ruling.ts","../src/security/management/ResourceManagerEvaluation.ts","../src/security/ratelimiting/RatePolicy.ts","../src/security/ratelimiting/NamedRateControlManager.ts","../src/resource/reactive.ts","../src/stores/MemoryStore.ts","../src/net/index.ts","../src/net/sockets/index.ts","../src/protocol/EpServer.ts","../src/security/sha3.ts","../src/security/providers/IdentityPassword.ts","../src/security/providers/PasswordAuthenticationHandler.ts","../src/security/providers/PasswordAuthenticationProvider.ts","../src/security/providers/PasswordHash.ts","../src/security/cryptography/AesEncryptionProvider.ts","../src/security/permissions/UserPermissionsManager.ts","../src/security/permissions/StorePermissionsManager.ts","../src/security/ratelimiting/BurstRatePolicy.ts"],"sourcesContent":["/** Category of an {@link AsyncException}. Wire-significant: sent in error replies. */\r\nexport enum ErrorType {\r\n  Management = 0,\r\n  Exception = 1,\r\n  Warning = 2,\r\n}\r\n","/**\r\n * Esiur management error codes (C# `ExceptionCode : ushort`).\r\n * Numeric values are wire-significant — keep order in sync with the C# enum.\r\n */\r\nexport enum ExceptionCode {\r\n  RuntimeException = 0,\r\n  HostNotReachable,\r\n  AccessDenied,\r\n  UserOrTokenNotFound,\r\n  ChallengeFailed,\r\n  ResourceNotFound,\r\n  AttachDenied,\r\n  InvalidMethod,\r\n  InvokeDenied,\r\n  CreateDenied,\r\n  AddParentDenied,\r\n  AddChildDenied,\r\n  ViewAttributeDenied,\r\n  UpdateAttributeDenied,\r\n  StoreNotFound,\r\n  ParentNotFound,\r\n  ChildNotFound,\r\n  ResourceIsNotStore,\r\n  DeleteDenied,\r\n  DeleteFailed,\r\n  UpdateAttributeFailed,\r\n  GetAttributesFailed,\r\n  ClearAttributesFailed,\r\n  TypeDefNotFound,\r\n  RenameDenied,\r\n  ClassNotFound,\r\n  MethodNotFound,\r\n  PropertyNotFound,\r\n  SetPropertyDenied,\r\n  ReadOnlyProperty,\r\n  GeneralFailure,\r\n  AddToStoreFailed,\r\n  NotAttached,\r\n  AlreadyListened,\r\n  AlreadyUnsubscribed,\r\n  NotSubscribable,\r\n  ParseError,\r\n  Timeout,\r\n  NotSupported,\r\n  NotImplemented,\r\n  NotAllowed,\r\n}\r\n","import { ErrorType } from \"./ErrorType.js\";\r\nimport { ExceptionCode } from \"./ExceptionCode.js\";\r\n\r\n/**\r\n * Error type used throughout Esiur (port of C# `AsyncException`).\r\n *\r\n * Carries an {@link ErrorType} category and an {@link ExceptionCode}. Wrapping a\r\n * plain error produces a `Type = Exception` instance with `Code = RuntimeException`.\r\n */\r\nexport class AsyncException extends Error {\r\n  readonly type: ErrorType;\r\n  readonly code: ExceptionCode;\r\n  /** The original error, when this wraps a thrown exception. */\r\n  readonly inner?: Error;\r\n\r\n  constructor(inner: Error);\r\n  constructor(type: ErrorType, code: number, message: string);\r\n  constructor(\r\n    typeOrInner: ErrorType | Error,\r\n    code?: number,\r\n    message?: string,\r\n  ) {\r\n    if (typeOrInner instanceof Error) {\r\n      super(typeOrInner.message);\r\n      this.type = ErrorType.Exception;\r\n      this.code = ExceptionCode.RuntimeException;\r\n      this.inner = typeOrInner;\r\n      if (typeOrInner.stack) this.stack = typeOrInner.stack;\r\n    } else {\r\n      super(message ?? \"\");\r\n      this.type = typeOrInner;\r\n      this.code = (code ?? 0) as ExceptionCode;\r\n    }\r\n    this.name = \"AsyncException\";\r\n    Object.setPrototypeOf(this, AsyncException.prototype);\r\n  }\r\n\r\n  override toString(): string {\r\n    return `${ExceptionCode[this.code] ?? this.code}: ${this.message}`;\r\n  }\r\n\r\n  /** Coerce any thrown value into an {@link AsyncException}. */\r\n  static from(value: unknown): AsyncException {\r\n    if (value instanceof AsyncException) return value;\r\n    if (value instanceof Error) return new AsyncException(value);\r\n    return new AsyncException(new Error(String(value)));\r\n  }\r\n}\r\n","import { AsyncException } from \"./AsyncException.js\";\r\nimport { ErrorType } from \"./ErrorType.js\";\r\nimport { ExceptionCode } from \"./ExceptionCode.js\";\r\nimport { ProgressType } from \"./ProgressType.js\";\r\n\r\ntype Awaitable<R> = R | AsyncReply<R> | PromiseLike<R>;\r\ntype FulfilledFn<T, R> = (value: T) => Awaitable<R>;\r\ntype RejectedFn<R> = (reason: AsyncException) => Awaitable<R>;\r\n\r\nfunction isThenable(v: unknown): v is PromiseLike<unknown> {\r\n  return (\r\n    v != null &&\r\n    (typeof v === \"object\" || typeof v === \"function\") &&\r\n    typeof (v as { then?: unknown }).then === \"function\"\r\n  );\r\n}\r\n\r\n/**\r\n * Esiur's universal asynchronous result (port of C# `AsyncReply<T>`).\r\n *\r\n * It is a {@link PromiseLike} — `await reply` works and `then`/`catch`/`finally`\r\n * behave like a Promise — while additionally exposing Esiur's side channels:\r\n * `progress`, `chunk`, `propagation` and `warning`. Unlike a native Promise,\r\n * callbacks registered after the result is ready are invoked **synchronously**,\r\n * matching the C# implementation.\r\n *\r\n * The blocking `Wait()` of the C# version is intentionally omitted (JS has no\r\n * synchronous blocking); use `await` instead.\r\n */\r\nexport class AsyncReply<T = any> implements PromiseLike<T> {\r\n  protected _ready = false;\r\n  protected _result: T | undefined = undefined;\r\n  protected _exception: AsyncException | undefined = undefined;\r\n\r\n  protected readonly _callbacks: Array<(value: T) => void> = [];\r\n  private _errorCallbacks: Array<(ex: AsyncException) => void> | null = null;\r\n  private _progressCallbacks:\r\n    | Array<(type: ProgressType, value: number, max: number) => void>\r\n    | null = null;\r\n  private _chunkCallbacks: Array<(value: unknown) => void> | null = null;\r\n  private _propagationCallbacks: Array<(value: unknown) => void> | null = null;\r\n  private _warningCallbacks: Array<(level: number, message: string) => void> | null =\r\n    null;\r\n\r\n  /** Wall-clock time the result became ready. */\r\n  readyTime: number | undefined;\r\n\r\n  constructor(result?: T) {\r\n    if (arguments.length > 0) {\r\n      this._ready = true;\r\n      this._result = result;\r\n      this.readyTime = Date.now();\r\n    }\r\n  }\r\n\r\n  /** True once a result has been delivered. */\r\n  get ready(): boolean {\r\n    return this._ready;\r\n  }\r\n\r\n  /** True if the reply completed with an error. */\r\n  get failed(): boolean {\r\n    return this._exception != null;\r\n  }\r\n\r\n  /** The exception, if {@link failed}. */\r\n  get exception(): AsyncException | undefined {\r\n    return this._exception;\r\n  }\r\n\r\n  /** The result value, or `undefined` if not ready. */\r\n  get result(): T | undefined {\r\n    return this._result;\r\n  }\r\n\r\n  /** A pre-resolved reply. */\r\n  static fromResult<U>(result: U): AsyncReply<U> {\r\n    return new AsyncReply<U>(result);\r\n  }\r\n\r\n  // ---- PromiseLike / chaining -------------------------------------------------\r\n\r\n  then<R1 = T, R2 = never>(\r\n    onFulfilled?: FulfilledFn<T, R1> | null,\r\n    onRejected?: RejectedFn<R2> | null,\r\n  ): AsyncReply<R1 | R2> {\r\n    const derived = new AsyncReply<R1 | R2>();\r\n\r\n    const handleValue = (value: T): void => {\r\n      if (!onFulfilled) {\r\n        derived.trigger(value as unknown as R1);\r\n        return;\r\n      }\r\n      try {\r\n        chain(derived, onFulfilled(value));\r\n      } catch (e) {\r\n        derived.triggerError(AsyncException.from(e));\r\n      }\r\n    };\r\n\r\n    const handleError = (ex: AsyncException): void => {\r\n      if (!onRejected) {\r\n        derived.triggerError(ex);\r\n        return;\r\n      }\r\n      try {\r\n        chain(derived, onRejected(ex));\r\n      } catch (e) {\r\n        derived.triggerError(AsyncException.from(e));\r\n      }\r\n    };\r\n\r\n    if (this._ready) {\r\n      handleValue(this._result as T);\r\n    } else if (this._exception != null) {\r\n      handleError(this._exception);\r\n    } else {\r\n      this._callbacks.push(handleValue);\r\n      this.addErrorHandler(handleError);\r\n    }\r\n\r\n    return derived;\r\n  }\r\n\r\n  /** Promise-style rejection handler. */\r\n  catch<R = never>(onRejected: RejectedFn<R>): AsyncReply<T | R> {\r\n    return this.then(null, onRejected);\r\n  }\r\n\r\n  /** Promise-style settle handler. */\r\n  finally(onFinally: () => void): AsyncReply<T> {\r\n    return this.then(\r\n      (v) => {\r\n        onFinally();\r\n        return v;\r\n      },\r\n      (e) => {\r\n        onFinally();\r\n        throw e;\r\n      },\r\n    ) as AsyncReply<T>;\r\n  }\r\n\r\n  // ---- Esiur fluent side-channels (return `this`) -----------------------------\r\n\r\n  /** Register a result handler (C# `Then`); returns `this` for chaining channels. */\r\n  onReady(callback: (value: T) => void): this {\r\n    if (this._ready) {\r\n      callback(this._result as T);\r\n    } else {\r\n      this._callbacks.push(callback);\r\n    }\r\n    return this;\r\n  }\r\n\r\n  /** Register an error handler (C# `Error`). */\r\n  error(callback: (ex: AsyncException) => void): this {\r\n    this.addErrorHandler(callback);\r\n    if (this._exception != null) callback(this._exception);\r\n    return this;\r\n  }\r\n\r\n  /** Register a progress handler. */\r\n  progress(\r\n    callback: (type: ProgressType, value: number, max: number) => void,\r\n  ): this {\r\n    (this._progressCallbacks ??= []).push(callback);\r\n    return this;\r\n  }\r\n\r\n  /** Register a chunk handler (streamed partial values). */\r\n  chunk(callback: (value: unknown) => void): this {\r\n    (this._chunkCallbacks ??= []).push(callback);\r\n    return this;\r\n  }\r\n\r\n  /** Register a propagation handler. */\r\n  propagation(callback: (value: unknown) => void): this {\r\n    (this._propagationCallbacks ??= []).push(callback);\r\n    return this;\r\n  }\r\n\r\n  /** Register a warning handler. */\r\n  warning(callback: (level: number, message: string) => void): this {\r\n    (this._warningCallbacks ??= []).push(callback);\r\n    return this;\r\n  }\r\n\r\n  private addErrorHandler(callback: (ex: AsyncException) => void): void {\r\n    (this._errorCallbacks ??= []).push(callback);\r\n  }\r\n\r\n  // ---- Triggers ---------------------------------------------------------------\r\n\r\n  /** Deliver the result. No-op if already settled. */\r\n  trigger(result: T): void {\r\n    if (this._exception != null || this._ready) return;\r\n\r\n    this.readyTime = Date.now();\r\n    this._result = result;\r\n    this._ready = true;\r\n\r\n    for (const cb of this._callbacks.slice()) cb(result);\r\n  }\r\n\r\n  /** Fail the reply. No-op if a result was already delivered. */\r\n  triggerError(exception: Error | AsyncException): void {\r\n    if (this._ready || this._exception != null) return;\r\n\r\n    this._exception = AsyncException.from(exception);\r\n\r\n    if (this._errorCallbacks != null) {\r\n      for (const cb of this._errorCallbacks.slice()) cb(this._exception);\r\n    }\r\n  }\r\n\r\n  triggerProgress(type: ProgressType, value: number, max: number): void {\r\n    if (this._progressCallbacks != null)\r\n      for (const cb of this._progressCallbacks.slice()) cb(type, value, max);\r\n  }\r\n\r\n  triggerWarning(level: number, message: string): void {\r\n    if (this._warningCallbacks != null)\r\n      for (const cb of this._warningCallbacks.slice()) cb(level, message);\r\n  }\r\n\r\n  triggerChunk(value: unknown): void {\r\n    if (this._chunkCallbacks != null)\r\n      for (const cb of this._chunkCallbacks.slice()) cb(value);\r\n  }\r\n\r\n  triggerPropagation(value: unknown): void {\r\n    if (this._propagationCallbacks != null)\r\n      for (const cb of this._propagationCallbacks.slice()) cb(value);\r\n  }\r\n\r\n  /** Fail the reply with a Timeout error after `ms` if it has not settled. */\r\n  timeout(ms: number, callback?: () => void): this {\r\n    setTimeout(() => {\r\n      if (!this._ready && this._exception == null) {\r\n        this.triggerError(\r\n          new AsyncException(\r\n            ErrorType.Management,\r\n            ExceptionCode.Timeout,\r\n            \"Execution timeout expired.\",\r\n          ),\r\n        );\r\n        callback?.();\r\n      }\r\n    }, ms);\r\n    return this;\r\n  }\r\n}\r\n\r\n/** Resolve `derived` with `value`, following the value if it is itself thenable. */\r\nfunction chain<R>(derived: AsyncReply<R>, value: Awaitable<R>): void {\r\n  if (value instanceof AsyncReply) {\r\n    value.onReady((v) => derived.trigger(v));\r\n    value.error((e) => derived.triggerError(e));\r\n  } else if (isThenable(value)) {\r\n    value.then(\r\n      (v) => derived.trigger(v as R),\r\n      (e) => derived.triggerError(AsyncException.from(e)),\r\n    );\r\n  } else {\r\n    derived.trigger(value);\r\n  }\r\n}\r\n","/** Byte order. The Esiur wire format is little-endian by default. */\r\nexport enum Endian {\r\n  Big = 0,\r\n  Little = 1,\r\n}\r\n","import { Endian } from \"./Endian.js\";\r\n\r\n/**\r\n * Data Converter (port of C# `DC`). Free functions to convert primitive values\r\n * to/from their byte representation on a `Uint8Array`, plus byte-buffer helpers.\r\n *\r\n * Conventions:\r\n *  - 8/16/32-bit integers and floats use `number`; 64-bit integers use `bigint`.\r\n *  - The wire format is little-endian; `endian` defaults to {@link Endian.Little}.\r\n */\r\n\r\nconst LITTLE = Endian.Little;\r\n\r\nconst textEncoder = new TextEncoder();\r\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: false });\r\n\r\n/** Milliseconds between .NET epoch (0001-01-01) and Unix epoch (1970-01-01). */\r\nexport const DOTNET_EPOCH_OFFSET_MS = 62135596800000;\r\n/** .NET ticks per millisecond (1 tick = 100 ns). */\r\nexport const TICKS_PER_MS = 10000n;\r\n\r\nfunction view(buf: Uint8Array): DataView {\r\n  return new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\r\n}\r\n\r\n// ---- value -> bytes ---------------------------------------------------------\r\n\r\nexport function boolToBytes(value: boolean): Uint8Array {\r\n  return new Uint8Array([value ? 1 : 0]);\r\n}\r\n\r\nexport function uint8ToBytes(value: number): Uint8Array {\r\n  return new Uint8Array([value & 0xff]);\r\n}\r\n\r\nexport function int8ToBytes(value: number): Uint8Array {\r\n  return new Uint8Array([value & 0xff]);\r\n}\r\n\r\nexport function int16ToBytes(value: number, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(2);\r\n  view(b).setInt16(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function uint16ToBytes(value: number, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(2);\r\n  view(b).setUint16(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function int32ToBytes(value: number, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(4);\r\n  view(b).setInt32(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function uint32ToBytes(value: number, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(4);\r\n  view(b).setUint32(0, value >>> 0, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function int64ToBytes(value: bigint, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(8);\r\n  view(b).setBigInt64(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function uint64ToBytes(value: bigint, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(8);\r\n  view(b).setBigUint64(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function float32ToBytes(value: number, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(4);\r\n  view(b).setFloat32(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\nexport function float64ToBytes(value: number, endian: Endian = LITTLE): Uint8Array {\r\n  const b = new Uint8Array(8);\r\n  view(b).setFloat64(0, value, endian === LITTLE);\r\n  return b;\r\n}\r\n\r\n/** UTF-8 encode a string (no length prefix). */\r\nexport function stringToBytes(value: string): Uint8Array {\r\n  return textEncoder.encode(value);\r\n}\r\n\r\n/** A .NET `DateTime` as a little-endian int64 of UTC ticks. */\r\nexport function dateTimeToBytes(value: Date): Uint8Array {\r\n  return int64ToBytes(dateToTicks(value), LITTLE);\r\n}\r\n\r\n/** Convert a JS `Date` to .NET UTC ticks. */\r\nexport function dateToTicks(value: Date): bigint {\r\n  return (BigInt(value.getTime()) + BigInt(DOTNET_EPOCH_OFFSET_MS)) * TICKS_PER_MS;\r\n}\r\n\r\n/** Convert .NET UTC ticks to a JS `Date`. */\r\nexport function ticksToDate(ticks: bigint): Date {\r\n  return new Date(Number(ticks / TICKS_PER_MS) - DOTNET_EPOCH_OFFSET_MS);\r\n}\r\n\r\n// ---- bytes -> value ---------------------------------------------------------\r\n\r\nexport function getUint8(data: Uint8Array, offset: number): number {\r\n  return data[offset];\r\n}\r\n\r\nexport function getInt8(data: Uint8Array, offset: number): number {\r\n  return (data[offset] << 24) >> 24;\r\n}\r\n\r\nexport function getInt16(data: Uint8Array, offset: number, endian: Endian = LITTLE): number {\r\n  return view(data).getInt16(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getUint16(data: Uint8Array, offset: number, endian: Endian = LITTLE): number {\r\n  return view(data).getUint16(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getInt32(data: Uint8Array, offset: number, endian: Endian = LITTLE): number {\r\n  return view(data).getInt32(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getUint32(data: Uint8Array, offset: number, endian: Endian = LITTLE): number {\r\n  return view(data).getUint32(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getInt64(data: Uint8Array, offset: number, endian: Endian = LITTLE): bigint {\r\n  return view(data).getBigInt64(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getUint64(data: Uint8Array, offset: number, endian: Endian = LITTLE): bigint {\r\n  return view(data).getBigUint64(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getFloat32(data: Uint8Array, offset: number, endian: Endian = LITTLE): number {\r\n  return view(data).getFloat32(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getFloat64(data: Uint8Array, offset: number, endian: Endian = LITTLE): number {\r\n  return view(data).getFloat64(offset, endian === LITTLE);\r\n}\r\n\r\nexport function getBoolean(data: Uint8Array, offset: number): boolean {\r\n  return data[offset] > 0;\r\n}\r\n\r\n/** Decode `length` bytes of UTF-8 starting at `offset`. */\r\nexport function getString(data: Uint8Array, offset: number, length: number): string {\r\n  return textDecoder.decode(data.subarray(offset, offset + length));\r\n}\r\n\r\nexport function getDateTime(data: Uint8Array, offset: number, endian: Endian = LITTLE): Date {\r\n  return ticksToDate(getInt64(data, offset, endian));\r\n}\r\n\r\n// ---- buffer helpers ---------------------------------------------------------\r\n\r\n/** Concatenate any number of byte arrays. */\r\nexport function merge(...arrays: Uint8Array[]): Uint8Array {\r\n  let total = 0;\r\n  for (const a of arrays) total += a.length;\r\n  const out = new Uint8Array(total);\r\n  let offset = 0;\r\n  for (const a of arrays) {\r\n    out.set(a, offset);\r\n    offset += a.length;\r\n  }\r\n  return out;\r\n}\r\n\r\n/** Concatenate two byte ranges (port of C# `DC.Combine`). */\r\nexport function combine(\r\n  src1: Uint8Array,\r\n  src1Offset: number,\r\n  src1Length: number,\r\n  src2: Uint8Array,\r\n  src2Offset: number,\r\n  src2Length: number,\r\n): Uint8Array {\r\n  const out = new Uint8Array(src1Length + src2Length);\r\n  out.set(src1.subarray(src1Offset, src1Offset + src1Length), 0);\r\n  out.set(src2.subarray(src2Offset, src2Offset + src2Length), src1Length);\r\n  return out;\r\n}\r\n\r\n/** Return a copy of `length` bytes starting at `offset`. */\r\nexport function clip(data: Uint8Array, offset: number, length: number): Uint8Array {\r\n  if (data.length < offset + length)\r\n    throw new RangeError(\"Length exceeds array boundary.\");\r\n  return data.slice(offset, offset + length);\r\n}\r\n\r\nconst HEX = \"0123456789abcdef\";\r\n\r\n/** Lowercase hex of a byte range (no separator by default). */\r\nexport function toHex(data: Uint8Array, offset = 0, length = data.length - offset, separator = \"\"): string {\r\n  const parts: string[] = [];\r\n  for (let i = 0; i < length; i++) {\r\n    const b = data[offset + i];\r\n    parts.push(HEX[b >> 4] + HEX[b & 0xf]);\r\n  }\r\n  return parts.join(separator);\r\n}\r\n\r\n/** Parse a hex string (optionally separated) into bytes. */\r\nexport function fromHex(hex: string, separator: string | null = \" \"): Uint8Array {\r\n  const tokens =\r\n    separator == null\r\n      ? (hex.match(/.{1,2}/g) ?? [])\r\n      : hex.split(separator).filter((t) => t.length > 0);\r\n  const out = new Uint8Array(tokens.length);\r\n  for (let i = 0; i < tokens.length; i++) out[i] = parseInt(tokens[i], 16) & 0xff;\r\n  return out;\r\n}\r\n","/** Lifecycle state of an {@link ISocket} (port of C# `SocketState`). */\r\nexport enum SocketState {\r\n  Initial = 0,\r\n  Listening = 1,\r\n  Connecting = 2,\r\n  Established = 3,\r\n  Closed = 4,\r\n}\r\n","import { combine } from \"../data/DC.js\";\r\n\r\n/**\r\n * Accumulating receive buffer (port of C# `NetworkBuffer`). The protocol parser\r\n * drains it with {@link read}; when a partial unit remains, it calls\r\n * {@link protect}/{@link holdFor} to push the unparsed tail back so it is\r\n * prepended to the next {@link write}. {@link protected_} is true while waiting\r\n * for more bytes.\r\n */\r\nexport class NetworkBuffer {\r\n  private data: Uint8Array = new Uint8Array(0);\r\n  private neededDataLength = 0;\r\n\r\n  /** True while more bytes are required before the held data can be read. */\r\n  get protected_(): boolean {\r\n    return this.neededDataLength > this.data.length;\r\n  }\r\n\r\n  /** Number of buffered bytes. */\r\n  get available(): number {\r\n    return this.data.length;\r\n  }\r\n\r\n  /** Hold the next write, expecting at least `src.length + 1` bytes total. */\r\n  holdForNextWrite(src: Uint8Array): void {\r\n    this.holdFor(src, 0, src.length, src.length + 1);\r\n  }\r\n\r\n  /** Prepend `src[offset..offset+size]` to the buffer and wait for `needed` bytes. */\r\n  holdFor(src: Uint8Array, offset: number, size: number, needed: number): void {\r\n    if (size >= needed) throw new Error(\"Size >= Needed!\");\r\n    this.data = combine(src, offset, size, this.data, 0, this.data.length);\r\n    this.neededDataLength = needed;\r\n  }\r\n\r\n  /**\r\n   * If `src` from `offset` has fewer than `needed` bytes, hold the remainder and\r\n   * return true (caller should stop and wait); otherwise return false.\r\n   */\r\n  protect(src: Uint8Array, offset: number, needed: number): boolean {\r\n    const dataLength = src.length - offset;\r\n    if (dataLength < needed) {\r\n      this.holdFor(src, offset, dataLength, needed);\r\n      return true;\r\n    }\r\n    return false;\r\n  }\r\n\r\n  /** Append bytes to the buffer. */\r\n  write(src: Uint8Array, offset = 0, length = src.length - offset): void {\r\n    const out = new Uint8Array(this.data.length + length);\r\n    out.set(this.data, 0);\r\n    out.set(src.subarray(offset, offset + length), this.data.length);\r\n    this.data = out;\r\n  }\r\n\r\n  /** True if a full held unit (or any data, when not holding) is available. */\r\n  get canRead(): boolean {\r\n    return this.data.length > 0 && this.data.length >= this.neededDataLength;\r\n  }\r\n\r\n  /** Take all buffered bytes if available (respecting any hold), else null. */\r\n  read(): Uint8Array | null {\r\n    if (this.data.length === 0) return null;\r\n\r\n    if (this.neededDataLength === 0) {\r\n      const rt = this.data;\r\n      this.data = new Uint8Array(0);\r\n      return rt;\r\n    }\r\n\r\n    if (this.data.length >= this.neededDataLength) {\r\n      const rt = this.data;\r\n      this.data = new Uint8Array(0);\r\n      this.neededDataLength = 0;\r\n      return rt;\r\n    }\r\n\r\n    return null;\r\n  }\r\n}\r\n","import { AsyncReply } from \"../../core/AsyncReply.js\";\r\nimport { AsyncException } from \"../../core/AsyncException.js\";\r\nimport type { DestroyedEvent } from \"../../core/IDestructible.js\";\r\nimport { NetworkBuffer } from \"../NetworkBuffer.js\";\r\nimport type { INetworkReceiver } from \"../INetworkReceiver.js\";\r\nimport type { ISocket } from \"./ISocket.js\";\r\nimport { SocketState } from \"./SocketState.js\";\r\n\r\ntype NodeSocket = import(\"node:net\").Socket;\r\ntype NetModule = typeof import(\"node:net\");\r\n\r\n/**\r\n * Raw TCP transport (port of C# `TcpSocket`), for Node.js hosts talking to an\r\n * esiur-dotnet server that only listens on its native TCP `TcpServer` (no\r\n * WebSocket upgrade route registered) — esiur-ts could otherwise only ever\r\n * connect via {@link WSocket}.\r\n *\r\n * Node-only: `node:net` is loaded via a dynamic `import()` inside\r\n * {@link connect} rather than a static top-level import, matching\r\n * `WSocket.ts`'s environment-detection convention exactly — this file's mere\r\n * existence (and the type-only `import(\"node:net\")` above, erased at compile\r\n * time) is safe to ship in a browser bundle; it only throws if actually\r\n * connected to from a non-Node runtime.\r\n */\r\nexport class TcpSocket implements ISocket {\r\n  state: SocketState = SocketState.Initial;\r\n  receiver?: INetworkReceiver<ISocket>;\r\n\r\n  private sock?: NodeSocket;\r\n  private readonly buffer = new NetworkBuffer();\r\n  private readonly destroyHandlers: DestroyedEvent[] = [];\r\n\r\n  /** `url` is `tcp://host:port`. */\r\n  connect(url: string): AsyncReply<boolean> {\r\n    const reply = new AsyncReply<boolean>();\r\n    this.state = SocketState.Connecting;\r\n\r\n    (async () => {\r\n      try {\r\n        const { hostname, port } = parseTcpUrl(url);\r\n        const net = await getNetModule();\r\n\r\n        if (this.state !== SocketState.Connecting) return;\r\n\r\n        const sock = net.connect({ host: hostname, port });\r\n        this.attach(sock);\r\n\r\n        sock.once(\"connect\", () => {\r\n          this.state = SocketState.Established;\r\n          reply.trigger(true);\r\n          this.receiver?.networkConnect(this);\r\n        });\r\n        sock.once(\"error\", (err: Error) => {\r\n          if (this.state === SocketState.Connecting) reply.triggerError(AsyncException.from(err));\r\n        });\r\n      } catch (error) {\r\n        this.state = SocketState.Closed;\r\n        reply.triggerError(AsyncException.from(error));\r\n      }\r\n    })();\r\n\r\n    return reply;\r\n  }\r\n\r\n  private attach(sock: NodeSocket): void {\r\n    this.sock = sock;\r\n\r\n    sock.on(\"data\", (chunk: Buffer) => {\r\n      this.buffer.write(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));\r\n      this.receiver?.networkReceive(this, this.buffer);\r\n    });\r\n    sock.on(\"close\", () => {\r\n      this.state = SocketState.Closed;\r\n      this.receiver?.networkClose(this);\r\n    });\r\n    // A post-handshake error (post-`connect`) should still tear the socket\r\n    // down cleanly rather than crash the process on an unhandled 'error'.\r\n    sock.on(\"error\", () => {\r\n      if (this.state !== SocketState.Connecting) this.close();\r\n    });\r\n  }\r\n\r\n  send(message: Uint8Array): void {\r\n    this.sock?.write(message);\r\n  }\r\n\r\n  close(): void {\r\n    this.state = SocketState.Closed;\r\n    this.sock?.end();\r\n  }\r\n\r\n  addDestroyHandler(handler: DestroyedEvent): void {\r\n    this.destroyHandlers.push(handler);\r\n  }\r\n\r\n  removeDestroyHandler(handler: DestroyedEvent): void {\r\n    const i = this.destroyHandlers.indexOf(handler);\r\n    if (i >= 0) this.destroyHandlers.splice(i, 1);\r\n  }\r\n\r\n  destroy(): void {\r\n    this.close();\r\n    this.receiver = undefined;\r\n    this.sock = undefined;\r\n    for (const h of this.destroyHandlers.slice()) h(this);\r\n  }\r\n}\r\n\r\nfunction parseTcpUrl(url: string): { hostname: string; port: number } {\r\n  let parsed: URL;\r\n  try {\r\n    parsed = new URL(url);\r\n  } catch {\r\n    throw new Error(`Invalid TCP URL: ${url}`);\r\n  }\r\n  const port = Number(parsed.port);\r\n  if (!parsed.hostname || !Number.isFinite(port) || port <= 0)\r\n    throw new Error(`Invalid TCP URL: ${url}`);\r\n  return { hostname: parsed.hostname, port };\r\n}\r\n\r\nasync function getNetModule(): Promise<NetModule> {\r\n  try {\r\n    return await import(\"node:net\");\r\n  } catch (error) {\r\n    throw new Error(\r\n      \"TcpSocket requires Node.js — the 'node:net' module is unavailable in this environment.\",\r\n      { cause: error },\r\n    );\r\n  }\r\n}\r\n","// Public entry point for the `esiur` package.\r\n// Re-exports are added phase-by-phase as the port progresses.\r\n\r\nimport \"./internal/metadata.js\";\r\n\r\n// Phase 1 — Foundation\r\nexport * from \"./core/index.js\";\r\nexport * from \"./data/index.js\";\r\n\r\n// Phase 3 — Resource model + stores\r\nexport * from \"./resource/index.js\";\r\nexport * from \"./stores/index.js\";\r\n\r\n// Phase 4 — Networking\r\nexport * from \"./net/index.js\";\r\n\r\n// Phase 5 — IIP/Ep protocol\r\nexport * from \"./protocol/index.js\";\r\n\r\n// Phase 6 — Security / auth\r\nexport * from \"./security/index.js\";\r\n","/**\r\n * Runtime shim for `Symbol.metadata` (TC39 decorator-metadata proposal).\r\n *\r\n * TS 5 standard decorators read/write per-class metadata through `Symbol.metadata`.\r\n * Some runtimes (e.g. current Node) don't define it yet, so we polyfill it with a\r\n * registered symbol. This module must be imported before any decorated class is\r\n * evaluated; the decorator implementations import it for that reason.\r\n */\r\ndeclare global {\r\n  interface SymbolConstructor {\r\n    readonly metadata: unique symbol;\r\n  }\r\n}\r\n\r\nif (typeof (Symbol as { metadata?: symbol }).metadata !== \"symbol\") {\r\n  Object.defineProperty(Symbol, \"metadata\", {\r\n    value: Symbol.for(\"Symbol.metadata\"),\r\n    writable: false,\r\n    enumerable: false,\r\n    configurable: true,\r\n  });\r\n}\r\n\r\nexport {};\r\n","export * from \"./ErrorType.js\";\r\nexport * from \"./ExceptionCode.js\";\r\nexport * from \"./ProgressType.js\";\r\nexport * from \"./LogType.js\";\r\nexport * from \"./AsyncException.js\";\r\nexport * from \"./IDestructible.js\";\r\nexport * from \"./AsyncReply.js\";\r\nexport * from \"./AsyncStreamReply.js\";\r\nexport * from \"./AsyncBag.js\";\r\nexport * from \"./AsyncQueue.js\";\r\nexport * from \"./EventHandler.js\";\r\n","/** Phase a progress report refers to. */\r\nexport enum ProgressType {\r\n  Execution = 0,\r\n  Network = 1,\r\n}\r\n","/** Severity for library logging. */\r\nexport enum LogType {\r\n  Debug = 0,\r\n  Warning = 1,\r\n  Error = 2,\r\n}\r\n","import { AsyncReply } from \"./AsyncReply.js\";\r\nimport { AsyncException } from \"./AsyncException.js\";\r\nimport { StreamMode } from \"../data/types/StreamMode.js\";\r\n\r\n/** A minimal deferred promise (stands in for C#'s `TaskCompletionSource`). */\r\ninterface Deferred<T> {\r\n  promise: Promise<T>;\r\n  resolve: (value: T) => void;\r\n  reject: (error: unknown) => void;\r\n  settled: boolean;\r\n}\r\n\r\nfunction createDeferred<T>(): Deferred<T> {\r\n  let resolve!: (value: T) => void;\r\n  let reject!: (error: unknown) => void;\r\n  const promise = new Promise<T>((res, rej) => {\r\n    resolve = res;\r\n    reject = rej;\r\n  });\r\n  const d: Deferred<T> = { promise, resolve: () => {}, reject: () => {}, settled: false };\r\n  d.resolve = (value: T) => {\r\n    if (d.settled) return;\r\n    d.settled = true;\r\n    resolve(value);\r\n  };\r\n  d.reject = (error: unknown) => {\r\n    if (d.settled) return;\r\n    d.settled = true;\r\n    reject(error);\r\n  };\r\n  return d;\r\n}\r\n\r\n/**\r\n * Represents a remotely executing stream and exposes its lifecycle controls\r\n * (port of C# `AsyncStreamReply`/`AsyncStreamReply<T>`, collapsed into one\r\n * generic class — TS has no need for C#'s non-generic/generic split, which\r\n * exists only because `IAsyncEnumerable<T>` needs a concrete `T`).\r\n *\r\n * All of C#'s `lock (_streamLock)`/`lock (_itemsLock)` blocks are dropped:\r\n * they're pure mutual-exclusion guards around synchronous state mutation,\r\n * with no JS equivalent needed since none of these methods yield to the\r\n * event loop mid-mutation.\r\n */\r\nexport class AsyncStreamReply<T = unknown> extends AsyncReply<T> implements AsyncIterable<T> {\r\n  private streamStarted = false;\r\n  private streamCompleted = false;\r\n  private terminationSent = false;\r\n  private streamException: AsyncException | undefined;\r\n  private readonly startedDeferred = createDeferred<void>();\r\n\r\n  private readonly items: T[] = [];\r\n  private itemAvailable: Deferred<void> | undefined;\r\n  private enumeratorCreated = false;\r\n  private movePending = false;\r\n\r\n  constructor(\r\n    readonly streamMode: StreamMode,\r\n    private readonly pullFn: () => AsyncReply,\r\n    private readonly terminateFn: () => AsyncReply,\r\n    private readonly haltFn: () => AsyncReply,\r\n    private readonly resumeFn: () => AsyncReply,\r\n  ) {\r\n    super();\r\n    this.chunk((value) => this.receiveItem(value as T));\r\n  }\r\n\r\n  /** Whether the peer acknowledged that the stream has started. */\r\n  get started(): boolean {\r\n    return this.streamStarted;\r\n  }\r\n\r\n  /** Whether the stream completed or was terminated. */\r\n  get completed(): boolean {\r\n    return this.streamCompleted;\r\n  }\r\n\r\n  /** Request the next item of a pull stream. */\r\n  pull(): AsyncReply {\r\n    if (this.streamMode !== StreamMode.Pull)\r\n      throw new Error(\"Pull is only valid for a pull stream.\");\r\n    if (this.streamCompleted) return AsyncReply.fromResult(null);\r\n    return this.pullFn();\r\n  }\r\n\r\n  /** Terminate the remote stream execution and release its enumerator. */\r\n  terminate(): AsyncReply {\r\n    if (this.terminationSent || this.streamCompleted) return AsyncReply.fromResult(null);\r\n\r\n    this.terminationSent = true;\r\n    this.streamCompleted = true;\r\n    this.startedDeferred.resolve();\r\n    this.onStreamCompleted();\r\n\r\n    const reply = this.terminateFn();\r\n    reply.error((e) => this.triggerStreamError(e));\r\n    return reply;\r\n  }\r\n\r\n  /** Halt a pausable remote stream execution. */\r\n  halt(): AsyncReply {\r\n    if (this.streamCompleted) return AsyncReply.fromResult(null);\r\n    const reply = this.haltFn();\r\n    reply.error((e) => this.triggerStreamError(e));\r\n    return reply;\r\n  }\r\n\r\n  /** Resume a halted remote stream execution. */\r\n  resume(): AsyncReply {\r\n    if (this.streamCompleted) return AsyncReply.fromResult(null);\r\n    const reply = this.resumeFn();\r\n    reply.error((e) => this.triggerStreamError(e));\r\n    return reply;\r\n  }\r\n\r\n  /** @internal Called by `EpConnection` when the peer's `Stream` reply arrives. */\r\n  triggerStreamStarted(): void {\r\n    if (this.streamCompleted || this.streamException != null) return;\r\n    this.streamStarted = true;\r\n    this.startedDeferred.resolve();\r\n    this.onStreamStarted();\r\n  }\r\n\r\n  /** @internal Called by `EpConnection` when the stream's `Completed` reply arrives. */\r\n  triggerStreamCompleted(): void {\r\n    if (this.streamCompleted) return;\r\n    this.streamCompleted = true;\r\n    this.startedDeferred.resolve();\r\n    this.onStreamCompleted();\r\n  }\r\n\r\n  /** @internal Called by `EpConnection` on an `ExecutionError`/`PermissionError` reply. */\r\n  triggerStreamError(exception: AsyncException): void {\r\n    if (this.streamCompleted || this.streamException != null) return;\r\n    this.streamException = exception;\r\n    this.streamCompleted = true;\r\n    this.startedDeferred.reject(exception);\r\n    this.onStreamError(exception);\r\n    super.triggerError(exception);\r\n  }\r\n\r\n  override triggerError(exception: Error | AsyncException): void {\r\n    this.triggerStreamError(AsyncException.from(exception));\r\n  }\r\n\r\n  protected onStreamStarted(): void {}\r\n\r\n  protected onStreamCompleted(): void {\r\n    this.itemAvailable?.resolve();\r\n    this.itemAvailable = undefined;\r\n  }\r\n\r\n  protected onStreamError(exception: AsyncException): void {\r\n    this.itemAvailable?.reject(exception);\r\n    this.itemAvailable = undefined;\r\n  }\r\n\r\n  private receiveItem(item: T): void {\r\n    if (this.streamCompleted || this.streamException != null) return;\r\n    this.items.push(item);\r\n    this.itemAvailable?.resolve();\r\n    this.itemAvailable = undefined;\r\n  }\r\n\r\n  private async moveNextAsync(): Promise<{ hasValue: boolean; value?: T }> {\r\n    if (this.movePending) throw new Error(\"Concurrent iteration calls are not supported.\");\r\n    this.movePending = true;\r\n    try {\r\n      await this.startedDeferred.promise;\r\n\r\n      for (;;) {\r\n        if (this.streamException != null) throw this.streamException;\r\n        if (this.items.length > 0) return { hasValue: true, value: this.items.shift() };\r\n        if (this.streamCompleted) return { hasValue: false };\r\n\r\n        const deferred = createDeferred<void>();\r\n        this.itemAvailable = deferred;\r\n\r\n        if (this.streamMode === StreamMode.Pull) this.pull().error((e) => this.triggerStreamError(e));\r\n\r\n        await deferred.promise;\r\n      }\r\n    } finally {\r\n      this.movePending = false;\r\n    }\r\n  }\r\n\r\n  /** Consume with `for await (const item of stream)`. A stream can only be enumerated once. */\r\n  [Symbol.asyncIterator](): AsyncIterator<T> {\r\n    if (this.enumeratorCreated) throw new Error(\"A remote stream can only be enumerated once.\");\r\n    this.enumeratorCreated = true;\r\n\r\n    return {\r\n      next: async (): Promise<IteratorResult<T>> => {\r\n        const r = await this.moveNextAsync();\r\n        return r.hasValue ? { done: false, value: r.value as T } : { done: true, value: undefined };\r\n      },\r\n      return: async (): Promise<IteratorResult<T>> => {\r\n        if (!this.streamCompleted) await this.terminate();\r\n        return { done: true, value: undefined };\r\n      },\r\n    };\r\n  }\r\n}\r\n","/** Streaming direction(s) a function supports (port of C# `StreamMode`). Flags. */\r\nexport enum StreamMode {\r\n  None = 0x0,\r\n  Push = 0x1,\r\n  Pull = 0x2,\r\n}\r\n","import { AsyncReply } from \"./AsyncReply.js\";\r\n\r\n/**\r\n * Collects a set of values and/or {@link AsyncReply}s and resolves to an array\r\n * once every member is ready (port of C# `AsyncBag<T>`).\r\n *\r\n * Add members with {@link add}, then {@link seal}; the bag triggers with the\r\n * results in insertion order. Any member error fails the whole bag.\r\n */\r\nexport class AsyncBag<T = any> extends AsyncReply<T[]> {\r\n  protected replies: Array<AsyncReply<T> | T> = [];\r\n  private count = 0;\r\n  private sealedBag = false;\r\n\r\n  /** Optional cast applied to plain (non-reply) members before storing. */\r\n  arrayCast?: (value: unknown) => T;\r\n\r\n  constructor(results?: T[]) {\r\n    if (results !== undefined) super(results);\r\n    else super();\r\n  }\r\n\r\n  /** Add a value or a pending reply to the bag (ignored once sealed). */\r\n  add(valueOrReply: AsyncReply<T> | T): void {\r\n    if (!this.sealedBag) this.replies.push(valueOrReply);\r\n  }\r\n\r\n  /** Merge all members of another bag into this one. */\r\n  addBag(bag: AsyncBag<T>): void {\r\n    for (const r of bag.replies) this.add(r);\r\n  }\r\n\r\n  /** Freeze the bag and arrange to trigger once all members are ready. */\r\n  seal(): void {\r\n    if (this.sealedBag) return;\r\n    this.sealedBag = true;\r\n\r\n    const results: T[] = new Array<T>(this.replies.length);\r\n\r\n    if (this.replies.length === 0) {\r\n      this.trigger(results);\r\n      return;\r\n    }\r\n\r\n    for (let i = 0; i < this.replies.length; i++) {\r\n      const k = this.replies[i];\r\n      const index = i;\r\n\r\n      if (k instanceof AsyncReply) {\r\n        k.onReady((r) => {\r\n          results[index] = r;\r\n          if (++this.count === this.replies.length) this.trigger(results);\r\n        }).error((e) => this.triggerError(e));\r\n      } else {\r\n        results[index] = this.arrayCast ? this.arrayCast(k) : (k as T);\r\n        if (++this.count === this.replies.length) this.trigger(results);\r\n      }\r\n    }\r\n  }\r\n}\r\n","import { AsyncReply } from \"./AsyncReply.js\";\r\n\r\n/**\r\n * Ordered, streaming delivery of {@link AsyncReply}s (port of C# `AsyncQueue<T>`).\r\n *\r\n * Replies are delivered to handlers registered via {@link AsyncReply.onReady} in\r\n * the exact order they were added, even if they become ready out of order — a\r\n * later reply waits for all earlier ones. Used for in-order event/notification\r\n * dispatch in the protocol layer.\r\n */\r\nexport class AsyncQueue<T = any> extends AsyncReply<T> {\r\n  private currentId = 0;\r\n  private items: Array<{ reply: AsyncReply<T>; sequence: number }> = [];\r\n\r\n  /** Enqueue a reply; it is delivered once it and all earlier ones are ready. */\r\n  add(reply: AsyncReply<T>): void {\r\n    this.currentId++;\r\n    this.items.push({ reply, sequence: this.currentId });\r\n    this._ready = false;\r\n\r\n    if (reply.ready) this.processQueue();\r\n    else reply.onReady(() => this.processQueue());\r\n  }\r\n\r\n  /** Drop a reply from the queue. */\r\n  remove(reply: AsyncReply<T>): void {\r\n    const idx = this.items.findIndex((i) => i.reply === reply);\r\n    if (idx >= 0) this.items.splice(idx, 1);\r\n    this.processQueue();\r\n  }\r\n\r\n  private processQueue(): void {\r\n    while (this.items.length > 0 && this.items[0].reply.ready) {\r\n      const item = this.items.shift()!;\r\n      this.deliver(item.reply.result as T);\r\n    }\r\n    this._ready = this.items.length === 0;\r\n  }\r\n\r\n  /** Fire result handlers for a single item without latching the ready state. */\r\n  private deliver(value: T): void {\r\n    this._result = value;\r\n    for (const cb of this._callbacks.slice()) cb(value);\r\n  }\r\n}\r\n","/**\r\n * A minimal multicast event (the TypeScript stand-in for a C# `event`).\r\n * Handlers are invoked synchronously in registration order.\r\n */\r\nexport class EventHandler<T = void> {\r\n  private readonly handlers: Array<(arg: T) => void> = [];\r\n\r\n  /** Subscribe; returns this for chaining. */\r\n  add(handler: (arg: T) => void): this {\r\n    this.handlers.push(handler);\r\n    return this;\r\n  }\r\n\r\n  /** Unsubscribe a previously-added handler. */\r\n  remove(handler: (arg: T) => void): void {\r\n    const i = this.handlers.indexOf(handler);\r\n    if (i >= 0) this.handlers.splice(i, 1);\r\n  }\r\n\r\n  /** Invoke all handlers with `arg`. */\r\n  emit(arg: T): void {\r\n    for (const h of this.handlers.slice()) h(arg);\r\n  }\r\n\r\n  /** Number of subscribed handlers. */\r\n  get count(): number {\r\n    return this.handlers.length;\r\n  }\r\n}\r\n","export * from \"./Endian.js\";\r\nexport * as DC from \"./DC.js\";\r\nexport * from \"./Uuid.js\";\r\nexport * from \"./Int128.js\";\r\nexport * from \"./UInt128.js\";\r\nexport * from \"./Decimal128.js\";\r\nexport * from \"./TduClass.js\";\r\nexport * from \"./TduIdentifier.js\";\r\nexport * from \"./Tdu.js\";\r\nexport * from \"./ParsedTdu.js\";\r\nexport * from \"./PlainTdu.js\";\r\nexport * from \"./NotModified.js\";\r\nexport * from \"./ResourceId.js\";\r\nexport * from \"./ResourceLink.js\";\r\nexport * from \"./widths.js\";\r\nexport * from \"./TruIdentifier.js\";\r\nexport * from \"./Tru.js\";\r\nexport * from \"./types/ITypeDef.js\";\r\nexport * from \"./types/StreamMode.js\";\r\nexport * from \"./descriptors.js\";\r\nexport * as Codec from \"./Codec.js\";\r\nexport * as DataSerializer from \"./DataSerializer.js\";\r\nexport * as DataDeserializer from \"./DataDeserializer.js\";\r\nexport * from \"./gvwie/index.js\";\r\n","import * as DC from \"./DC.js\";\r\n\r\n/**\r\n * A 16-byte universally-unique identifier (port of C# `Uuid`).\r\n *\r\n * Stores the raw bytes as-is (no group reordering); {@link toString} formats\r\n * them in the canonical 8-4-4-4-12 grouping directly from byte order.\r\n */\r\nexport class Uuid {\r\n  /** The raw 16 bytes. */\r\n  readonly data: Uint8Array;\r\n\r\n  constructor(data: Uint8Array, offset = 0) {\r\n    if (offset + 16 > data.length)\r\n      throw new Error(\"UUID data size must be at least 16 bytes\");\r\n    this.data = data.slice(offset, offset + 16);\r\n  }\r\n\r\n  toString(): string {\r\n    return (\r\n      `${DC.toHex(this.data, 0, 4)}-${DC.toHex(this.data, 4, 2)}-` +\r\n      `${DC.toHex(this.data, 6, 2)}-${DC.toHex(this.data, 8, 2)}-` +\r\n      `${DC.toHex(this.data, 10, 6)}`\r\n    );\r\n  }\r\n\r\n  equals(other: unknown): boolean {\r\n    if (!(other instanceof Uuid) || other.data.length !== this.data.length)\r\n      return false;\r\n    for (let i = 0; i < this.data.length; i++)\r\n      if (this.data[i] !== other.data[i]) return false;\r\n    return true;\r\n  }\r\n\r\n  /** Parse a canonical UUID string (\"xxxxxxxx-xxxx-...\") into raw bytes. */\r\n  static parse(value: string): Uuid {\r\n    return new Uuid(DC.fromHex(value.replace(/-/g, \"\"), null));\r\n  }\r\n\r\n  /** A random v4-style UUID (uses crypto when available). */\r\n  static newUuid(): Uuid {\r\n    const bytes = new Uint8Array(16);\r\n    const g = globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => void } };\r\n    if (g.crypto?.getRandomValues) g.crypto.getRandomValues(bytes);\r\n    else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\r\n    return new Uuid(bytes);\r\n  }\r\n}\r\n","const MASK64 = (1n << 64n) - 1n;\r\nconst TWO_128 = 1n << 128n;\r\nconst SIGN_BIT = 1n << 127n;\r\n\r\n/**\r\n * Signed 128-bit integer (port of C# `Int128`, a `{MSB, LSB}` value struct).\r\n *\r\n * Backed by a JS `bigint`. Also serves as an explicit wire-width marker so the\r\n * serializer encodes the value as a 128-bit integer rather than inferring a\r\n * narrower width from a bare `bigint`.\r\n */\r\nexport class Int128 {\r\n  /** Two's-complement value in the signed 128-bit range. */\r\n  readonly value: bigint;\r\n\r\n  constructor(value: bigint);\r\n  constructor(lsb: bigint, msb: bigint);\r\n  constructor(a: bigint, b?: bigint) {\r\n    let v = b === undefined ? a : ((b & MASK64) << 64n) | (a & MASK64);\r\n    v &= TWO_128 - 1n;\r\n    if (v & SIGN_BIT) v -= TWO_128; // interpret as signed\r\n    this.value = v;\r\n  }\r\n\r\n  /** Low 64 bits. */\r\n  get lsb(): bigint {\r\n    return this.value & MASK64;\r\n  }\r\n\r\n  /** High 64 bits. */\r\n  get msb(): bigint {\r\n    return (this.value >> 64n) & MASK64;\r\n  }\r\n\r\n  toString(): string {\r\n    return this.value.toString();\r\n  }\r\n\r\n  equals(other: unknown): boolean {\r\n    return other instanceof Int128 && other.value === this.value;\r\n  }\r\n}\r\n","const MASK64 = (1n << 64n) - 1n;\r\nconst MASK128 = (1n << 128n) - 1n;\r\n\r\n/**\r\n * Unsigned 128-bit integer (port of C# `UInt128`, a `{MSB, LSB}` value struct).\r\n *\r\n * Backed by a JS `bigint`. Also serves as an explicit wire-width marker so the\r\n * serializer encodes the value as a 128-bit integer.\r\n */\r\nexport class UInt128 {\r\n  /** Value in the unsigned 128-bit range. */\r\n  readonly value: bigint;\r\n\r\n  constructor(value: bigint);\r\n  constructor(lsb: bigint, msb: bigint);\r\n  constructor(a: bigint, b?: bigint) {\r\n    const v = b === undefined ? a : ((b & MASK64) << 64n) | (a & MASK64);\r\n    this.value = v & MASK128;\r\n  }\r\n\r\n  /** Low 64 bits. */\r\n  get lsb(): bigint {\r\n    return this.value & MASK64;\r\n  }\r\n\r\n  /** High 64 bits. */\r\n  get msb(): bigint {\r\n    return (this.value >> 64n) & MASK64;\r\n  }\r\n\r\n  toString(): string {\r\n    return this.value.toString();\r\n  }\r\n\r\n  equals(other: unknown): boolean {\r\n    return other instanceof UInt128 && other.value === this.value;\r\n  }\r\n}\r\n","import { Endian } from \"./Endian.js\";\r\nimport * as DC from \"./DC.js\";\r\n\r\nconst MASK32 = 0xffffffffn;\r\nconst TWO_96 = 1n << 96n;\r\n\r\n/**\r\n * 128-bit base-10 floating point, wire-compatible with .NET `decimal`\r\n * (port of the value carried by C# `Decimal128`).\r\n *\r\n * Value = (-1)^negative × mantissa × 10^(−scale), where `mantissa` is a 96-bit\r\n * unsigned integer and `scale` ∈ [0, 28]. Serialized as the raw .NET in-memory\r\n * layout: four little-endian 32-bit words in the order `[flags, hi, lo, mid]`.\r\n */\r\nexport class Decimal128 {\r\n  readonly negative: boolean;\r\n  readonly scale: number;\r\n  readonly mantissa: bigint;\r\n\r\n  constructor(negative: boolean, scale: number, mantissa: bigint) {\r\n    if (scale < 0 || scale > 28) throw new RangeError(`decimal scale out of range: ${scale}`);\r\n    if (mantissa < 0n || mantissa >= TWO_96)\r\n      throw new RangeError(\"decimal mantissa exceeds 96 bits\");\r\n    this.mantissa = mantissa;\r\n    this.scale = scale;\r\n    this.negative = mantissa === 0n ? false : negative;\r\n  }\r\n\r\n  // ---- wire ----------------------------------------------------------------\r\n\r\n  /** 16-byte .NET layout: LE words `[flags, hi, lo, mid]`. */\r\n  toBytes(endian: Endian = Endian.Little): Uint8Array {\r\n    const lo = Number(this.mantissa & MASK32) >>> 0;\r\n    const mid = Number((this.mantissa >> 32n) & MASK32) >>> 0;\r\n    const hi = Number((this.mantissa >> 64n) & MASK32) >>> 0;\r\n    const flags = ((this.scale << 16) | (this.negative ? 0x80000000 : 0)) >>> 0;\r\n\r\n    const out = new Uint8Array(16);\r\n    const v = new DataView(out.buffer);\r\n    const le = endian === Endian.Little;\r\n    v.setUint32(0, flags, le);\r\n    v.setUint32(4, hi, le);\r\n    v.setUint32(8, lo, le);\r\n    v.setUint32(12, mid, le);\r\n    if (endian === Endian.Big) out.reverse();\r\n    return out;\r\n  }\r\n\r\n  static fromBytes(data: Uint8Array, offset = 0, endian: Endian = Endian.Little): Decimal128 {\r\n    let buf = data.subarray(offset, offset + 16);\r\n    if (endian === Endian.Big) buf = buf.slice().reverse();\r\n    const flags = DC.getUint32(buf, 0, Endian.Little);\r\n    const hi = BigInt(DC.getUint32(buf, 4, Endian.Little));\r\n    const lo = BigInt(DC.getUint32(buf, 8, Endian.Little));\r\n    const mid = BigInt(DC.getUint32(buf, 12, Endian.Little));\r\n    const mantissa = (hi << 64n) | (mid << 32n) | lo;\r\n    const scale = (flags >>> 16) & 0xff;\r\n    const negative = (flags & 0x80000000) !== 0;\r\n    return new Decimal128(negative, scale, mantissa);\r\n  }\r\n\r\n  // ---- conversions ---------------------------------------------------------\r\n\r\n  /** Parse a decimal string (e.g. \"-12.3450\"); preserves trailing-zero scale. */\r\n  static parse(text: string): Decimal128 {\r\n    let s = text.trim();\r\n    let negative = false;\r\n    if (s[0] === \"+\" || s[0] === \"-\") {\r\n      negative = s[0] === \"-\";\r\n      s = s.slice(1);\r\n    }\r\n    let scale = 0;\r\n    const dot = s.indexOf(\".\");\r\n    let digits = s;\r\n    if (dot >= 0) {\r\n      scale = s.length - dot - 1;\r\n      digits = s.slice(0, dot) + s.slice(dot + 1);\r\n    }\r\n    if (digits === \"\" || !/^\\d+$/.test(digits))\r\n      throw new SyntaxError(`invalid decimal: ${text}`);\r\n    return new Decimal128(negative, scale, BigInt(digits));\r\n  }\r\n\r\n  static fromNumber(value: number): Decimal128 {\r\n    if (!Number.isFinite(value)) throw new RangeError(\"decimal must be finite\");\r\n    return Decimal128.parse(value.toString());\r\n  }\r\n\r\n  toString(): string {\r\n    let digits = this.mantissa.toString();\r\n    let result: string;\r\n    if (this.scale === 0) {\r\n      result = digits;\r\n    } else {\r\n      if (digits.length <= this.scale) digits = digits.padStart(this.scale + 1, \"0\");\r\n      const point = digits.length - this.scale;\r\n      result = `${digits.slice(0, point)}.${digits.slice(point)}`;\r\n    }\r\n    return this.negative ? `-${result}` : result;\r\n  }\r\n\r\n  toNumber(): number {\r\n    return Number(this.toString());\r\n  }\r\n\r\n  equals(other: unknown): boolean {\r\n    return (\r\n      other instanceof Decimal128 &&\r\n      other.negative === this.negative &&\r\n      other.scale === this.scale &&\r\n      other.mantissa === this.mantissa\r\n    );\r\n  }\r\n}\r\n","/**\r\n * The top 2 bits of a TDU identifier select its class, which determines how the\r\n * payload length is framed (port of C# `TduClass`).\r\n */\r\nexport enum TduClass {\r\n  /** Self-sized primitive (length implied by the identifier's exponent). */\r\n  Fixed = 0x0,\r\n  /** Length-prefixed payload (string, list, raw bytes, …). */\r\n  Dynamic = 0x1,\r\n  /** Length-prefixed payload preceded by a type-representation (Tru). */\r\n  Typed = 0x2,\r\n  /** Reserved extension space. */\r\n  Extension = 0x3,\r\n  /** Not a valid TDU. */\r\n  Invalid = 0x4,\r\n}\r\n","/**\r\n * Leading type byte of a Transmission Data Unit (port of C# `TduIdentifier`).\r\n *\r\n * Bit layout: `[class:2][size-or-exponent:3][index:3]`. For {@link TduClass.Fixed}\r\n * the middle 3 bits are the size exponent; for {@link TduClass.Dynamic} they hold\r\n * the byte-count of the length prefix when a payload is present.\r\n */\r\nexport enum TduIdentifier {\r\n  // Fixed, zero-payload\r\n  Null = 0x0,\r\n  False = 0x1,\r\n  True = 0x2,\r\n  NotModified = 0x3,\r\n  Infinity = 0x4,\r\n  // Fixed, 1 byte\r\n  UInt8 = 0x8,\r\n  Int8 = 0x9,\r\n  Char8 = 0xa,\r\n  LocalResource8 = 0xb,\r\n  RemoteResource8 = 0xc,\r\n  LocalProcedure8 = 0xd,\r\n  RemoteProcedure8 = 0xe,\r\n  // Fixed, 2 bytes\r\n  UInt16 = 0x10,\r\n  Int16 = 0x11,\r\n  Char16 = 0x12,\r\n  LocalResource16 = 0x13,\r\n  RemoteResource16 = 0x14,\r\n  LocalProcedure16 = 0x15,\r\n  RemoteProcedure16 = 0x16,\r\n  // Fixed, 4 bytes\r\n  UInt32 = 0x18,\r\n  Int32 = 0x19,\r\n  Float32 = 0x1a,\r\n  LocalResource32 = 0x1b,\r\n  RemoteResource32 = 0x1c,\r\n  LocalProcedure32 = 0x1d,\r\n  RemoteProcedure32 = 0x1e,\r\n  // Fixed, 8 bytes\r\n  UInt64 = 0x20,\r\n  Int64 = 0x21,\r\n  Float64 = 0x22,\r\n  DateTime = 0x23,\r\n  // Fixed, 16 bytes\r\n  UInt128 = 0x28,\r\n  Int128 = 0x29,\r\n  Decimal128 = 0x2a,\r\n  UUID = 0x2b,\r\n\r\n  // Dynamic (length-prefixed)\r\n  RawData = 0x40,\r\n  String = 0x41,\r\n  List = 0x42,\r\n  ResourceList = 0x43,\r\n  RecordList = 0x44,\r\n  ResourceLink = 0x45,\r\n  Map = 0x46,\r\n  MapList = 0x47,\r\n\r\n  // Typed\r\n  Typed = 0x80,\r\n  TypeDef = 0x81,\r\n  TRU = 0x82,\r\n\r\n  // Extension\r\n  TypeContinuation = 0xc0,\r\n  TypeOfTarget = 0xc1,\r\n}\r\n","import { TduClass } from \"./TduClass.js\";\r\nimport { TduIdentifier } from \"./TduIdentifier.js\";\r\nimport { merge } from \"./DC.js\";\r\n\r\n/** Type-representation metadata that can serialize itself (implemented by Tru). */\r\nexport interface ComposableTru {\r\n  compose(connection: unknown): Uint8Array;\r\n  match(other: ComposableTru): boolean;\r\n}\r\n\r\n/**\r\n * Build the framing header for a length-prefixed (Dynamic/Typed/Extension) TDU:\r\n * `[identifier | (n << 3)]` followed by the content length as `n` big-endian\r\n * bytes. A zero-length payload omits the size flag and length bytes entirely.\r\n */\r\nfunction framedHeader(idByte: number, contentLength: number): Uint8Array {\r\n  if (contentLength === 0) return Uint8Array.of(idByte);\r\n\r\n  let n: number;\r\n  if (contentLength <= 0xff) n = 1;\r\n  else if (contentLength <= 0xffff) n = 2;\r\n  else if (contentLength <= 0xffffff) n = 3;\r\n  else if (contentLength <= 0xffffffff) n = 4;\r\n  else if (contentLength <= 0xffffffffff) n = 5;\r\n  else if (contentLength <= 0xffffffffffff) n = 6;\r\n  else n = 7;\r\n\r\n  const header = new Uint8Array(1 + n);\r\n  header[0] = (idByte | (n << 3)) & 0xff;\r\n  for (let i = 0; i < n; i++)\r\n    header[1 + i] = Math.floor(contentLength / 2 ** (8 * (n - 1 - i))) % 256;\r\n  return header;\r\n}\r\n\r\n/**\r\n * A Transmission Data Unit — one self-describing value on the wire\r\n * (port of C# `Tdu`). The constructor produces {@link composed}, the full\r\n * encoded bytes including the leading identifier.\r\n */\r\nexport class Tdu {\r\n  readonly identifier: TduIdentifier;\r\n  readonly tduClass: TduClass;\r\n  /** Fully encoded bytes (identifier + framing + payload). */\r\n  readonly composed: Uint8Array;\r\n  /** Offset within {@link composed} at which the value payload begins. */\r\n  readonly contentOffset: number = 0;\r\n  /** Type metadata for {@link TduClass.Typed} units. */\r\n  readonly metadata: ComposableTru | null;\r\n\r\n  constructor(\r\n    identifier: TduIdentifier,\r\n    data: Uint8Array | null,\r\n    length: number,\r\n    metadata: ComposableTru | null = null,\r\n    connection: unknown = null,\r\n  ) {\r\n    this.identifier = identifier;\r\n    this.tduClass = (identifier >> 6) as TduClass;\r\n    this.metadata = metadata;\r\n\r\n    const idByte = identifier & 0xff;\r\n\r\n    if (this.tduClass === TduClass.Fixed) {\r\n      if (length === 0) {\r\n        this.composed = Uint8Array.of(idByte);\r\n      } else {\r\n        const out = new Uint8Array(1 + length);\r\n        out[0] = idByte;\r\n        out.set(data!.subarray(0, length), 1);\r\n        this.composed = out;\r\n      }\r\n    } else if (\r\n      this.tduClass === TduClass.Dynamic ||\r\n      this.tduClass === TduClass.Extension ||\r\n      (this.tduClass === TduClass.Typed && this.identifier !== TduIdentifier.Typed)\r\n    ) {\r\n      // Dynamic/Extension, and Typed-but-not-plain-Typed (TypeDef/TRU): a\r\n      // plain framed payload with no metadata prefix.\r\n      const header = framedHeader(idByte, length);\r\n      if (length === 0) {\r\n        this.composed = header;\r\n      } else {\r\n        this.composed = merge(header, data!.subarray(0, length));\r\n        this.contentOffset = header.length;\r\n      }\r\n    } else {\r\n      // Typed identifier itself (0x80): metadata bytes precede the payload.\r\n      if (metadata == null)\r\n        throw new Error(\"Metadata must be provided for typed TDUs.\");\r\n      const metadataData = metadata.compose(connection);\r\n      const content = merge(metadataData, (data ?? new Uint8Array(0)).subarray(0, length));\r\n      const header = framedHeader(idByte, content.length);\r\n      this.composed = merge(header, content);\r\n      this.contentOffset = header.length + metadataData.length;\r\n    }\r\n  }\r\n\r\n  /** True if both are typed TDUs of the same identifier and matching metadata. */\r\n  matchType(other: Tdu): boolean {\r\n    if (this.identifier !== other.identifier) return false;\r\n    if (this.tduClass !== TduClass.Typed || other.tduClass !== TduClass.Typed)\r\n      return false;\r\n    // TypeDef/TRU carry no metadata — the identifier alone fully describes\r\n    // the outer type, so two TDUs with the same identifier already match.\r\n    if (this.identifier !== TduIdentifier.Typed) return true;\r\n    if (this.metadata == null || other.metadata == null) return false;\r\n    return this.metadata.match(other.metadata);\r\n  }\r\n}\r\n","/**\r\n * Raised when untrusted input declares a length that exceeds a configured\r\n * parser budget (port of C# `ParserLimitException`).\r\n */\r\nexport class ParserLimitException extends Error {\r\n  constructor(message: string) {\r\n    super(message);\r\n    this.name = \"ParserLimitException\";\r\n    Object.setPrototypeOf(this, ParserLimitException.prototype);\r\n  }\r\n}\r\n\r\n/**\r\n * Default cap on a TDU's declared payload length, matching esiur-dotnet's\r\n * `ParserConfiguration.MaximumPacketSize` default (8 MiB). The Dynamic/Typed/\r\n * Extension length prefix can be up to 7 bytes (declaring up to 2^56), so\r\n * leaving it unchecked lets a peer force a huge allocation — or a long wait\r\n * for bytes that may never arrive — from a single header.\r\n */\r\nexport const DEFAULT_MAXIMUM_PAYLOAD_LENGTH = 8 * 1024 * 1024;\r\n\r\n/**\r\n * Throws {@link ParserLimitException} when `declaredLength` exceeds\r\n * `maximumPayloadLength` (port of C# `ParserGuard.EnsurePacketSize`). Callers\r\n * must invoke this immediately after decoding the length prefix, before it is\r\n * used to size an allocation or decide how many more bytes to wait for. A\r\n * `maximumPayloadLength` of `0` disables the check.\r\n */\r\nexport function ensurePacketSize(declaredLength: number, maximumPayloadLength: number): void {\r\n  if (maximumPayloadLength > 0 && declaredLength > maximumPayloadLength)\r\n    throw new ParserLimitException(\r\n      `Declared packet payload of ${declaredLength} bytes exceeds the ${maximumPayloadLength}-byte limit.`,\r\n    );\r\n}\r\n","import { TduClass } from \"./TduClass.js\";\r\nimport { TduIdentifier } from \"./TduIdentifier.js\";\r\nimport { DEFAULT_MAXIMUM_PAYLOAD_LENGTH, ensurePacketSize } from \"./ParserGuard.js\";\r\n\r\n/**\r\n * A decoded TDU header pointing back into the source buffer (port of C#\r\n * `ParsedTdu`). `parseSync` reads the identifier/length framing and locates the\r\n * payload; the actual value is produced by the parsers in `DataDeserializer`.\r\n */\r\nexport class ParsedTdu {\r\n  identifier: TduIdentifier = TduIdentifier.Null;\r\n  index = 0;\r\n  tduClass: TduClass = TduClass.Invalid;\r\n  payloadOffset = 0;\r\n  payloadLength = 0;\r\n  data: Uint8Array = new Uint8Array(0);\r\n  exponent = 0;\r\n  totalLength = 0;\r\n  /** Type metadata (Tru) for {@link TduClass.Typed}; populated in Step B. */\r\n  metadata: unknown = null;\r\n  ends = 0;\r\n\r\n  static invalid(totalLength: number): ParsedTdu {\r\n    const t = new ParsedTdu();\r\n    t.tduClass = TduClass.Invalid;\r\n    t.totalLength = totalLength;\r\n    return t;\r\n  }\r\n\r\n  /** Parse a TDU header at `offset` (sync path; resolves typed metadata via warehouse). */\r\n  static parseSync(\r\n    data: Uint8Array,\r\n    offset: number,\r\n    ends: number,\r\n    warehouse: unknown = null,\r\n    maximumPayloadLength: number = DEFAULT_MAXIMUM_PAYLOAD_LENGTH,\r\n  ): ParsedTdu {\r\n    let pos = offset;\r\n    const h = data[pos++];\r\n    const cls = (h >> 6) as TduClass;\r\n\r\n    if (cls === TduClass.Fixed) {\r\n      const exp = (h & 0x38) >> 3;\r\n      const t = new ParsedTdu();\r\n      t.data = data;\r\n      t.tduClass = cls;\r\n      t.identifier = h as TduIdentifier;\r\n      t.exponent = exp;\r\n      t.index = h & 0x7;\r\n      t.ends = ends;\r\n\r\n      if (exp === 0) {\r\n        t.payloadOffset = pos;\r\n        t.payloadLength = 0;\r\n        t.totalLength = 1;\r\n        return t;\r\n      }\r\n\r\n      const cl = 1 << (exp - 1);\r\n      if (ends - pos < cl) return ParsedTdu.invalid(cl - (ends - pos));\r\n\r\n      t.payloadOffset = pos;\r\n      t.payloadLength = cl;\r\n      t.totalLength = 1 + cl;\r\n      return t;\r\n    }\r\n\r\n    // Dynamic / Typed / Extension: read `cll` big-endian length bytes.\r\n    const cll = (h >> 3) & 0x7;\r\n    if (ends - pos < cll) return ParsedTdu.invalid(cll - (ends - pos));\r\n\r\n    let cl = 0;\r\n    for (let i = 0; i < cll; i++) cl = cl * 256 + data[pos++];\r\n    // Reject an oversized declaration before it can be used to size a buffer\r\n    // or justify waiting for more bytes — checked ahead of the completeness\r\n    // test below, which would otherwise treat it as merely \"incomplete\".\r\n    ensurePacketSize(cl, maximumPayloadLength);\r\n    if (ends - pos < cl) return ParsedTdu.invalid(cl - (ends - pos));\r\n\r\n    // Only the plain `Typed` identifier (0x80, index 0) carries embedded Tru\r\n    // metadata ahead of its payload. `TypeDef` (0x81) and `TRU` (0x82) share\r\n    // the same TduClass.Typed class bits but are self-describing, framed\r\n    // payloads with no metadata prefix — they fall through to the generic\r\n    // branch below, matching esiur-dotnet's exact `(h & 0xC7) == 0x80` check.\r\n    if (cls === TduClass.Typed && (h & 0xc7) === 0x80) {\r\n      const { value: tru, size } = parseTruSync(data, pos, warehouse);\r\n      pos += size;\r\n      const t = new ParsedTdu();\r\n      t.data = data;\r\n      t.tduClass = cls;\r\n      t.identifier = (h & 0xc7) as TduIdentifier;\r\n      t.index = h & 0x7;\r\n      t.payloadOffset = pos;\r\n      t.payloadLength = cl - size;\r\n      t.totalLength = 1 + cl + cll;\r\n      t.metadata = tru;\r\n      t.ends = ends;\r\n      return t;\r\n    }\r\n\r\n    const t = new ParsedTdu();\r\n    t.data = data;\r\n    t.tduClass = cls;\r\n    t.identifier = (h & 0xc7) as TduIdentifier;\r\n    t.index = h & 0x7;\r\n    t.payloadOffset = pos;\r\n    t.payloadLength = cl;\r\n    t.totalLength = 1 + cl + cll;\r\n    t.ends = ends;\r\n    return t;\r\n  }\r\n\r\n  /**\r\n   * Async twin of {@link parseSync}, used when a `Tru` value (embedded\r\n   * metadata, or a nested `TduIdentifier.TRU`/`TypeDef` value further down the\r\n   * tree) may need to resolve a not-yet-fetched remote TypeDef reference.\r\n   * Structurally identical to `parseSync`; the one embedded-Tru-metadata spot\r\n   * awaits the async Tru parser instead of the sync one.\r\n   */\r\n  static async parseAsync(\r\n    data: Uint8Array,\r\n    offset: number,\r\n    ends: number,\r\n    warehouse: unknown,\r\n    remoteResolver: unknown,\r\n    requestSequence: readonly number[] | null,\r\n    maximumPayloadLength: number = DEFAULT_MAXIMUM_PAYLOAD_LENGTH,\r\n  ): Promise<ParsedTdu> {\r\n    let pos = offset;\r\n    const h = data[pos++];\r\n    const cls = (h >> 6) as TduClass;\r\n\r\n    if (cls === TduClass.Fixed) {\r\n      const exp = (h & 0x38) >> 3;\r\n      const t = new ParsedTdu();\r\n      t.data = data;\r\n      t.tduClass = cls;\r\n      t.identifier = h as TduIdentifier;\r\n      t.exponent = exp;\r\n      t.index = h & 0x7;\r\n      t.ends = ends;\r\n\r\n      if (exp === 0) {\r\n        t.payloadOffset = pos;\r\n        t.payloadLength = 0;\r\n        t.totalLength = 1;\r\n        return t;\r\n      }\r\n\r\n      const cl = 1 << (exp - 1);\r\n      if (ends - pos < cl) return ParsedTdu.invalid(cl - (ends - pos));\r\n\r\n      t.payloadOffset = pos;\r\n      t.payloadLength = cl;\r\n      t.totalLength = 1 + cl;\r\n      return t;\r\n    }\r\n\r\n    const cll = (h >> 3) & 0x7;\r\n    if (ends - pos < cll) return ParsedTdu.invalid(cll - (ends - pos));\r\n\r\n    let cl = 0;\r\n    for (let i = 0; i < cll; i++) cl = cl * 256 + data[pos++];\r\n    // Reject an oversized declaration before it can be used to size a buffer\r\n    // or justify waiting for more bytes — checked ahead of the completeness\r\n    // test below, which would otherwise treat it as merely \"incomplete\".\r\n    ensurePacketSize(cl, maximumPayloadLength);\r\n    if (ends - pos < cl) return ParsedTdu.invalid(cl - (ends - pos));\r\n\r\n    if (cls === TduClass.Typed && (h & 0xc7) === 0x80) {\r\n      const { value: tru, size } = await parseTruAsync(\r\n        data,\r\n        pos,\r\n        warehouse,\r\n        remoteResolver,\r\n        requestSequence,\r\n      );\r\n      pos += size;\r\n      const t = new ParsedTdu();\r\n      t.data = data;\r\n      t.tduClass = cls;\r\n      t.identifier = (h & 0xc7) as TduIdentifier;\r\n      t.index = h & 0x7;\r\n      t.payloadOffset = pos;\r\n      t.payloadLength = cl - size;\r\n      t.totalLength = 1 + cl + cll;\r\n      t.metadata = tru;\r\n      t.ends = ends;\r\n      return t;\r\n    }\r\n\r\n    const t = new ParsedTdu();\r\n    t.data = data;\r\n    t.tduClass = cls;\r\n    t.identifier = (h & 0xc7) as TduIdentifier;\r\n    t.index = h & 0x7;\r\n    t.payloadOffset = pos;\r\n    t.payloadLength = cl;\r\n    t.totalLength = 1 + cl + cll;\r\n    t.ends = ends;\r\n    return t;\r\n  }\r\n}\r\n\r\n/**\r\n * Pluggable Tru (type-representation) parser. Replaced by the real implementation\r\n * when the Tru family lands (Phase 2 Step B); until then, typed TDUs are not\r\n * decodable.\r\n */\r\nlet parseTruSync: (\r\n  data: Uint8Array,\r\n  offset: number,\r\n  warehouse: unknown,\r\n) => { value: unknown; size: number } = () => {\r\n  throw new Error(\"Typed TDU parsing requires the Tru family (Phase 2 continuation).\");\r\n};\r\n\r\n/** Wire up the Tru parser (called by the Tru module on import). */\r\nexport function registerTruParser(\r\n  fn: (data: Uint8Array, offset: number, warehouse: unknown) => { value: unknown; size: number },\r\n): void {\r\n  parseTruSync = fn;\r\n}\r\n\r\n/** Async twin of {@link parseTruSync}, threading a remote-typedef resolver. */\r\nlet parseTruAsync: (\r\n  data: Uint8Array,\r\n  offset: number,\r\n  warehouse: unknown,\r\n  remoteResolver: unknown,\r\n  requestSequence: readonly number[] | null,\r\n) => Promise<{ value: unknown; size: number }> = () => {\r\n  throw new Error(\"Typed TDU parsing requires the Tru family (Phase 2 continuation).\");\r\n};\r\n\r\n/** Wire up the async Tru parser (called by the Tru module on import). */\r\nexport function registerTruParserAsync(\r\n  fn: (\r\n    data: Uint8Array,\r\n    offset: number,\r\n    warehouse: unknown,\r\n    remoteResolver: unknown,\r\n    requestSequence: readonly number[] | null,\r\n  ) => Promise<{ value: unknown; size: number }>,\r\n): void {\r\n  parseTruAsync = fn;\r\n}\r\n","import { TduClass } from \"./TduClass.js\";\r\nimport { TduIdentifier } from \"./TduIdentifier.js\";\r\nimport { DEFAULT_MAXIMUM_PAYLOAD_LENGTH, ensurePacketSize } from \"./ParserGuard.js\";\r\n\r\n/**\r\n * A measured-but-undecoded TDU (port of C# `PlainTdu`). Used by the packet layer\r\n * to delimit a value within a packet without decoding it — the decode (which may\r\n * need the connection to resolve remote resources/typedefs) is deferred and run\r\n * later via the async {@link Codec} parse path. Unlike {@link ParsedTdu}, the\r\n * Typed branch does not parse its Tru metadata; `payloadLength` covers the whole\r\n * content (metadata + value).\r\n */\r\nexport class PlainTdu {\r\n  identifier: TduIdentifier = TduIdentifier.Null;\r\n  index = 0;\r\n  tduClass: TduClass = TduClass.Invalid;\r\n  /** Offset of the TDU start (the identifier byte). */\r\n  tduOffset = 0;\r\n  payloadOffset = 0;\r\n  payloadLength = 0;\r\n  exponent = 0;\r\n  totalLength = 0;\r\n  data: Uint8Array = new Uint8Array(0);\r\n  ends = 0;\r\n\r\n  static invalid(totalLength: number): PlainTdu {\r\n    const t = new PlainTdu();\r\n    t.tduClass = TduClass.Invalid;\r\n    t.totalLength = totalLength;\r\n    return t;\r\n  }\r\n\r\n  /** Measure the TDU at `offset` without decoding its value. */\r\n  static parse(\r\n    data: Uint8Array,\r\n    offset: number,\r\n    ends: number,\r\n    maximumPayloadLength: number = DEFAULT_MAXIMUM_PAYLOAD_LENGTH,\r\n  ): PlainTdu {\r\n    const start = offset;\r\n    const h = data[offset++];\r\n    const cls = (h >> 6) as TduClass;\r\n\r\n    if (cls === TduClass.Fixed) {\r\n      const exp = (h & 0x38) >> 3;\r\n      const t = new PlainTdu();\r\n      t.data = data;\r\n      t.tduClass = cls;\r\n      t.identifier = h as TduIdentifier;\r\n      t.exponent = exp;\r\n      t.index = h & 0x7;\r\n      t.tduOffset = start;\r\n      t.ends = ends;\r\n\r\n      if (exp === 0) {\r\n        t.payloadOffset = offset;\r\n        t.payloadLength = 0;\r\n        t.totalLength = 1;\r\n        return t;\r\n      }\r\n\r\n      const cl = 1 << (exp - 1);\r\n      if (ends - offset < cl) return PlainTdu.invalid(cl - (ends - offset));\r\n\r\n      t.payloadOffset = offset;\r\n      t.payloadLength = cl;\r\n      t.totalLength = 1 + cl;\r\n      return t;\r\n    }\r\n\r\n    // Dynamic / Typed / Extension: read `cll` big-endian length bytes.\r\n    const cll = (h >> 3) & 0x7;\r\n    if (ends - offset < cll) return PlainTdu.invalid(cll - (ends - offset));\r\n\r\n    let cl = 0;\r\n    for (let i = 0; i < cll; i++) cl = cl * 256 + data[offset++];\r\n    // Reject an oversized declaration before it can be used to size a buffer\r\n    // or justify waiting for more bytes — checked ahead of the completeness\r\n    // test below, which would otherwise treat it as merely \"incomplete\".\r\n    ensurePacketSize(cl, maximumPayloadLength);\r\n    if (ends - offset < cl) return PlainTdu.invalid(cl - (ends - offset));\r\n\r\n    const t = new PlainTdu();\r\n    t.data = data;\r\n    t.tduClass = cls;\r\n    t.identifier = (h & 0xc7) as TduIdentifier;\r\n    t.index = h & 0x7;\r\n    t.tduOffset = start;\r\n    t.payloadOffset = offset;\r\n    t.payloadLength = cl;\r\n    t.totalLength = 1 + cl + cll;\r\n    t.ends = ends;\r\n    return t;\r\n  }\r\n}\r\n","/**\r\n * Sentinel meaning \"value unchanged\" (port of C# `NotModified`). Used in\r\n * property-update replies to signal that a property keeps its current value.\r\n */\r\nexport class NotModified {\r\n  static readonly Default = new NotModified();\r\n  private constructor() {}\r\n}\r\n","/**\r\n * A placeholder produced when a resource reference is decoded without a\r\n * connection/warehouse to resolve it (port of C# `ResourceId`). Carries whether\r\n * the reference is local and the numeric instance id.\r\n */\r\nexport class ResourceId {\r\n  constructor(\r\n    readonly local: boolean,\r\n    readonly id: number,\r\n  ) {}\r\n}\r\n","/**\r\n * A textual link to a resource, e.g. \"iip://host/path\" (port of C#\r\n * `ResourceLink`, which is implicitly convertible to/from string).\r\n */\r\nexport class ResourceLink {\r\n  constructor(readonly link: string) {}\r\n  toString(): string {\r\n    return this.link;\r\n  }\r\n}\r\n","/**\r\n * Explicit numeric-width wrappers. A bare JS `number` is treated as a C#\r\n * `double` and a bare `bigint` as a C# `long`; wrap a value in one of these to\r\n * pin the wire width the serializer should use (e.g. unsigned types, or a\r\n * 32-bit float). Like the C# composers, these still narrow to the smallest\r\n * representation that fits — `u32(255)` encodes as `UInt8`.\r\n */\r\n\r\nexport class Int8 {\r\n  constructor(readonly value: number) {}\r\n}\r\nexport class UInt8 {\r\n  constructor(readonly value: number) {}\r\n}\r\nexport class Int16 {\r\n  constructor(readonly value: number) {}\r\n}\r\nexport class UInt16 {\r\n  constructor(readonly value: number) {}\r\n}\r\nexport class Int32 {\r\n  constructor(readonly value: number) {}\r\n}\r\nexport class UInt32 {\r\n  constructor(readonly value: number) {}\r\n}\r\nexport class Int64 {\r\n  constructor(readonly value: bigint) {}\r\n}\r\nexport class UInt64 {\r\n  constructor(readonly value: bigint) {}\r\n}\r\nexport class Float32 {\r\n  constructor(readonly value: number) {}\r\n}\r\n/** A UTF-16 code unit, encoded as the `Char16` TDU. */\r\nexport class Char16 {\r\n  constructor(readonly value: number) {}\r\n}\r\n\r\n/** Convenience factories for the width wrappers. */\r\nexport const i8 = (v: number) => new Int8(v);\r\nexport const u8 = (v: number) => new UInt8(v);\r\nexport const i16 = (v: number) => new Int16(v);\r\nexport const u16 = (v: number) => new UInt16(v);\r\nexport const i32 = (v: number) => new Int32(v);\r\nexport const u32 = (v: number) => new UInt32(v);\r\nexport const i64 = (v: bigint) => new Int64(v);\r\nexport const u64 = (v: bigint) => new UInt64(v);\r\nexport const f32 = (v: number) => new Float32(v);\r\nexport const char16 = (v: number | string) =>\r\n  new Char16(typeof v === \"string\" ? v.charCodeAt(0) : v);\r\n","/**\r\n * Type-Representation Unit identifier (port of C# `TruIdentifier`).\r\n *\r\n * Values < 0x40 are primitives. Values ≥ 0x40 set bit 6 (the \"composite/ref\"\r\n * flag); their bits 3-5 encode the sub-type count, so `TypedList` (0x48) implies\r\n * one sub-type and `TypedMap`/`Tuple2` (0x50/0x51) imply two.\r\n */\r\nexport enum TruIdentifier {\r\n  Void = 0x0,\r\n  Dynamic = 0x1,\r\n  Bool = 0x2,\r\n  UInt8 = 0x3,\r\n  Int8 = 0x4,\r\n  Char = 0x5,\r\n  UInt16 = 0x6,\r\n  Int16 = 0x7,\r\n  UInt32 = 0x8,\r\n  Int32 = 0x9,\r\n  Float32 = 0xa,\r\n  UInt64 = 0xb,\r\n  Int64 = 0xc,\r\n  Float64 = 0xd,\r\n  DateTime = 0xe,\r\n  UInt128 = 0xf,\r\n  Int128 = 0x10,\r\n  Decimal = 0x11,\r\n  String = 0x12,\r\n  RawData = 0x13,\r\n  Resource = 0x14,\r\n  Record = 0x15,\r\n  List = 0x16,\r\n  Map = 0x17,\r\n\r\n  LocalType8 = 0x40,\r\n  RemoteType8 = 0x41,\r\n  LocalType16 = 0x42,\r\n  RemoteType16 = 0x43,\r\n  LocalType32 = 0x44,\r\n  RemoteType32 = 0x45,\r\n  LocalType64 = 0x46,\r\n  RemoteType64 = 0x47,\r\n\r\n  TypedList = 0x48,\r\n\r\n  Tuple2 = 0x50,\r\n  TypedMap = 0x51,\r\n  Tuple3 = 0x58,\r\n  Tuple4 = 0x60,\r\n  Tuple5 = 0x68,\r\n  Tuple6 = 0x70,\r\n  Tuple7 = 0x78,\r\n}\r\n","import { TruIdentifier } from \"./TruIdentifier.js\";\r\nimport { merge } from \"./DC.js\";\r\nimport * as DC from \"./DC.js\";\r\nimport { registerTruParser, registerTruParserAsync } from \"./ParsedTdu.js\";\r\nimport type { ComposableTru } from \"./Tdu.js\";\r\nimport type { ITypeDef } from \"./types/ITypeDef.js\";\r\n\r\nexport type RemoteTypeDefResolver = (\r\n  id: number,\r\n  requestSequence: readonly number[] | null,\r\n) => ITypeDef | PromiseLike<ITypeDef>;\r\n\r\n/**\r\n * Type-Representation Unit (port of C# `Tru`). Describes how a value's type maps\r\n * onto the wire. Because TypeScript has no runtime reflection, Trus are built\r\n * explicitly via the `t.*` descriptors (see `descriptors.ts`) rather than from a\r\n * CLR `Type`.\r\n *\r\n * Wire encoding (one header byte): `(nullable ? 0x80 : 0) | identifier`. For\r\n * composites the identifier's bits 3-5 imply the sub-type count, whose Trus\r\n * follow inline.\r\n */\r\nexport abstract class Tru implements ComposableTru {\r\n  identifier: TruIdentifier;\r\n  nullable: boolean;\r\n\r\n  protected constructor(identifier: TruIdentifier, nullable: boolean) {\r\n    this.identifier = identifier;\r\n    this.nullable = nullable;\r\n  }\r\n\r\n  abstract compose(connection?: unknown): Uint8Array;\r\n  abstract match(other: Tru): boolean;\r\n  abstract toNullable(): Tru;\r\n\r\n  protected get headerByte(): number {\r\n    return ((this.nullable ? 0x80 : 0) | this.identifier) & 0xff;\r\n  }\r\n\r\n  /** Parse a Tru at `offset`; returns the Tru and the number of bytes consumed. */\r\n  static parseSync(\r\n    data: Uint8Array,\r\n    offset: number,\r\n    warehouse: unknown = null,\r\n  ): { value: Tru; size: number } {\r\n    const start = offset;\r\n    const header = data[offset++];\r\n    const nullable = (header & 0x80) > 0;\r\n    const identifier = (header & 0x7f) as TruIdentifier;\r\n\r\n    if ((header & 0x40) > 0) {\r\n      const subsCount = (header >> 3) & 0x7;\r\n      if (subsCount === 0) {\r\n        // TypeDef reference (record/enum/resource): id follows, width by identifier.\r\n        const ref = readTypeDefId(data, offset, identifier);\r\n        if (ref.remote)\r\n          throw new Error(\"Remote type definitions require a connection (Phase 5).\");\r\n        const typeDef = typeDefResolver(warehouse, ref.id);\r\n        return { value: new TruTypeDef(nullable, typeDef), size: 1 + ref.size };\r\n      }\r\n\r\n      const subTypes: Tru[] = [];\r\n      for (let i = 0; i < subsCount; i++) {\r\n        const pr = Tru.parseSync(data, offset, warehouse);\r\n        subTypes.push(pr.value);\r\n        offset += pr.size;\r\n      }\r\n      return { value: new TruComposite(identifier, nullable, subTypes), size: offset - start };\r\n    }\r\n\r\n    return { value: new TruPrimitive(identifier, nullable), size: 1 };\r\n  }\r\n\r\n  /** Async parser variant used when remote TypeDef references may need fetching. */\r\n  static async parseAsync(\r\n    data: Uint8Array,\r\n    offset: number,\r\n    warehouse: unknown = null,\r\n    remoteResolver?: RemoteTypeDefResolver,\r\n    requestSequence: readonly number[] | null = null,\r\n  ): Promise<{ value: Tru; size: number }> {\r\n    const start = offset;\r\n    const header = data[offset++];\r\n    const nullable = (header & 0x80) > 0;\r\n    const identifier = (header & 0x7f) as TruIdentifier;\r\n\r\n    if ((header & 0x40) > 0) {\r\n      const subsCount = (header >> 3) & 0x7;\r\n      if (subsCount === 0) {\r\n        const ref = readTypeDefId(data, offset, identifier);\r\n        const typeDef = ref.remote\r\n          ? await resolveRemoteTypeDef(remoteResolver, ref.id, requestSequence)\r\n          : typeDefResolver(warehouse, ref.id);\r\n        return { value: new TruTypeDef(nullable, typeDef), size: 1 + ref.size };\r\n      }\r\n\r\n      const subTypes: Tru[] = [];\r\n      for (let i = 0; i < subsCount; i++) {\r\n        const pr = await Tru.parseAsync(\r\n          data,\r\n          offset,\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n        subTypes.push(pr.value);\r\n        offset += pr.size;\r\n      }\r\n      return { value: new TruComposite(identifier, nullable, subTypes), size: offset - start };\r\n    }\r\n\r\n    return { value: new TruPrimitive(identifier, nullable), size: 1 };\r\n  }\r\n}\r\n\r\n/** A primitive Tru (single header byte, no sub-types). */\r\nexport class TruPrimitive extends Tru {\r\n  constructor(identifier: TruIdentifier, nullable = false) {\r\n    super(identifier, nullable);\r\n  }\r\n\r\n  override compose(): Uint8Array {\r\n    return Uint8Array.of(this.headerByte);\r\n  }\r\n\r\n  override match(other: Tru): boolean {\r\n    return other instanceof TruPrimitive && other.identifier === this.identifier;\r\n  }\r\n\r\n  override toNullable(): TruPrimitive {\r\n    return new TruPrimitive(this.identifier, true);\r\n  }\r\n\r\n  override toString(): string {\r\n    return TruIdentifier[this.identifier] + (this.nullable ? \"?\" : \"\");\r\n  }\r\n}\r\n\r\n/** A composite Tru (typed list/map/tuple) carrying inline sub-type Trus. */\r\nexport class TruComposite extends Tru {\r\n  readonly subTypes: Tru[];\r\n\r\n  constructor(identifier: TruIdentifier, nullable: boolean, subTypes: Tru[]) {\r\n    super(identifier, nullable);\r\n    this.subTypes = subTypes;\r\n  }\r\n\r\n  override compose(connection?: unknown): Uint8Array {\r\n    return merge(\r\n      Uint8Array.of(this.headerByte),\r\n      ...this.subTypes.map((s) => s.compose(connection)),\r\n    );\r\n  }\r\n\r\n  override match(other: Tru): boolean {\r\n    if (!(other instanceof TruComposite)) return false;\r\n    if (other.identifier !== this.identifier) return false;\r\n    if (other.subTypes.length !== this.subTypes.length) return false;\r\n    for (let i = 0; i < this.subTypes.length; i++)\r\n      if (!this.subTypes[i].match(other.subTypes[i])) return false;\r\n    return true;\r\n  }\r\n\r\n  override toNullable(): TruComposite {\r\n    return new TruComposite(this.identifier, true, this.subTypes);\r\n  }\r\n\r\n  override toString(): string {\r\n    return `${TruIdentifier[this.identifier]}<${this.subTypes.map((s) => s.toString()).join(\",\")}>${this.nullable ? \"?\" : \"\"}`;\r\n  }\r\n}\r\n\r\n/** Smallest local-typedef identifier that can carry `id`. */\r\nfunction localTypeIdentifier(id: number): TruIdentifier {\r\n  if (id <= 0xff) return TruIdentifier.LocalType8;\r\n  if (id <= 0xffff) return TruIdentifier.LocalType16;\r\n  if (id <= 0xffffffff) return TruIdentifier.LocalType32;\r\n  return TruIdentifier.LocalType64;\r\n}\r\n\r\n/** Read a typedef id (little-endian) whose width is implied by the identifier. */\r\nfunction readTypeDefId(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  identifier: TruIdentifier,\r\n): { id: number; remote: boolean; size: number } {\r\n  switch (identifier) {\r\n    case TruIdentifier.LocalType8:\r\n      return { id: DC.getUint8(data, offset), remote: false, size: 1 };\r\n    case TruIdentifier.RemoteType8:\r\n      return { id: DC.getUint8(data, offset), remote: true, size: 1 };\r\n    case TruIdentifier.LocalType16:\r\n      return { id: DC.getUint16(data, offset), remote: false, size: 2 };\r\n    case TruIdentifier.RemoteType16:\r\n      return { id: DC.getUint16(data, offset), remote: true, size: 2 };\r\n    case TruIdentifier.LocalType32:\r\n      return { id: DC.getUint32(data, offset), remote: false, size: 4 };\r\n    case TruIdentifier.RemoteType32:\r\n      return { id: DC.getUint32(data, offset), remote: true, size: 4 };\r\n    case TruIdentifier.LocalType64:\r\n      return { id: Number(DC.getUint64(data, offset)), remote: false, size: 8 };\r\n    case TruIdentifier.RemoteType64:\r\n      return { id: Number(DC.getUint64(data, offset)), remote: true, size: 8 };\r\n    default:\r\n      throw new Error(\"Invalid Tru typedef identifier.\");\r\n  }\r\n}\r\n\r\nasync function resolveRemoteTypeDef(\r\n  resolver: RemoteTypeDefResolver | undefined,\r\n  id: number,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<ITypeDef> {\r\n  if (!resolver)\r\n    throw new Error(\"Remote type definitions require a connection.\");\r\n  return await resolver(id, requestSequence);\r\n}\r\n\r\n/** A Tru referencing a registered type definition (record/enum/resource). */\r\nexport class TruTypeDef extends Tru {\r\n  readonly typeDef: ITypeDef;\r\n\r\n  constructor(nullable: boolean, typeDef: ITypeDef) {\r\n    super(localTypeIdentifier(typeDef.id), nullable);\r\n    this.typeDef = typeDef;\r\n  }\r\n\r\n  override compose(): Uint8Array {\r\n    const id = this.typeDef.id;\r\n    let idBytes: Uint8Array;\r\n    switch (this.identifier) {\r\n      case TruIdentifier.LocalType8:\r\n        idBytes = Uint8Array.of(id & 0xff);\r\n        break;\r\n      case TruIdentifier.LocalType16:\r\n        idBytes = DC.uint16ToBytes(id);\r\n        break;\r\n      case TruIdentifier.LocalType32:\r\n        idBytes = DC.uint32ToBytes(id);\r\n        break;\r\n      default:\r\n        idBytes = DC.uint64ToBytes(BigInt(id));\r\n        break;\r\n    }\r\n    return merge(Uint8Array.of(this.headerByte), idBytes);\r\n  }\r\n\r\n  override match(other: Tru): boolean {\r\n    return other instanceof TruTypeDef && other.typeDef.id === this.typeDef.id;\r\n  }\r\n\r\n  override toNullable(): TruTypeDef {\r\n    return new TruTypeDef(true, this.typeDef);\r\n  }\r\n\r\n  override toString(): string {\r\n    return this.typeDef.name + (this.nullable ? \"?\" : \"\");\r\n  }\r\n}\r\n\r\n/** Resolves a typedef id to its definition (registered by the resource layer). */\r\nlet typeDefResolver: (warehouse: unknown, id: number) => ITypeDef = () => {\r\n  throw new Error(\"No TypeDef resolver registered (import the resource layer).\");\r\n};\r\n\r\n/** Register the typedef resolver used when decoding TypeDef-referencing Trus. */\r\nexport function registerTypeDefResolver(\r\n  fn: (warehouse: unknown, id: number) => ITypeDef,\r\n): void {\r\n  typeDefResolver = fn;\r\n}\r\n\r\n// Make typed TDUs decodable by wiring Tru parsing into ParsedTdu.\r\nregisterTruParser((data, offset, warehouse) => Tru.parseSync(data, offset, warehouse));\r\nregisterTruParserAsync((data, offset, warehouse, remoteResolver, requestSequence) =>\r\n  Tru.parseAsync(\r\n    data,\r\n    offset,\r\n    warehouse,\r\n    remoteResolver as RemoteTypeDefResolver | undefined,\r\n    requestSequence,\r\n  ),\r\n);\r\n","import type { Tru } from \"../Tru.js\";\r\n\r\n/** Kind of a type definition (port of C# `TypeDefKind`). */\r\nexport enum TypeDefKind {\r\n  Resource = 0,\r\n  Record = 1,\r\n  Enum = 2,\r\n  Function = 3,\r\n}\r\n\r\n/** A property entry within a type definition. */\r\nexport interface TypeDefProperty {\r\n  name: string;\r\n  valueType?: Tru;\r\n}\r\n\r\n/** A constant entry within an enum type definition. */\r\nexport interface TypeDefConstant {\r\n  name: string;\r\n  value: unknown;\r\n  index: number;\r\n}\r\n\r\n/**\r\n * Minimal, layer-neutral view of a type definition used by the serializer\r\n * (records/enums). The full implementation (`LocalTypeDef`) lives in the\r\n * resource layer and is resolved via a registered hook, keeping `data/`\r\n * independent of the resource model.\r\n */\r\nexport interface ITypeDef {\r\n  readonly id: number;\r\n  readonly kind: TypeDefKind;\r\n  readonly name: string;\r\n  readonly properties: ReadonlyArray<TypeDefProperty>;\r\n  readonly constants?: ReadonlyArray<TypeDefConstant>;\r\n  /** Create a fresh instance of the described type. */\r\n  createInstance(): object;\r\n  /** Assign a decoded property value to an instance. */\r\n  setProperty(instance: object, name: string, value: unknown): void;\r\n}\r\n","import { Tru, TruPrimitive, TruComposite } from \"./Tru.js\";\r\nimport { TruIdentifier } from \"./TruIdentifier.js\";\r\n\r\n/**\r\n * Type descriptors — the TypeScript stand-in for C#'s reflection-driven\r\n * `Tru.FromType`. Use these to declare element/key/value types where the wire\r\n * needs a type representation (typed lists/maps/tuples), e.g.\r\n * `t.list(t.i32)` or `t.map(t.string, t.f64)`. The codegen CLI emits these.\r\n */\r\nexport function tupleIdentifier(count: number): TruIdentifier {\r\n  switch (count) {\r\n    case 2: return TruIdentifier.Tuple2;\r\n    case 3: return TruIdentifier.Tuple3;\r\n    case 4: return TruIdentifier.Tuple4;\r\n    case 5: return TruIdentifier.Tuple5;\r\n    case 6: return TruIdentifier.Tuple6;\r\n    case 7: return TruIdentifier.Tuple7;\r\n    default:\r\n      throw new RangeError(\"Tuples must have between 2 and 7 elements.\");\r\n  }\r\n}\r\n\r\nexport const t = {\r\n  void: new TruPrimitive(TruIdentifier.Void),\r\n  dynamic: new TruPrimitive(TruIdentifier.Dynamic),\r\n  bool: new TruPrimitive(TruIdentifier.Bool),\r\n  char: new TruPrimitive(TruIdentifier.Char),\r\n  u8: new TruPrimitive(TruIdentifier.UInt8),\r\n  i8: new TruPrimitive(TruIdentifier.Int8),\r\n  u16: new TruPrimitive(TruIdentifier.UInt16),\r\n  i16: new TruPrimitive(TruIdentifier.Int16),\r\n  u32: new TruPrimitive(TruIdentifier.UInt32),\r\n  i32: new TruPrimitive(TruIdentifier.Int32),\r\n  u64: new TruPrimitive(TruIdentifier.UInt64),\r\n  i64: new TruPrimitive(TruIdentifier.Int64),\r\n  u128: new TruPrimitive(TruIdentifier.UInt128),\r\n  i128: new TruPrimitive(TruIdentifier.Int128),\r\n  f32: new TruPrimitive(TruIdentifier.Float32),\r\n  f64: new TruPrimitive(TruIdentifier.Float64),\r\n  decimal: new TruPrimitive(TruIdentifier.Decimal),\r\n  string: new TruPrimitive(TruIdentifier.String),\r\n  rawData: new TruPrimitive(TruIdentifier.RawData),\r\n  datetime: new TruPrimitive(TruIdentifier.DateTime),\r\n  resource: new TruPrimitive(TruIdentifier.Resource),\r\n  record: new TruPrimitive(TruIdentifier.Record),\r\n\r\n  list: (element: Tru): TruComposite =>\r\n    new TruComposite(TruIdentifier.TypedList, false, [element]),\r\n  map: (key: Tru, value: Tru): TruComposite =>\r\n    new TruComposite(TruIdentifier.TypedMap, false, [key, value]),\r\n  tuple: (...subTypes: Tru[]): TruComposite =>\r\n    new TruComposite(tupleIdentifier(subTypes.length), false, subTypes),\r\n  nullable: (type: Tru): Tru => type.toNullable(),\r\n} as const;\r\n\r\n/**\r\n * An explicitly-typed array value. Composing it produces a Typed TDU whose\r\n * metadata is `TypedList<element>`; numeric element types use the compact Gvwie\r\n * group encoding.\r\n */\r\nexport class TypedList {\r\n  constructor(\r\n    readonly element: Tru,\r\n    readonly values: readonly unknown[],\r\n  ) {}\r\n}\r\n\r\n/** Construct a {@link TypedList} value, e.g. `typedList(t.i32, [1, 2, 3])`. */\r\nexport function typedList(element: Tru, values: readonly unknown[]): TypedList {\r\n  return new TypedList(element, values);\r\n}\r\n\r\n/**\r\n * An explicitly-typed map value. Composing it produces a Typed TDU with\r\n * metadata `TypedMap<key, value>` whose payload is the keys array followed by\r\n * the values array.\r\n */\r\nexport class TypedMap {\r\n  readonly entries: ReadonlyArray<readonly [unknown, unknown]>;\r\n  constructor(\r\n    readonly keyType: Tru,\r\n    readonly valueType: Tru,\r\n    entries: Map<unknown, unknown> | ReadonlyArray<readonly [unknown, unknown]>,\r\n  ) {\r\n    this.entries = entries instanceof Map ? [...entries.entries()] : entries;\r\n  }\r\n}\r\n\r\n/** Construct a {@link TypedMap}, e.g. `typedMap(t.string, t.i32, myMap)`. */\r\nexport function typedMap(\r\n  keyType: Tru,\r\n  valueType: Tru,\r\n  entries: Map<unknown, unknown> | ReadonlyArray<readonly [unknown, unknown]>,\r\n): TypedMap {\r\n  return new TypedMap(keyType, valueType, entries);\r\n}\r\n\r\n/**\r\n * An explicitly-typed tuple value (2-7 elements). Composing it produces a Typed\r\n * TDU with metadata `TupleN<...elementTypes>`.\r\n */\r\nexport class TypedTuple {\r\n  constructor(\r\n    readonly elements: readonly Tru[],\r\n    readonly values: readonly unknown[],\r\n  ) {\r\n    if (elements.length !== values.length)\r\n      throw new RangeError(\"Tuple element-type count must match value count.\");\r\n  }\r\n}\r\n\r\n/** Construct a {@link TypedTuple}, e.g. `typedTuple([t.i32, t.string], [1, \"a\"])`. */\r\nexport function typedTuple(elements: readonly Tru[], values: readonly unknown[]): TypedTuple {\r\n  return new TypedTuple(elements, values);\r\n}\r\n","import { Tdu } from \"./Tdu.js\";\r\nimport { TduIdentifier } from \"./TduIdentifier.js\";\r\nimport { TduClass } from \"./TduClass.js\";\r\nimport { ParsedTdu } from \"./ParsedTdu.js\";\r\nimport * as D from \"./DataDeserializer.js\";\r\nimport { Decimal128 } from \"./Decimal128.js\";\r\nimport { Uuid } from \"./Uuid.js\";\r\nimport { merge } from \"./DC.js\";\r\nimport { Tru, TruComposite, type RemoteTypeDefResolver } from \"./Tru.js\";\r\nimport { TruIdentifier } from \"./TruIdentifier.js\";\r\nimport { TypedList, TypedMap, TypedTuple, tupleIdentifier } from \"./descriptors.js\";\r\nimport { IndexedStructure } from \"./IndexedStructure.js\";\r\nimport { TypeDefInfo } from \"./types/TypeDefInfo.js\";\r\nimport {\r\n  GroupInt16Codec,\r\n  GroupInt32Codec,\r\n  GroupInt64Codec,\r\n  GroupUInt16Codec,\r\n  GroupUInt32Codec,\r\n  GroupUInt64Codec,\r\n} from \"./gvwie/index.js\";\r\nimport {\r\n  Int8,\r\n  UInt8,\r\n  Int16,\r\n  UInt16,\r\n  Int32,\r\n  UInt32,\r\n  Int64,\r\n  UInt64,\r\n  Float32,\r\n  Char16,\r\n} from \"./widths.js\";\r\nimport * as S from \"./DataSerializer.js\";\r\n\r\n/**\r\n * Self-describing value codec (port of C# `Codec`). Encodes a value to its\r\n * type-prefixed TDU representation.\r\n *\r\n * Type mapping for bare JS values:\r\n *  - `null`/`undefined` → Null\r\n *  - `boolean` → True/False\r\n *  - `number` → C# `double` semantics (narrowed; integral → smallest int)\r\n *  - `bigint` → C# `long` semantics (narrowed)\r\n *  - `string` → String\r\n *  - `Date` → DateTime, `Uuid` → UUID, `Decimal128` → Decimal128\r\n *  - width wrappers (`u8`, `i32`, `f32`, …) pin an explicit wire width\r\n *\r\n * Collections, maps, records and resources require the type registry and\r\n * connection context and are added in the Phase 2 continuation.\r\n */\r\nexport function composeInternal(\r\n  value: unknown,\r\n  warehouse: unknown = null,\r\n  connection: unknown = null,\r\n): Tdu {\r\n  if (value === null || value === undefined)\r\n    return new Tdu(TduIdentifier.Null, null, 0);\r\n\r\n  // Explicit width wrappers\r\n  if (value instanceof UInt8) return S.uint8Composer(value.value);\r\n  if (value instanceof Int8) return S.int8Composer(value.value);\r\n  if (value instanceof UInt16) return S.uint16Composer(value.value);\r\n  if (value instanceof Int16) return S.int16Composer(value.value);\r\n  if (value instanceof UInt32) return S.uint32Composer(value.value);\r\n  if (value instanceof Int32) return S.int32Composer(value.value);\r\n  if (value instanceof UInt64) return S.uint64Composer(value.value);\r\n  if (value instanceof Int64) return S.int64Composer(value.value);\r\n  if (value instanceof Float32) return S.float32Composer(value.value);\r\n  if (value instanceof Char16) return S.char16Composer(value.value);\r\n\r\n  switch (typeof value) {\r\n    case \"boolean\":\r\n      return S.boolComposer(value);\r\n    case \"number\":\r\n      return S.float64Composer(value);\r\n    case \"bigint\":\r\n      return S.int64Composer(value);\r\n    case \"string\":\r\n      return S.stringComposer(value);\r\n  }\r\n\r\n  if (value instanceof Date) return S.dateTimeComposer(value);\r\n  if (value instanceof Uuid) return S.uuidComposer(value);\r\n  if (value instanceof Decimal128) return S.decimal128Composer(value);\r\n  if (value instanceof Uint8Array) return S.rawDataComposer(value);\r\n  if (value instanceof TypedList) return typedListComposer(value, warehouse, connection);\r\n  if (value instanceof TypedMap) return typedMapComposer(value, warehouse, connection);\r\n  if (value instanceof TypedTuple) return tupleComposer(value, warehouse, connection);\r\n  if (value instanceof Map) return mapComposer(value, warehouse, connection);\r\n\r\n  // A bare JS array becomes a dynamic, self-describing List (each element keeps\r\n  // its own type tag). Typed Gvwie arrays are produced from explicit typed-list\r\n  // values via the Tru family.\r\n  if (Array.isArray(value))\r\n    return listComposer(value, TduIdentifier.List, warehouse, connection);\r\n  if (value instanceof Map)\r\n    return mapComposer(value, warehouse, connection);\r\n\r\n  // A `Tru` value composes into its own dedicated, metadata-free TDU slot; a\r\n  // `TypeDefInfo` composes into its own dedicated slot wrapping a structure\r\n  // payload; any other `IndexedStructure` composes as a plain sparse\r\n  // `TypedMap<u8, dynamic>` (see `IndexedStructureCodec`).\r\n  if (value instanceof Tru) return S.truComposer(value, warehouse, connection);\r\n  if (value instanceof TypeDefInfo) return S.typeDefComposer(value, warehouse, connection);\r\n  if (value instanceof IndexedStructure)\r\n    return S.structureComposer(value, warehouse, connection);\r\n\r\n  // Records, enums and other registered structured types are handled by the\r\n  // resource layer through hooks, keeping `data/` independent of it.\r\n  for (const fn of structuredComposers) {\r\n    const tdu = fn(value, warehouse, connection);\r\n    if (tdu) return tdu;\r\n  }\r\n\r\n  throw new Error(\r\n    `Codec.compose: serialization for ${describe(value)} is not supported.`,\r\n  );\r\n}\r\n\r\n/**\r\n * Hooks for composing registered structured types (records, enums). Installed by\r\n * the resource layer; each returns a {@link Tdu} for a recognized value or\r\n * undefined. They are tried in registration order.\r\n */\r\nconst structuredComposers: Array<\r\n  (value: unknown, warehouse: unknown, connection: unknown) => Tdu | undefined\r\n> = [];\r\n\r\n/** Register a structured-type composer hook (called by the resource layer). */\r\nexport function registerComposer(\r\n  fn: (value: unknown, warehouse: unknown, connection: unknown) => Tdu | undefined,\r\n): void {\r\n  structuredComposers.push(fn);\r\n}\r\n\r\n/** Encode a value to its self-describing TDU bytes (leading identifier included). */\r\nexport function compose(\r\n  value: unknown,\r\n  warehouse: unknown = null,\r\n  connection: unknown = null,\r\n): Uint8Array {\r\n  return composeInternal(value, warehouse, connection).composed;\r\n}\r\n\r\n/**\r\n * Compose a self-describing array as a single Dynamic TDU. Consecutive items of\r\n * the same typed shape collapse to a TypeContinuation (matching C#\r\n * `DynamicArrayComposer`); primitives never match, so each is emitted in full.\r\n */\r\nfunction listComposer(\r\n  value: Iterable<unknown>,\r\n  identifier: TduIdentifier,\r\n  warehouse: unknown,\r\n  connection: unknown,\r\n): Tdu {\r\n  const parts: Uint8Array[] = [];\r\n  let previous: Tdu | null = null;\r\n\r\n  for (const el of value) {\r\n    const tdu = composeInternal(el, warehouse, connection);\r\n    if (previous && tdu.matchType(previous)) {\r\n      const d = tdu.composed.subarray(tdu.contentOffset);\r\n      parts.push(new Tdu(TduIdentifier.TypeContinuation, d, d.length).composed);\r\n    } else {\r\n      parts.push(tdu.composed);\r\n    }\r\n    previous = tdu;\r\n  }\r\n\r\n  const content = merge(...parts);\r\n  return new Tdu(identifier, content, content.length);\r\n}\r\n\r\n/** Compose a dynamic Map TDU as alternating key/value self-describing TDUs. */\r\nfunction mapComposer(\r\n  value: Map<unknown, unknown>,\r\n  warehouse: unknown,\r\n  connection: unknown,\r\n): Tdu {\r\n  const flat: unknown[] = [];\r\n  for (const [key, item] of value.entries()) {\r\n    flat.push(key, item);\r\n  }\r\n  return listComposer(flat, TduIdentifier.Map, warehouse, connection);\r\n}\r\n\r\n/** Compose an explicitly-typed array as a Typed TDU with `TypedList<element>`. */\r\nfunction typedListComposer(value: TypedList, warehouse: unknown, connection: unknown): Tdu {\r\n  const payload = typedArrayComposer(value.values, value.element, warehouse, connection);\r\n  const metadata = new TruComposite(TruIdentifier.TypedList, false, [value.element]);\r\n  return new Tdu(TduIdentifier.Typed, payload, payload.length, metadata, connection);\r\n}\r\n\r\n/**\r\n * Encode the elements of a typed array. Numeric element types use the compact\r\n * Gvwie group encoding; other element types fall back to a concatenation of\r\n * self-describing TDUs (matching C# `DataSerializer.TypedArrayComposer` for\r\n * primitive elements).\r\n */\r\nfunction typedArrayComposer(\r\n  values: readonly unknown[],\r\n  element: Tru,\r\n  warehouse: unknown,\r\n  connection: unknown,\r\n): Uint8Array {\r\n  switch (element.identifier) {\r\n    case TruIdentifier.Int16:\r\n      return GroupInt16Codec.encode(values as number[]);\r\n    case TruIdentifier.Int32:\r\n      return GroupInt32Codec.encode(values as number[]);\r\n    case TruIdentifier.Int64:\r\n      return GroupInt64Codec.encode(values as bigint[]);\r\n    case TruIdentifier.UInt16:\r\n      return GroupUInt16Codec.encode(values as number[]);\r\n    case TruIdentifier.UInt32:\r\n      return GroupUInt32Codec.encode(values as number[]);\r\n    case TruIdentifier.UInt64:\r\n      return GroupUInt64Codec.encode(values as bigint[]);\r\n    default: {\r\n      const parts: Uint8Array[] = [];\r\n      let previous: Tdu | null = null;\r\n      for (const v of values) {\r\n        const tdu = composeInternal(v, warehouse, connection);\r\n        if (tdu.tduClass === TduClass.Typed && tdu.metadata && element.match(tdu.metadata as Tru)) {\r\n          // Element's type matches the declared element type: strip its metadata.\r\n          const d = tdu.composed.subarray(tdu.contentOffset);\r\n          parts.push(new Tdu(TduIdentifier.TypeOfTarget, d, d.length).composed);\r\n        } else if (previous && tdu.matchType(previous)) {\r\n          const d = tdu.composed.subarray(tdu.contentOffset);\r\n          parts.push(new Tdu(TduIdentifier.TypeContinuation, d, d.length).composed);\r\n        } else {\r\n          parts.push(tdu.composed);\r\n        }\r\n        previous = tdu;\r\n      }\r\n      return merge(...parts);\r\n    }\r\n  }\r\n}\r\n\r\n/** Compose an explicitly-typed map as a Typed TDU (`TypedMap<key,value>`). */\r\nfunction typedMapComposer(value: TypedMap, warehouse: unknown, connection: unknown): Tdu {\r\n  const keys = value.entries.map((e) => e[0]);\r\n  const values = value.entries.map((e) => e[1]);\r\n  const composedKeys = typedArrayComposer(keys, value.keyType, warehouse, connection);\r\n  const composedValues = typedArrayComposer(values, value.valueType, warehouse, connection);\r\n\r\n  const keysTdu = new Tdu(TduIdentifier.TypeOfTarget, composedKeys, composedKeys.length).composed;\r\n  const valuesTdu = new Tdu(TduIdentifier.TypeOfTarget, composedValues, composedValues.length).composed;\r\n  const all = merge(keysTdu, valuesTdu);\r\n\r\n  const metadata = new TruComposite(TruIdentifier.TypedMap, false, [value.keyType, value.valueType]);\r\n  return new Tdu(TduIdentifier.Typed, all, all.length, metadata, connection);\r\n}\r\n\r\n/** Compose an explicitly-typed tuple as a Typed TDU (`TupleN<...>`). */\r\nfunction tupleComposer(value: TypedTuple, warehouse: unknown, connection: unknown): Tdu {\r\n  const parts: Uint8Array[] = [];\r\n  for (let i = 0; i < value.values.length; i++) {\r\n    const target = value.elements[i];\r\n    const tdu = composeInternal(value.values[i], warehouse, connection);\r\n    if (tdu.tduClass === TduClass.Typed && tdu.metadata && target.match(tdu.metadata as Tru)) {\r\n      const d = tdu.composed.subarray(tdu.contentOffset);\r\n      parts.push(new Tdu(TduIdentifier.TypeOfTarget, d, d.length).composed);\r\n    } else {\r\n      parts.push(tdu.composed);\r\n    }\r\n  }\r\n  const all = merge(...parts);\r\n  const metadata = new TruComposite(\r\n    tupleIdentifier(value.elements.length),\r\n    false,\r\n    value.elements as Tru[],\r\n  );\r\n  return new Tdu(TduIdentifier.Typed, all, all.length, metadata, connection);\r\n}\r\n\r\nfunction describe(value: unknown): string {\r\n  if (Array.isArray(value)) return \"array\";\r\n  const ctor = (value as { constructor?: { name?: string } })?.constructor?.name;\r\n  return ctor ?? typeof value;\r\n}\r\n\r\n// ---- decode -----------------------------------------------------------------\r\n\r\n/** Sync parser dispatch table, indexed `[exponent][index]` for Fixed TDUs. */\r\nconst fixedParsers: D.Parser[][] = [\r\n  [D.nullParser, D.booleanFalseParser, D.booleanTrueParser, D.notModifiedParser, D.infinityParser],\r\n  [D.uint8Parser, D.int8Parser, D.char8Parser, D.localResource8Parser, D.resource8Parser],\r\n  [D.uint16Parser, D.int16Parser, D.char16Parser, D.localResource16Parser, D.resource16Parser],\r\n  [D.uint32Parser, D.int32Parser, D.float32Parser, D.localResource32Parser, D.resource32Parser],\r\n  [D.uint64Parser, D.int64Parser, D.float64Parser, D.dateTimeParser],\r\n  [D.uint128Parser, D.int128Parser, D.decimal128Parser, D.uuidParser],\r\n];\r\n\r\nconst dynamicParsers: D.Parser[] = [\r\n  D.rawDataParser,\r\n  D.stringParser,\r\n  D.listParser,\r\n  D.resourceListParser,\r\n  D.recordListParser,\r\n  D.resourceLinkParser,\r\n  D.mapParser,\r\n  D.mapListParser,\r\n];\r\n\r\nconst typedParsers: D.Parser[] = [D.typedParser, D.typeDefInfoParser, D.truParser];\r\n\r\n/** Dispatch an already-parsed TDU header to the matching value parser. */\r\nexport function parseSyncTdu(tdu: ParsedTdu, warehouse: unknown = null): unknown {\r\n  switch (tdu.tduClass) {\r\n    case TduClass.Fixed:\r\n      return fixedParsers[tdu.exponent][tdu.index](tdu, warehouse);\r\n    case TduClass.Dynamic:\r\n      return dynamicParsers[tdu.index](tdu, warehouse);\r\n    case TduClass.Typed:\r\n      return typedParsers[tdu.index](tdu, warehouse);\r\n    case TduClass.Extension:\r\n      throw new Error(\"Extension TDUs are not supported.\");\r\n    default:\r\n      throw new Error(\"Invalid TDU.\");\r\n  }\r\n}\r\n\r\n/** Decode one value at `offset`; returns the value and bytes consumed. */\r\nexport function parseSync(\r\n  data: Uint8Array,\r\n  offset = 0,\r\n  warehouse: unknown = null,\r\n): { value: unknown; length: number } {\r\n  const tdu = ParsedTdu.parseSync(data, offset, data.length, warehouse);\r\n  if (tdu.tduClass === TduClass.Invalid)\r\n    throw new Error(\"DataType can't be parsed.\");\r\n  return { value: parseSyncTdu(tdu, warehouse), length: tdu.totalLength };\r\n}\r\n\r\n/** Decode one value at `offset` and return just the value. */\r\nexport function parse(data: Uint8Array, offset = 0, warehouse: unknown = null): unknown {\r\n  return parseSync(data, offset, warehouse).value;\r\n}\r\n\r\n// ---- async decode -------------------------------------------------------\r\n//\r\n// Parallel to the sync pipeline above, needed only because a `Tru`/`TypeDef`\r\n// value anywhere in a decoded tree may reference a not-yet-fetched remote\r\n// TypeDef. Most callers (regular request/reply decoding) never need this —\r\n// it exists for `RemoteTypeDef`'s new-format (`TduIdentifier.TypeDef`, 0x81)\r\n// decode path, which commonly contains member value-types that reference\r\n// other remote TypeDefs on the same connection.\r\n\r\nconst dynamicAsyncParsers: D.AsyncParser[] = [\r\n  D.rawDataParserAsync,\r\n  D.stringParserAsync,\r\n  D.listParserAsync,\r\n  D.resourceListParserAsync,\r\n  D.recordListParserAsync,\r\n  D.resourceLinkParserAsync,\r\n  D.mapParserAsync,\r\n  D.mapListParserAsync,\r\n];\r\n\r\nconst typedAsyncParsers: D.AsyncParser[] = [\r\n  D.typedParserAsync,\r\n  D.typeDefInfoParserAsync,\r\n  D.truParserAsync,\r\n];\r\n\r\n/** Async twin of {@link parseSyncTdu}. */\r\nexport async function parseAsyncTdu(\r\n  tdu: ParsedTdu,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<unknown> {\r\n  switch (tdu.tduClass) {\r\n    case TduClass.Fixed:\r\n      // Fixed-class values are always primitives; no async resolution is ever needed.\r\n      return fixedParsers[tdu.exponent][tdu.index](tdu, warehouse);\r\n    case TduClass.Dynamic:\r\n      return dynamicAsyncParsers[tdu.index](tdu, warehouse, remoteResolver, requestSequence);\r\n    case TduClass.Typed:\r\n      return typedAsyncParsers[tdu.index](tdu, warehouse, remoteResolver, requestSequence);\r\n    case TduClass.Extension:\r\n      throw new Error(\"Extension TDUs are not supported.\");\r\n    default:\r\n      throw new Error(\"Invalid TDU.\");\r\n  }\r\n}\r\n\r\n/** Async twin of {@link parseSync}. */\r\nexport async function parseAsync(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<{ value: unknown; length: number }> {\r\n  const tdu = await ParsedTdu.parseAsync(\r\n    data,\r\n    offset,\r\n    data.length,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  if (tdu.tduClass === TduClass.Invalid) throw new Error(\"DataType can't be parsed.\");\r\n  return {\r\n    value: await parseAsyncTdu(tdu, warehouse, remoteResolver, requestSequence),\r\n    length: tdu.totalLength,\r\n  };\r\n}\r\n","import { ParsedTdu } from \"./ParsedTdu.js\";\r\nimport { TduClass } from \"./TduClass.js\";\r\nimport { TduIdentifier } from \"./TduIdentifier.js\";\r\nimport { NotModified } from \"./NotModified.js\";\r\nimport { Uuid } from \"./Uuid.js\";\r\nimport { Int128 } from \"./Int128.js\";\r\nimport { UInt128 } from \"./UInt128.js\";\r\nimport { Decimal128 } from \"./Decimal128.js\";\r\nimport { ResourceId } from \"./ResourceId.js\";\r\nimport { ResourceLink } from \"./ResourceLink.js\";\r\nimport * as DC from \"./DC.js\";\r\nimport { parseAsyncTdu, parseAsync, parseSync, parseSyncTdu } from \"./Codec.js\";\r\nimport { Tru, TruComposite, TruTypeDef, type RemoteTypeDefResolver } from \"./Tru.js\";\r\nimport { TruIdentifier } from \"./TruIdentifier.js\";\r\nimport { TypeDefKind, type ITypeDef } from \"./types/ITypeDef.js\";\r\nimport { fromIndexedMap } from \"./IndexedStructureCodec.js\";\r\nimport { TypeDefInfo } from \"./types/TypeDefInfo.js\";\r\nimport { PropertyDefInfo } from \"./types/PropertyDefInfo.js\";\r\nimport { FunctionDefInfo } from \"./types/FunctionDefInfo.js\";\r\nimport { EventDefInfo } from \"./types/EventDefInfo.js\";\r\nimport { ConstantDefInfo } from \"./types/ConstantDefInfo.js\";\r\nimport { ArgumentDefInfo } from \"./types/ArgumentDefInfo.js\";\r\nimport {\r\n  GroupInt16Codec,\r\n  GroupInt32Codec,\r\n  GroupInt64Codec,\r\n  GroupUInt16Codec,\r\n  GroupUInt32Codec,\r\n  GroupUInt64Codec,\r\n} from \"./gvwie/index.js\";\r\n\r\n/**\r\n * Sync value parsers (port of the sync parsers in C# `DataDeserializer`). Each\r\n * reads its value from `tdu.data` at `tdu.payloadOffset`. Returned JS types:\r\n * integers ≤32-bit and floats → `number`, 64-bit → `bigint`, decimal →\r\n * {@link Decimal128}, datetime → `Date`, uuid → {@link Uuid}.\r\n */\r\nexport type Parser = (tdu: ParsedTdu, warehouse: unknown) => unknown;\r\n\r\n/**\r\n * Async twin of {@link Parser}, used where a `Tru`/`TypeDef`-family value\r\n * anywhere in the tree may need to resolve a not-yet-fetched remote TypeDef\r\n * reference via `remoteResolver`.\r\n */\r\nexport type AsyncParser = (\r\n  tdu: ParsedTdu,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n) => Promise<unknown>;\r\n\r\nexport const nullParser: Parser = () => null;\r\nexport const booleanTrueParser: Parser = () => true;\r\nexport const booleanFalseParser: Parser = () => false;\r\nexport const notModifiedParser: Parser = () => NotModified.Default;\r\nexport const infinityParser: Parser = () => Number.POSITIVE_INFINITY;\r\n\r\nexport const uint8Parser: Parser = (t) => DC.getUint8(t.data, t.payloadOffset);\r\nexport const int8Parser: Parser = (t) => DC.getInt8(t.data, t.payloadOffset);\r\nexport const char8Parser: Parser = (t) => DC.getUint8(t.data, t.payloadOffset);\r\nexport const char16Parser: Parser = (t) => DC.getUint16(t.data, t.payloadOffset);\r\nexport const int16Parser: Parser = (t) => DC.getInt16(t.data, t.payloadOffset);\r\nexport const uint16Parser: Parser = (t) => DC.getUint16(t.data, t.payloadOffset);\r\nexport const int32Parser: Parser = (t) => DC.getInt32(t.data, t.payloadOffset);\r\nexport const uint32Parser: Parser = (t) => DC.getUint32(t.data, t.payloadOffset);\r\nexport const float32Parser: Parser = (t) => DC.getFloat32(t.data, t.payloadOffset);\r\nexport const float64Parser: Parser = (t) => DC.getFloat64(t.data, t.payloadOffset);\r\nexport const int64Parser: Parser = (t) => DC.getInt64(t.data, t.payloadOffset);\r\nexport const uint64Parser: Parser = (t) => DC.getUint64(t.data, t.payloadOffset);\r\nexport const dateTimeParser: Parser = (t) => DC.getDateTime(t.data, t.payloadOffset);\r\n\r\nexport const decimal128Parser: Parser = (t) =>\r\n  Decimal128.fromBytes(t.data, t.payloadOffset);\r\nexport const uuidParser: Parser = (t) => new Uuid(t.data, t.payloadOffset);\r\n\r\nexport const int128Parser: Parser = (t) =>\r\n  new Int128(\r\n    DC.getUint64(t.data, t.payloadOffset),\r\n    DC.getUint64(t.data, t.payloadOffset + 8),\r\n  );\r\nexport const uint128Parser: Parser = (t) =>\r\n  new UInt128(\r\n    DC.getUint64(t.data, t.payloadOffset),\r\n    DC.getUint64(t.data, t.payloadOffset + 8),\r\n  );\r\n\r\nexport const resourceLinkParser: Parser = (t) =>\r\n  new ResourceLink(DC.getString(t.data, t.payloadOffset, t.payloadLength));\r\n\r\nexport const rawDataParser: Parser = (t) =>\r\n  t.data.slice(t.payloadOffset, t.payloadOffset + t.payloadLength);\r\nexport const stringParser: Parser = (t) =>\r\n  DC.getString(t.data, t.payloadOffset, t.payloadLength);\r\n\r\n// Resource references (sync path returns placeholders).\r\nexport const resource8Parser: Parser = (t) => new ResourceId(false, DC.getUint8(t.data, t.payloadOffset));\r\nexport const resource16Parser: Parser = (t) => new ResourceId(false, DC.getUint16(t.data, t.payloadOffset));\r\nexport const resource32Parser: Parser = (t) => new ResourceId(false, DC.getUint32(t.data, t.payloadOffset));\r\nexport const localResource8Parser: Parser = (t) => new ResourceId(true, DC.getUint8(t.data, t.payloadOffset));\r\nexport const localResource16Parser: Parser = (t) => new ResourceId(true, DC.getUint16(t.data, t.payloadOffset));\r\nexport const localResource32Parser: Parser = (t) => new ResourceId(true, DC.getUint32(t.data, t.payloadOffset));\r\n\r\n/** Parse a self-describing array payload, honouring TypeContinuation runs. */\r\nfunction parseDynamicArray(tdu: ParsedTdu, warehouse: unknown): unknown[] {\r\n  const list: unknown[] = [];\r\n  let offset = tdu.payloadOffset;\r\n  let length = tdu.payloadLength;\r\n  const ends = offset + length;\r\n  let previous: ParsedTdu | null = null;\r\n\r\n  while (length > 0) {\r\n    const current = ParsedTdu.parseSync(tdu.data, offset, ends, warehouse);\r\n    if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n    if (current.identifier === TduIdentifier.TypeContinuation && previous) {\r\n      current.tduClass = previous.tduClass;\r\n      current.identifier = previous.identifier;\r\n      current.metadata = previous.metadata;\r\n    }\r\n\r\n    list.push(parseSyncTdu(current, warehouse));\r\n\r\n    if (current.totalLength <= 0)\r\n      throw new Error(\"Error while parsing structured data.\");\r\n    offset += current.totalLength;\r\n    length -= current.totalLength;\r\n    previous = current;\r\n  }\r\n\r\n  return list;\r\n}\r\n\r\nexport const listParser: Parser = (t, w) => parseDynamicArray(t, w);\r\nexport const resourceListParser: Parser = (t, w) => parseDynamicArray(t, w);\r\nexport const recordListParser: Parser = (t, w) => parseDynamicArray(t, w);\r\nexport const mapParser: Parser = (t, w) => {\r\n  const flat = parseDynamicArray(t, w);\r\n  const map = new Map<unknown, unknown>();\r\n  for (let i = 0; i + 1 < flat.length; i += 2)\r\n    map.set(flat[i], flat[i + 1]);\r\n  return map;\r\n};\r\nexport const mapListParser: Parser = (t, w) => parseDynamicArray(t, w);\r\n\r\nexport const typedParser: Parser = (tdu, warehouse) => {\r\n  const tru = tdu.metadata;\r\n  if (tru instanceof TruComposite) {\r\n    switch (tru.identifier) {\r\n      case TruIdentifier.TypedList:\r\n        return typedArrayParser(tdu, tru.subTypes[0], warehouse);\r\n      case TruIdentifier.TypedMap:\r\n        return typedMapParser(tdu, tru.subTypes[0], tru.subTypes[1], warehouse);\r\n      case TruIdentifier.Tuple2:\r\n      case TruIdentifier.Tuple3:\r\n      case TruIdentifier.Tuple4:\r\n      case TruIdentifier.Tuple5:\r\n      case TruIdentifier.Tuple6:\r\n      case TruIdentifier.Tuple7:\r\n        return tupleParser(tdu, tru.subTypes, warehouse);\r\n      default:\r\n        throw new Error(\"Unsupported type for typed parser.\");\r\n    }\r\n  }\r\n  if (tru instanceof TruTypeDef) return typedObjectParser(tdu, tru.typeDef, warehouse);\r\n  throw new Error(\"Unknown TRU.\");\r\n};\r\n\r\n/** Dispatch a TypeDef-described typed value to the record/enum parser. */\r\nfunction typedObjectParser(tdu: ParsedTdu, typeDef: ITypeDef, warehouse: unknown): unknown {\r\n  if (typeDef.kind === TypeDefKind.Record) return recordParser(tdu, typeDef, warehouse);\r\n  if (typeDef.kind === TypeDefKind.Enum) return enumParser(tdu, typeDef);\r\n  throw new Error(\"Typed resource parsing is not supported yet.\");\r\n}\r\n\r\n/** Decode a record TDU: parse each property in TypeDef order, then build the instance. */\r\nfunction recordParser(tdu: ParsedTdu, typeDef: ITypeDef, warehouse: unknown): object {\r\n  const values: unknown[] = [];\r\n  let offset = tdu.payloadOffset;\r\n  let length = tdu.payloadLength;\r\n  const ends = offset + length;\r\n  let previous: ParsedTdu | null = null;\r\n\r\n  for (let i = 0; i < typeDef.properties.length; i++) {\r\n    const current = ParsedTdu.parseSync(tdu.data, offset, ends, warehouse);\r\n    if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n    if (current.identifier === TduIdentifier.TypeContinuation && previous) {\r\n      current.tduClass = previous.tduClass;\r\n      current.identifier = previous.identifier;\r\n      current.metadata = previous.metadata;\r\n    } else if (current.identifier === TduIdentifier.TypeOfTarget) {\r\n      current.tduClass = TduClass.Typed;\r\n      current.identifier = TduIdentifier.Typed;\r\n      current.metadata = typeDef.properties[i].valueType ?? null;\r\n      current.index = TduIdentifier.Typed & 0x7;\r\n    }\r\n\r\n    values.push(parseSyncTdu(current, warehouse));\r\n\r\n    if (current.totalLength <= 0)\r\n      throw new Error(\"Error while parsing structured data.\");\r\n    offset += current.totalLength;\r\n    length -= current.totalLength;\r\n    previous = current;\r\n  }\r\n\r\n  const instance = typeDef.createInstance();\r\n  for (let i = 0; i < typeDef.properties.length; i++)\r\n    typeDef.setProperty(instance, typeDef.properties[i].name, values[i]);\r\n  return instance;\r\n}\r\n\r\n/** Decode an enum TDU: a single constant-index byte resolved via the typedef. */\r\nfunction enumParser(tdu: ParsedTdu, typeDef: ITypeDef): unknown {\r\n  const index = tdu.data[tdu.payloadOffset];\r\n  return typeDef.constants?.[index]?.value;\r\n}\r\n\r\n/** Decode the payload of a `TypedList<element>` TDU into a JS array. */\r\nfunction typedArrayParser(tdu: ParsedTdu, element: Tru, warehouse: unknown): unknown[] {\r\n  const start = tdu.payloadOffset;\r\n  const end = start + tdu.payloadLength;\r\n\r\n  switch (element.identifier) {\r\n    case TruIdentifier.Int16:\r\n      return GroupInt16Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.Int32:\r\n      return GroupInt32Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.Int64:\r\n      return GroupInt64Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.UInt16:\r\n      return GroupUInt16Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.UInt32:\r\n      return GroupUInt32Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.UInt64:\r\n      return GroupUInt64Codec.decode(tdu.data, start, end);\r\n    default: {\r\n      const list: unknown[] = [];\r\n      let offset = start;\r\n      let length = tdu.payloadLength;\r\n      let previous: ParsedTdu | null = null;\r\n\r\n      while (length > 0) {\r\n        const current = ParsedTdu.parseSync(tdu.data, offset, end, warehouse);\r\n        if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n        if (current.identifier === TduIdentifier.TypeContinuation && previous) {\r\n          current.tduClass = previous.tduClass;\r\n          current.identifier = previous.identifier;\r\n          current.metadata = previous.metadata;\r\n        } else if (current.identifier === TduIdentifier.TypeOfTarget) {\r\n          current.tduClass = TduClass.Typed;\r\n          current.identifier = TduIdentifier.Typed;\r\n          current.metadata = element;\r\n          current.index = TduIdentifier.Typed & 0x7;\r\n        }\r\n\r\n        list.push(parseSyncTdu(current, warehouse));\r\n\r\n        if (current.totalLength <= 0)\r\n          throw new Error(\"Error while parsing structured data.\");\r\n        offset += current.totalLength;\r\n        length -= current.totalLength;\r\n        previous = current;\r\n      }\r\n      return list;\r\n    }\r\n  }\r\n}\r\n\r\n/** Decode a `TypedMap<key,value>` TDU (two TypeOfTarget-wrapped arrays) to a JS Map. */\r\nfunction typedMapParser(\r\n  tdu: ParsedTdu,\r\n  keyTru: Tru,\r\n  valueTru: Tru,\r\n  warehouse: unknown,\r\n): Map<unknown, unknown> {\r\n  const keysTdu = ParsedTdu.parseSync(\r\n    tdu.data,\r\n    tdu.payloadOffset,\r\n    tdu.payloadOffset + tdu.payloadLength,\r\n    warehouse,\r\n  );\r\n  const valuesTdu = ParsedTdu.parseSync(\r\n    tdu.data,\r\n    keysTdu.payloadOffset + keysTdu.payloadLength,\r\n    tdu.ends,\r\n    warehouse,\r\n  );\r\n\r\n  const keys = typedArrayParser(keysTdu, keyTru, warehouse);\r\n  const values = typedArrayParser(valuesTdu, valueTru, warehouse);\r\n\r\n  const map = new Map<unknown, unknown>();\r\n  for (let i = 0; i < keys.length; i++) map.set(keys[i], values[i]);\r\n  return map;\r\n}\r\n\r\n/** Decode a `TupleN<...>` TDU to a JS array (in element order). */\r\nfunction tupleParser(tdu: ParsedTdu, subTrus: Tru[], warehouse: unknown): unknown[] {\r\n  const results: unknown[] = [];\r\n  let offset = tdu.payloadOffset;\r\n  let length = tdu.payloadLength;\r\n  const ends = offset + length;\r\n\r\n  for (let i = 0; i < subTrus.length; i++) {\r\n    const current = ParsedTdu.parseSync(tdu.data, offset, ends, warehouse);\r\n    if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n    if (current.identifier === TduIdentifier.TypeOfTarget) {\r\n      current.tduClass = TduClass.Typed;\r\n      current.identifier = TduIdentifier.Typed;\r\n      current.metadata = subTrus[i];\r\n      current.index = TduIdentifier.Typed & 0x7;\r\n    }\r\n\r\n    results.push(parseSyncTdu(current, warehouse));\r\n\r\n    if (current.totalLength <= 0)\r\n      throw new Error(\"Error while parsing structured data.\");\r\n    offset += current.totalLength;\r\n    length -= current.totalLength;\r\n  }\r\n\r\n  return results;\r\n}\r\n\r\n/** Decode a `TduIdentifier.TypeDef` (0x81) payload into a {@link TypeDefInfo}. */\r\nexport const typeDefInfoParser: Parser = (tdu, warehouse) => {\r\n  const parsed = parseSync(tdu.data, tdu.payloadOffset, warehouse);\r\n  if (parsed.length !== tdu.payloadLength)\r\n    throw new Error(\"The TypeDef payload contains trailing or incomplete data.\");\r\n  return hydrateTypeDefInfo(fromIndexedMap(TypeDefInfo, parsed.value));\r\n};\r\n\r\n/** Decode a `TduIdentifier.TRU` (0x82) payload into a standalone {@link Tru} value. */\r\nexport const truParser: Parser = (tdu, warehouse) => {\r\n  const parsed = Tru.parseSync(tdu.data, tdu.payloadOffset, warehouse);\r\n  if (parsed.size !== tdu.payloadLength)\r\n    throw new Error(\"The TRU payload contains trailing or incomplete data.\");\r\n  return parsed.value;\r\n};\r\n\r\n/**\r\n * `fromIndexedMap` only assigns already-fully-decoded values generically; the\r\n * member-list fields (`properties`/`functions`/`events`/`constants`, and a\r\n * function's `arguments`) decode as arrays of plain `Map`s (each a nested,\r\n * generically-decoded `IndexedStructure` payload) that must be converted to\r\n * their concrete `*DefInfo` classes by hand at this known call site.\r\n */\r\nfunction hydrateTypeDefInfo(info: TypeDefInfo): TypeDefInfo {\r\n  if (Array.isArray(info.properties))\r\n    info.properties = info.properties.map((m) => fromIndexedMap(PropertyDefInfo, m));\r\n  if (Array.isArray(info.functions))\r\n    info.functions = info.functions.map((m) => hydrateFunctionDefInfo(fromIndexedMap(FunctionDefInfo, m)));\r\n  if (Array.isArray(info.events))\r\n    info.events = info.events.map((m) => fromIndexedMap(EventDefInfo, m));\r\n  if (Array.isArray(info.constants))\r\n    info.constants = info.constants.map((m) => fromIndexedMap(ConstantDefInfo, m));\r\n  return info;\r\n}\r\n\r\nfunction hydrateFunctionDefInfo(fn: FunctionDefInfo): FunctionDefInfo {\r\n  if (Array.isArray(fn.arguments))\r\n    fn.arguments = fn.arguments.map((a) => fromIndexedMap(ArgumentDefInfo, a));\r\n  return fn;\r\n}\r\n\r\n// ---- async parsers ------------------------------------------------------\r\n//\r\n// Async twins of the parsers above, needed only because a `Tru`/`TypeDef`\r\n// value anywhere in a decoded tree (most commonly a `PropertyDefInfo.valueType`\r\n// or `FunctionDefInfo.returnType` inside a `TypeDefInfo`) may reference a\r\n// remote TypeDef that hasn't been fetched yet. Each is a mechanical\r\n// `await`-ified copy of its sync counterpart — matching the C# source, which\r\n// also doesn't share code between its sync and async parser families.\r\n\r\n/** Async twin of {@link parseDynamicArray}. */\r\nasync function parseDynamicArrayAsync(\r\n  tdu: ParsedTdu,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<unknown[]> {\r\n  const list: unknown[] = [];\r\n  let offset = tdu.payloadOffset;\r\n  let length = tdu.payloadLength;\r\n  const ends = offset + length;\r\n  let previous: ParsedTdu | null = null;\r\n\r\n  while (length > 0) {\r\n    const current = await ParsedTdu.parseAsync(\r\n      tdu.data,\r\n      offset,\r\n      ends,\r\n      warehouse,\r\n      remoteResolver,\r\n      requestSequence,\r\n    );\r\n    if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n    if (current.identifier === TduIdentifier.TypeContinuation && previous) {\r\n      current.tduClass = previous.tduClass;\r\n      current.identifier = previous.identifier;\r\n      current.metadata = previous.metadata;\r\n    }\r\n\r\n    list.push(await parseAsyncTdu(current, warehouse, remoteResolver, requestSequence));\r\n\r\n    if (current.totalLength <= 0)\r\n      throw new Error(\"Error while parsing structured data.\");\r\n    offset += current.totalLength;\r\n    length -= current.totalLength;\r\n    previous = current;\r\n  }\r\n\r\n  return list;\r\n}\r\n\r\nexport const listParserAsync: AsyncParser = (t, w, r, s) => parseDynamicArrayAsync(t, w, r, s);\r\nexport const resourceListParserAsync: AsyncParser = (t, w, r, s) => parseDynamicArrayAsync(t, w, r, s);\r\nexport const recordListParserAsync: AsyncParser = (t, w, r, s) => parseDynamicArrayAsync(t, w, r, s);\r\nexport const mapParserAsync: AsyncParser = async (t, w, r, s) => {\r\n  const flat = await parseDynamicArrayAsync(t, w, r, s);\r\n  const map = new Map<unknown, unknown>();\r\n  for (let i = 0; i + 1 < flat.length; i += 2) map.set(flat[i], flat[i + 1]);\r\n  return map;\r\n};\r\nexport const mapListParserAsync: AsyncParser = (t, w, r, s) => parseDynamicArrayAsync(t, w, r, s);\r\nexport const rawDataParserAsync: AsyncParser = async (t, w) => rawDataParser(t, w);\r\nexport const stringParserAsync: AsyncParser = async (t, w) => stringParser(t, w);\r\nexport const resourceLinkParserAsync: AsyncParser = async (t, w) => resourceLinkParser(t, w);\r\n\r\nexport const typedParserAsync: AsyncParser = async (tdu, warehouse, remoteResolver, requestSequence) => {\r\n  const tru = tdu.metadata;\r\n  if (tru instanceof TruComposite) {\r\n    switch (tru.identifier) {\r\n      case TruIdentifier.TypedList:\r\n        return typedArrayParserAsync(tdu, tru.subTypes[0], warehouse, remoteResolver, requestSequence);\r\n      case TruIdentifier.TypedMap:\r\n        return typedMapParserAsync(\r\n          tdu,\r\n          tru.subTypes[0],\r\n          tru.subTypes[1],\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n      case TruIdentifier.Tuple2:\r\n      case TruIdentifier.Tuple3:\r\n      case TruIdentifier.Tuple4:\r\n      case TruIdentifier.Tuple5:\r\n      case TruIdentifier.Tuple6:\r\n      case TruIdentifier.Tuple7:\r\n        return tupleParserAsync(tdu, tru.subTypes, warehouse, remoteResolver, requestSequence);\r\n      default:\r\n        throw new Error(\"Unsupported type for typed parser.\");\r\n    }\r\n  }\r\n  if (tru instanceof TruTypeDef)\r\n    return typedObjectParserAsync(tdu, tru.typeDef, warehouse, remoteResolver, requestSequence);\r\n  throw new Error(\"Unknown TRU.\");\r\n};\r\n\r\nasync function typedObjectParserAsync(\r\n  tdu: ParsedTdu,\r\n  typeDef: ITypeDef,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<unknown> {\r\n  if (typeDef.kind === TypeDefKind.Record)\r\n    return recordParserAsync(tdu, typeDef, warehouse, remoteResolver, requestSequence);\r\n  if (typeDef.kind === TypeDefKind.Enum) return enumParser(tdu, typeDef);\r\n  throw new Error(\"Typed resource parsing is not supported yet.\");\r\n}\r\n\r\nasync function recordParserAsync(\r\n  tdu: ParsedTdu,\r\n  typeDef: ITypeDef,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<object> {\r\n  const values: unknown[] = [];\r\n  let offset = tdu.payloadOffset;\r\n  let length = tdu.payloadLength;\r\n  const ends = offset + length;\r\n  let previous: ParsedTdu | null = null;\r\n\r\n  for (let i = 0; i < typeDef.properties.length; i++) {\r\n    const current = await ParsedTdu.parseAsync(\r\n      tdu.data,\r\n      offset,\r\n      ends,\r\n      warehouse,\r\n      remoteResolver,\r\n      requestSequence,\r\n    );\r\n    if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n    if (current.identifier === TduIdentifier.TypeContinuation && previous) {\r\n      current.tduClass = previous.tduClass;\r\n      current.identifier = previous.identifier;\r\n      current.metadata = previous.metadata;\r\n    } else if (current.identifier === TduIdentifier.TypeOfTarget) {\r\n      current.tduClass = TduClass.Typed;\r\n      current.identifier = TduIdentifier.Typed;\r\n      current.metadata = typeDef.properties[i].valueType ?? null;\r\n      current.index = TduIdentifier.Typed & 0x7;\r\n    }\r\n\r\n    values.push(await parseAsyncTdu(current, warehouse, remoteResolver, requestSequence));\r\n\r\n    if (current.totalLength <= 0)\r\n      throw new Error(\"Error while parsing structured data.\");\r\n    offset += current.totalLength;\r\n    length -= current.totalLength;\r\n    previous = current;\r\n  }\r\n\r\n  const instance = typeDef.createInstance();\r\n  for (let i = 0; i < typeDef.properties.length; i++)\r\n    typeDef.setProperty(instance, typeDef.properties[i].name, values[i]);\r\n  return instance;\r\n}\r\n\r\nasync function typedArrayParserAsync(\r\n  tdu: ParsedTdu,\r\n  element: Tru,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<unknown[]> {\r\n  const start = tdu.payloadOffset;\r\n  const end = start + tdu.payloadLength;\r\n\r\n  switch (element.identifier) {\r\n    case TruIdentifier.Int16:\r\n      return GroupInt16Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.Int32:\r\n      return GroupInt32Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.Int64:\r\n      return GroupInt64Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.UInt16:\r\n      return GroupUInt16Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.UInt32:\r\n      return GroupUInt32Codec.decode(tdu.data, start, end);\r\n    case TruIdentifier.UInt64:\r\n      return GroupUInt64Codec.decode(tdu.data, start, end);\r\n    default: {\r\n      const list: unknown[] = [];\r\n      let offset = start;\r\n      let length = tdu.payloadLength;\r\n      let previous: ParsedTdu | null = null;\r\n\r\n      while (length > 0) {\r\n        const current = await ParsedTdu.parseAsync(\r\n          tdu.data,\r\n          offset,\r\n          end,\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n        if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n        if (current.identifier === TduIdentifier.TypeContinuation && previous) {\r\n          current.tduClass = previous.tduClass;\r\n          current.identifier = previous.identifier;\r\n          current.metadata = previous.metadata;\r\n        } else if (current.identifier === TduIdentifier.TypeOfTarget) {\r\n          current.tduClass = TduClass.Typed;\r\n          current.identifier = TduIdentifier.Typed;\r\n          current.metadata = element;\r\n          current.index = TduIdentifier.Typed & 0x7;\r\n        }\r\n\r\n        list.push(await parseAsyncTdu(current, warehouse, remoteResolver, requestSequence));\r\n\r\n        if (current.totalLength <= 0)\r\n          throw new Error(\"Error while parsing structured data.\");\r\n        offset += current.totalLength;\r\n        length -= current.totalLength;\r\n        previous = current;\r\n      }\r\n      return list;\r\n    }\r\n  }\r\n}\r\n\r\nasync function typedMapParserAsync(\r\n  tdu: ParsedTdu,\r\n  keyTru: Tru,\r\n  valueTru: Tru,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<Map<unknown, unknown>> {\r\n  const keysTdu = await ParsedTdu.parseAsync(\r\n    tdu.data,\r\n    tdu.payloadOffset,\r\n    tdu.payloadOffset + tdu.payloadLength,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  const valuesTdu = await ParsedTdu.parseAsync(\r\n    tdu.data,\r\n    keysTdu.payloadOffset + keysTdu.payloadLength,\r\n    tdu.ends,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n\r\n  const keys = await typedArrayParserAsync(keysTdu, keyTru, warehouse, remoteResolver, requestSequence);\r\n  const values = await typedArrayParserAsync(\r\n    valuesTdu,\r\n    valueTru,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n\r\n  const map = new Map<unknown, unknown>();\r\n  for (let i = 0; i < keys.length; i++) map.set(keys[i], values[i]);\r\n  return map;\r\n}\r\n\r\nasync function tupleParserAsync(\r\n  tdu: ParsedTdu,\r\n  subTrus: Tru[],\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<unknown[]> {\r\n  const results: unknown[] = [];\r\n  let offset = tdu.payloadOffset;\r\n  let length = tdu.payloadLength;\r\n  const ends = offset + length;\r\n\r\n  for (let i = 0; i < subTrus.length; i++) {\r\n    const current = await ParsedTdu.parseAsync(\r\n      tdu.data,\r\n      offset,\r\n      ends,\r\n      warehouse,\r\n      remoteResolver,\r\n      requestSequence,\r\n    );\r\n    if (current.tduClass === TduClass.Invalid) throw new Error(\"Unknown type.\");\r\n\r\n    if (current.identifier === TduIdentifier.TypeOfTarget) {\r\n      current.tduClass = TduClass.Typed;\r\n      current.identifier = TduIdentifier.Typed;\r\n      current.metadata = subTrus[i];\r\n      current.index = TduIdentifier.Typed & 0x7;\r\n    }\r\n\r\n    results.push(await parseAsyncTdu(current, warehouse, remoteResolver, requestSequence));\r\n\r\n    if (current.totalLength <= 0)\r\n      throw new Error(\"Error while parsing structured data.\");\r\n    offset += current.totalLength;\r\n    length -= current.totalLength;\r\n  }\r\n\r\n  return results;\r\n}\r\n\r\n/** Async twin of {@link typeDefInfoParser}. */\r\nexport const typeDefInfoParserAsync: AsyncParser = async (\r\n  tdu,\r\n  warehouse,\r\n  remoteResolver,\r\n  requestSequence,\r\n) => {\r\n  const parsed = await parseAsync(tdu.data, tdu.payloadOffset, warehouse, remoteResolver, requestSequence);\r\n  if (parsed.length !== tdu.payloadLength)\r\n    throw new Error(\"The TypeDef payload contains trailing or incomplete data.\");\r\n  return hydrateTypeDefInfo(fromIndexedMap(TypeDefInfo, parsed.value));\r\n};\r\n\r\n/** Async twin of {@link truParser}. */\r\nexport const truParserAsync: AsyncParser = async (tdu, warehouse, remoteResolver, requestSequence) => {\r\n  const parsed = await Tru.parseAsync(\r\n    tdu.data,\r\n    tdu.payloadOffset,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  if (parsed.size !== tdu.payloadLength)\r\n    throw new Error(\"The TRU payload contains trailing or incomplete data.\");\r\n  return parsed.value;\r\n};\r\n","/**\r\n * Marker base for local, schema-less types whose members are identified by\r\n * byte indexes on the wire (port of C# `IndexedStructure`). Composed as a\r\n * sparse `TypedMap<u8, dynamic>` — `null`/`undefined` members are omitted,\r\n * and unknown indices are silently ignored on decode (version tolerant).\r\n */\r\nexport abstract class IndexedStructure {}\r\n","import \"../internal/metadata.js\";\r\n\r\n/** A discovered `@Index`ed member: its wire index and property name. */\r\nexport interface IndexedMember {\r\n  index: number;\r\n  name: string;\r\n}\r\n\r\nconst INDEXED_MEMBERS = Symbol.for(\"esiur.indexedMembers\");\r\n\r\ntype MetaBag = Record<symbol, unknown>;\r\n\r\n/**\r\n * Marks a class field as a wire member of an {@link IndexedStructure}, keyed\r\n * by a stable byte index 0-255 (port of C#'s `[Index(n)]`). Plain class\r\n * fields are enough here — unlike `@Export`, indexed members need no\r\n * change-notification wrapping, just presence in `context.metadata`.\r\n *\r\n * Subclassing inherits base-class `@Index` fields automatically: the TC39\r\n * decorator-metadata proposal chains `[Symbol.metadata]` through the\r\n * prototype, so e.g. `PropertyDefInfo extends MemberDefInfo` sees\r\n * `MemberDefInfo`'s indexed fields with no extra work.\r\n */\r\nexport function Index(index: number) {\r\n  if (index < 0 || index > 255)\r\n    throw new RangeError(\"A structure index must be between 0 and 255.\");\r\n  return function (_value: unknown, context: ClassMemberDecoratorContext): void {\r\n    if (context.kind !== \"field\" && context.kind !== \"accessor\")\r\n      throw new Error(`@Index cannot be applied to a ${context.kind} ('${String(context.name)}').`);\r\n    const meta = context.metadata as MetaBag;\r\n    const members = ownMembers(meta);\r\n    const name = String(context.name);\r\n    if (members.some((m) => m.index === index))\r\n      throw new Error(`Structure index ${index} is already used on this type.`);\r\n    members.push({ index, name });\r\n  };\r\n}\r\n\r\n/**\r\n * Get (creating if absent) `meta`'s OWN `INDEXED_MEMBERS` array. `meta[KEY]`\r\n * alone isn't enough to detect absence: the TC39 metadata proposal chains a\r\n * subclass's `[Symbol.metadata]` object off its base class's via the\r\n * prototype, so a plain `??=` would read the *inherited* array through that\r\n * chain and then mutate it in place — silently corrupting the base class's\r\n * own member list with every subclass's fields. Seed a fresh own array (a\r\n * copy of whatever was inherited) the first time a subclass is decorated.\r\n */\r\nfunction ownMembers(meta: MetaBag): IndexedMember[] {\r\n  if (!Object.hasOwn(meta, INDEXED_MEMBERS)) {\r\n    const inherited = (meta[INDEXED_MEMBERS] as IndexedMember[] | undefined) ?? [];\r\n    meta[INDEXED_MEMBERS] = inherited.slice();\r\n  }\r\n  return meta[INDEXED_MEMBERS] as IndexedMember[];\r\n}\r\n\r\n/** Read the `@Index`ed members declared (including inherited) on `ctor`. */\r\nexport function getIndexedMembers(ctor: Function): IndexedMember[] {\r\n  const meta = (ctor as { [Symbol.metadata]?: MetaBag })[Symbol.metadata];\r\n  if (!meta) return [];\r\n  return (meta[INDEXED_MEMBERS] as IndexedMember[] | undefined) ?? [];\r\n}\r\n","import { IndexedStructure } from \"./IndexedStructure.js\";\r\nimport { getIndexedMembers } from \"./IndexAttribute.js\";\r\nimport { TypedMap, t } from \"./descriptors.js\";\r\n\r\n/**\r\n * Convert an {@link IndexedStructure} instance to a sparse `TypedMap<u8,\r\n * dynamic>` (port of C# `IndexedStructureCodec.ToMap`). `null`/`undefined`\r\n * members are omitted. Nested `IndexedStructure` values recurse; arrays map\r\n * element-wise. TS enums need no unwrap step (already plain numbers at\r\n * runtime, unlike C# `Enum`).\r\n *\r\n * Deliberately uniform for nested structures too: C#'s compose side uses a\r\n * plain dynamic `Map` (0x46) wire form for *nested* structures but a\r\n * `TypedMap` for the outer one — an artifact of its runtime-type composer\r\n * dispatch, not a protocol requirement. Decode only requires the result be\r\n * `IDictionary`-compatible, and both wire forms satisfy that, so using\r\n * `TypedMap` everywhere here is safe and lets the existing\r\n * `typedMapComposer`/`typedMapParser` machinery handle all recursion with no\r\n * new composer/parser code.\r\n */\r\nexport function toIndexedMap(value: IndexedStructure): TypedMap {\r\n  const members = getIndexedMembers(value.constructor as Function)\r\n    .slice()\r\n    .sort((a, b) => a.index - b.index);\r\n  const record = value as unknown as Record<string, unknown>;\r\n  const entries: Array<[number, unknown]> = [];\r\n  for (const m of members) {\r\n    const raw = record[m.name];\r\n    if (raw === null || raw === undefined) continue;\r\n    entries.push([m.index, prepareValue(raw)]);\r\n  }\r\n  return new TypedMap(t.u8, t.dynamic, entries);\r\n}\r\n\r\nfunction prepareValue(v: unknown): unknown {\r\n  if (v instanceof IndexedStructure) return toIndexedMap(v);\r\n  if (Array.isArray(v)) return v.map(prepareValue);\r\n  return v;\r\n}\r\n\r\n/**\r\n * Populate a new `T` from a decoded indexed-map payload (port of C#\r\n * `IndexedStructureCodec.FromMap`). Version tolerant: indices absent from the\r\n * map leave the constructed instance's default; indices in the map with no\r\n * matching `@Index` member are ignored.\r\n *\r\n * Only scalar/already-fully-decoded values are assigned generically here —\r\n * there is no runtime field-type reflection in TS to drive automatic nested\r\n * structure/list conversion the way C# reflection does, so callers that need\r\n * a field's value re-interpreted as a specific nested `IndexedStructure`\r\n * subclass (e.g. `TypeDefInfo.properties: PropertyDefInfo[]`) must convert it\r\n * themselves after this call — mirroring how C#'s own\r\n * `RemoteTypeDef.ApplyInfo`/`ToProperty`/etc. hand-write their nested\r\n * conversions rather than trusting blind reflection there either.\r\n */\r\nexport function fromIndexedMap<T extends IndexedStructure>(\r\n  ctor: new () => T,\r\n  value: unknown,\r\n): T {\r\n  if (!(value instanceof Map))\r\n    throw new Error(\"An indexed structure payload must decode to a Map.\");\r\n  const instance = new ctor();\r\n  const members = getIndexedMembers(ctor);\r\n  const record = instance as unknown as Record<string, unknown>;\r\n  for (const m of members) {\r\n    if (value.has(m.index)) record[m.name] = value.get(m.index);\r\n  }\r\n  return instance;\r\n}\r\n","import { IndexedStructure } from \"../IndexedStructure.js\";\r\nimport { Index } from \"../IndexAttribute.js\";\r\nimport { TypeDefKind } from \"./ITypeDef.js\";\r\nimport type { PropertyDefInfo } from \"./PropertyDefInfo.js\";\r\nimport type { FunctionDefInfo } from \"./FunctionDefInfo.js\";\r\nimport type { EventDefInfo } from \"./EventDefInfo.js\";\r\nimport type { ConstantDefInfo } from \"./ConstantDefInfo.js\";\r\n\r\n/**\r\n * Wire-format shape of a type definition (port of C# `TypeDefInfo`), the\r\n * payload carried by a `TduIdentifier.TypeDef` (0x81) TDU. Decode-only in\r\n * this port: the compose-direction helpers (`FromTypeDef`/`CopyMember`/etc.\r\n * in C#) only matter for hosting local resources and answering `TypeDefById`\r\n * as a server, which is out of today's client-focused scope.\r\n */\r\nexport class TypeDefInfo extends IndexedStructure {\r\n  @Index(0x00) version = 0;\r\n  @Index(0x01) id = 0;\r\n  @Index(0x02) name = \"\";\r\n  @Index(0x03) namespace: string | undefined;\r\n  @Index(0x04) kind: TypeDefKind = TypeDefKind.Resource;\r\n  @Index(0x05) parent: number | undefined;\r\n  @Index(0x06) properties: PropertyDefInfo[] | undefined;\r\n  @Index(0x07) functions: FunctionDefInfo[] | undefined;\r\n  @Index(0x08) events: EventDefInfo[] | undefined;\r\n  @Index(0x09) constants: ConstantDefInfo[] | undefined;\r\n\r\n  @Index(0x20) usage: string | undefined;\r\n  @Index(0x21) description: string | undefined;\r\n  @Index(0x22) example: unknown;\r\n  @Index(0x23) category: string | undefined;\r\n  @Index(0x24) since: string | undefined;\r\n  @Index(0x25) annotations: Map<string, string> | undefined;\r\n}\r\n","import { IndexedStructure } from \"../IndexedStructure.js\";\r\nimport { Index } from \"../IndexAttribute.js\";\r\n\r\n/**\r\n * Base wire-format shape shared by every member kind (property/function/\r\n * event/constant/argument), port of C# `MemberDefInfo`. Carries the shared\r\n * identity fields plus the new documentation/semantics metadata surface\r\n * (`usage`/`description`/`examples`/`tags`/etc.) introduced alongside\r\n * `IndexedStructure`.\r\n */\r\nexport class MemberDefInfo extends IndexedStructure {\r\n  @Index(0x00) index = 0;\r\n  @Index(0x01) name = \"\";\r\n  /** Raw flags byte; interpret via the subclass's own `*DefFlags` enum. */\r\n  @Index(0x02) flags = 0;\r\n\r\n  @Index(0x20) description: string | undefined;\r\n  @Index(0x21) usage: string | undefined;\r\n  @Index(0x22) examples: unknown[] | undefined;\r\n  @Index(0x23) tags: string[] | undefined;\r\n  @Index(0x24) unit: string | undefined;\r\n  @Index(0x25) minimum: unknown;\r\n  @Index(0x26) maximum: unknown;\r\n  @Index(0x27) allowedValues: unknown[] | undefined;\r\n  @Index(0x28) pattern: string | undefined;\r\n  @Index(0x29) format: string | undefined;\r\n  @Index(0x2a) preconditions: string[] | undefined;\r\n  @Index(0x2b) postconditions: string[] | undefined;\r\n  /** {@link import(\"./OperationEffects.js\").OperationEffects} bitmask. */\r\n  @Index(0x2c) effects = 0;\r\n  @Index(0x2d) warnings: string[] | undefined;\r\n  @Index(0x2e) relatedMembers: number[] | undefined;\r\n  @Index(0x2f) deprecationMessage: string | undefined;\r\n  @Index(0x30) annotations: Map<string, string> | undefined;\r\n}\r\n","import { Index } from \"../IndexAttribute.js\";\r\nimport type { Tru } from \"../Tru.js\";\r\nimport { MemberDefInfo } from \"./MemberDefInfo.js\";\r\nimport { OrderingControl } from \"../OrderingControl.js\";\r\n\r\n/** Wire-format shape of a property definition (port of C# `PropertyDefInfo`). */\r\nexport class PropertyDefInfo extends MemberDefInfo {\r\n  @Index(0x03) valueType: Tru | undefined;\r\n  @Index(0x04) orderingControl: OrderingControl = OrderingControl.Strict;\r\n  @Index(0x05) historyControl = 0;\r\n  @Index(0x06) defaultValue: unknown;\r\n}\r\n","import { Index } from \"../IndexAttribute.js\";\r\nimport type { Tru } from \"../Tru.js\";\r\nimport { MemberDefInfo } from \"./MemberDefInfo.js\";\r\nimport { StreamMode } from \"./StreamMode.js\";\r\nimport type { ArgumentDefInfo } from \"./ArgumentDefInfo.js\";\r\n\r\n/** Wire-format shape of a function definition (port of C# `FunctionDefInfo`). */\r\nexport class FunctionDefInfo extends MemberDefInfo {\r\n  @Index(0x03) arguments: ArgumentDefInfo[] | undefined;\r\n  @Index(0x04) returnType: Tru | undefined;\r\n  @Index(0x05) streamMode: StreamMode = StreamMode.None;\r\n}\r\n","import { Index } from \"../IndexAttribute.js\";\r\nimport type { Tru } from \"../Tru.js\";\r\nimport { MemberDefInfo } from \"./MemberDefInfo.js\";\r\nimport { OrderingControl } from \"../OrderingControl.js\";\r\n\r\n/** Wire-format shape of an event definition (port of C# `EventDefInfo`). */\r\nexport class EventDefInfo extends MemberDefInfo {\r\n  @Index(0x03) argumentType: Tru | undefined;\r\n  @Index(0x04) argumentName: string | undefined;\r\n  @Index(0x05) orderingControl: OrderingControl = OrderingControl.Strict;\r\n  @Index(0x06) historyControl = 0;\r\n}\r\n","import { Index } from \"../IndexAttribute.js\";\r\nimport type { Tru } from \"../Tru.js\";\r\nimport { MemberDefInfo } from \"./MemberDefInfo.js\";\r\n\r\n/** Wire-format shape of a constant definition (port of C# `ConstantDefInfo`). */\r\nexport class ConstantDefInfo extends MemberDefInfo {\r\n  @Index(0x03) valueType: Tru | undefined;\r\n  @Index(0x04) value: unknown;\r\n}\r\n","import { Index } from \"../IndexAttribute.js\";\r\nimport type { Tru } from \"../Tru.js\";\r\nimport { MemberDefInfo } from \"./MemberDefInfo.js\";\r\n\r\n/**\r\n * Wire-format shape of a function argument (port of C# `ArgumentDefInfo`).\r\n * The argument's name comes from the inherited `MemberDefInfo.name` field.\r\n */\r\nexport class ArgumentDefInfo extends MemberDefInfo {\r\n  @Index(0x03) valueType: Tru | undefined;\r\n  @Index(0x04) defaultValue: unknown;\r\n}\r\n","/**\r\n * Generic group-varint codec core (port of the shared structure of C#'s\r\n * `Gvwie.GroupIntNNCodec` family). One header byte frames a run:\r\n * `1 | countField[countBits] | (width-1)[widthBits]`, where `countBits +\r\n * widthBits === 7`. Values ≤ 7 bits take a single literal byte. Signed widths\r\n * zig-zag; unsigned widths store the value directly. Everything is computed in\r\n * `bigint` so a single implementation serves the 16/32/64-bit variants.\r\n */\r\nexport interface GroupConfig {\r\n  /** Bits in the header's count field (16→6, 32→5, 64→4). */\r\n  countBits: number;\r\n  /** Maximum payload width in bytes (16→2, 32→4, 64→8). */\r\n  maxWidth: number;\r\n  /** Total value width in bits (16/32/64) — used for the zig-zag mask. */\r\n  bits: number;\r\n  /** Whether values are zig-zag encoded (signed) or stored directly. */\r\n  signed: boolean;\r\n}\r\n\r\nfunction build(cfg: GroupConfig) {\r\n  const widthBits = 7 - cfg.countBits;\r\n  const countFieldMax = (1 << cfg.countBits) - 1;\r\n  const maxShortField = countFieldMax - 4; // extended uses the top 4 field values\r\n  const shortMaxCount = maxShortField + 1;\r\n  const widthMask = (1 << widthBits) - 1;\r\n  const valueMask = (1n << BigInt(cfg.bits)) - 1n;\r\n\r\n  const toZ = cfg.signed\r\n    ? (v: bigint): bigint => ((v << 1n) ^ (v >> BigInt(cfg.bits - 1))) & valueMask\r\n    : (v: bigint): bigint => v & valueMask;\r\n  const fromZ = cfg.signed\r\n    ? (u: bigint): bigint => (u >> 1n) ^ -(u & 1n)\r\n    : (u: bigint): bigint => u;\r\n\r\n  const widthOf = (z: bigint): number => {\r\n    let w = 0;\r\n    let t = z;\r\n    while (t > 0n) {\r\n      w++;\r\n      t >>= 8n;\r\n    }\r\n    return Math.min(Math.max(w, 1), cfg.maxWidth);\r\n  };\r\n\r\n  const lolOf = (extra: number): number => {\r\n    if (extra <= 0xff) return 1;\r\n    if (extra <= 0xffff) return 2;\r\n    if (extra <= 0xffffff) return 3;\r\n    return 4;\r\n  };\r\n\r\n  const writeLE = (dst: number[], value: bigint, width: number): void => {\r\n    for (let i = 0; i < width; i++) dst.push(Number((value >> BigInt(8 * i)) & 0xffn));\r\n  };\r\n\r\n  const readLE = (src: Uint8Array, pos: { i: number }, width: number): bigint => {\r\n    if (pos.i + width > src.length)\r\n      throw new RangeError(\"Buffer underflow while reading group payload.\");\r\n    let v = 0n;\r\n    for (let i = 0; i < width; i++) v |= BigInt(src[pos.i++]) << BigInt(8 * i);\r\n    return v;\r\n  };\r\n\r\n  function encode(values: bigint[]): Uint8Array {\r\n    const dst: number[] = [];\r\n    let i = 0;\r\n\r\n    while (i < values.length) {\r\n      const zz = toZ(values[i]);\r\n      if (zz <= 0x7fn) {\r\n        dst.push(Number(zz));\r\n        i++;\r\n        continue;\r\n      }\r\n\r\n      const start = i;\r\n      const width = widthOf(zz);\r\n      let count = 1;\r\n      while (i + count < values.length) {\r\n        const z2 = toZ(values[i + count]);\r\n        if (z2 <= 0x7fn) break;\r\n        if (widthOf(z2) !== width) break;\r\n        count++;\r\n      }\r\n\r\n      if (count <= shortMaxCount) {\r\n        dst.push((0x80 | ((count - 1) << widthBits) | ((width - 1) & widthMask)) & 0xff);\r\n      } else {\r\n        const extra = count - (shortMaxCount + 1);\r\n        const lol = lolOf(extra);\r\n        const groupBits = maxShortField + lol;\r\n        dst.push((0x80 | (groupBits << widthBits) | ((width - 1) & widthMask)) & 0xff);\r\n        writeLE(dst, BigInt(extra), lol);\r\n      }\r\n\r\n      for (let k = 0; k < count; k++) writeLE(dst, toZ(values[start + k]), width);\r\n      i += count;\r\n    }\r\n\r\n    return Uint8Array.from(dst);\r\n  }\r\n\r\n  function decode(src: Uint8Array, start = 0, end = src.length): bigint[] {\r\n    const result: bigint[] = [];\r\n    const pos = { i: start };\r\n\r\n    while (pos.i < end) {\r\n      const h = src[pos.i++];\r\n      if ((h & 0x80) === 0) {\r\n        result.push(fromZ(BigInt(h & 0x7f)));\r\n        continue;\r\n      }\r\n\r\n      const countField = (h >> widthBits) & countFieldMax;\r\n      const width = (h & widthMask) + 1;\r\n\r\n      let count: number;\r\n      if (countField <= maxShortField) {\r\n        count = countField + 1;\r\n      } else {\r\n        const lol = countField - maxShortField;\r\n        const extra = Number(readLE(src, pos, lol));\r\n        count = shortMaxCount + 1 + extra;\r\n      }\r\n\r\n      for (let j = 0; j < count; j++) result.push(fromZ(readLE(src, pos, width)));\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n  return { encode, decode };\r\n}\r\n\r\n/** A group codec over JS `number` arrays (16/32-bit widths). */\r\nexport function makeNumberCodec(cfg: GroupConfig) {\r\n  const core = build(cfg);\r\n  return {\r\n    encode: (values: ArrayLike<number>): Uint8Array =>\r\n      core.encode(Array.from(values, (v) => BigInt(v))),\r\n    decode: (src: Uint8Array, start?: number, end?: number): number[] =>\r\n      core.decode(src, start, end).map((v) => Number(v)),\r\n  };\r\n}\r\n\r\n/** A group codec over JS `bigint` arrays (64-bit widths). */\r\nexport function makeBigIntCodec(cfg: GroupConfig) {\r\n  const core = build(cfg);\r\n  return {\r\n    encode: (values: ArrayLike<bigint>): Uint8Array => core.encode(Array.from(values)),\r\n    decode: (src: Uint8Array, start?: number, end?: number): bigint[] =>\r\n      core.decode(src, start, end),\r\n  };\r\n}\r\n","import { makeNumberCodec } from \"./groupCodec.js\";\r\n\r\n/** Group-varint zig-zag codec for `Int16` arrays (port of `GroupInt16Codec`). */\r\nexport const GroupInt16Codec = makeNumberCodec({\r\n  countBits: 6,\r\n  maxWidth: 2,\r\n  bits: 16,\r\n  signed: true,\r\n});\r\n","import { makeNumberCodec } from \"./groupCodec.js\";\r\n\r\n/** Group-varint zig-zag codec for `Int32` arrays (port of `GroupInt32Codec`). */\r\nexport const GroupInt32Codec = makeNumberCodec({\r\n  countBits: 5,\r\n  maxWidth: 4,\r\n  bits: 32,\r\n  signed: true,\r\n});\r\n","import { makeBigIntCodec } from \"./groupCodec.js\";\r\n\r\n/** Group-varint zig-zag codec for `Int64` arrays (port of `GroupInt64Codec`). */\r\nexport const GroupInt64Codec = makeBigIntCodec({\r\n  countBits: 4,\r\n  maxWidth: 8,\r\n  bits: 64,\r\n  signed: true,\r\n});\r\n","import { makeNumberCodec } from \"./groupCodec.js\";\r\n\r\n/** Group-varint codec for `UInt16` arrays (port of `GroupUInt16Codec`). */\r\nexport const GroupUInt16Codec = makeNumberCodec({\r\n  countBits: 6,\r\n  maxWidth: 2,\r\n  bits: 16,\r\n  signed: false,\r\n});\r\n","import { makeNumberCodec } from \"./groupCodec.js\";\r\n\r\n/** Group-varint codec for `UInt32` arrays (port of `GroupUInt32Codec`). */\r\nexport const GroupUInt32Codec = makeNumberCodec({\r\n  countBits: 5,\r\n  maxWidth: 4,\r\n  bits: 32,\r\n  signed: false,\r\n});\r\n","import { makeBigIntCodec } from \"./groupCodec.js\";\r\n\r\n/** Group-varint codec for `UInt64` arrays (port of `GroupUInt64Codec`). */\r\nexport const GroupUInt64Codec = makeBigIntCodec({\r\n  countBits: 4,\r\n  maxWidth: 8,\r\n  bits: 64,\r\n  signed: false,\r\n});\r\n","import { Tdu } from \"./Tdu.js\";\r\nimport { TduIdentifier } from \"./TduIdentifier.js\";\r\nimport { Decimal128 } from \"./Decimal128.js\";\r\nimport { Uuid } from \"./Uuid.js\";\r\nimport * as DC from \"./DC.js\";\r\nimport { composeInternal } from \"./Codec.js\";\r\nimport { IndexedStructure } from \"./IndexedStructure.js\";\r\nimport { toIndexedMap } from \"./IndexedStructureCodec.js\";\r\nimport type { Tru } from \"./Tru.js\";\r\n\r\n/**\r\n * Primitive value composers (port of the primitive parts of C#\r\n * `DataSerializer`). Each returns a {@link Tdu}. The integer/float composers\r\n * narrow to the smallest wire representation that preserves the value, matching\r\n * the C# implementation exactly. Typed/collection composers land with the type\r\n * registry in the Phase 2 continuation.\r\n */\r\n\r\nconst SBYTE_MIN = -128, SBYTE_MAX = 127;\r\nconst SHORT_MIN = -32768, SHORT_MAX = 32767;\r\nconst INT_MIN = -2147483648, INT_MAX = 2147483647;\r\nconst BYTE_MAX = 255, USHORT_MAX = 65535, UINT_MAX = 4294967295;\r\n\r\nconst I64_MIN = -(2n ** 63n), I64_MAX = 2n ** 63n - 1n;\r\nconst U64_MAX = 2n ** 64n - 1n;\r\n\r\nfunction fixed(id: TduIdentifier, data: Uint8Array): Tdu {\r\n  return new Tdu(id, data, data.length);\r\n}\r\n\r\nexport function boolComposer(value: boolean): Tdu {\r\n  return new Tdu(value ? TduIdentifier.True : TduIdentifier.False, null, 0);\r\n}\r\n\r\nexport function notModifiedComposer(): Tdu {\r\n  return new Tdu(TduIdentifier.NotModified, null, 0);\r\n}\r\n\r\nexport function uint8Composer(value: number): Tdu {\r\n  return fixed(TduIdentifier.UInt8, Uint8Array.of(value & 0xff));\r\n}\r\n\r\nexport function int8Composer(value: number): Tdu {\r\n  return fixed(TduIdentifier.Int8, Uint8Array.of(value & 0xff));\r\n}\r\n\r\nexport function char16Composer(value: number): Tdu {\r\n  return fixed(TduIdentifier.Char16, DC.uint16ToBytes(value & 0xffff));\r\n}\r\n\r\nexport function int16Composer(value: number): Tdu {\r\n  if (value >= SBYTE_MIN && value <= SBYTE_MAX)\r\n    return fixed(TduIdentifier.Int8, Uint8Array.of(value & 0xff));\r\n  return fixed(TduIdentifier.Int16, DC.int16ToBytes(value));\r\n}\r\n\r\nexport function uint16Composer(value: number): Tdu {\r\n  if (value <= BYTE_MAX) return fixed(TduIdentifier.UInt8, Uint8Array.of(value & 0xff));\r\n  return fixed(TduIdentifier.UInt16, DC.uint16ToBytes(value));\r\n}\r\n\r\nexport function int32Composer(value: number): Tdu {\r\n  if (value >= SBYTE_MIN && value <= SBYTE_MAX)\r\n    return fixed(TduIdentifier.Int8, Uint8Array.of(value & 0xff));\r\n  if (value >= SHORT_MIN && value <= SHORT_MAX)\r\n    return fixed(TduIdentifier.Int16, DC.int16ToBytes(value));\r\n  return fixed(TduIdentifier.Int32, DC.int32ToBytes(value));\r\n}\r\n\r\nexport function uint32Composer(value: number): Tdu {\r\n  if (value <= BYTE_MAX) return fixed(TduIdentifier.UInt8, Uint8Array.of(value & 0xff));\r\n  if (value <= USHORT_MAX) return fixed(TduIdentifier.UInt16, DC.uint16ToBytes(value));\r\n  return fixed(TduIdentifier.UInt32, DC.uint32ToBytes(value));\r\n}\r\n\r\nexport function int64Composer(value: bigint): Tdu {\r\n  if (value >= BigInt(SBYTE_MIN) && value <= BigInt(SBYTE_MAX))\r\n    return fixed(TduIdentifier.Int8, Uint8Array.of(Number(value) & 0xff));\r\n  if (value >= BigInt(SHORT_MIN) && value <= BigInt(SHORT_MAX))\r\n    return fixed(TduIdentifier.Int16, DC.int16ToBytes(Number(value)));\r\n  if (value >= BigInt(INT_MIN) && value <= BigInt(INT_MAX))\r\n    return fixed(TduIdentifier.Int32, DC.int32ToBytes(Number(value)));\r\n  if (value < I64_MIN || value > I64_MAX)\r\n    throw new RangeError(\"value exceeds Int64 range; use Int128\");\r\n  return fixed(TduIdentifier.Int64, DC.int64ToBytes(value));\r\n}\r\n\r\nexport function uint64Composer(value: bigint): Tdu {\r\n  if (value <= BigInt(BYTE_MAX)) return fixed(TduIdentifier.UInt8, Uint8Array.of(Number(value) & 0xff));\r\n  if (value <= BigInt(USHORT_MAX)) return fixed(TduIdentifier.UInt16, DC.uint16ToBytes(Number(value)));\r\n  if (value <= BigInt(UINT_MAX)) return fixed(TduIdentifier.UInt32, DC.uint32ToBytes(Number(value)));\r\n  if (value < 0n || value > U64_MAX)\r\n    throw new RangeError(\"value exceeds UInt64 range; use UInt128\");\r\n  return fixed(TduIdentifier.UInt64, DC.uint64ToBytes(value));\r\n}\r\n\r\nexport function float32Composer(value: number): Tdu {\r\n  if (Number.isNaN(value) || !Number.isFinite(value))\r\n    return new Tdu(TduIdentifier.Infinity, null, 0);\r\n  if (value === Math.trunc(value)) {\r\n    if (value >= SBYTE_MIN && value <= SBYTE_MAX)\r\n      return fixed(TduIdentifier.Int8, Uint8Array.of(value & 0xff));\r\n    if (value >= SHORT_MIN && value <= SHORT_MAX)\r\n      return fixed(TduIdentifier.Int16, DC.int16ToBytes(value));\r\n  }\r\n  return fixed(TduIdentifier.Float32, DC.float32ToBytes(value));\r\n}\r\n\r\nexport function float64Composer(value: number): Tdu {\r\n  if (Number.isNaN(value) || !Number.isFinite(value))\r\n    return new Tdu(TduIdentifier.Infinity, null, 0);\r\n\r\n  if (value === Math.trunc(value)) {\r\n    if (value >= SBYTE_MIN && value <= SBYTE_MAX)\r\n      return fixed(TduIdentifier.Int8, Uint8Array.of(value & 0xff));\r\n    if (value >= SHORT_MIN && value <= SHORT_MAX)\r\n      return fixed(TduIdentifier.Int16, DC.int16ToBytes(value));\r\n    if (value >= INT_MIN && value <= INT_MAX)\r\n      return fixed(TduIdentifier.Int32, DC.int32ToBytes(value));\r\n    // integral but wider than int32: fall through to float encoding\r\n  }\r\n\r\n  if (Math.fround(value) === value)\r\n    return fixed(TduIdentifier.Float32, DC.float32ToBytes(value));\r\n\r\n  return fixed(TduIdentifier.Float64, DC.float64ToBytes(value));\r\n}\r\n\r\nexport function dateTimeComposer(value: Date): Tdu {\r\n  return fixed(TduIdentifier.DateTime, DC.dateTimeToBytes(value));\r\n}\r\n\r\nexport function stringComposer(value: string): Tdu {\r\n  const b = DC.stringToBytes(value);\r\n  return new Tdu(TduIdentifier.String, b, b.length);\r\n}\r\n\r\nexport function uuidComposer(value: Uuid): Tdu {\r\n  return fixed(TduIdentifier.UUID, value.data);\r\n}\r\n\r\nexport function rawDataComposer(value: Uint8Array): Tdu {\r\n  return new Tdu(TduIdentifier.RawData, value, value.length);\r\n}\r\n\r\n/** Compose an {@link IndexedStructure} as a sparse `TypedMap<u8, dynamic>` (`Typed`, 0x80). */\r\nexport function structureComposer(\r\n  value: IndexedStructure | null,\r\n  warehouse: unknown,\r\n  connection: unknown,\r\n): Tdu {\r\n  if (value == null) return new Tdu(TduIdentifier.Null, null, 0);\r\n  return composeInternal(toIndexedMap(value), warehouse, connection);\r\n}\r\n\r\n/** Compose a standalone {@link Tru} value into its own dedicated, metadata-free slot (0x82). */\r\nexport function truComposer(value: Tru, _warehouse: unknown, connection: unknown): Tdu {\r\n  const data = value.compose(connection);\r\n  return new Tdu(TduIdentifier.TRU, data, data.length, null, connection);\r\n}\r\n\r\n/** Compose a {@link TypeDefInfo}-shaped structure into its dedicated wire slot (0x81). */\r\nexport function typeDefComposer(\r\n  value: IndexedStructure | null,\r\n  warehouse: unknown,\r\n  connection: unknown,\r\n): Tdu {\r\n  const structure = structureComposer(value, warehouse, connection);\r\n  return new Tdu(\r\n    TduIdentifier.TypeDef,\r\n    structure.composed,\r\n    structure.composed.length,\r\n    null,\r\n    connection,\r\n  );\r\n}\r\n\r\n/**\r\n * Decimal composer. Narrows a scale-0 decimal to the smallest signed integer\r\n * that fits (matching C#); otherwise emits the full 16-byte .NET layout.\r\n *\r\n * Note: C# additionally shrinks decimals that are exactly representable as\r\n * float32/float64. We always send full precision for fractional decimals — a\r\n * lossless, interoperable choice — so those specific byte sequences differ while\r\n * the decoded value is identical.\r\n */\r\nexport function decimal128Composer(value: Decimal128): Tdu {\r\n  if (value.scale === 0) {\r\n    const iv = value.negative ? -value.mantissa : value.mantissa;\r\n    if (iv >= BigInt(SBYTE_MIN) && iv <= BigInt(SBYTE_MAX))\r\n      return fixed(TduIdentifier.Int8, Uint8Array.of(Number(iv) & 0xff));\r\n    if (iv >= BigInt(SHORT_MIN) && iv <= BigInt(SHORT_MAX))\r\n      return fixed(TduIdentifier.Int16, DC.int16ToBytes(Number(iv)));\r\n    if (iv >= BigInt(INT_MIN) && iv <= BigInt(INT_MAX))\r\n      return fixed(TduIdentifier.Int32, DC.int32ToBytes(Number(iv)));\r\n    if (iv >= I64_MIN && iv <= I64_MAX)\r\n      return fixed(TduIdentifier.Int64, DC.int64ToBytes(iv));\r\n  }\r\n  return fixed(TduIdentifier.Decimal128, value.toBytes());\r\n}\r\n","/** Lifecycle operations dispatched to a resource via `handle` (port of C# `ResourceOperation`). */\r\nexport enum ResourceOperation {\r\n  Open = 0,\r\n  Initialize = 1,\r\n  Configure = 2,\r\n  Close = 3,\r\n  Terminate = 4,\r\n  SystemReady = 5,\r\n  SystemReloading = 6,\r\n  SystemReloaded = 7,\r\n  SystemTerminating = 8,\r\n  /** Second termination phase; intentionally shares dotnet's `SystemTerminating` value. */\r\n  // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\r\n  SystemTerminated = 8,\r\n  Save = 9,\r\n  Load = 10,\r\n  Pause = 11,\r\n  Resume = 12,\r\n}\r\n","import type { Tru } from \"../data/Tru.js\";\r\nimport { StreamMode } from \"../data/types/StreamMode.js\";\r\n\r\n/**\r\n * Lightweight TypeDef describing a resource's exported members, built from\r\n * decorator metadata instead of reflection.\r\n */\r\nexport enum MemberType {\r\n  Function = 0,\r\n  Property = 1,\r\n  Event = 2,\r\n}\r\n\r\nexport class ArgumentTemplate {\r\n  constructor(\r\n    public name: string,\r\n    public type: Tru | undefined,\r\n    public optional = false,\r\n    public annotations?: Map<string, string>,\r\n  ) {}\r\n}\r\n\r\nexport class PropertyTemplate {\r\n  readonly memberType = MemberType.Property;\r\n  /** Named Warehouse rate policy applied by `@RateControl(name)`. */\r\n  ratePolicyName?: string;\r\n  constructor(\r\n    public name: string,\r\n    public index: number,\r\n    public valueType: Tru | undefined,\r\n    public readOnly = false,\r\n    public annotations?: Map<string, string>,\r\n  ) {}\r\n}\r\n\r\nexport class FunctionTemplate {\r\n  readonly memberType = MemberType.Function;\r\n  /** Named Warehouse rate policy applied by `@RateControl(name)`. */\r\n  ratePolicyName?: string;\r\n  constructor(\r\n    public name: string,\r\n    public index: number,\r\n    public returnType: Tru | undefined,\r\n    public args: ArgumentTemplate[] = [],\r\n    public isStatic = false,\r\n    public annotations?: Map<string, string>,\r\n    /** `None` for an ordinary call; `Push`/`Pull` for a streamed one (see `@Export`'s `streamMode` option). */\r\n    public streamMode: StreamMode = StreamMode.None,\r\n    /** Whether an in-flight stream from this function can be halted/resumed. Meaningless when `streamMode` is `None`. */\r\n    public pausable = false,\r\n  ) {}\r\n}\r\n\r\nexport class EventTemplate {\r\n  readonly memberType = MemberType.Event;\r\n  constructor(\r\n    public name: string,\r\n    public index: number,\r\n    public argType: Tru | undefined,\r\n    public annotations?: Map<string, string>,\r\n    // Matches dotnet: an event requires an explicit Subscribe by default;\r\n    // `@AutoDelivered()` (port of C#'s `[AutoDelivery]`) opts out of that.\r\n    public subscribable = true,\r\n  ) {}\r\n}\r\n\r\nexport type MemberTemplate = PropertyTemplate | FunctionTemplate | EventTemplate;\r\n\r\n/** Describes the exported surface of a resource type. */\r\nexport class TypeDef {\r\n  constructor(\r\n    public className: string,\r\n    public members: MemberTemplate[],\r\n    public annotations?: Map<string, string>,\r\n  ) {}\r\n\r\n  get properties(): PropertyTemplate[] {\r\n    return this.members.filter((m): m is PropertyTemplate => m.memberType === MemberType.Property);\r\n  }\r\n  get functions(): FunctionTemplate[] {\r\n    return this.members.filter((m): m is FunctionTemplate => m.memberType === MemberType.Function);\r\n  }\r\n  get events(): EventTemplate[] {\r\n    return this.members.filter((m): m is EventTemplate => m.memberType === MemberType.Event);\r\n  }\r\n\r\n  getPropertyByName(name: string): PropertyTemplate | undefined {\r\n    return this.properties.find((p) => p.name === name);\r\n  }\r\n  getPropertyByIndex(index: number): PropertyTemplate | undefined {\r\n    return this.properties.find((p) => p.index === index);\r\n  }\r\n  getFunctionByName(name: string): FunctionTemplate | undefined {\r\n    return this.functions.find((f) => f.name === name);\r\n  }\r\n  getFunctionByIndex(index: number): FunctionTemplate | undefined {\r\n    return this.functions.find((f) => f.index === index);\r\n  }\r\n  getEventByName(name: string): EventTemplate | undefined {\r\n    return this.events.find((e) => e.name === name);\r\n  }\r\n  getEventByIndex(index: number): EventTemplate | undefined {\r\n    return this.events.find((e) => e.index === index);\r\n  }\r\n}\r\n\r\n/** @deprecated Use {@link TypeDef}. */\r\nexport { TypeDef as TypeTemplate };\r\n","import \"../internal/metadata.js\";\r\nimport type { Tru } from \"../data/Tru.js\";\r\nimport { StreamMode } from \"../data/types/StreamMode.js\";\r\nimport type { IPermissionsManager } from \"../security/permissions/IPermissionsManager.js\";\r\nimport type { IRateControlManager } from \"../security/management/IRateControlManager.js\";\r\nimport type { IAuditingManager } from \"../security/management/IAuditingManager.js\";\r\nimport {\r\n  ArgumentTemplate,\r\n  EventTemplate,\r\n  FunctionTemplate,\r\n  MemberType,\r\n  PropertyTemplate,\r\n  TypeDef,\r\n  type MemberTemplate,\r\n} from \"./template.js\";\r\n\r\nconst MEMBERS = Symbol.for(\"esiur.members\");\r\nconst TEMPLATE = Symbol.for(\"esiur.template\");\r\nconst RATE_CONTROL_POLICIES = Symbol.for(\"esiur.ratePolicies\");\r\nconst RESOURCE_MANAGER_TYPES = Symbol.for(\"esiur.resourceManagerTypes\");\r\nconst AUTO_DELIVERED_EVENTS = Symbol.for(\"esiur.autoDeliveredEvents\");\r\nconst REMOTE = Symbol.for(\"esiur.remote\");\r\n\r\ninterface PendingMember {\r\n  kind: MemberType;\r\n  name: string;\r\n  type?: Tru;\r\n  args?: Tru[];\r\n  isStatic?: boolean;\r\n  streamMode?: StreamMode;\r\n  pausable?: boolean;\r\n}\r\n\r\n/** Function-only options for {@link Export} — a streaming call's mode and whether it can be halted/resumed mid-flight. */\r\nexport interface ExportFunctionOptions {\r\n  streamMode?: StreamMode;\r\n  pausable?: boolean;\r\n}\r\n\r\ntype MetaBag = Record<symbol, unknown>;\r\n\r\nexport interface RemoteInfo {\r\n  name: string;\r\n  domains: string[];\r\n}\r\n\r\n/**\r\n * Get (creating if absent) `meta`'s OWN array/map at `key`, seeded with a\r\n * copy of whatever was inherited. `meta[key] ??= ...` alone isn't enough: the\r\n * TC39 decorator-metadata proposal chains a subclass's `[Symbol.metadata]`\r\n * off its base class's via the prototype, so a plain `??=` would read the\r\n * *inherited* collection through that chain and mutate it in place —\r\n * silently leaking a subclass's own decorated members/associations into\r\n * (and across siblings of) its base class.\r\n */\r\nfunction ownArray<T>(meta: MetaBag, key: symbol): T[] {\r\n  if (!Object.hasOwn(meta, key)) meta[key] = [...((meta[key] as T[] | undefined) ?? [])];\r\n  return meta[key] as T[];\r\n}\r\n\r\nfunction ownMap<K, V>(meta: MetaBag, key: symbol): Map<K, V> {\r\n  if (!Object.hasOwn(meta, key)) meta[key] = new Map(meta[key] as Map<K, V> | undefined);\r\n  return meta[key] as Map<K, V>;\r\n}\r\n\r\n/**\r\n * Marks a class member as exported over Esiur (port of C#'s `[Export]`).\r\n *\r\n * - On an `accessor` property → a notifying property; the setter reports changes\r\n *   to the resource's {@link Instance}. Pass the wire type, e.g. `@Export(t.i32)`.\r\n * - On a `method` → an exported function. Pass return type and argument types,\r\n *   e.g. `@Export(t.string, [t.string])`. Pass {@link ExportFunctionOptions} as a\r\n *   4th argument to mark it streaming, e.g. `@Export(t.i32, [], { streamMode: StreamMode.Pull })`\r\n *   — the method should then return an `AsyncIterable`/`Iterable` rather than a plain value.\r\n * - On a `field` initialized with {@link event} → an exported event. Pass the\r\n *   event argument type, e.g. `@Export(t.string)`.\r\n */\r\nexport function Export(type?: Tru, args?: Tru[], functionOptions?: ExportFunctionOptions) {\r\n  // Returns `any`: one decorator serves accessor/method/field positions, each of\r\n  // which expects a different result type.\r\n  return function (value: unknown, context: ClassMemberDecoratorContext): any {\r\n    const meta = context.metadata as MetaBag;\r\n    const members = ownArray<PendingMember>(meta, MEMBERS);\r\n    const name = String(context.name);\r\n\r\n    switch (context.kind) {\r\n      case \"accessor\": {\r\n        members.push({ kind: MemberType.Property, name, type });\r\n        const target = value as ClassAccessorDecoratorTarget<unknown, unknown>;\r\n        return {\r\n          get(this: { instance?: { modified(n: string, v: unknown): void } }) {\r\n            return target.get.call(this);\r\n          },\r\n          set(\r\n            this: { instance?: { modified(n: string, v: unknown): void } },\r\n            v: unknown,\r\n          ) {\r\n            target.set.call(this, v);\r\n            this.instance?.modified(name, v);\r\n          },\r\n        } satisfies ClassAccessorDecoratorResult<unknown, unknown>;\r\n      }\r\n      case \"method\":\r\n        // `context.static` is auto-detected from the `static` keyword — no\r\n        // separate decorator option needed, mirroring how dotnet derives\r\n        // `FunctionDef.IsStatic` from reflection rather than an attribute flag.\r\n        members.push({\r\n          kind: MemberType.Function,\r\n          name,\r\n          type,\r\n          args,\r\n          isStatic: context.static,\r\n          streamMode: functionOptions?.streamMode,\r\n          pausable: functionOptions?.pausable,\r\n        });\r\n        return value;\r\n      case \"field\":\r\n        // Expected to hold an EventSource (an exported event).\r\n        members.push({ kind: MemberType.Event, name, type });\r\n        return value;\r\n      default:\r\n        throw new Error(`@Export cannot be applied to a ${context.kind} ('${name}').`);\r\n    }\r\n  };\r\n}\r\n\r\n/**\r\n * Applies a named Warehouse rate policy to an exported function or property\r\n * setter (port of C#'s `[RateControl(policyName)]`). The name is resolved\r\n * against `Warehouse.tryGetRatePolicy` by {@link NamedRateControlManager}\r\n * when the member is invoked/set.\r\n */\r\nexport function RateControl(policyName: string) {\r\n  if (!policyName?.trim()) throw new Error(\"A rate policy name is required.\");\r\n  return function (_value: unknown, context: ClassMemberDecoratorContext): void {\r\n    if (context.kind !== \"accessor\" && context.kind !== \"method\")\r\n      throw new Error(\r\n        `@RateControl cannot be applied to a ${context.kind} ('${String(context.name)}').`,\r\n      );\r\n    const meta = context.metadata as MetaBag;\r\n    ownMap<string, string>(meta, RATE_CONTROL_POLICIES).set(String(context.name), policyName);\r\n  };\r\n}\r\n\r\n/**\r\n * Marks an exported event as delivered to every attached connection\r\n * unconditionally, with no explicit `Subscribe` request needed (port of\r\n * C#'s `[AutoDelivery]`/`EventDefFlags.AutoDelivered`). Without this, an\r\n * exported event requires an explicit Subscribe before it starts flowing\r\n * (`EventDef.Subscribable` is true by default in dotnet) — reach for\r\n * `@AutoDelivered()` for low-frequency events every listener wants anyway;\r\n * leave it off for high-frequency/expensive-to-compute events clients\r\n * should opt into explicitly.\r\n */\r\nexport function AutoDelivered() {\r\n  return function (_value: unknown, context: ClassMemberDecoratorContext): void {\r\n    if (context.kind !== \"field\")\r\n      throw new Error(\r\n        `@AutoDelivered cannot be applied to a ${context.kind} ('${String(context.name)}').`,\r\n      );\r\n    const meta = context.metadata as MetaBag;\r\n    const names = ownArray<string>(meta, AUTO_DELIVERED_EVENTS);\r\n    names.push(String(context.name));\r\n  };\r\n}\r\n\r\n/**\r\n * Associates a registered manager implementation with a resource type (port\r\n * of C#'s `[PermissionsManager<T>]`/`[RateControlManager<T>]`/\r\n * `[AuditingManager<T>]`). The manager type itself must be registered with\r\n * the Warehouse via `registerManager` before the resource is created — this\r\n * decorator only records the association, mirroring dotnet's own\r\n * \"attributes never create instances directly\" design.\r\n */\r\nfunction ResourceManager(managerCtor: Function) {\r\n  return function (_value: Function, context: ClassDecoratorContext): void {\r\n    const meta = context.metadata as MetaBag;\r\n    const types = ownArray<Function>(meta, RESOURCE_MANAGER_TYPES);\r\n    if (!types.includes(managerCtor)) types.push(managerCtor);\r\n  };\r\n}\r\n\r\n/** Associates a registered {@link IPermissionsManager} implementation with a resource class. */\r\nexport function PermissionsManager(managerCtor: new (...args: never[]) => IPermissionsManager) {\r\n  return ResourceManager(managerCtor);\r\n}\r\n\r\n/** Associates a registered {@link IRateControlManager} implementation with a resource class. */\r\nexport function RateControlManager(managerCtor: new (...args: never[]) => IRateControlManager) {\r\n  return ResourceManager(managerCtor);\r\n}\r\n\r\n/** Associates a registered {@link IAuditingManager} implementation with a resource class. */\r\nexport function AuditingManager(managerCtor: new (...args: never[]) => IAuditingManager) {\r\n  return ResourceManager(managerCtor);\r\n}\r\n\r\n/** Read the manager constructor types declared (including inherited) on `ctor`. */\r\nexport function getResourceManagerTypes(ctor: Function): Function[] {\r\n  const meta = (ctor as { [Symbol.metadata]?: MetaBag })[Symbol.metadata];\r\n  if (!meta) return [];\r\n  return (meta[RESOURCE_MANAGER_TYPES] as Function[] | undefined) ?? [];\r\n}\r\n\r\n/** Build (and cache) the decorated {@link TypeDef} surface for a resource class. */\r\nexport function getTypeDef(ctor: Function): TypeDef {\r\n  const meta = (ctor as { [Symbol.metadata]?: MetaBag })[Symbol.metadata];\r\n  if (!meta) return new TypeDef(ctor.name, []);\r\n\r\n  const cached = meta[TEMPLATE] as TypeDef | undefined;\r\n  if (cached && cached.className === ctor.name) return cached;\r\n\r\n  const pending = (meta[MEMBERS] as PendingMember[] | undefined) ?? [];\r\n  const ratePolicies = meta[RATE_CONTROL_POLICIES] as Map<string, string> | undefined;\r\n  const autoDeliveredEvents = new Set((meta[AUTO_DELIVERED_EVENTS] as string[] | undefined) ?? []);\r\n  let propertyIndex = 0;\r\n  let functionIndex = 0;\r\n  let eventIndex = 0;\r\n\r\n  const members: MemberTemplate[] = pending.map((m) => {\r\n    if (m.kind === MemberType.Property) {\r\n      const t = new PropertyTemplate(m.name, propertyIndex++, m.type);\r\n      t.ratePolicyName = ratePolicies?.get(m.name);\r\n      return t;\r\n    }\r\n    if (m.kind === MemberType.Function) {\r\n      const t = new FunctionTemplate(\r\n        m.name,\r\n        functionIndex++,\r\n        m.type,\r\n        (m.args ?? []).map((a, i) => new ArgumentTemplate(`arg${i}`, a)),\r\n        m.isStatic ?? false,\r\n        undefined,\r\n        m.streamMode ?? StreamMode.None,\r\n        m.pausable ?? false,\r\n      );\r\n      t.ratePolicyName = ratePolicies?.get(m.name);\r\n      return t;\r\n    }\r\n    return new EventTemplate(\r\n      m.name,\r\n      eventIndex++,\r\n      m.type,\r\n      undefined,\r\n      !autoDeliveredEvents.has(m.name),\r\n    );\r\n  });\r\n\r\n  const template = new TypeDef(ctor.name, members);\r\n  meta[TEMPLATE] = template;\r\n  return template;\r\n}\r\n\r\n/** @deprecated Use {@link getTypeDef}. */\r\nexport function getTemplate(ctor: Function): TypeDef {\r\n  return getTypeDef(ctor);\r\n}\r\n\r\n/** Marks a generated proxy class as representing a remote TypeDef. */\r\nexport function Remote(name: string, ...domains: string[]) {\r\n  return function (value: Function, _context?: ClassDecoratorContext): void {\r\n    (value as { [REMOTE]?: RemoteInfo })[REMOTE] = { name, domains };\r\n  };\r\n}\r\n\r\n/** Read remote proxy metadata from a class decorator or generator statics. */\r\nexport function getRemoteInfo(ctor: Function): RemoteInfo | undefined {\r\n  const decorated = (ctor as { [REMOTE]?: RemoteInfo })[REMOTE];\r\n  if (decorated) return decorated;\r\n\r\n  const statics = ctor as {\r\n    remote?: RemoteInfo;\r\n    Remote?: RemoteInfo;\r\n    remoteName?: string;\r\n    RemoteName?: string;\r\n    fullName?: string;\r\n    FullName?: string;\r\n    domains?: string[] | string;\r\n    Domains?: string[] | string;\r\n    domain?: string;\r\n    Domain?: string;\r\n  };\r\n\r\n  const structured = statics.remote ?? statics.Remote;\r\n  if (structured?.name) return structured;\r\n\r\n  const name = statics.remoteName ?? statics.RemoteName ?? statics.fullName ?? statics.FullName;\r\n  if (!name) return undefined;\r\n\r\n  const domains = statics.domains ?? statics.Domains ?? statics.domain ?? statics.Domain;\r\n  return { name, domains: normalizeDomains(domains) };\r\n}\r\n\r\nfunction normalizeDomains(value: string[] | string | undefined): string[] {\r\n  if (Array.isArray(value)) return value;\r\n  if (typeof value === \"string\") return [value];\r\n  return [];\r\n}\r\n\r\n/**\r\n * A raised-event channel held by a resource (the TypeScript analogue of C#'s\r\n * `ResourceEventHandler<T>` delegate field). The resource raises it with\r\n * {@link emit}; the {@link Instance} attaches a {@link sink} to forward\r\n * occurrences across the network.\r\n */\r\nexport class EventSource<T = unknown> {\r\n  private readonly listeners: Array<(arg: T) => void> = [];\r\n  /** @internal Forwarder installed by the owning Instance. */\r\n  sink?: (value: T) => void;\r\n\r\n  /** Subscribe a local listener. */\r\n  listen(handler: (arg: T) => void): this {\r\n    this.listeners.push(handler);\r\n    return this;\r\n  }\r\n\r\n  /** Unsubscribe a local listener. */\r\n  unlisten(handler: (arg: T) => void): void {\r\n    const i = this.listeners.indexOf(handler);\r\n    if (i >= 0) this.listeners.splice(i, 1);\r\n  }\r\n\r\n  /** Raise the event: notify local listeners and the network sink. */\r\n  emit(value: T): void {\r\n    for (const l of this.listeners.slice()) l(value);\r\n    this.sink?.(value);\r\n  }\r\n}\r\n\r\n/** Create an {@link EventSource} for an exported event field. */\r\nexport function event<T = unknown>(): EventSource<T> {\r\n  return new EventSource<T>();\r\n}\r\n","import type { TypeDef } from \"./template.js\";\r\n\r\n/**\r\n * A resource whose properties aren't backed by real class fields — e.g. a\r\n * remote {@link EpResource} proxy, whose values live in a wire-driven cache\r\n * indexed by property number rather than named class members. Implementing\r\n * this lets {@link Instance} read/write/serialize it the same way it does a\r\n * locally-defined resource (port of C# `IDynamicResource`).\r\n */\r\nexport interface IDynamicResource {\r\n  /** The TypeDef describing this resource's shape (bypasses constructor-based lookup). */\r\n  readonly resourceDefinition: TypeDef;\r\n  getResourceProperty(index: number): unknown;\r\n  setResourceProperty(index: number, value: unknown): void;\r\n  getResourcePropertyAge(index: number): number;\r\n  getResourcePropertyDate(index: number): Date | undefined;\r\n}\r\n\r\nexport function isDynamicResource(value: unknown): value is IDynamicResource {\r\n  return !!value && typeof (value as IDynamicResource).getResourceProperty === \"function\";\r\n}\r\n","import { EventHandler } from \"../core/EventHandler.js\";\r\nimport type { IResource, IStore } from \"./IResource.js\";\r\nimport type { Warehouse } from \"./Warehouse.js\";\r\nimport type { TypeDef, PropertyTemplate, EventTemplate } from \"./template.js\";\r\nimport { EventSource } from \"./decorators.js\";\r\nimport { isDynamicResource } from \"./IDynamicResource.js\";\r\n\r\n/** Payload for {@link Instance.propertyModified}. */\r\nexport interface PropertyModificationInfo {\r\n  resource: IResource;\r\n  property: PropertyTemplate;\r\n  value: unknown;\r\n  age: number;\r\n}\r\n\r\n/** Payload for {@link Instance.eventOccurred}. */\r\nexport interface EventOccurredInfo {\r\n  resource: IResource;\r\n  event: EventTemplate;\r\n  value: unknown;\r\n}\r\n\r\n/**\r\n * Manages a resource's identity and state (port of C# `Instance`): id, name,\r\n * owning store, TypeDef, per-property age/modification date, and the\r\n * property-change / event notification channels.\r\n */\r\nexport class Instance {\r\n  readonly warehouse: Warehouse;\r\n  readonly id: number;\r\n  name: string;\r\n  readonly definition: TypeDef;\r\n  readonly variables = new Map<string, unknown>();\r\n\r\n  readonly propertyModified = new EventHandler<PropertyModificationInfo>();\r\n  readonly eventOccurred = new EventHandler<EventOccurredInfo>();\r\n  readonly destroyed = new EventHandler<IResource>();\r\n\r\n  isDestroyed = false;\r\n\r\n  private readonly store_: IStore;\r\n  private readonly resourceRef: WeakRef<IResource>;\r\n  private readonly ages: number[] = [];\r\n  private readonly modificationDates: Array<Date | undefined> = [];\r\n  private instanceAge: number;\r\n  private loading = false;\r\n\r\n  constructor(\r\n    warehouse: Warehouse,\r\n    id: number,\r\n    name: string,\r\n    resource: IResource,\r\n    store: IStore,\r\n    age = 0,\r\n  ) {\r\n    this.warehouse = warehouse;\r\n    this.id = id;\r\n    this.name = name ?? \"\";\r\n    this.store_ = store;\r\n    this.resourceRef = new WeakRef(resource);\r\n    this.instanceAge = age;\r\n\r\n    // A dynamic resource (e.g. a remote EpResource proxy relayed into this\r\n    // warehouse) carries its own TypeDef and current property state directly\r\n    // — there's no real constructor-per-remote-type to look TypeDef up from,\r\n    // and unlike a freshly-`new`ed local resource it may already have live\r\n    // data (fetched before being `put()`), so ages/dates must be seeded from\r\n    // it rather than starting at zero.\r\n    const dyn = isDynamicResource(resource) ? resource : undefined;\r\n    this.definition = dyn ? dyn.resourceDefinition : warehouse.getTypeDef(resource.constructor);\r\n\r\n    for (let i = 0; i < this.definition.properties.length; i++) {\r\n      this.ages.push(dyn ? dyn.getResourcePropertyAge(i) : 0);\r\n      this.modificationDates.push(dyn ? dyn.getResourcePropertyDate(i) : undefined);\r\n    }\r\n\r\n    // Forward exported events raised by the resource through this instance.\r\n    for (const evt of this.definition.events) {\r\n      const src = (resource as unknown as Record<string, unknown>)[evt.name];\r\n      if (src instanceof EventSource)\r\n        src.sink = (v: unknown) => this.emitEventByIndex(evt.index, v);\r\n    }\r\n\r\n    resource.addDestroyHandler((sender) => {\r\n      this.isDestroyed = true;\r\n      this.destroyed.emit(sender as IResource);\r\n    });\r\n  }\r\n\r\n  get store(): IStore {\r\n    return this.store_;\r\n  }\r\n\r\n  /** The managed resource, or `undefined` if it has been collected. */\r\n  get resource(): IResource | undefined {\r\n    return this.resourceRef.deref();\r\n  }\r\n\r\n  /** Instance age, incremented on each property modification. */\r\n  get age(): number {\r\n    return this.instanceAge;\r\n  }\r\n\r\n  getAge(index: number): number | undefined {\r\n    return index < this.ages.length ? this.ages[index] : 0;\r\n  }\r\n\r\n  setAge(index: number, value: number): void {\r\n    if (index < this.ages.length) {\r\n      this.ages[index] = value;\r\n      if (value > this.instanceAge) this.instanceAge = value;\r\n    }\r\n  }\r\n\r\n  getModificationDate(index: number): Date | undefined {\r\n    return index < this.modificationDates.length ? this.modificationDates[index] : undefined;\r\n  }\r\n\r\n  setModificationDate(index: number, date: Date | undefined): void {\r\n    if (index < this.modificationDates.length) this.modificationDates[index] = date;\r\n  }\r\n\r\n  /** Notify that an exported property changed (called by the generated setter). */\r\n  modified(name: string, value?: unknown): void {\r\n    if (this.loading) return;\r\n    const pt = this.definition.getPropertyByName(name);\r\n    const res = this.resource;\r\n    if (!pt || !res) return;\r\n    const v =\r\n      arguments.length > 1 ? value : (res as unknown as Record<string, unknown>)[name];\r\n    this.emitModification(pt, v);\r\n  }\r\n\r\n  private emitModification(property: PropertyTemplate, value: unknown): void {\r\n    const res = this.resource;\r\n    if (!res) return;\r\n    this.instanceAge++;\r\n    const now = new Date();\r\n    this.ages[property.index] = this.instanceAge;\r\n    this.modificationDates[property.index] = now;\r\n    this.store_.modify(res, property, value, this.instanceAge, now);\r\n    this.propertyModified.emit({ resource: res, property, value, age: this.instanceAge });\r\n  }\r\n\r\n  /** Raise an exported event by its TypeDef index. */\r\n  emitEventByIndex(index: number, value: unknown): void {\r\n    const res = this.resource;\r\n    if (!res) return;\r\n    const def = this.definition.getEventByIndex(index);\r\n    if (!def) return;\r\n    this.eventOccurred.emit({ resource: res, event: def, value });\r\n  }\r\n\r\n  /** The permanent path link to the resource. */\r\n  get link(): string | undefined {\r\n    const res = this.resource;\r\n    if (!res) return undefined;\r\n    if ((res as IResource) === (this.store_ as IResource)) return this.name; // root store\r\n    return `${this.store_.instance?.name}/${this.store_.link(res)}`;\r\n  }\r\n}\r\n","import { AsyncReply } from \"../core/AsyncReply.js\";\r\nimport type { DestroyedEvent } from \"../core/IDestructible.js\";\r\nimport { ResourceOperation } from \"./ResourceOperation.js\";\r\nimport type { IResource, IResourceContext } from \"./IResource.js\";\r\nimport type { Instance } from \"./Instance.js\";\r\n\r\n/**\r\n * Convenience base class for resources (port of C# `Resource`). Provides the\r\n * {@link Instance} slot, lifecycle `handle`, and destroy notification, so a\r\n * subclass need only declare its `@Export`ed members.\r\n */\r\nexport class Resource implements IResource {\r\n  instance?: Instance;\r\n\r\n  private readonly destroyHandlers: DestroyedEvent[] = [];\r\n\r\n  handle(operation: ResourceOperation, _context?: IResourceContext): AsyncReply<boolean> {\r\n    if (operation === ResourceOperation.Initialize)\r\n      return AsyncReply.fromResult(this.create());\r\n    return AsyncReply.fromResult(true);\r\n  }\r\n\r\n  /** Override to run setup logic on Initialize; return false to fail the put. */\r\n  protected create(): boolean {\r\n    return true;\r\n  }\r\n\r\n  addDestroyHandler(handler: DestroyedEvent): void {\r\n    this.destroyHandlers.push(handler);\r\n  }\r\n\r\n  removeDestroyHandler(handler: DestroyedEvent): void {\r\n    const i = this.destroyHandlers.indexOf(handler);\r\n    if (i >= 0) this.destroyHandlers.splice(i, 1);\r\n  }\r\n\r\n  destroy(): void {\r\n    for (const h of this.destroyHandlers.slice()) h(this);\r\n  }\r\n}\r\n","import {\r\n  TypeDefKind,\r\n  type ITypeDef,\r\n  type TypeDefConstant,\r\n  type TypeDefProperty,\r\n} from \"../data/types/ITypeDef.js\";\r\nimport type { TypeDef } from \"./template.js\";\r\n\r\n/**\r\n * Concrete type definition built from a resource/record class's decorated\r\n * {@link TypeDef} surface. Implements the layer-neutral\r\n * {@link ITypeDef} consumed by the serializer.\r\n */\r\nexport class LocalTypeDef implements ITypeDef {\r\n  private cachedProperties?: TypeDefProperty[];\r\n\r\n  constructor(\r\n    readonly id: number,\r\n    readonly kind: TypeDefKind,\r\n    readonly name: string,\r\n    readonly template: TypeDef,\r\n    private readonly ctor?: new () => object,\r\n    readonly constants?: TypeDefConstant[],\r\n  ) {}\r\n\r\n  get properties(): TypeDefProperty[] {\r\n    return (this.cachedProperties ??= this.template.properties.map((p) => ({\r\n      name: p.name,\r\n      valueType: p.valueType,\r\n    })));\r\n  }\r\n\r\n  createInstance(): object {\r\n    if (!this.ctor) throw new Error(`TypeDef '${this.name}' has no constructor.`);\r\n    return new this.ctor();\r\n  }\r\n\r\n  setProperty(instance: object, name: string, value: unknown): void {\r\n    (instance as { [key: string]: unknown })[name] = value;\r\n  }\r\n\r\n  /**\r\n   * Invoke a `static` exported function by name (port of what dotnet reaches\r\n   * via `MethodInfo.Invoke(null, args)` for a static `FunctionDef`). The\r\n   * caller is responsible for having checked `FunctionTemplate.isStatic`.\r\n   */\r\n  invokeStaticFunction(name: string, args: unknown[]): unknown {\r\n    if (!this.ctor) throw new Error(`TypeDef '${this.name}' has no constructor.`);\r\n    const fn = (this.ctor as unknown as Record<string, (...a: unknown[]) => unknown>)[name];\r\n    if (typeof fn !== \"function\") throw new Error(`'${this.name}' has no static function '${name}'.`);\r\n    return fn(...args);\r\n  }\r\n}\r\n","import { Tdu } from \"../data/Tdu.js\";\r\nimport { TduClass } from \"../data/TduClass.js\";\r\nimport { TduIdentifier } from \"../data/TduIdentifier.js\";\r\nimport { TruTypeDef, type Tru, registerTypeDefResolver } from \"../data/Tru.js\";\r\nimport { composeInternal, registerComposer } from \"../data/Codec.js\";\r\nimport { merge } from \"../data/DC.js\";\r\nimport type { ITypeDef } from \"../data/types/ITypeDef.js\";\r\nimport type { LocalTypeDef } from \"./typedef.js\";\r\nimport type { Warehouse } from \"./Warehouse.js\";\r\n\r\n/**\r\n * Marker base class for record (data-transfer) types. A record exposes\r\n * `@Export`ed properties and serializes as a Typed TDU referencing its\r\n * {@link LocalTypeDef} (port of C# `Record`/`IRecord`).\r\n */\r\nexport class Record {}\r\n\r\n/** True if a value is a record instance. */\r\nexport function isRecord(value: unknown): value is Record {\r\n  return value instanceof Record;\r\n}\r\n\r\n/** Compose a record as a Typed TDU: `TruTypeDef` metadata + each property value. */\r\nexport function recordCompose(value: object, warehouse: Warehouse, connection: unknown): Tdu {\r\n  const typeDef = warehouse.getLocalTypeDefByType(value.constructor) as LocalTypeDef;\r\n  const metadata = new TruTypeDef(false, typeDef);\r\n\r\n  const bag = value as { [key: string]: unknown };\r\n  const parts: Uint8Array[] = [];\r\n\r\n  for (const pt of typeDef.template.properties) {\r\n    const tdu = composeInternal(bag[pt.name], warehouse, connection);\r\n    if (\r\n      tdu.tduClass === TduClass.Typed &&\r\n      pt.valueType &&\r\n      tdu.metadata &&\r\n      pt.valueType.match(tdu.metadata as Tru)\r\n    ) {\r\n      const d = tdu.composed.subarray(tdu.contentOffset);\r\n      parts.push(new Tdu(TduIdentifier.TypeOfTarget, d, d.length).composed);\r\n    } else {\r\n      parts.push(tdu.composed);\r\n    }\r\n  }\r\n\r\n  const payload = merge(...parts);\r\n  return new Tdu(TduIdentifier.Typed, payload, payload.length, metadata, connection);\r\n}\r\n\r\n// Wire records into the serializer:\r\n//  - compose: recognize record instances and produce their Typed TDU.\r\n//  - decode: resolve a TypeDef id to its definition via the warehouse.\r\nregisterComposer((value, warehouse, connection) =>\r\n  isRecord(value) ? recordCompose(value, warehouse as Warehouse, connection) : undefined,\r\n);\r\nregisterTypeDefResolver((warehouse, id): ITypeDef =>\r\n  (warehouse as Warehouse).getLocalTypeDefById(id),\r\n);\r\n","import { Tdu } from \"../data/Tdu.js\";\r\nimport { TduIdentifier } from \"../data/TduIdentifier.js\";\r\nimport { TruTypeDef } from \"../data/Tru.js\";\r\nimport { registerComposer } from \"../data/Codec.js\";\r\nimport type { Warehouse } from \"./Warehouse.js\";\r\n\r\n/** A named enum constant. */\r\nexport interface EnumConstant {\r\n  name: string;\r\n  value: number;\r\n  index: number;\r\n}\r\n\r\n/**\r\n * Describes an enumeration for serialization (port of the enum side of C#\r\n * `TypeDef`/`LocalTypeDef`). Since a TS enum value is a bare number, wrap values\r\n * with {@link value}/{@link enumValue} so the serializer knows the enum type.\r\n */\r\nexport class EnumType {\r\n  readonly constants: EnumConstant[];\r\n\r\n  constructor(\r\n    readonly name: string,\r\n    members: Record<string, number>,\r\n  ) {\r\n    this.constants = Object.entries(members).map(([n, v], index) => ({\r\n      name: n,\r\n      value: v,\r\n      index,\r\n    }));\r\n  }\r\n\r\n  /** Wrap a numeric value as an {@link EnumValue} for serialization. */\r\n  value(v: number): EnumValue {\r\n    return new EnumValue(this, v);\r\n  }\r\n}\r\n\r\n/** A value tagged with its {@link EnumType} for serialization. */\r\nexport class EnumValue {\r\n  constructor(\r\n    readonly enumType: EnumType,\r\n    readonly value: number,\r\n  ) {}\r\n}\r\n\r\n/** Define an enum type, e.g. `defineEnum(\"Color\", { Red: 0, Green: 1, Blue: 2 })`. */\r\nexport function defineEnum(name: string, members: Record<string, number>): EnumType {\r\n  return new EnumType(name, members);\r\n}\r\n\r\n/** Tag a numeric value with an enum type for serialization. */\r\nexport function enumValue(enumType: EnumType, value: number): EnumValue {\r\n  return new EnumValue(enumType, value);\r\n}\r\n\r\n/** Compose an enum value as a Typed TDU (`TruTypeDef` metadata + constant index). */\r\nfunction enumCompose(value: EnumValue, warehouse: Warehouse, connection: unknown): Tdu {\r\n  const ct = value.enumType.constants.find((c) => c.value === value.value);\r\n  if (!ct) return new Tdu(TduIdentifier.Null, null, 0);\r\n\r\n  const typeDef = warehouse.getLocalTypeDefByEnum(value.enumType);\r\n  const metadata = new TruTypeDef(false, typeDef);\r\n  return new Tdu(TduIdentifier.Typed, Uint8Array.of(ct.index), 1, metadata, connection);\r\n}\r\n\r\nregisterComposer((value, warehouse, connection) =>\r\n  value instanceof EnumValue ? enumCompose(value, warehouse as Warehouse, connection) : undefined,\r\n);\r\n","import { AsyncReply } from \"../core/AsyncReply.js\";\r\nimport { EventHandler } from \"../core/EventHandler.js\";\r\nimport type { IResource, IResourceContext, IStore } from \"./IResource.js\";\r\nimport { Instance } from \"./Instance.js\";\r\nimport { ResourceOperation } from \"./ResourceOperation.js\";\r\nimport { getRemoteInfo, getTypeDef } from \"./decorators.js\";\r\nimport { TypeDef } from \"./template.js\";\r\nimport { TypeDefKind, type ITypeDef } from \"../data/types/ITypeDef.js\";\r\nimport { LocalTypeDef } from \"./typedef.js\";\r\nimport { Record } from \"./records.js\";\r\nimport type { EnumType } from \"./enums.js\";\r\nimport { EpConnection, type EpConnectionOptions } from \"../protocol/EpConnection.js\";\r\nimport type { EpResourceConstructor } from \"../protocol/EpResource.js\";\r\nimport type { IAuthenticationProvider } from \"../security/IAuthenticationProvider.js\";\r\nimport type { IEncryptionProvider } from \"../security/cryptography/IEncryptionProvider.js\";\r\nimport { getResourceManagerTypes } from \"./decorators.js\";\r\nimport type { IResourceManager } from \"../security/management/IResourceManager.js\";\r\nimport type { IPermissionsManager } from \"../security/permissions/IPermissionsManager.js\";\r\nimport type { IRateControlManager } from \"../security/management/IRateControlManager.js\";\r\nimport type { IAuditingManager } from \"../security/management/IAuditingManager.js\";\r\nimport type { ResourceManagerContext } from \"../security/management/ResourceManagerContext.js\";\r\nimport { ResourceManagerEvaluation } from \"../security/management/ResourceManagerEvaluation.js\";\r\nimport { ActionType } from \"../security/permissions/ActionType.js\";\r\nimport { Ruling } from \"../security/permissions/Ruling.js\";\r\nimport type { RatePolicy } from \"../security/ratelimiting/RatePolicy.js\";\r\nimport { NamedRateControlManager } from \"../security/ratelimiting/NamedRateControlManager.js\";\r\n\r\nexport interface WarehouseRemoteGetOptions extends EpConnectionOptions {\r\n  /** TypeDef for the remote resource proxy. Required when the URL includes a resource path. */\r\n  typeDef?: TypeDef;\r\n  /** @deprecated Use {@link typeDef}. */\r\n  template?: TypeDef;\r\n  /** Resource/stub constructor used to derive {@link typeDef}. */\r\n  type?: Function | EpResourceConstructor;\r\n}\r\n\r\nexport type WarehouseGetOptions =\r\n  | WarehouseRemoteGetOptions\r\n  | TypeDef\r\n  | Function;\r\n\r\n/** Duck-typed check for an {@link IStore}. */\r\nfunction isStore(resource: IResource): resource is IStore {\r\n  const s = resource as Partial<IStore>;\r\n  return (\r\n    typeof s.get === \"function\" &&\r\n    typeof s.put === \"function\" &&\r\n    typeof s.link === \"function\" &&\r\n    typeof s.modify === \"function\"\r\n  );\r\n}\r\n\r\n/**\r\n * Central resource manager (port of C# `Warehouse`). Holds stores and active\r\n * resources, resolves `*nix`-style paths, and drives the resource lifecycle.\r\n *\r\n * `get` resolves local paths and EP URLs. A bare EP URL returns an\r\n * {@link EpConnection}; an EP URL with a resource path returns an attached\r\n * remote proxy when a TypeDef/stub type is supplied.\r\n */\r\nexport class Warehouse {\r\n  static readonly default = new Warehouse();\r\n\r\n  readonly storeConnected = new EventHandler<IStore>();\r\n  readonly storeDisconnected = new EventHandler<IStore>();\r\n\r\n  private readonly resources = new Map<number, IResource>();\r\n  private readonly stores = new Set<IStore>();\r\n  private resourceCounter = 0;\r\n  private opened = false;\r\n\r\n  private readonly typeDefs = new Map<number, ITypeDef>();\r\n  private readonly typeDefsByCtor = new Map<Function, ITypeDef>();\r\n  private readonly typeDefsByEnum = new Map<EnumType, ITypeDef>();\r\n  private typeDefCounter = 0;\r\n  private readonly authenticationProviders = new Map<string, IAuthenticationProvider>();\r\n  private readonly encryptionProviders = new Map<string, IEncryptionProvider>();\r\n  private readonly resourceManagers = new Map<Function, IResourceManager>();\r\n  private readonly defaultResourceManagerTypes = new Set<Function>();\r\n  private readonly ratePolicies = new Map<string, RatePolicy>();\r\n  private readonly proxyTypes = new Map<string, Function>();\r\n\r\n  constructor() {\r\n    // Built in and always-on, matching dotnet's own Warehouse construction —\r\n    // bridges `@RateControl(name)`-tagged members into the named rate-policy\r\n    // registry (see `addRatePolicy`/`tryGetRatePolicy`).\r\n    this.registerManager(new NamedRateControlManager(), true);\r\n  }\r\n\r\n  /** Register an authentication provider under its default protocol name. */\r\n  registerAuthenticationProvider(provider: IAuthenticationProvider): void;\r\n  /** Register an authentication provider under an explicit protocol name. */\r\n  registerAuthenticationProvider(name: string, provider: IAuthenticationProvider): void;\r\n  registerAuthenticationProvider(\r\n    nameOrProvider: string | IAuthenticationProvider,\r\n    provider?: IAuthenticationProvider,\r\n  ): void {\r\n    const name = typeof nameOrProvider === \"string\" ? nameOrProvider : nameOrProvider.defaultName;\r\n    const resolved = provider ?? (nameOrProvider as IAuthenticationProvider);\r\n    this.authenticationProviders.set(name, resolved);\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link registerAuthenticationProvider}. */\r\n  RegisterAuthenticationProvider(provider: IAuthenticationProvider): void;\r\n  /** .NET-compatible alias for {@link registerAuthenticationProvider}. */\r\n  RegisterAuthenticationProvider(name: string, provider: IAuthenticationProvider): void;\r\n  RegisterAuthenticationProvider(\r\n    nameOrProvider: string | IAuthenticationProvider,\r\n    provider?: IAuthenticationProvider,\r\n  ): void {\r\n    if (typeof nameOrProvider === \"string\")\r\n      this.registerAuthenticationProvider(nameOrProvider, provider!);\r\n    else\r\n      this.registerAuthenticationProvider(nameOrProvider);\r\n  }\r\n\r\n  /** Resolve an authentication provider by protocol name, throwing when missing. */\r\n  getAuthenticationProvider(name: string): IAuthenticationProvider {\r\n    const provider = this.tryGetAuthenticationProvider(name);\r\n    if (!provider) throw new Error(\"Authentication provider not found.\");\r\n    return provider;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link getAuthenticationProvider}. */\r\n  GetAuthenticationProvider(name: string): IAuthenticationProvider {\r\n    return this.getAuthenticationProvider(name);\r\n  }\r\n\r\n  /** Try to resolve an authentication provider by protocol name. */\r\n  tryGetAuthenticationProvider(name: string): IAuthenticationProvider | undefined {\r\n    return this.authenticationProviders.get(name);\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link tryGetAuthenticationProvider}. */\r\n  TryGetAuthenticationProvider(name: string): IAuthenticationProvider | undefined {\r\n    return this.tryGetAuthenticationProvider(name);\r\n  }\r\n\r\n  /** Register an encryption provider under its default protocol name. */\r\n  registerEncryptionProvider(provider: IEncryptionProvider): void;\r\n  /** Register an encryption provider under an explicit protocol name. */\r\n  registerEncryptionProvider(name: string, provider: IEncryptionProvider): void;\r\n  registerEncryptionProvider(\r\n    nameOrProvider: string | IEncryptionProvider,\r\n    provider?: IEncryptionProvider,\r\n  ): void {\r\n    const name = typeof nameOrProvider === \"string\" ? nameOrProvider : nameOrProvider.defaultName;\r\n    const resolved = provider ?? (nameOrProvider as IEncryptionProvider);\r\n    if (this.encryptionProviders.has(name))\r\n      throw new Error(`An encryption provider named '${name}' is already registered.`);\r\n    this.encryptionProviders.set(name, resolved);\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link registerEncryptionProvider}. */\r\n  RegisterEncryptionProvider(provider: IEncryptionProvider): void;\r\n  /** .NET-compatible alias for {@link registerEncryptionProvider}. */\r\n  RegisterEncryptionProvider(name: string, provider: IEncryptionProvider): void;\r\n  RegisterEncryptionProvider(\r\n    nameOrProvider: string | IEncryptionProvider,\r\n    provider?: IEncryptionProvider,\r\n  ): void {\r\n    if (typeof nameOrProvider === \"string\") this.registerEncryptionProvider(nameOrProvider, provider!);\r\n    else this.registerEncryptionProvider(nameOrProvider);\r\n  }\r\n\r\n  /** Unregister an encryption provider previously registered under `name`. */\r\n  unregisterEncryptionProvider(name: string, provider: IEncryptionProvider): boolean {\r\n    return this.encryptionProviders.get(name) === provider && this.encryptionProviders.delete(name);\r\n  }\r\n\r\n  /** Resolve an encryption provider by protocol name, throwing when missing. */\r\n  getEncryptionProvider(name: string): IEncryptionProvider {\r\n    const provider = this.tryGetEncryptionProvider(name);\r\n    if (!provider) throw new Error(`No encryption provider named '${name}'.`);\r\n    return provider;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link getEncryptionProvider}. */\r\n  GetEncryptionProvider(name: string): IEncryptionProvider {\r\n    return this.getEncryptionProvider(name);\r\n  }\r\n\r\n  /** Try to resolve an encryption provider by protocol name. */\r\n  tryGetEncryptionProvider(name: string): IEncryptionProvider | undefined {\r\n    return this.encryptionProviders.get(name);\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link tryGetEncryptionProvider}. */\r\n  TryGetEncryptionProvider(name: string): IEncryptionProvider | undefined {\r\n    return this.tryGetEncryptionProvider(name);\r\n  }\r\n\r\n  /** Names of every registered encryption provider. */\r\n  getEncryptionProviderNames(): string[] {\r\n    return [...this.encryptionProviders.keys()];\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link getEncryptionProviderNames}. */\r\n  GetEncryptionProviderNames(): string[] {\r\n    return this.getEncryptionProviderNames();\r\n  }\r\n\r\n  // ---- resource managers (permissions / rate control / auditing) --------------\r\n\r\n  /**\r\n   * Register a manager instance by its concrete type (port of C#\r\n   * `RegisterManager`). Type-level `@PermissionsManager`/`@RateControlManager`/\r\n   * `@AuditingManager` associations and `resolveResourceManagers` can only\r\n   * reference instances registered here.\r\n   */\r\n  registerManager(manager: IResourceManager, useAsDefault = false): void {\r\n    if (\r\n      manager.managerCategory !== \"permissions\" &&\r\n      manager.managerCategory !== \"rateControl\" &&\r\n      manager.managerCategory !== \"auditing\"\r\n    )\r\n      throw new Error(`Manager \\`${manager.constructor.name}\\` does not implement a supported manager category.`);\r\n\r\n    const managerCtor = manager.constructor as Function;\r\n    if (this.resourceManagers.has(managerCtor))\r\n      throw new Error(`A resource manager of type \\`${managerCtor.name}\\` is already registered.`);\r\n\r\n    this.resourceManagers.set(managerCtor, manager);\r\n    if (useAsDefault) this.defaultResourceManagerTypes.add(managerCtor);\r\n  }\r\n\r\n  /** Compatibility registration for Warehouse-wide permissions (registered managers default to on). */\r\n  registerPermissionsManager(manager: IPermissionsManager, useAsDefault = true): void {\r\n    this.registerManager(manager, useAsDefault);\r\n  }\r\n\r\n  registerRateControlManager(manager: IRateControlManager, useAsDefault = false): void {\r\n    this.registerManager(manager, useAsDefault);\r\n  }\r\n\r\n  registerAuditingManager(manager: IAuditingManager, useAsDefault = false): void {\r\n    this.registerManager(manager, useAsDefault);\r\n  }\r\n\r\n  /** Enable/disable a registered manager as a Warehouse-wide default. Multiple defaults per category are allowed. */\r\n  setDefaultManager(managerCtor: Function, enabled = true): void {\r\n    if (!this.resourceManagers.has(managerCtor))\r\n      throw new Error(`Resource manager \\`${managerCtor.name}\\` is not registered.`);\r\n    if (!enabled && managerCtor === NamedRateControlManager)\r\n      throw new Error(\"The built-in named rate-control manager cannot be disabled.\");\r\n\r\n    if (enabled) this.defaultResourceManagerTypes.add(managerCtor);\r\n    else this.defaultResourceManagerTypes.delete(managerCtor);\r\n  }\r\n\r\n  tryGetManager<T extends IResourceManager = IResourceManager>(managerCtor: Function): T | undefined {\r\n    return this.resourceManagers.get(managerCtor) as T | undefined;\r\n  }\r\n\r\n  removeManager(managerCtor: Function): boolean {\r\n    if (managerCtor === NamedRateControlManager) return false;\r\n    this.defaultResourceManagerTypes.delete(managerCtor);\r\n    return this.resourceManagers.delete(managerCtor);\r\n  }\r\n\r\n  getDefaultManagers(): IResourceManager[] {\r\n    return [...this.defaultResourceManagerTypes]\r\n      .map((ctor) => this.resourceManagers.get(ctor))\r\n      .filter((m): m is IResourceManager => m != null);\r\n  }\r\n\r\n  private isRegisteredManager(manager: IResourceManager): boolean {\r\n    return this.resourceManagers.get(manager.constructor as Function) === manager;\r\n  }\r\n\r\n  /** Resolve the managers a resource type declared via `@PermissionsManager`/`@RateControlManager`/`@AuditingManager`. */\r\n  resolveResourceManagers(resourceCtor: Function): IResourceManager[] {\r\n    const resolved: IResourceManager[] = [];\r\n    for (const managerCtor of getResourceManagerTypes(resourceCtor)) {\r\n      const manager = this.tryGetManager(managerCtor);\r\n      if (!manager)\r\n        throw new Error(\r\n          `Resource manager \\`${managerCtor.name}\\` declared by \\`${resourceCtor.name}\\` is not registered.`,\r\n        );\r\n      if (!resolved.includes(manager)) resolved.push(manager);\r\n    }\r\n    return resolved;\r\n  }\r\n\r\n  /**\r\n   * Ask every applicable manager, using independent deny-overrides\r\n   * aggregation for permissions/rate-control/auditing (port of C#\r\n   * `EvaluateManagers`). When `managers` isn't supplied, resolves them from\r\n   * the target resource's type (dotnet also folds in per-instance managers\r\n   * via `Instance.Managers`; this port has no per-instance manager override\r\n   * concept, only the type-level `@...Manager` decorators).\r\n   */\r\n  evaluateManagers(\r\n    context: ResourceManagerContext,\r\n    managers?: Iterable<IResourceManager>,\r\n  ): ResourceManagerEvaluation {\r\n    const local = managers\r\n      ? [...managers]\r\n      : context.resource\r\n        ? this.resolveResourceManagers(context.resource.constructor as Function)\r\n        : [];\r\n\r\n    const combined: IResourceManager[] = [];\r\n    for (const manager of [...this.getDefaultManagers(), ...local])\r\n      if (manager && !combined.includes(manager)) combined.push(manager);\r\n\r\n    let permissionsAllowed = false;\r\n    let permissionsDenied = false;\r\n    let rateAllowed = false;\r\n    let rateDenied = false;\r\n    let auditingAllowed = false;\r\n    let auditingDenied = false;\r\n    let delay = 0;\r\n    let permissionsReason: string | undefined;\r\n    let rateReason: string | undefined;\r\n    let auditingReason: string | undefined;\r\n\r\n    for (const manager of combined) {\r\n      context.delay = 0;\r\n      context.denialReason = undefined;\r\n\r\n      try {\r\n        if (!this.isRegisteredManager(manager))\r\n          throw new Error(`Resource manager \\`${manager.constructor.name}\\` is not registered with this Warehouse.`);\r\n\r\n        if (manager.managerCategory === \"permissions\") {\r\n          const ruling = (manager as IPermissionsManager).applicable(\r\n            context.resource,\r\n            context.session,\r\n            context.action,\r\n            context.member,\r\n            context.inquirer,\r\n          );\r\n          permissionsDenied ||= ruling === Ruling.Denied;\r\n          permissionsAllowed ||= ruling === Ruling.Allowed;\r\n          if (ruling === Ruling.Denied && permissionsReason == null)\r\n            permissionsReason =\r\n              context.denialReason ?? `Permissions manager \\`${manager.constructor.name}\\` denied the operation.`;\r\n        } else if (manager.managerCategory === \"rateControl\") {\r\n          const ruling = (manager as IRateControlManager).applicable(context);\r\n          rateDenied ||= ruling === Ruling.Denied;\r\n          rateAllowed ||= ruling === Ruling.Allowed;\r\n          if (context.delay > delay) delay = context.delay;\r\n          if (ruling === Ruling.Denied && rateReason == null)\r\n            rateReason =\r\n              context.denialReason ?? `Rate-control manager \\`${manager.constructor.name}\\` denied the operation.`;\r\n        } else if (manager.managerCategory === \"auditing\") {\r\n          const ruling = (manager as IAuditingManager).applicable(context);\r\n          auditingDenied ||= ruling === Ruling.Denied;\r\n          auditingAllowed ||= ruling === Ruling.Allowed;\r\n          if (ruling === Ruling.Denied && auditingReason == null)\r\n            auditingReason =\r\n              context.denialReason ?? `Auditing manager \\`${manager.constructor.name}\\` denied the operation.`;\r\n        }\r\n      } catch (error) {\r\n        if (manager.managerCategory === \"permissions\") {\r\n          permissionsDenied = true;\r\n          permissionsReason ??= \"A permissions manager failed while evaluating the operation.\";\r\n        } else if (manager.managerCategory === \"rateControl\") {\r\n          rateDenied = true;\r\n          rateReason ??= \"A rate-control manager failed while evaluating the operation.\";\r\n        } else if (manager.managerCategory === \"auditing\") {\r\n          auditingDenied = true;\r\n          auditingReason ??= \"An auditing manager failed while evaluating the operation.\";\r\n        }\r\n        void error;\r\n      }\r\n    }\r\n\r\n    const permissions = permissionsDenied\r\n      ? Ruling.Denied\r\n      : permissionsAllowed\r\n        ? Ruling.Allowed\r\n        : defaultPermissions(context.action);\r\n    const rateControl = rateDenied ? Ruling.Denied : rateAllowed ? Ruling.Allowed : Ruling.DontCare;\r\n    const auditing = auditingDenied ? Ruling.Denied : auditingAllowed ? Ruling.Allowed : Ruling.DontCare;\r\n\r\n    context.delay = delay;\r\n    context.denialReason =\r\n      permissions === Ruling.Denied ? permissionsReason : auditing === Ruling.Denied ? auditingReason : rateReason;\r\n\r\n    return new ResourceManagerEvaluation(\r\n      permissions,\r\n      rateControl,\r\n      auditing,\r\n      delay,\r\n      permissionsReason,\r\n      rateReason,\r\n      auditingReason,\r\n    );\r\n  }\r\n\r\n  /** Register a named rate policy referenced by `@RateControl(name)`. */\r\n  addRatePolicy(policy: RatePolicy): void;\r\n  addRatePolicy(name: string, policy: RatePolicy): void;\r\n  addRatePolicy(nameOrPolicy: string | RatePolicy, policy?: RatePolicy): void {\r\n    const resolved = typeof nameOrPolicy === \"string\" ? policy! : nameOrPolicy;\r\n    if (typeof nameOrPolicy === \"string\") resolved.name = nameOrPolicy;\r\n    if (!resolved.name?.trim()) throw new Error(\"The rate policy must have a name.\");\r\n    if (this.ratePolicies.has(resolved.name))\r\n      throw new Error(`A rate policy named \\`${resolved.name}\\` is already registered.`);\r\n    this.ratePolicies.set(resolved.name, resolved);\r\n  }\r\n\r\n  tryGetRatePolicy(name: string): RatePolicy | undefined {\r\n    return name?.trim() ? this.ratePolicies.get(name) : undefined;\r\n  }\r\n\r\n  removeRatePolicy(name: string): boolean {\r\n    return name?.trim() ? this.ratePolicies.delete(name) : false;\r\n  }\r\n\r\n  /** Register a generated remote proxy type for automatic EpResource attachment. */\r\n  registerProxyType(type: Function): void {\r\n    const registration = getProxyRegistration(type);\r\n    const domains = registration.domains.length > 0 ? registration.domains : [\"\"];\r\n    for (const domain of domains)\r\n      this.proxyTypes.set(proxyKey(registration.kind, domain, registration.name), type);\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link registerProxyType}. */\r\n  RegisterProxyType(type: Function): void {\r\n    this.registerProxyType(type);\r\n  }\r\n\r\n  /** Register multiple generated remote proxy types. */\r\n  registerProxyTypes(types: Iterable<Function>): void {\r\n    for (const type of types) this.registerProxyType(type);\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link registerProxyTypes}. */\r\n  RegisterProxyTypes(types: Iterable<Function>): void {\r\n    this.registerProxyTypes(types);\r\n  }\r\n\r\n  /** Resolve a registered generated proxy type by kind, domain and remote TypeDef name. */\r\n  tryGetProxyType(kind: TypeDefKind, domain: string, name: string): Function | undefined {\r\n    const exact = this.proxyTypes.get(proxyKey(kind, domain, name));\r\n    if (exact) return exact;\r\n\r\n    const wildcard = this.proxyTypes.get(proxyKey(kind, \"*\", name));\r\n    if (wildcard) return wildcard;\r\n\r\n    const domainless = this.proxyTypes.get(proxyKey(kind, \"\", name));\r\n    if (domainless) return domainless;\r\n\r\n    const suffix = `|${kind}|${name}`;\r\n    for (const [key, type] of this.proxyTypes)\r\n      if (key.endsWith(suffix)) return type;\r\n    return undefined;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link tryGetProxyType}. */\r\n  TryGetProxyType(kind: TypeDefKind, domain: string, name: string): Function | undefined {\r\n    return this.tryGetProxyType(kind, domain, name);\r\n  }\r\n\r\n  /** Resolve a registered generated proxy type or throw when missing. */\r\n  getProxyType(kind: TypeDefKind, domain: string, name: string): Function {\r\n    const type = this.tryGetProxyType(kind, domain, name);\r\n    if (!type) throw new Error(`No proxy type registered for '${name}' in '${domain}'.`);\r\n    return type;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link getProxyType}. */\r\n  GetProxyType(kind: TypeDefKind, domain: string, name: string): Function {\r\n    return this.getProxyType(kind, domain, name);\r\n  }\r\n\r\n  /** Build (cached) the decorated TypeDef surface for a resource class. */\r\n  getTypeDef(ctor: Function): TypeDef {\r\n    return getTypeDef(ctor);\r\n  }\r\n\r\n  /** @deprecated Use {@link getTypeDef}. */\r\n  getTemplate(ctor: Function): TypeDef {\r\n    return this.getTypeDef(ctor);\r\n  }\r\n\r\n  /** Get (or lazily create) the type definition for a resource/record class. */\r\n  getLocalTypeDefByType(ctor: Function): ITypeDef {\r\n    const existing = this.typeDefsByCtor.get(ctor);\r\n    if (existing) return existing;\r\n\r\n    const template = getTypeDef(ctor);\r\n    const kind = (ctor.prototype instanceof Record)\r\n      ? TypeDefKind.Record\r\n      : TypeDefKind.Resource;\r\n    const id = ++this.typeDefCounter;\r\n    const typeDef = new LocalTypeDef(\r\n      id,\r\n      kind,\r\n      ctor.name,\r\n      template,\r\n      ctor as new () => object,\r\n    );\r\n    this.typeDefs.set(id, typeDef);\r\n    this.typeDefsByCtor.set(ctor, typeDef);\r\n    return typeDef;\r\n  }\r\n\r\n  /** Get (or lazily create) the type definition for an enum descriptor. */\r\n  getLocalTypeDefByEnum(enumType: EnumType): ITypeDef {\r\n    const existing = this.typeDefsByEnum.get(enumType);\r\n    if (existing) return existing;\r\n\r\n    const id = ++this.typeDefCounter;\r\n    const typeDef = new LocalTypeDef(\r\n      id,\r\n      TypeDefKind.Enum,\r\n      enumType.name,\r\n      new TypeDef(enumType.name, []),\r\n      undefined,\r\n      enumType.constants,\r\n    );\r\n    this.typeDefs.set(id, typeDef);\r\n    this.typeDefsByEnum.set(enumType, typeDef);\r\n    return typeDef;\r\n  }\r\n\r\n  /** Resolve a type definition by its numeric id. */\r\n  getLocalTypeDefById(id: number): ITypeDef {\r\n    const td = this.typeDefs.get(id);\r\n    if (!td) throw new Error(`TypeDef ${id} not found.`);\r\n    return td;\r\n  }\r\n\r\n  /** Resolve a type definition registered on this warehouse by its class name. */\r\n  getLocalTypeDefByName(name: string): ITypeDef | undefined {\r\n    for (const td of this.typeDefs.values()) if (td.name === name) return td;\r\n    return undefined;\r\n  }\r\n\r\n  /** Look up an active resource by its numeric instance id. */\r\n  getById(id: number): IResource | undefined {\r\n    return this.resources.get(id);\r\n  }\r\n\r\n  /** Put a resource (or store) at `path` and initialize it. */\r\n  put<T extends IResource>(path: string, resource: T, context?: IResourceContext): AsyncReply<T> {\r\n    const reply = new AsyncReply<T>();\r\n    this.putAsync(path, resource, context).then(\r\n      (r) => reply.trigger(r),\r\n      (e) => reply.triggerError(e),\r\n    );\r\n    return reply;\r\n  }\r\n\r\n  private async putAsync<T extends IResource>(\r\n    path: string,\r\n    resource: T,\r\n    context?: IResourceContext,\r\n  ): Promise<T> {\r\n    if (resource.instance) throw new Error(\"Resource already initialized.\");\r\n    if (!path) throw new Error(\"Invalid path.\");\r\n\r\n    const location = path.replace(/^\\/+/, \"\").split(\"/\");\r\n    const instanceName = location[location.length - 1];\r\n\r\n    let store: IStore;\r\n    if (location.length === 1) {\r\n      if (!isStore(resource))\r\n        throw new Error(\"Resource is not a store; a root-level path is not allowed.\");\r\n      store = resource;\r\n    } else {\r\n      const parent = await this.query(location.slice(0, -1).join(\"/\"));\r\n      if (!parent) throw new Error(\"Can't find parent.\");\r\n      store = parent.instance!.store;\r\n    }\r\n\r\n    const id = ++this.resourceCounter;\r\n    resource.instance = new Instance(this, id, instanceName, resource, store, context?.age ?? 0);\r\n\r\n    if (isStore(resource)) {\r\n      this.stores.add(resource);\r\n    } else if ((resource as IResource) !== (store as IResource)) {\r\n      const ok = await store.put(resource, location.slice(1).join(\"/\"));\r\n      if (!ok) throw new Error(\"Store failed to put the resource.\");\r\n    }\r\n\r\n    this.resources.set(id, resource);\r\n\r\n    if (this.opened) {\r\n      await resource.handle(ResourceOperation.Initialize, context);\r\n      if (isStore(resource)) await resource.handle(ResourceOperation.Open, context);\r\n    }\r\n\r\n    if (isStore(resource)) this.storeConnected.emit(resource);\r\n    return resource;\r\n  }\r\n\r\n  /**\r\n   * Resolve a local resource path or an EP URL. `ep://host:port` returns an\r\n   * {@link EpConnection}; `ep://host:port/path` returns an attached remote proxy\r\n   * when `options` supplies a {@link TypeDef} or resource/stub constructor.\r\n   */\r\n  get<T = IResource>(\r\n    path: string,\r\n    options?: WarehouseGetOptions,\r\n  ): AsyncReply<T | EpConnection | undefined> {\r\n    const reply = new AsyncReply<T | EpConnection | undefined>();\r\n    this.getAsync<T>(path, options).then(\r\n      (r) => reply.trigger(r),\r\n      (e) => reply.triggerError(e),\r\n    );\r\n    return reply;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link get}. */\r\n  Get<T = IResource>(\r\n    path: string,\r\n    options?: WarehouseGetOptions,\r\n  ): AsyncReply<T | EpConnection | undefined> {\r\n    return this.get<T>(path, options);\r\n  }\r\n\r\n  /** Resolve a resource by path, returning the raw resource. */\r\n  query(path: string): AsyncReply<IResource | undefined> {\r\n    const reply = new AsyncReply<IResource | undefined>();\r\n    this.queryAsync(path).then(\r\n      (r) => reply.trigger(r),\r\n      (e) => reply.triggerError(e),\r\n    );\r\n    return reply;\r\n  }\r\n\r\n  private async getAsync<T>(\r\n    path: string,\r\n    options?: WarehouseGetOptions,\r\n  ): Promise<T | EpConnection | undefined> {\r\n    const remote = parseRemoteEpUrl(path);\r\n    if (remote) {\r\n      if (!this.opened) await this.open();\r\n\r\n      const remoteOptions = normalizeRemoteOptions(options, this);\r\n      const connection = await EpConnection.connect(remote.socketUrl, this, remoteOptions);\r\n      if (!remote.resourcePath) return connection;\r\n\r\n      const target = remoteOptions.type ?? remoteOptions.typeDef;\r\n      return (await connection.get(\r\n        remote.resourcePath,\r\n        target as TypeDef | EpResourceConstructor | undefined,\r\n      )) as T;\r\n    }\r\n\r\n    return (await this.queryAsync(path)) as T | undefined;\r\n  }\r\n\r\n  private async queryAsync(path: string): Promise<IResource | undefined> {\r\n    const p = path.trim().replace(/^\\/+/, \"\").split(\"/\");\r\n    for (const store of this.stores) {\r\n      if (p[0] === store.instance?.name) {\r\n        if (p.length === 1) return store;\r\n        const res = await store.get(p.slice(1).join(\"/\"));\r\n        return res ?? undefined;\r\n      }\r\n    }\r\n    return undefined;\r\n  }\r\n\r\n  /** Open the warehouse: initialize all resources and open all stores. */\r\n  open(): AsyncReply<boolean> {\r\n    const reply = new AsyncReply<boolean>();\r\n    this.openAsync().then(\r\n      () => reply.trigger(true),\r\n      (e) => reply.triggerError(e),\r\n    );\r\n    return reply;\r\n  }\r\n\r\n  private async openAsync(): Promise<void> {\r\n    this.opened = true;\r\n    for (const r of this.resources.values()) await r.handle(ResourceOperation.Initialize);\r\n    for (const s of this.stores) await s.handle(ResourceOperation.Open);\r\n  }\r\n\r\n  /**\r\n   * Close the warehouse: terminate all resources in two fully-settled phases\r\n   * (`Terminate` then `SystemTerminated`), matching C# `Warehouse.Close()`.\r\n   * Each phase notifies every resource even if some throw; errors from both\r\n   * phases are aggregated rather than aborting the remaining resources.\r\n   */\r\n  close(): AsyncReply<boolean> {\r\n    const reply = new AsyncReply<boolean>();\r\n    (async () => {\r\n      const resources = new Set<IResource>([...this.resources.values(), ...this.stores]);\r\n      const terminateErrors = await settleOperation(resources, ResourceOperation.Terminate);\r\n      const systemTerminatedErrors = await settleOperation(resources, ResourceOperation.SystemTerminated);\r\n      this.opened = false;\r\n\r\n      const errors = [...terminateErrors, ...systemTerminatedErrors];\r\n      if (errors.length === 1) throw errors[0];\r\n      if (errors.length > 1)\r\n        throw new AggregateError(errors, \"One or more resources failed while closing the warehouse.\");\r\n    })().then(\r\n      () => reply.trigger(true),\r\n      (e) => reply.triggerError(e),\r\n    );\r\n    return reply;\r\n  }\r\n\r\n  /**\r\n   * Remove a resource from the warehouse: drops it from the id/store maps,\r\n   * tells its owning store to release it, destroys it, and clears its\r\n   * `.instance`. Kept synchronous (matching dotnet's `Warehouse.Remove`) —\r\n   * `MemoryStore.remove()`'s own mutation already runs synchronously despite\r\n   * its `AsyncReply` return type, so the result isn't awaited here.\r\n   *\r\n   * Deferred: recursive cascade-delete of a *store* resource's own children\r\n   * (dotnet does this too) isn't implemented — `IStore.children()` returns\r\n   * an `AsyncBag`, making that a genuinely async, separate piece of work.\r\n   */\r\n  remove(resource: IResource): boolean {\r\n    if (!resource.instance) return false;\r\n    const store = resource.instance.store;\r\n    this.resources.delete(resource.instance.id);\r\n    if (isStore(resource)) {\r\n      this.stores.delete(resource);\r\n      this.storeDisconnected.emit(resource);\r\n    }\r\n    if (store && (store as unknown as IResource) !== resource) store.remove(resource);\r\n    resource.destroy();\r\n    resource.instance = undefined;\r\n    return true;\r\n  }\r\n}\r\n\r\n/** Dispatch `operation` to every resource, collecting (not throwing on) per-resource errors. */\r\nasync function settleOperation(\r\n  resources: Iterable<IResource>,\r\n  operation: ResourceOperation,\r\n): Promise<unknown[]> {\r\n  const errors: unknown[] = [];\r\n  await Promise.all(\r\n    [...resources].map(async (r) => {\r\n      try {\r\n        await r.handle(operation);\r\n      } catch (e) {\r\n        errors.push(e);\r\n      }\r\n    }),\r\n  );\r\n  return errors;\r\n}\r\n\r\n/**\r\n * Fallback ruling when no permissions manager voted either way (port of C#\r\n * `Warehouse.DefaultPermissions`) — read-ish/connection-lifecycle actions\r\n * default to allowed for backward compatibility; mutating/administrative\r\n * actions default to denied (fail closed).\r\n */\r\nfunction defaultPermissions(action: ActionType): Ruling {\r\n  switch (action) {\r\n    case ActionType.GetProperty:\r\n    case ActionType.ViewTypeDef:\r\n    case ActionType.ReceiveEvent:\r\n    case ActionType.Attach:\r\n    case ActionType.Execute:\r\n    case ActionType.Detach:\r\n    case ActionType.Subscribe:\r\n    case ActionType.Unsubscribe:\r\n    case ActionType.PullStream:\r\n    case ActionType.TerminateExecution:\r\n    case ActionType.HaltExecution:\r\n    case ActionType.ResumeExecution:\r\n      return Ruling.Allowed;\r\n    default:\r\n      return Ruling.Denied;\r\n  }\r\n}\r\n\r\ninterface RemoteEpUrl {\r\n  socketUrl: string;\r\n  resourcePath: string;\r\n}\r\n\r\nfunction parseRemoteEpUrl(path: string): RemoteEpUrl | undefined {\n  let url: URL;\r\n  try {\r\n    url = new URL(path);\r\n  } catch {\r\n    return undefined;\r\n  }\r\n\r\n  const scheme = url.protocol.slice(0, -1).toLowerCase();\r\n  let socketScheme: \"ws\" | \"wss\" | \"tcp\";\r\n  if (scheme === \"ep\" || scheme === \"ws\") socketScheme = \"ws\";\r\n  else if (scheme === \"eps\" || scheme === \"wss\") socketScheme = \"wss\";\r\n  // `tcp://host:port` dials a raw TCP socket (Node-only) instead of a\r\n  // WebSocket — for esiur-dotnet servers exposing only their native\r\n  // `TcpServer`, with no WebSocket upgrade route.\r\n  else if (scheme === \"tcp\") socketScheme = \"tcp\";\n  else return undefined;\n\n  const port = getExplicitPort(path);\n  if (port == null)\n    throw new Error(\n      `EP endpoints must include an explicit port (for example, ep://host:port): ${path}`,\n    );\n\n  const resourcePath = decodeURIComponent(url.pathname.replace(/^\\/+/, \"\"));\n  const hostname = url.hostname.includes(\":\") && !url.hostname.startsWith(\"[\")\n    ? `[${url.hostname}]`\n    : url.hostname;\n  return {\n    socketUrl: `${socketScheme}://${hostname}:${port}`,\n    resourcePath,\n  };\n}\n\nfunction getExplicitPort(value: string): number | undefined {\n  const schemeEnd = value.indexOf(\"://\");\n  if (schemeEnd < 0) return undefined;\n\n  const authorityStart = schemeEnd + 3;\n  const separatorIndexes = [\"/\", \"?\", \"#\"]\n    .map((separator) => value.indexOf(separator, authorityStart))\n    .filter((index) => index >= 0);\n  const authorityEnd = separatorIndexes.length > 0 ? Math.min(...separatorIndexes) : value.length;\n  const authority = value.slice(authorityStart, authorityEnd).split(\"@\").at(-1) ?? \"\";\n  const closingBracket = authority.indexOf(\"]\");\n  const colon = authority.startsWith(\"[\") ? closingBracket + 1 : authority.lastIndexOf(\":\");\n  if (colon <= 0 || authority[colon] !== \":\") return undefined;\n\n  const portText = authority.slice(colon + 1);\n  const port = Number(portText);\n  return /^\\d+$/.test(portText) && port > 0 && port <= 65535 ? port : undefined;\n}\n\r\nfunction normalizeRemoteOptions(\r\n  options: WarehouseGetOptions | undefined,\r\n  warehouse: Warehouse,\r\n): WarehouseRemoteGetOptions {\r\n  if (!options) return {};\r\n  if (options instanceof TypeDef) return { typeDef: options };\r\n  if (typeof options === \"function\")\r\n    return { type: options, typeDef: getRemoteOptionTypeDef(options, warehouse) };\r\n  const typeDef =\r\n    options.typeDef ??\r\n    options.template ??\r\n    (options.type ? getRemoteOptionTypeDef(options.type, warehouse) : undefined);\r\n  return { ...options, typeDef, template: options.template ?? typeDef };\r\n}\r\n\r\nfunction getRemoteOptionTypeDef(type: Function, warehouse: Warehouse): TypeDef | undefined {\r\n  const statics = type as {\r\n    typeDef?: unknown;\r\n    TypeDef?: unknown;\r\n    template?: unknown;\r\n    Template?: unknown;\r\n  };\r\n  const explicit = statics.typeDef ?? statics.TypeDef ?? statics.template ?? statics.Template;\r\n  if (explicit instanceof TypeDef) return explicit;\r\n\r\n  const decorated = warehouse.getTypeDef(type);\r\n  return decorated.members.length > 0 ? decorated : undefined;\r\n}\r\n\r\ninterface ProxyRegistration {\r\n  kind: TypeDefKind;\r\n  name: string;\r\n  domains: string[];\r\n}\r\n\r\nfunction getProxyRegistration(type: Function): ProxyRegistration {\r\n  const remote = getRemoteInfo(type);\r\n  const statics = type as {\r\n    typeDef?: unknown;\r\n    TypeDef?: unknown;\r\n    template?: unknown;\r\n    Template?: unknown;\r\n    kind?: TypeDefKind;\r\n    Kind?: TypeDefKind;\r\n    typeDefKind?: TypeDefKind;\r\n    TypeDefKind?: TypeDefKind;\r\n  };\r\n  const template = statics.typeDef ?? statics.TypeDef ?? statics.template ?? statics.Template;\r\n  const templateName = template instanceof TypeDef ? template.className : undefined;\r\n  const kind =\r\n    statics.kind ??\r\n    statics.Kind ??\r\n    statics.typeDefKind ??\r\n    statics.TypeDefKind ??\r\n    (type.prototype instanceof Record ? TypeDefKind.Record : TypeDefKind.Resource);\r\n\r\n  return {\r\n    kind,\r\n    name: remote?.name ?? templateName ?? type.name,\r\n    domains: remote?.domains ?? [],\r\n  };\r\n}\r\n\r\nfunction proxyKey(kind: TypeDefKind, domain: string, name: string): string {\r\n  return `${domain}|${kind}|${name}`;\r\n}\r\n","import { AsyncReply } from \"../core/AsyncReply.js\";\r\nimport { AsyncStreamReply } from \"../core/AsyncStreamReply.js\";\r\nimport { AsyncException } from \"../core/AsyncException.js\";\r\nimport { ErrorType } from \"../core/ErrorType.js\";\r\nimport { ExceptionCode } from \"../core/ExceptionCode.js\";\r\nimport { ProgressType } from \"../core/ProgressType.js\";\r\nimport { NetworkConnection } from \"../net/NetworkConnection.js\";\r\nimport type { NetworkBuffer } from \"../net/NetworkBuffer.js\";\r\nimport { EpPacket } from \"../net/packets/EpPacket.js\";\r\nimport { EpPacketMethod } from \"../net/packets/EpPacketMethod.js\";\r\nimport { EpPacketRequest } from \"../net/packets/EpPacketRequest.js\";\r\nimport { EpPacketReply } from \"../net/packets/EpPacketReply.js\";\r\nimport { EpPacketNotification } from \"../net/packets/EpPacketNotification.js\";\r\nimport type { PlainTdu } from \"../data/PlainTdu.js\";\r\nimport { compose, parse, parseSync } from \"../data/Codec.js\";\r\nimport { TduIdentifier } from \"../data/TduIdentifier.js\";\r\nimport { TypeDefInfo } from \"../data/types/TypeDefInfo.js\";\r\nimport { TypeDefKind, type ITypeDef } from \"../data/types/ITypeDef.js\";\r\nimport { StreamMode } from \"../data/types/StreamMode.js\";\r\nimport { Tru, TruComposite, TruTypeDef } from \"../data/Tru.js\";\r\nimport { getUint32, getUint64, merge, uint32ToBytes } from \"../data/DC.js\";\r\nimport { Endian } from \"../data/Endian.js\";\r\nimport { typedMap } from \"../data/descriptors.js\";\r\nimport { t } from \"../data/descriptors.js\";\r\nimport { u8 } from \"../data/widths.js\";\r\nimport { ResourceId } from \"../data/ResourceId.js\";\r\nimport { WSocket } from \"../net/sockets/WSocket.js\";\r\nimport type { ISocket } from \"../net/sockets/ISocket.js\";\r\nimport { EpAuthPacket } from \"../net/packets/EpAuthPacket.js\";\r\nimport { EpAuthPacketCommand } from \"../net/packets/EpAuthPacketCommand.js\";\r\nimport { EpAuthPacketMethod } from \"../net/packets/EpAuthPacketMethod.js\";\r\nimport { EpAuthPacketHeader } from \"../net/packets/EpAuthPacketHeader.js\";\r\nimport { AuthenticationMode } from \"../security/AuthenticationMode.js\";\r\nimport { EncryptionMode } from \"../security/EncryptionMode.js\";\r\nimport { AuthenticationDirection } from \"../security/AuthenticationDirection.js\";\r\nimport { AuthenticationMaterialType } from \"../security/AuthenticationMaterialType.js\";\r\nimport { AuthenticationResult } from \"../security/AuthenticationResult.js\";\r\nimport { AuthenticationRuling } from \"../security/AuthenticationRuling.js\";\r\nimport type { AuthenticationSession } from \"../security/AuthenticationSession.js\";\r\nimport type { IAuthenticationHandler } from \"../security/IAuthenticationHandler.js\";\r\nimport type { IAuthenticationProvider } from \"../security/IAuthenticationProvider.js\";\r\nimport type { IEncryptionProvider } from \"../security/cryptography/IEncryptionProvider.js\";\r\nimport type { ISymetricCipher } from \"../security/cryptography/ISymetricCipher.js\";\r\nimport type { EncryptionContext } from \"../security/cryptography/EncryptionContext.js\";\r\nimport { randomBytes } from \"../security/random.js\";\r\nimport { ResourceManagerContext } from \"../security/management/ResourceManagerContext.js\";\r\nimport { ActionType } from \"../security/permissions/ActionType.js\";\r\nimport type { Warehouse } from \"../resource/Warehouse.js\";\r\nimport { TypeDef, type MemberTemplate, type FunctionTemplate } from \"../resource/template.js\";\r\nimport type { IResource } from \"../resource/IResource.js\";\r\nimport { isDynamicResource } from \"../resource/IDynamicResource.js\";\r\nimport { LocalTypeDef } from \"../resource/typedef.js\";\r\nimport { typeDefInfoFromTypeDef } from \"../resource/typeDefInfoCompose.js\";\r\nimport {\r\n  EpResource,\r\n  type EpResourceConstructor,\r\n  type EpResourceOptions,\r\n  type RemotePropertyValue,\r\n} from \"./EpResource.js\";\r\nimport { RemoteTypeDef } from \"./RemoteTypeDef.js\";\r\nimport { ServerInvocationContext, isIterableResult } from \"./ServerInvocationContext.js\";\r\n\r\n/** Handles an inbound request packet (server-side dispatch). */\r\nexport type RequestHandler = (\r\n  connection: EpConnection,\r\n  action: EpPacketRequest,\r\n  callbackId: number,\r\n  tdu: PlainTdu | null,\r\n) => void;\r\n\r\n/** Handles an inbound notification packet. */\r\nexport type NotificationHandler = (\r\n  connection: EpConnection,\r\n  action: EpPacketNotification,\r\n  tdu: PlainTdu | null,\r\n) => void;\r\n\r\nexport interface EpConnectionOptions {\r\n  /** Reconnect automatically after an unexpected client-side disconnect. */\r\n  autoReconnect?: boolean;\r\n  /** .NET-compatible alias for {@link autoReconnect}. */\r\n  AutoReconnect?: boolean;\r\n  /** Delay between reconnect attempts, in milliseconds. */\r\n  reconnectInterval?: number;\r\n  /** .NET-compatible alias for {@link reconnectInterval}. */\r\n  ReconnectInterval?: number;\r\n  /** Authentication mode requested by the initiator. Default `None`. */\r\n  authenticationMode?: AuthenticationMode;\r\n  /** .NET-compatible alias for {@link authenticationMode}. */\r\n  AuthenticationMode?: AuthenticationMode;\r\n  /** Authentication protocol name. Default `\"password-sha3-v1\"`. */\r\n  authenticationProtocol?: string;\r\n  /** .NET-compatible alias for {@link authenticationProtocol}. */\r\n  AuthenticationProtocol?: string;\r\n  /** Transport encryption mode requested by the initiator. Default `None`. */\r\n  encryptionMode?: EncryptionMode;\r\n  /** .NET-compatible alias for {@link encryptionMode}. */\r\n  EncryptionMode?: EncryptionMode;\r\n  /** Provider used to create the initiator authentication handler. */\r\n  authenticationProvider?: IAuthenticationProvider;\r\n  /** PascalCase alias for {@link authenticationProvider}. */\r\n  AuthenticationProvider?: IAuthenticationProvider;\r\n  /** Initiator identity for protocols that need one. */\r\n  identity?: string;\r\n  /** .NET-compatible alias for {@link identity}. */\r\n  Identity?: string;\r\n  /** Optional responder identity for protocols that need one. */\r\n  responderIdentity?: string;\r\n  /** PascalCase alias for {@link responderIdentity}. */\r\n  ResponderIdentity?: string;\r\n  /** Remote domain. Defaults to the WebSocket host. */\r\n  domain?: string;\r\n  /** .NET-compatible alias for {@link domain}. */\r\n  Domain?: string;\r\n  /**\r\n   * Absolute `ws`/`wss` URL used verbatim as the socket transport, overriding\r\n   * whatever host/port was parsed from the `Warehouse.get`/`connect` path.\r\n   * Lets a resource path (e.g. `sys/counter`) and a WebSocket upgrade route\r\n   * that doesn't match it (e.g. an ASP.NET Core host mounting Esiur at\r\n   * `/esiur`) be specified independently — mirrors dotnet's\r\n   * `EpConnectionContext.WebSocketUri`, which is used as-is, never\r\n   * concatenated with the resource path.\r\n   */\r\n  webSocketUri?: string | URL;\r\n  /** .NET-compatible alias for {@link webSocketUri}. */\r\n  WebSocketUri?: string | URL;\r\n}\r\n\r\n/** .NET-compatible connection context accepted by `Warehouse.get` and `EpConnection.connect`. */\r\nexport class EpConnectionContext implements EpConnectionOptions {\r\n  AutoReconnect?: boolean;\r\n  ReconnectInterval?: number;\r\n  AuthenticationMode?: AuthenticationMode;\r\n  AuthenticationProtocol?: string;\r\n  AuthenticationProvider?: IAuthenticationProvider;\r\n  EncryptionMode?: EncryptionMode;\r\n  Identity?: string;\r\n  ResponderIdentity?: string;\r\n  Domain?: string;\r\n  WebSocketUri?: string | URL;\r\n\r\n  constructor(options?: EpConnectionOptions) {\r\n    if (options) Object.assign(this, options);\r\n  }\r\n}\r\n\r\nexport interface EpReconnectMetrics {\r\n  connectMs: number;\r\n  reattachMs: number;\r\n  recoveryMs: number;\r\n  restoredResources: number;\r\n  failedResources: number;\r\n}\r\n\r\nexport type EpResourceAttachTarget<T extends EpResource = EpResource> =\r\n  | TypeDef\r\n  | EpResourceConstructor<T>;\r\n\r\ninterface TypeDefFetchRequestInfo {\r\n  reply: AsyncReply<RemoteTypeDef>;\r\n  requestSequence: number[];\r\n}\r\n\r\n/**\r\n * IIP/Ep connection — request/reply correlation and packet dispatch\r\n * (the backbone of C# `EpConnection`/`EpConnectionProtocol`).\r\n *\r\n * This build implements the request/reply engine, SHA3 password-hash\r\n * authentication, resource operations, and reply decoding. Incoming\r\n * requests/notifications can still be surfaced via {@link onRequest}/\r\n * {@link onNotification} for custom protocol handlers.\r\n */\r\nexport class EpConnection extends NetworkConnection {\r\n  /** Warehouse used to resolve types/resources during (de)serialization. */\r\n  warehouse?: Warehouse;\r\n\r\n  /** Invoked for inbound Request packets. */\r\n  onRequest?: RequestHandler;\r\n  /** Invoked for inbound Notification packets. */\r\n  onNotification?: NotificationHandler;\r\n\r\n  private readonly requests = new Map<number, AsyncReply>();\r\n  private callbackCounter = 0;\r\n  private readonly packet = new EpPacket();\r\n\r\n  /** Remote resources attached through this connection (instance id → proxy state). */\r\n  private readonly attachedResources = new Map<number, EpResource>();\r\n\r\n  /**\r\n   * The raw {@link EpResource} behind an id returned by {@link get}/{@link attach}\r\n   * (which hand back the ergonomic dot-access proxy instead). Needed to\r\n   * `warehouse.put()` a fetched resource for relaying to a third node — the\r\n   * warehouse machinery needs the real object, not a Proxy wrapper, so it can\r\n   * assign `.instance` and use it as an `IDynamicResource` directly.\r\n   */\r\n  getAttachedResource(instanceId: number): EpResource | undefined {\r\n    return this.attachedResources.get(instanceId);\r\n  }\r\n  /** Remote TypeDefs currently needed by an in-flight parse (type id to placeholder). */\r\n  private readonly neededTypeDefs = new Map<number, RemoteTypeDef>();\r\n  /** Fully parsed remote TypeDefs (type id to definition). */\r\n  private readonly cachedTypeDefs = new Map<number, RemoteTypeDef>();\r\n  /** In-flight TypeDef fetches, used to share work and detect recursive cycles. */\r\n  private readonly typeDefRequests = new Map<number, TypeDefFetchRequestInfo>();\r\n  /** Wait-for graph for in-flight remote TypeDef parsing. */\r\n  private readonly typeDefsFetchBlockedOn = new Map<number, Set<number>>();\r\n  /** Server-side notification subscriptions (instance id → unsubscribe). */\r\n  private readonly subscriptions = new Map<number, () => void>();\r\n  /**\r\n   * Server-side explicit per-event subscriptions (instance id → subscribed\r\n   * event indices), consulted only for events where {@link EventTemplate.subscribable}\r\n   * is true — other events keep being pushed to every attached connection\r\n   * unconditionally, as `subscribeToInstance` already does.\r\n   */\r\n  private readonly eventSubscriptions = new Map<number, Set<number>>();\r\n  /**\r\n   * Per (instanceId, eventIndex) marker listener used to ref-count an\r\n   * upstream `.on()` subscription when relaying a `subscribable` event\r\n   * through an {@link EpResource} — keeps the upstream connection subscribed\r\n   * only while at least one downstream peer here still is.\r\n   */\r\n  private readonly relayListeners = new Map<string, (value: unknown) => void>();\r\n  /**\r\n   * In-flight streamed calls, keyed by the *originating* `InvokeFunction`/\r\n   * `StaticCall` request's callback id — the same id `PullStream`/\r\n   * `TerminateExecution`/`HaltExecution`/`ResumeExecution` reference as\r\n   * their \"execution callback\" (see `sendStreamRequest`, the client-side\r\n   * counterpart that keys these the same way).\r\n   */\r\n  private readonly invocations = new Map<number, ServerInvocationContext>();\r\n\r\n  // ---- handshake --------------------------------------------------------------\r\n\r\n  /**\r\n   * True once the connection is past the auth phase. Defaults to true so a\r\n   * directly-`assign`ed connection processes packets immediately; `connect` and\r\n   * `EpServer` switch it off to run the (anonymous) handshake first.\r\n   */\r\n  private authenticated = true;\r\n  private authSessionEstablished = true;\r\n  private direction: \"initiator\" | \"responder\" | null = null;\r\n  private readonly authPacket = new EpAuthPacket();\r\n  private readyReply?: AsyncReply;\r\n  private domain = \"\";\r\n  private hostName: string | null = null;\r\n  private authenticationMode = AuthenticationMode.None;\r\n  private encryptionMode = EncryptionMode.None;\r\n  private encryptionProvider: IEncryptionProvider | null = null;\r\n  private symetricCipher: ISymetricCipher | null = null;\r\n  /** True once inbound records are being decrypted (mirrors dotnet's `_decryptInbound`). */\r\n  private decryptInbound = false;\r\n  /** True once outbound records are being encrypted. */\r\n  private encryptionActive = false;\r\n  /** Encryption protocols offered in this connection's own Initialize headers (initiator only). */\r\n  private offeredEncryptionProviders: string[] = [];\r\n  private authenticationProtocol = \"password-sha3-v1\";\r\n  private authenticationProvider?: IAuthenticationProvider;\r\n  private authenticationHandler?: IAuthenticationHandler;\r\n  private localIdentity: string | null = null;\r\n  private remoteIdentity: string | null = null;\r\n  private responderIdentity: string | null = null;\r\n  private sessionKey: Uint8Array | null = null;\r\n  private readonly localHeaders = new Map<EpAuthPacketHeader, unknown>();\r\n  private readonly remoteHeaders = new Map<EpAuthPacketHeader, unknown>();\r\n  private readonly variables = new Map<string, unknown>();\r\n  /** Responder: accept unauthenticated (anonymous, None-mode) peers. */\r\n  allowUnauthorized = true;\r\n  /** Reconnect automatically after an unexpected client-side disconnect. */\r\n  autoReconnect = false;\r\n  /** Delay between reconnect attempts, in milliseconds. */\r\n  reconnectInterval = 5000;\r\n  /** Metrics from the most recent reconnect attempt. */\r\n  lastReconnectMetrics?: EpReconnectMetrics;\r\n\r\n  /** True once the authentication phase has completed. */\r\n  get isAuthenticated(): boolean {\r\n    return this.authenticated;\r\n  }\r\n\r\n  /** Local identity reported by the authentication handler. */\r\n  get localAuthenticationIdentity(): string | null {\r\n    return this.localIdentity;\r\n  }\r\n\r\n  /** Remote identity reported by the authentication handler. */\r\n  get remoteAuthenticationIdentity(): string | null {\r\n    return this.remoteIdentity;\r\n  }\r\n\r\n  /** Derived session key, when the selected authentication protocol creates one. */\r\n  get authenticationSessionKey(): Uint8Array | null {\r\n    return this.sessionKey;\r\n  }\r\n\r\n  private reconnectUrl?: string;\r\n  private reconnectTimer?: ReturnType<typeof setTimeout>;\r\n  private reconnectReply?: AsyncReply<boolean>;\r\n  private manualClose = false;\r\n  private lastRestoreStats = { restored: 0, failed: 0 };\r\n\r\n  /** Begin the client-side handshake; resolves via {@link whenReady}. */\r\n  startInitiatorHandshake(domain = \"\"): void {\r\n    this.authenticated = false;\r\n    this.authSessionEstablished = false;\r\n    this.direction = \"initiator\";\r\n    if (domain) this.domain = domain;\r\n    this.authenticationHandler = undefined;\r\n    this.remoteHeaders.clear();\r\n    this.localHeaders.clear();\r\n    if (this.domain) this.localHeaders.set(EpAuthPacketHeader.Domain, this.domain);\r\n    this.readyReply = new AsyncReply();\r\n  }\r\n\r\n  /** Begin the server-side handshake (waits for the peer's Initialize). */\r\n  startResponderHandshake(): void {\r\n    this.authenticated = false;\r\n    this.authSessionEstablished = false;\r\n    this.direction = \"responder\";\r\n    this.authenticationHandler = undefined;\r\n    this.remoteHeaders.clear();\r\n    this.localHeaders.clear();\r\n    this.localIdentity = null;\r\n    this.remoteIdentity = null;\r\n    this.sessionKey = null;\r\n  }\r\n\r\n  /** Resolves when the handshake completes (initiator side). */\r\n  whenReady(): AsyncReply {\r\n    return this.readyReply ?? AsyncReply.fromResult(true);\r\n  }\r\n\r\n  /**\r\n   * Open a client connection to `url` over WebSocket, run the anonymous\r\n   * handshake, and resolve once the session is established.\r\n   */\r\n  static async connect(\r\n    url: string,\r\n    warehouseOrOptions?: Warehouse | EpConnectionOptions,\r\n    options?: EpConnectionOptions,\r\n  ): Promise<EpConnection> {\r\n    const connection = new EpConnection();\r\n    const config = isConnectionOptions(warehouseOrOptions) ? warehouseOrOptions : options;\r\n    if (!isConnectionOptions(warehouseOrOptions) && warehouseOrOptions)\r\n      connection.warehouse = warehouseOrOptions;\r\n    connection.applyOptions(config);\r\n    // `webSocketUri`, when set, is used verbatim as the socket transport —\r\n    // never combined with `url` — matching dotnet's `WebSocketUri` override.\r\n    const webSocketUri = config?.webSocketUri ?? config?.WebSocketUri;\r\n    await connection.openClientSocket(webSocketUri ? String(webSocketUri) : url);\r\n    return connection;\r\n  }\r\n\r\n  private applyOptions(options?: EpConnectionOptions): void {\r\n    if (!options) return;\r\n    const autoReconnect = options.autoReconnect ?? options.AutoReconnect;\r\n    const reconnectInterval = options.reconnectInterval ?? options.ReconnectInterval;\r\n    const authenticationMode = options.authenticationMode ?? options.AuthenticationMode;\r\n    const authenticationProtocol = options.authenticationProtocol ?? options.AuthenticationProtocol;\r\n    const authenticationProvider = options.authenticationProvider ?? options.AuthenticationProvider;\r\n    const encryptionMode = options.encryptionMode ?? options.EncryptionMode;\r\n    const identity = options.identity ?? options.Identity;\r\n    const responderIdentity = options.responderIdentity ?? options.ResponderIdentity;\r\n    const domain = options.domain ?? options.Domain;\r\n\r\n    if (autoReconnect != null) this.autoReconnect = autoReconnect;\r\n    if (reconnectInterval != null) this.reconnectInterval = reconnectInterval;\r\n    if (authenticationMode != null) this.authenticationMode = authenticationMode;\r\n    if (encryptionMode != null) this.encryptionMode = encryptionMode;\r\n    if (authenticationProtocol != null) this.authenticationProtocol = authenticationProtocol;\r\n    if (authenticationProvider != null) this.authenticationProvider = authenticationProvider;\r\n    if (identity != null) this.localIdentity = identity;\r\n    if (responderIdentity != null) this.responderIdentity = responderIdentity;\r\n    if (domain != null) this.domain = domain;\r\n  }\r\n\r\n  private async openClientSocket(url: string): Promise<void> {\n    requireExplicitEndpointPort(url);\n    this.reconnectUrl = url;\n    this.manualClose = false;\r\n    try {\r\n      this.hostName = new URL(url).hostname;\r\n      if (!this.domain) this.domain = this.hostName;\r\n    } catch {\r\n      /* leave domain empty */\r\n    }\r\n    this.startInitiatorHandshake(this.domain);\r\n\r\n    const socket = await this.createClientSocket(url);\r\n    this.assign(socket);\r\n    await socket.connect(url);\r\n    await this.whenReady();\r\n  }\r\n\r\n  /**\r\n   * Choose the transport for `url`'s scheme. Unlike C#'s `CreateClientSocket`\r\n   * (which picks `TcpSocket` vs `FrameworkWebSocket` based on whether\r\n   * `WebSocketUri`/a browser runtime is in play, since dotnet's connect API\r\n   * takes a bare host/port), esiur-ts's `connect()`/`Warehouse.get()` always\r\n   * take a single URL string — so the URL's own scheme is the natural,\r\n   * explicit selector here: `tcp://host:port` dials a raw {@link TcpSocket}\r\n   * (Node-only; esiur-dotnet servers exposing only their native `TcpServer`,\r\n   * with no WebSocket upgrade route, are otherwise unreachable from\r\n   * esiur-ts), anything else (`ws://`/`wss://`/`ep://`/`eps://`) keeps using\r\n   * {@link WSocket} as before.\r\n   */\r\n  private async createClientSocket(url: string): Promise<ISocket> {\r\n    let scheme = \"\";\r\n    try {\r\n      scheme = new URL(url).protocol.slice(0, -1).toLowerCase();\r\n    } catch {\r\n      /* fall through to the default WebSocket transport */\r\n    }\r\n    if (scheme === \"tcp\") {\r\n      const { TcpSocket } = await import(\"../net/sockets/TcpSocket.js\");\r\n      return new TcpSocket();\r\n    }\r\n    return new WSocket();\r\n  }\r\n\r\n  /** Send the initiator's Initialize packet. */\r\n  private declare(): void {\r\n    try {\r\n      const headers = new Map(this.localHeaders);\r\n      if (this.domain) headers.set(EpAuthPacketHeader.Domain, this.domain);\r\n\r\n      if (this.encryptionMode !== EncryptionMode.None) this.prepareEncryptionOffer(headers);\r\n\r\n      if (this.authenticationMode !== AuthenticationMode.None) {\r\n        const handler = this.getOrCreateInitiatorAuthenticationHandler();\r\n        const initAuthResult = handler.process(null);\r\n        if (initAuthResult.ruling === AuthenticationRuling.Failed)\r\n          throw new AsyncException(\r\n            ErrorType.Management,\r\n            ExceptionCode.AccessDenied,\r\n            \"Authentication failed.\",\r\n          );\r\n        headers.set(EpAuthPacketHeader.AuthenticationProtocol, handler.protocol);\r\n        headers.set(EpAuthPacketHeader.AuthenticationData, initAuthResult.authenticationData);\r\n      }\r\n\r\n      this.send(\r\n        EpAuthPacket.composeInitialize(\r\n          this.authenticationMode,\r\n          this.encryptionMode,\r\n          this.composeAuthHeaders(headers),\r\n        ),\r\n      );\r\n    } catch (e) {\r\n      this.failAuthentication(e);\r\n    }\r\n  }\r\n\r\n  /** Initiator: offer supported cipher names and a fresh nonce before sending Initialize. */\r\n  private prepareEncryptionOffer(headers: Map<EpAuthPacketHeader, unknown>): void {\r\n    if (this.authenticationMode === AuthenticationMode.None)\r\n      throw new Error(\"Session-key encryption requires an authenticated session.\");\r\n    if (\r\n      this.encryptionMode !== EncryptionMode.EncryptWithSessionKey &&\r\n      this.encryptionMode !== EncryptionMode.EncryptWithSessionKeyAndAddress\r\n    )\r\n      throw new Error(`Unsupported encryption mode \\`${this.encryptionMode}\\`.`);\r\n\r\n    const names = this.offeredEncryptionProviders.length > 0\r\n      ? this.offeredEncryptionProviders\r\n      : (this.warehouse?.getEncryptionProviderNames() ?? []);\r\n    const offered = [...new Set(names.filter((n) => n && this.warehouse?.tryGetEncryptionProvider(n)))];\r\n\r\n    if (offered.length === 0)\r\n      throw new Error(\"Encryption was requested but none of the offered providers are registered.\");\r\n\r\n    this.offeredEncryptionProviders = offered;\r\n    this.localHeaders.set(EpAuthPacketHeader.SupportedCiphers, offered);\r\n    this.localHeaders.delete(EpAuthPacketHeader.CipherType);\r\n    const nonce = randomBytes(32);\r\n    this.localHeaders.set(EpAuthPacketHeader.CipherNonce, nonce);\r\n    headers.set(EpAuthPacketHeader.SupportedCiphers, offered);\r\n    headers.set(EpAuthPacketHeader.CipherNonce, nonce);\r\n  }\r\n\r\n  /**\r\n   * Responder: negotiate an offered cipher against this connection's\r\n   * registered providers, mutating `localHeaders` (the Acknowledge headers\r\n   * about to be sent) with the selection.\r\n   */\r\n  private negotiateEncryptionAsResponder(localHeaders: Map<EpAuthPacketHeader, unknown>): boolean {\r\n    this.encryptionMode = this.authPacket.encryptionMode;\r\n    if (this.encryptionMode === EncryptionMode.None) return true;\r\n\r\n    if (\r\n      this.encryptionMode !== EncryptionMode.EncryptWithSessionKey &&\r\n      this.encryptionMode !== EncryptionMode.EncryptWithSessionKeyAndAddress\r\n    )\r\n      return this.rejectEncryption(\"The requested encryption mode is not supported.\");\r\n    if (this.authPacket.authMode === AuthenticationMode.None)\r\n      return this.rejectEncryption(\"Session-key encryption requires authentication.\");\r\n\r\n    const offered = asStringArray(this.remoteHeaders.get(EpAuthPacketHeader.SupportedCiphers));\r\n    const selected = offered.find((name) => name && this.warehouse?.tryGetEncryptionProvider(name));\r\n    if (!selected) return this.rejectEncryption(\"No mutually supported encryption provider is available.\");\r\n\r\n    const remoteNonce = this.remoteHeaders.get(EpAuthPacketHeader.CipherNonce);\r\n    if (!(remoteNonce instanceof Uint8Array) || remoteNonce.length < 16 || remoteNonce.length > 64)\r\n      return this.rejectEncryption(\"The initiator did not supply a valid cipher nonce.\");\r\n\r\n    this.encryptionProvider = this.warehouse!.getEncryptionProvider(selected);\r\n    const localOffered = (this.warehouse?.getEncryptionProviderNames() ?? []).filter(\r\n      (n) => this.warehouse?.tryGetEncryptionProvider(n),\r\n    );\r\n    this.localHeaders.set(EpAuthPacketHeader.SupportedCiphers, localOffered);\r\n    this.localHeaders.set(EpAuthPacketHeader.CipherType, selected);\r\n    const nonce = randomBytes(32);\r\n    this.localHeaders.set(EpAuthPacketHeader.CipherNonce, nonce);\r\n\r\n    localHeaders.set(EpAuthPacketHeader.SupportedCiphers, localOffered);\r\n    localHeaders.set(EpAuthPacketHeader.CipherType, selected);\r\n    localHeaders.set(EpAuthPacketHeader.CipherNonce, nonce);\r\n    return true;\r\n  }\r\n\r\n  /** Initiator: accept the responder's cipher selection from its Acknowledge headers. */\r\n  private acceptEncryptionAsInitiator(): boolean {\r\n    if (this.encryptionMode === EncryptionMode.None) {\r\n      const selected = this.remoteHeaders.get(EpAuthPacketHeader.CipherType);\r\n      return selected == null || this.rejectEncryption(\"The responder selected encryption that was not requested.\");\r\n    }\r\n\r\n    const selected = this.remoteHeaders.get(EpAuthPacketHeader.CipherType);\r\n    if (typeof selected !== \"string\" || !selected.trim() || !this.offeredEncryptionProviders.includes(selected))\r\n      return this.rejectEncryption(\"The responder did not select an offered encryption provider.\");\r\n\r\n    const remoteNonce = this.remoteHeaders.get(EpAuthPacketHeader.CipherNonce);\r\n    if (!(remoteNonce instanceof Uint8Array) || remoteNonce.length < 16 || remoteNonce.length > 64)\r\n      return this.rejectEncryption(\"The responder did not supply a valid cipher nonce.\");\r\n\r\n    const provider = this.warehouse?.tryGetEncryptionProvider(selected);\r\n    if (!provider) return this.rejectEncryption(`Encryption provider \\`${selected}\\` is not registered locally.`);\r\n\r\n    this.encryptionProvider = provider;\r\n    return true;\r\n  }\r\n\r\n  private rejectEncryption(message: string): false {\r\n    try {\r\n      this.sendAuthData(EpAuthPacketMethod.ErrorMustEncrypt, message);\r\n    } catch {\r\n      /* best effort */\r\n    }\r\n    this.failAuthentication(message, true);\r\n    return false;\r\n  }\r\n\r\n  /**\r\n   * Once a session key and negotiated provider are available, derive the\r\n   * session cipher (port of C# `PrepareSessionEncryption`). Async only\r\n   * because {@link IEncryptionProvider.createCipher} may need to resolve a\r\n   * Node-only crypto module once per session — see `AesEncryptionProvider.ts`.\r\n   */\r\n  private async prepareSessionEncryption(): Promise<void> {\r\n    if (this.encryptionMode === EncryptionMode.None || this.symetricCipher) return;\r\n    if (!this.sessionKey || this.sessionKey.length === 0)\r\n      throw new Error(\"The authentication provider did not derive a session key for encryption.\");\r\n    if (!this.encryptionProvider) throw new Error(\"No encryption provider was negotiated.\");\r\n\r\n    const initiator = this.direction === \"initiator\";\r\n    const initiatorNonce = asBytes(\r\n      initiator\r\n        ? this.localHeaders.get(EpAuthPacketHeader.CipherNonce)\r\n        : this.remoteHeaders.get(EpAuthPacketHeader.CipherNonce),\r\n    );\r\n    const responderNonce = asBytes(\r\n      initiator\r\n        ? this.remoteHeaders.get(EpAuthPacketHeader.CipherNonce)\r\n        : this.localHeaders.get(EpAuthPacketHeader.CipherNonce),\r\n    );\r\n    if (!initiatorNonce || !responderNonce) throw new Error(\"Missing negotiated cipher nonce.\");\r\n\r\n    const offeredProtocols = initiator\r\n      ? this.offeredEncryptionProviders\r\n      : asStringArray(this.remoteHeaders.get(EpAuthPacketHeader.SupportedCiphers));\r\n    const authenticationProtocol = initiator\r\n      ? this.authenticationHandler?.protocol\r\n      : String(this.remoteHeaders.get(EpAuthPacketHeader.AuthenticationProtocol) ?? \"\");\r\n    const selectedProtocol = String(\r\n      initiator\r\n        ? this.remoteHeaders.get(EpAuthPacketHeader.CipherType)\r\n        : this.localHeaders.get(EpAuthPacketHeader.CipherType),\r\n    );\r\n\r\n    const context: EncryptionContext = {\r\n      key: this.sessionKey,\r\n      direction: initiator ? AuthenticationDirection.Initiator : AuthenticationDirection.Responder,\r\n      mode: this.encryptionMode,\r\n      protocol: selectedProtocol,\r\n      offeredProtocols,\r\n      authenticationMode: this.authenticationMode,\r\n      authenticationProtocol: authenticationProtocol ?? \"\",\r\n      domain: initiator ? this.domain : String(this.remoteHeaders.get(EpAuthPacketHeader.Domain) ?? \"\"),\r\n      initiatorNonce,\r\n      responderNonce,\r\n    };\r\n\r\n    this.symetricCipher = await this.encryptionProvider.createCipher(context);\r\n  }\r\n\r\n  /** Turn on record protection for both directions once the cipher is ready. */\r\n  private enableEncryption(): void {\r\n    if (!this.symetricCipher) throw new Error(\"Cannot enable encryption before creating a cipher.\");\r\n    this.decryptInbound = true;\r\n    this.encryptionActive = true;\r\n  }\r\n\r\n  /** Handle an auth-phase packet. */\r\n  private handleAuthPacket(packet: EpAuthPacket): void {\r\n    try {\r\n      if (packet.command === EpAuthPacketCommand.Initialize) {\r\n        this.handleAuthInitialize(packet);\r\n      } else if (packet.command === EpAuthPacketCommand.Acknowledge) {\r\n        this.handleAuthAcknowledge(packet);\r\n      } else if (packet.command === EpAuthPacketCommand.Action) {\r\n        this.handleAuthAction(packet);\r\n      } else if (packet.command === EpAuthPacketCommand.Event) {\r\n        this.handleAuthEvent(packet);\r\n      }\r\n    } catch (e) {\r\n      this.failAuthentication(e);\r\n    }\r\n  }\r\n\r\n  private handleAuthInitialize(packet: EpAuthPacket): void {\r\n    const { headers: remoteHeaders, authData: remoteAuthData } = this.parseAuthHeaders(packet);\r\n    this.remoteHeaders.clear();\r\n    for (const [key, value] of remoteHeaders) this.remoteHeaders.set(key, value);\r\n\r\n    const localHeaders = new Map(this.localHeaders);\r\n\r\n    if (!this.negotiateEncryptionAsResponder(localHeaders)) return;\r\n\r\n    if (packet.authMode === AuthenticationMode.None) {\r\n      if (!this.allowUnauthorized) {\r\n        this.sendAuthData(EpAuthPacketMethod.ErrorTerminate, \"Unauthorized access not allowed.\");\r\n        this.failAuthentication(\"Unauthorized access not allowed.\", true);\r\n        return;\r\n      }\r\n\r\n      this.sendAuthHeaders(EpAuthPacketMethod.SessionEstablished, localHeaders);\r\n      this.authenticationMode = AuthenticationMode.None;\r\n      this.completeAuthentication(nullResult());\r\n      return;\r\n    }\r\n\r\n    const protocol = this.remoteHeaders.get(EpAuthPacketHeader.AuthenticationProtocol);\r\n    if (typeof protocol !== \"string\") {\r\n      this.sendAuthHeaders(EpAuthPacketMethod.NotSupported, localHeaders);\r\n      this.failAuthentication(\"Authentication protocol is missing.\", true);\r\n      return;\r\n    }\r\n\r\n    const provider =\r\n      this.warehouse?.tryGetAuthenticationProvider(protocol) ??\r\n      (this.authenticationProvider?.defaultName === protocol ? this.authenticationProvider : undefined);\r\n    if (!provider) {\r\n      this.sendAuthHeaders(EpAuthPacketMethod.NotSupported, localHeaders);\r\n      this.failAuthentication(\"Authentication provider not found.\", true);\r\n      return;\r\n    }\r\n\r\n    this.authenticationMode = packet.authMode;\r\n    this.authenticationProtocol = protocol;\r\n    this.authenticationProvider = provider;\r\n    const handler = provider.createAuthenticationHandler({\r\n      direction: AuthenticationDirection.Responder,\r\n      mode: packet.authMode,\r\n      domain: String(this.remoteHeaders.get(EpAuthPacketHeader.Domain) ?? this.domain ?? \"\"),\r\n      hostName: this.hostName,\r\n      materials: [{ type: AuthenticationMaterialType.Data, value: remoteAuthData }],\r\n    });\r\n    if (!handler) {\r\n      this.sendAuthHeaders(EpAuthPacketMethod.NotSupported, localHeaders);\r\n      this.failAuthentication(\"Authentication handler not found.\", true);\r\n      return;\r\n    }\r\n\r\n    this.authenticationHandler = handler;\r\n    const authResult = handler.process(remoteAuthData);\r\n    localHeaders.set(EpAuthPacketHeader.AuthenticationData, authResult.authenticationData);\r\n\r\n    if (authResult.ruling === AuthenticationRuling.Failed) {\r\n      this.sendAuthHeaders(EpAuthPacketMethod.Denied, localHeaders);\r\n      this.failAuthentication(\"Authentication failed.\", true);\r\n    } else if (authResult.ruling === AuthenticationRuling.InProgress) {\r\n      this.sendAuthHeaders(EpAuthPacketMethod.ProceedToHandshake, localHeaders);\r\n    } else {\r\n      this.sendAuthHeaders(EpAuthPacketMethod.SessionEstablished, localHeaders);\r\n      this.completeAuthentication(authResult);\r\n    }\r\n  }\r\n\r\n  private handleAuthAcknowledge(packet: EpAuthPacket): void {\r\n    if (this.authenticationMode === AuthenticationMode.None) {\r\n      if (packet.method === EpAuthPacketMethod.SessionEstablished) {\r\n        this.completeAuthentication(nullResult());\r\n      } else {\r\n        this.failAuthentication(this.readAuthErrorMessage(packet), true);\r\n      }\r\n      return;\r\n    }\r\n\r\n    if (\r\n      packet.method === EpAuthPacketMethod.Denied ||\r\n      packet.method === EpAuthPacketMethod.NotSupported\r\n    ) {\r\n      this.failAuthentication(this.readAuthErrorMessage(packet), true);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      packet.method !== EpAuthPacketMethod.ProceedToHandshake &&\r\n      packet.method !== EpAuthPacketMethod.ProceedToFinalHandshake &&\r\n      packet.method !== EpAuthPacketMethod.SessionEstablished\r\n    ) {\r\n      return;\r\n    }\r\n\r\n    const { headers: remoteHeaders, authData: remoteAuthData } = this.parseAuthHeaders(packet);\r\n    this.remoteHeaders.clear();\r\n    for (const [key, value] of remoteHeaders) this.remoteHeaders.set(key, value);\r\n\r\n    if (!this.acceptEncryptionAsInitiator()) return;\r\n\r\n    const authResult = this.requireAuthenticationHandler().process(remoteAuthData);\r\n    if (authResult.ruling === AuthenticationRuling.Failed) {\r\n      this.failAuthentication(\"Authentication failed.\");\r\n    } else if (authResult.ruling === AuthenticationRuling.InProgress) {\r\n      if (packet.method === EpAuthPacketMethod.ProceedToHandshake)\r\n        this.sendAuthData(EpAuthPacketMethod.Handshake, authResult.authenticationData);\r\n      else\r\n        this.failAuthentication(\"Bad authentication protocol sequence.\");\r\n    } else {\r\n      this.storeAuthenticationResult(authResult);\r\n      if (packet.method === EpAuthPacketMethod.SessionEstablished) {\r\n        this.completeAuthentication(authResult);\r\n      } else {\r\n        this.sendAuthData(EpAuthPacketMethod.FinalHandshake, authResult.authenticationData);\r\n      }\r\n    }\r\n  }\r\n\r\n  private handleAuthAction(packet: EpAuthPacket): void {\r\n    if (\r\n      packet.method !== EpAuthPacketMethod.Handshake &&\r\n      packet.method !== EpAuthPacketMethod.FinalHandshake\r\n    ) {\r\n      return;\r\n    }\r\n\r\n    const authData = this.decodeAuthValue(packet);\r\n    const authResult = this.requireAuthenticationHandler().process(authData);\r\n    if (authResult.ruling === AuthenticationRuling.Failed) {\r\n      this.failAuthentication(\"Authentication failed.\");\r\n    } else if (authResult.ruling === AuthenticationRuling.InProgress) {\r\n      this.sendAuthData(EpAuthPacketMethod.Handshake, authResult.authenticationData);\r\n    } else {\r\n      this.storeAuthenticationResult(authResult);\r\n      if (authResult.authenticationData != null) {\r\n        this.sendAuthData(EpAuthPacketMethod.FinalHandshake, authResult.authenticationData);\r\n      }\r\n\r\n      if (packet.method === EpAuthPacketMethod.FinalHandshake || authResult.authenticationData == null) {\r\n        this.sendAuth(EpAuthPacketMethod.Established);\r\n        this.completeAuthentication(authResult);\r\n      }\r\n    }\r\n  }\r\n\r\n  private handleAuthEvent(packet: EpAuthPacket): void {\r\n    if (packet.method === EpAuthPacketMethod.Established) {\r\n      if (this.authSessionEstablished) this.completeAuthentication();\r\n      else this.failAuthentication(\"Authentication error.\");\r\n    } else if (\r\n      packet.method === EpAuthPacketMethod.ErrorTerminate ||\r\n      packet.method === EpAuthPacketMethod.ErrorMustEncrypt ||\r\n      packet.method === EpAuthPacketMethod.ErrorRetry\r\n    ) {\r\n      this.failAuthentication(this.readAuthErrorMessage(packet), true);\r\n    }\r\n  }\r\n\r\n  private getOrCreateInitiatorAuthenticationHandler(): IAuthenticationHandler {\r\n    if (this.authenticationHandler) return this.authenticationHandler;\r\n\r\n    const provider =\r\n      this.authenticationProvider ??\r\n      this.warehouse?.tryGetAuthenticationProvider(this.authenticationProtocol);\r\n    if (!provider)\r\n      throw new AsyncException(\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n        \"Authentication provider not found.\",\r\n      );\r\n\r\n    const handler = provider.createAuthenticationHandler({\r\n      direction: AuthenticationDirection.Initiator,\r\n      mode: this.authenticationMode,\r\n      domain: this.domain,\r\n      hostName: this.hostName,\r\n      initiatorIdentity: this.localIdentity,\r\n      responderIdentity: this.responderIdentity,\r\n    });\r\n    if (!handler)\r\n      throw new AsyncException(\r\n        ErrorType.Management,\r\n        ExceptionCode.NotSupported,\r\n        \"Authentication handler not found.\",\r\n      );\r\n\r\n    this.authenticationProvider = provider;\r\n    this.authenticationHandler = handler;\r\n    return handler;\r\n  }\r\n\r\n  private requireAuthenticationHandler(): IAuthenticationHandler {\r\n    if (!this.authenticationHandler)\r\n      throw new AsyncException(\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n        \"Authentication handler is not initialized.\",\r\n      );\r\n    return this.authenticationHandler;\r\n  }\r\n\r\n  private composeAuthHeaders(headers: Map<EpAuthPacketHeader, unknown>): Uint8Array {\r\n    return compose(\r\n      typedMap(\r\n        t.u8,\r\n        t.dynamic,\r\n        [...headers.entries()].map(([key, value]) => [u8(key), value] as const),\r\n      ),\r\n      this.warehouse,\r\n      this,\r\n    );\r\n  }\r\n\r\n  private sendAuth(method: EpAuthPacketMethod): void {\r\n    this.send(EpAuthPacket.composeMethod(method));\r\n  }\r\n\r\n  private sendAuthData(method: EpAuthPacketMethod, data: unknown): void {\r\n    const tdu = data == null ? undefined : compose(data, this.warehouse, this);\r\n    this.send(EpAuthPacket.composeMethod(method, tdu));\r\n  }\r\n\r\n  private sendAuthHeaders(\r\n    method: EpAuthPacketMethod,\r\n    headers: Map<EpAuthPacketHeader, unknown>,\r\n  ): void {\r\n    this.send(EpAuthPacket.composeMethod(method, this.composeAuthHeaders(headers)));\r\n  }\r\n\r\n  private parseAuthHeaders(packet: EpAuthPacket): {\r\n    headers: Map<EpAuthPacketHeader, unknown>;\r\n    authData: unknown;\r\n  } {\r\n    const value = this.decodeAuthValue(packet);\r\n    const headers = new Map<EpAuthPacketHeader, unknown>();\r\n    let authData: unknown = null;\r\n    if (value == null) return { headers, authData };\r\n    if (!(value instanceof Map))\r\n      throw new AsyncException(\r\n        ErrorType.Management,\r\n        ExceptionCode.ParseError,\r\n        \"Authentication headers must be a map.\",\r\n      );\r\n\r\n    for (const [rawKey, headerValue] of value.entries()) {\r\n      const key = Number(rawKey) as EpAuthPacketHeader;\r\n      if (key === EpAuthPacketHeader.AuthenticationData) authData = headerValue;\r\n      else headers.set(key, headerValue);\r\n    }\r\n\r\n    return { headers, authData };\r\n  }\r\n\r\n  private decodeAuthValue(packet: EpAuthPacket): unknown {\r\n    if (!packet.tdu) return null;\r\n    return parse(packet.tdu.data, packet.tdu.tduOffset, this.warehouse);\r\n  }\r\n\r\n  private readAuthErrorMessage(packet: EpAuthPacket): string {\r\n    const fallback = \"Authentication error.\";\r\n    try {\r\n      const value = this.decodeAuthValue(packet);\r\n      if (typeof value === \"string\") return value;\r\n      if (value instanceof Map) {\r\n        const msg = value.get(EpAuthPacketHeader.ErrorMessage);\r\n        if (msg != null) return String(msg);\r\n      }\r\n    } catch {\r\n      /* keep fallback */\r\n    }\r\n    return fallback;\r\n  }\r\n\r\n  private storeAuthenticationResult(result: AuthenticationResult): void {\r\n    this.authSessionEstablished = true;\r\n    this.localIdentity = result.localIdentity;\r\n    this.remoteIdentity = result.remoteIdentity;\r\n    this.sessionKey = result.sessionKey;\r\n  }\r\n\r\n  private completeAuthentication(result?: AuthenticationResult | null): void {\r\n    if (result) this.storeAuthenticationResult(result);\r\n    this.authSessionEstablished = true;\r\n\r\n    if (this.encryptionMode === EncryptionMode.None) {\r\n      this.finishAuthenticationReady();\r\n      return;\r\n    }\r\n\r\n    // Every call site above has already sent its final plaintext auth\r\n    // message (SessionEstablished/Established) before reaching this point,\r\n    // so it's safe to derive the cipher and flip to encrypted transport here\r\n    // — nothing more goes out unencrypted after readiness is published.\r\n    void this.prepareSessionEncryption()\r\n      .then(() => {\r\n        this.enableEncryption();\r\n        this.finishAuthenticationReady();\r\n      })\r\n      .catch((e) => this.failAuthentication(e));\r\n  }\r\n\r\n  private finishAuthenticationReady(): void {\r\n    this.authenticated = true;\r\n    this.readyReply?.trigger(true);\r\n    this.authenticationProvider?.login?.(this.getAuthenticationSession());\r\n  }\r\n\r\n  private failAuthentication(error: unknown, suppressSend = false): void {\r\n    const exception =\r\n      error instanceof AsyncException\r\n        ? error\r\n        : new AsyncException(ErrorType.Management, ExceptionCode.AccessDenied, String(error));\r\n    this.readyReply?.triggerError(exception);\r\n    if (!suppressSend) this.sendAuthData(EpAuthPacketMethod.ErrorTerminate, exception.message);\r\n    this.close();\r\n  }\r\n\r\n  private getAuthenticationSession(): AuthenticationSession {\r\n    return {\r\n      authenticationMode: this.authenticationMode,\r\n      localHeaders: this.localHeaders,\r\n      remoteHeaders: this.remoteHeaders,\r\n      localIdentity: this.localIdentity,\r\n      remoteIdentity: this.remoteIdentity,\r\n      key: this.sessionKey,\r\n      authenticated: this.authenticated,\r\n      variables: this.variables,\r\n      encryptionMode: this.encryptionMode,\r\n      encryptionProvider: this.encryptionProvider,\r\n      symetricCipher: this.symetricCipher,\r\n      encryptionActive: this.encryptionActive,\r\n    };\r\n  }\r\n\r\n  // ---- outbound ---------------------------------------------------------------\r\n\r\n  /** Send a request and return a reply that settles when the peer responds. */\r\n  sendRequest(action: EpPacketRequest, ...args: unknown[]): AsyncReply {\r\n    const reply = new AsyncReply();\r\n    const callbackId = ++this.callbackCounter;\r\n    this.requests.set(callbackId, reply);\r\n    this.send(EpPacket.composeRequest(action, callbackId, this.composeArgs(args)));\r\n    return reply;\r\n  }\r\n\r\n  /** Invoke function `index` on the resource with `instanceId`, resolving its result. */\r\n  invoke(instanceId: number, index: number, ...args: unknown[]): AsyncReply {\r\n    // The member index is a byte (UInt8) on the wire — C# casts it as `(byte)`.\r\n    return this.sendRequest(EpPacketRequest.InvokeFunction, instanceId, u8(index), args);\r\n  }\r\n\r\n  /** Invoke a `static` exported function `index` on TypeDef `typeId` — no resource instance involved. */\r\n  staticCall(typeId: number, index: number, ...args: unknown[]): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.StaticCall, typeId, u8(index), args);\r\n  }\r\n\r\n  /**\r\n   * Send a stream-flavored request: the callback id also drives\r\n   * `PullStream`/`TerminateExecution`/`HaltExecution`/`ResumeExecution`\r\n   * against the same remote invocation via the returned {@link AsyncStreamReply}.\r\n   */\r\n  sendStreamRequest<T = unknown>(\r\n    streamMode: StreamMode,\r\n    action: EpPacketRequest,\r\n    ...args: unknown[]\r\n  ): AsyncStreamReply<T> {\r\n    const callbackId = ++this.callbackCounter;\r\n    const reply = new AsyncStreamReply<T>(\r\n      streamMode,\r\n      () => this.sendRequest(EpPacketRequest.PullStream, callbackId),\r\n      () => this.sendRequest(EpPacketRequest.TerminateExecution, callbackId),\r\n      () => this.sendRequest(EpPacketRequest.HaltExecution, callbackId),\r\n      () => this.sendRequest(EpPacketRequest.ResumeExecution, callbackId),\r\n    );\r\n    this.requests.set(callbackId, reply);\r\n    this.send(EpPacket.composeRequest(action, callbackId, this.composeArgs(args)));\r\n    return reply;\r\n  }\r\n\r\n  /** Invoke a streaming function `index` on the resource with `instanceId`. */\r\n  invokeStream<T = unknown>(\r\n    streamMode: StreamMode,\r\n    instanceId: number,\r\n    index: number,\r\n    ...args: unknown[]\r\n  ): AsyncStreamReply<T> {\r\n    return this.sendStreamRequest<T>(\r\n      streamMode,\r\n      EpPacketRequest.InvokeFunction,\r\n      instanceId,\r\n      u8(index),\r\n      args,\r\n    );\r\n  }\r\n\r\n  /** Invoke function `index` with an already-shaped argument payload. */\r\n  invokeWithArguments(instanceId: number, index: number, args: unknown): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.InvokeFunction, instanceId, u8(index), args ?? []);\r\n  }\r\n\r\n  /** Set property `index` on the resource with `instanceId`. */\r\n  set(instanceId: number, index: number, value: unknown): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.SetProperty, instanceId, u8(index), value);\r\n  }\r\n\r\n  /**\r\n   * Subscribe to event `index` on the resource with `instanceId` — required\r\n   * before the server pushes `EventOccurred` notifications for events where\r\n   * {@link RemoteEventDef.subscribable} is true (`autoDelivered` events are\r\n   * pushed unconditionally and never need this). The server errors\r\n   * (`AlreadyListened`) on a duplicate call for an already-subscribed event,\r\n   * so callers must track subscription state themselves — see\r\n   * {@link EpResource.on}, which does this per-event, ref-counted by listener\r\n   * count, rather than sending on every call.\r\n   */\r\n  subscribe(instanceId: number, index: number): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.Subscribe, instanceId, u8(index));\r\n  }\r\n\r\n  /** Unsubscribe from event `index` on the resource with `instanceId`. See {@link subscribe}. */\r\n  unsubscribe(instanceId: number, index: number): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.Unsubscribe, instanceId, u8(index));\r\n  }\r\n\r\n  /** Resolve a resource path to a {@link ResourceId} reference. */\r\n  getResourceIdByLink(link: string): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.GetResourceIdByLink, link);\r\n  }\r\n\r\n  /** Stop receiving notifications for a resource on this connection (it keeps living for other subscribers). */\r\n  detach(instanceId: number): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.DetachResource, instanceId);\r\n  }\r\n\r\n  /** Rename a resource (single path segment — no `/`). */\r\n  moveResource(instanceId: number, newName: string): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.MoveResource, instanceId, newName);\r\n  }\r\n\r\n  /** Remove a resource from the peer's warehouse. */\r\n  deleteResource(instanceId: number): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.DeleteResource, instanceId);\r\n  }\r\n\r\n  /**\r\n   * Create a resource of a type already registered on the peer's warehouse.\r\n   * `properties` is keyed by wire property index; replies with the new\r\n   * resource's instance id.\r\n   */\r\n  createResource(\r\n    path: string,\r\n    typeIdOrName: number | string,\r\n    properties?: Map<number, unknown>,\r\n    attributes?: Map<string, unknown>,\r\n  ): AsyncReply<number> {\r\n    return this.sendRequest(\r\n      EpPacketRequest.CreateResource,\r\n      path,\r\n      typeIdOrName,\r\n      properties ?? new Map<number, unknown>(),\r\n      attributes ?? new Map<string, unknown>(),\r\n    ).then((reply) => Number(reply));\r\n  }\r\n\r\n  /**\r\n   * Resolve a resource path, replying with its children as `[id, link]`\r\n   * pairs (see `epRequestQueryResources`'s doc comment for why this isn't\r\n   * full auto-attaching resource references, unlike dotnet's `Query`).\r\n   * Distinct from {@link getResourceIdByLink}, which resolves a single link.\r\n   */\r\n  queryResources(path: string): AsyncReply<Array<[number, string]>> {\r\n    return this.sendRequest(EpPacketRequest.Query, path).then(\r\n      (reply) => (reply as Array<[number, string]>) ?? [],\r\n    );\r\n  }\r\n\r\n  /** Bulk-fetch a resource type's full TypeDef dependency graph in one round trip. */\r\n  fetchLinkedTypeDefs(path: string): AsyncReply<RemoteTypeDef[]> {\r\n    return this.sendRequest(EpPacketRequest.LinkTypeDefs, path).then(async (reply) => {\r\n      const payloads = (reply as unknown[]) ?? [];\r\n      const results: RemoteTypeDef[] = [];\r\n      for (const p of payloads) {\r\n        const data = this.expectTypeDefPayload(p, \"LinkTypeDefs did not return raw TypeDef payloads.\");\r\n        results.push(await this.parseTypeDefPayload(data, null));\r\n      }\r\n      return results;\r\n    });\r\n  }\r\n\r\n  /** Fetch and parse the runtime TypeDef for a remote resource id. */\r\n  fetchTypeDefByResourceId(instanceId: number): AsyncReply<RemoteTypeDef> {\r\n    return this.sendRequest(EpPacketRequest.TypeDefByResourceId, instanceId).then((reply) => {\r\n      const data = this.expectTypeDefPayload(\r\n        reply,\r\n        \"TypeDefByResourceId did not return a raw TypeDef payload.\",\r\n      );\r\n      return this.parseTypeDefPayload(data, null);\r\n    });\r\n  }\r\n\r\n  /** Fetch and parse a runtime TypeDef by its remote TypeDef id. */\r\n  fetchTypeDefById(typeDefId: number): AsyncReply<RemoteTypeDef> {\r\n    return this.fetchTypeDef(typeDefId, null);\r\n  }\r\n\r\n  /** Batch-resolve full class names to their remote TypeDef ids. */\r\n  getTypeDefIds(fullNames: string[]): AsyncReply<number[]> {\r\n    return this.sendRequest(EpPacketRequest.TypeDefIdsByNames, fullNames).then((reply) => {\r\n      if (!Array.isArray(reply))\r\n        throw new AsyncException(\r\n          ErrorType.Management,\r\n          ExceptionCode.ParseError,\r\n          \"TypeDefIdsByNames did not return an id array.\",\r\n        );\r\n      return reply.map((v) => Number(v));\r\n    });\r\n  }\r\n\r\n  /** Fetch and parse a runtime TypeDef by id, resolving cyclic remote TypeDef references. */\r\n  fetchTypeDef(\r\n    typeDefId: number,\r\n    requestSequence: readonly number[] | null = null,\r\n  ): AsyncReply<RemoteTypeDef> {\r\n    const cached = this.cachedTypeDefs.get(typeDefId);\r\n    if (cached) return AsyncReply.fromResult(cached);\r\n\r\n    const needed = this.neededTypeDefs.get(typeDefId);\r\n    const requestInfo = this.typeDefRequests.get(typeDefId);\r\n    const parent =\r\n      requestSequence && requestSequence.length > 0\r\n        ? requestSequence[requestSequence.length - 1]\r\n        : undefined;\r\n\r\n    if (requestInfo) {\r\n      if (needed && requestSequence?.includes(typeDefId))\r\n        return AsyncReply.fromResult(needed);\r\n\r\n      if (needed && this.hasTypeDefWaitForCycle(typeDefId, requestSequence))\r\n        return AsyncReply.fromResult(needed);\r\n\r\n      if (parent != null) this.addTypeDefFetchBlock(parent, typeDefId);\r\n      return requestInfo.reply;\r\n    }\r\n\r\n    const newSequence = requestSequence ? [...requestSequence, typeDefId] : [typeDefId];\r\n    const reply = new AsyncReply<RemoteTypeDef>();\r\n    this.typeDefRequests.set(typeDefId, { reply, requestSequence: newSequence });\r\n\r\n    if (parent != null) this.addTypeDefFetchBlock(parent, typeDefId);\r\n\r\n    this.sendRequest(EpPacketRequest.TypeDefById, typeDefId)\r\n      .onReady((result) => {\r\n        void (async () => {\r\n          try {\r\n            const data = this.expectTypeDefPayload(\r\n              result,\r\n              \"TypeDefById did not return a raw TypeDef payload.\",\r\n            );\r\n            const typeDef = await this.finishTypeDefRequest(typeDefId, data, newSequence);\r\n            reply.trigger(typeDef);\r\n          } catch (e) {\r\n            this.typeDefRequests.delete(typeDefId);\r\n            this.neededTypeDefs.delete(typeDefId);\r\n            this.clearTypeDefFetchNode(typeDefId);\r\n            reply.triggerError(AsyncException.from(e));\r\n          }\r\n        })();\r\n      })\r\n      .error((ex) => {\r\n        this.typeDefRequests.delete(typeDefId);\r\n        this.clearTypeDefFetchNode(typeDefId);\r\n        reply.triggerError(ex);\r\n      });\r\n\r\n    return reply;\r\n  }\r\n\r\n  private expectTypeDefPayload(value: unknown, message: string): Uint8Array {\r\n    if (value instanceof Uint8Array) return value;\r\n    throw new AsyncException(ErrorType.Management, ExceptionCode.ParseError, message);\r\n  }\r\n\r\n  private parseTypeDefPayload(\r\n    data: Uint8Array,\r\n    requestSequence: readonly number[] | null,\r\n  ): AsyncReply<RemoteTypeDef> {\r\n    const typeDefId = readTypeDefPayloadId(data, this.warehouse);\r\n    const cached = this.cachedTypeDefs.get(typeDefId);\r\n    if (cached) return AsyncReply.fromResult(cached);\r\n\r\n    const pending = this.typeDefRequests.get(typeDefId);\r\n    if (pending) return pending.reply;\r\n\r\n    const newSequence = requestSequence ? [...requestSequence, typeDefId] : [typeDefId];\r\n    const reply = new AsyncReply<RemoteTypeDef>();\r\n    this.typeDefRequests.set(typeDefId, { reply, requestSequence: newSequence });\r\n\r\n    void (async () => {\r\n      try {\r\n        const typeDef = await this.finishTypeDefRequest(typeDefId, data, newSequence);\r\n        reply.trigger(typeDef);\r\n      } catch (e) {\r\n        reply.triggerError(AsyncException.from(e));\r\n      }\r\n    })();\r\n\r\n    return reply;\r\n  }\r\n\r\n  private async finishTypeDefRequest(\r\n    typeDefId: number,\r\n    data: Uint8Array,\r\n    requestSequence: readonly number[],\r\n  ): Promise<RemoteTypeDef> {\r\n    const placeholder = this.neededTypeDefs.get(typeDefId) ?? new RemoteTypeDef();\r\n    this.neededTypeDefs.set(typeDefId, placeholder);\r\n    try {\r\n      const typeDef = await RemoteTypeDef.parseAsyncInto(\r\n        placeholder,\r\n        data,\r\n        this.warehouse,\r\n        (id, sequence) => this.fetchTypeDef(id, sequence),\r\n        requestSequence,\r\n      );\r\n      this.cachedTypeDefs.set(typeDefId, typeDef);\r\n      if (typeDef.id !== typeDefId) this.cachedTypeDefs.set(typeDef.id, typeDef);\r\n      return typeDef;\r\n    } finally {\r\n      this.typeDefRequests.delete(typeDefId);\r\n      this.neededTypeDefs.delete(typeDefId);\r\n      this.clearTypeDefFetchNode(typeDefId);\r\n    }\r\n  }\r\n\r\n  private addTypeDefFetchBlock(parent: number, child: number): void {\r\n    let children = this.typeDefsFetchBlockedOn.get(parent);\r\n    if (!children) {\r\n      children = new Set<number>();\r\n      this.typeDefsFetchBlockedOn.set(parent, children);\r\n    }\r\n    children.add(child);\r\n  }\r\n\r\n  private clearTypeDefFetchNode(typeDefId: number): void {\r\n    this.typeDefsFetchBlockedOn.delete(typeDefId);\r\n    for (const children of this.typeDefsFetchBlockedOn.values())\r\n      children.delete(typeDefId);\r\n  }\r\n\r\n  private hasTypeDefWaitForCycle(\r\n    typeDefId: number,\r\n    requestSequence: readonly number[] | null,\r\n  ): boolean {\r\n    if (!requestSequence || requestSequence.length === 0) return false;\r\n\r\n    const chain = new Set(requestSequence);\r\n    const visited = new Set<number>();\r\n    const stack = [typeDefId];\r\n    while (stack.length > 0) {\r\n      const current = stack.pop();\r\n      if (current == null) continue;\r\n      if (visited.has(current)) continue;\r\n      visited.add(current);\r\n\r\n      const children = this.typeDefsFetchBlockedOn.get(current);\r\n      if (!children) continue;\r\n\r\n      for (const child of children) {\r\n        if (chain.has(child)) return true;\r\n        stack.push(child);\r\n      }\r\n    }\r\n    return false;\r\n  }\r\n\r\n  /**\r\n   * Resolve and attach a remote resource by its path on this connection. When\r\n   * `typeDef` is omitted, its TypeDef is fetched from the server first (one\r\n   * extra round trip) — mirrors dotnet's `Get<T>`, which never needs a\r\n   * caller-supplied type because C# generates the proxy dynamically.\r\n   */\r\n  get<T extends EpResource = EpResource>(\r\n    path: string,\r\n    target?: EpResourceAttachTarget<T>,\r\n  ): AsyncReply {\r\n    return this.getResourceIdByLink(path).then((resourceRef) => {\r\n      const instanceId = toInstanceId(resourceRef);\r\n      if (instanceId == null)\r\n        throw new AsyncException(\r\n          ErrorType.Management,\r\n          ExceptionCode.ResourceNotFound,\r\n          `Remote resource '${path}' was not found.`,\r\n        );\r\n      return this.attach(instanceId, target);\r\n    });\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link get}. */\r\n  Get<T extends EpResource = EpResource>(\r\n    path: string,\r\n    target?: EpResourceAttachTarget<T>,\r\n  ): AsyncReply {\r\n    return this.get(path, target);\r\n  }\r\n\r\n  /** Reopen the WebSocket session and reattach all known remote resources. */\r\n  reconnect(): AsyncReply<boolean> {\r\n    if (!this.reconnectUrl) {\r\n      const reply = new AsyncReply<boolean>();\r\n      reply.triggerError(\r\n        new AsyncException(ErrorType.Management, ExceptionCode.HostNotReachable, \"No reconnect URL.\"),\r\n      );\r\n      return reply;\r\n    }\r\n    if (this.reconnectReply) return this.reconnectReply;\r\n\r\n    const reply = new AsyncReply<boolean>();\r\n    this.reconnectReply = reply;\r\n    (async () => {\r\n      const started = nowMs();\r\n      try {\r\n        await this.openClientSocket(this.reconnectUrl!);\r\n        const connected = nowMs();\r\n        await this.restoreAttachedResources();\r\n        const finished = nowMs();\r\n        this.lastReconnectMetrics = {\r\n          connectMs: connected - started,\r\n          reattachMs: finished - connected,\r\n          recoveryMs: finished - started,\r\n          restoredResources: this.lastRestoreStats.restored,\r\n          failedResources: this.lastRestoreStats.failed,\r\n        };\r\n        reply.trigger(true);\r\n      } catch (e) {\r\n        reply.triggerError(AsyncException.from(e));\r\n      } finally {\r\n        if (this.reconnectReply === reply) this.reconnectReply = undefined;\r\n      }\r\n    })();\r\n    return reply;\r\n  }\r\n\r\n  /**\r\n   * Attach to a remote resource, returning a live {@link EpResource}. Passing\r\n   * a generated EpResource subclass instantiates that class; passing a TypeDef\r\n   * keeps the dynamic-proxy behavior.\r\n   */\r\n  attach(instanceId: number): AsyncReply<any>;\r\n  attach(instanceId: number, typeDef: TypeDef): AsyncReply<any>;\r\n  attach<T extends EpResource>(\r\n    instanceId: number,\r\n    ctor: EpResourceConstructor<T>,\r\n  ): AsyncReply<T & Record<string, any>>;\r\n  attach<T extends EpResource>(\r\n    instanceId: number,\r\n    target?: EpResourceAttachTarget<T>,\r\n  ): AsyncReply<any>;\r\n  attach<T extends EpResource>(\r\n    instanceId: number,\r\n    target?: EpResourceAttachTarget<T>,\r\n  ): AsyncReply {\r\n    const resolved = this.resolveAttachTarget(target);\r\n    if (resolved.typeDef)\r\n      return this.attachWithTypeDef(instanceId, resolved.typeDef, resolved.ctor);\r\n\r\n    return this.fetchTypeDefByResourceId(instanceId).then((remoteTypeDef) => {\r\n      const ctor = resolved.ctor ?? this.findProxyType(remoteTypeDef);\r\n      return this.attachWithTypeDef(instanceId, remoteTypeDef.template, ctor);\r\n    });\r\n  }\r\n\r\n  private attachWithTypeDef<T extends EpResource>(\r\n    instanceId: number,\r\n    typeDef: TypeDef,\r\n    ctor?: EpResourceConstructor<T>,\r\n  ): AsyncReply {\r\n    return this.sendRequest(EpPacketRequest.AttachResource, instanceId).then((reply) => {\r\n      // Reply: [typeDefId, age, link, hops, propertyValues] (matches C#). The\r\n      // 5th element is a RawData blob of (age, date, value) self-describing TDUs,\r\n      // one triple per property in index order.\r\n      const list = reply as unknown[];\r\n      const typeDefId = asNumber(list[0]);\r\n      const age = asNumber(list[1]);\r\n      const link = String(list[2] ?? \"\");\r\n      const hops = asNumber(list[3]);\r\n      const raw = list[4] as Uint8Array | undefined;\r\n\r\n      const resource = this.createAttachedResource(instanceId, typeDef, ctor, {\r\n        typeDefId,\r\n        age,\r\n        link,\r\n        hops,\r\n      });\r\n      if (raw) {\r\n        const snapshots = this.parsePropertyValueArray(raw, typeDef);\r\n        for (const pv of snapshots)\r\n          resource.setPropertySnapshot(pv.index, pv.age, pv.date, pv.value);\r\n      }\r\n\r\n      this.attachedResources.set(instanceId, resource);\r\n      return EpResource.createProxy(resource);\r\n    });\r\n  }\r\n\r\n  private resolveAttachTarget<T extends EpResource>(\r\n    target?: EpResourceAttachTarget<T>,\r\n  ): { typeDef?: TypeDef; ctor?: EpResourceConstructor<T> } {\r\n    if (!target) return {};\r\n    if (isTypeDef(target)) return { typeDef: target };\r\n\r\n    return {\r\n      ctor: target,\r\n      typeDef: getGeneratedTypeDef(target, this.warehouse),\r\n    };\r\n  }\r\n\r\n  private createAttachedResource<T extends EpResource>(\r\n    instanceId: number,\r\n    typeDef: TypeDef,\r\n    ctor: EpResourceConstructor<T> | undefined,\r\n    options: EpResourceOptions,\r\n  ): EpResource {\r\n    const resource = ctor\r\n      ? new ctor(this, instanceId, options.age ?? 0, options.link ?? \"\")\r\n      : new EpResource();\r\n    resource.initializeRemote(this, instanceId, typeDef, options);\r\n    return resource;\r\n  }\r\n\r\n  private findProxyType(typeDef: RemoteTypeDef): EpResourceConstructor | undefined {\r\n    return this.warehouse?.tryGetProxyType(\r\n      typeDef.kind,\r\n      this.domain || this.hostName || \"\",\r\n      typeDef.name,\r\n    ) as EpResourceConstructor | undefined;\r\n  }\r\n\r\n  /**\r\n   * Reattach an already-known resource by link or instance id, sending its\r\n   * last-known age. The peer returns only properties modified after that\r\n   * age. Prefer the link — the remote node may have freed/recreated the\r\n   * resource since, so its id is not permanent, but the link is. The reply\r\n   * leads with the resolved id so an id change (link re-resolved to a\r\n   * different instance) can be detected and tracking re-keyed.\r\n   */\r\n  reattach(resourceLinkOrId: string | number, age: number, resource: EpResource): AsyncReply<EpResource> {\r\n    return this.sendRequest(EpPacketRequest.ReattachResource, resourceLinkOrId, age).then((reply) => {\r\n      const list = reply as unknown[];\r\n      const oldId = resource.instanceId;\r\n      const resolvedId = asNumber(list[0]);\r\n      resource.setRemoteIdentity({\r\n        instanceId: resolvedId,\r\n        typeDefId: asNumber(list[1]),\r\n        age: asNumber(list[2]),\r\n        link: String(list[3] ?? \"\"),\r\n        hops: asNumber(list[4]),\r\n      });\r\n\r\n      const raw = list[5] as Uint8Array | undefined;\r\n      if (raw) resource.applyDelta(this.parsePropertyValueMap(raw));\r\n\r\n      if (resolvedId !== oldId) {\r\n        // Only evict oldId's entry if it still points to this resource —\r\n        // if the remote node reused oldId for something else in the\r\n        // meantime, a blind delete would wrongly evict that unrelated\r\n        // resource's own valid tracking.\r\n        if (this.attachedResources.get(oldId) === resource) this.attachedResources.delete(oldId);\r\n      }\r\n      this.attachedResources.set(resolvedId, resource);\r\n      return resource;\r\n    });\r\n  }\r\n\r\n  /** Send a reply to a peer request. */\r\n  sendReply(action: EpPacketReply, callbackId: number, ...args: unknown[]): void {\r\n    this.send(EpPacket.composeReply(action, callbackId, this.composeArgs(args)));\r\n  }\r\n\r\n  /** Send a notification (no reply expected). */\r\n  sendNotification(action: EpPacketNotification, ...args: unknown[]): void {\r\n    this.send(EpPacket.composeNotification(action, this.composeArgs(args)));\r\n  }\r\n\r\n  /** Send an error/warning reply. */\r\n  sendError(type: ErrorType, callbackId: number, code: number, message = \"\"): void {\r\n    if (type === ErrorType.Management)\r\n      this.sendReply(EpPacketReply.PermissionError, callbackId, code, message);\r\n    else if (type === ErrorType.Exception)\r\n      this.sendReply(EpPacketReply.ExecutionError, callbackId, code, message);\r\n    else this.sendReply(EpPacketReply.Warning, callbackId, code, message);\r\n  }\r\n\r\n  sendProgress(callbackId: number, value: number, max: number): void {\r\n    this.sendReply(EpPacketReply.Progress, callbackId, value, max);\r\n  }\r\n\r\n  /** Encode request/reply arguments: one value as-is, multiple as a list, none → no TDU. */\r\n  private composeArgs(args: unknown[]): Uint8Array | undefined {\r\n    if (args.length === 0) return undefined;\r\n    if (args.length === 1) return compose(args[0], this.warehouse, this);\r\n    return compose(args, this.warehouse, this);\r\n  }\r\n\r\n  private parsePropertyValueArray(raw: Uint8Array, typeDef: TypeDef): RemotePropertyValue[] {\r\n    const values: RemotePropertyValue[] = [];\r\n    let offset = 0;\r\n    for (const p of typeDef.properties) {\r\n      const age = parseSync(raw, offset, this.warehouse);\r\n      offset += age.length;\r\n      const date = parseSync(raw, offset, this.warehouse);\r\n      offset += date.length;\r\n      const value = parseSync(raw, offset, this.warehouse);\r\n      offset += value.length;\r\n      values.push({\r\n        index: p.index,\r\n        age: asNumber(age.value),\r\n        date: asDate(date.value),\r\n        value: value.value,\r\n      });\r\n    }\r\n    return values;\r\n  }\r\n\r\n  private parsePropertyValueMap(raw: Uint8Array): RemotePropertyValue[] {\r\n    const values: RemotePropertyValue[] = [];\r\n    let offset = 0;\r\n    while (offset < raw.length) {\r\n      const index = parseSync(raw, offset, this.warehouse);\r\n      offset += index.length;\r\n      const age = parseSync(raw, offset, this.warehouse);\r\n      offset += age.length;\r\n      const date = parseSync(raw, offset, this.warehouse);\r\n      offset += date.length;\r\n      const value = parseSync(raw, offset, this.warehouse);\r\n      offset += value.length;\r\n      values.push({\r\n        index: asNumber(index.value),\r\n        age: asNumber(age.value),\r\n        date: asDate(date.value),\r\n        value: value.value,\r\n      });\r\n    }\r\n    return values;\r\n  }\r\n\r\n  private composePropertyValueArray(instanceId: number): Uint8Array {\r\n    const resource = this.warehouse?.getById(instanceId);\r\n    if (!resource?.instance) return new Uint8Array(0);\r\n\r\n    const instance = resource.instance;\r\n    const dyn = isDynamicResource(resource) ? resource : undefined;\r\n    const bag = resource as unknown as Record<string, unknown>;\r\n    const parts: Uint8Array[] = [];\r\n    for (const p of instance.definition.properties) {\r\n      parts.push(compose(instance.getAge(p.index) ?? 0, this.warehouse, this));\r\n      parts.push(compose(instance.getModificationDate(p.index) ?? new Date(0), this.warehouse, this));\r\n      parts.push(compose(dyn ? dyn.getResourceProperty(p.index) : bag[p.name], this.warehouse, this));\r\n    }\r\n    return merge(...parts);\r\n  }\r\n\r\n  private composePropertyValueMap(instanceId: number, sinceAge: number): Uint8Array {\r\n    const resource = this.warehouse?.getById(instanceId);\r\n    if (!resource?.instance) return new Uint8Array(0);\r\n\r\n    const instance = resource.instance;\r\n    const dyn = isDynamicResource(resource) ? resource : undefined;\r\n    const bag = resource as unknown as Record<string, unknown>;\r\n    const parts: Uint8Array[] = [];\r\n    for (const p of instance.definition.properties) {\r\n      const propertyAge = instance.getAge(p.index) ?? 0;\r\n      if (propertyAge <= sinceAge) continue;\r\n      parts.push(compose(u8(p.index), this.warehouse, this));\r\n      parts.push(compose(propertyAge, this.warehouse, this));\r\n      parts.push(compose(instance.getModificationDate(p.index) ?? new Date(0), this.warehouse, this));\r\n      parts.push(compose(dyn ? dyn.getResourceProperty(p.index) : bag[p.name], this.warehouse, this));\r\n    }\r\n    return merge(...parts);\r\n  }\r\n\r\n  private async restoreAttachedResources(): Promise<void> {\r\n    const resources = [...this.attachedResources.values()];\r\n    const stats = { restored: 0, failed: 0 };\r\n    for (const resource of resources) {\r\n      try {\r\n        await this.reattach(resource.link || resource.instanceId, resource.age, resource);\r\n        resource.resubscribeAfterReconnect();\r\n        stats.restored++;\r\n      } catch (e) {\r\n        if (AsyncException.from(e).code === ExceptionCode.ResourceNotFound) {\r\n          stats.failed++;\r\n          continue;\r\n        }\r\n        throw e;\r\n      }\r\n    }\r\n    this.lastRestoreStats = stats;\r\n  }\r\n\r\n  // ---- outbound (encrypted transport) ------------------------------------------\r\n\r\n  private static readonly ENCRYPTED_RECORD_HEADER_SIZE = 4;\r\n\r\n  /**\r\n   * Wrap outbound bytes in an AES-GCM-protected record once encryption is\r\n   * active (port of C# `SendAsync`'s `ComposeEncryptedRecord` path):\r\n   * `[4-byte BE protected-length][cipher.encrypt(message)]`. Plain\r\n   * pass-through otherwise.\r\n   */\r\n  override send(message: Uint8Array): void {\r\n    if (!this.encryptionActive || !this.symetricCipher) {\r\n      super.send(message);\r\n      return;\r\n    }\r\n    const protectedPayload = this.symetricCipher.encrypt(message);\r\n    super.send(merge(uint32ToBytes(protectedPayload.length, Endian.Big), protectedPayload));\r\n  }\r\n\r\n  // ---- inbound ----------------------------------------------------------------\r\n\r\n  protected override dataReceived(buffer: NetworkBuffer): void {\r\n    const msg = buffer.read();\r\n    if (!msg) return;\r\n\r\n    let offset = 0;\r\n    const ends = msg.length;\r\n    while (offset < ends) {\r\n      if (this.decryptInbound) {\r\n        const remaining = ends - offset;\r\n        const headerSize = EpConnection.ENCRYPTED_RECORD_HEADER_SIZE;\r\n        if (remaining < headerSize) {\r\n          buffer.holdFor(msg, offset, remaining, headerSize);\r\n          return;\r\n        }\r\n\r\n        const protectedLength = getUint32(msg, offset, Endian.Big);\r\n        const totalLength = headerSize + protectedLength;\r\n        if (remaining < totalLength) {\r\n          buffer.holdFor(msg, offset, remaining, totalLength);\r\n          return;\r\n        }\r\n\r\n        const protectedPayload = msg.subarray(offset + headerSize, offset + totalLength);\r\n        offset += totalLength;\r\n\r\n        let plaintext: Uint8Array;\r\n        try {\r\n          plaintext = this.symetricCipher!.decrypt(protectedPayload);\r\n        } catch (e) {\r\n          this.failAuthentication(e, true);\r\n          this.close();\r\n          return;\r\n        }\r\n\r\n        this.dispatchPlaintext(plaintext);\r\n        continue;\r\n      }\r\n\r\n      // Auth phase: consume auth packets until the session is established; the\r\n      // handshake may finish mid-buffer and the rest continues as Ep packets.\r\n      if (!this.authenticated) {\r\n        const consumed = this.authPacket.parse(msg, offset, ends);\r\n        if (consumed <= 0) {\r\n          const size = ends - offset;\r\n          buffer.holdFor(msg, offset, size, size + -consumed);\r\n          return;\r\n        }\r\n        offset += consumed;\r\n        this.handleAuthPacket(this.authPacket);\r\n        continue;\r\n      }\r\n\r\n      const consumed = this.packet.parse(msg, offset, ends);\r\n      if (consumed <= 0) {\r\n        const size = ends - offset;\r\n        buffer.holdFor(msg, offset, size, size + -consumed);\r\n        return;\r\n      }\r\n      offset += consumed;\r\n      this.dispatch(this.packet);\r\n    }\r\n  }\r\n\r\n  /**\r\n   * Parse and dispatch every complete packet within an already-decrypted\r\n   * record. Unlike the plaintext path above, a truncated packet here is a\r\n   * genuine protocol error rather than \"need more data\" — the whole record\r\n   * was already fully received and authenticated before decryption.\r\n   */\r\n  private dispatchPlaintext(plaintext: Uint8Array): void {\r\n    let offset = 0;\r\n    const ends = plaintext.length;\r\n    while (offset < ends) {\r\n      if (!this.authenticated) {\r\n        const consumed = this.authPacket.parse(plaintext, offset, ends);\r\n        if (consumed <= 0) throw new Error(\"Truncated encrypted auth packet.\");\r\n        offset += consumed;\r\n        this.handleAuthPacket(this.authPacket);\r\n        continue;\r\n      }\r\n      const consumed = this.packet.parse(plaintext, offset, ends);\r\n      if (consumed <= 0) throw new Error(\"Truncated encrypted packet.\");\r\n      offset += consumed;\r\n      this.dispatch(this.packet);\r\n    }\r\n  }\r\n\r\n  private dispatch(packet: EpPacket): void {\r\n    switch (packet.method) {\r\n      case EpPacketMethod.Reply:\r\n        this.dispatchReply(packet);\r\n        break;\r\n      case EpPacketMethod.Request:\r\n        this.processRequest(packet.request, packet.callbackId, packet.tdu);\r\n        break;\r\n      case EpPacketMethod.Notification:\r\n        this.processNotification(packet.notification, packet.tdu);\r\n        break;\r\n      case EpPacketMethod.Extension:\r\n        break;\r\n    }\r\n  }\r\n\r\n  /** Route an inbound request to a built-in handler, or fall back to {@link onRequest}. */\r\n  private processRequest(action: EpPacketRequest, callbackId: number, tdu: PlainTdu | null): void {\r\n    if (this.warehouse) {\r\n      switch (action) {\r\n        case EpPacketRequest.InvokeFunction:\r\n          void this.epRequestInvokeFunction(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.StaticCall:\r\n          void this.epRequestStaticCall(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.SetProperty:\r\n          void this.epRequestSetProperty(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.Subscribe:\r\n          void this.epRequestSubscribe(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.Unsubscribe:\r\n          void this.epRequestUnsubscribe(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.AttachResource:\r\n          void this.epRequestAttachResource(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.ReattachResource:\r\n          void this.epRequestReattachResource(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.GetResourceIdByLink:\r\n          this.epRequestGetResourceIdByLink(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.TypeDefById:\r\n          void this.epRequestTypeDefById(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.TypeDefByResourceId:\r\n          void this.epRequestTypeDefByResourceId(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.TypeDefIdsByNames:\r\n          void this.epRequestTypeDefIdsByNames(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.Query:\r\n          void this.epRequestQueryResources(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.LinkTypeDefs:\r\n          void this.epRequestLinkTypeDefs(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.DetachResource:\r\n          void this.epRequestDetachResource(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.CreateResource:\r\n          void this.epRequestCreateResource(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.DeleteResource:\r\n          void this.epRequestDeleteResource(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.MoveResource:\r\n          void this.epRequestMoveResource(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.PullStream:\r\n          void this.epRequestPullStream(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.TerminateExecution:\r\n          void this.epRequestTerminateExecution(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.HaltExecution:\r\n          void this.epRequestHaltExecution(callbackId, tdu);\r\n          return;\r\n        case EpPacketRequest.ResumeExecution:\r\n          void this.epRequestResumeExecution(callbackId, tdu);\r\n          return;\r\n      }\r\n    }\r\n    this.onRequest?.(this, action, callbackId, tdu);\r\n  }\r\n\r\n  /**\r\n   * Evaluate permissions/rate-control/auditing managers for one operation\r\n   * (port of C# `TryApplyManagers`). Sends the denial error itself and\r\n   * returns `false` when the operation isn't admitted; otherwise waits out\r\n   * any rate-control-assigned delay and returns `true`.\r\n   *\r\n   * Scope note: dotnet additionally tracks repeated rate-control denials\r\n   * per connection and, past a threshold, blocks the connection outright\r\n   * (`IsRateControlBlocked`/`DenyRateControlledRequest`) — a secondary\r\n   * DoS-hardening layer on top of this per-operation check, not ported here.\r\n   */\r\n  private async tryApplyManagers(\r\n    member: MemberTemplate | null,\r\n    resource: IResource | null,\r\n    action: ActionType,\r\n    callbackId: number,\r\n    denialErrorType: ErrorType,\r\n    denialCode: ExceptionCode,\r\n    supportsDelay = false,\r\n  ): Promise<boolean> {\r\n    if (!this.warehouse) return true;\r\n\r\n    const context = new ResourceManagerContext(\r\n      this.warehouse,\r\n      this,\r\n      this.getAuthenticationSession(),\r\n      resource,\r\n      member,\r\n      action,\r\n      this,\r\n      [],\r\n      null,\r\n      supportsDelay,\r\n    );\r\n\r\n    try {\r\n      const evaluation = this.warehouse.evaluateManagers(context);\r\n      if (!evaluation.isAllowed) {\r\n        this.sendError(denialErrorType, callbackId, denialCode);\r\n        return false;\r\n      }\r\n      if (evaluation.delay > 0) {\r\n        if (!supportsDelay) {\r\n          this.sendError(denialErrorType, callbackId, denialCode);\r\n          return false;\r\n        }\r\n        await new Promise<void>((resolve) => setTimeout(resolve, evaluation.delay));\r\n      }\r\n      return true;\r\n    } catch {\r\n      this.sendError(denialErrorType, callbackId, denialCode);\r\n      return false;\r\n    }\r\n  }\r\n\r\n  /** Server handler: send current property values and subscribe the peer to changes. */\r\n  private async epRequestAttachResource(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const instanceId = Number(this.decode(tdu));\r\n    const resource = this.warehouse.getById(instanceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.Attach,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const instance = resource.instance;\r\n    if (!instance) return;\r\n    const propertyValues = this.composePropertyValueArray(instanceId);\r\n\r\n    const typeDef = this.warehouse.getLocalTypeDefByType(resource.constructor);\r\n\r\n    this.subscribeToInstance(instanceId);\r\n\r\n    this.sendReply(\r\n      EpPacketReply.Completed,\r\n      callbackId,\r\n      typeDef.id,\r\n      instance.age,\r\n      instance.link ?? \"\",\r\n      0, // hops\r\n      propertyValues,\r\n    );\r\n  }\r\n\r\n  /**\r\n   * Server handler: send only properties modified after the caller's known\r\n   * age. Accepts either a resource link (string) or a previously-known\r\n   * instance id (number) — the id is not permanent (the remote node may\r\n   * free/recreate a resource from memory), but the link is, so reconnecting\r\n   * clients resolve by link. Reply leads with the resolved id so the caller\r\n   * can detect it changed since its last attach.\r\n   */\r\n  private async epRequestReattachResource(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    let parsed: unknown[];\r\n    try {\r\n      parsed = this.decode(tdu) as unknown[];\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const linkOrId = parsed[0];\r\n    const sinceAge = asNumber(parsed[1]);\r\n\r\n    let resource: IResource | undefined;\r\n    if (typeof linkOrId === \"string\") {\r\n      try {\r\n        resource = await this.warehouse.query(linkOrId);\r\n      } catch {\r\n        resource = undefined;\r\n      }\r\n    } else {\r\n      resource = this.warehouse.getById(Number(linkOrId));\r\n    }\r\n\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.Attach,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const instance = resource.instance;\r\n    if (!instance) return;\r\n    const resolvedId = instance.id;\r\n    const typeDef = this.warehouse.getLocalTypeDefByType(resource.constructor);\r\n    const propertyValues = this.composePropertyValueMap(resolvedId, sinceAge);\r\n    this.subscribeToInstance(resolvedId);\r\n\r\n    this.sendReply(\r\n      EpPacketReply.Completed,\r\n      callbackId,\r\n      resolvedId,\r\n      typeDef.id,\r\n      instance.age,\r\n      instance.link ?? \"\",\r\n      0,\r\n      propertyValues,\r\n    );\r\n  }\r\n\r\n  /** Server handler: resolve a resource path to an instance id. */\r\n  private epRequestGetResourceIdByLink(callbackId: number, tdu: PlainTdu | null): void {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const link = String(this.decode(tdu) ?? \"\");\r\n    this.warehouse.query(link).then(\r\n      (resource) => {\r\n        if (!resource?.instance) {\r\n          this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n          return;\r\n        }\r\n        this.sendReply(EpPacketReply.Completed, callbackId, resource.instance.id);\r\n      },\r\n      () => this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound),\r\n    );\r\n  }\r\n\r\n  /** Server handler: compose and reply with a registered TypeDef by its numeric id. */\r\n  private async epRequestTypeDefById(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const id = Number(this.decode(tdu));\r\n    let local: ITypeDef;\r\n    try {\r\n      local = this.warehouse.getLocalTypeDefById(id);\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.TypeDefNotFound);\r\n      return;\r\n    }\r\n    if (!(local instanceof LocalTypeDef)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.TypeDefNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        null,\r\n        ActionType.ViewTypeDef,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const info = typeDefInfoFromTypeDef(local.id, local.kind, local.template);\r\n    this.sendReply(EpPacketReply.Completed, callbackId, compose(info, this.warehouse, this));\r\n  }\r\n\r\n  /** Server handler: compose and reply with a resource's TypeDef. */\r\n  private async epRequestTypeDefByResourceId(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const resourceId = Number(this.decode(tdu));\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.ViewTypeDef,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    // A relayed EpResource has no LocalTypeDef registration of its own on\r\n    // this warehouse — forward the id the upstream connection originally\r\n    // assigned this type (mirrors dotnet's RemoteTypeDef, which inherits\r\n    // TypeDef.Id and is composed unchanged when relayed onward).\r\n    let id: number;\r\n    let kind: TypeDefKind;\r\n    if (resource instanceof EpResource) {\r\n      id = resource.typeDefId ?? 0;\r\n      kind = TypeDefKind.Resource;\r\n    } else {\r\n      const local = this.warehouse.getLocalTypeDefByType(resource.constructor);\r\n      id = local.id;\r\n      kind = local.kind;\r\n    }\r\n\r\n    const info = typeDefInfoFromTypeDef(id, kind, resource.instance.definition);\r\n    this.sendReply(EpPacketReply.Completed, callbackId, compose(info, this.warehouse, this));\r\n  }\r\n\r\n  /** Server handler: batch name -> id lookup. Misses are skipped, not errored. */\r\n  private async epRequestTypeDefIdsByNames(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    let names: unknown[];\r\n    try {\r\n      names = (this.decode(tdu) as unknown[]) ?? [];\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const resolved = names\r\n      .map((n) => this.warehouse!.getLocalTypeDefByName(String(n)))\r\n      .filter((td): td is ITypeDef => td != null);\r\n\r\n    if (resolved.length === 0) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.TypeDefNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        null,\r\n        ActionType.ViewTypeDef,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    this.sendReply(\r\n      EpPacketReply.Completed,\r\n      callbackId,\r\n      resolved.map((td) => td.id),\r\n    );\r\n  }\r\n\r\n  /**\r\n   * Server handler (Query, 0xB): resolve a link, reply with the resource's\r\n   * children as `{id, link}` descriptors, filtered to what the caller is\r\n   * allowed to Attach. Distinct from {@link epRequestGetResourceIdByLink},\r\n   * which resolves a single link rather than listing children.\r\n   *\r\n   * Dotnet replies with full resource references that auto-attach on\r\n   * decode; esiur-ts has no compose-side counterpart for that at all yet\r\n   * (`LocalResource8/16/32` TDUs are decode-only — see `ResourceId.ts` /\r\n   * `DataDeserializer.ts` — and nothing turns a decoded `ResourceId` into an\r\n   * attached `EpResource` either). Building that bidirectional\r\n   * resource-reference wire support is its own substantial feature; this\r\n   * intentionally replies with plain, already-composable descriptors\r\n   * instead — the caller can `attach()`/`get()` any id it wants from there.\r\n   */\r\n  private async epRequestQueryResources(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const link = String(this.decode(tdu) ?? \"\");\r\n    let resource: IResource | undefined;\r\n    try {\r\n      resource = await this.warehouse.query(link);\r\n    } catch {\r\n      resource = undefined;\r\n    }\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    const children = await resource.instance.store.children<IResource>(resource);\r\n    const allowed = children.filter((child) => this.isActionAllowed(child, ActionType.Attach));\r\n    // [id, link] pairs — Codec.compose has no generic plain-object composer,\r\n    // only Map/Array/etc.; a nested array composes fine through the same\r\n    // dynamic-List path every other multi-field reply in this file uses.\r\n    const descriptors = allowed.map((child) => [child.instance!.id, child.instance!.link ?? \"\"]);\r\n    this.sendReply(EpPacketReply.Completed, callbackId, descriptors);\r\n  }\r\n\r\n  /**\r\n   * Server handler (LinkTypeDefs, 0xC): resolve a link, reply with the\r\n   * composed TypeDef payloads for the resource's type and every type it\r\n   * transitively references through property/argument/return `Tru`s — a\r\n   * bulk fetch of a type's full dependency graph in one round trip. Remote\r\n   * (relayed) types are unsupported, matching dotnet.\r\n   */\r\n  private async epRequestLinkTypeDefs(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const link = String(this.decode(tdu) ?? \"\");\r\n    let resource: IResource | undefined;\r\n    try {\r\n      resource = await this.warehouse.query(link);\r\n    } catch {\r\n      resource = undefined;\r\n    }\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    const local = this.warehouse.getLocalTypeDefByType(resource.constructor);\r\n    if (!(local instanceof LocalTypeDef)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotSupported);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.ViewTypeDef,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const closure = new Map<number, LocalTypeDef>();\r\n    collectTypeDefDependencies(local, closure);\r\n    const payloads = [...closure.values()].map((td) =>\r\n      compose(typeDefInfoFromTypeDef(td.id, td.kind, td.template), this.warehouse, this),\r\n    );\r\n    this.sendReply(EpPacketReply.Completed, callbackId, payloads);\r\n  }\r\n\r\n  /**\r\n   * Silent (no error reply) permission check, for filtering a list of\r\n   * candidates (e.g. Query's children) rather than gating a single request.\r\n   */\r\n  private isActionAllowed(resource: IResource | null, action: ActionType): boolean {\r\n    if (!this.warehouse) return true;\r\n    const context = new ResourceManagerContext(\r\n      this.warehouse,\r\n      this,\r\n      this.getAuthenticationSession(),\r\n      resource,\r\n      null,\r\n      action,\r\n      this,\r\n    );\r\n    try {\r\n      return this.warehouse.evaluateManagers(context).isAllowed;\r\n    } catch {\r\n      return false;\r\n    }\r\n  }\r\n\r\n  /**\r\n   * Server handler: pure per-connection bookkeeping — stop notifying *this*\r\n   * connection about a resource; the resource itself keeps living in the\r\n   * warehouse for other subscribers. The cleanup closure is the same one\r\n   * {@link subscribeToInstance} stores on attach.\r\n   */\r\n  private async epRequestDetachResource(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const resourceId = Number(this.decode(tdu));\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.Detach,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    this.subscriptions.get(resourceId)?.();\r\n    this.subscriptions.delete(resourceId);\r\n    this.sendReply(EpPacketReply.Completed, callbackId);\r\n  }\r\n\r\n  /**\r\n   * Server handler: rename a resource within its current parent (dotnet's\r\n   * MoveResource never actually re-parents — same restriction here, no `/`\r\n   * allowed in the new name). Unlike dotnet, which gets away with a bare\r\n   * `Instance.Name = name` assignment, ts's `MemoryStore.link()` tracks a\r\n   * resource's path via a separate `instance.variables` entry rather than\r\n   * deriving it from `Instance.name` — so the rename has to go through\r\n   * `IStore.move()`, which keeps both in sync.\r\n   */\r\n  private async epRequestMoveResource(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    let args: unknown[];\r\n    try {\r\n      args = this.decode(tdu) as unknown[];\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const resourceId = Number(args[0]);\r\n    const newName = String(args[1] ?? \"\");\r\n    if (newName.includes(\"/\")) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotSupported);\r\n      return;\r\n    }\r\n\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.Rename,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.RenameDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const store = resource.instance.store;\r\n    const relativeLink = store.link(resource) ?? resource.instance.name;\r\n    const parts = relativeLink.split(\"/\");\r\n    parts[parts.length - 1] = newName;\r\n    await store.move(resource, parts.join(\"/\"));\r\n    this.sendReply(EpPacketReply.Completed, callbackId);\r\n  }\r\n\r\n  /** Server handler: remove a resource from the warehouse and its store. */\r\n  private async epRequestDeleteResource(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const resourceId = Number(this.decode(tdu));\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        resource,\r\n        ActionType.Delete,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.DeleteDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    if (this.warehouse.remove(resource)) this.sendReply(EpPacketReply.Completed, callbackId);\r\n    else this.sendError(ErrorType.Management, callbackId, ExceptionCode.DeleteFailed);\r\n  }\r\n\r\n  /**\r\n   * Server handler: create a resource of a type already registered on this\r\n   * warehouse (no dynamic/generic creation — matches dotnet's\r\n   * `Activator.CreateInstance`-on-a-known-compiled-`Type` restriction).\r\n   */\r\n  private async epRequestCreateResource(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    let args: unknown[];\r\n    try {\r\n      args = this.decode(tdu) as unknown[];\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const path = String(args[0] ?? \"\");\r\n    const typeIdOrName = args[1];\r\n    const props = (args[2] as Map<number, unknown> | undefined) ?? new Map<number, unknown>();\r\n    const attrs = (args[3] as Map<string, unknown> | undefined) ?? undefined;\r\n\r\n    let local: ITypeDef | undefined;\r\n    try {\r\n      local =\r\n        typeof typeIdOrName === \"string\"\r\n          ? this.warehouse.getLocalTypeDefByName(typeIdOrName)\r\n          : this.warehouse.getLocalTypeDefById(Number(typeIdOrName));\r\n    } catch {\r\n      local = undefined;\r\n    }\r\n    if (!local || !(local instanceof LocalTypeDef)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ClassNotFound);\r\n      return;\r\n    }\r\n\r\n    const parts = path.replace(/^\\/+/, \"\").split(\"/\");\r\n    const parentPath = parts.slice(0, -1).join(\"/\");\r\n    let parent: IResource | undefined;\r\n    try {\r\n      parent = await this.warehouse.query(parentPath);\r\n    } catch {\r\n      parent = undefined;\r\n    }\r\n    if (!parent?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.StoreNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        parent,\r\n        ActionType.CreateResource,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.CreateDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    try {\r\n      const instance = local.createInstance() as IResource;\r\n      for (const [index, value] of props) {\r\n        const name = local.template.getPropertyByIndex(index)?.name;\r\n        if (name) local.setProperty(instance, name, value);\r\n      }\r\n      const put = await this.warehouse.put(path, instance, { attributes: attrs });\r\n      this.sendReply(EpPacketReply.Completed, callbackId, put.instance!.id);\r\n    } catch (e) {\r\n      this.sendError(ErrorType.Exception, callbackId, ExceptionCode.RuntimeException, String(e));\r\n    }\r\n  }\r\n\r\n  private subscribeToInstance(instanceId: number): void {\r\n    const resource = this.warehouse?.getById(instanceId);\r\n    if (!resource?.instance || this.subscriptions.has(instanceId)) return;\r\n\r\n    const instance = resource.instance;\r\n    const onProp = (info: { property: { index: number }; value: unknown }): void =>\r\n      this.sendNotification(\r\n        EpPacketNotification.PropertyModified,\r\n        instanceId,\r\n        info.property.index,\r\n        info.value,\r\n      );\r\n    const onEvent = (info: { event: { index: number; subscribable?: boolean }; value: unknown }): void => {\r\n      if (info.event.subscribable && !this.eventSubscriptions.get(instanceId)?.has(info.event.index)) return;\r\n      this.sendNotification(\r\n        EpPacketNotification.EventOccurred,\r\n        instanceId,\r\n        info.event.index,\r\n        info.value,\r\n      );\r\n    };\r\n    instance.propertyModified.add(onProp);\r\n    instance.eventOccurred.add(onEvent);\r\n    this.subscriptions.set(instanceId, () => {\r\n      instance.propertyModified.remove(onProp);\r\n      instance.eventOccurred.remove(onEvent);\r\n    });\r\n  }\r\n\r\n  /** Server handler: resolve the resource, invoke the function by index, reply with its result. */\r\n  private async epRequestInvokeFunction(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    let parsed: unknown[];\r\n    try {\r\n      parsed = this.decode(tdu) as unknown[];\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const resourceId = Number(parsed[0]);\r\n    const index = Number(parsed[1]);\r\n\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    const ft = resource.instance.definition.getFunctionByIndex(index);\r\n    if (!ft) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.MethodNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        ft,\r\n        resource,\r\n        ActionType.Execute,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n        /* supportsDelay */ true,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const args = toIndexedArguments(parsed[2], ft.args.length);\r\n\r\n    let result: unknown;\r\n    try {\r\n      // A relayed EpResource has no real class method matching `ft.name` —\r\n      // only its own bespoke invoke-by-index, which forwards the call to\r\n      // the upstream connection it's a proxy for.\r\n      result =\r\n        resource instanceof EpResource\r\n          ? resource.invoke(index, args)\r\n          : (resource as unknown as Record<string, (...a: unknown[]) => unknown>)[ft.name](\r\n              ...args,\r\n            );\r\n    } catch (e) {\r\n      this.sendError(ErrorType.Exception, callbackId, ExceptionCode.RuntimeException, String(e));\r\n      return;\r\n    }\r\n\r\n    this.replyWithFunctionResult(callbackId, ft, result);\r\n  }\r\n\r\n  /** Shared invoke-result reply tail for {@link epRequestInvokeFunction} and {@link epRequestStaticCall}. */\r\n  private replyWithFunctionResult(callbackId: number, ft: FunctionTemplate, result: unknown): void {\r\n    if (ft.streamMode !== StreamMode.None) {\r\n      this.beginStreamedReply(callbackId, ft, result);\r\n      return;\r\n    }\r\n    if (isThenable(result)) {\r\n      result.then(\r\n        (r) => this.sendReply(EpPacketReply.Completed, callbackId, r),\r\n        (e) =>\r\n          this.sendError(ErrorType.Exception, callbackId, ExceptionCode.RuntimeException, String(e)),\r\n      );\r\n    } else {\r\n      this.sendReply(EpPacketReply.Completed, callbackId, result);\r\n    }\r\n  }\r\n\r\n  /**\r\n   * Register a streaming call's result and reply `Stream` on `callbackId`\r\n   * (the \"execution callback\" `PullStream`/etc. later reference). A `Push`\r\n   * source is pumped immediately; a `Pull` source just sits registered until\r\n   * an explicit `PullStream` request drives it.\r\n   */\r\n  private beginStreamedReply(callbackId: number, ft: FunctionTemplate, result: unknown): void {\r\n    if (!isIterableResult(result)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotSupported);\r\n      return;\r\n    }\r\n\r\n    const context = new ServerInvocationContext(result, ft.streamMode, ft.pausable);\r\n    this.invocations.set(callbackId, context);\r\n    this.sendReply(EpPacketReply.Stream, callbackId);\r\n\r\n    if (ft.streamMode === StreamMode.Push) void this.pumpStream(callbackId, context);\r\n  }\r\n\r\n  /** Drive a `Push`-mode stream to completion, sending one `Chunk` reply per item. */\r\n  private async pumpStream(executionCallbackId: number, context: ServerInvocationContext): Promise<void> {\r\n    try {\r\n      for (;;) {\r\n        const r = await context.pullAsync();\r\n        if (r.done) break;\r\n        this.sendReply(EpPacketReply.Chunk, executionCallbackId, r.value);\r\n      }\r\n      this.invocations.delete(executionCallbackId);\r\n      this.sendReply(EpPacketReply.Completed, executionCallbackId);\r\n    } catch (e) {\r\n      this.invocations.delete(executionCallbackId);\r\n      this.sendError(ErrorType.Exception, executionCallbackId, ExceptionCode.RuntimeException, String(e));\r\n    }\r\n  }\r\n\r\n  /** Server handler (PullStream): advance a `Pull`-mode stream by one item. */\r\n  private async epRequestPullStream(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const executionCallbackId = Number(this.decode(tdu));\r\n    const context = this.invocations.get(executionCallbackId);\r\n    if (!context || context.streamMode !== StreamMode.Pull) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAllowed);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        null,\r\n        ActionType.PullStream,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    try {\r\n      const r = await context.pullAsync();\r\n      if (r.done) {\r\n        this.invocations.delete(executionCallbackId);\r\n        this.sendReply(EpPacketReply.Completed, executionCallbackId);\r\n      } else {\r\n        this.sendReply(EpPacketReply.Chunk, executionCallbackId, r.value);\r\n      }\r\n      this.sendReply(EpPacketReply.Completed, callbackId);\r\n    } catch (e) {\r\n      this.invocations.delete(executionCallbackId);\r\n      this.sendError(ErrorType.Exception, executionCallbackId, ExceptionCode.RuntimeException, String(e));\r\n      this.sendError(ErrorType.Exception, callbackId, ExceptionCode.RuntimeException, String(e));\r\n    }\r\n  }\r\n\r\n  /** Server handler (TerminateExecution): stop a stream and release its iterator. */\r\n  private async epRequestTerminateExecution(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const executionCallbackId = Number(this.decode(tdu));\r\n    const context = this.invocations.get(executionCallbackId);\r\n    if (!context) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAllowed);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        null,\r\n        ActionType.TerminateExecution,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    this.invocations.delete(executionCallbackId);\r\n    await context.terminate();\r\n    this.sendReply(EpPacketReply.Completed, executionCallbackId);\r\n    this.sendReply(EpPacketReply.Completed, callbackId);\r\n  }\r\n\r\n  /** Server handler (HaltExecution): pause a pausable stream. */\r\n  private async epRequestHaltExecution(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const executionCallbackId = Number(this.decode(tdu));\r\n    const context = this.invocations.get(executionCallbackId);\r\n    if (!context) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAllowed);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        null,\r\n        ActionType.HaltExecution,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    try {\r\n      context.halt();\r\n      this.sendReply(EpPacketReply.Completed, callbackId);\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAllowed);\r\n    }\r\n  }\r\n\r\n  /** Server handler (ResumeExecution): resume a halted stream. */\r\n  private async epRequestResumeExecution(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const executionCallbackId = Number(this.decode(tdu));\r\n    const context = this.invocations.get(executionCallbackId);\r\n    if (!context) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAllowed);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        null,\r\n        null,\r\n        ActionType.ResumeExecution,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.NotAllowed,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    try {\r\n      context.resume();\r\n      this.sendReply(EpPacketReply.Completed, callbackId);\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAllowed);\r\n    }\r\n  }\r\n\r\n  /**\r\n   * Server handler (StaticCall): invoke a `static` exported function by\r\n   * TypeDef id + function index — class-level, no resource instance\r\n   * involved.\r\n   */\r\n  private async epRequestStaticCall(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    let parsed: unknown[];\r\n    try {\r\n      parsed = this.decode(tdu) as unknown[];\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const typeId = Number(parsed[0]);\r\n    const index = Number(parsed[1]);\r\n    const args = (parsed[2] as unknown[]) ?? [];\r\n\r\n    let local: ITypeDef;\r\n    try {\r\n      local = this.warehouse.getLocalTypeDefById(typeId);\r\n    } catch {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.TypeDefNotFound);\r\n      return;\r\n    }\r\n    if (!(local instanceof LocalTypeDef)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.TypeDefNotFound);\r\n      return;\r\n    }\r\n\r\n    const ft = local.template.getFunctionByIndex(index);\r\n    if (!ft || !ft.isStatic) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.MethodNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        ft,\r\n        null,\r\n        ActionType.Execute,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.InvokeDenied,\r\n        /* supportsDelay */ true,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    let result: unknown;\r\n    try {\r\n      result = local.invokeStaticFunction(ft.name, args);\r\n    } catch (e) {\r\n      this.sendError(ErrorType.Exception, callbackId, ExceptionCode.RuntimeException, String(e));\r\n      return;\r\n    }\r\n\r\n    this.replyWithFunctionResult(callbackId, ft, result);\r\n  }\r\n\r\n  /** Server handler: resolve the resource and set a property by index. */\r\n  private async epRequestSetProperty(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const parsed = this.decode(tdu) as unknown[];\r\n    const resourceId = Number(parsed[0]);\r\n    const index = Number(parsed[1]);\r\n    const value = parsed[2];\r\n\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n\r\n    const pt = resource.instance.definition.getPropertyByIndex(index);\r\n    if (!pt) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.PropertyNotFound);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        pt,\r\n        resource,\r\n        ActionType.SetProperty,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n        /* supportsDelay */ true,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    if (isDynamicResource(resource)) resource.setResourceProperty(pt.index, value);\r\n    else (resource as unknown as Record<string, unknown>)[pt.name] = value;\r\n    this.sendReply(EpPacketReply.Completed, callbackId);\r\n  }\r\n\r\n  /**\r\n   * Server handler: an already-attached connection asks to start receiving a\r\n   * `subscribable` event's occurrences. Errors `AlreadyListened` on a\r\n   * duplicate call — callers must track subscription state themselves (see\r\n   * {@link EpResource.on}) rather than relying on this being a no-op.\r\n   */\r\n  private async epRequestSubscribe(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const parsed = this.decode(tdu) as unknown[];\r\n    const resourceId = Number(parsed[0]);\r\n    const index = Number(parsed[1]);\r\n\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n    if (!this.subscriptions.has(resourceId)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAttached);\r\n      return;\r\n    }\r\n    const et = resource.instance.definition.getEventByIndex(index);\r\n    if (!et) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.GeneralFailure);\r\n      return;\r\n    }\r\n    if (!et.subscribable) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotSubscribable);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        et,\r\n        resource,\r\n        ActionType.Subscribe,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    const subscribed = this.eventSubscriptions.get(resourceId) ?? new Set<number>();\r\n    if (subscribed.has(index)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.AlreadyListened);\r\n      return;\r\n    }\r\n    subscribed.add(index);\r\n    this.eventSubscriptions.set(resourceId, subscribed);\r\n\r\n    // Relaying through a proxy: this resource only receives the event at all\r\n    // if *it* is subscribed upstream. Ref-count via .on() so the upstream\r\n    // wire subscription stays alive for as long as any downstream peer\r\n    // (there may be several) needs it.\r\n    if (resource instanceof EpResource) {\r\n      const key = `${resourceId}:${index}`;\r\n      const listener = (): void => {};\r\n      this.relayListeners.set(key, listener);\r\n      resource.on(et.name, listener);\r\n    }\r\n\r\n    this.sendReply(EpPacketReply.Completed, callbackId);\r\n  }\r\n\r\n  /** Server handler: the mirror of {@link epRequestSubscribe}. */\r\n  private async epRequestUnsubscribe(callbackId: number, tdu: PlainTdu | null): Promise<void> {\r\n    if (!tdu || !this.warehouse) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ParseError);\r\n      return;\r\n    }\r\n\r\n    const parsed = this.decode(tdu) as unknown[];\r\n    const resourceId = Number(parsed[0]);\r\n    const index = Number(parsed[1]);\r\n\r\n    const resource = this.warehouse.getById(resourceId);\r\n    if (!resource?.instance) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.ResourceNotFound);\r\n      return;\r\n    }\r\n    if (!this.subscriptions.has(resourceId)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.NotAttached);\r\n      return;\r\n    }\r\n    const et = resource.instance.definition.getEventByIndex(index);\r\n    if (!et) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.GeneralFailure);\r\n      return;\r\n    }\r\n\r\n    const subscribed = this.eventSubscriptions.get(resourceId);\r\n    if (!subscribed?.has(index)) {\r\n      this.sendError(ErrorType.Management, callbackId, ExceptionCode.AlreadyUnsubscribed);\r\n      return;\r\n    }\r\n\r\n    if (\r\n      !(await this.tryApplyManagers(\r\n        et,\r\n        resource,\r\n        ActionType.Unsubscribe,\r\n        callbackId,\r\n        ErrorType.Management,\r\n        ExceptionCode.AccessDenied,\r\n      ))\r\n    )\r\n      return;\r\n\r\n    subscribed.delete(index);\r\n\r\n    if (resource instanceof EpResource) {\r\n      const key = `${resourceId}:${index}`;\r\n      const listener = this.relayListeners.get(key);\r\n      if (listener) {\r\n        resource.off(et.name, listener);\r\n        this.relayListeners.delete(key);\r\n      }\r\n    }\r\n\r\n    this.sendReply(EpPacketReply.Completed, callbackId);\r\n  }\r\n\r\n  /** Route an inbound notification to a built-in handler, or fall back to {@link onNotification}. */\r\n  private processNotification(action: EpPacketNotification, tdu: PlainTdu | null): void {\r\n    switch (action) {\r\n      case EpPacketNotification.PropertyModified: {\r\n        const a = (this.decode(tdu) as unknown[]) ?? [];\r\n        this.attachedResources\r\n          .get(Number(a[0]))\r\n          ?.updateProperty(Number(a[1]), a[2]);\r\n        return;\r\n      }\r\n      case EpPacketNotification.EventOccurred: {\r\n        const a = (this.decode(tdu) as unknown[]) ?? [];\r\n        this.attachedResources.get(Number(a[0]))?.applyEvent(Number(a[1]), a[2]);\r\n        return;\r\n      }\r\n    }\r\n    this.onNotification?.(this, action, tdu);\r\n  }\r\n\r\n  private dispatchReply(packet: EpPacket): void {\r\n    const { callbackId, tdu } = packet;\r\n    switch (packet.reply) {\r\n      case EpPacketReply.Completed:\r\n        this.replyCompleted(callbackId, tdu);\r\n        break;\r\n      case EpPacketReply.Stream:\r\n        this.replyStream(callbackId);\r\n        break;\r\n      case EpPacketReply.Propagated:\r\n        this.replyPropagated(callbackId, tdu);\r\n        break;\r\n      case EpPacketReply.PermissionError:\r\n        this.replyError(callbackId, tdu, ErrorType.Management);\r\n        break;\r\n      case EpPacketReply.ExecutionError:\r\n        this.replyError(callbackId, tdu, ErrorType.Exception);\r\n        break;\r\n      case EpPacketReply.Progress:\r\n        this.replyProgress(callbackId, tdu);\r\n        break;\r\n      case EpPacketReply.Chunk:\r\n        this.replyChunk(callbackId, tdu);\r\n        break;\r\n      case EpPacketReply.Warning:\r\n        this.replyWarning(callbackId, tdu);\r\n        break;\r\n    }\r\n  }\r\n\r\n  private decode(tdu: PlainTdu | null): unknown {\r\n    if (!tdu) return undefined;\r\n    // A top-level `TduIdentifier.TypeDef` (0x81) value is never generically\r\n    // decoded here: its `PropertyDefInfo.valueType`/`FunctionDefInfo.returnType`/\r\n    // etc. fields commonly reference other not-yet-fetched remote TypeDefs on\r\n    // this connection, which only the async, resolver-aware\r\n    // `RemoteTypeDef.parseAsyncInto` (driven by `finishTypeDefRequest`) can\r\n    // resolve. Hand back the raw TDU bytes instead, matching the shape the\r\n    // legacy wire format already produced (a `RawData` payload) so\r\n    // `expectTypeDefPayload`/`RemoteTypeDef.parse*` work unchanged either way.\r\n    if (tdu.identifier === TduIdentifier.TypeDef)\r\n      return tdu.data.subarray(tdu.tduOffset, tdu.tduOffset + tdu.totalLength);\r\n    return parse(tdu.data, tdu.tduOffset, this.warehouse);\r\n  }\r\n\r\n  private replyCompleted(callbackId: number, tdu: PlainTdu | null): void {\r\n    const req = this.requests.get(callbackId);\r\n    if (!req) return;\r\n    this.requests.delete(callbackId);\r\n    // A `Completed` reply for a streamed invocation signals both \"the call\r\n    // is done\" (the normal `trigger`, inherited unchanged) and \"no more\r\n    // chunks are coming\" — without the latter, `for await` consumers of an\r\n    // `AsyncStreamReply` would hang waiting on a chunk that will never arrive.\r\n    if (req instanceof AsyncStreamReply) req.triggerStreamCompleted();\r\n    req.trigger(this.decode(tdu));\r\n  }\r\n\r\n  private replyStream(callbackId: number): void {\r\n    const req = this.requests.get(callbackId);\r\n    if (req instanceof AsyncStreamReply) req.triggerStreamStarted();\r\n  }\r\n\r\n  private replyChunk(callbackId: number, tdu: PlainTdu | null): void {\r\n    this.requests.get(callbackId)?.triggerChunk(this.decode(tdu));\r\n  }\r\n\r\n  private replyWarning(callbackId: number, tdu: PlainTdu | null): void {\r\n    const args = (this.decode(tdu) as unknown[]) ?? [];\r\n    this.requests\r\n      .get(callbackId)\r\n      ?.triggerWarning(Number(args[0] ?? 0), String(args[1] ?? \"\"));\r\n  }\r\n\r\n  private replyPropagated(callbackId: number, tdu: PlainTdu | null): void {\r\n    this.requests.get(callbackId)?.triggerPropagation(this.decode(tdu));\r\n  }\r\n\r\n  private replyError(callbackId: number, tdu: PlainTdu | null, type: ErrorType): void {\r\n    const req = this.requests.get(callbackId);\r\n    if (!req) return;\r\n    this.requests.delete(callbackId);\r\n    const args = (this.decode(tdu) as unknown[]) ?? [];\r\n    req.triggerError(new AsyncException(type, Number(args[0] ?? 0), String(args[1] ?? \"\")));\r\n  }\r\n\r\n  private replyProgress(callbackId: number, tdu: PlainTdu | null): void {\r\n    const args = (this.decode(tdu) as unknown[]) ?? [];\r\n    this.requests\r\n      .get(callbackId)\r\n      ?.triggerProgress(ProgressType.Execution, Number(args[0] ?? 0), Number(args[1] ?? 0));\r\n  }\r\n\r\n  protected override connected(): void {\r\n    if (this.direction === \"initiator\" && !this.authenticated) this.declare();\r\n  }\r\n\r\n  override close(): void {\r\n    this.manualClose = true;\r\n    this.clearReconnectTimer();\r\n    if (this.authSessionEstablished)\r\n      this.authenticationProvider?.logout?.(this.getAuthenticationSession());\r\n    super.close();\r\n  }\r\n\r\n  override destroy(): void {\r\n    this.manualClose = true;\r\n    this.clearReconnectTimer();\r\n    super.destroy();\r\n  }\r\n\r\n  protected override disconnected(): void {\r\n    // Fail a pending handshake.\r\n    this.readyReply?.triggerError(\r\n      new AsyncException(ErrorType.Management, 1, \"Connection closed during handshake.\"),\r\n    );\r\n    // Drop notification subscriptions and fail any in-flight requests.\r\n    for (const unsubscribe of this.subscriptions.values()) unsubscribe();\r\n    this.subscriptions.clear();\r\n    this.eventSubscriptions.clear();\r\n\r\n    const pending = [...this.requests.values()];\r\n    this.requests.clear();\r\n    for (const req of pending)\r\n      req.triggerError(\r\n        new AsyncException(ErrorType.Management, 1, \"Connection closed.\"),\r\n      );\r\n\r\n    if (this.shouldAutoReconnect()) this.scheduleReconnect();\r\n  }\r\n\r\n  private shouldAutoReconnect(): boolean {\r\n    return (\r\n      this.autoReconnect &&\r\n      !this.manualClose &&\r\n      this.direction === \"initiator\" &&\r\n      this.reconnectUrl != null\r\n    );\r\n  }\r\n\r\n  private scheduleReconnect(): void {\r\n    if (this.reconnectTimer || this.reconnectReply || !this.shouldAutoReconnect()) return;\r\n    this.reconnectTimer = setTimeout(() => {\r\n      this.reconnectTimer = undefined;\r\n      this.reconnect().then(\r\n        () => undefined,\r\n        () => this.scheduleReconnect(),\r\n      );\r\n    }, Math.max(0, this.reconnectInterval));\r\n  }\r\n\r\n  private clearReconnectTimer(): void {\r\n    if (!this.reconnectTimer) return;\r\n    clearTimeout(this.reconnectTimer);\r\n    this.reconnectTimer = undefined;\r\n  }\r\n}\n\n/** Reject URL handling that would otherwise inherit a transport's default port. */\nfunction requireExplicitEndpointPort(value: string): URL {\n  let url: URL;\n  try {\n    url = new URL(value);\n  } catch {\n    throw new Error(`Invalid EP endpoint: ${value}`);\n  }\n\n  const schemeEnd = value.indexOf(\"://\");\n  const authorityStart = schemeEnd < 0 ? -1 : schemeEnd + 3;\n  const authorityEnd =\n    authorityStart < 0\n      ? -1\n      : [\"/\", \"?\", \"#\"]\n          .map((separator) => value.indexOf(separator, authorityStart))\n          .filter((index) => index >= 0)\n          .reduce((first, index) => Math.min(first, index), value.length);\n  const authority =\n    authorityStart < 0 ? \"\" : value.slice(authorityStart, authorityEnd).split(\"@\").at(-1) ?? \"\";\n  const portText = authority.startsWith(\"[\")\n    ? authority.slice(authority.indexOf(\"]\") + 1).replace(/^:/, \"\")\n    : authority.slice(authority.lastIndexOf(\":\") + 1);\n  const hasPortSeparator = authority.startsWith(\"[\")\n    ? authority.indexOf(\"]\") >= 0 && authority[authority.indexOf(\"]\") + 1] === \":\"\n    : authority.lastIndexOf(\":\") > 0;\n  const port = Number(portText);\n\n  if (!url.hostname || !hasPortSeparator || !/^\\d+$/.test(portText) || port <= 0 || port > 65535)\n    throw new Error(\n      `EP endpoints must include an explicit port (for example, ep://host:port): ${value}`,\n    );\n\n  return url;\n}\n\r\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\r\n  return (\r\n    value != null &&\r\n    (typeof value === \"object\" || typeof value === \"function\") &&\r\n    typeof (value as { then?: unknown }).then === \"function\"\r\n  );\r\n}\r\n\r\nfunction isConnectionOptions(value: unknown): value is EpConnectionOptions {\r\n  if (value == null || typeof value !== \"object\") return false;\r\n  const keys = value as Record<string, unknown>;\r\n  return (\r\n    \"autoReconnect\" in keys ||\r\n    \"AutoReconnect\" in keys ||\r\n    \"reconnectInterval\" in keys ||\r\n    \"ReconnectInterval\" in keys ||\r\n    \"authenticationMode\" in keys ||\r\n    \"AuthenticationMode\" in keys ||\r\n    \"authenticationProtocol\" in keys ||\r\n    \"AuthenticationProtocol\" in keys ||\r\n    \"authenticationProvider\" in keys ||\r\n    \"AuthenticationProvider\" in keys ||\r\n    \"identity\" in keys ||\r\n    \"Identity\" in keys ||\r\n    \"responderIdentity\" in keys ||\r\n    \"ResponderIdentity\" in keys ||\r\n    \"domain\" in keys ||\r\n    \"Domain\" in keys\r\n  );\r\n}\r\n\r\nfunction isTypeDef(value: unknown): value is TypeDef {\r\n  return value instanceof TypeDef ||\r\n    (\r\n      value != null &&\r\n      typeof value === \"object\" &&\r\n      Array.isArray((value as { members?: unknown }).members) &&\r\n      typeof (value as { getPropertyByIndex?: unknown }).getPropertyByIndex === \"function\"\r\n    );\r\n}\r\n\r\nfunction getGeneratedTypeDef(\r\n  ctor: Function,\r\n  warehouse: Warehouse | undefined,\r\n): TypeDef | undefined {\r\n  const statics = ctor as {\r\n    typeDef?: unknown;\r\n    TypeDef?: unknown;\r\n    template?: unknown;\r\n    Template?: unknown;\r\n  };\r\n  const explicit =\r\n    statics.typeDef ?? statics.TypeDef ?? statics.template ?? statics.Template;\r\n  if (isTypeDef(explicit)) return explicit;\r\n\r\n  const decorated = warehouse?.getTypeDef(ctor);\r\n  return decorated && decorated.members.length > 0 ? decorated : undefined;\r\n}\r\n\r\nfunction nullResult(): AuthenticationResult {\r\n  return new AuthenticationResult(AuthenticationRuling.Succeeded, null, null, null, null);\r\n}\r\n\r\n/**\r\n * Walk `local`'s properties/functions/events for `Tru`s referencing another\r\n * local type (`TruTypeDef`, recursing through `TruComposite` sub-types for\r\n * typed lists/maps/tuples), collecting the full transitive closure. Used by\r\n * `LinkTypeDefs` to bulk-fetch a type's dependency graph in one round trip.\r\n */\r\nfunction collectTypeDefDependencies(local: LocalTypeDef, closure: Map<number, LocalTypeDef>): void {\r\n  if (closure.has(local.id)) return;\r\n  closure.set(local.id, local);\r\n\r\n  const visitTru = (tru: Tru | undefined): void => {\r\n    if (!tru) return;\r\n    if (tru instanceof TruTypeDef) {\r\n      if (tru.typeDef instanceof LocalTypeDef) collectTypeDefDependencies(tru.typeDef, closure);\r\n      return;\r\n    }\r\n    if (tru instanceof TruComposite) for (const sub of tru.subTypes) visitTru(sub);\r\n  };\r\n\r\n  for (const p of local.template.properties) visitTru(p.valueType);\r\n  for (const f of local.template.functions) {\r\n    visitTru(f.returnType);\r\n    for (const a of f.args) visitTru(a.type);\r\n  }\r\n  for (const e of local.template.events) visitTru(e.argType);\r\n}\r\n\r\nfunction asNumber(value: unknown): number {\r\n  if (typeof value === \"number\") return value;\r\n  if (typeof value === \"bigint\") return Number(value);\r\n  if (value instanceof Number) return Number(value.valueOf());\r\n  return Number(value ?? 0);\r\n}\r\n\r\nfunction asDate(value: unknown): Date | undefined {\r\n  return value instanceof Date ? value : undefined;\r\n}\r\n\r\nfunction toIndexedArguments(value: unknown, expectedCount = 0): unknown[] {\r\n  if (value == null) return [];\r\n  if (Array.isArray(value)) return value;\r\n  if (!(value instanceof Map)) return [value];\r\n\r\n  let size = expectedCount;\r\n  for (const key of value.keys()) {\r\n    const index = asNumber(key);\r\n    if (index >= size) size = index + 1;\r\n  }\r\n\r\n  const args = new Array<unknown>(size);\r\n  for (const [key, item] of value.entries()) {\r\n    const index = asNumber(key);\r\n    if (Number.isInteger(index) && index >= 0) args[index] = item;\r\n  }\r\n  return args;\r\n}\r\n\r\nfunction asBytes(value: unknown): Uint8Array | undefined {\r\n  return value instanceof Uint8Array ? value : undefined;\r\n}\r\n\r\nfunction asStringArray(value: unknown): string[] {\r\n  if (!Array.isArray(value)) return [];\r\n  return value.filter((v): v is string => typeof v === \"string\");\r\n}\r\n\r\nfunction readTypeDefPayloadId(data: Uint8Array, warehouse: unknown): number {\r\n  if (data.length < 1)\r\n    throw new AsyncException(\r\n      ErrorType.Management,\r\n      ExceptionCode.ParseError,\r\n      \"TypeDef payload is too short.\",\r\n    );\r\n\r\n  if ((data[0] & 0xc7) === TduIdentifier.TypeDef) {\r\n    // No fixed-offset shortcut exists in the new format (matching dotnet) —\r\n    // the id is `TypeDefField.Id` inside the indexed structure, so extracting\r\n    // it requires a full (small) decode.\r\n    const parsed = parseSync(data, 0, warehouse);\r\n    if (!(parsed.value instanceof TypeDefInfo))\r\n      throw new AsyncException(\r\n        ErrorType.Management,\r\n        ExceptionCode.ParseError,\r\n        \"Invalid TypeDefInfo payload.\",\r\n      );\r\n    return parsed.value.id;\r\n  }\r\n\r\n  if (data.length < 9)\r\n    throw new AsyncException(\r\n      ErrorType.Management,\r\n      ExceptionCode.ParseError,\r\n      \"TypeDef payload is too short.\",\r\n    );\r\n  return Number(getUint64(data, 1));\r\n}\r\n\r\nfunction toInstanceId(value: unknown): number | undefined {\r\n  if (value instanceof ResourceId) return value.id;\r\n  if (typeof value === \"number\") return value;\r\n  if (typeof value === \"bigint\") return Number(value);\r\n  if (value instanceof EpResource) return value.instanceId;\r\n\r\n  const maybe = value as\r\n    | { id?: unknown; instanceId?: unknown; instance?: { id?: unknown } }\r\n    | undefined;\r\n  if (!maybe || typeof maybe !== \"object\") return undefined;\r\n  if (maybe.instanceId != null) return asNumber(maybe.instanceId);\r\n  if (maybe.id != null) return asNumber(maybe.id);\r\n  if (maybe.instance?.id != null) return asNumber(maybe.instance.id);\r\n  return undefined;\r\n}\r\n\r\nfunction nowMs(): number {\r\n  return globalThis.performance?.now() ?? Date.now();\r\n}\r\n","import { EventHandler } from \"../core/EventHandler.js\";\r\nimport type { DestroyedEvent, IDestructible } from \"../core/IDestructible.js\";\r\nimport type { NetworkBuffer } from \"./NetworkBuffer.js\";\r\nimport type { INetworkReceiver } from \"./INetworkReceiver.js\";\r\nimport type { ISocket } from \"./sockets/ISocket.js\";\r\nimport { SocketState } from \"./sockets/SocketState.js\";\r\n\r\n/**\r\n * Base for a logical connection over an {@link ISocket} (port of C#\r\n * `NetworkConnection`). Owns the socket, drains inbound buffers to\r\n * {@link dataReceived}, and exposes send helpers. Subclasses implement the\r\n * protocol-specific framing.\r\n */\r\nexport abstract class NetworkConnection\r\n  implements INetworkReceiver<ISocket>, IDestructible\r\n{\r\n  protected socket?: ISocket;\r\n  private receivingFlag = false;\r\n\r\n  readonly onConnect = new EventHandler<NetworkConnection>();\r\n  readonly onClose = new EventHandler<NetworkConnection>();\r\n  private readonly destroyHandlers: DestroyedEvent[] = [];\r\n\r\n  /** Attach a socket and route its events here. */\r\n  assign(socket: ISocket): void {\r\n    this.socket = socket;\r\n    socket.receiver = this;\r\n  }\r\n\r\n  /** Detach the socket without closing it (e.g. for a protocol upgrade). */\r\n  unassign(): ISocket | undefined {\r\n    const sock = this.socket;\r\n    if (!sock) return undefined;\r\n    sock.receiver = undefined;\r\n    this.socket = undefined;\r\n    return sock;\r\n  }\r\n\r\n  get isConnected(): boolean {\r\n    return this.socket != null && this.socket.state === SocketState.Established;\r\n  }\r\n\r\n  send(message: Uint8Array): void {\r\n    this.socket?.send(message);\r\n  }\r\n\r\n  close(): void {\r\n    this.socket?.close();\r\n  }\r\n\r\n  networkConnect(_socket: ISocket): void {\r\n    if (_socket !== this.socket) return;\r\n    this.connected();\r\n    this.onConnect.emit(this);\r\n  }\r\n\r\n  networkClose(_socket: ISocket): void {\r\n    if (_socket !== this.socket) return;\r\n    this.disconnected();\r\n    this.onClose.emit(this);\r\n  }\r\n\r\n  networkReceive(_sender: ISocket, buffer: NetworkBuffer): void {\r\n    if (_sender !== this.socket || this.socket.state === SocketState.Closed) return;\r\n\r\n    // Drain once; re-entrant callbacks return and let the active drain continue.\r\n    if (this.receivingFlag) return;\r\n    this.receivingFlag = true;\r\n    try {\r\n      while (buffer.available > 0 && !buffer.protected_) this.dataReceived(buffer);\r\n    } finally {\r\n      this.receivingFlag = false;\r\n    }\r\n  }\r\n\r\n  protected abstract dataReceived(buffer: NetworkBuffer): void;\r\n  protected abstract connected(): void;\r\n  protected abstract disconnected(): void;\r\n\r\n  addDestroyHandler(handler: DestroyedEvent): void {\r\n    this.destroyHandlers.push(handler);\r\n  }\r\n\r\n  removeDestroyHandler(handler: DestroyedEvent): void {\r\n    const i = this.destroyHandlers.indexOf(handler);\r\n    if (i >= 0) this.destroyHandlers.splice(i, 1);\r\n  }\r\n\r\n  destroy(): void {\r\n    this.socket?.destroy();\r\n    this.socket = undefined;\r\n    for (const h of this.destroyHandlers.slice()) h(this);\r\n  }\r\n}\r\n","import { PlainTdu } from \"../../data/PlainTdu.js\";\r\nimport { TduClass } from \"../../data/TduClass.js\";\r\nimport { merge, uint32ToBytes, getUint32 } from \"../../data/DC.js\";\r\nimport { EpPacketMethod } from \"./EpPacketMethod.js\";\r\nimport type { EpPacketRequest } from \"./EpPacketRequest.js\";\r\nimport type { EpPacketReply } from \"./EpPacketReply.js\";\r\nimport type { EpPacketNotification } from \"./EpPacketNotification.js\";\r\n\r\n/**\r\n * An IIP/Ep protocol packet (port of C# `EpPacket`).\r\n *\r\n * Wire layout — header byte `[method:2][hasTDU:1][action:5]`, then a 4-byte\r\n * little-endian callback id for Request/Reply, then an optional self-describing\r\n * TDU (measured via {@link PlainTdu}, decoded later with connection context).\r\n */\r\nexport class EpPacket {\r\n  method: EpPacketMethod = EpPacketMethod.Notification;\r\n  /** The action in the low 5 bits (an EpPacketRequest/Reply/Notification or extension byte). */\r\n  action = 0;\r\n  callbackId = 0;\r\n  hasTdu = false;\r\n  tdu: PlainTdu | null = null;\r\n\r\n  private dataLengthNeeded = 0;\r\n\r\n  get request(): EpPacketRequest {\r\n    return this.action;\r\n  }\r\n  get reply(): EpPacketReply {\r\n    return this.action;\r\n  }\r\n  get notification(): EpPacketNotification {\r\n    return this.action;\r\n  }\r\n\r\n  private notEnough(offset: number, ends: number, needed: number): boolean {\r\n    if (offset + needed > ends) {\r\n      this.dataLengthNeeded = needed - (ends - offset);\r\n      return true;\r\n    }\r\n    return false;\r\n  }\r\n\r\n  /**\r\n   * Parse a packet from `data[offset..ends]`. Returns the number of bytes\r\n   * consumed, or a negative value (`-bytesStillNeeded`) if the buffer is short.\r\n   */\r\n  parse(data: Uint8Array, offset: number, ends: number): number {\r\n    const start = offset;\r\n\r\n    if (this.notEnough(offset, ends, 1)) return -this.dataLengthNeeded;\r\n\r\n    const header = data[offset++];\r\n    this.hasTdu = (header & 0x20) === 0x20;\r\n    this.method = (header >> 6) as EpPacketMethod;\r\n    this.action = header & 0x1f;\r\n\r\n    if (this.method === EpPacketMethod.Request || this.method === EpPacketMethod.Reply) {\r\n      if (this.notEnough(offset, ends, 4)) return -this.dataLengthNeeded;\r\n      this.callbackId = getUint32(data, offset);\r\n      offset += 4;\r\n    }\r\n\r\n    if (this.hasTdu) {\r\n      if (this.notEnough(offset, ends, 1)) return -this.dataLengthNeeded;\r\n      this.tdu = PlainTdu.parse(data, offset, ends);\r\n      if (this.tdu.tduClass === TduClass.Invalid) return -this.tdu.totalLength;\r\n      offset += this.tdu.totalLength;\r\n    } else {\r\n      this.tdu = null;\r\n    }\r\n\r\n    return offset - start;\r\n  }\r\n\r\n  // ---- compose helpers --------------------------------------------------------\r\n\r\n  private static header(method: EpPacketMethod, action: number, hasTdu: boolean): number {\r\n    return ((method << 6) | (hasTdu ? 0x20 : 0) | (action & 0x1f)) & 0xff;\r\n  }\r\n\r\n  /** Build a Request packet. */\r\n  static composeRequest(action: EpPacketRequest, callbackId: number, tdu?: Uint8Array): Uint8Array {\r\n    return merge(\r\n      Uint8Array.of(EpPacket.header(EpPacketMethod.Request, action, tdu != null)),\r\n      uint32ToBytes(callbackId),\r\n      tdu ?? new Uint8Array(0),\r\n    );\r\n  }\r\n\r\n  /** Build a Reply packet. */\r\n  static composeReply(action: EpPacketReply, callbackId: number, tdu?: Uint8Array): Uint8Array {\r\n    return merge(\r\n      Uint8Array.of(EpPacket.header(EpPacketMethod.Reply, action, tdu != null)),\r\n      uint32ToBytes(callbackId),\r\n      tdu ?? new Uint8Array(0),\r\n    );\r\n  }\r\n\r\n  /** Build a Notification packet. */\r\n  static composeNotification(action: EpPacketNotification, tdu?: Uint8Array): Uint8Array {\r\n    return merge(\r\n      Uint8Array.of(EpPacket.header(EpPacketMethod.Notification, action, tdu != null)),\r\n      tdu ?? new Uint8Array(0),\r\n    );\r\n  }\r\n}\r\n","/** Top 2 bits of an Ep packet header — the packet method (port of C# `EpPacketMethod`). */\r\nexport enum EpPacketMethod {\r\n  Notification = 0,\r\n  Request = 1,\r\n  Reply = 2,\r\n  Extension = 3,\r\n}\r\n","/** Request actions, in the low 5 bits of the header (port of C# `EpPacketRequest`). */\r\nexport enum EpPacketRequest {\r\n  // Invoke\r\n  InvokeFunction = 0x0,\r\n  SetProperty = 0x1,\r\n  Subscribe = 0x2,\r\n  Unsubscribe = 0x3,\r\n  // Inquire\r\n  /** Batch name → id lookup (request: `string[]`, reply: `ulong[]`). */\r\n  TypeDefIdsByNames = 0x8,\r\n  TypeDefById = 0x9,\r\n  TypeDefByResourceId = 0xa,\r\n  Query = 0xb,\r\n  LinkTypeDefs = 0xc,\r\n  Token = 0xd,\r\n  GetResourceIdByLink = 0xe,\r\n  // Manage\r\n  AttachResource = 0x10,\r\n  ReattachResource = 0x11,\r\n  DetachResource = 0x12,\r\n  CreateResource = 0x13,\r\n  DeleteResource = 0x14,\r\n  MoveResource = 0x15,\r\n  // Static\r\n  KeepAlive = 0x18,\r\n  ProcedureCall = 0x19,\r\n  StaticCall = 0x1a,\r\n  IndirectCall = 0x1b,\r\n  PullStream = 0x1c,\r\n  TerminateExecution = 0x1d,\r\n  HaltExecution = 0x1e,\r\n  ResumeExecution = 0x1f,\r\n}\r\n","/** Reply actions, in the low 5 bits of the header (port of C# `EpPacketReply`). */\r\nexport enum EpPacketReply {\r\n  // Success\r\n  Completed = 0x0,\r\n  Propagated = 0x1,\r\n  Stream = 0x2,\r\n  // Error\r\n  PermissionError = 0x4,\r\n  ExecutionError = 0x5,\r\n  // Partial\r\n  Progress = 0x8,\r\n  Chunk = 0x9,\r\n  Warning = 0xa,\r\n}\r\n","/** Notification actions, in the low 5 bits of the header (port of C# `EpPacketNotification`). */\r\nexport enum EpPacketNotification {\r\n  // Invoke\r\n  PropertyModified = 0x0,\r\n  EventOccurred = 0x1,\r\n  // Manage\r\n  ResourceDestroyed = 0x8,\r\n  ResourceReassigned = 0x9,\r\n  ResourceMoved = 0xa,\r\n  SystemFailure = 0xb,\r\n}\r\n","import { AsyncReply } from \"../../core/AsyncReply.js\";\r\nimport { AsyncException } from \"../../core/AsyncException.js\";\r\nimport type { DestroyedEvent } from \"../../core/IDestructible.js\";\r\nimport { NetworkBuffer } from \"../NetworkBuffer.js\";\r\nimport type { INetworkReceiver } from \"../INetworkReceiver.js\";\r\nimport type { ISocket } from \"./ISocket.js\";\r\nimport { SocketState } from \"./SocketState.js\";\r\n\r\nconst textEncoder = new TextEncoder();\r\n\r\n/**\r\n * The WebSocket subprotocol esiur-dotnet's `FrameworkWebSocket` requires be\r\n * negotiated (`FrameworkWebSocket.SubProtocol`, `Net/Sockets/FrameworkWebSocket.cs`).\r\n * A current esiur-dotnet server rejects the upgrade with `400 Bad Request`\r\n * if the client doesn't request it.\r\n */\r\nconst EP_SUBPROTOCOL = \"EP\";\r\n\r\n/**\r\n * WebSocket transport (port of C# `WSocket`). Unlike the C# version it does no\r\n * frame parsing — both the browser `WebSocket` and Node's global `WebSocket`\r\n * (and `ws`) deliver already-deframed binary messages. Works in any environment\r\n * that exposes the standard `WebSocket` (browser, Node ≥ 21, or a `ws` instance\r\n * passed to the constructor).\r\n */\r\nexport class WSocket implements ISocket {\r\n  state: SocketState = SocketState.Initial;\r\n  receiver?: INetworkReceiver<ISocket>;\r\n\r\n  private ws?: WebSocket;\r\n  private readonly buffer = new NetworkBuffer();\r\n  private readonly destroyHandlers: DestroyedEvent[] = [];\r\n\r\n  constructor(ws?: WebSocket) {\r\n    if (ws) this.attach(ws);\r\n  }\r\n\r\n  connect(url: string): AsyncReply<boolean> {\r\n    const reply = new AsyncReply<boolean>();\r\n    this.state = SocketState.Connecting;\r\n\r\n    (async () => {\r\n      try {\r\n        const ws = await createWebSocket(url);\r\n        if (this.state !== SocketState.Connecting) {\r\n          ws.close();\r\n          return;\r\n        }\r\n\r\n        this.attach(ws);\r\n        ws.addEventListener(\"open\", () => {\r\n          if (ws.protocol && ws.protocol !== EP_SUBPROTOCOL) {\r\n            this.state = SocketState.Closed;\r\n            ws.close();\r\n            reply.triggerError(\r\n              new AsyncException(\r\n                new Error(\r\n                  `The server did not negotiate the required '${EP_SUBPROTOCOL}' WebSocket subprotocol (got '${ws.protocol}').`,\r\n                ),\r\n              ),\r\n            );\r\n            return;\r\n          }\r\n          this.state = SocketState.Established;\r\n          reply.trigger(true);\r\n          this.receiver?.networkConnect(this);\r\n        });\r\n        ws.addEventListener(\"error\", () => {\r\n          if (this.state === SocketState.Connecting)\r\n            reply.triggerError(\r\n              new AsyncException(new Error(`WebSocket connection to ${url} failed.`)),\r\n            );\r\n        });\r\n      } catch (error) {\r\n        this.state = SocketState.Closed;\r\n        reply.triggerError(AsyncException.from(error));\r\n      }\r\n    })();\r\n\r\n    return reply;\r\n  }\r\n\r\n  private attach(ws: WebSocket): void {\r\n    this.ws = ws;\r\n    ws.binaryType = \"arraybuffer\";\r\n\r\n    ws.addEventListener(\"message\", (ev: MessageEvent) => {\r\n      const bytes = toBytes(ev.data);\r\n      if (bytes.length === 0) return;\r\n      this.buffer.write(bytes);\r\n      this.receiver?.networkReceive(this, this.buffer);\r\n    });\r\n    ws.addEventListener(\"close\", () => {\r\n      this.state = SocketState.Closed;\r\n      this.receiver?.networkClose(this);\r\n    });\r\n\r\n    if (ws.readyState === 1) this.state = SocketState.Established;\r\n  }\r\n\r\n  send(message: Uint8Array): void {\r\n    this.ws?.send(message);\r\n  }\r\n\r\n  close(): void {\r\n    this.state = SocketState.Closed;\r\n    this.ws?.close();\r\n  }\r\n\r\n  addDestroyHandler(handler: DestroyedEvent): void {\r\n    this.destroyHandlers.push(handler);\r\n  }\r\n\r\n  removeDestroyHandler(handler: DestroyedEvent): void {\r\n    const i = this.destroyHandlers.indexOf(handler);\r\n    if (i >= 0) this.destroyHandlers.splice(i, 1);\r\n  }\r\n\r\n  destroy(): void {\r\n    this.close();\r\n    this.receiver = undefined;\r\n    this.ws = undefined;\r\n    for (const h of this.destroyHandlers.slice()) h(this);\r\n  }\r\n}\r\n\r\n/** Normalize a WebSocket message payload to bytes. */\r\nfunction toBytes(data: unknown): Uint8Array {\r\n  if (data instanceof ArrayBuffer) return new Uint8Array(data);\r\n  if (ArrayBuffer.isView(data))\r\n    return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\r\n  if (typeof data === \"string\") return textEncoder.encode(data);\r\n  return new Uint8Array(0);\r\n}\r\n\r\ntype WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocket;\r\n\r\nasync function createWebSocket(url: string): Promise<WebSocket> {\r\n  const ctor = await getWebSocketConstructor();\r\n  return new ctor(url, EP_SUBPROTOCOL);\r\n}\r\n\r\nasync function getWebSocketConstructor(): Promise<WebSocketConstructor> {\r\n  if (typeof globalThis.WebSocket === \"function\")\r\n    return globalThis.WebSocket as WebSocketConstructor;\r\n\r\n  try {\r\n    const ws = await import(\"ws\");\r\n    const ctor = ws.WebSocket ?? ws.default;\r\n    if (typeof ctor === \"function\") return ctor as unknown as WebSocketConstructor;\r\n  } catch (error) {\r\n    throw new Error(\r\n      \"No WebSocket implementation is available. In Node.js 18-20, install the optional peer dependency 'ws'.\",\r\n      { cause: error },\r\n    );\r\n  }\r\n\r\n  throw new Error(\r\n    \"No WebSocket implementation is available. In Node.js 18-20, install the optional peer dependency 'ws'.\",\r\n  );\r\n}\r\n","import { PlainTdu } from \"../../data/PlainTdu.js\";\r\nimport { TduClass } from \"../../data/TduClass.js\";\r\nimport { merge } from \"../../data/DC.js\";\r\nimport { EpAuthPacketCommand } from \"./EpAuthPacketCommand.js\";\r\nimport { EpAuthPacketMethod } from \"./EpAuthPacketMethod.js\";\r\nimport { AuthenticationMode } from \"../../security/AuthenticationMode.js\";\r\nimport { EncryptionMode } from \"../../security/EncryptionMode.js\";\r\n\r\n/**\r\n * Authentication-phase packet (port of C# `EpAuthPacket`).\r\n *\r\n * Header byte: `[command:2][hasTDU:1][…]`. For Initialize the low bits carry\r\n * `authMode<<2 | encryptionMode`; for the other commands they carry the\r\n * {@link EpAuthPacketMethod} (whose own top bits repeat the command). An\r\n * optional TDU follows — typically a `TypedMap<u8, dynamic>` of headers.\r\n */\r\nexport class EpAuthPacket {\r\n  command: EpAuthPacketCommand = EpAuthPacketCommand.Initialize;\r\n  method: EpAuthPacketMethod = EpAuthPacketMethod.Initialize;\r\n  authMode: AuthenticationMode = AuthenticationMode.None;\r\n  encryptionMode: EncryptionMode = EncryptionMode.None;\r\n  hasTdu = false;\r\n  tdu: PlainTdu | null = null;\r\n  errorCode = 0;\r\n  sessionId: Uint8Array | null = null;\r\n  /** IAuth reference, set by auth-flow logic (not read from `data[]` by {@link parse}). */\r\n  reference = 0;\r\n\r\n  private dataLengthNeeded = 0;\r\n\r\n  private notEnough(offset: number, ends: number, needed: number): boolean {\r\n    if (offset + needed > ends) {\r\n      this.dataLengthNeeded = needed - (ends - offset);\r\n      return true;\r\n    }\r\n    return false;\r\n  }\r\n\r\n  /** Parse an auth packet; returns bytes consumed or `-bytesNeeded`. */\r\n  parse(data: Uint8Array, offset: number, ends: number): number {\r\n    this.tdu = null;\r\n    const start = offset;\r\n\r\n    if (this.notEnough(offset, ends, 1)) return -this.dataLengthNeeded;\r\n\r\n    const b = data[offset];\r\n    this.command = (b >> 6) as EpAuthPacketCommand;\r\n    this.hasTdu = (b & 0x20) !== 0;\r\n\r\n    if (this.command === EpAuthPacketCommand.Initialize) {\r\n      this.authMode = ((b >> 2) & 0x3) as AuthenticationMode;\r\n      this.encryptionMode = (b & 0x3) as EncryptionMode;\r\n    } else {\r\n      this.method = (b & 0xdf) as EpAuthPacketMethod;\r\n    }\r\n    offset++;\r\n\r\n    if (this.hasTdu) {\r\n      if (this.notEnough(offset, ends, 1)) return -this.dataLengthNeeded;\r\n      this.tdu = PlainTdu.parse(data, offset, ends);\r\n      if (this.tdu.tduClass === TduClass.Invalid) return -this.tdu.totalLength;\r\n      offset += this.tdu.totalLength;\r\n    }\r\n\r\n    return offset - start;\r\n  }\r\n\r\n  // ---- compose helpers --------------------------------------------------------\r\n\r\n  /** Build an Initialize packet (`authMode`/`encryptionMode` in the low bits). */\r\n  static composeInitialize(\r\n    authMode: AuthenticationMode,\r\n    encryptionMode: EncryptionMode,\r\n    headersTdu?: Uint8Array,\r\n  ): Uint8Array {\r\n    const header =\r\n      ((EpAuthPacketCommand.Initialize << 6) |\r\n        (headersTdu ? 0x20 : 0) |\r\n        ((authMode & 0x3) << 2) |\r\n        (encryptionMode & 0x3)) &\r\n      0xff;\r\n    return headersTdu ? merge(Uint8Array.of(header), headersTdu) : Uint8Array.of(header);\r\n  }\r\n\r\n  /** Build a non-Initialize packet from a method (whose top bits carry the command). */\r\n  static composeMethod(method: EpAuthPacketMethod, headersTdu?: Uint8Array): Uint8Array {\r\n    const header = (method | (headersTdu ? 0x20 : 0)) & 0xff;\r\n    return headersTdu ? merge(Uint8Array.of(header), headersTdu) : Uint8Array.of(header);\r\n  }\r\n}\r\n","/** Top 2 bits of an auth packet header — the command (port of C# `EpAuthPacketCommand`). */\r\nexport enum EpAuthPacketCommand {\r\n  Initialize = 0x0,\r\n  Acknowledge = 0x1,\r\n  Action = 0x2,\r\n  Event = 0x3,\r\n}\r\n","/**\r\n * Auth packet methods (port of C# `EpAuthPacketMethod`). The top 2 bits encode\r\n * the {@link EpAuthPacketCommand}; e.g. `SessionEstablished` (0x47) is an\r\n * Acknowledge.\r\n */\r\nexport enum EpAuthPacketMethod {\r\n  // Initialize\r\n  Initialize = 0x00,\r\n\r\n  // Actions\r\n  Handshake = 0x80,\r\n  FinalHandshake = 0x81,\r\n\r\n  // Acknowledgements\r\n  Denied = 0x40,\r\n  NotSupported = 0x41,\r\n  TrySupported = 0x42,\r\n  Retry = 0x43,\r\n  ProceedToHandshake = 0x44,\r\n  ProceedToFinalHandshake = 0x45,\r\n  ProceedToEstablishSession = 0x46,\r\n  SessionEstablished = 0x47,\r\n\r\n  // Events\r\n  Established = 0xc0,\r\n  ErrorTerminate = 0xc1,\r\n  ErrorMustEncrypt = 0xc2,\r\n  ErrorRetry = 0xc3,\r\n  IndicationEstablished = 0xc8,\r\n  IAuthPlain = 0xd0,\r\n  IAuthHashed = 0xd1,\r\n  IAuthEncrypted = 0xd2,\r\n}\r\n","/** Which parties prove identity during the handshake (port of C# `AuthenticationMode`). */\r\nexport enum AuthenticationMode {\r\n  None = 0x0,\r\n  InitializerIdentity = 0x1,\r\n  ResponderIdentity = 0x2,\r\n  DualIdentity = 0x3,\r\n}\r\n","/** Transport encryption mode (port of C# `EncryptionMode`). */\r\nexport enum EncryptionMode {\r\n  None = 0,\r\n  EncryptWithSessionKey = 1,\r\n  EncryptWithSessionKeyAndAddress = 2,\r\n}\r\n","/** Header keys carried in an auth packet's TypedMap (port of C# `EpAuthPacketHeader`). */\r\nexport enum EpAuthPacketHeader {\r\n  Version = 0,\r\n  Domain = 1,\r\n  SupportedAuthentications = 2,\r\n  SupportedHashAlgorithms = 3,\r\n  SupportedCiphers = 4,\r\n  SupportedCompression = 5,\r\n  SupportedMultiFactorAuthentications = 6,\r\n  CipherType = 7,\r\n  CipherKey = 8,\r\n  SoftwareIdentity = 9,\r\n  Referrer = 10,\r\n  Time = 11,\r\n  IPAddress = 12,\r\n  Identity = 13,\r\n  AuthenticationProtocol = 14,\r\n  AuthenticationData = 15,\r\n  ErrorMessage = 16,\r\n  /** Fresh public nonce used with the authenticated session key to derive unique per-connection encryption keys. */\r\n  CipherNonce = 17,\r\n}\r\n","/** Which side of the authentication exchange this handler represents. */\r\nexport enum AuthenticationDirection {\r\n  Initiator = 0,\r\n  Responder = 1,\r\n}\r\n","/** Material kinds passed to authentication providers. */\r\nexport enum AuthenticationMaterialType {\r\n  Secret = 0,\r\n  Key = 1,\r\n  Identity = 2,\r\n  Data = 3,\r\n}\r\n","import type { ExceptionCode } from \"../core/ExceptionCode.js\";\r\nimport type { AuthenticationRuling } from \"./AuthenticationRuling.js\";\r\n\r\n/** Result returned by one authentication handler step. */\r\nexport class AuthenticationResult {\r\n  constructor(\r\n    readonly ruling: AuthenticationRuling,\r\n    readonly authenticationData: unknown,\r\n    readonly localIdentity: string | null = null,\r\n    readonly remoteIdentity: string | null = null,\r\n    readonly sessionKey: Uint8Array | null = null,\r\n    readonly exceptionCode: ExceptionCode | null = null,\r\n    readonly exceptionMessage: string | null = null,\r\n  ) {}\r\n}\r\n","/** Result state returned by an authentication handler step. */\r\nexport enum AuthenticationRuling {\r\n  Failed = 0,\r\n  InProgress = 1,\r\n  Succeeded = 2,\r\n}\r\n","/** Generate `length` cryptographically-random bytes. */\r\nexport function randomBytes(length: number): Uint8Array {\r\n  const out = new Uint8Array(length);\r\n  const crypto = globalThis.crypto as\r\n    | { getRandomValues?: (target: Uint8Array) => Uint8Array }\r\n    | undefined;\r\n  if (!crypto?.getRandomValues)\r\n    throw new Error(\"Secure random bytes are unavailable in this environment.\");\r\n  crypto.getRandomValues(out);\r\n  return out;\r\n}\r\n","import type { Warehouse } from \"../../resource/Warehouse.js\";\r\nimport type { EpConnection } from \"../../protocol/EpConnection.js\";\r\nimport type { AuthenticationSession } from \"../AuthenticationSession.js\";\r\nimport type { IResource } from \"../../resource/IResource.js\";\r\nimport type { MemberTemplate, TypeDef } from \"../../resource/template.js\";\r\nimport type { ActionType } from \"../permissions/ActionType.js\";\r\n\r\n/**\r\n * Metadata describing a resource operation being evaluated by managers\r\n * (port of C# `ResourceManagerContext`). Operation identity is immutable;\r\n * {@link ResourceManagerContext.delay}/{@link ResourceManagerContext.denialReason}\r\n * let a manager return admission details.\r\n *\r\n * `memberPolicyAttributes` is always empty in this port: dotnet lets any\r\n * custom `Attribute` ride along for bespoke manager types via reflection;\r\n * TS has no reflection-based generic attribute bag to source that from, and\r\n * nothing in this port's manager set (Permissions/RateControl/Auditing)\r\n * reads it, so it's kept only for shape parity with the C# constructor.\r\n */\r\nexport class ResourceManagerContext {\r\n  /** Optional delay requested by a rate-control manager. */\r\n  delay = 0;\r\n  /** Optional public-safe reason supplied by a manager when it denies an operation. */\r\n  denialReason: string | undefined;\r\n\r\n  readonly memberPolicyAttributes: readonly unknown[];\r\n  readonly typeDefinition: TypeDef | null;\r\n\r\n  constructor(\r\n    readonly warehouse: Warehouse,\r\n    readonly connection: EpConnection | null,\r\n    readonly session: AuthenticationSession | null,\r\n    readonly resource: IResource | null,\r\n    readonly member: MemberTemplate | null,\r\n    readonly action: ActionType,\r\n    readonly inquirer: unknown = null,\r\n    memberPolicyAttributes: readonly unknown[] = [],\r\n    typeDefinition: TypeDef | null = null,\r\n    readonly supportsDelay = false,\r\n  ) {\r\n    this.memberPolicyAttributes = memberPolicyAttributes;\r\n    this.typeDefinition = typeDefinition;\r\n  }\r\n}\r\n","/** A resource operation category evaluated by resource managers (port of C# `ActionType`). */\r\nexport enum ActionType {\r\n  Attach = 0,\r\n  Delete = 1,\r\n  Execute = 2,\r\n  GetProperty = 3,\r\n  SetProperty = 4,\r\n  CreateResource = 5,\r\n  UpdateAttributes = 6,\r\n  InquireAttributes = 7,\r\n  AddParent = 8,\r\n  RemoveParent = 9,\r\n  AddChild = 10,\r\n  RemoveChild = 11,\r\n  Rename = 12,\r\n  ReceiveEvent = 13,\r\n  ViewTypeDef = 14,\r\n  Detach = 15,\r\n  Subscribe = 16,\r\n  Unsubscribe = 17,\r\n  PullStream = 18,\r\n  TerminateExecution = 19,\r\n  HaltExecution = 20,\r\n  ResumeExecution = 21,\r\n}\r\n","import { TypeDefInfo } from \"../data/types/TypeDefInfo.js\";\r\nimport { PropertyDefInfo } from \"../data/types/PropertyDefInfo.js\";\r\nimport { FunctionDefInfo } from \"../data/types/FunctionDefInfo.js\";\r\nimport { EventDefInfo } from \"../data/types/EventDefInfo.js\";\r\nimport { ArgumentDefInfo } from \"../data/types/ArgumentDefInfo.js\";\r\nimport { PropertyDefFlags } from \"../data/types/PropertyDefFlags.js\";\r\nimport { FunctionDefFlags } from \"../data/types/FunctionDefFlags.js\";\r\nimport { EventDefFlags } from \"../data/types/EventDefFlags.js\";\r\nimport { ArgumentDefFlags } from \"../data/types/ArgumentDefFlags.js\";\r\nimport type { TypeDefKind } from \"../data/types/ITypeDef.js\";\r\nimport type {\r\n  ArgumentTemplate,\r\n  EventTemplate,\r\n  FunctionTemplate,\r\n  PropertyTemplate,\r\n  TypeDef,\r\n} from \"./template.js\";\r\n\r\n/**\r\n * Build the wire-format {@link TypeDefInfo} for a resource's decorated\r\n * {@link TypeDef} surface (port of C# `TypeDefInfo.FromTypeDef`). `id`/`kind`\r\n * are supplied separately since ts's structural `TypeDef` (unlike dotnet's\r\n * richer class) carries no id of its own — callers pass the id a\r\n * `LocalTypeDef` was registered under, or (when relaying) the id assigned by\r\n * the upstream connection that originally described the type.\r\n *\r\n * ts's `PropertyTemplate`/`FunctionTemplate`/`EventTemplate` are leaner than\r\n * dotnet's `MemberDef` — no `usage`/`description`/`examples`/etc. metadata,\r\n * no resource-level constant members — so most `MemberDefInfo` fields beyond\r\n * identity/flags/type stay `undefined`; that's an accepted, current gap, not\r\n * an oversight here.\r\n */\r\nexport function typeDefInfoFromTypeDef(id: number, kind: TypeDefKind, typeDef: TypeDef): TypeDefInfo {\r\n  const info = new TypeDefInfo();\r\n  info.id = id;\r\n  info.kind = kind;\r\n  info.name = typeDef.className;\r\n  info.annotations = typeDef.annotations;\r\n  info.properties = typeDef.properties.map(propertyDefInfoFromTemplate);\r\n  info.functions = typeDef.functions.map(functionDefInfoFromTemplate);\r\n  info.events = typeDef.events.map(eventDefInfoFromTemplate);\r\n  return info;\r\n}\r\n\r\nfunction propertyDefInfoFromTemplate(source: PropertyTemplate): PropertyDefInfo {\r\n  const info = new PropertyDefInfo();\r\n  info.index = source.index;\r\n  info.name = source.name;\r\n  info.flags = source.readOnly ? PropertyDefFlags.ReadOnly : PropertyDefFlags.None;\r\n  info.annotations = source.annotations;\r\n  info.valueType = source.valueType;\r\n  return info;\r\n}\r\n\r\nfunction functionDefInfoFromTemplate(source: FunctionTemplate): FunctionDefInfo {\r\n  const info = new FunctionDefInfo();\r\n  info.index = source.index;\r\n  info.name = source.name;\r\n  info.flags = source.isStatic ? FunctionDefFlags.Static : FunctionDefFlags.None;\r\n  info.annotations = source.annotations;\r\n  info.returnType = source.returnType;\r\n  info.arguments = source.args.map(argumentDefInfoFromTemplate);\r\n  return info;\r\n}\r\n\r\nfunction eventDefInfoFromTemplate(source: EventTemplate): EventDefInfo {\r\n  const info = new EventDefInfo();\r\n  info.index = source.index;\r\n  info.name = source.name;\r\n  info.flags = source.subscribable ? EventDefFlags.None : EventDefFlags.AutoDelivered;\r\n  info.annotations = source.annotations;\r\n  info.argumentType = source.argType;\r\n  return info;\r\n}\r\n\r\nfunction argumentDefInfoFromTemplate(source: ArgumentTemplate, index: number): ArgumentDefInfo {\r\n  const info = new ArgumentDefInfo();\r\n  info.index = index;\r\n  info.name = source.name;\r\n  info.flags = source.optional ? ArgumentDefFlags.Optional : ArgumentDefFlags.None;\r\n  info.annotations = source.annotations;\r\n  info.valueType = source.type;\r\n  return info;\r\n}\r\n","import { EventHandler } from \"../core/EventHandler.js\";\r\nimport { AsyncReply } from \"../core/AsyncReply.js\";\r\nimport type { DestroyedEvent } from \"../core/IDestructible.js\";\r\nimport { TypeDef } from \"../resource/template.js\";\r\nimport type { Instance } from \"../resource/Instance.js\";\r\nimport type { IResource, IResourceContext } from \"../resource/IResource.js\";\r\nimport type { IDynamicResource } from \"../resource/IDynamicResource.js\";\r\nimport { ResourceOperation } from \"../resource/ResourceOperation.js\";\r\nimport type { EpConnection } from \"./EpConnection.js\";\r\n\r\n/** Notification payload for a remote property change. */\r\nexport interface RemotePropertyChange {\r\n  name: string;\r\n  index: number;\r\n  value: unknown;\r\n  age?: number;\r\n  date?: Date;\r\n}\r\n\r\n/** Snapshot metadata for one remote property value. */\r\nexport interface RemotePropertyValue {\r\n  index: number;\r\n  age: number;\r\n  date?: Date;\r\n  value: unknown;\r\n}\r\n\r\nexport interface EpResourceOptions {\r\n  typeDefId?: number;\r\n  age?: number;\r\n  link?: string;\r\n  hops?: number;\r\n}\r\n\r\n/** Constructor shape emitted by generated TypeScript remote resource stubs. */\r\nexport type EpResourceConstructor<T extends EpResource = EpResource> = new (\r\n  connection: EpConnection,\r\n  instanceId: number,\r\n  age: number,\r\n  link: string,\r\n) => T;\r\n\r\n/**\r\n * A remote resource proxy (port of C# `EpResource`). Wraps a connection +\r\n * instance id + TypeDef; exported functions invoke remotely, exported\r\n * properties read from a locally-cached value (kept fresh by PropertyModified\r\n * notifications), and exported events surface via {@link eventOccurred}.\r\n *\r\n * Use {@link createProxy} to get an ergonomic object where `res.sayHi(x)` and\r\n * `res.counts` work directly.\r\n *\r\n * Implements {@link IResource}/{@link IDynamicResource} so it can be\r\n * `warehouse.put()` into this node's own warehouse — every proxy is itself a\r\n * resource with a life cycle, and once put, a third node connecting to this\r\n * one can attach to it too, relaying reads/writes/invokes/events through to\r\n * the original connection transparently.\r\n */\r\nexport class EpResource implements IResource, IDynamicResource {\r\n  /** Assigned by the {@link Warehouse} on `put()` — absent until relayed. */\r\n  instance?: Instance;\r\n\r\n  private readonly destroyHandlers: DestroyedEvent[] = [];\r\n\r\n  /** Property index to last known value. */\r\n  readonly cache = new Map<number, unknown>();\r\n  /** Property index to last known property age. */\r\n  readonly propertyAges = new Map<number, number>();\r\n  /** Property index to last known modification date. */\r\n  readonly propertyModificationDates = new Map<number, Date | undefined>();\r\n  /** Fires when a property is updated by a notification. */\r\n  readonly propertyModified = new EventHandler<RemotePropertyChange>();\r\n  /** Fires when a remote event occurs. */\r\n  readonly eventOccurred = new EventHandler<RemotePropertyChange>();\r\n\r\n  /** `.on(\":name\", cb)` listeners, keyed by property index. */\r\n  private readonly propertyListeners = new Map<number, Set<(value: unknown) => void>>();\r\n  /** `.on(\"name\", cb)` listeners, keyed by event index. */\r\n  private readonly eventListeners = new Map<number, Set<(value: unknown) => void>>();\r\n  /** Events we believe the server currently has us subscribed to — checked\r\n   * before sending a Subscribe/Unsubscribe request, since the server errors\r\n   * (`AlreadyListened`/`AlreadyUnsubscribed`) on a redundant one. */\r\n  private readonly subscribedEvents = new Set<number>();\r\n  /** Event indices with a subscription-reconciliation loop currently running. */\r\n  private readonly reconciling = new Set<number>();\r\n\r\n  typeDefId?: number;\r\n  age = 0;\r\n  link = \"\";\r\n  hops = 0;\r\n\r\n  connection!: EpConnection;\r\n  instanceId = 0;\r\n  typeDef: TypeDef = new TypeDef(\"\", []);\r\n\r\n  /** Array alias used by generated stubs (`this.properties[index]`). */\r\n  protected readonly properties: unknown[] = [];\r\n  /** .NET-name alias used by generated stubs (`this._properties[index]`). */\r\n  protected readonly _properties = this.properties;\r\n\r\n  constructor();\r\n  constructor(\r\n    connection: EpConnection,\r\n    instanceId: number,\r\n    typeDef: TypeDef,\r\n    options?: EpResourceOptions,\r\n  );\r\n  constructor(connection: EpConnection, instanceId: number, age: number, link?: string);\r\n  constructor(\r\n    connection?: EpConnection,\r\n    instanceId = 0,\r\n    typeDefOrAge?: TypeDef | number,\r\n    optionsOrLink: EpResourceOptions | string = {},\r\n  ) {\r\n    if (connection) this.connection = connection;\r\n    this.instanceId = instanceId;\r\n\r\n    if (isTypeDef(typeDefOrAge)) {\r\n      this.typeDef = typeDefOrAge;\r\n      const options =\r\n        typeof optionsOrLink === \"string\" ? { link: optionsOrLink } : optionsOrLink;\r\n      this.setRemoteIdentity(options);\r\n    } else {\r\n      this.age = typeDefOrAge ?? 0;\r\n      this.link =\r\n        typeof optionsOrLink === \"string\" ? optionsOrLink : (optionsOrLink.link ?? \"\");\r\n      if (typeof optionsOrLink !== \"string\") this.setRemoteIdentity(optionsOrLink);\r\n    }\r\n\r\n    this.propertyModified.add((change) => {\r\n      for (const cb of this.propertyListeners.get(change.index) ?? []) cb(change.value);\r\n    });\r\n    this.eventOccurred.add((change) => {\r\n      for (const cb of this.eventListeners.get(change.index) ?? []) cb(change.value);\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Listen for a property change (`.on(\":propName\", cb)`) or an exported\r\n   * event (`.on(\"eventName\", cb)`). For events where the TypeDef marks\r\n   * `subscribable` (i.e. not `autoDelivered`), the first listener triggers a\r\n   * `Subscribe` request and the last {@link off} triggers `Unsubscribe` —\r\n   * ref-counted by listener count, so redundant wire requests aren't sent\r\n   * for a second/third listener on the same already-subscribed event.\r\n   */\r\n  on(name: string, callback: (value: unknown) => void): this {\r\n    if (name.startsWith(\":\")) {\r\n      const propertyName = name.slice(1);\r\n      const property = this.typeDef.getPropertyByName(propertyName);\r\n      if (!property) throw new Error(`Unknown property \"${propertyName}\".`);\r\n      getOrCreate(this.propertyListeners, property.index).add(callback);\r\n      return this;\r\n    }\r\n    const event = this.typeDef.getEventByName(name);\r\n    if (!event) throw new Error(`Unknown event \"${name}\".`);\r\n    getOrCreate(this.eventListeners, event.index).add(callback);\r\n    if (event.subscribable) this.reconcileSubscription(event.index);\r\n    return this;\r\n  }\r\n\r\n  /** Remove a listener registered with {@link on}. */\r\n  off(name: string, callback: (value: unknown) => void): this {\r\n    if (name.startsWith(\":\")) {\r\n      const property = this.typeDef.getPropertyByName(name.slice(1));\r\n      if (property) this.propertyListeners.get(property.index)?.delete(callback);\r\n      return this;\r\n    }\r\n    const event = this.typeDef.getEventByName(name);\r\n    if (!event) return this;\r\n    this.eventListeners.get(event.index)?.delete(callback);\r\n    if (event.subscribable) this.reconcileSubscription(event.index);\r\n    return this;\r\n  }\r\n\r\n  /**\r\n   * Settle the wire subscription state for event `index` toward whatever the\r\n   * current listener count implies, retrying against the *current* desired\r\n   * state on each step — so a burst of `on()`/`off()` calls while a request\r\n   * is in flight is coalesced into whatever the state actually is once the\r\n   * in-flight request settles, rather than replaying every transition.\r\n   */\r\n  private reconcileSubscription(index: number): void {\r\n    if (this.reconciling.has(index)) return;\r\n    this.reconciling.add(index);\r\n    (async () => {\r\n      for (;;) {\r\n        const desired = (this.eventListeners.get(index)?.size ?? 0) > 0;\r\n        const actual = this.subscribedEvents.has(index);\r\n        if (desired === actual) return;\r\n        try {\r\n          if (desired) {\r\n            await this.connection.subscribe(this.instanceId, index);\r\n            this.subscribedEvents.add(index);\r\n          } else {\r\n            await this.connection.unsubscribe(this.instanceId, index);\r\n            this.subscribedEvents.delete(index);\r\n          }\r\n        } catch {\r\n          // Leave `subscribedEvents` as-is; the next on()/off() call that\r\n          // changes the listener count re-triggers reconciliation, so a\r\n          // transient failure here just needs another transition to retry.\r\n          return;\r\n        }\r\n      }\r\n    })().finally(() => this.reconciling.delete(index));\r\n  }\r\n\r\n  /**\r\n   * @internal After a reattach on a fresh connection (post-reconnect), our\r\n   * belief about server-side subscription state is stale — a brand-new\r\n   * connection starts with no subscriptions of its own, even for events we\r\n   * were subscribed to before the disconnect. Clear that belief and re-run\r\n   * reconciliation for every event that still has active listeners (from\r\n   * `.on()` or, on the .NET side's equivalent, `+=`), so subscriptions\r\n   * survive a reconnect transparently.\r\n   */\r\n  resubscribeAfterReconnect(): void {\r\n    this.subscribedEvents.clear();\r\n    this.reconciling.clear();\r\n    for (const index of this.eventListeners.keys()) {\r\n      if ((this.eventListeners.get(index)?.size ?? 0) === 0) continue;\r\n      const event = this.typeDef.getEventByIndex(index);\r\n      if (event?.subscribable) this.reconcileSubscription(index);\r\n    }\r\n  }\r\n\r\n  /** @deprecated Use {@link typeDef}. */\r\n  get template(): TypeDef {\r\n    return this.typeDef;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link connection}. */\r\n  get ResourceConnection(): EpConnection {\r\n    return this.connection;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link link}. */\r\n  get ResourceLink(): string {\r\n    return this.link;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link instanceId}. */\r\n  get ResourceInstanceId(): number {\r\n    return this.instanceId;\r\n  }\r\n\r\n  set ResourceInstanceId(value: number) {\r\n    this.instanceId = value;\r\n  }\r\n\r\n  /** .NET-compatible alias for {@link typeDef}. */\r\n  get ResourceDefinition(): TypeDef {\r\n    return this.typeDef;\r\n  }\r\n\r\n  set ResourceDefinition(value: TypeDef) {\r\n    this.typeDef = value;\r\n  }\r\n\r\n  /** @internal Initialize an instance created from a generated subclass. */\r\n  initializeRemote(\r\n    connection: EpConnection,\r\n    instanceId: number,\r\n    typeDef: TypeDef,\r\n    options: EpResourceOptions = {},\r\n  ): void {\r\n    this.connection = connection;\r\n    this.instanceId = instanceId;\r\n    this.typeDef = typeDef;\r\n    this.setRemoteIdentity(options);\r\n  }\r\n\r\n  /** @internal Update resource-level metadata returned by attach/reattach. */\r\n  setRemoteIdentity(options: EpResourceOptions & { instanceId?: number }): void {\r\n    if (options.instanceId != null) this.instanceId = options.instanceId;\r\n    if (options.typeDefId != null) this.typeDefId = options.typeDefId;\r\n    if (options.age != null) this.age = options.age;\r\n    if (options.link != null) this.link = options.link;\r\n    if (options.hops != null) this.hops = options.hops;\r\n  }\r\n\r\n  /** @internal Seed or merge a property snapshot without implying a notification. */\r\n  setPropertySnapshot(index: number, age: number, date: Date | undefined, value: unknown): void {\r\n    this.properties[index] = value;\r\n    this.cache.set(index, value);\r\n    this.propertyAges.set(index, age);\r\n    this.propertyModificationDates.set(index, date);\r\n    if (age > this.age) this.age = age;\r\n    // Mirror into `instance` (silently — no propertyModified emit) when this\r\n    // proxy has been relayed into a warehouse: this is a merge/seed, not a\r\n    // live change, matching how attach/reattach never fire a notification.\r\n    if (this.instance) {\r\n      this.instance.setAge(index, age);\r\n      this.instance.setModificationDate(index, date);\r\n    }\r\n  }\r\n\r\n  /** Last known age for a property index. */\r\n  getAge(index: number): number {\r\n    return this.propertyAges.get(index) ?? 0;\r\n  }\r\n\r\n  /** Last known modification date for a property index. */\r\n  getModificationDate(index: number): Date | undefined {\r\n    return this.propertyModificationDates.get(index);\r\n  }\r\n\r\n  /** @internal Merge a sparse reattach delta. */\r\n  applyDelta(delta: readonly RemotePropertyValue[]): void {\r\n    for (const pv of delta)\r\n      this.setPropertySnapshot(pv.index, pv.age, pv.date, pv.value);\r\n  }\r\n\r\n  /** @internal Apply a property value pushed by the server. */\r\n  updateProperty(index: number, value: unknown, age?: number, date?: Date): void {\r\n    this.properties[index] = value;\r\n    this.cache.set(index, value);\r\n    if (age != null) {\r\n      this.propertyAges.set(index, age);\r\n      if (age > this.age) this.age = age;\r\n    }\r\n    if (date != null) this.propertyModificationDates.set(index, date);\r\n    const pt = this.typeDef.getPropertyByIndex(index);\r\n    if (pt) {\r\n      this.propertyModified.emit({ name: pt.name, index, value, age, date });\r\n      // Relay: if this proxy has been put() into a warehouse, forward the\r\n      // change through its Instance so a third node attached to it (via\r\n      // subscribeToInstance) gets notified too. Live PropertyModified\r\n      // notifications don't carry the origin's age/date on the wire, so\r\n      // this self-increments the Instance's own age like any local write\r\n      // would (matching how a relayed EmitModification loses origin-age\r\n      // fidelity in dotnet too).\r\n      this.instance?.modified(pt.name, value);\r\n    }\r\n  }\r\n\r\n  /** @internal Apply an event occurrence pushed by the server. */\r\n  applyEvent(index: number, value: unknown): void {\r\n    const et = this.typeDef.getEventByIndex(index);\r\n    if (et) {\r\n      this.eventOccurred.emit({ name: et.name, index, value });\r\n      this.instance?.emitEventByIndex(index, value);\r\n    }\r\n    this._EmitEventByIndex(index, value);\r\n  }\r\n\r\n  /** Invoke a remote function by index. Used by generated EpResource stubs. */\r\n  protected _Invoke(index: number, args: unknown = []): AsyncReply {\r\n    return this.requireConnection().invokeWithArguments(this.instanceId, index, normalizeArguments(args));\r\n  }\r\n\r\n  /** Older generated-stub alias for invoking by positional argument array. */\r\n  protected _InvokeByArrayArguments(index: number, args: readonly unknown[] = []): AsyncReply {\r\n    return this._Invoke(index, args);\r\n  }\r\n\r\n  /** Read a cached remote property by index. Used by generated EpResource stubs. */\r\n  protected GetResourceProperty<T = unknown>(index: number): T {\r\n    return this.properties[index] as T;\r\n  }\r\n\r\n  /** Set a remote property asynchronously by index. */\r\n  protected SetResourcePropertyAsync(index: number, value: unknown): AsyncReply<void> {\r\n    return this.requireConnection().set(this.instanceId, index, value).then(() => {\r\n      this.setLocalProperty(index, value);\r\n    }) as AsyncReply<void>;\r\n  }\r\n\r\n  /** camelCase alias for {@link SetResourcePropertyAsync}. */\r\n  protected setResourcePropertyAsync(index: number, value: unknown): AsyncReply<void> {\r\n    return this.SetResourcePropertyAsync(index, value);\r\n  }\r\n\r\n  /** Set a remote property by index and update the local cache optimistically. */\r\n  protected SetResourceProperty(index: number, value: unknown): AsyncReply<void> {\r\n    const reply = this.requireConnection().set(this.instanceId, index, value).then(() => undefined);\r\n    this.setLocalProperty(index, value);\r\n    return reply as AsyncReply<void>;\r\n  }\r\n\r\n  /** Override point for generated typed event dispatch. */\r\n  protected _EmitEventByIndex(_index: number, _value: unknown): void {\r\n    /* generated subclasses may override */\r\n  }\r\n\r\n  private setLocalProperty(index: number, value: unknown): void {\r\n    this.properties[index] = value;\r\n    this.cache.set(index, value);\r\n  }\r\n\r\n  private requireConnection(): EpConnection {\r\n    if (!this.connection) throw new Error(\"Remote resource is not attached to a connection.\");\r\n    return this.connection;\r\n  }\r\n\r\n  /** Wrap an {@link EpResource} in an ergonomic dynamic proxy. */\r\n  static createProxy(resource: EpResource): EpResource & Record<string, any> {\r\n    return new Proxy(resource, proxyHandler) as EpResource & Record<string, any>;\r\n  }\r\n\r\n  // ---- IResource / IDestructible -----------------------------------------\r\n\r\n  handle(_operation: ResourceOperation, _context?: IResourceContext): AsyncReply<boolean> {\r\n    return AsyncReply.fromResult(true);\r\n  }\r\n\r\n  addDestroyHandler(handler: DestroyedEvent): void {\r\n    this.destroyHandlers.push(handler);\r\n  }\r\n\r\n  removeDestroyHandler(handler: DestroyedEvent): void {\r\n    const i = this.destroyHandlers.indexOf(handler);\r\n    if (i >= 0) this.destroyHandlers.splice(i, 1);\r\n  }\r\n\r\n  destroy(): void {\r\n    for (const h of this.destroyHandlers.slice()) h(this);\r\n  }\r\n\r\n  // ---- IDynamicResource ---------------------------------------------------\r\n\r\n  get resourceDefinition(): TypeDef {\r\n    return this.typeDef;\r\n  }\r\n\r\n  getResourceProperty<T = unknown>(index: number): T {\r\n    return this.cache.get(index) as T;\r\n  }\r\n\r\n  /** Forward a write to the upstream connection this proxy is relaying — the same path the ergonomic proxy's `set` trap uses. */\r\n  setResourceProperty(index: number, value: unknown): AsyncReply<void> {\r\n    return this.SetResourceProperty(index, value);\r\n  }\r\n\r\n  getResourcePropertyAge(index: number): number {\r\n    return this.getAge(index);\r\n  }\r\n\r\n  getResourcePropertyDate(index: number): Date | undefined {\r\n    return this.getModificationDate(index);\r\n  }\r\n\r\n  /** Invoke a remote function by index — the same path the ergonomic proxy's function-call trap uses. */\r\n  invoke(index: number, args: unknown[]): AsyncReply {\r\n    return this.connection.invoke(this.instanceId, index, ...args);\r\n  }\r\n}\r\n\r\nfunction getOrCreate<K>(map: Map<K, Set<(value: unknown) => void>>, key: K): Set<(value: unknown) => void> {\r\n  let set = map.get(key);\r\n  if (!set) {\r\n    set = new Set();\r\n    map.set(key, set);\r\n  }\r\n  return set;\r\n}\r\n\r\nconst proxyHandler: ProxyHandler<EpResource> = {\r\n  get(target, prop, receiver) {\r\n    if (typeof prop === \"string\" && !(prop in target)) {\r\n      const fn = target.typeDef.getFunctionByName(prop);\r\n      if (fn) {\r\n        return (...args: unknown[]): AsyncReply => target.invoke(fn.index, args);\r\n      }\r\n      const pt = target.typeDef.getPropertyByName(prop);\r\n      if (pt) return target.getResourceProperty(pt.index);\r\n    }\r\n    return Reflect.get(target, prop, receiver);\r\n  },\r\n\r\n  set(target, prop, value, receiver) {\r\n    if (typeof prop === \"string\") {\r\n      const pt = target.typeDef.getPropertyByName(prop);\r\n      if (pt) {\r\n        target.setResourceProperty(pt.index, value);\r\n        return true;\r\n      }\r\n    }\r\n    return Reflect.set(target, prop, value, receiver);\r\n  },\r\n};\r\n\r\nfunction isTypeDef(value: unknown): value is TypeDef {\r\n  return value instanceof TypeDef ||\r\n    (\r\n      value != null &&\r\n      typeof value === \"object\" &&\r\n      Array.isArray((value as { members?: unknown }).members) &&\r\n      typeof (value as { getPropertyByIndex?: unknown }).getPropertyByIndex === \"function\"\r\n    );\r\n}\r\n\r\nfunction normalizeArguments(args: unknown): unknown {\r\n  return args == null ? [] : args;\r\n}\r\n","import { parseAsync, parseSync } from \"../data/Codec.js\";\r\nimport * as DC from \"../data/DC.js\";\r\nimport { Tru, type RemoteTypeDefResolver, type Tru as TruType } from \"../data/Tru.js\";\r\nimport { TduIdentifier } from \"../data/TduIdentifier.js\";\r\nimport {\r\n  TypeDefKind,\r\n  type ITypeDef,\r\n  type TypeDefConstant,\r\n  type TypeDefProperty,\r\n} from \"../data/types/ITypeDef.js\";\r\nimport { TypeDefInfo } from \"../data/types/TypeDefInfo.js\";\r\nimport type { MemberDefInfo } from \"../data/types/MemberDefInfo.js\";\r\nimport type { PropertyDefInfo } from \"../data/types/PropertyDefInfo.js\";\r\nimport type { FunctionDefInfo } from \"../data/types/FunctionDefInfo.js\";\r\nimport type { EventDefInfo } from \"../data/types/EventDefInfo.js\";\r\nimport type { ConstantDefInfo } from \"../data/types/ConstantDefInfo.js\";\r\nimport type { ArgumentDefInfo } from \"../data/types/ArgumentDefInfo.js\";\r\nimport { MemberDefFlags } from \"../data/types/MemberDefFlags.js\";\r\nimport { PropertyDefFlags } from \"../data/types/PropertyDefFlags.js\";\r\nimport { FunctionDefFlags } from \"../data/types/FunctionDefFlags.js\";\r\nimport { EventDefFlags } from \"../data/types/EventDefFlags.js\";\r\nimport { ArgumentDefFlags } from \"../data/types/ArgumentDefFlags.js\";\r\nimport {\r\n  ArgumentTemplate,\r\n  EventTemplate,\r\n  FunctionTemplate,\r\n  PropertyTemplate,\r\n  TypeDef,\r\n} from \"../resource/template.js\";\r\n\r\n/**\r\n * Documentation/semantics metadata shared by every member kind, introduced\r\n * alongside the `IndexedStructure`-based wire format. Absent (`undefined`)\r\n * for members decoded from the legacy manual byte format.\r\n */\r\nexport interface RemoteMemberMetadata {\r\n  deprecated?: boolean;\r\n  deprecationMessage?: string;\r\n  description?: string;\r\n  usage?: string;\r\n  examples?: unknown[];\r\n  tags?: string[];\r\n  unit?: string;\r\n  minimum?: unknown;\r\n  maximum?: unknown;\r\n  allowedValues?: unknown[];\r\n  pattern?: string;\r\n  format?: string;\r\n  preconditions?: string[];\r\n  postconditions?: string[];\r\n  /** {@link import(\"../data/types/OperationEffects.js\").OperationEffects} bitmask. */\r\n  effects?: number;\r\n  warnings?: string[];\r\n  relatedMembers?: number[];\r\n}\r\n\r\nexport interface RemoteArgumentDef extends RemoteMemberMetadata {\r\n  index: number;\r\n  name: string;\r\n  type?: TruType;\r\n  optional: boolean;\r\n  variadic?: boolean;\r\n  defaultValue?: unknown;\r\n  annotations?: Map<string, string>;\r\n}\r\n\r\nexport interface RemoteFunctionDef extends RemoteMemberMetadata {\r\n  index: number;\r\n  name: string;\r\n  returnType?: TruType;\r\n  arguments: RemoteArgumentDef[];\r\n  inherited: boolean;\r\n  isStatic: boolean;\r\n  readOnly?: boolean;\r\n  idempotent?: boolean;\r\n  cancellable?: boolean;\r\n  pausable?: boolean;\r\n  /** {@link import(\"../data/types/StreamMode.js\").StreamMode} bitmask. */\r\n  streamMode?: number;\r\n  annotations?: Map<string, string>;\r\n}\r\n\r\nexport interface RemotePropertyDef extends RemoteMemberMetadata {\r\n  index: number;\r\n  name: string;\r\n  valueType?: TruType;\r\n  inherited: boolean;\r\n  /** Legacy 2-bit permission field; not populated by the new-format decoder (unused downstream — see `readOnly`/`constant`/`volatile`). */\r\n  permission: number;\r\n  hasHistory: boolean;\r\n  readOnly?: boolean;\r\n  constant?: boolean;\r\n  volatile?: boolean;\r\n  orderingControl?: number;\r\n  historyControl?: number;\r\n  defaultValue?: unknown;\r\n  annotations?: Map<string, string>;\r\n}\r\n\r\nexport interface RemoteEventDef extends RemoteMemberMetadata {\r\n  index: number;\r\n  name: string;\r\n  argumentType?: TruType;\r\n  argumentName?: string;\r\n  inherited: boolean;\r\n  subscribable: boolean;\r\n  autoDelivered?: boolean;\r\n  orderingControl?: number;\r\n  historyControl?: number;\r\n  annotations?: Map<string, string>;\r\n}\r\n\r\nexport interface RemoteConstantDef extends RemoteMemberMetadata {\r\n  index: number;\r\n  name: string;\r\n  valueType?: TruType;\r\n  value: unknown;\r\n  inherited: boolean;\r\n  annotations?: Map<string, string>;\r\n}\r\n\r\nexport interface RemoteTypeDefSnapshot {\r\n  id: number;\r\n  name: string;\r\n  kind: string;\r\n  version: number;\r\n  parentTypeId?: number;\r\n  annotations?: Record<string, string>;\r\n  properties: Array<Record<string, unknown>>;\r\n  functions: Array<Record<string, unknown>>;\r\n  events: Array<Record<string, unknown>>;\r\n  constants: Array<Record<string, unknown>>;\r\n}\r\n\r\nexport class RemoteTypeDef implements ITypeDef {\r\n  template = new TypeDef(\"\", []);\r\n\r\n  private cachedProperties: TypeDefProperty[] = [];\r\n  private _id = 0;\r\n  private _kind = TypeDefKind.Resource;\r\n  private _name = \"\";\r\n  private _version = 0;\r\n  private _parentTypeId: number | undefined;\r\n  private _annotations: Map<string, string> | undefined;\r\n  private _remoteProperties: RemotePropertyDef[] = [];\r\n  private _remoteFunctions: RemoteFunctionDef[] = [];\r\n  private _remoteEvents: RemoteEventDef[] = [];\r\n  private _remoteConstants: RemoteConstantDef[] = [];\r\n\r\n  get id(): number {\r\n    return this._id;\r\n  }\r\n\r\n  get kind(): TypeDefKind {\r\n    return this._kind;\r\n  }\r\n\r\n  get name(): string {\r\n    return this._name;\r\n  }\r\n\r\n  get version(): number {\r\n    return this._version;\r\n  }\r\n\r\n  get parentTypeId(): number | undefined {\r\n    return this._parentTypeId;\r\n  }\r\n\r\n  get annotations(): Map<string, string> | undefined {\r\n    return this._annotations;\r\n  }\r\n\r\n  get remoteProperties(): ReadonlyArray<RemotePropertyDef> {\r\n    return this._remoteProperties;\r\n  }\r\n\r\n  get remoteFunctions(): ReadonlyArray<RemoteFunctionDef> {\r\n    return this._remoteFunctions;\r\n  }\r\n\r\n  get remoteEvents(): ReadonlyArray<RemoteEventDef> {\r\n    return this._remoteEvents;\r\n  }\r\n\r\n  get remoteConstants(): ReadonlyArray<RemoteConstantDef> {\r\n    return this._remoteConstants;\r\n  }\r\n\r\n  hydrate(\r\n    id: number,\r\n    kind: TypeDefKind,\r\n    name: string,\r\n    version: number,\r\n    parentTypeId: number | undefined,\r\n    annotations: Map<string, string> | undefined,\r\n    remoteProperties: RemotePropertyDef[],\r\n    remoteFunctions: RemoteFunctionDef[],\r\n    remoteEvents: RemoteEventDef[],\r\n    remoteConstants: RemoteConstantDef[],\r\n  ): void {\r\n    this._id = id;\r\n    this._kind = kind;\r\n    this._name = name;\r\n    this._version = version;\r\n    this._parentTypeId = parentTypeId;\r\n    this._annotations = annotations;\r\n    this._remoteProperties = remoteProperties;\r\n    this._remoteFunctions = remoteFunctions;\r\n    this._remoteEvents = remoteEvents;\r\n    this._remoteConstants = remoteConstants;\r\n\r\n    const members = [\r\n      ...remoteProperties.map(\r\n        (p) => new PropertyTemplate(p.name, p.index, p.valueType, false, p.annotations),\r\n      ),\r\n      ...remoteFunctions.map(\r\n        (f) =>\r\n          new FunctionTemplate(\r\n            f.name,\r\n            f.index,\r\n            f.returnType,\r\n            f.arguments.map(\r\n              (a) => new ArgumentTemplate(a.name, a.type, a.optional, a.annotations),\r\n            ),\r\n            f.isStatic,\r\n            f.annotations,\r\n          ),\r\n      ),\r\n      ...remoteEvents.map(\r\n        (e) =>\r\n          new EventTemplate(\r\n            e.name,\r\n            e.index,\r\n            e.argumentType,\r\n            e.annotations,\r\n            e.subscribable,\r\n          ),\r\n      ),\r\n    ];\r\n    this.template = new TypeDef(name, members, annotations);\r\n    this.cachedProperties = remoteProperties.map((p) => ({\r\n      name: p.name,\r\n      valueType: p.valueType,\r\n    }));\r\n  }\r\n\r\n  get properties(): TypeDefProperty[] {\r\n    return this.cachedProperties;\r\n  }\r\n\r\n  get constants(): TypeDefConstant[] {\r\n    return this.remoteConstants.map((c) => ({\r\n      name: c.name,\r\n      value: c.value,\r\n      index: c.index,\r\n    }));\r\n  }\r\n\r\n  createInstance(): object {\r\n    return {};\r\n  }\r\n\r\n  setProperty(instance: object, name: string, value: unknown): void {\r\n    (instance as Record<string, unknown>)[name] = value;\r\n  }\r\n\r\n  toJSON(): RemoteTypeDefSnapshot {\r\n    return {\r\n      id: this.id,\r\n      name: this.name,\r\n      kind: TypeDefKind[this.kind] ?? String(this.kind),\r\n      version: this.version,\r\n      parentTypeId: this.parentTypeId,\r\n      annotations: mapToObject(this.annotations),\r\n      properties: this.remoteProperties.map((p) => ({\r\n        index: p.index,\r\n        name: p.name,\r\n        type: p.valueType?.toString(),\r\n        inherited: p.inherited,\r\n        permission: p.permission,\r\n        hasHistory: p.hasHistory,\r\n        readOnly: p.readOnly,\r\n        constant: p.constant,\r\n        volatile: p.volatile,\r\n        deprecated: p.deprecated,\r\n        description: p.description,\r\n        annotations: mapToObject(p.annotations),\r\n      })),\r\n      functions: this.remoteFunctions.map((f) => ({\r\n        index: f.index,\r\n        name: f.name,\r\n        returnType: f.returnType?.toString(),\r\n        inherited: f.inherited,\r\n        isStatic: f.isStatic,\r\n        readOnly: f.readOnly,\r\n        idempotent: f.idempotent,\r\n        cancellable: f.cancellable,\r\n        pausable: f.pausable,\r\n        deprecated: f.deprecated,\r\n        description: f.description,\r\n        arguments: f.arguments.map((a) => ({\r\n          index: a.index,\r\n          name: a.name,\r\n          type: a.type?.toString(),\r\n          optional: a.optional,\r\n          variadic: a.variadic,\r\n          annotations: mapToObject(a.annotations),\r\n        })),\r\n        annotations: mapToObject(f.annotations),\r\n      })),\r\n      events: this.remoteEvents.map((e) => ({\r\n        index: e.index,\r\n        name: e.name,\r\n        argumentType: e.argumentType?.toString(),\r\n        inherited: e.inherited,\r\n        subscribable: e.subscribable,\r\n        autoDelivered: e.autoDelivered,\r\n        deprecated: e.deprecated,\r\n        description: e.description,\r\n        annotations: mapToObject(e.annotations),\r\n      })),\r\n      constants: this.remoteConstants.map((c) => ({\r\n        index: c.index,\r\n        name: c.name,\r\n        type: c.valueType?.toString(),\r\n        value: c.value,\r\n        inherited: c.inherited,\r\n        deprecated: c.deprecated,\r\n        description: c.description,\r\n        annotations: mapToObject(c.annotations),\r\n      })),\r\n    };\r\n  }\r\n\r\n  static parse(data: Uint8Array, warehouse: unknown = null): RemoteTypeDef {\r\n    if ((data[0] & 0xc7) === TduIdentifier.TypeDef) {\r\n      const parsed = parseSync(data, 0, warehouse);\r\n      if (parsed.length !== data.length || !(parsed.value instanceof TypeDefInfo))\r\n        throw new Error(\"Invalid TypeDefInfo payload.\");\r\n      const typeDef = new RemoteTypeDef();\r\n      applyInfo(typeDef, parsed.value);\r\n      return typeDef;\r\n    }\r\n\r\n    let offset = 0;\r\n    const flags = data[offset++];\r\n    const hasParent = (flags & 0x80) > 0;\r\n    const hasClassAnnotation = (flags & 0x40) > 0;\r\n    const kind = (flags & 0x0f) as TypeDefKind;\r\n\r\n    const id = Number(DC.getUint64(data, offset));\r\n    offset += 8;\r\n\r\n    const name = readName(data, offset);\r\n    offset = name.offset;\r\n\r\n    let parentTypeId: number | undefined;\r\n    if (hasParent) {\r\n      parentTypeId = Number(DC.getUint64(data, offset));\r\n      offset += 8;\r\n    }\r\n\r\n    let annotations: Map<string, string> | undefined;\r\n    if (hasClassAnnotation) {\r\n      const parsed = parseSync(data, offset, warehouse);\r\n      annotations = asStringMap(parsed.value);\r\n      offset += parsed.length;\r\n    }\r\n\r\n    const version = DC.getInt32(data, offset);\r\n    offset += 4;\r\n    const memberCount = DC.getUint16(data, offset);\r\n    offset += 2;\r\n\r\n    const functions: RemoteFunctionDef[] = [];\r\n    const properties: RemotePropertyDef[] = [];\r\n    const events: RemoteEventDef[] = [];\r\n    const constants: RemoteConstantDef[] = [];\r\n\r\n    let functionIndex = 0;\r\n    let propertyIndex = 0;\r\n    let eventIndex = 0;\r\n    let constantIndex = 0;\r\n\r\n    for (let i = 0; i < memberCount; i++) {\r\n      const inherited = (data[offset] & 0x80) > 0;\r\n      const memberType = (data[offset] >> 5) & 0x3;\r\n      if (memberType === 0) {\r\n        const parsed = parseFunction(data, offset, functionIndex++, inherited, warehouse);\r\n        functions.push(parsed.value);\r\n        offset = parsed.offset;\r\n      } else if (memberType === 1) {\r\n        const parsed = parseProperty(data, offset, propertyIndex++, inherited, warehouse);\r\n        properties.push(parsed.value);\r\n        offset = parsed.offset;\r\n      } else if (memberType === 2) {\r\n        const parsed = parseEvent(data, offset, eventIndex++, inherited, warehouse);\r\n        events.push(parsed.value);\r\n        offset = parsed.offset;\r\n      } else {\r\n        const parsed = parseConstant(data, offset, constantIndex++, inherited, warehouse);\r\n        constants.push(parsed.value);\r\n        offset = parsed.offset;\r\n      }\r\n    }\r\n\r\n    const typeDef = new RemoteTypeDef();\r\n    typeDef.hydrate(\r\n      id,\r\n      kind,\r\n      name.value,\r\n      version,\r\n      parentTypeId,\r\n      annotations,\r\n      properties,\r\n      functions,\r\n      events,\r\n      constants,\r\n    );\r\n    return typeDef;\r\n  }\r\n\r\n  static async parseAsync(\r\n    data: Uint8Array,\r\n    warehouse: unknown = null,\r\n    remoteResolver?: RemoteTypeDefResolver,\r\n    requestSequence: readonly number[] | null = null,\r\n  ): Promise<RemoteTypeDef> {\r\n    return RemoteTypeDef.parseAsyncInto(\r\n      new RemoteTypeDef(),\r\n      data,\r\n      warehouse,\r\n      remoteResolver,\r\n      requestSequence,\r\n    );\r\n  }\r\n\r\n  static async parseAsyncInto(\r\n    target: RemoteTypeDef,\r\n    data: Uint8Array,\r\n    warehouse: unknown = null,\r\n    remoteResolver?: RemoteTypeDefResolver,\r\n    requestSequence: readonly number[] | null = null,\r\n  ): Promise<RemoteTypeDef> {\r\n    if ((data[0] & 0xc7) === TduIdentifier.TypeDef) {\r\n      const parsed = await parseAsync(data, 0, warehouse, remoteResolver, requestSequence);\r\n      if (parsed.length !== data.length || !(parsed.value instanceof TypeDefInfo))\r\n        throw new Error(\"Invalid TypeDefInfo payload.\");\r\n      applyInfo(target, parsed.value);\r\n      return target;\r\n    }\r\n\r\n    let offset = 0;\r\n    const flags = data[offset++];\r\n    const hasParent = (flags & 0x80) > 0;\r\n    const hasClassAnnotation = (flags & 0x40) > 0;\r\n    const kind = (flags & 0x0f) as TypeDefKind;\r\n\r\n    const id = Number(DC.getUint64(data, offset));\r\n    offset += 8;\r\n\r\n    const name = readName(data, offset);\r\n    offset = name.offset;\r\n\r\n    let parentTypeId: number | undefined;\r\n    if (hasParent) {\r\n      parentTypeId = Number(DC.getUint64(data, offset));\r\n      offset += 8;\r\n    }\r\n\r\n    let annotations: Map<string, string> | undefined;\r\n    if (hasClassAnnotation) {\r\n      const parsed = parseSync(data, offset, warehouse);\r\n      annotations = asStringMap(parsed.value);\r\n      offset += parsed.length;\r\n    }\r\n\r\n    const version = DC.getInt32(data, offset);\r\n    offset += 4;\r\n    const memberCount = DC.getUint16(data, offset);\r\n    offset += 2;\r\n\r\n    const functions: RemoteFunctionDef[] = [];\r\n    const properties: RemotePropertyDef[] = [];\r\n    const events: RemoteEventDef[] = [];\r\n    const constants: RemoteConstantDef[] = [];\r\n\r\n    target.hydrate(\r\n      id,\r\n      kind,\r\n      name.value,\r\n      version,\r\n      parentTypeId,\r\n      annotations,\r\n      properties,\r\n      functions,\r\n      events,\r\n      constants,\r\n    );\r\n\r\n    let functionIndex = 0;\r\n    let propertyIndex = 0;\r\n    let eventIndex = 0;\r\n    let constantIndex = 0;\r\n\r\n    for (let i = 0; i < memberCount; i++) {\r\n      const inherited = (data[offset] & 0x80) > 0;\r\n      const memberType = (data[offset] >> 5) & 0x3;\r\n      if (memberType === 0) {\r\n        const parsed = await parseFunctionAsync(\r\n          data,\r\n          offset,\r\n          functionIndex++,\r\n          inherited,\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n        functions.push(parsed.value);\r\n        offset = parsed.offset;\r\n      } else if (memberType === 1) {\r\n        const parsed = await parsePropertyAsync(\r\n          data,\r\n          offset,\r\n          propertyIndex++,\r\n          inherited,\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n        properties.push(parsed.value);\r\n        offset = parsed.offset;\r\n      } else if (memberType === 2) {\r\n        const parsed = await parseEventAsync(\r\n          data,\r\n          offset,\r\n          eventIndex++,\r\n          inherited,\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n        events.push(parsed.value);\r\n        offset = parsed.offset;\r\n      } else {\r\n        const parsed = await parseConstantAsync(\r\n          data,\r\n          offset,\r\n          constantIndex++,\r\n          inherited,\r\n          warehouse,\r\n          remoteResolver,\r\n          requestSequence,\r\n        );\r\n        constants.push(parsed.value);\r\n        offset = parsed.offset;\r\n      }\r\n    }\r\n\r\n    target.hydrate(\r\n      id,\r\n      kind,\r\n      name.value,\r\n      version,\r\n      parentTypeId,\r\n      annotations,\r\n      properties,\r\n      functions,\r\n      events,\r\n      constants,\r\n    );\r\n    return target;\r\n  }\r\n}\r\n\r\n// ---- new-format (IndexedStructure/TduIdentifier.TypeDef) conversion -------\r\n\r\n/**\r\n * Populate `target` from a decoded new-format {@link TypeDefInfo} (port of C#\r\n * `RemoteTypeDef.ApplyInfo`/`ApplyMember`/`ToProperty`/`ToFunction`/\r\n * `ToArgument`/`ToEvent`/`ToConstant`). The member lists are already fully\r\n * decoded objects by this point (see `hydrateTypeDefInfo` in\r\n * `DataDeserializer.ts`) — this is purely field remapping onto the existing\r\n * `Remote*Def` shapes, no further byte parsing.\r\n */\r\nfunction applyInfo(target: RemoteTypeDef, info: TypeDefInfo): void {\r\n  const properties = (info.properties ?? []).map((p) => toRemoteProperty(p));\r\n  const functions = (info.functions ?? []).map((f) => toRemoteFunction(f));\r\n  const events = (info.events ?? []).map((e) => toRemoteEvent(e));\r\n  const constants = (info.constants ?? []).map((c) => toRemoteConstant(c));\r\n\r\n  target.hydrate(\r\n    info.id,\r\n    info.kind,\r\n    info.name,\r\n    info.version,\r\n    info.parent,\r\n    info.annotations,\r\n    properties,\r\n    functions,\r\n    events,\r\n    constants,\r\n  );\r\n}\r\n\r\nfunction toRemoteProperty(p: PropertyDefInfo): RemotePropertyDef {\r\n  const flags = p.flags;\r\n  return {\r\n    index: p.index,\r\n    name: p.name,\r\n    valueType: p.valueType,\r\n    inherited: (flags & MemberDefFlags.Inherited) !== 0,\r\n    // Legacy 2-bit permission field; the new format has no equivalent (and\r\n    // nothing downstream consumes it — see `readOnly`/`constant`/`volatile`).\r\n    permission: 0,\r\n    hasHistory: (flags & PropertyDefFlags.Historical) !== 0 || p.historyControl !== 0,\r\n    readOnly: (flags & PropertyDefFlags.ReadOnly) !== 0,\r\n    constant: (flags & PropertyDefFlags.Constant) !== 0,\r\n    volatile: (flags & PropertyDefFlags.Volatile) !== 0,\r\n    orderingControl: p.orderingControl,\r\n    historyControl: p.historyControl,\r\n    defaultValue: p.defaultValue,\r\n    annotations: p.annotations,\r\n    ...memberMetadata(p),\r\n  };\r\n}\r\n\r\nfunction toRemoteFunction(f: FunctionDefInfo): RemoteFunctionDef {\r\n  const flags = f.flags;\r\n  return {\r\n    index: f.index,\r\n    name: f.name,\r\n    returnType: f.returnType,\r\n    arguments: (f.arguments ?? []).map(toRemoteArgument),\r\n    inherited: (flags & MemberDefFlags.Inherited) !== 0,\r\n    isStatic: (flags & FunctionDefFlags.Static) !== 0,\r\n    readOnly: (flags & FunctionDefFlags.ReadOnly) !== 0,\r\n    idempotent: (flags & FunctionDefFlags.Idempotent) !== 0,\r\n    cancellable: (flags & FunctionDefFlags.Cancellable) !== 0,\r\n    pausable: (flags & FunctionDefFlags.Pausable) !== 0,\r\n    streamMode: f.streamMode,\r\n    annotations: f.annotations,\r\n    ...memberMetadata(f),\r\n  };\r\n}\r\n\r\nfunction toRemoteEvent(e: EventDefInfo): RemoteEventDef {\r\n  const flags = e.flags;\r\n  return {\r\n    index: e.index,\r\n    name: e.name,\r\n    argumentType: e.argumentType,\r\n    argumentName: e.argumentName,\r\n    inherited: (flags & MemberDefFlags.Inherited) !== 0,\r\n    // The new format has no direct \"subscribable\" bit; an auto-delivered\r\n    // event is pushed without a subscription, so treat non-auto-delivered\r\n    // events as subscribable (matches typical Subscribe/Unsubscribe usage).\r\n    subscribable: (flags & EventDefFlags.AutoDelivered) === 0,\r\n    autoDelivered: (flags & EventDefFlags.AutoDelivered) !== 0,\r\n    orderingControl: e.orderingControl,\r\n    historyControl: e.historyControl,\r\n    annotations: e.annotations,\r\n    ...memberMetadata(e),\r\n  };\r\n}\r\n\r\nfunction toRemoteConstant(c: ConstantDefInfo): RemoteConstantDef {\r\n  const flags = c.flags;\r\n  return {\r\n    index: c.index,\r\n    name: c.name,\r\n    valueType: c.valueType,\r\n    value: c.value,\r\n    inherited: (flags & MemberDefFlags.Inherited) !== 0,\r\n    annotations: c.annotations,\r\n    ...memberMetadata(c),\r\n  };\r\n}\r\n\r\nfunction toRemoteArgument(a: ArgumentDefInfo): RemoteArgumentDef {\r\n  const flags = a.flags;\r\n  return {\r\n    index: a.index,\r\n    name: a.name,\r\n    type: a.valueType,\r\n    optional: (flags & ArgumentDefFlags.Optional) !== 0,\r\n    variadic: (flags & ArgumentDefFlags.Variadic) !== 0,\r\n    defaultValue: a.defaultValue,\r\n    annotations: a.annotations,\r\n  };\r\n}\r\n\r\n/** Extract the shared documentation/semantics metadata fields common to every member kind. */\r\nfunction memberMetadata(m: MemberDefInfo): RemoteMemberMetadata {\r\n  const meta: RemoteMemberMetadata = {};\r\n  if ((m.flags & MemberDefFlags.Deprecated) !== 0) meta.deprecated = true;\r\n  if (m.deprecationMessage !== undefined) meta.deprecationMessage = m.deprecationMessage;\r\n  if (m.description !== undefined) meta.description = m.description;\r\n  if (m.usage !== undefined) meta.usage = m.usage;\r\n  if (m.examples !== undefined) meta.examples = m.examples;\r\n  if (m.tags !== undefined) meta.tags = m.tags;\r\n  if (m.unit !== undefined) meta.unit = m.unit;\r\n  if (m.minimum !== undefined) meta.minimum = m.minimum;\r\n  if (m.maximum !== undefined) meta.maximum = m.maximum;\r\n  if (m.allowedValues !== undefined) meta.allowedValues = m.allowedValues;\r\n  if (m.pattern !== undefined) meta.pattern = m.pattern;\r\n  if (m.format !== undefined) meta.format = m.format;\r\n  if (m.preconditions !== undefined) meta.preconditions = m.preconditions;\r\n  if (m.postconditions !== undefined) meta.postconditions = m.postconditions;\r\n  if (m.effects !== undefined) meta.effects = m.effects;\r\n  if (m.warnings !== undefined) meta.warnings = m.warnings;\r\n  if (m.relatedMembers !== undefined) meta.relatedMembers = m.relatedMembers;\r\n  return meta;\r\n}\r\n\r\n// ---- legacy manual-byte-format helpers -------------------------------------\r\n\r\nfunction parseFunction(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n): { value: RemoteFunctionDef; offset: number } {\r\n  const header = data[offset++];\r\n  const isStatic = (header & 0x04) > 0;\r\n  const hasAnnotations = (header & 0x10) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const returnType = Tru.parseSync(data, offset, warehouse);\r\n  offset += returnType.size;\r\n\r\n  const argsCount = data[offset++];\r\n  const args: RemoteArgumentDef[] = [];\r\n  for (let i = 0; i < argsCount; i++) {\r\n    const parsed = parseArgument(data, offset, i, warehouse);\r\n    args.push(parsed.value);\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseAnnotationMap(data, offset, warehouse, true);\r\n    annotations = parsed.value;\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      returnType: returnType.value,\r\n      arguments: args,\r\n      inherited,\r\n      isStatic,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nasync function parseFunctionAsync(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<{ value: RemoteFunctionDef; offset: number }> {\r\n  const header = data[offset++];\r\n  const isStatic = (header & 0x04) > 0;\r\n  const hasAnnotations = (header & 0x10) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const returnType = await Tru.parseAsync(\r\n    data,\r\n    offset,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  offset += returnType.size;\r\n\r\n  const argsCount = data[offset++];\r\n  const args: RemoteArgumentDef[] = [];\r\n  for (let i = 0; i < argsCount; i++) {\r\n    const parsed = await parseArgumentAsync(\r\n      data,\r\n      offset,\r\n      i,\r\n      warehouse,\r\n      remoteResolver,\r\n      requestSequence,\r\n    );\r\n    args.push(parsed.value);\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseAnnotationMap(data, offset, warehouse, true);\r\n    annotations = parsed.value;\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      returnType: returnType.value,\r\n      arguments: args,\r\n      inherited,\r\n      isStatic,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nfunction parseProperty(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n): { value: RemotePropertyDef; offset: number } {\r\n  const header = data[offset++];\r\n  const hasAnnotations = (header & 0x08) > 0;\r\n  const hasHistory = (header & 0x01) > 0;\r\n  const permission = (header >> 1) & 0x03;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const valueType = Tru.parseSync(data, offset, warehouse);\r\n  offset += valueType.size;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseAnnotationMap(data, offset, warehouse, true);\r\n    annotations = parsed.value;\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      valueType: valueType.value,\r\n      inherited,\r\n      permission,\r\n      hasHistory,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nasync function parsePropertyAsync(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<{ value: RemotePropertyDef; offset: number }> {\r\n  const header = data[offset++];\r\n  const hasAnnotations = (header & 0x08) > 0;\r\n  const hasHistory = (header & 0x01) > 0;\r\n  const permission = (header >> 1) & 0x03;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const valueType = await Tru.parseAsync(\r\n    data,\r\n    offset,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  offset += valueType.size;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseAnnotationMap(data, offset, warehouse, true);\r\n    annotations = parsed.value;\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      valueType: valueType.value,\r\n      inherited,\r\n      permission,\r\n      hasHistory,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nfunction parseEvent(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n): { value: RemoteEventDef; offset: number } {\r\n  const header = data[offset++];\r\n  const hasAnnotations = (header & 0x10) > 0;\r\n  const subscribable = (header & 0x08) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const argType = Tru.parseSync(data, offset, warehouse);\r\n  offset += argType.size;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseAnnotationMap(data, offset, warehouse, true);\r\n    annotations = parsed.value;\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      argumentType: argType.value,\r\n      inherited,\r\n      subscribable,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nasync function parseEventAsync(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<{ value: RemoteEventDef; offset: number }> {\r\n  const header = data[offset++];\r\n  const hasAnnotations = (header & 0x10) > 0;\r\n  const subscribable = (header & 0x08) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const argType = await Tru.parseAsync(\r\n    data,\r\n    offset,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  offset += argType.size;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseAnnotationMap(data, offset, warehouse, true);\r\n    annotations = parsed.value;\r\n    offset = parsed.offset;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      argumentType: argType.value,\r\n      inherited,\r\n      subscribable,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nfunction parseArgument(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  warehouse: unknown,\r\n): { value: RemoteArgumentDef; offset: number } {\r\n  const header = data[offset++];\r\n  const optional = (header & 0x01) > 0;\r\n  const hasAnnotations = (header & 0x02) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const type = Tru.parseSync(data, offset, warehouse);\r\n  offset += type.size;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseSync(data, offset, warehouse);\r\n    annotations = asStringMap(parsed.value);\r\n    offset += parsed.length;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      type: type.value,\r\n      optional,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nasync function parseArgumentAsync(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<{ value: RemoteArgumentDef; offset: number }> {\r\n  const header = data[offset++];\r\n  const optional = (header & 0x01) > 0;\r\n  const hasAnnotations = (header & 0x02) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const type = await Tru.parseAsync(\r\n    data,\r\n    offset,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  offset += type.size;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseSync(data, offset, warehouse);\r\n    annotations = asStringMap(parsed.value);\r\n    offset += parsed.length;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      type: type.value,\r\n      optional,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nfunction parseConstant(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n): { value: RemoteConstantDef; offset: number } {\r\n  const header = data[offset++];\r\n  const hasAnnotations = (header & 0x10) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const valueType = Tru.parseSync(data, offset, warehouse);\r\n  offset += valueType.size;\r\n\r\n  const value = parseSync(data, offset, warehouse);\r\n  offset += value.length;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseSync(data, offset, warehouse);\r\n    annotations = asStringMap(parsed.value);\r\n    offset += parsed.length;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      valueType: valueType.value,\r\n      value: value.value,\r\n      inherited,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nasync function parseConstantAsync(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  index: number,\r\n  inherited: boolean,\r\n  warehouse: unknown,\r\n  remoteResolver: RemoteTypeDefResolver | undefined,\r\n  requestSequence: readonly number[] | null,\r\n): Promise<{ value: RemoteConstantDef; offset: number }> {\r\n  const header = data[offset++];\r\n  const hasAnnotations = (header & 0x10) > 0;\r\n\r\n  const name = readName(data, offset);\r\n  offset = name.offset;\r\n\r\n  const valueType = await Tru.parseAsync(\r\n    data,\r\n    offset,\r\n    warehouse,\r\n    remoteResolver,\r\n    requestSequence,\r\n  );\r\n  offset += valueType.size;\r\n\r\n  const value = parseSync(data, offset, warehouse);\r\n  offset += value.length;\r\n\r\n  let annotations: Map<string, string> | undefined;\r\n  if (hasAnnotations) {\r\n    const parsed = parseSync(data, offset, warehouse);\r\n    annotations = asStringMap(parsed.value);\r\n    offset += parsed.length;\r\n  }\r\n\r\n  return {\r\n    value: {\r\n      index,\r\n      name: name.value,\r\n      valueType: valueType.value,\r\n      value: value.value,\r\n      inherited,\r\n      annotations,\r\n    },\r\n    offset,\r\n  };\r\n}\r\n\r\nfunction readName(data: Uint8Array, offset: number): { value: string; offset: number } {\r\n  const length = data[offset++];\r\n  const value = DC.getString(data, offset, length);\r\n  return { value, offset: offset + length };\r\n}\r\n\r\nfunction parseAnnotationMap(\r\n  data: Uint8Array,\r\n  offset: number,\r\n  warehouse: unknown,\r\n  allowLengthPrefix = false,\r\n): { value: Map<string, string> | undefined; offset: number } {\r\n  if (allowLengthPrefix && offset + 4 <= data.length) {\r\n    const length = DC.getUint32(data, offset);\r\n    const starts = offset + 4;\r\n    const ends = starts + length;\r\n    if (length > 0 && ends <= data.length) {\r\n      try {\r\n        const parsed = parseSync(data.slice(starts, ends), 0, warehouse);\r\n        if (parsed.length === length)\r\n          return { value: asStringMap(parsed.value), offset: ends };\r\n      } catch {\r\n        // Fall through to the direct TDU shape used by other member annotations.\r\n      }\r\n    }\r\n  }\r\n\r\n  const parsed = parseSync(data, offset, warehouse);\r\n  return { value: asStringMap(parsed.value), offset: offset + parsed.length };\r\n}\r\n\r\nfunction asStringMap(value: unknown): Map<string, string> | undefined {\r\n  if (!(value instanceof Map)) return undefined;\r\n  const result = new Map<string, string>();\r\n  for (const [k, v] of value.entries())\r\n    result.set(String(k), String(v));\r\n  return result;\r\n}\r\n\r\nfunction mapToObject(map: Map<string, string> | undefined): Record<string, string> | undefined {\r\n  if (!map) return undefined;\r\n  return Object.fromEntries(map.entries());\r\n}\r\n","import { StreamMode } from \"../data/types/StreamMode.js\";\r\n\r\ninterface Deferred<T> {\r\n  promise: Promise<T>;\r\n  resolve: (value: T) => void;\r\n}\r\n\r\nfunction createDeferred<T>(): Deferred<T> {\r\n  let resolve!: (value: T) => void;\r\n  const promise = new Promise<T>((res) => {\r\n    resolve = res;\r\n  });\r\n  return { promise, resolve };\r\n}\r\n\r\n/** Result of {@link ServerInvocationContext.pullAsync}. */\r\nexport interface PullResult {\r\n  done: boolean;\r\n  value?: unknown;\r\n}\r\n\r\n/**\r\n * Server-side tracking for one in-flight streamed function call (port of C#\r\n * `InvocationContext`, scoped to what `PullStream`/`TerminateExecution`/\r\n * `HaltExecution`/`ResumeExecution` need). Wraps whatever iterator a\r\n * streaming function returned — `AsyncIterable`/`Iterable` is JS's native\r\n * equivalent of dotnet's `IAsyncEnumerable<T>`/`IEnumerable<T>` split, so\r\n * unlike dotnet there's no separate Push/Pull source-shape branch needed\r\n * here: both are driven the same way, just on a different schedule\r\n * (immediately, pumped, vs. only on an explicit `PullStream`).\r\n */\r\nexport class ServerInvocationContext {\r\n  private readonly iterator: AsyncIterator<unknown> | Iterator<unknown>;\r\n  private readonly abort = new AbortController();\r\n  private ended = false;\r\n  private halted = false;\r\n  private resumeDeferred: Deferred<void> | undefined;\r\n\r\n  constructor(\r\n    source: AsyncIterable<unknown> | Iterable<unknown>,\r\n    readonly streamMode: StreamMode,\r\n    readonly pausable: boolean,\r\n  ) {\r\n    this.iterator =\r\n      Symbol.asyncIterator in source\r\n        ? (source as AsyncIterable<unknown>)[Symbol.asyncIterator]()\r\n        : (source as Iterable<unknown>)[Symbol.iterator]();\r\n  }\r\n\r\n  /** Aborted when {@link terminate} runs — a source can observe this to stop early work of its own. */\r\n  get signal(): AbortSignal {\r\n    return this.abort.signal;\r\n  }\r\n\r\n  get isEnded(): boolean {\r\n    return this.ended;\r\n  }\r\n\r\n  /** Advance the iterator by one item, waiting out any active halt first. */\r\n  async pullAsync(): Promise<PullResult> {\r\n    if (this.ended) return { done: true };\r\n    await this.waitWhileHalted();\r\n    if (this.ended) return { done: true };\r\n\r\n    const r = await this.iterator.next();\r\n    if (r.done) this.ended = true;\r\n    return { done: !!r.done, value: r.value };\r\n  }\r\n\r\n  /** Stop the stream: aborts {@link signal}, releases any halt wait, and closes the iterator. */\r\n  async terminate(): Promise<void> {\r\n    if (this.ended) return;\r\n    this.ended = true;\r\n    this.abort.abort();\r\n    this.resumeDeferred?.resolve();\r\n    this.resumeDeferred = undefined;\r\n    await this.iterator.return?.();\r\n  }\r\n\r\n  halt(): void {\r\n    if (this.ended) throw new Error(\"Cannot halt an execution that has already ended.\");\r\n    if (!this.pausable) throw new Error(\"This stream is not pausable.\");\r\n    if (this.halted) throw new Error(\"This stream is already halted.\");\r\n    this.halted = true;\r\n    this.resumeDeferred = createDeferred<void>();\r\n  }\r\n\r\n  resume(): void {\r\n    if (this.ended) throw new Error(\"Cannot resume an execution that has already ended.\");\r\n    if (!this.pausable) throw new Error(\"This stream is not pausable.\");\r\n    if (!this.halted) throw new Error(\"This stream is not halted.\");\r\n    this.halted = false;\r\n    this.resumeDeferred?.resolve();\r\n    this.resumeDeferred = undefined;\r\n  }\r\n\r\n  private async waitWhileHalted(): Promise<void> {\r\n    while (this.halted && !this.ended) await this.resumeDeferred?.promise;\r\n  }\r\n}\r\n\r\n/** Duck-type check for a value with `Symbol.asyncIterator` or `Symbol.iterator`. */\r\nexport function isIterableResult(value: unknown): value is AsyncIterable<unknown> | Iterable<unknown> {\r\n  if (value == null || typeof value !== \"object\") return false;\r\n  return Symbol.asyncIterator in value || Symbol.iterator in value;\r\n}\r\n","/** A resource manager's decision on one operation (port of C# `Ruling`). */\r\nexport enum Ruling {\r\n  Denied = 0,\r\n  Allowed = 1,\r\n  DontCare = 2,\r\n}\r\n","import { Ruling } from \"../permissions/Ruling.js\";\r\n\r\n/**\r\n * Aggregated decisions from each independent manager category (port of C#\r\n * `ResourceManagerEvaluation`). An allow in one category never grants\r\n * admission in another category.\r\n */\r\nexport class ResourceManagerEvaluation {\r\n  readonly delay: number;\r\n\r\n  constructor(\r\n    readonly permissions: Ruling,\r\n    readonly rateControl: Ruling,\r\n    readonly auditing: Ruling,\r\n    delay: number,\r\n    readonly permissionsDenialReason?: string,\r\n    readonly rateControlDenialReason?: string,\r\n    readonly auditingDenialReason?: string,\r\n  ) {\r\n    this.delay = delay > 0 ? delay : 0;\r\n  }\r\n\r\n  get isAllowed(): boolean {\r\n    return (\r\n      this.permissions === Ruling.Allowed &&\r\n      this.rateControl !== Ruling.Denied &&\r\n      this.auditing !== Ruling.Denied\r\n    );\r\n  }\r\n}\r\n","import type { Warehouse } from \"../../resource/Warehouse.js\";\r\nimport type { EpConnection } from \"../../protocol/EpConnection.js\";\r\nimport type { AuthenticationSession } from \"../AuthenticationSession.js\";\r\nimport type { IResource } from \"../../resource/IResource.js\";\r\nimport type { MemberTemplate } from \"../../resource/template.js\";\r\nimport type { ActionType } from \"../permissions/ActionType.js\";\r\nimport { Ruling } from \"../permissions/Ruling.js\";\r\n\r\n/** Describes the request currently being evaluated by a rate policy (port of C# `RateControlContext`). */\r\nexport class RateControlContext {\r\n  /** Optional delay (ms) assigned by a policy to an allowed queued request. */\r\n  delay = 0;\r\n\r\n  constructor(\r\n    readonly warehouse: Warehouse,\r\n    readonly connection: EpConnection,\r\n    readonly session: AuthenticationSession,\r\n    readonly resource: IResource | null,\r\n    readonly member: MemberTemplate,\r\n    readonly action: ActionType,\r\n  ) {}\r\n}\r\n\r\n/**\r\n * Base class for named Warehouse rate-control policies (port of C#\r\n * `RatePolicy`). dotnet exposes this as two overloads (a context-free\r\n * `Applicable()` and a context-aware `Applicable(RateControlContext)`,\r\n * the latter defaulting to calling the former) — TS collapses them into one\r\n * overridable method, since it has no overload-resolution equivalent;\r\n * context-free policies simply ignore the parameter.\r\n */\r\nexport abstract class RatePolicy {\r\n  constructor(public name: string = \"\") {}\r\n\r\n  /** Evaluate a request. Override for context-aware policies (e.g. {@link BurstRatePolicy}). */\r\n  applicable(_context?: RateControlContext): Ruling {\r\n    return Ruling.DontCare;\r\n  }\r\n}\r\n","import type { IRateControlManager } from \"../management/IRateControlManager.js\";\r\nimport type { ResourceManagerContext } from \"../management/ResourceManagerContext.js\";\r\nimport { ActionType } from \"../permissions/ActionType.js\";\r\nimport { Ruling } from \"../permissions/Ruling.js\";\r\nimport { RateControlContext } from \"./RatePolicy.js\";\r\n\r\n/**\r\n * Bridges the named Warehouse rate-policy registry into the unified\r\n * resource-manager pipeline (port of C# `NamedRateControlManager`). Applies\r\n * only to members carrying a `@RateControl(name)` policy name, and only for\r\n * `Execute`/`SetProperty` actions.\r\n */\r\nexport class NamedRateControlManager implements IRateControlManager {\r\n  readonly managerCategory = \"rateControl\" as const;\r\n\r\n  applicable(context: ResourceManagerContext): Ruling {\r\n    if (context.action !== ActionType.Execute && context.action !== ActionType.SetProperty)\r\n      return Ruling.DontCare;\r\n\r\n    const policyName = (context.member as { ratePolicyName?: string } | null)?.ratePolicyName;\r\n    if (!policyName) return Ruling.DontCare;\r\n\r\n    if (!context.connection || !context.session || !context.member) {\r\n      context.denialReason = `Rate policy \\`${policyName}\\` requires an authenticated connection.`;\r\n      return Ruling.Denied;\r\n    }\r\n\r\n    const policy = context.warehouse.tryGetRatePolicy(policyName);\r\n    if (!policy) {\r\n      context.denialReason = `Rate policy \\`${policyName}\\` is not registered.`;\r\n      return Ruling.Denied;\r\n    }\r\n\r\n    const rateContext = new RateControlContext(\r\n      context.warehouse,\r\n      context.connection,\r\n      context.session,\r\n      context.resource,\r\n      context.member,\r\n      context.action,\r\n    );\r\n\r\n    const ruling = policy.applicable(rateContext);\r\n    if (rateContext.delay > context.delay) context.delay = rateContext.delay;\r\n\r\n    if (ruling === Ruling.Denied && !context.denialReason)\r\n      context.denialReason = `Rate policy \\`${policyName}\\` denied \\`${context.member.name}\\`.`;\r\n\r\n    return ruling;\r\n  }\r\n}\r\n","/**\r\n * Framework-agnostic adapter over the property/event-change notifications\r\n * already fired by {@link Instance} (local resources) and {@link EpResource}\r\n * (remote resource proxies from `EpConnection.attach()`/`.get()`). Depends\r\n * on neither — it duck-types over whatever `EventHandler`-shaped\r\n * `propertyModified`/`eventOccurred` it finds, so it works for both without\r\n * importing either class (avoiding a dependency on the protocol layer from\r\n * here, and keeping this file usable as the basis for *any* UI binding, not\r\n * just the `esiur/react` one built on top of it).\r\n */\r\n\r\ninterface EventHandlerLike {\r\n  add(handler: (value: unknown) => void): unknown;\r\n  remove(handler: (value: unknown) => void): unknown;\r\n}\r\n\r\nfunction isEventHandlerLike(value: unknown): value is EventHandlerLike {\r\n  const v = value as EventHandlerLike | undefined;\r\n  return !!v && typeof v.add === \"function\" && typeof v.remove === \"function\";\r\n}\r\n\r\n/** A normalized property-change notification, regardless of source shape. */\r\nexport interface PropertyChangeEvent {\r\n  name: string;\r\n  value: unknown;\r\n}\r\n\r\nfunction normalizePropertyChange(raw: unknown): PropertyChangeEvent | undefined {\r\n  // `EpResource.propertyModified` fires `{ name, index, value, age?, date? }`;\r\n  // `Instance.propertyModified` fires `{ resource, property: { name }, value, age }`.\r\n  const r = raw as { name?: unknown; property?: { name?: unknown }; value?: unknown } | undefined;\r\n  const name = typeof r?.name === \"string\" ? r.name : r?.property?.name;\r\n  return typeof name === \"string\" ? { name, value: r?.value } : undefined;\r\n}\r\n\r\nfunction findPropertyModifiedHandler(resource: unknown): EventHandlerLike | undefined {\r\n  const r = resource as Record<string, unknown> | undefined;\r\n  if (!r) return undefined;\r\n  // Remote proxy (or a raw EpResource): `propertyModified` is a real own\r\n  // property on the underlying instance, so `Proxy`'s `get` trap in\r\n  // `EpResource.createProxy` passes it through unchanged.\r\n  if (isEventHandlerLike(r.propertyModified)) return r.propertyModified as EventHandlerLike;\r\n  // Local resource: the notifier lives on `.instance`, not the resource itself.\r\n  const instance = r.instance as Record<string, unknown> | undefined;\r\n  if (instance && isEventHandlerLike(instance.propertyModified))\r\n    return instance.propertyModified as EventHandlerLike;\r\n  return undefined;\r\n}\r\n\r\n/**\r\n * Subscribe to every property change on `resource` (local or remote).\r\n * Returns an unsubscribe function; a no-op if `resource` exposes no\r\n * recognizable change notifier.\r\n */\r\nexport function subscribeToResource(\r\n  resource: unknown,\r\n  onChange: (event: PropertyChangeEvent) => void,\r\n): () => void {\r\n  const handler = findPropertyModifiedHandler(resource);\r\n  if (!handler) return () => {};\r\n\r\n  const wrapped = (raw: unknown): void => {\r\n    const event = normalizePropertyChange(raw);\r\n    if (event) onChange(event);\r\n  };\r\n  handler.add(wrapped);\r\n  return () => handler.remove(wrapped);\r\n}\r\n\r\n/** Subscribe to a single named property's changes. */\r\nexport function subscribeToProperty(\r\n  resource: unknown,\r\n  propertyName: string,\r\n  onChange: (value: unknown) => void,\r\n): () => void {\r\n  return subscribeToResource(resource, (event) => {\r\n    if (event.name === propertyName) onChange(event.value);\r\n  });\r\n}\r\n\r\n/** Read a property's current value directly off a resource/proxy. */\r\nexport function readProperty<T = unknown>(resource: unknown, propertyName: string): T | undefined {\r\n  if (resource == null) return undefined;\r\n  return (resource as Record<string, unknown>)[propertyName] as T | undefined;\r\n}\r\n\r\ninterface PropertyLike {\r\n  name: string;\r\n}\r\ninterface TypeDefLike {\r\n  properties: readonly PropertyLike[];\r\n}\r\n\r\nfunction isTypeDefLike(value: unknown): value is TypeDefLike {\r\n  return !!value && Array.isArray((value as TypeDefLike).properties);\r\n}\r\n\r\nfunction findTypeDef(resource: unknown): TypeDefLike | undefined {\r\n  const r = resource as Record<string, unknown> | undefined;\r\n  if (!r) return undefined;\r\n  // Remote proxy: `typeDef` is a real own property (same pass-through as above).\r\n  if (isTypeDefLike(r.typeDef)) return r.typeDef as TypeDefLike;\r\n  // Local resource: the TypeDef lives on `.instance.definition`.\r\n  const instance = r.instance as Record<string, unknown> | undefined;\r\n  if (instance && isTypeDefLike(instance.definition)) return instance.definition as TypeDefLike;\r\n  return undefined;\r\n}\r\n\r\n/** Build a plain snapshot object of every exported property's current value. */\r\nexport function snapshotProperties<T extends Record<string, unknown> = Record<string, unknown>>(\r\n  resource: unknown,\r\n): T {\r\n  const typeDef = findTypeDef(resource);\r\n  const out: Record<string, unknown> = {};\r\n  if (typeDef) for (const p of typeDef.properties) out[p.name] = readProperty(resource, p.name);\r\n  return out as T;\r\n}\r\n\r\nfunction findEventOccurredHandler(resource: unknown): EventHandlerLike | undefined {\r\n  const r = resource as Record<string, unknown> | undefined;\r\n  return r && isEventHandlerLike(r.eventOccurred) ? (r.eventOccurred as EventHandlerLike) : undefined;\r\n}\r\n\r\ninterface ListenerLike {\r\n  listen(handler: (value: unknown) => void): unknown;\r\n  unlisten(handler: (value: unknown) => void): unknown;\r\n}\r\n\r\nfunction isListenerLike(value: unknown): value is ListenerLike {\r\n  const v = value as ListenerLike | undefined;\r\n  return !!v && typeof v.listen === \"function\" && typeof v.unlisten === \"function\";\r\n}\r\n\r\n/**\r\n * Subscribe to one named exported event, local or remote. Remote proxies\r\n * fire everything through the single `eventOccurred` notifier (filtered\r\n * here by name); local resources expose each event as its own\r\n * {@link EventSource} field with `listen`/`unlisten`.\r\n */\r\nexport function subscribeToResourceEvent(\r\n  resource: unknown,\r\n  eventName: string,\r\n  onEvent: (value: unknown) => void,\r\n): () => void {\r\n  const remoteHandler = findEventOccurredHandler(resource);\r\n  if (remoteHandler) {\r\n    const wrapped = (raw: unknown): void => {\r\n      const event = normalizePropertyChange(raw);\r\n      if (event && event.name === eventName) onEvent(event.value);\r\n    };\r\n    remoteHandler.add(wrapped);\r\n    return () => remoteHandler.remove(wrapped);\r\n  }\r\n\r\n  const source = (resource as Record<string, unknown> | undefined)?.[eventName];\r\n  if (isListenerLike(source)) {\r\n    const wrapped = (value: unknown): void => onEvent(value);\r\n    source.listen(wrapped);\r\n    return () => source.unlisten(wrapped);\r\n  }\r\n\r\n  return () => {};\r\n}\r\n","import { AsyncReply } from \"../core/AsyncReply.js\";\r\nimport { AsyncBag } from \"../core/AsyncBag.js\";\r\nimport type { DestroyedEvent } from \"../core/IDestructible.js\";\r\nimport type { IResource, IStore } from \"../resource/IResource.js\";\r\nimport type { Instance } from \"../resource/Instance.js\";\r\nimport { ResourceOperation } from \"../resource/ResourceOperation.js\";\r\n\r\n/**\r\n * An in-memory {@link IStore} that keeps its resources in RAM (port of C#\r\n * `MemoryStore`). Resources are addressed by their stored link path, or by\r\n * `$<id>` for a direct instance-id lookup.\r\n */\r\nexport class MemoryStore implements IStore {\r\n  instance?: Instance;\r\n\r\n  private readonly resources = new Map<number, IResource>();\r\n  private readonly destroyHandlers: DestroyedEvent[] = [];\r\n\r\n  handle(_operation: ResourceOperation): AsyncReply<boolean> {\r\n    return AsyncReply.fromResult(true);\r\n  }\r\n\r\n  link(resource: IResource): string | undefined {\r\n    if (resource.instance?.store === this)\r\n      return resource.instance.variables.get(\"link\") as string | undefined;\r\n    return undefined;\r\n  }\r\n\r\n  get(path: string): AsyncReply<IResource | undefined> {\r\n    if (path.startsWith(\"$\")) {\r\n      const id = Number.parseInt(path.slice(1), 10);\r\n      if (!Number.isNaN(id)) {\r\n        const found = this.resources.get(id);\r\n        if (found) return AsyncReply.fromResult<IResource | undefined>(found);\r\n      }\r\n    } else {\r\n      for (const r of this.resources.values())\r\n        if (this.link(r) === path) return AsyncReply.fromResult<IResource | undefined>(r);\r\n    }\r\n    return AsyncReply.fromResult<IResource | undefined>(undefined);\r\n  }\r\n\r\n  put(resource: IResource, path: string): AsyncReply<boolean> {\r\n    resource.instance!.variables.set(\"link\", path);\r\n    this.resources.set(resource.instance!.id, resource);\r\n    return AsyncReply.fromResult(true);\r\n  }\r\n\r\n  modify(): boolean {\r\n    return true;\r\n  }\r\n\r\n  remove(resource: IResource): AsyncReply<boolean>;\r\n  remove(path: string): AsyncReply<boolean>;\r\n  remove(resourceOrPath: IResource | string): AsyncReply<boolean> {\r\n    if (typeof resourceOrPath === \"string\") {\r\n      const path = normalizeStorePath(resourceOrPath, this.instance?.name);\r\n      for (const r of this.resources.values()) {\r\n        if (this.link(r) === path) {\r\n          this.resources.delete(r.instance!.id);\r\n          return AsyncReply.fromResult(true);\r\n        }\r\n      }\r\n      return AsyncReply.fromResult(false);\r\n    }\r\n\r\n    if (resourceOrPath.instance?.store !== this) return AsyncReply.fromResult(false);\r\n    return AsyncReply.fromResult(this.resources.delete(resourceOrPath.instance.id));\r\n  }\r\n\r\n  move(resource: IResource, newPath: string): AsyncReply<boolean> {\r\n    if (resource.instance?.store !== this) return AsyncReply.fromResult(false);\r\n\r\n    const path = normalizeStorePath(newPath, this.instance?.name);\r\n    resource.instance.variables.set(\"link\", path);\r\n\r\n    const parts = path.split(\"/\").filter((p) => p.length > 0);\r\n    if (parts.length > 0) resource.instance.name = parts[parts.length - 1];\r\n\r\n    return AsyncReply.fromResult(true);\r\n  }\r\n\r\n  children<T extends IResource>(resource: IResource): AsyncBag<T> {\r\n    const prefix = `${this.link(resource)}/`;\r\n    const matches = [...this.resources.values()].filter((r) => {\r\n      const link = this.link(r);\r\n      return link != null && link.startsWith(prefix);\r\n    });\r\n    return new AsyncBag<T>(matches as T[]);\r\n  }\r\n\r\n  parents<T extends IResource>(): AsyncBag<T> {\r\n    return new AsyncBag<T>([]);\r\n  }\r\n\r\n  addDestroyHandler(handler: DestroyedEvent): void {\r\n    this.destroyHandlers.push(handler);\r\n  }\r\n\r\n  removeDestroyHandler(handler: DestroyedEvent): void {\r\n    const i = this.destroyHandlers.indexOf(handler);\r\n    if (i >= 0) this.destroyHandlers.splice(i, 1);\r\n  }\r\n\r\n  destroy(): void {\r\n    for (const h of this.destroyHandlers.slice()) h(this);\r\n  }\r\n}\r\n\r\nfunction normalizeStorePath(path: string, storeName?: string): string {\r\n  const normalized = path.trim().replace(/^\\/+|\\/+$/g, \"\");\r\n  if (!storeName) return normalized;\r\n  if (normalized === storeName) return \"\";\r\n  const prefix = `${storeName}/`;\r\n  return normalized.startsWith(prefix) ? normalized.slice(prefix.length) : normalized;\r\n}\r\n","export * from \"./NetworkBuffer.js\";\r\nexport * from \"./INetworkReceiver.js\";\r\nexport * from \"./NetworkConnection.js\";\r\nexport * from \"./sockets/index.js\";\r\nexport * from \"./packets/index.js\";\r\n","export * from \"./SocketState.js\";\r\nexport * from \"./ISocket.js\";\r\nexport * from \"./WSocket.js\";\r\nexport * from \"./TcpSocket.js\";\r\n","import type { Warehouse } from \"../resource/Warehouse.js\";\r\nimport { WSocket } from \"../net/sockets/WSocket.js\";\r\nimport { EpConnection } from \"./EpConnection.js\";\r\nimport type { IAuthenticationProvider } from \"../security/IAuthenticationProvider.js\";\r\nimport type { VerifyClientCallbackAsync } from \"ws\";\r\n\r\n/**\r\n * The WebSocket subprotocol a connecting peer must request (matches\r\n * `WSocket`'s `EP_SUBPROTOCOL` and esiur-dotnet's `FrameworkWebSocket.SubProtocol`).\r\n * Upgrades that don't request it -- exactly and case-sensitively -- are rejected\r\n * with `400 Bad Request`, mirroring esiur-dotnet's `EsiurWebSocketEndpoint` and\r\n * the raw-TCP upgrade path in `EpConnection.cs`.\r\n */\r\nconst EP_SUBPROTOCOL = \"EP\";\r\n\r\n/** Reject the upgrade unless the client requested the \"EP\" subprotocol. */\r\nconst verifyEpSubprotocol: VerifyClientCallbackAsync = (info, callback) => {\r\n  const protocols = requestedProtocols(info.req.headers[\"sec-websocket-protocol\"]);\r\n  if (protocols.includes(EP_SUBPROTOCOL)) {\r\n    callback(true);\r\n  } else {\r\n    callback(false, 400, `The '${EP_SUBPROTOCOL}' WebSocket subprotocol is required.`);\r\n  }\r\n};\r\n\r\n/** Always negotiate \"EP\" itself, regardless of what else the client offered. */\r\nfunction selectEpSubprotocol(protocols: Set<string>): string | false {\r\n  return protocols.has(EP_SUBPROTOCOL) ? EP_SUBPROTOCOL : false;\r\n}\r\n\r\n/** Split a raw `Sec-WebSocket-Protocol` header value into its comma-separated tokens. */\r\nfunction requestedProtocols(header: string | string[] | undefined): string[] {\r\n  const raw = Array.isArray(header) ? header.join(\",\") : header;\r\n  if (!raw) return [];\r\n  return raw\r\n    .split(\",\")\r\n    .map((protocol) => protocol.trim())\r\n    .filter((protocol) => protocol.length > 0);\r\n}\r\n\r\nexport interface EpServerOptions {\r\n  /** Port to listen on (0 = an ephemeral port). */\r\n  port: number;\r\n  /** Host interface (default: all). */\r\n  host?: string;\r\n  /** Warehouse whose resources are served to connecting peers. */\r\n  warehouse: Warehouse;\r\n  /** Accept anonymous (None-mode) peers. Default true. */\r\n  allowUnauthorized?: boolean;\r\n  /** Optional authentication provider to register on the served warehouse. */\r\n  authenticationProvider?: IAuthenticationProvider;\r\n}\r\n\r\n/**\r\n * A WebSocket server that hosts a {@link Warehouse}'s resources for remote peers\r\n * (the TypeScript analogue of C# `DistributedServer`/`EpServer`). Node-only: it\r\n * dynamically imports `ws`, so importing this module does not pull `ws` into a\r\n * browser bundle.\r\n */\r\nexport class EpServer {\r\n  /** Live client connections. */\r\n  readonly connections = new Set<EpConnection>();\r\n\r\n  private wss: any;\r\n  private constructor(readonly warehouse: Warehouse) {}\r\n\r\n  /** Start listening and accepting connections bound to `warehouse`. */\n  static async listen(options: EpServerOptions): Promise<EpServer> {\n    if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)\n      throw new RangeError(\"EpServer.listen requires an explicit port from 0 through 65535.\");\n\n    const server = new EpServer(options.warehouse);\n    if (options.authenticationProvider)\r\n      options.warehouse.registerAuthenticationProvider(options.authenticationProvider);\r\n\r\n    const { WebSocketServer } = await import(\"ws\");\r\n    const wss = new WebSocketServer({\r\n      port: options.port,\r\n      host: options.host,\r\n      verifyClient: verifyEpSubprotocol,\r\n      handleProtocols: selectEpSubprotocol,\r\n    });\r\n    server.wss = wss;\r\n\r\n    await new Promise<void>((resolve, reject) => {\r\n      wss.once(\"listening\", () => resolve());\r\n      wss.once(\"error\", reject);\r\n    });\r\n\r\n    wss.on(\"connection\", (raw) => {\r\n      const connection = new EpConnection();\r\n      connection.warehouse = options.warehouse;\r\n      connection.allowUnauthorized = options.allowUnauthorized ?? true;\r\n      connection.startResponderHandshake(); // wait for the peer's Initialize\r\n      connection.assign(new WSocket(raw as unknown as WebSocket));\r\n      server.connections.add(connection);\r\n      connection.onClose.add(() => server.connections.delete(connection));\r\n    });\r\n\r\n    return server;\r\n  }\r\n\r\n  /** The bound port (useful when listening on port 0). */\r\n  get port(): number {\r\n    const addr = this.wss.address();\r\n    return typeof addr === \"object\" && addr ? addr.port : 0;\r\n  }\r\n\r\n  /** Stop the server and close all connections. */\r\n  close(): Promise<void> {\r\n    return new Promise<void>((resolve) => this.wss.close(() => resolve()));\r\n  }\r\n}\r\n","const MASK_64 = (1n << 64n) - 1n;\r\n\r\nconst ROUND_CONSTANTS = [\r\n  0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an,\r\n  0x8000000080008000n, 0x000000000000808bn, 0x0000000080000001n,\r\n  0x8000000080008081n, 0x8000000000008009n, 0x000000000000008an,\r\n  0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,\r\n  0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n,\r\n  0x8000000000008003n, 0x8000000000008002n, 0x8000000000000080n,\r\n  0x000000000000800an, 0x800000008000000an, 0x8000000080008081n,\r\n  0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,\r\n] as const;\r\n\r\nconst RHO_OFFSETS = [\r\n  0, 1, 62, 28, 27,\r\n  36, 44, 6, 55, 20,\r\n  3, 10, 43, 25, 39,\r\n  41, 45, 15, 21, 8,\r\n  18, 2, 61, 56, 14,\r\n] as const;\r\n\r\n/** SHA3 digest compatible with .NET/BouncyCastle SHA3. Supports 224/256/384/512 bits. */\r\nexport function sha3(data: Uint8Array, bitLength = 256): Uint8Array {\r\n  if (![224, 256, 384, 512].includes(bitLength))\r\n    throw new RangeError(\"SHA3 bit length must be 224, 256, 384, or 512.\");\r\n\r\n  const outputLength = bitLength / 8;\r\n  const rate = 200 - outputLength * 2;\r\n  const state = new Array<bigint>(25).fill(0n);\r\n\r\n  let offset = 0;\r\n  while (offset + rate <= data.length) {\r\n    absorbBlock(state, data.subarray(offset, offset + rate), rate);\r\n    keccakF1600(state);\r\n    offset += rate;\r\n  }\r\n\r\n  const block = new Uint8Array(rate);\r\n  block.set(data.subarray(offset));\r\n  block[data.length - offset] ^= 0x06;\r\n  block[rate - 1] ^= 0x80;\r\n  absorbBlock(state, block, rate);\r\n  keccakF1600(state);\r\n\r\n  return squeeze(state, rate, outputLength);\r\n}\r\n\r\nexport const sha3_256 = (data: Uint8Array): Uint8Array => sha3(data, 256);\r\nexport const sha3_512 = (data: Uint8Array): Uint8Array => sha3(data, 512);\r\n\r\nfunction absorbBlock(state: bigint[], block: Uint8Array, rate: number): void {\r\n  for (let i = 0; i < rate; i++) {\r\n    const lane = i >> 3;\r\n    const shift = BigInt((i & 7) * 8);\r\n    state[lane] = (state[lane] ^ (BigInt(block[i]) << shift)) & MASK_64;\r\n  }\r\n}\r\n\r\nfunction squeeze(state: bigint[], rate: number, outputLength: number): Uint8Array {\r\n  const out = new Uint8Array(outputLength);\r\n  let produced = 0;\r\n  while (produced < outputLength) {\r\n    for (let i = 0; i < rate && produced < outputLength; i++) {\r\n      const lane = state[i >> 3];\r\n      out[produced++] = Number((lane >> BigInt((i & 7) * 8)) & 0xffn);\r\n    }\r\n    if (produced < outputLength) keccakF1600(state);\r\n  }\r\n  return out;\r\n}\r\n\r\nfunction keccakF1600(a: bigint[]): void {\r\n  const b = new Array<bigint>(25).fill(0n);\r\n  const c = new Array<bigint>(5).fill(0n);\r\n  const d = new Array<bigint>(5).fill(0n);\r\n\r\n  for (const rc of ROUND_CONSTANTS) {\r\n    for (let x = 0; x < 5; x++)\r\n      c[x] = a[x] ^ a[x + 5] ^ a[x + 10] ^ a[x + 15] ^ a[x + 20];\r\n\r\n    for (let x = 0; x < 5; x++)\r\n      d[x] = c[(x + 4) % 5] ^ rotl64(c[(x + 1) % 5], 1);\r\n\r\n    for (let x = 0; x < 5; x++) {\r\n      for (let y = 0; y < 5; y++) a[x + 5 * y] = (a[x + 5 * y] ^ d[x]) & MASK_64;\r\n    }\r\n\r\n    for (let x = 0; x < 5; x++) {\r\n      for (let y = 0; y < 5; y++) {\r\n        const source = x + 5 * y;\r\n        const target = y + 5 * ((2 * x + 3 * y) % 5);\r\n        b[target] = rotl64(a[source], RHO_OFFSETS[source]);\r\n      }\r\n    }\r\n\r\n    for (let y = 0; y < 5; y++) {\r\n      for (let x = 0; x < 5; x++) {\r\n        a[x + 5 * y] =\r\n          (b[x + 5 * y] ^ ((~b[((x + 1) % 5) + 5 * y] & MASK_64) & b[((x + 2) % 5) + 5 * y])) &\r\n          MASK_64;\r\n      }\r\n    }\r\n\r\n    a[0] = (a[0] ^ rc) & MASK_64;\r\n  }\r\n}\r\n\r\nfunction rotl64(value: bigint, bits: number): bigint {\r\n  if (bits === 0) return value & MASK_64;\r\n  const n = BigInt(bits);\r\n  return ((value << n) | (value >> (64n - n))) & MASK_64;\r\n}\r\n","/** Identity plus raw password bytes returned by a password provider for itself. */\r\nexport class IdentityPassword {\r\n  constructor(\r\n    readonly identity: string | null = null,\r\n    readonly password: Uint8Array | null = null,\r\n  ) {}\r\n}\r\n","import { merge, stringToBytes } from \"../../data/DC.js\";\r\nimport { AuthenticationDirection } from \"../AuthenticationDirection.js\";\r\nimport { AuthenticationResult } from \"../AuthenticationResult.js\";\r\nimport { AuthenticationRuling } from \"../AuthenticationRuling.js\";\r\nimport { AuthenticationMode } from \"../AuthenticationMode.js\";\r\nimport type { IAuthenticationHandler } from \"../IAuthenticationHandler.js\";\r\nimport { sha3 } from \"../sha3.js\";\r\nimport { randomBytes } from \"../random.js\";\r\nimport type { PasswordAuthenticationProvider } from \"./PasswordAuthenticationProvider.js\";\r\n\r\n/** Implements Esiur's `\"password-sha3-v1\"` SHA3 nonce/challenge-response authentication. */\r\nexport class PasswordAuthenticationHandler implements IAuthenticationHandler {\r\n  static readonly nonceLength = 20;\r\n\r\n  readonly protocol = \"password-sha3-v1\";\r\n  private readonly localNonce = randomBytes(PasswordAuthenticationHandler.nonceLength);\r\n  private remoteNonce: Uint8Array | null = null;\r\n  private localSalt: Uint8Array | null = null;\r\n  private remoteSalt: Uint8Array | null = null;\r\n  private initiatorPassword: Uint8Array | null = null;\r\n  private responderPassword: Uint8Array | null = null;\r\n  private step = 0;\r\n\r\n  constructor(\r\n    private readonly mode: AuthenticationMode,\r\n    private readonly direction: AuthenticationDirection,\r\n    private initiatorIdentity: string | null,\r\n    private responderIdentity: string | null,\r\n    private readonly hostName: string | null,\r\n    private readonly domain: string | null,\r\n    readonly provider: PasswordAuthenticationProvider,\r\n  ) {}\r\n\r\n  static computeSha3(data: Uint8Array, bitLength = 256): Uint8Array {\r\n    return sha3(data, bitLength);\r\n  }\r\n\r\n  process(authData: unknown): AuthenticationResult {\r\n    try {\r\n      return this.processInternal(authData);\r\n    } catch {\r\n      this.step = -1;\r\n      return failed();\r\n    }\r\n  }\r\n\r\n  private processInternal(authData: unknown): AuthenticationResult {\r\n    const remoteAuthData = asAuthArray(authData);\r\n    const localAuthData: unknown[] = [];\r\n\r\n    if (this.direction === AuthenticationDirection.Initiator) {\r\n      if (this.mode === AuthenticationMode.InitializerIdentity)\r\n        return this.processInitiatorInitializerIdentity(remoteAuthData, localAuthData);\r\n      if (this.mode === AuthenticationMode.ResponderIdentity)\r\n        return this.processInitiatorResponderIdentity(remoteAuthData, localAuthData);\r\n      if (this.mode === AuthenticationMode.DualIdentity)\r\n        return this.processInitiatorDualIdentity(remoteAuthData, localAuthData);\r\n    } else {\r\n      if (this.mode === AuthenticationMode.InitializerIdentity)\r\n        return this.processResponderInitializerIdentity(remoteAuthData, localAuthData);\r\n      if (this.mode === AuthenticationMode.ResponderIdentity)\r\n        return this.processResponderResponderIdentity(remoteAuthData, localAuthData);\r\n      if (this.mode === AuthenticationMode.DualIdentity)\r\n        return this.processResponderDualIdentity(remoteAuthData, localAuthData);\r\n    }\r\n\r\n    this.step = -1;\r\n    return failed();\r\n  }\r\n\r\n  private processInitiatorInitializerIdentity(\r\n    remote: unknown[] | null,\r\n    local: unknown[],\r\n  ): AuthenticationResult {\r\n    if (this.step === 0) {\r\n      if (!this.loadInitiatorSelfPassword()) return failed();\r\n\r\n      local.push(this.localNonce, this.initiatorIdentity);\r\n      this.step = 1;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step !== 1 || !remote || remote.length < 3) return failed();\r\n\r\n    this.remoteNonce = asBytes(remote[0]);\r\n    this.remoteSalt = asBytes(remote[1]);\r\n    const remoteChallenge = asBytes(remote[2]);\r\n    if (!this.validRemoteNonce(this.remoteNonce) || !this.remoteSalt || !remoteChallenge)\r\n      return this.failedAndStop();\r\n\r\n    const hashedPassword = sha3(merge(this.initiatorPassword!, this.remoteSalt));\r\n    const expectedRemoteChallenge = sha3(merge(this.remoteNonce, hashedPassword, this.localNonce));\r\n    if (!fixedTimeEquals(remoteChallenge, expectedRemoteChallenge)) return this.failedAndStop();\r\n\r\n    const localChallenge = sha3(merge(this.localNonce, hashedPassword, this.remoteNonce));\r\n    local.push(localChallenge);\r\n    const sessionKey = sha3(\r\n      merge(stringToBytes(this.initiatorIdentity!), hashedPassword, this.localNonce, this.remoteNonce),\r\n      512,\r\n    );\r\n    this.step = -1;\r\n    return succeeded(local, this.initiatorIdentity, null, sessionKey);\r\n  }\r\n\r\n  private processResponderInitializerIdentity(\r\n    remote: unknown[] | null,\r\n    local: unknown[],\r\n  ): AuthenticationResult {\r\n    if (this.step === 0) {\r\n      if (!remote || remote.length < 2) return failed();\r\n\r\n      this.remoteNonce = asBytes(remote[0]);\r\n      this.initiatorIdentity = asString(remote[1]);\r\n      if (!this.validRemoteNonce(this.remoteNonce) || !this.initiatorIdentity)\r\n        return this.failedAndStop();\r\n\r\n      const credential = this.provider.getHostedAccountCredential(this.initiatorIdentity, this.domain);\r\n      this.localSalt = credential.salt;\r\n      this.initiatorPassword = credential.hash;\r\n      if (!this.localSalt || !this.initiatorPassword) return failed();\r\n\r\n      const localChallenge = sha3(merge(this.localNonce, this.initiatorPassword, this.remoteNonce));\r\n      local.push(this.localNonce, this.localSalt, localChallenge);\r\n      this.step = 1;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step !== 1 || !remote || remote.length < 1) return failed();\r\n\r\n    const remoteChallenge = asBytes(remote[0]);\r\n    if (!remoteChallenge || !this.remoteNonce || !this.initiatorPassword) return this.failedAndStop();\r\n\r\n    const expectedRemoteChallenge = sha3(\r\n      merge(this.remoteNonce, this.initiatorPassword, this.localNonce),\r\n    );\r\n    if (!fixedTimeEquals(expectedRemoteChallenge, remoteChallenge)) return this.failedAndStop();\r\n\r\n    const sessionKey = sha3(\r\n      merge(stringToBytes(this.initiatorIdentity!), this.initiatorPassword, this.remoteNonce, this.localNonce),\r\n      512,\r\n    );\r\n    this.step = -1;\r\n    return succeeded(null, this.initiatorIdentity, this.responderIdentity, sessionKey);\r\n  }\r\n\r\n  private processInitiatorResponderIdentity(\r\n    remote: unknown[] | null,\r\n    local: unknown[],\r\n  ): AuthenticationResult {\r\n    if (this.step === 0) {\r\n      local.push(this.localNonce);\r\n      this.step = 1;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step === 1) {\r\n      if (!remote || remote.length < 2) return failed();\r\n\r\n      this.remoteNonce = asBytes(remote[0]);\r\n      this.responderIdentity = asString(remote[1]);\r\n      if (!this.validRemoteNonce(this.remoteNonce) || !this.responderIdentity)\r\n        return this.failedAndStop();\r\n\r\n      const credential = this.provider.getHostedAccountCredential(this.responderIdentity, this.domain);\r\n      this.localSalt = credential.salt;\r\n      this.responderPassword = credential.hash;\r\n      if (!this.localSalt || !this.responderPassword) return this.failedAndStop();\r\n\r\n      const localChallenge = sha3(merge(this.localNonce, this.responderPassword, this.remoteNonce));\r\n      local.push(this.localSalt, localChallenge);\r\n      this.step = 2;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step !== 2 || !remote || remote.length < 1) return failed();\r\n\r\n    const remoteChallenge = asBytes(remote[0]);\r\n    if (!remoteChallenge || !this.remoteNonce || !this.responderPassword)\r\n      return this.failedAndStop();\r\n\r\n    const expectedRemoteChallenge = sha3(\r\n      merge(this.remoteNonce, this.responderPassword, this.localNonce),\r\n    );\r\n    if (!fixedTimeEquals(remoteChallenge, expectedRemoteChallenge)) return this.failedAndStop();\r\n\r\n    const sessionKey = sha3(\r\n      merge(stringToBytes(this.responderIdentity!), this.responderPassword, this.localNonce, this.remoteNonce),\r\n      512,\r\n    );\r\n    this.step = -1;\r\n    return succeeded(null, this.initiatorIdentity, this.responderIdentity, sessionKey);\r\n  }\r\n\r\n  private processResponderResponderIdentity(\r\n    remote: unknown[] | null,\r\n    local: unknown[],\r\n  ): AuthenticationResult {\r\n    if (this.step === 0) {\r\n      if (!remote || remote.length < 1) return failed();\r\n\r\n      this.remoteNonce = asBytes(remote[0]);\r\n      if (!this.validRemoteNonce(this.remoteNonce)) return this.failedAndStop();\r\n      if (!this.loadResponderSelfPassword()) return failed();\r\n\r\n      local.push(this.localNonce, this.responderIdentity);\r\n      this.step = 1;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step !== 1 || !remote || remote.length < 2) return failed();\r\n\r\n    this.remoteSalt = asBytes(remote[0]);\r\n    const remoteChallenge = asBytes(remote[1]);\r\n    if (!this.remoteSalt || !remoteChallenge || !this.remoteNonce || !this.responderPassword)\r\n      return this.failedAndStop();\r\n\r\n    const hashedPassword = sha3(merge(this.responderPassword, this.remoteSalt));\r\n    const expectedRemoteChallenge = sha3(merge(this.remoteNonce, hashedPassword, this.localNonce));\r\n    if (!fixedTimeEquals(expectedRemoteChallenge, remoteChallenge)) return this.failedAndStop();\r\n\r\n    const localChallenge = sha3(merge(this.localNonce, hashedPassword, this.remoteNonce));\r\n    const sessionKey = sha3(\r\n      merge(stringToBytes(this.responderIdentity!), hashedPassword, this.remoteNonce, this.localNonce),\r\n      512,\r\n    );\r\n    local.push(localChallenge);\r\n    this.step = -1;\r\n    return succeeded(local, this.responderIdentity, null, sessionKey);\r\n  }\r\n\r\n  private processInitiatorDualIdentity(\r\n    remote: unknown[] | null,\r\n    local: unknown[],\r\n  ): AuthenticationResult {\r\n    if (this.step === 0) {\r\n      if (!this.loadInitiatorSelfPassword()) return failed();\r\n      local.push(this.localNonce, this.initiatorIdentity);\r\n      this.step = 1;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step === 1) {\r\n      if (!remote || remote.length < 3) return failed();\r\n\r\n      this.remoteNonce = asBytes(remote[0]);\r\n      const parsed = parseDualResponderStep(remote);\r\n      this.responderIdentity = parsed.responderIdentity;\r\n      this.remoteSalt = parsed.salt;\r\n      if (!this.validRemoteNonce(this.remoteNonce) || !this.responderIdentity || !this.remoteSalt)\r\n        return this.failedAndStop();\r\n\r\n      const responderCredential = this.provider.getHostedAccountCredential(\r\n        this.responderIdentity,\r\n        this.domain,\r\n      );\r\n      this.localSalt = responderCredential.salt;\r\n      this.responderPassword = responderCredential.hash;\r\n      if (!this.localSalt || !this.responderPassword) return this.failedAndStop();\r\n\r\n      const hashedPassword = sha3(merge(this.initiatorPassword!, this.remoteSalt));\r\n      const localChallenge = sha3(\r\n        merge(this.localNonce, hashedPassword, this.responderPassword, this.remoteNonce),\r\n      );\r\n      local.push(this.localSalt, localChallenge);\r\n      this.step = 2;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step !== 2 || !remote || remote.length < 1) return failed();\r\n\r\n    const remoteChallenge = asBytes(remote[0]);\r\n    if (!remoteChallenge || !this.remoteNonce || !this.remoteSalt || !this.responderPassword)\r\n      return this.failedAndStop();\r\n\r\n    const hashedPassword = sha3(merge(this.initiatorPassword!, this.remoteSalt));\r\n    const expectedRemoteChallenge = sha3(\r\n      merge(this.remoteNonce, this.responderPassword, hashedPassword, this.localNonce),\r\n    );\r\n    if (!fixedTimeEquals(remoteChallenge, expectedRemoteChallenge)) return this.failedAndStop();\r\n\r\n    const sessionKey = sha3(\r\n      merge(\r\n        stringToBytes(this.initiatorIdentity!),\r\n        stringToBytes(this.responderIdentity!),\r\n        hashedPassword,\r\n        this.responderPassword,\r\n        this.localNonce,\r\n        this.remoteNonce,\r\n      ),\r\n      512,\r\n    );\r\n    this.step = -1;\r\n    return succeeded(null, this.initiatorIdentity, this.responderIdentity, sessionKey);\r\n  }\r\n\r\n  private processResponderDualIdentity(\r\n    remote: unknown[] | null,\r\n    local: unknown[],\r\n  ): AuthenticationResult {\r\n    if (this.step === 0) {\r\n      if (!remote || remote.length < 2) return failed();\r\n\r\n      this.remoteNonce = asBytes(remote[0]);\r\n      this.initiatorIdentity = asString(remote[1]);\r\n      if (!this.validRemoteNonce(this.remoteNonce) || !this.initiatorIdentity)\r\n        return this.failedAndStop();\r\n      if (!this.loadResponderSelfPassword()) return failed();\r\n\r\n      const initiatorCredential = this.provider.getHostedAccountCredential(\r\n        this.initiatorIdentity,\r\n        this.domain,\r\n      );\r\n      this.localSalt = initiatorCredential.salt;\r\n      this.initiatorPassword = initiatorCredential.hash;\r\n      if (!this.localSalt || !this.initiatorPassword) return failed();\r\n\r\n      local.push(this.localNonce, this.responderIdentity, this.localSalt);\r\n      this.step = 1;\r\n      return inProgress(local);\r\n    }\r\n\r\n    if (this.step !== 1 || !remote || remote.length < 2) return failed();\r\n\r\n    const remoteSalt = asBytes(remote[0]);\r\n    const remoteChallenge = asBytes(remote[1]);\r\n    if (!remoteSalt || !remoteChallenge || !this.remoteNonce || !this.initiatorPassword)\r\n      return this.failedAndStop();\r\n\r\n    const hashedPassword = sha3(merge(this.responderPassword!, remoteSalt));\r\n    const expectedRemoteChallenge = sha3(\r\n      merge(this.remoteNonce, this.initiatorPassword, hashedPassword, this.localNonce),\r\n    );\r\n    if (!fixedTimeEquals(expectedRemoteChallenge, remoteChallenge)) return this.failedAndStop();\r\n\r\n    const localChallenge = sha3(\r\n      merge(this.localNonce, hashedPassword, this.initiatorPassword, this.remoteNonce),\r\n    );\r\n    const sessionKey = sha3(\r\n      merge(\r\n        stringToBytes(this.initiatorIdentity!),\r\n        stringToBytes(this.responderIdentity!),\r\n        this.initiatorPassword,\r\n        hashedPassword,\r\n        this.remoteNonce,\r\n        this.localNonce,\r\n      ),\r\n      512,\r\n    );\r\n    local.push(localChallenge);\r\n    this.step = -1;\r\n    return succeeded(local, this.initiatorIdentity, this.responderIdentity, sessionKey);\r\n  }\r\n\r\n  private loadInitiatorSelfPassword(): boolean {\r\n    if (this.initiatorIdentity == null) {\r\n      const identityPassword = this.provider.getSelfIdentityAndCredential(this.domain, this.hostName);\r\n      this.initiatorIdentity = identityPassword.identity;\r\n      this.initiatorPassword = identityPassword.password;\r\n    } else {\r\n      this.initiatorPassword = this.provider.getSelfCredential(\r\n        this.initiatorIdentity,\r\n        this.domain,\r\n        this.hostName,\r\n      );\r\n    }\r\n    return this.initiatorIdentity != null && this.initiatorPassword != null;\r\n  }\r\n\r\n  private loadResponderSelfPassword(): boolean {\r\n    if (this.responderIdentity == null) {\r\n      const identityPassword = this.provider.getSelfIdentityAndCredential(this.domain, this.hostName);\r\n      this.responderIdentity = identityPassword.identity;\r\n      this.responderPassword = identityPassword.password;\r\n    } else {\r\n      this.responderPassword = this.provider.getSelfCredential(\r\n        this.responderIdentity,\r\n        this.domain,\r\n        this.hostName,\r\n      );\r\n    }\r\n    return this.responderIdentity != null && this.responderPassword != null;\r\n  }\r\n\r\n  private validRemoteNonce(remoteNonce: Uint8Array | null): remoteNonce is Uint8Array {\r\n    return (\r\n      remoteNonce != null &&\r\n      remoteNonce.length === PasswordAuthenticationHandler.nonceLength &&\r\n      !fixedTimeEquals(remoteNonce, this.localNonce)\r\n    );\r\n  }\r\n\r\n  private failedAndStop(): AuthenticationResult {\r\n    this.step = -1;\r\n    return failed();\r\n  }\r\n}\r\n\r\nfunction asAuthArray(value: unknown): unknown[] | null {\r\n  if (value == null) return null;\r\n  if (Array.isArray(value)) return value;\r\n  throw new TypeError(\"Authentication data must be an array.\");\r\n}\r\n\r\nfunction asBytes(value: unknown): Uint8Array | null {\r\n  return value instanceof Uint8Array ? value : null;\r\n}\r\n\r\nfunction asString(value: unknown): string | null {\r\n  return typeof value === \"string\" ? value : null;\r\n}\r\n\r\nfunction parseDualResponderStep(remote: unknown[]): {\r\n  responderIdentity: string | null;\r\n  salt: Uint8Array | null;\r\n} {\r\n  if (typeof remote[1] === \"string\")\r\n    return { responderIdentity: remote[1], salt: asBytes(remote[2]) };\r\n  if (typeof remote[2] === \"string\")\r\n    return { responderIdentity: remote[2], salt: asBytes(remote[1]) };\r\n  return { responderIdentity: null, salt: null };\r\n}\r\n\r\nfunction fixedTimeEquals(a: Uint8Array | null, b: Uint8Array | null): boolean {\r\n  if (!a || !b || a.length !== b.length) return false;\r\n  let diff = 0;\r\n  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\r\n  return diff === 0;\r\n}\r\n\r\nfunction failed(): AuthenticationResult {\r\n  return new AuthenticationResult(AuthenticationRuling.Failed, null);\r\n}\r\n\r\nfunction inProgress(data: unknown[]): AuthenticationResult {\r\n  return new AuthenticationResult(AuthenticationRuling.InProgress, data);\r\n}\r\n\r\nfunction succeeded(\r\n  data: unknown[] | null,\r\n  localIdentity: string | null,\r\n  remoteIdentity: string | null,\r\n  sessionKey: Uint8Array,\r\n): AuthenticationResult {\r\n  return new AuthenticationResult(\r\n    AuthenticationRuling.Succeeded,\r\n    data,\r\n    localIdentity,\r\n    remoteIdentity,\r\n    sessionKey,\r\n  );\r\n}\r\n","import { AsyncReply } from \"../../core/AsyncReply.js\";\r\nimport { merge } from \"../../data/DC.js\";\r\nimport type { AuthenticationContext } from \"../AuthenticationContext.js\";\r\nimport type { AuthenticationSession } from \"../AuthenticationSession.js\";\r\nimport type { IAuthenticationHandler } from \"../IAuthenticationHandler.js\";\r\nimport type { IAuthenticationProvider } from \"../IAuthenticationProvider.js\";\r\nimport { randomBytes } from \"../random.js\";\r\nimport { IdentityPassword } from \"./IdentityPassword.js\";\r\nimport { PasswordAuthenticationHandler } from \"./PasswordAuthenticationHandler.js\";\r\nimport { PasswordHash } from \"./PasswordHash.js\";\r\n\r\n/** Base provider for Esiur's SHA3 password-hash authentication protocol. */\r\nexport class PasswordAuthenticationProvider implements IAuthenticationProvider {\r\n  readonly defaultName = \"password-sha3-v1\";\r\n\r\n  /** Derive a storable, salted {@link PasswordHash} from a plaintext password. */\r\n  static createCredential(password: Uint8Array): PasswordHash {\r\n    if (password.length === 0) throw new Error(\"A password cannot be empty.\");\r\n    const salt = randomBytes(32);\r\n    const hash = PasswordAuthenticationHandler.computeSha3(merge(password, salt));\r\n    return new PasswordHash(hash, salt);\r\n  }\r\n\r\n  createAuthenticationHandler(context: AuthenticationContext): IAuthenticationHandler {\r\n    return new PasswordAuthenticationHandler(\r\n      context.mode,\r\n      context.direction,\r\n      context.initiatorIdentity ?? null,\r\n      context.responderIdentity ?? null,\r\n      context.hostName ?? null,\r\n      context.domain ?? null,\r\n      this,\r\n    );\r\n  }\r\n\r\n  getHostedAccountCredential(_identity: string, _domain: string | null): PasswordHash {\r\n    return new PasswordHash();\r\n  }\r\n\r\n  getSelfIdentityAndCredential(_domain: string | null, _hostname: string | null): IdentityPassword {\r\n    return new IdentityPassword();\r\n  }\r\n\r\n  getSelfCredential(\r\n    _identity: string,\r\n    _domain: string | null,\r\n    _hostname: string | null,\r\n  ): Uint8Array | null {\r\n    return null;\r\n  }\r\n\r\n  login(_session: AuthenticationSession): AsyncReply<boolean> {\r\n    return AsyncReply.fromResult(false);\r\n  }\r\n\r\n  logout(_session: AuthenticationSession): AsyncReply<boolean> {\r\n    return AsyncReply.fromResult(false);\r\n  }\r\n}\r\n","/** Stored salted password hash and salt for a hosted account. */\r\nexport class PasswordHash {\r\n  constructor(\r\n    readonly hash: Uint8Array | null = null,\r\n    readonly salt: Uint8Array | null = null,\r\n  ) {}\r\n}\r\n","import { merge, stringToBytes, uint32ToBytes, uint64ToBytes } from \"../../data/DC.js\";\r\nimport { Endian } from \"../../data/Endian.js\";\r\nimport { AuthenticationDirection } from \"../AuthenticationDirection.js\";\r\nimport { AuthenticationMode } from \"../AuthenticationMode.js\";\r\nimport { EncryptionMode } from \"../EncryptionMode.js\";\r\nimport type { EncryptionContext } from \"./EncryptionContext.js\";\r\nimport type { IEncryptionProvider } from \"./IEncryptionProvider.js\";\r\nimport type { ISymetricCipher } from \"./ISymetricCipher.js\";\r\n\r\ntype NodeCrypto = typeof import(\"node:crypto\");\r\n\r\nconst KEY_SIZE = 32;\r\nconst NONCE_PREFIX_SIZE = 4;\r\nconst SEQUENCE_SIZE = 8;\r\nconst TAG_SIZE = 16;\r\nconst RECORD_OVERHEAD = SEQUENCE_SIZE + TAG_SIZE;\r\nconst MIN_SHARED_KEY = 16;\r\nconst MAX_SHARED_KEY = 1024;\r\nconst MIN_PEER_NONCE = 16;\r\nconst MAX_PEER_NONCE = 64;\r\nconst MAX_SEQUENCE = 0xffffffffffffffffn;\r\n\r\nconst CONTEXT_LABEL = stringToBytes(\"esiur/ep/aes-256-gcm/context/v3\");\r\nconst INITIATOR_TO_RESPONDER_KEY_LABEL = stringToBytes(\r\n  \"esiur/ep/aes-256-gcm/v1/initiator-to-responder/key\",\r\n);\r\nconst RESPONDER_TO_INITIATOR_KEY_LABEL = stringToBytes(\r\n  \"esiur/ep/aes-256-gcm/v1/responder-to-initiator/key\",\r\n);\r\nconst INITIATOR_TO_RESPONDER_NONCE_LABEL = stringToBytes(\r\n  \"esiur/ep/aes-256-gcm/v1/initiator-to-responder/nonce\",\r\n);\r\nconst RESPONDER_TO_INITIATOR_NONCE_LABEL = stringToBytes(\r\n  \"esiur/ep/aes-256-gcm/v1/responder-to-initiator/nonce\",\r\n);\r\n\r\n/**\r\n * Creates AES-256-GCM record ciphers (port of C# `AesEncryptionProvider`).\r\n * Session keys and nonce prefixes are derived with HKDF-SHA256 and separated\r\n * by protocol direction and purpose.\r\n *\r\n * Node-only: `node:crypto` is loaded via a dynamic `import()` inside\r\n * {@link createCipher} (called once per session, during the handshake) —\r\n * matching `TcpSocket.ts`'s environment-detection convention. This is what\r\n * lets the actual per-record {@link ISymetricCipher.encrypt}/`decrypt` stay\r\n * fully synchronous afterward: Web Crypto has no synchronous AES-GCM in\r\n * either browser or Node, but `node:crypto`'s `createCipheriv`/\r\n * `createDecipheriv` does, and resolving the module once per session (not\r\n * once per record) keeps `NetworkConnection.send`'s synchronous contract\r\n * intact with no ripple into the hot send/receive path. The tradeoff is that\r\n * encrypted transport is Node-only for now — a browser WSocket connection\r\n * can still connect, just not with `encryptionMode` set.\r\n */\r\nexport class AesEncryptionProvider implements IEncryptionProvider {\r\n  static readonly Name = \"aes-gcm\";\r\n  readonly defaultName = AesEncryptionProvider.Name;\r\n  readonly maximumRecordOverhead = RECORD_OVERHEAD;\r\n\r\n  async createCipher(context: EncryptionContext): Promise<ISymetricCipher> {\r\n    const nodeCrypto = await getNodeCrypto();\r\n    return new AesGcmSymetricCipher(context, nodeCrypto);\r\n  }\r\n}\r\n\r\n/**\r\n * AES-256-GCM session record cipher (port of C# `AesGcmSymetricCipher`).\r\n *\r\n * A record contains an 8-byte big-endian sequence followed by ciphertext and\r\n * a 16-byte GCM tag. The transport's 4-byte record length and the sequence\r\n * are authenticated as associated data. Sequence numbers are both implicit\r\n * state and explicit record fields, so replay and reordering fail closed.\r\n */\r\nexport class AesGcmSymetricCipher implements ISymetricCipher {\r\n  /** {@link import(\"../../../esiur-dotnet counterpart\").SymetricEncryptionAlgorithmType.AES} */\r\n  readonly identifier = 0;\r\n\r\n  private readonly contextSalt: Uint8Array;\r\n  private readonly sendKeyLabel: Uint8Array;\r\n  private readonly receiveKeyLabel: Uint8Array;\r\n  private readonly sendNonceLabel: Uint8Array;\r\n  private readonly receiveNonceLabel: Uint8Array;\r\n\r\n  private sendKey: Uint8Array | undefined;\r\n  private receiveKey: Uint8Array | undefined;\r\n  private sendNoncePrefix: Uint8Array | undefined;\r\n  private receiveNoncePrefix: Uint8Array | undefined;\r\n  private sendSequence = 0n;\r\n  private receiveSequence = 0n;\r\n  private keyInitialized = false;\r\n\r\n  constructor(\r\n    context: EncryptionContext,\r\n    private readonly nodeCrypto: NodeCrypto,\r\n  ) {\r\n    validateContext(context);\r\n    this.contextSalt = composeContextSalt(context, nodeCrypto);\r\n\r\n    if (context.direction === AuthenticationDirection.Initiator) {\r\n      this.sendKeyLabel = INITIATOR_TO_RESPONDER_KEY_LABEL;\r\n      this.receiveKeyLabel = RESPONDER_TO_INITIATOR_KEY_LABEL;\r\n      this.sendNonceLabel = INITIATOR_TO_RESPONDER_NONCE_LABEL;\r\n      this.receiveNonceLabel = RESPONDER_TO_INITIATOR_NONCE_LABEL;\r\n    } else {\r\n      this.sendKeyLabel = RESPONDER_TO_INITIATOR_KEY_LABEL;\r\n      this.receiveKeyLabel = INITIATOR_TO_RESPONDER_KEY_LABEL;\r\n      this.sendNonceLabel = RESPONDER_TO_INITIATOR_NONCE_LABEL;\r\n      this.receiveNonceLabel = INITIATOR_TO_RESPONDER_NONCE_LABEL;\r\n    }\r\n\r\n    this.setKey(context.key);\r\n  }\r\n\r\n  encrypt(data: Uint8Array): Uint8Array {\r\n    if (!this.sendKey || !this.sendNoncePrefix) throw new Error(\"Cipher key is not initialized.\");\r\n    if (this.sendSequence === MAX_SEQUENCE)\r\n      throw new Error(\"The AES-GCM send sequence is exhausted.\");\r\n\r\n    const sequence = this.sendSequence;\r\n    const recordLength = data.length + RECORD_OVERHEAD;\r\n    const nonce = composeNonce(this.sendNoncePrefix, sequence);\r\n    const aad = composeAad(recordLength, sequence);\r\n\r\n    const cipher = this.nodeCrypto.createCipheriv(\"aes-256-gcm\", this.sendKey, nonce, {\r\n      authTagLength: TAG_SIZE,\r\n    });\r\n    cipher.setAAD(aad);\r\n    const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);\r\n    const tag = cipher.getAuthTag();\r\n\r\n    this.sendSequence++;\r\n    return merge(uint64ToBytes(sequence, Endian.Big), ciphertext, tag);\r\n  }\r\n\r\n  decrypt(data: Uint8Array): Uint8Array {\r\n    if (!this.receiveKey || !this.receiveNoncePrefix)\r\n      throw new Error(\"Cipher key is not initialized.\");\r\n    if (data.length < RECORD_OVERHEAD) throw new Error(\"The AES-GCM record is truncated.\");\r\n\r\n    const sequence = readUInt64BE(data, 0);\r\n    if (sequence !== this.receiveSequence)\r\n      throw new Error(\"The AES-GCM record sequence is invalid.\");\r\n    if (this.receiveSequence === MAX_SEQUENCE)\r\n      throw new Error(\"The AES-GCM receive sequence is exhausted.\");\r\n\r\n    const recordLength = data.length;\r\n    const ciphertext = data.subarray(SEQUENCE_SIZE, data.length - TAG_SIZE);\r\n    const tag = data.subarray(data.length - TAG_SIZE);\r\n    const nonce = composeNonce(this.receiveNoncePrefix, sequence);\r\n    const aad = composeAad(recordLength, sequence);\r\n\r\n    const decipher = this.nodeCrypto.createDecipheriv(\"aes-256-gcm\", this.receiveKey, nonce, {\r\n      authTagLength: TAG_SIZE,\r\n    });\r\n    decipher.setAAD(aad);\r\n    decipher.setAuthTag(tag);\r\n\r\n    let plaintext: Buffer;\r\n    try {\r\n      plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\r\n    } catch (error) {\r\n      throw new Error(\"AES-GCM record authentication failed.\", { cause: error });\r\n    }\r\n\r\n    this.receiveSequence++;\r\n    return new Uint8Array(plaintext);\r\n  }\r\n\r\n  /**\r\n   * Initialize the cipher key. Session ciphers are deliberately immutable\r\n   * after construction — resetting a key would also reset the GCM nonce\r\n   * sequence. Create a new cipher with fresh peer nonces to use different\r\n   * key material.\r\n   */\r\n  setKey(key: Uint8Array): Uint8Array {\r\n    validateSharedKey(key);\r\n    if (this.keyInitialized)\r\n      throw new Error(\r\n        \"AES-GCM session keys are immutable; create a new cipher with fresh peer nonces.\",\r\n      );\r\n\r\n    this.sendKey = derive(this.nodeCrypto, key, this.contextSalt, this.sendKeyLabel, KEY_SIZE);\r\n    this.receiveKey = derive(\r\n      this.nodeCrypto,\r\n      key,\r\n      this.contextSalt,\r\n      this.receiveKeyLabel,\r\n      KEY_SIZE,\r\n    );\r\n    this.sendNoncePrefix = derive(\r\n      this.nodeCrypto,\r\n      key,\r\n      this.contextSalt,\r\n      this.sendNonceLabel,\r\n      NONCE_PREFIX_SIZE,\r\n    );\r\n    this.receiveNoncePrefix = derive(\r\n      this.nodeCrypto,\r\n      key,\r\n      this.contextSalt,\r\n      this.receiveNonceLabel,\r\n      NONCE_PREFIX_SIZE,\r\n    );\r\n    this.sendSequence = 0n;\r\n    this.receiveSequence = 0n;\r\n    this.keyInitialized = true;\r\n    return key.slice();\r\n  }\r\n}\r\n\r\nfunction validateSharedKey(key: Uint8Array): void {\r\n  if (key.length < MIN_SHARED_KEY || key.length > MAX_SHARED_KEY)\r\n    throw new RangeError(\r\n      `The shared key must contain between ${MIN_SHARED_KEY} and ${MAX_SHARED_KEY} bytes.`,\r\n    );\r\n}\r\n\r\nfunction validateNonce(nonce: Uint8Array | null | undefined, name: string): asserts nonce is Uint8Array {\r\n  if (!nonce) throw new Error(`${name} is required.`);\r\n  if (nonce.length < MIN_PEER_NONCE || nonce.length > MAX_PEER_NONCE)\r\n    throw new RangeError(\r\n      `${name} must contain between ${MIN_PEER_NONCE} and ${MAX_PEER_NONCE} bytes.`,\r\n    );\r\n}\r\n\r\nfunction validateAddress(\r\n  address: Uint8Array | null | undefined,\r\n  name: string,\r\n): asserts address is Uint8Array {\r\n  if (!address) throw new Error(`${name} is required for address-bound encryption.`);\r\n  if (address.length !== 4 && address.length !== 16)\r\n    throw new RangeError(`${name} must be an IPv4 or IPv6 byte sequence.`);\r\n}\r\n\r\nfunction isUnspecifiedAddress(address: Uint8Array): boolean {\r\n  return address.every((b) => b === 0);\r\n}\r\n\r\nfunction validateContext(context: EncryptionContext): void {\r\n  validateSharedKey(context.key);\r\n  validateNonce(context.initiatorNonce, \"initiatorNonce\");\r\n  validateNonce(context.responderNonce, \"responderNonce\");\r\n\r\n  if (\r\n    context.direction !== AuthenticationDirection.Initiator &&\r\n    context.direction !== AuthenticationDirection.Responder\r\n  )\r\n    throw new RangeError(\"Invalid encryption context direction.\");\r\n  if (context.mode === EncryptionMode.None)\r\n    throw new Error(\"AES-GCM requires an encrypted session mode.\");\r\n  if (\r\n    context.mode !== EncryptionMode.EncryptWithSessionKey &&\r\n    context.mode !== EncryptionMode.EncryptWithSessionKeyAndAddress\r\n  )\r\n    throw new RangeError(`Unsupported encryption mode \\`${context.mode}\\`.`);\r\n  if (!context.protocol?.trim()) throw new Error(\"A negotiated encryption protocol is required.\");\r\n  if (!context.offeredProtocols || context.offeredProtocols.length === 0)\r\n    throw new Error(\"The initiator's encryption offer is required.\");\r\n  if (context.offeredProtocols.some((p) => !p?.trim()))\r\n    throw new Error(\"Encryption offers cannot contain empty protocol names.\");\r\n  if (!context.offeredProtocols.includes(context.protocol))\r\n    throw new Error(\"The selected encryption protocol was not offered.\");\r\n  if (context.authenticationMode === AuthenticationMode.None)\r\n    throw new Error(\"AES-GCM requires an authenticated session.\");\r\n  if (!context.authenticationProtocol?.trim())\r\n    throw new Error(\"A negotiated authentication protocol is required.\");\r\n\r\n  if (context.mode === EncryptionMode.EncryptWithSessionKeyAndAddress) {\r\n    validateAddress(context.initiatorAddress, \"initiatorAddress\");\r\n    validateAddress(context.responderAddress, \"responderAddress\");\r\n    if (\r\n      isUnspecifiedAddress(context.initiatorAddress) ||\r\n      isUnspecifiedAddress(context.responderAddress)\r\n    )\r\n      throw new Error(\"Address-bound encryption requires concrete peer network addresses.\");\r\n  }\r\n}\r\n\r\nfunction lengthPrefixed(value: Uint8Array): Uint8Array {\r\n  return merge(uint32ToBytes(value.length, Endian.Big), value);\r\n}\r\n\r\n/** SHA-256 over an ordered, length-prefixed transcript of every negotiation field. */\r\nfunction composeContextSalt(context: EncryptionContext, nodeCrypto: NodeCrypto): Uint8Array {\r\n  const parts: Uint8Array[] = [\r\n    CONTEXT_LABEL,\r\n    Uint8Array.of(context.authenticationMode & 0xff),\r\n    lengthPrefixed(stringToBytes(context.authenticationProtocol)),\r\n    lengthPrefixed(stringToBytes(context.domain ?? \"\")),\r\n    Uint8Array.of(context.mode & 0xff),\r\n    uint32ToBytes(context.offeredProtocols.length, Endian.Big),\r\n  ];\r\n  for (const offered of context.offeredProtocols) parts.push(lengthPrefixed(stringToBytes(offered)));\r\n  parts.push(lengthPrefixed(stringToBytes(context.protocol)));\r\n  parts.push(lengthPrefixed(context.initiatorNonce));\r\n  parts.push(lengthPrefixed(context.responderNonce));\r\n\r\n  if (context.mode === EncryptionMode.EncryptWithSessionKeyAndAddress) {\r\n    parts.push(lengthPrefixed(context.initiatorAddress!));\r\n    parts.push(lengthPrefixed(context.responderAddress!));\r\n  }\r\n\r\n  const transcript = merge(...parts);\r\n  return new Uint8Array(nodeCrypto.createHash(\"sha256\").update(transcript).digest());\r\n}\r\n\r\nfunction derive(\r\n  nodeCrypto: NodeCrypto,\r\n  key: Uint8Array,\r\n  salt: Uint8Array,\r\n  label: Uint8Array,\r\n  size: number,\r\n): Uint8Array {\r\n  return new Uint8Array(nodeCrypto.hkdfSync(\"sha256\", key, salt, label, size));\r\n}\r\n\r\nfunction composeNonce(prefix: Uint8Array, sequence: bigint): Uint8Array {\r\n  return merge(prefix, uint64ToBytes(sequence, Endian.Big));\r\n}\r\n\r\nfunction composeAad(recordLength: number, sequence: bigint): Uint8Array {\r\n  return merge(uint32ToBytes(recordLength, Endian.Big), uint64ToBytes(sequence, Endian.Big));\r\n}\r\n\r\nfunction readUInt64BE(data: Uint8Array, offset: number): bigint {\r\n  let value = 0n;\r\n  for (let i = 0; i < 8; i++) value = (value << 8n) | BigInt(data[offset + i]);\r\n  return value;\r\n}\r\n\r\nasync function getNodeCrypto(): Promise<NodeCrypto> {\r\n  try {\r\n    return await import(\"node:crypto\");\r\n  } catch (error) {\r\n    throw new Error(\r\n      \"AesEncryptionProvider requires Node.js — the 'node:crypto' module is unavailable in this environment.\",\r\n      { cause: error },\r\n    );\r\n  }\r\n}\r\n","import type { IResource } from \"../../resource/IResource.js\";\r\nimport type { MemberTemplate } from \"../../resource/template.js\";\r\nimport type { AuthenticationSession } from \"../AuthenticationSession.js\";\r\nimport { ActionType } from \"./ActionType.js\";\r\nimport type { IPermissionsManager } from \"./IPermissionsManager.js\";\r\nimport { Ruling } from \"./Ruling.js\";\r\n\r\nconst RESOURCE_PERMISSION_KEYS: ReadonlyMap<ActionType, string> = new Map([\r\n  [ActionType.Attach, \"_attach\"],\r\n  [ActionType.Detach, \"_detach\"],\r\n  [ActionType.Delete, \"_delete\"],\r\n  [ActionType.CreateResource, \"_create_resource\"],\r\n  [ActionType.InquireAttributes, \"_get_attributes\"],\r\n  [ActionType.UpdateAttributes, \"_set_attributes\"],\r\n  [ActionType.AddChild, \"_add_child\"],\r\n  [ActionType.RemoveChild, \"_remove_child\"],\r\n  [ActionType.AddParent, \"_add_parent\"],\r\n  [ActionType.RemoveParent, \"_remove_parent\"],\r\n  [ActionType.Rename, \"_rename\"],\r\n  [ActionType.ViewTypeDef, \"_view_typedef\"],\r\n]);\r\n\r\n/**\r\n * Per-identity permissions from a settings map (port of C#\r\n * `UserPermissionsManager`). Settings shape: `{ [identity|\"public\"]: {\r\n * [resourcePermissionKey|memberName]: \"yes\" | ... } }`.\r\n */\r\nexport class UserPermissionsManager implements IPermissionsManager {\r\n  readonly managerCategory = \"permissions\" as const;\r\n  private _settings: Map<string, unknown> | undefined;\r\n\r\n  constructor(settings?: Map<string, unknown>) {\r\n    this._settings = settings;\r\n  }\r\n\r\n  get settings(): Map<string, unknown> | undefined {\r\n    return this._settings;\r\n  }\r\n\r\n  applicable(\r\n    resource: IResource | null,\r\n    session: AuthenticationSession | null,\r\n    action: ActionType,\r\n    member: MemberTemplate | null,\r\n    _inquirer?: unknown,\r\n  ): Ruling {\r\n    if (!this._settings || !session) return Ruling.Denied;\r\n\r\n    let userPermissions: Map<string, unknown> | undefined;\r\n    if (session.remoteIdentity && this._settings.get(session.remoteIdentity) instanceof Map) {\r\n      userPermissions = this._settings.get(session.remoteIdentity) as Map<string, unknown>;\r\n    } else if (this._settings.get(\"public\") instanceof Map) {\r\n      userPermissions = this._settings.get(\"public\") as Map<string, unknown>;\r\n    }\r\n\r\n    if (!userPermissions) return Ruling.Denied;\r\n\r\n    const resourcePermissionKey = RESOURCE_PERMISSION_KEYS.get(action);\r\n    if (resourcePermissionKey) return isAllowed(userPermissions, resourcePermissionKey);\r\n\r\n    // Member-level access is fail closed: an absent member/action entry must\r\n    // never fall through to Warehouse's compatibility defaults.\r\n    const rawMemberPermissions = member ? userPermissions.get(member.name) : undefined;\r\n    if (!(rawMemberPermissions instanceof Map)) return Ruling.Denied;\r\n\r\n    return isAllowed(rawMemberPermissions, ActionType[action]);\r\n  }\r\n\r\n  initialize(settings: Map<string, unknown> | undefined, _resource: IResource | null): boolean {\r\n    this._settings = settings;\r\n    return true;\r\n  }\r\n}\r\n\r\nfunction isAllowed(permissions: Map<string, unknown>, key: string): Ruling {\r\n  return permissions.get(key) === \"yes\" ? Ruling.Allowed : Ruling.Denied;\r\n}\r\n","import type { IResource } from \"../../resource/IResource.js\";\r\nimport type { MemberTemplate } from \"../../resource/template.js\";\r\nimport type { AuthenticationSession } from \"../AuthenticationSession.js\";\r\nimport type { ActionType } from \"./ActionType.js\";\r\nimport type { IPermissionsManager } from \"./IPermissionsManager.js\";\r\nimport { Ruling } from \"./Ruling.js\";\r\n\r\n/**\r\n * Delegates permission checks to whatever `IPermissionsManager`s are\r\n * registered for the resource's owning store's type (port of C#\r\n * `StorePermissionsManager`) — lets a store centralize policy for every\r\n * resource it holds rather than annotating each resource type individually.\r\n *\r\n * Delegates only to managers attached to the store's own type, excluding\r\n * itself: re-entering evaluation for the store would run Warehouse defaults\r\n * (including this manager) again and could recurse indefinitely or apply a\r\n * rate policy twice.\r\n */\r\nexport class StorePermissionsManager implements IPermissionsManager {\r\n  readonly managerCategory = \"permissions\" as const;\r\n  private _settings: Map<string, unknown> | undefined;\r\n\r\n  get settings(): Map<string, unknown> | undefined {\r\n    return this._settings;\r\n  }\r\n\r\n  applicable(\r\n    resource: IResource | null,\r\n    session: AuthenticationSession | null,\r\n    action: ActionType,\r\n    member: MemberTemplate | null,\r\n    inquirer?: unknown,\r\n  ): Ruling {\r\n    const storeInstance = resource?.instance?.store?.instance;\r\n    const store = storeInstance?.resource;\r\n    if (!storeInstance || !store) return Ruling.DontCare;\r\n\r\n    const managers = storeInstance.warehouse\r\n      .resolveResourceManagers(store.constructor as Function)\r\n      .filter(\r\n        (m): m is IPermissionsManager => m.managerCategory === \"permissions\" && m !== this,\r\n      );\r\n\r\n    let allowed = false;\r\n    for (const manager of managers) {\r\n      const ruling = manager.applicable(store, session, action, member, inquirer);\r\n      if (ruling === Ruling.Denied) return Ruling.Denied;\r\n      if (ruling === Ruling.Allowed) allowed = true;\r\n    }\r\n\r\n    return allowed ? Ruling.Allowed : Ruling.DontCare;\r\n  }\r\n\r\n  initialize(settings: Map<string, unknown> | undefined, _resource: IResource | null): boolean {\r\n    this._settings = settings;\r\n    return true;\r\n  }\r\n}\r\n","import type { EpConnection } from \"../../protocol/EpConnection.js\";\r\nimport { Ruling } from \"../permissions/Ruling.js\";\r\nimport { RateControlContext, RatePolicy } from \"./RatePolicy.js\";\r\n\r\ninterface Bucket {\r\n  tokens: number;\r\n  lastTimestamp: number;\r\n  queued: number;\r\n}\r\n\r\n/**\r\n * Per-connection, per-member token-bucket policy with bounded delayed\r\n * reservations (port of C# `BurstRatePolicy`).\r\n *\r\n * Buckets are scoped per `EpConnection` via a `WeakMap` (the GC-friendly\r\n * analogue of C#'s `ConditionalWeakTable<object, ConnectionBuckets>` —\r\n * entries are dropped automatically once a connection is no longer\r\n * referenced elsewhere). Timestamps use `performance.now()` (monotonic,\r\n * sub-millisecond, available in both Node and browsers) in place of\r\n * `Stopwatch.GetTimestamp()`; all durations are in milliseconds rather than\r\n * `TimeSpan`. JS's single-threaded event loop makes C#'s per-bucket `lock`\r\n * unnecessary — nothing here awaits mid-mutation.\r\n */\r\nexport class BurstRatePolicy extends RatePolicy {\r\n  /** Number of permits replenished during each {@link period}. */\r\n  permitLimit = 100;\r\n  /** Replenishment period, in milliseconds. */\r\n  period = 1000;\r\n  /** Additional permits available for an immediate burst. */\r\n  burstLimit = 0;\r\n  /**\r\n   * Maximum number of delayed reservations per connection and member.\r\n   * Further requests are denied until queue positions become available.\r\n   */\r\n  queueLimit = 0;\r\n\r\n  private readonly connections = new WeakMap<EpConnection, Map<string, Bucket>>();\r\n\r\n  constructor(name: string = \"\") {\r\n    super(name);\r\n  }\r\n\r\n  override applicable(context?: RateControlContext): Ruling {\r\n    if (!context) return Ruling.DontCare;\r\n    this.validate();\r\n\r\n    const capacity = this.permitLimit + this.burstLimit;\r\n    const now = performance.now();\r\n    const key = `${context.action}:${memberKey(context)}`;\r\n\r\n    let buckets = this.connections.get(context.connection);\r\n    if (!buckets) {\r\n      buckets = new Map();\r\n      this.connections.set(context.connection, buckets);\r\n    }\r\n    let bucket = buckets.get(key);\r\n    if (!bucket) {\r\n      bucket = { tokens: capacity, lastTimestamp: now, queued: 0 };\r\n      buckets.set(key, bucket);\r\n    }\r\n\r\n    this.replenish(bucket, now, capacity);\r\n\r\n    if (bucket.tokens >= 1) {\r\n      bucket.tokens -= 1;\r\n      return Ruling.Allowed;\r\n    }\r\n\r\n    if (this.queueLimit === 0 || bucket.queued >= this.queueLimit) return Ruling.Denied;\r\n\r\n    bucket.tokens -= 1;\r\n    bucket.queued++;\r\n\r\n    const seconds = (-bucket.tokens * (this.period / 1000)) / this.permitLimit;\r\n    const delayMs = Math.max(0, seconds * 1000);\r\n    context.delay = delayMs;\r\n\r\n    void this.releaseQueuePosition(bucket, delayMs);\r\n    return Ruling.Allowed;\r\n  }\r\n\r\n  private validate(): void {\r\n    if (this.permitLimit <= 0) throw new Error(\"permitLimit must be greater than zero.\");\r\n    if (this.period <= 0) throw new Error(\"period must be greater than zero.\");\r\n    if (this.burstLimit < 0) throw new Error(\"burstLimit cannot be negative.\");\r\n    if (this.queueLimit < 0) throw new Error(\"queueLimit cannot be negative.\");\r\n  }\r\n\r\n  private replenish(bucket: Bucket, now: number, capacity: number): void {\r\n    const elapsedMs = now - bucket.lastTimestamp;\r\n    if (elapsedMs <= 0) return;\r\n    const replenished = (elapsedMs / this.period) * this.permitLimit;\r\n    bucket.tokens = Math.min(capacity, bucket.tokens + replenished);\r\n    bucket.lastTimestamp = now;\r\n  }\r\n\r\n  private async releaseQueuePosition(bucket: Bucket, delayMs: number): Promise<void> {\r\n    if (delayMs > 0) await new Promise<void>((resolve) => setTimeout(resolve, delayMs));\r\n    if (bucket.queued > 0) bucket.queued--;\r\n  }\r\n}\r\n\r\nfunction memberKey(context: RateControlContext): string {\r\n  const typeName = (context.resource?.constructor as { name?: string } | undefined)?.name ?? \"\";\r\n  return `${typeName}.${context.member.name}`;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IACY;AADZ;AAAA;AAAA;AACO,IAAK,YAAL,kBAAKA,eAAL;AACL,MAAAA,sBAAA,gBAAa,KAAb;AACA,MAAAA,sBAAA,eAAY,KAAZ;AACA,MAAAA,sBAAA,aAAU,KAAV;AAHU,aAAAA;AAAA,OAAA;AAAA;AAAA;;;ACDZ,IAIY;AAJZ;AAAA;AAAA;AAIO,IAAK,gBAAL,kBAAKC,mBAAL;AACL,MAAAA,8BAAA,sBAAmB,KAAnB;AACA,MAAAA,8BAAA;AACA,MAAAA,8BAAA;AACA,MAAAA,8BAAA;AACA,MAAAA,8BAAA;AACA,MAAAA,8BAAA;AACA,MAAAA,8BAAA;AACA,MAAAA,8BA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AAEA,SAAS,UAAU,SAAqC;AACtD,QAAM,WAAY,QAAQ,UAAU,aAA+C,QAAQ;AAC3F,SAAO,GAAG,QAAQ,IAAI,QAAQ,OAAO,IAAI;AAC3C;","names":["ErrorType","ExceptionCode","Endian","t","SocketState","ProgressType","LogType","StreamMode","MASK64","TduClass","TduIdentifier","t","cl","t","cl","TruIdentifier","TypeDefKind","_annotations_dec","_usage_dec","_description_dec","_name_dec","_a","_init","_a","_init","_a","_init","_historyControl_dec","_orderingControl_dec","_a","_init","_valueType_dec","_a","_init","_defaultValue_dec","_valueType_dec","_a","_init","t","t","ResourceOperation","MemberType","t","EpPacketMethod","EpPacketRequest","EpPacketReply","EpPacketNotification","textEncoder","EpAuthPacketCommand","EpAuthPacketMethod","AuthenticationMode","EncryptionMode","EpAuthPacketHeader","AuthenticationDirection","AuthenticationMaterialType","AuthenticationRuling","ActionType","event","typeDef","parsed","createDeferred","TcpSocket","selected","chain","reply","isTypeDef","consumed","isThenable","Ruling","event","EP_SUBPROTOCOL","asBytes","hashedPassword"]}