{"version":3,"sources":["../src/constants/namespaces.constants.ts","../src/constants/protocol.constants.ts","../src/errors/sdk-error.ts","../src/errors/handshake-error.ts","../src/errors/http-client-error.ts","../src/errors/http-server-error.ts","../src/errors/protocol-error.ts","../src/errors/request-cancelled-error.ts","../src/errors/stream-cancelled-error.ts","../src/errors/timeout-error.ts","../src/errors/transport-error.ts","../src/logging/console-logger.ts","../src/logging/noop-logger.ts","../src/modules/api.module.ts","../src/modules/appearance.module.ts","../src/modules/auth.module.ts","../src/modules/chat.module.ts","../src/modules/config.module.ts","../src/modules/device.module.ts","../src/modules/flags.module.ts","../src/modules/http.module.ts","../src/modules/links.module.ts","../src/modules/module-registry.ts","../src/modules/navigation.module.ts","../src/modules/notifications.module.ts","../src/modules/permissions.module.ts","../src/modules/platform.module.ts","../src/modules/storage.module.ts","../src/rpc/middleware.ts","../src/constants/version.generated.ts","../src/observability/metrics-recorder.ts","../src/observability/tracer.ts","../src/utils/backoff.ts","../src/utils/delay.ts","../src/utils/id.ts","../src/protocol/message-factory.ts","../src/protocol/message-validator.ts","../src/stream/stream-builder.ts","../src/rpc/rpc-client.ts","../src/transport/default-transport.ts","../src/client/MiniAppSdk.ts","../src/index.ts"],"sourcesContent":["/**\n * Every RPC namespace the SDK talks to. Centralized so a typo in a module\n * implementation becomes a compile error (unknown property) instead of a\n * silently-broken runtime string.\n */\nexport const NAMESPACES = {\n  AUTH: \"auth\",\n  PERMISSIONS: \"permissions\",\n  FLAGS: \"flags\",\n  CONFIG: \"config\",\n  NAVIGATION: \"navigation\",\n  PLATFORM: \"platform\",\n  DEVICE: \"device\",\n  API: \"api\",\n  STORAGE: \"storage\",\n  HTTP: \"http\",\n  APPEARANCE: \"appearance\",\n  AI: \"ai\",\n  NOTIFICATIONS: \"notifications\",\n  LINKS: \"links\",\n  EVENT: \"event\",\n  HANDSHAKE: \"handshake\",\n  HEARTBEAT: \"heartbeat\",\n} as const;\n\nexport type Namespace = (typeof NAMESPACES)[keyof typeof NAMESPACES];\n\n/**\n * The domain namespaces this SDK build can make requests against. Sent to\n * the host during the handshake so it can tell the mini app which of them,\n * if any, it doesn't actually implement — deliberately excludes `event` and\n * `handshake`, which are protocol-level concerns rather than domain\n * capabilities a host opts in or out of.\n */\nexport const SDK_CAPABILITIES: string[] = [\n  NAMESPACES.AUTH,\n  NAMESPACES.PERMISSIONS,\n  NAMESPACES.FLAGS,\n  NAMESPACES.CONFIG,\n  NAMESPACES.NAVIGATION,\n  NAMESPACES.PLATFORM,\n  NAMESPACES.DEVICE,\n  NAMESPACES.STORAGE,\n  NAMESPACES.API,\n  NAMESPACES.HTTP,\n  NAMESPACES.APPEARANCE,\n  NAMESPACES.AI,\n  NAMESPACES.NOTIFICATIONS,\n  NAMESPACES.LINKS,\n];\n\n/**\n * Actions, grouped by namespace. Every module implementation must use these\n * instead of inline string literals.\n */\nexport const ACTIONS = {\n  AUTH: {\n    GET_USER: \"getUser\",\n    IS_AUTHENTICATED: \"isAuthenticated\",\n    LOGOUT: \"logout\",\n  },\n  PERMISSIONS: {\n    HAS: \"has\",\n    LIST: \"list\",\n  },\n  FLAGS: {\n    IS_ENABLED: \"isEnabled\",\n    GET_ALL: \"getAll\",\n  },\n  CONFIG: {\n    GET: \"get\",\n    GET_ALL: \"getAll\",\n  },\n  NAVIGATION: {\n    NAVIGATE: \"navigate\",\n    GET_CURRENT: \"getCurrent\",\n    BACK: \"back\",\n    PUSH: \"push\",\n  },\n  PLATFORM: {\n    GET_TYPE: \"getType\",\n  },\n  DEVICE: {\n    LOCATION: \"location\",\n    CAMERA: \"camera\",\n    GALLERY: \"gallery\",\n    FILES: \"files\",\n    DOWNLOAD: \"download\",\n    CONTACT: \"contact\",\n    BIOMETRIC: \"biometric\",\n    NOTIFICATIONS: \"notifications\",\n    NETWORK: \"network\",\n    INFO: \"info\",\n  },\n  HTTP: {\n    GET: \"get\",\n    POST: \"post\",\n    PUT: \"put\",\n    PATCH: \"patch\",\n    DELETE: \"delete\",\n    STREAM: \"stream\",\n    GET_STREAM: \"getStream\",\n  },\n  STORAGE: {\n    GET: \"get\",\n    SET: \"set\",\n    REMOVE: \"remove\",\n  },\n  API: {\n    REQUEST: \"request\",\n  },\n  APPEARANCE: {\n    GET_LOCALE: \"getLocale\",\n    GET_THEME: \"getTheme\",\n  },\n  AI: {\n    CHAT: \"chat\",\n    CANCEL: \"cancel\",\n  },\n  NOTIFICATIONS: {\n    REGISTER: \"register\",\n  },\n  LINKS: {\n    OPEN: \"open\",\n  },\n  EVENT: {\n    SUBSCRIBE: \"subscribe\",\n    UNSUBSCRIBE: \"unsubscribe\",\n    EMIT: \"emit\",\n  },\n  HANDSHAKE: {\n    CONNECT: \"connect\",\n  },\n  HEARTBEAT: {\n    PING: \"ping\",\n  },\n} as const;\n\n/**\n * Navigation events on the wire, in both directions:\n *\n *  - `BACK_REQUESTED` (host → mini app) is published when the user presses\n *    the native back button. The host holds the container open until the\n *    mini app answers with `navigation.router.back(consumed)`; `false`\n *    means \"I'm at my root, you take over\".\n *  - `ROUTE_CHANGED` (mini app → host) is what a mini app `emit()`s after\n *    its own router moved, so the host can keep its back-button policy in\n *    sync without polling `navigation.getCurrent()`.\n */\nexport const NAVIGATION_EVENTS = {\n  BACK_REQUESTED: \"navigation.back.requested\",\n  ROUTE_CHANGED: \"navigation.route.changed\",\n} as const;\n\n/**\n * Connection-state events the SDK itself emits (as opposed to host-published\n * events). Mini apps subscribe with `sdk.on(\"connection.lost\", …)` /\n * `sdk.on(\"connection.established\", …)` to reconcile state — re-fetch config\n * or flags, re-subscribe to events — after a host restart or transport drop.\n * Emitted only when the heartbeat/reconnect feature is enabled.\n */\nexport const CONNECTION_EVENTS = {\n  LOST: \"connection.lost\",\n  ESTABLISHED: \"connection.established\",\n} as const;\n\n/**\n * HTTP events on the wire. `UPLOAD_PROGRESS` (host → mini app) is how the\n * host reports bytes-sent for an in-flight upload; `HttpSdkModule` mirrors\n * it onto `HttpUploadOptions.onProgress`, and mini apps can also subscribe\n * directly with `sdk.on(\"http.uploadProgress\", …)`.\n */\nexport const HTTP_EVENTS = {\n  UPLOAD_PROGRESS: \"http.uploadProgress\",\n} as const;\n\n/**\n * Notification events on the wire (host → mini app): `TOKEN` delivers the\n * device push token once the host has it, `OPENED` fires when the user taps\n * a push notification and the host resolves it into the mini app. Mini apps\n * subscribe via `sdk.notifications.onToken` / `sdk.notifications.onOpen`, or\n * directly with `sdk.on(\"notifications.token\", …)`.\n */\nexport const NOTIFICATIONS_EVENTS = {\n  TOKEN: \"notifications.token\",\n  OPENED: \"notifications.opened\",\n} as const;\n\n/**\n * Deep-link events on the wire (host → mini app): `OPENED` fires when the\n * host resolves an incoming deep link into the mini app. Subscribe via\n * `sdk.links.onOpen` or `sdk.on(\"links.opened\", …)`.\n */\nexport const LINKS_EVENTS = {\n  OPENED: \"links.opened\",\n} as const;\n","/**\n * The protocol/wire version this SDK build speaks.\n * Bumped whenever the shape of `PlatformMessage` changes in a\n * backward-incompatible way. Phase 1 stamps every message with this value\n * but does not yet negotiate it against the host (see Phase 2).\n */\nexport const PROTOCOL_VERSION = \"1.0.0\";\n\n/**\n * Value written to `PlatformMessage.channel`. Used by hosts to distinguish\n * SDK protocol messages from unrelated `postMessage` traffic on the same\n * window.\n */\nexport const MESSAGE_CHANNEL = \"gov-platform-sdk\";\n\n/**\n * Name of the `CustomEvent` a host may dispatch as a secondary inbound\n * channel (used by non-`postMessage` hosts, e.g. a Flutter WebView bridge\n * that cannot easily synthesize a `MessageEvent`).\n */\nexport const PLATFORM_EVENT_NAME = \"gov-platform-event\";\n\n/**\n * The logical identity of the host application on the other end of the\n * transport. Every outbound request/handshake message is addressed to this\n * target.\n */\nexport const HOST_TARGET = \"shell\";\n\n/**\n * Wildcard target: a host broadcasting to every connected mini app uses this\n * value instead of a specific `miniAppId`.\n */\nexport const BROADCAST_TARGET = \"*\";\n\n/**\n * Global key the shell sets before mounting a mini-app with the static host\n * descriptor (type, version, capabilities, sdkVersion). The SDK reads this\n * at construction time. See `HostDescriptor` in `types/platform.types.ts`.\n */\nexport const HOST_DESCRIPTOR_GLOBAL_KEY = \"__GSA_HOST_DESCRIPTOR__\";\n\n/**\n * The single well-known global for the SDK. Before the CDN `<script>` tag\n * runs, the host shell sets it to the config (a `MiniAppSdkOptions` object)\n * the CDN build reads at load. The SDK then overwrites it with the live\n * instance, giving the shell a reference to `window.__GSA_SDK__` for\n * one-mini-app-per-tab scenarios. The instance is deleted on `destroy()`.\n */\nexport const SDK_GLOBAL_KEY = \"__GSA_SDK__\";\n","/**\n * Exhaustive union of machine-readable error codes the SDK itself can\n * raise. Host-originated errors (returned inside a `response` message's\n * `error.code`) are host-defined strings and are preserved as-is on\n * `ProtocolError`/`SdkError.code` even if they don't appear in this union —\n * this union only constrains codes the SDK *generates*.\n */\nexport type SdkErrorCode =\n  | \"TIMEOUT\"\n  | \"TRANSPORT_NOT_STARTED\"\n  | \"TRANSPORT_SEND_FAILED\"\n  | \"HANDSHAKE_FAILED\"\n  | \"HANDSHAKE_TIMEOUT\"\n  | \"INVALID_MESSAGE\"\n  | \"SDK_NOT_INITIALIZED\"\n  | \"SDK_ALREADY_DESTROYED\"\n  | \"REQUEST_CANCELLED\"\n  | \"STREAM_CANCELLED\"\n  | \"HTTP_CLIENT_ERROR\"\n  | \"HTTP_SERVER_ERROR\"\n  | \"HOST_ERROR\";\n\nexport interface SdkErrorOptions {\n  code: SdkErrorCode | (string & {});\n  message: string;\n  retryable?: boolean;\n  details?: Record<string, unknown>;\n  cause?: unknown;\n}\n\n/**\n * Root of the SDK's error hierarchy. Every error the SDK throws is an\n * instance of `SdkError` (or one of its subclasses below), so consumers can\n * reliably `catch (err) { if (err instanceof SdkError) ... }` instead of\n * pattern-matching on message strings.\n */\nexport class SdkError extends Error {\n  readonly code: string;\n  readonly retryable: boolean;\n  readonly details: Record<string, unknown> | undefined;\n  readonly cause: unknown;\n\n  constructor(options: SdkErrorOptions) {\n    super(options.message);\n    this.name = \"SdkError\";\n    this.code = options.code;\n    this.retryable = options.retryable ?? false;\n    this.details = options.details;\n    this.cause = options.cause;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { SdkError } from \"./sdk-error\";\n\n/**\n * Raised when the initial handshake with the host fails or times out.\n * Kept distinct from `TimeoutError`/`ProtocolError` because a failed\n * handshake is a fatal condition for the whole SDK instance (nothing can\n * proceed), whereas a single request timing out is typically recoverable.\n */\nexport class HandshakeError extends SdkError {\n  constructor(params: {\n    message: string;\n    cause?: unknown;\n    timedOut?: boolean;\n  }) {\n    super({\n      code: params.timedOut ? \"HANDSHAKE_TIMEOUT\" : \"HANDSHAKE_FAILED\",\n      message: params.message,\n      retryable: false,\n      cause: params.cause,\n    });\n    this.name = \"HandshakeError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { SdkError } from \"./sdk-error\";\n\n/**\n * Raised when an HTTP request resolves but the host's response carries a 4xx\n * status. Distinct from `HttpServerError` so consumers can branch on the kind\n * of failure: 4xx is never retryable — the request itself was rejected, and\n * retrying it would only fail again.\n */\nexport class HttpClientError extends SdkError {\n  /** The HTTP status code the host reported (e.g. 404, 422). */\n  readonly status: number;\n\n  constructor(params: {\n    status: number;\n    message?: string;\n    details?: Record<string, unknown>;\n  }) {\n    super({\n      code: \"HTTP_CLIENT_ERROR\",\n      message:\n        params.message ??\n        `HTTP request failed with client error status ${params.status}`,\n      retryable: false,\n      details: params.details,\n    });\n    this.name = \"HttpClientError\";\n    this.status = params.status;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { SdkError } from \"./sdk-error\";\n\n/**\n * Raised when an HTTP request resolves but the host's response carries a 5xx\n * status. Marked `retryable: true` so the request participates in the RPC\n * retry machinery — a transient upstream failure is exactly the case the\n * backoff/retry policy was built for.\n */\nexport class HttpServerError extends SdkError {\n  /** The HTTP status code the host reported (e.g. 500, 502, 503). */\n  readonly status: number;\n\n  constructor(params: {\n    status: number;\n    message?: string;\n    details?: Record<string, unknown>;\n  }) {\n    super({\n      code: \"HTTP_SERVER_ERROR\",\n      message:\n        params.message ??\n        `HTTP request failed with server error status ${params.status}`,\n      retryable: true,\n      details: params.details,\n    });\n    this.name = \"HttpServerError\";\n    this.status = params.status;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import type { PlatformError } from \"../protocol\";\nimport { SdkError } from \"./sdk-error\";\n\n/**\n * Raised in two situations:\n *  1. An incoming message from the host fails runtime validation (malformed\n *     envelope, wrong protocol version, missing required fields).\n *  2. The host explicitly returned a `PlatformError` inside a `response`\n *     message — i.e. the request reached the host and the host rejected it.\n *\n * Distinguishing (1) from (2) matters for debugging: (1) means \"we don't\n * trust what we received\", (2) means \"the host understood us and said no\".\n * Use the `reason` field to tell them apart.\n */\nexport class ProtocolError extends SdkError {\n  readonly reason: \"malformed-message\" | \"host-rejected\";\n\n  constructor(params: {\n    reason: \"malformed-message\" | \"host-rejected\";\n    platformError?: PlatformError;\n    message?: string;\n  }) {\n    const platformError = params.platformError;\n    super({\n      code: platformError?.code ?? \"INVALID_MESSAGE\",\n      message:\n        params.message ??\n        platformError?.message ??\n        \"Received an invalid protocol message\",\n      retryable: platformError?.retryable ?? false,\n      details: platformError?.details,\n    });\n    this.name = \"ProtocolError\";\n    this.reason = params.reason;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { SdkError } from \"./sdk-error\";\n\nexport interface RequestCancelledErrorOptions {\n  namespace: string;\n  action: string;\n  cause?: unknown;\n}\n\n/**\n * Raised when a caller aborts an in-flight request via its `AbortSignal`\n * before the host answers. Never retryable: a cancellation is the caller's\n * explicit choice, not a transient failure.\n */\nexport class RequestCancelledError extends SdkError {\n  readonly namespace: string;\n  readonly action: string;\n\n  constructor(options: RequestCancelledErrorOptions) {\n    super({\n      code: \"REQUEST_CANCELLED\",\n      message: `Request \"${options.namespace}.${options.action}\" was cancelled`,\n      retryable: false,\n      cause: options.cause,\n    });\n    this.name = \"RequestCancelledError\";\n    this.namespace = options.namespace;\n    this.action = options.action;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { SdkError } from \"./sdk-error\";\n\n/**\n * Raised when a streamed response is cancelled before it completes — either\n * explicitly via `StreamBuilder.cancel()` or because the mini app aborted the\n * owning `AbortSignal`. Never retryable: a cancellation is the caller's\n * explicit choice, not a transient failure.\n */\nexport class StreamCancelledError extends SdkError {\n  constructor(message = \"Stream was cancelled\") {\n    super({\n      code: \"STREAM_CANCELLED\",\n      message,\n      retryable: false,\n    });\n    this.name = \"StreamCancelledError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import { SdkError } from \"./sdk-error\";\n\n/**\n * Raised when a request (or the handshake) does not receive a matching\n * response within the configured timeout. Timeouts are retryable by\n * default, since the most common cause is a transient host delay rather\n * than a permanent failure.\n */\nexport class TimeoutError extends SdkError {\n  constructor(params: {\n    namespace: string;\n    action: string;\n    timeoutMs: number;\n  }) {\n    super({\n      code: \"TIMEOUT\",\n      message: `Request \"${params.namespace}.${params.action}\" timed out after ${params.timeoutMs}ms`,\n      retryable: true,\n      details: {\n        namespace: params.namespace,\n        action: params.action,\n        timeoutMs: params.timeoutMs,\n      },\n    });\n    this.name = \"TimeoutError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import type { SdkErrorOptions } from \"./sdk-error\";\nimport { SdkError } from \"./sdk-error\";\n\n/**\n * Raised when the underlying `Transport` implementation fails to start,\n * send, or otherwise operate — as opposed to a failure at the RPC/protocol\n * layer above it. A `TransportError` means the pipe itself is broken.\n */\nexport class TransportError extends SdkError {\n  constructor(\n    options: Omit<SdkErrorOptions, \"code\"> & { code?: SdkErrorOptions[\"code\"] },\n  ) {\n    super({ ...options, code: options.code ?? \"TRANSPORT_SEND_FAILED\" });\n    this.name = \"TransportError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n","import type { Logger } from \"./logger\";\n\nexport interface ConsoleLoggerOptions {\n  /** Minimum level that actually gets written. Anything below this is dropped. Defaults to 'info'. */\n  minLevel?: \"debug\" | \"info\" | \"warn\" | \"error\";\n  /** Prefix prepended to every message, useful for telling multiple SDK instances apart in one console. Defaults to '[MiniAppSdk]'. */\n  prefix?: string;\n  /**\n   * Masks sensitive fields in `context` before a line is written. Either a\n   * `Set<string>` of top-level keys to redact unconditionally, or a\n   * predicate `(key, value) => boolean` for finer control. Redacted values\n   * are written as `\"[REDACTED]\"`. Applies to top-level context keys only —\n   * it is a fast safety net, not a full PII scrubber (nested objects are\n   * not walked).\n   */\n  redact?: Set<string> | ((key: string, value: unknown) => boolean);\n}\n\nconst LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 } as const;\nconst REDACTED_MARKER = \"[REDACTED]\";\n\n/**\n * The SDK's ready-to-use `Logger` implementation. Not wired in by default —\n * `MiniAppSdk` still defaults to `NoopLogger` so logging stays opt-in — but\n * this is what a mini app or host passes in when it wants to actually see\n * what the SDK is doing:\n *\n * ```ts\n * const sdk = new MiniAppSdk({ miniAppId: 'x' }, {\n *   logger: new ConsoleLogger({ minLevel: 'debug', redact: new Set(['token']) }),\n * });\n * ```\n */\nexport class ConsoleLogger implements Logger {\n  private readonly minLevel: \"debug\" | \"info\" | \"warn\" | \"error\";\n  private readonly prefix: string;\n  private readonly redact: ConsoleLoggerOptions[\"redact\"];\n\n  constructor(options: ConsoleLoggerOptions = {}) {\n    this.minLevel = options.minLevel ?? \"info\";\n    this.prefix = options.prefix ?? \"[MiniAppSdk]\";\n    this.redact = options.redact;\n  }\n\n  debug(message: string, context?: Record<string, unknown>): void {\n    this.write(\"debug\", message, context);\n  }\n\n  info(message: string, context?: Record<string, unknown>): void {\n    this.write(\"info\", message, context);\n  }\n\n  warn(message: string, context?: Record<string, unknown>): void {\n    this.write(\"warn\", message, context);\n  }\n\n  error(message: string, context?: Record<string, unknown>): void {\n    this.write(\"error\", message, context);\n  }\n\n  private write(\n    level: \"debug\" | \"info\" | \"warn\" | \"error\",\n    message: string,\n    context?: Record<string, unknown>,\n  ): void {\n    if (LEVEL_ORDER[level] < LEVEL_ORDER[this.minLevel]) return;\n\n    const line = `${this.prefix} ${message}`;\n    const redacted = this.maybeRedact(context);\n    switch (level) {\n      case \"debug\":\n        console.debug(line, redacted ?? \"\");\n        break;\n      case \"info\":\n        console.info(line, redacted ?? \"\");\n        break;\n      case \"warn\":\n        console.warn(line, redacted ?? \"\");\n        break;\n      case \"error\":\n        console.error(line, redacted ?? \"\");\n        break;\n    }\n  }\n\n  private maybeRedact(\n    context?: Record<string, unknown>,\n  ): Record<string, unknown> | undefined {\n    if (!context || !this.redact) return context;\n\n    const redact = this.redact;\n    const isKeyRedacted = (key: string, value: unknown): boolean =>\n      typeof redact === \"function\" ? redact(key, value) : redact.has(key);\n\n    const masked: Record<string, unknown> = {};\n    let changed = false;\n    for (const [key, value] of Object.entries(context)) {\n      if (isKeyRedacted(key, value)) {\n        masked[key] = REDACTED_MARKER;\n        changed = true;\n      } else {\n        masked[key] = value;\n      }\n    }\n    // Avoid allocating a throwaway object when nothing needed masking.\n    return changed ? masked : context;\n  }\n}\n","import type { Logger } from \"./logger\";\n\n/**\n * A `Logger` that discards everything. This is the SDK's default logger so\n * that omitting a logger has zero behavioral or performance cost — consumers\n * only pay for logging if they opt in by injecting a real implementation.\n */\nexport class NoopLogger implements Logger {\n  debug(): void {\n    // intentionally empty\n  }\n\n  info(): void {\n    // intentionally empty\n  }\n\n  warn(): void {\n    // intentionally empty\n  }\n\n  error(): void {\n    // intentionally empty\n  }\n}\n\n/** Shared singleton instance — stateless, safe to reuse everywhere. */\nexport const noopLogger: Logger = new NoopLogger();\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type {\n  ApiRequestParams,\n  ApiResult,\n  ApiSdkModule,\n  HttpMethod,\n} from \"../types\";\n\nexport function createApiModule(rpc: RpcClient): ApiSdkModule {\n  return {\n    request: <T = unknown, B = unknown>(params?: ApiRequestParams<B>) => {\n      const method: HttpMethod = params?.method ?? \"POST\";\n      const body = params?.body;\n      const headers = params?.headers;\n      return rpc.request<ApiResult<T>>(NAMESPACES.API, ACTIONS.API.REQUEST, {\n        method,\n        ...(body !== undefined && { body }),\n        ...(headers !== undefined && { headers }),\n      });\n    },\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type {\n  AppearanceSdkModule,\n  AppearanceState,\n  Direction,\n  LocaleState,\n  ThemeMode,\n  ThemePreference,\n  ThemeState,\n} from \"../types\";\nimport type { AppearanceType } from \"../types/common.types\";\n\nconst DEFAULT_STATE: AppearanceState = {\n  locale: { locale: \"en\", language: \"en\", direction: \"ltr\" },\n  theme: { preference: \"system\", mode: \"light\" },\n};\n\n/** Language subtags written right-to-left, used to derive `direction` from a bare locale string. */\nconst RTL_LANGUAGES = new Set([\n  \"ar\",\n  \"he\",\n  \"fa\",\n  \"ur\",\n  \"ps\",\n  \"sd\",\n  \"ug\",\n  \"yi\",\n  \"dv\",\n  \"ku\",\n  \"nqo\",\n]);\n\n/**\n * Resolves `system` into a concrete mode. The Flutter shell sends only a\n * preference, so `system` has to be resolved on this side; `matchMedia` is\n * absent in the WebView tests and in SSR, hence the fallback.\n */\nfunction resolveSystemMode(fallback: ThemeMode): ThemeMode {\n  if (\n    typeof window !== \"undefined\" &&\n    typeof window.matchMedia === \"function\"\n  ) {\n    try {\n      return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n        ? \"dark\"\n        : \"light\";\n    } catch {\n      return fallback;\n    }\n  }\n  return fallback;\n}\n\n/** Expands a locale tag (`en`, `en-LK`, `ar_SA`) into a full `LocaleState`. */\nfunction localeFromTag(tag: string): LocaleState | null {\n  const normalized = tag.trim().replace(/_/g, \"-\");\n  if (!normalized) return null;\n\n  const [languageRaw = \"\", regionRaw] = normalized.split(\"-\");\n  const language = languageRaw.toLowerCase();\n  if (!language) return null;\n\n  const region = regionRaw ? regionRaw.toUpperCase() : undefined;\n  const locale: LocaleState = {\n    locale: region ? `${language}-${region}` : language,\n    language,\n    direction: RTL_LANGUAGES.has(language) ? \"rtl\" : \"ltr\",\n  };\n  if (region) locale.region = region;\n  return locale;\n}\n\n/**\n * Coerces whatever a host sent for \"locale\" into a full `LocaleState`.\n *\n * Accepts the bare tag the Flutter shell sends (`\"en-LK\"`), the structured\n * state the web shell's `appearance` namespace returns, and the\n * `{ locale: … }` wrapper an event payload may arrive in. Returns `null` for\n * anything unusable so the caller can leave the store untouched rather than\n * overwrite good state with garbage.\n *\n * Fields the host supplied always win: `direction` is only derived from the\n * language subtag when the host didn't say.\n */\nexport function normalizeLocale(input: unknown): LocaleState | null {\n  if (typeof input === \"string\") return localeFromTag(input);\n  if (!input || typeof input !== \"object\") return null;\n\n  const candidate = input as Partial<LocaleState> & { locale?: unknown };\n\n  // `LocaleState.locale` is a string; an object there means a `{ locale: … }`\n  // wrapper, so unwrap one level and re-enter.\n  if (candidate.locale && typeof candidate.locale === \"object\") {\n    return normalizeLocale(candidate.locale);\n  }\n\n  const tag =\n    typeof candidate.locale === \"string\" && candidate.locale\n      ? candidate.locale\n      : candidate.language;\n  if (typeof tag !== \"string\") return null;\n\n  const derived = localeFromTag(tag);\n  if (!derived) return null;\n\n  const language = candidate.language ?? derived.language;\n  const region = candidate.region ?? derived.region;\n  const direction: Direction =\n    candidate.direction === \"rtl\" || candidate.direction === \"ltr\"\n      ? candidate.direction\n      : derived.direction;\n\n  const locale: LocaleState = { locale: derived.locale, language, direction };\n  if (region) locale.region = region;\n  return locale;\n}\n\n/**\n * Coerces whatever a host sent for \"theme\" into a full `ThemeState`.\n *\n * Accepts the bare preference the Flutter shell sends (`\"dark\"`), the\n * `{ preference, mode }` state the web shell returns, and the\n * `{ theme: … }` wrapper an event payload may arrive in. `system` is\n * resolved to a concrete mode when the host didn't already resolve it.\n * Returns `null` for anything unusable.\n */\nexport function normalizeTheme(\n  input: unknown,\n  fallbackMode: ThemeMode = \"light\",\n): ThemeState | null {\n  if (typeof input === \"string\") {\n    const value = input.trim().toLowerCase();\n    if (value !== \"dark\" && value !== \"light\" && value !== \"system\")\n      return null;\n    const preference = value as ThemePreference;\n    return {\n      preference,\n      mode:\n        preference === \"system\" ? resolveSystemMode(fallbackMode) : preference,\n    };\n  }\n\n  if (!input || typeof input !== \"object\") return null;\n  const candidate = input as Partial<ThemeState> & { theme?: unknown };\n\n  // A `{ theme: … }` wrapper — `ThemeState` itself has no `theme` field.\n  if (candidate.theme !== undefined && candidate.preference === undefined) {\n    return normalizeTheme(candidate.theme, fallbackMode);\n  }\n\n  const base = normalizeTheme(candidate.preference, fallbackMode);\n  if (!base) return null;\n\n  // A host-resolved mode is authoritative — only fall back to our own\n  // resolution when it didn't send one.\n  const mode: ThemeMode =\n    candidate.mode === \"dark\" || candidate.mode === \"light\"\n      ? candidate.mode\n      : base.mode;\n  return { preference: base.preference, mode };\n}\n\n/** Event names published by the host (mirror of host `PLATFORM_EVENTS`). */\nexport const APPEARANCE_EVENTS = {\n  LOCALE_CHANGED: \"appearance.locale.changed\",\n  THEME_CHANGED: \"appearance.theme.changed\",\n} as const;\n\n/**\n * Internal handle returned alongside the public `AppearanceSdkModule` so the\n * composition root (`MiniAppSdk`) can push host-published `appearance.*`\n * events into the store.\n */\nexport interface AppearanceModuleHandle {\n  module: AppearanceSdkModule;\n  setLocale(locale: LocaleState): void;\n  setTheme(theme: ThemeState): void;\n  /**\n   * Seeds the store from the loose `{ theme, locale }` hint a host attaches\n   * to its `platform.getType` reply. This is how the Flutter shell — which\n   * doesn't implement the `appearance` namespace — gets its theme and locale\n   * into `sdk.appearance`, so mini-app code reads the same surface on both\n   * shells.\n   */\n  applyHint(hint: AppearanceType): void;\n}\n\n/**\n * Host-driven locale & theme module. Reads the active locale/theme from the\n * host and keeps a tiny observable store that subscribers (framework hooks)\n * consume. The host is the single source of truth: on `appearance.locale.changed`\n * / `appearance.theme.changed` the SDK updates the store and listeners re-render.\n */\nexport function createAppearanceModule(rpc: RpcClient): AppearanceModuleHandle {\n  let state: AppearanceState = { ...DEFAULT_STATE };\n  const listeners = new Set<(next: AppearanceState) => void>();\n\n  const notify = (): void => {\n    const snapshot: AppearanceState = {\n      locale: { ...state.locale },\n      theme: { ...state.theme },\n    };\n    for (const listener of listeners) {\n      try {\n        listener(snapshot);\n      } catch (error) {\n        // A subscriber must not break the notification loop.\n        // eslint-disable-next-line no-console\n        console.error(\"[appearance] listener error:\", error);\n      }\n    }\n  };\n\n  const setLocale = (locale: LocaleState): void => {\n    const prev = state.locale;\n    if (locale.locale === prev.locale && locale.direction === prev.direction)\n      return;\n    state = { ...state, locale: { ...locale } };\n    notify();\n  };\n\n  const setTheme = (theme: ThemeState): void => {\n    const prev = state.theme;\n    if (theme.preference === prev.preference && theme.mode === prev.mode)\n      return;\n    state = { ...state, theme: { ...theme } };\n    notify();\n  };\n\n  const applyHint = (hint: AppearanceType): void => {\n    if (!hint) return;\n    if (hint.locale !== undefined) {\n      const locale = normalizeLocale(hint.locale);\n      if (locale) setLocale(locale);\n    }\n    if (hint.theme !== undefined) {\n      const theme = normalizeTheme(hint.theme, state.theme.mode);\n      if (theme) setTheme(theme);\n    }\n  };\n\n  const module: AppearanceSdkModule = {\n    async getLocale(): Promise<LocaleState> {\n      // Hosts that deliver appearance via the `platform.getType` hint (the\n      // Flutter shell) don't implement this namespace, so an explicit call\n      // would reject. Serving the store keeps the module's surface identical\n      // on every shell.\n      if (!rpc.getCapabilities().includes(NAMESPACES.APPEARANCE)) {\n        return { ...state.locale };\n      }\n      const raw = await rpc.request<LocaleState>(\n        NAMESPACES.APPEARANCE,\n        ACTIONS.APPEARANCE.GET_LOCALE,\n      );\n      const locale = normalizeLocale(raw) ?? raw;\n      setLocale(locale);\n      return { ...locale };\n    },\n\n    async getTheme(): Promise<ThemeState> {\n      if (!rpc.getCapabilities().includes(NAMESPACES.APPEARANCE)) {\n        return { ...state.theme };\n      }\n      const raw = await rpc.request<ThemeState>(\n        NAMESPACES.APPEARANCE,\n        ACTIONS.APPEARANCE.GET_THEME,\n      );\n      const theme = normalizeTheme(raw, state.theme.mode) ?? raw;\n      setTheme(theme);\n      return { ...theme };\n    },\n\n    state(): AppearanceState {\n      return {\n        locale: { ...state.locale },\n        theme: { ...state.theme },\n      };\n    },\n\n    subscribe(listener: (next: AppearanceState) => void): () => void {\n      listeners.add(listener);\n      return () => listeners.delete(listener);\n    },\n  };\n\n  return { module, setLocale, setTheme, applyHint };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type { AuthSdkModule, PlatformUser } from \"../types\";\n\n/**\n * Every module in this directory follows the same shape: a factory function\n * that takes an `RpcClient` and returns an object satisfying the module's\n * public interface. Modules never touch `Transport` directly and never hold\n * their own state — all correlation, retry, and timeout handling lives in\n * `RpcClient`. That keeps each module small, easy to test in isolation, and\n * easy to replace or extend independently of the others.\n */\nexport function createAuthModule(rpc: RpcClient): AuthSdkModule {\n  return {\n    getUser: () =>\n      rpc.request<PlatformUser | null>(NAMESPACES.AUTH, ACTIONS.AUTH.GET_USER),\n    isAuthenticated: () =>\n      rpc.request<boolean>(NAMESPACES.AUTH, ACTIONS.AUTH.IS_AUTHENTICATED),\n    logout: () => rpc.request<void>(NAMESPACES.AUTH, ACTIONS.AUTH.LOGOUT),\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type { ChatMessage, ChatRequestOptions, ChatSdkModule } from \"../types\";\n\n/**\n * Small helpers for assembling a `ChatMessage[]` without hand-writing\n * literals. Only the roles the wire protocol supports (`user`, `system`) are\n * offered — assistant turns come back from the host model's stream, not from\n * a mini app assembling its own history.\n */\nexport const ChatMessages = {\n  user(content: string): ChatMessage {\n    return { role: \"user\", content };\n  },\n  system(content: string): ChatMessage {\n    return { role: \"system\", content };\n  },\n} as const;\n\n/**\n * The AI/chat module. Streams a model completion from the host over the\n * `ai.chat` namespace. The host answers with a sequence of `stream`\n * messages rather than a single response, so this routes through\n * `rpc.sendStreamRequest` and hands the caller a `StreamBuilder` to\n * consume the chunks from. Cancellation is supported two ways: an\n * `AbortSignal` in `requestOptions`, or `builder.cancel()` on the returned\n * builder — both notify the host to stop producing.\n */\nexport function createChatModule(rpc: RpcClient): ChatSdkModule {\n  return {\n    chat(messages, options, requestOptions?: ChatRequestOptions) {\n      return rpc.sendStreamRequest(\n        NAMESPACES.HTTP,\n        ACTIONS.HTTP.STREAM,\n        { messages, options },\n        requestOptions,\n      );\n    },\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type { ConfigSdkModule } from \"../types\";\n\nexport function createConfigModule(rpc: RpcClient): ConfigSdkModule {\n  return {\n    get: <T = unknown>(key: string) =>\n      rpc.request<T | undefined>(NAMESPACES.CONFIG, ACTIONS.CONFIG.GET, {\n        key,\n      }),\n    getAll: () =>\n      rpc.request<Record<string, unknown>>(\n        NAMESPACES.CONFIG,\n        ACTIONS.CONFIG.GET_ALL,\n      ),\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type {\n  DeviceAction,\n  DeviceBiometricOptions,\n  DeviceBiometricResult,\n  DeviceCameraResult,\n  DeviceContactResult,\n  DeviceDownloadOptions,\n  DeviceDownloadResult,\n  DeviceExtraOptions,\n  DeviceFileOptions,\n  DeviceFileResult,\n  DeviceGalleryResult,\n  DeviceInfoResult,\n  DeviceLocationResult,\n  DeviceNetworkResult,\n  DeviceNotificationResult,\n  DeviceNotificationsOptions,\n  DevicePermissionBaseResponse,\n  DeviceSdkModuleWithGuards,\n} from \"../types\";\n\n/** Every action the device module can feature-detect. */\nconst DEVICE_ACTIONS: readonly DeviceAction[] = [\n  \"location\",\n  \"camera\",\n  \"gallery\",\n  \"files\",\n  \"download\",\n  \"contact\",\n  \"biometric\",\n  \"notifications\",\n  \"network\",\n  \"info\",\n];\n\nexport function createDeviceModule(rpc: RpcClient): DeviceSdkModuleWithGuards {\n  return {\n    isSupported: (action: DeviceAction): boolean =>\n      DEVICE_ACTIONS.includes(action) &&\n      rpc.getCapabilities().includes(NAMESPACES.DEVICE),\n\n    location: (options?: DeviceExtraOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceLocationResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.LOCATION,\n        options,\n      ),\n\n    camera: (options?: DeviceExtraOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceCameraResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.CAMERA,\n        options,\n      ),\n\n    gallery: (options?: DeviceFileOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceGalleryResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.GALLERY,\n        options,\n      ),\n\n    files: (options?: DeviceFileOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceFileResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.FILES,\n        options,\n      ),\n\n    download: (options?: DeviceDownloadOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceDownloadResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.DOWNLOAD,\n        options,\n      ),\n\n    contact: (options?: DeviceExtraOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceContactResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.CONTACT,\n        options,\n      ),\n\n    biometric: (options?: DeviceBiometricOptions) =>\n      rpc.request<DevicePermissionBaseResponse<DeviceBiometricResult>>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.BIOMETRIC,\n        options,\n      ),\n\n    notifications: (options?: DeviceNotificationsOptions) =>\n      rpc.request<DeviceNotificationResult>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.NOTIFICATIONS,\n        options,\n      ),\n\n    network: () =>\n      rpc.request<DeviceNetworkResult>(\n        NAMESPACES.DEVICE,\n        ACTIONS.DEVICE.NETWORK,\n      ),\n\n    info: () =>\n      rpc.request<DeviceInfoResult>(NAMESPACES.DEVICE, ACTIONS.DEVICE.INFO),\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type { FlagsSdkModule } from \"../types\";\n\nexport function createFlagsModule(rpc: RpcClient): FlagsSdkModule {\n  return {\n    isEnabled: (flag: string) =>\n      rpc.request<boolean>(NAMESPACES.FLAGS, ACTIONS.FLAGS.IS_ENABLED, {\n        flag,\n      }),\n    getAll: () =>\n      rpc.request<Record<string, boolean>>(\n        NAMESPACES.FLAGS,\n        ACTIONS.FLAGS.GET_ALL,\n      ),\n  };\n}\n","import type {\n  ChatMessage,\n  ChatRequestOptions,\n  HttpDeleteParams,\n  HttpGetParams,\n  HttpPatchParams,\n  HttpPostParams,\n  HttpProgress,\n  HttpPutParams,\n  HttpResult,\n  HttpSdkModule,\n  HttpUploadOptions,\n  ModelCompletionOptions,\n} from \"@lizuz/mini-app-types\";\nimport { ACTIONS, HTTP_EVENTS, NAMESPACES } from \"../constants\";\nimport { HttpClientError, HttpServerError } from \"../errors\";\nimport type { RpcClient } from \"../rpc\";\n\n/**\n * Shared response mapper for every non-streaming verb: turns an `HttpResult`\n * whose `status` is an error into a typed `SdkError` subclass *inside* the\n * retry loop (via `RpcRequestOptions.mapPayload`), so a 5xx is retried with\n * the normal backoff policy and a 4xx fails fast. A successful status\n * (< 400) passes the result through untouched.\n */\nfunction mapHttpResult(result: unknown): HttpResult {\n  const httpResult = result as HttpResult;\n  if (typeof httpResult?.status !== \"number\") {\n    return httpResult;\n  }\n  if (httpResult.status >= 500) {\n    throw new HttpServerError({ status: httpResult.status });\n  }\n  if (httpResult.status >= 400) {\n    throw new HttpClientError({ status: httpResult.status });\n  }\n  return httpResult;\n}\n\n/**\n * Runs one upload-carrying request with optional progress mirroring: when\n * `options.onProgress` is set, subscribes to the host's `http.uploadProgress`\n * event for the duration of the request and forwards payloads to the\n * callback, then unsubscribes once the request settles.\n */\nasync function runUpload<T, B>(\n  rpc: RpcClient,\n  namespace: string,\n  action: string,\n  params: HttpPostParams<B>,\n  options?: HttpUploadOptions,\n): Promise<HttpResult<T>> {\n  const unsubscribe = options?.onProgress\n    ? rpc.onEvent<HttpProgress>(HTTP_EVENTS.UPLOAD_PROGRESS, (progress) => {\n        options.onProgress?.(progress);\n      })\n    : undefined;\n  try {\n    return await rpc.request<HttpResult<T>>(namespace, action, params, {\n      mapPayload: mapHttpResult,\n    });\n  } finally {\n    unsubscribe?.();\n  }\n}\n\nexport function createHttpModule(rpc: RpcClient): HttpSdkModule {\n  return {\n    get: <T = unknown>(params: HttpGetParams) =>\n      rpc.request<HttpResult<T>>(NAMESPACES.HTTP, ACTIONS.HTTP.GET, params, {\n        mapPayload: mapHttpResult,\n      }),\n\n    post: <T = unknown, B = unknown>(\n      params: HttpPostParams<B>,\n      options?: HttpUploadOptions,\n    ) =>\n      runUpload<T, B>(rpc, NAMESPACES.HTTP, ACTIONS.HTTP.POST, params, options),\n\n    put: <T = unknown, B = unknown>(\n      params: HttpPutParams<B>,\n      options?: HttpUploadOptions,\n    ) =>\n      runUpload<T, B>(rpc, NAMESPACES.HTTP, ACTIONS.HTTP.PUT, params, options),\n\n    patch: <T = unknown, B = unknown>(\n      params: HttpPatchParams<B>,\n      options?: HttpUploadOptions,\n    ) =>\n      runUpload<T, B>(\n        rpc,\n        NAMESPACES.HTTP,\n        ACTIONS.HTTP.PATCH,\n        params,\n        options,\n      ),\n\n    delete: <T = unknown>(params: HttpDeleteParams) =>\n      rpc.request<HttpResult<T>>(NAMESPACES.HTTP, ACTIONS.HTTP.DELETE, params, {\n        mapPayload: mapHttpResult,\n      }),\n\n    getStream: <T = unknown>(params: HttpGetParams) =>\n      rpc.sendStreamRequest(\n        NAMESPACES.HTTP,\n        ACTIONS.HTTP.GET_STREAM,\n        params,\n      ) as Promise<T>,\n    stream: <T = unknown>(params: {\n      messages: ChatMessage[];\n      options?: ModelCompletionOptions;\n      requestOptions?: ChatRequestOptions;\n    }) =>\n      rpc.sendStreamRequest(\n        NAMESPACES.HTTP,\n        ACTIONS.HTTP.STREAM,\n        params,\n      ) as Promise<T>,\n  };\n}\n","import { ACTIONS, LINKS_EVENTS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type {\n  LinksOpenedEvent,\n  LinksOpenOptions,\n  LinksSdkModule,\n} from \"../types\";\n\nexport function createLinksModule(rpc: RpcClient): LinksSdkModule {\n  return {\n    isSupported: rpc.getCapabilities().includes(NAMESPACES.LINKS),\n    open: (url: string, options?: LinksOpenOptions) =>\n      rpc.request<void>(NAMESPACES.LINKS, ACTIONS.LINKS.OPEN, {\n        url,\n        ...options,\n      }),\n    onOpen: (handler) =>\n      rpc.onEvent<LinksOpenedEvent>(LINKS_EVENTS.OPENED, handler),\n  };\n}\n","import type { RpcClient } from \"../rpc\";\n\nexport type ModuleFactory<T = unknown> = (rpc: RpcClient) => T;\n\n/**\n * Holds a set of `(rpc) => module` factories and, once built, the module\n * instances they produced. `MiniAppSdk` uses this internally to construct\n * its nine built-in modules — each one is `register()`ed by name instead of\n * being new'd inline in the composition root's constructor — and the same\n * registry is what backs `sdk.registerModule()` / `sdk.getModule()`, so a\n * host or vendor can add a module the SDK doesn't ship without forking\n * anything.\n *\n * A registry only ever builds a given name once: `build()` iterates every\n * factory that hasn't produced an instance yet, so registering a new\n * module after `initialize()` and calling `build()` again only constructs\n * the new one, leaving already-built modules untouched.\n */\nexport class ModuleRegistry {\n  private readonly factories = new Map<string, ModuleFactory>();\n  private readonly instances = new Map<string, unknown>();\n\n  /**\n   * Registers a factory under `name`. Registering a second factory under a\n   * name that's already been built has no effect on the existing instance —\n   * call `get()` to check first if that matters for your use case.\n   */\n  register<T>(name: string, factory: ModuleFactory<T>): void {\n    this.factories.set(name, factory as ModuleFactory);\n  }\n\n  has(name: string): boolean {\n    return this.factories.has(name);\n  }\n\n  /** Instantiates every registered factory that hasn't been built yet. */\n  build(rpc: RpcClient): void {\n    for (const [name, factory] of this.factories) {\n      if (!this.instances.has(name)) {\n        this.instances.set(name, factory(rpc));\n      }\n    }\n  }\n\n  get<T>(name: string): T | undefined {\n    return this.instances.get(name) as T | undefined;\n  }\n\n  /** Names of every module that has been built so far. */\n  list(): string[] {\n    return [...this.instances.keys()];\n  }\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type {\n  NavigationRouterResult,\n  NavigationRouterSdkModule,\n  NavigationSdkModule,\n  NavigationState,\n  NavigationTarget,\n} from \"../types\";\n\n/**\n * Coerces the host's reply into a `NavigationRouterResult`.\n *\n * Hosts answer this call in one of three shapes: the full\n * `{ consumed }` object, a bare boolean, or nothing at all (a shell that\n * treats `back`/`push` as fire-and-forget and just acknowledges the\n * request). Falling back to the flag the caller sent keeps the promise\n * resolving to a usable object on every shell, so mini-app code can read\n * `result.consumed` unconditionally instead of guarding for `undefined`.\n */\nfunction toRouterResult(\n  raw: unknown,\n  requested: boolean,\n): NavigationRouterResult {\n  if (typeof raw === \"boolean\") return { consumed: raw };\n  if (raw && typeof raw === \"object\") {\n    const { consumed } = raw as Partial<NavigationRouterResult>;\n    if (typeof consumed === \"boolean\") return { consumed };\n  }\n  return { consumed: requested };\n}\n\n/**\n * The mini app's own router, mirrored to the host.\n *\n * `navigate()` asks the host to move *the platform* somewhere; these two\n * instead report a move the mini app is making *inside itself*, and the\n * boolean is the whole point of them. On `navigation.back.requested` the\n * host is holding the native back press, waiting to hear whether the mini\n * app handled it:\n *\n * ```ts\n * sdk.on(NAVIGATION_EVENTS.BACK_REQUESTED, async () => {\n *   const { history } = await sdk.navigation.getCurrent();\n *   // true  -> mini app popped a route, host keeps the container open\n *   // false -> mini app is at its root, host exits the container\n *   await sdk.navigation.router.back(history.length > 1);\n * });\n * ```\n */\nfunction createNavigationRouter(rpc: RpcClient): NavigationRouterSdkModule {\n  return {\n    /**\n     * Reports a back step. Pass `false` when the mini app has no history\n     * left, which hands the back press back to the host.\n     */\n    async back(consumed = true): Promise<NavigationRouterResult> {\n      const raw = await rpc.request<unknown>(\n        NAMESPACES.NAVIGATION,\n        ACTIONS.NAVIGATION.BACK,\n        { consumed },\n      );\n      return toRouterResult(raw, consumed);\n    },\n\n    /**\n     * Reports a forward step, so the host learns the mini app now has\n     * history to pop and keeps the container open on the next back press.\n     */\n    async push(consumed = true): Promise<NavigationRouterResult> {\n      const raw = await rpc.request<unknown>(\n        NAMESPACES.NAVIGATION,\n        ACTIONS.NAVIGATION.PUSH,\n        { consumed },\n      );\n      return toRouterResult(raw, consumed);\n    },\n  };\n}\n\nexport function createNavigationModule(rpc: RpcClient): NavigationSdkModule {\n  return {\n    navigate: (target: NavigationTarget) =>\n      rpc.request<void>(\n        NAMESPACES.NAVIGATION,\n        ACTIONS.NAVIGATION.NAVIGATE,\n        target,\n      ),\n    getCurrent: () =>\n      rpc.request<NavigationState>(\n        NAMESPACES.NAVIGATION,\n        ACTIONS.NAVIGATION.GET_CURRENT,\n      ),\n    router: createNavigationRouter(rpc),\n  };\n}\n","import { ACTIONS, NAMESPACES, NOTIFICATIONS_EVENTS } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type {\n  NotificationOpenEvent,\n  NotificationsRegisterOptions,\n  NotificationsRegisterResult,\n  NotificationsSdkModule,\n} from \"../types\";\n\nexport function createNotificationsModule(\n  rpc: RpcClient,\n): NotificationsSdkModule {\n  return {\n    isSupported: () => rpc.getCapabilities().includes(NAMESPACES.NOTIFICATIONS),\n    register: (options?: NotificationsRegisterOptions) =>\n      rpc.request<NotificationsRegisterResult>(\n        NAMESPACES.NOTIFICATIONS,\n        ACTIONS.NOTIFICATIONS.REGISTER,\n        options,\n      ),\n    onToken: (handler) =>\n      rpc.onEvent<string>(NOTIFICATIONS_EVENTS.TOKEN, handler),\n    onOpen: (handler) =>\n      rpc.onEvent<NotificationOpenEvent>(NOTIFICATIONS_EVENTS.OPENED, handler),\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type { PermissionsSdkModule } from \"../types\";\n\nexport function createPermissionsModule(rpc: RpcClient): PermissionsSdkModule {\n  return {\n    has: (permission: string) =>\n      rpc.request<boolean>(NAMESPACES.PERMISSIONS, ACTIONS.PERMISSIONS.HAS, {\n        permission,\n      }),\n    list: () =>\n      rpc.request<string[]>(NAMESPACES.PERMISSIONS, ACTIONS.PERMISSIONS.LIST),\n  };\n}\n","import type {\n  AppearanceType,\n  PlatformTypeLiteral,\n  PlatformTypeResponse,\n} from \"../types/common.types\";\nimport type { PlatformSdkModule } from \"../types/platform.types\";\n\n/** What a `platform.getType` reply resolves to once normalized. */\nexport interface ResolvedPlatformResponse {\n  type: PlatformTypeLiteral;\n  /** `null` when the host sent no appearance hint (e.g. the web shell). */\n  appearance: AppearanceType | null;\n}\n\nexport interface PlatformModuleHandle {\n  /** The public-facing module, satisfying `PlatformSdkModule` exactly — no extra methods. */\n  module: PlatformSdkModule;\n  /**\n   * Internal setter used only by the composition root (`MiniAppSdk`) once\n   * the actual platform type is known (fetched from the host during\n   * `initialize()`). Not part of `PlatformSdkModule`, so it cannot be\n   * called by consumer code even though it closes over the same state.\n   */\n  setType: (type: PlatformTypeLiteral) => void;\n  /**\n   * Applies a raw `platform.getType` reply — bare string or\n   * `PlatformTypeResponse` — and returns the resolved type plus any\n   * appearance hint that rode along with it. The hint is handed back rather\n   * than stored here: appearance state belongs to the appearance module,\n   * this module only relays what the platform handshake happened to carry.\n   */\n  applyResponse: (raw: unknown) => ResolvedPlatformResponse;\n}\n\nconst isPlatformType = (value: unknown): value is PlatformTypeLiteral =>\n  value === \"web\" || value === \"flutter\";\n\n/**\n * Normalizes whatever the host answered `platform.getType` with. The web\n * shell replies with a bare `\"web\"`; the Flutter shell replies with\n * `{ types: 'flutter', appearance: { theme, locale } }` because it has no\n * `appearance` namespace of its own. Anything unrecognized falls back to the\n * current type so a malformed reply can't leave the module in a bogus state.\n */\nexport function normalizePlatformResponse(\n  raw: unknown,\n  fallbackType: PlatformTypeLiteral,\n): ResolvedPlatformResponse {\n  if (isPlatformType(raw)) {\n    return { type: raw, appearance: null };\n  }\n\n  if (raw && typeof raw === \"object\") {\n    const response = raw as PlatformTypeResponse;\n    const candidate = response.type ?? response.types;\n    const appearance = response.appearance;\n    // Either field may arrive as a loose string (`'dark'`, `'si-LK'`) or as a\n    // full `ThemeState`/`LocaleState` object — the appearance module coerces\n    // both, so accept both here rather than only the string form.\n    const isHintValue = (value: unknown): boolean =>\n      typeof value === \"string\" || (!!value && typeof value === \"object\");\n    const hasHint =\n      !!appearance &&\n      typeof appearance === \"object\" &&\n      (isHintValue(appearance.theme) || isHintValue(appearance.locale));\n\n    return {\n      type: isPlatformType(candidate) ? candidate : fallbackType,\n      appearance: hasHint ? { ...appearance } : null,\n    };\n  }\n\n  return { type: fallbackType, appearance: null };\n}\n\n/**\n * `platform` holds one piece of local mutable state — `type` — which isn't\n * known until the host responds during `initialize()`, so it can't be\n * fetched fresh per call like the other modules do. That state lives\n * entirely inside this closure; nothing outside this file can change it\n * except through the `setType`/`applyResponse` handle returned alongside the\n * module.\n */\nexport function createPlatformModule(\n  initialType: PlatformTypeLiteral = \"web\",\n): PlatformModuleHandle {\n  let type: PlatformTypeLiteral = initialType;\n\n  const module: PlatformSdkModule = {\n    get type() {\n      return type;\n    },\n    isWeb: () => type === \"web\",\n    isFlutter: () => type === \"flutter\",\n    isMobile: () => type === \"flutter\",\n  };\n\n  const setType = (newType: PlatformTypeLiteral): void => {\n    type = newType;\n  };\n\n  return {\n    module,\n    setType,\n    applyResponse: (raw: unknown) => {\n      const resolved = normalizePlatformResponse(raw, type);\n      setType(resolved.type);\n      return resolved;\n    },\n  };\n}\n","import { ACTIONS, NAMESPACES } from \"../constants\";\nimport type { RpcClient } from \"../rpc\";\nimport type { StorageSdkModule, StorageSetOptions } from \"../types\";\n\ninterface StorageRpcResult {\n  value: string | null;\n}\n\ninterface StorageRpcSetPayload {\n  key: string;\n  value: string;\n  ttlMs?: number;\n}\n\n/**\n * The storage module. `get`/`set` speak the raw-string wire format exactly as\n * before; `getJson`/`setJson` layer JSON (de)serialization on top of that same\n * wire, and `scoped(prefix)` returns a sub-module that prefixes every key.\n */\nexport function createStorageModule(rpc: RpcClient): StorageSdkModule {\n  const rawGet = (key: string): Promise<string | null> =>\n    rpc\n      .request<StorageRpcResult>(NAMESPACES.STORAGE, ACTIONS.STORAGE.GET, {\n        key,\n      })\n      .then((result) => result?.value ?? null);\n\n  const rawSet = (\n    key: string,\n    value: string,\n    options?: StorageSetOptions,\n  ): Promise<void> => {\n    const payload: StorageRpcSetPayload = { key, value };\n    if (options?.ttlMs !== undefined) payload.ttlMs = options.ttlMs;\n    return rpc.request<void>(NAMESPACES.STORAGE, ACTIONS.STORAGE.SET, payload);\n  };\n\n  const rawRemove = (key: string): Promise<void> =>\n    rpc.request<void>(NAMESPACES.STORAGE, ACTIONS.STORAGE.REMOVE, { key });\n\n  const getJson = async <T = unknown>(key: string): Promise<T | null> => {\n    const raw = await rawGet(key);\n    if (raw === null) return null;\n    try {\n      return JSON.parse(raw) as T;\n    } catch {\n      // The stored string isn't JSON (a raw-string value). Null is the honest\n      // answer — it's indistinguishable from \"unset\" from the caller's view.\n      return null;\n    }\n  };\n\n  const setJson = (\n    key: string,\n    value: unknown,\n    options?: StorageSetOptions,\n  ): Promise<void> => rawSet(key, JSON.stringify(value), options);\n\n  const scoped = (prefix: string): StorageSdkModule => {\n    const prefixKey = (key: string): string => `${prefix}:${key}`;\n    return {\n      get: (key: string) => rawGet(prefixKey(key)),\n      getJson: <T = unknown>(key: string) => getJson<T>(prefixKey(key)),\n      set: (key: string, value: string, options?: StorageSetOptions) =>\n        rawSet(prefixKey(key), value, options),\n      setJson: (key: string, value: unknown, options?: StorageSetOptions) =>\n        setJson(prefixKey(key), value, options),\n      remove: (key: string) => rawRemove(prefixKey(key)),\n      scoped: (nested: string) => scoped(prefixKey(nested)),\n    };\n  };\n\n  return {\n    get: rawGet,\n    getJson,\n    set: rawSet,\n    setJson,\n    remove: rawRemove,\n    scoped,\n  };\n}\n","/**\n * Everything a middleware knows about the request it's wrapping. Deliberately\n * a plain, serializable-ish shape — a middleware shouldn't need to reach\n * into `RpcClient` internals to decide what to do with a call.\n */\nexport interface RpcMiddlewareContext {\n  readonly namespace: string;\n  readonly action: string;\n  readonly payload: unknown;\n  /** Which attempt this is, 0-indexed. Middleware wrapping the outer request only ever sees attempt 0 — see the module doc comment for why. */\n  readonly attempt: number;\n}\n\n/** Calls the next middleware in the chain (or the actual request, if this is the last one) and returns its result. */\nexport type RpcNext<T> = () => Promise<T>;\n\n/**\n * A middleware wraps a request: it can inspect the context, run code before\n * and after, short-circuit by not calling `next()`, or transform the\n * result/error. Middleware compose like Express/Koa handlers — each one\n * decides whether and when to call `next()`.\n *\n * ```ts\n * const loggingMiddleware: RpcMiddleware = async (ctx, next) => {\n *   const start = Date.now();\n *   try {\n *     return await next();\n *   } finally {\n *     console.log(`${ctx.namespace}.${ctx.action} took ${Date.now() - start}ms`);\n *   }\n * };\n * ```\n */\nexport type RpcMiddleware = <T>(\n  context: RpcMiddlewareContext,\n  next: RpcNext<T>,\n) => Promise<T>;\n\n/**\n * Builds a single callable from a list of middlewares plus a terminal\n * function (the actual request). Middlewares run in registration order on\n * the way in — the first one registered is the outermost wrapper — and\n * unwind in reverse order on the way out, exactly like Koa's `compose`.\n *\n * Applied once per logical request (i.e. wraps the whole retry loop, not\n * each individual attempt) — a middleware that measures duration or logs a\n * call should see one entry per `sdk.auth.getUser()` call a mini app makes,\n * not one entry per retry attempt underneath it.\n */\nexport function composeMiddleware<T>(\n  middlewares: readonly RpcMiddleware[],\n  context: RpcMiddlewareContext,\n  terminal: RpcNext<T>,\n): Promise<T> {\n  let index = -1;\n\n  function dispatch(i: number): Promise<T> {\n    if (i <= index) {\n      throw new Error(\"next() called multiple times in one middleware\");\n    }\n    index = i;\n\n    const middleware = middlewares[i];\n    if (!middleware) {\n      return terminal();\n    }\n    return middleware(context, () => dispatch(i + 1));\n  }\n\n  return dispatch(0);\n}\n","// @generated by scripts/generate-version.mjs — do not edit.\n/**\n * The SDK package version (\"@lizuz/sewa-sdk\") reported to the host during\n * handshake via the \"sdkVersion\" field. Generated from \"package.json\" so it\n * can never drift from the published release.\n */\nexport const RPC_CLIENT_SDK_VERSION = \"1.0.7\";\n","import type {\n  ActionMetrics,\n  DurationPercentiles,\n  RpcMetricsOptions,\n  RpcMetricsSnapshot,\n} from \"./metrics.types\";\n\nconst DEFAULT_MAX_DURATION_ENTRIES = 100;\n\ninterface DurationSample {\n  at: number;\n  durationMs: number;\n}\n\nfunction emptyActionMetrics(): ActionMetrics {\n  return {\n    count: 0,\n    successes: 0,\n    failures: 0,\n    timeouts: 0,\n    retries: 0,\n    totalDurationMs: 0,\n    averageDurationMs: 0,\n    percentiles: emptyPercentiles(),\n  };\n}\n\nfunction emptyPercentiles(): DurationPercentiles {\n  return { p50Ms: 0, p95Ms: 0, p99Ms: 0 };\n}\n\nfunction percentile(sortedValues: number[], p: number): number {\n  const n = sortedValues.length;\n  if (n === 0) return 0;\n  const index = Math.min(n - 1, Math.max(0, Math.ceil((p / 100) * n) - 1));\n  return sortedValues[index];\n}\n\nfunction computePercentiles(samples: DurationSample[]): DurationPercentiles {\n  if (samples.length === 0) return emptyPercentiles();\n  const values = samples\n    .map((sample) => sample.durationMs)\n    .sort((a, b) => a - b);\n  return {\n    p50Ms: percentile(values, 50),\n    p95Ms: percentile(values, 95),\n    p99Ms: percentile(values, 99),\n  };\n}\n\n/**\n * Records what happens to every request that passes through `RpcClient`,\n * broken down per `namespace.action`. This is deliberately in-memory,\n * process-local, and answers \"what has this SDK instance seen so far\", not\n * a long-term metrics store. A host or mini app that wants durable metrics\n * reads a snapshot periodically (via `sdk.getMetrics()`) and ships it\n * wherever it needs to go; `MetricsRecorder` itself never makes a network\n * call.\n *\n * Counters are cumulative, but latency percentiles come from a bounded\n * window of recent durations (see `RpcMetricsOptions`) so long-running\n * mini apps stay memory-bounded and the p99 reflects recent behavior.\n */\nexport class MetricsRecorder {\n  private readonly maxDurationEntries: number;\n  private readonly durationsWindowMs: number | undefined;\n  private readonly onSnapshot: RpcMetricsOptions[\"onSnapshot\"];\n\n  private readonly actions = new Map<string, ActionMetrics>();\n  private readonly durationSamples = new Map<string, DurationSample[]>();\n\n  constructor(options: RpcMetricsOptions = {}) {\n    this.maxDurationEntries =\n      options.maxDurationEntries ?? DEFAULT_MAX_DURATION_ENTRIES;\n    this.durationsWindowMs = options.durationsWindowMs;\n    this.onSnapshot = options.onSnapshot;\n  }\n\n  recordSuccess(namespace: string, action: string, durationMs: number): void {\n    const metrics = this.getOrCreate(namespace, action);\n    metrics.count += 1;\n    metrics.successes += 1;\n    metrics.totalDurationMs += durationMs;\n    metrics.averageDurationMs = metrics.totalDurationMs / metrics.count;\n    this.recordDuration(namespace, action, durationMs);\n  }\n\n  recordFailure(\n    namespace: string,\n    action: string,\n    durationMs: number,\n    wasTimeout: boolean,\n  ): void {\n    const metrics = this.getOrCreate(namespace, action);\n    metrics.count += 1;\n    metrics.failures += 1;\n    if (wasTimeout) metrics.timeouts += 1;\n    metrics.totalDurationMs += durationMs;\n    metrics.averageDurationMs = metrics.totalDurationMs / metrics.count;\n    this.recordDuration(namespace, action, durationMs);\n  }\n\n  recordRetry(namespace: string, action: string): void {\n    const metrics = this.getOrCreate(namespace, action);\n    metrics.retries += 1;\n  }\n\n  snapshot(): RpcMetricsSnapshot {\n    const byAction: Record<string, ActionMetrics> = {};\n    let totalRequests = 0;\n    let totalSuccesses = 0;\n    let totalFailures = 0;\n    let totalTimeouts = 0;\n    let totalRetries = 0;\n    let totalDurationMs = 0;\n    const allSamples: DurationSample[] = [];\n\n    const now = Date.now();\n    for (const [key, metrics] of this.actions) {\n      const window = this.samplesWithinWindow(key, now);\n      byAction[key] = {\n        ...metrics,\n        percentiles: computePercentiles(window),\n      };\n      totalRequests += metrics.count;\n      totalSuccesses += metrics.successes;\n      totalFailures += metrics.failures;\n      totalTimeouts += metrics.timeouts;\n      totalRetries += metrics.retries;\n      totalDurationMs += metrics.totalDurationMs;\n      allSamples.push(...window);\n    }\n\n    const snapshot: RpcMetricsSnapshot = {\n      totalRequests,\n      totalSuccesses,\n      totalFailures,\n      totalTimeouts,\n      totalRetries,\n      averageDurationMs:\n        totalRequests > 0 ? totalDurationMs / totalRequests : 0,\n      percentiles: computePercentiles(allSamples),\n      byAction,\n    };\n\n    try {\n      this.onSnapshot?.(snapshot);\n    } catch {\n      // A host's snapshot hook must never break metric reads.\n    }\n\n    return snapshot;\n  }\n\n  reset(): void {\n    this.actions.clear();\n    this.durationSamples.clear();\n  }\n\n  private recordDuration(\n    namespace: string,\n    action: string,\n    durationMs: number,\n  ): void {\n    const key = `${namespace}.${action}`;\n    const samples = this.durationSamples.get(key) ?? [];\n    samples.push({ at: Date.now(), durationMs });\n    if (samples.length > this.maxDurationEntries) samples.shift();\n    this.durationSamples.set(key, samples);\n  }\n\n  /** The bounded, age-windowed duration samples for one action. */\n  private samplesWithinWindow(key: string, now: number): DurationSample[] {\n    const samples = this.durationSamples.get(key);\n    if (!samples) return [];\n    if (this.durationsWindowMs === undefined) return samples;\n    const cutoff = now - this.durationsWindowMs;\n    const window = samples.filter((sample) => sample.at >= cutoff);\n    // Opportunistically drop aged-out samples so the array stays tight.\n    if (window.length !== samples.length) this.durationSamples.set(key, window);\n    return window;\n  }\n\n  private getOrCreate(namespace: string, action: string): ActionMetrics {\n    const key = `${namespace}.${action}`;\n    let metrics = this.actions.get(key);\n    if (!metrics) {\n      metrics = emptyActionMetrics();\n      this.actions.set(key, metrics);\n    }\n    return metrics;\n  }\n}\n","import type { Span, Tracer } from \"./tracer.types\";\n\n/**\n * Default `Span` used when no tracer is supplied: accepts every call and does\n * nothing. Kept so the `RpcClient` hot path never branches on whether tracing\n * is enabled.\n */\nexport class NoopSpan implements Span {\n  constructor(readonly name: string) {}\n  end(): void {}\n  setAttribute(): void {}\n}\n\n/**\n * The default `Tracer`: starts `NoopSpan`s, so an SDK that isn't given a\n * tracer behaves exactly as it always has — no allocation of real spans, no\n * behavior change.\n */\nexport const noopTracer: Tracer = {\n  startSpan(name: string): Span {\n    return new NoopSpan(name);\n  },\n};\n","/**\n * Computes how long to wait before the given retry attempt.\n *\n * Delay doubles with each attempt (`baseMs * 2^attempt`), capped at\n * `maxMs`, then a random amount of jitter (up to 30% of that delay) is\n * added on top. The jitter matters once a namespace/action starts timing\n * out for a lot of mini apps at once (e.g. the host briefly restarts) —\n * without it, every retry would land on the host at exactly the same\n * moment, attempt after attempt, which is the thing you the least want during\n * a recovery.\n *\n * `attempt` is 0-indexed: the delay before the *first* retry uses `attempt = 0`.\n */\n\n/**\n * Returns the delay (in milliseconds) before the next retry.\n *\n * The delay grows exponentially with each retry:\n *   baseMs, baseMs * 2, baseMs * 4, ...\n *\n * It never exceeds `maxMs`. After calculating the delay, a random jitter\n * of up to 30% is added. This spreads retries out over time so that many\n * clients don't all retry at the same moment, which helps reduce a load\n * during outages or service recovery.\n *\n * `attempt` is zero-based, so `attempt = 0` is the delay before the first retry.\n */\nexport function computeBackoffMs(\n  attempt: number,\n  baseMs: number,\n  maxMs: number,\n): number {\n  const exponential = baseMs * 2 ** attempt;\n  const capped = Math.min(exponential, maxMs);\n  const jitter = capped * 0.3 * Math.random();\n  return Math.round(capped + jitter);\n}\n","/**\n * Resolves after `ms` milliseconds. Used to space out retry attempts.\n */\nexport function delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Generates a unique identifier. Prefers `crypto.randomUUID()` where\n * available (all modern browsers and WebViews) and falls back to a\n * timestamp+random string for older/embedded JS engines.\n */\nexport function generateId(): string {\n  if (\n    typeof crypto !== \"undefined\" &&\n    typeof crypto.randomUUID === \"function\"\n  ) {\n    return crypto.randomUUID();\n  }\n  return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n","import { MESSAGE_CHANNEL, PROTOCOL_VERSION } from \"../constants\";\nimport { generateId } from \"../utils\";\nimport type {\n  MessageType,\n  PlatformError,\n  PlatformMessage,\n} from \"./message.types\";\n\nexport interface CreateMessageOptions {\n  requestId?: string;\n  traceId?: string;\n  gsaProtocolVersion?: string;\n  error?: PlatformError;\n}\n\n/**\n * Builds a `PlatformMessage` envelope with every required field populated.\n * This is the only place in the SDK that should construct an envelope by\n * hand — everywhere else should call this factory so the envelope shape\n * stays consistent as the protocol evolves.\n */\nexport function createMessage<TPayload = unknown>(\n  type: MessageType,\n  namespace: string,\n  action: string,\n  source: string,\n  target: string,\n  payload?: TPayload,\n  options?: CreateMessageOptions,\n): PlatformMessage<TPayload> {\n  return {\n    channel: MESSAGE_CHANNEL,\n    requestId: options?.requestId ?? generateId(),\n    type,\n    namespace,\n    action,\n    source,\n    target,\n    gsaProtocolVersion: options?.gsaProtocolVersion ?? PROTOCOL_VERSION,\n    payload,\n    error: options?.error,\n    traceId: options?.traceId ?? generateId(),\n    timestamp: Date.now(),\n  };\n}\n","import { PROTOCOL_VERSION } from \"../constants\";\nimport type { PlatformError, PlatformMessage } from \"./message.types\";\n\nconst MESSAGE_TYPES = new Set([\n  \"request\",\n  \"response\",\n  \"event\",\n  \"handshake\",\n  \"stream\",\n]);\n\nexport interface MessageValidationResult {\n  valid: boolean;\n  /** Populated when `valid` is false — a human-readable reason, safe to log. */\n  reason?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n  return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isValidPlatformError(value: unknown): value is PlatformError {\n  if (!isRecord(value)) return false;\n  if (!isNonEmptyString(value.code)) return false;\n  if (!isNonEmptyString(value.message)) return false;\n  if (value.retryable !== undefined && typeof value.retryable !== \"boolean\")\n    return false;\n  if (value.details !== undefined && !isRecord(value.details)) return false;\n  return true;\n}\n\n/**\n * The SDK's sole trust boundary for anything arriving from the host. No\n * incoming message is dispatched to a pending request, an event handler, or\n * anywhere else in the SDK until it passes this check.\n *\n * This is deliberately a plain type guard (not an exception-throwing\n * \"assert\") so callers on a hot path (every `window.message` event) can\n * cheaply discard non-protocol traffic without paying exception-handling\n * cost, and can decide for themselves whether a *specific* failure (e.g.\n * \"correlation id not found\") is protocol-error-worthy.\n */\nexport function isValidPlatformMessage(data: unknown): data is PlatformMessage {\n  return validatePlatformMessage(data).valid;\n}\n\n/**\n * Same check as `isValidPlatformMessage`, but returns a reason string for\n * logging/diagnostics instead of a boolean, since \"the message was\n * rejected\" alone isn't actionable in production.\n */\nexport function validatePlatformMessage(\n  data: unknown,\n): MessageValidationResult {\n  if (!isRecord(data)) {\n    return { valid: false, reason: \"message is not an object\" };\n  }\n\n  if (!isNonEmptyString(data.channel)) {\n    return { valid: false, reason: 'missing or invalid \"channel\"' };\n  }\n\n  if (!isNonEmptyString(data.requestId)) {\n    return {\n      valid: false,\n      reason: 'missing or invalid \"requestId\" (correlation id)',\n    };\n  }\n\n  if (typeof data.type !== \"string\" || !MESSAGE_TYPES.has(data.type)) {\n    return {\n      valid: false,\n      reason: `missing or invalid \"type\" (must be one of ${[...MESSAGE_TYPES].join(\", \")})`,\n    };\n  }\n\n  if (!isNonEmptyString(data.namespace)) {\n    return { valid: false, reason: 'missing or invalid \"namespace\"' };\n  }\n\n  if (!isNonEmptyString(data.action)) {\n    return { valid: false, reason: 'missing or invalid \"action\"' };\n  }\n\n  if (!isNonEmptyString(data.source)) {\n    return { valid: false, reason: 'missing or invalid \"source\"' };\n  }\n\n  if (!isNonEmptyString(data.target)) {\n    return { valid: false, reason: 'missing or invalid \"target\"' };\n  }\n\n  if (!isNonEmptyString(data.gsaProtocolVersion)) {\n    return { valid: false, reason: 'missing or invalid \"gsaProtocolVersion\"' };\n  }\n\n  if (!isNonEmptyString(data.traceId)) {\n    return { valid: false, reason: 'missing or invalid \"traceId\"' };\n  }\n\n  if (typeof data.timestamp !== \"number\" || !Number.isFinite(data.timestamp)) {\n    return { valid: false, reason: 'missing or invalid \"timestamp\"' };\n  }\n\n  if (data.error !== undefined && !isValidPlatformError(data.error)) {\n    return { valid: false, reason: 'invalid \"error\" shape' };\n  }\n\n  if (data.type === \"stream\") {\n    if (\n      data.streamIndex !== undefined &&\n      (typeof data.streamIndex !== \"number\" ||\n        !Number.isFinite(data.streamIndex))\n    ) {\n      return {\n        valid: false,\n        reason: 'invalid \"streamIndex\" on stream message',\n      };\n    }\n    if (\n      data.streamTotal !== undefined &&\n      (typeof data.streamTotal !== \"number\" ||\n        !Number.isFinite(data.streamTotal))\n    ) {\n      return {\n        valid: false,\n        reason: 'invalid \"streamTotal\" on stream message',\n      };\n    }\n    if (data.streamLast !== undefined && typeof data.streamLast !== \"boolean\") {\n      return { valid: false, reason: 'invalid \"streamLast\" on stream message' };\n    }\n  }\n\n  return { valid: true };\n}\n\n/**\n * Compares two protocol version strings by their major component only —\n * `\"3.1.0\"` and `\"3.4.2\"` are compatible, `\"3.0.0\"` and `\"4.0.0\"` are not.\n * A minor/patch bump is expected to stay backward compatible within a\n * major version, per the SDK's SemVer policy; only a major bump signals a\n * breaking wire-format change.\n */\nexport function majorVersionsMatch(a: string, b: string): boolean {\n  return a.split(\".\")[0] === b.split(\".\")[0];\n}\n\n/**\n * Compares the protocol version stamped on an incoming message against\n * this SDK build's `PROTOCOL_VERSION` (or an explicit `expected` value).\n * Used as the first line of defense against processing a message shaped\n * for a wire format this SDK build doesn't speak.\n */\nexport function hasCompatibleMajorVersion(\n  message: PlatformMessage,\n  expected: string = PROTOCOL_VERSION,\n): boolean {\n  return majorVersionsMatch(message.gsaProtocolVersion, expected);\n}\n","import type { StreamChunk } from \"@lizuz/mini-app-types\";\nimport { StreamCancelledError } from \"../errors\";\n\n/**\n * Accumulates the chunks of an in-flight streamed response and hands the\n * assembled result to consumers via a promise and an async iterator.\n *\n * Lifecycle: the `RpcClient` registers a `StreamBuilder` per streamed\n * request, feeds it one `StreamChunk` per inbound `stream` message, and the\n * builder resolves once the host flags the final chunk (`last: true`) or\n * rejects if the host reports an error / the stream times out.\n *\n * This class is intentionally transport-agnostic: it holds no reference to\n * `RpcClient`, `Transport`, or the wire format — chunks in, result out.\n * Cancellation follows the same rule: `cancel()` rejects the stream locally\n * and invokes the `onCancel` hook if one was set, but the hook — which is\n * what tells the host to stop producing — is the RPC layer's responsibility\n * to wire up.\n */\nexport class StreamBuilder {\n  private readonly chunks = new Map<number, Uint8Array | string>();\n  private resolved = false;\n  private rejected = false;\n\n  private receivedBytesCount = 0;\n  private receivedChunksCount = 0;\n  private totalCount = 0;\n\n  /** Hook the RPC layer sets to notify the host that this stream is being cancelled. */\n  private onCancelCallback: (() => void) | null = null;\n\n  private readonly promise = new Promise<(Uint8Array | string)[]>(\n    (resolve, reject) => {\n      this.resolve = resolve;\n      this.reject = reject;\n    },\n  );\n\n  private resolve?: (chunks: (Uint8Array | string)[]) => void;\n  private reject?: (err: Error) => void;\n\n  /**\n   * A never-rejecting mirror of `promise`, so consumers that only want the\n   * chunks produced before a failure (`iterate`) don't have to catch.\n   */\n  private readonly settledPromise = this.promise.catch(() => {\n    this.rejected = true;\n    return [];\n  });\n\n  /** Resolves when the stream completes, or rejects if it fails mid-stream. */\n  waitUntilDone(): Promise<void> {\n    return this.promise.then(() => {});\n  }\n\n  /** Records one inbound chunk. Chunks are keyed by `index` (out-of-order delivery is safe). */\n  addChunk(chunk: StreamChunk): void {\n    if (this.resolved || this.rejected) return;\n    this.chunks.set(chunk.index, chunk.data);\n    this.receivedChunksCount = this.chunks.size;\n\n    // Recomputed on every chunk so a retransmission (same index) doesn't\n    // double-count bytes. String length is UTF-16 code units — close enough\n    // for progress reporting; the host's `total` (when sent) is authoritative.\n    let bytes = 0;\n    for (const data of this.chunks.values()) {\n      bytes += data instanceof Uint8Array ? data.byteLength : data.length;\n    }\n    this.receivedBytesCount = bytes;\n\n    if (chunk.total !== undefined) this.totalCount = chunk.total;\n\n    if (chunk.last) {\n      this.resolved = true;\n      this.resolve?.([...this.chunks.values()]);\n    }\n  }\n\n  /** True once the final chunk has been received. */\n  get isDone(): boolean {\n    return this.resolved;\n  }\n\n  /** True once the stream has been failed (via error chunk, transport, timeout, or cancellation). */\n  get isRejected(): boolean {\n    return this.rejected;\n  }\n\n  /** Total number of distinct chunks received so far (deduplicated by index). */\n  get receivedChunks(): number {\n    return this.receivedChunksCount;\n  }\n\n  /** Total bytes received so far across all distinct chunks. */\n  get receivedBytes(): number {\n    return this.receivedBytesCount;\n  }\n\n  /** The stream's overall size as reported by the host via `streamTotal`, or 0 if it never sent one. */\n  get total(): number {\n    return this.totalCount;\n  }\n\n  /**\n   * Yields every chunk received so far once the stream settles. After a\n   * failure this yields nothing (the chunks already buffered before the\n   * failure are considered untrustworthy — a mid-stream failure means the\n   * response may be incomplete).\n   */\n  async *iterate(): AsyncIterableIterator<string | Uint8Array> {\n    if (this.rejected) return;\n    const result = await this.settledPromise;\n    if (this.rejected) return;\n    for (const chunk of result) {\n      yield chunk;\n    }\n  }\n\n  /** Fails the stream. No further chunks are accepted. */\n  rejectChunk(err: Error): void {\n    if (this.rejected || this.resolved) return;\n    this.rejected = true;\n    this.reject?.(err);\n  }\n\n  /**\n   * Cancels the stream: rejects it with a `StreamCancelledError` (or the\n   * provided error) and fires the `onCancel` hook the RPC layer installed, so\n   * the host is told to stop producing. Safe to call more than once; only the\n   * first call has any effect.\n   */\n  cancel(error?: Error): void {\n    if (this.rejected || this.resolved) return;\n    this.rejected = true;\n    this.onCancelCallback?.();\n    this.reject?.(error ?? new StreamCancelledError());\n  }\n\n  /**\n   * Internal hook used by the RPC layer: invoked when the mini app cancels the\n   * stream via `cancel()`, giving the layer a chance to notify the host (e.g.\n   * send an `ai.cancel` request) before the stream settles. Transport-agnostic\n   * here — the hook's semantics belong entirely to whoever installs it.\n   */\n  get onCancel(): (() => void) | null {\n    return this.onCancelCallback;\n  }\n\n  set onCancel(callback: (() => void) | null) {\n    this.onCancelCallback = callback;\n  }\n}\n","import {\n  ACTIONS,\n  CONNECTION_EVENTS,\n  HOST_TARGET,\n  NAMESPACES,\n  PROTOCOL_VERSION,\n  SDK_CAPABILITIES,\n} from \"../constants\";\nimport { RPC_CLIENT_SDK_VERSION } from \"../constants/version.generated\";\nimport {\n  HandshakeError,\n  ProtocolError,\n  RequestCancelledError,\n  TimeoutError,\n} from \"../errors\";\nimport type { Logger } from \"../logging\";\nimport { noopLogger } from \"../logging\";\nimport type {\n  RpcMetricsOptions,\n  RpcMetricsSnapshot,\n  Span,\n  Tracer,\n} from \"../observability\";\nimport { MetricsRecorder, noopTracer } from \"../observability\";\nimport type {\n  HandshakeAckPayload,\n  HandshakePayload,\n  PlatformMessage,\n} from \"../protocol\";\nimport {\n  createMessage,\n  hasCompatibleMajorVersion,\n  majorVersionsMatch,\n} from \"../protocol\";\nimport { StreamBuilder } from \"../stream\";\nimport type { Transport, TransportDebugInfo } from \"../transport\";\nimport type {\n  HeartbeatOptions,\n  OnEventOptions,\n  PendingRequestInfo,\n} from \"../types\";\nimport { computeBackoffMs, delay, generateId } from \"../utils\";\nimport type { RpcMiddleware } from \"./middleware\";\nimport { composeMiddleware } from \"./middleware\";\n\nexport type EventHandler<TPayload = unknown> = (payload: TPayload) => void;\n\n/** Per-request control knobs passed to `request()`. */\nexport interface RpcRequestOptions {\n  /**\n   * When provided, aborting the signal rejects the in-flight request (and any\n   * pending retries) with a `RequestCancelledError` — useful for unmounting\n   * screens or navigating away without waiting for the timeout.\n   */\n  signal?: AbortSignal;\n  /**\n   * Optional transformation applied to the host's response **inside** the\n   * retry loop. Throwing from here — e.g. mapping an `HttpResult` carrying a\n   * 5xx `status` onto an `HttpServerError` — rejects the request and, when\n   * the thrown error is `retryable`, participates in the normal retry policy\n   * exactly like any other request failure.\n   */\n  mapPayload?: (payload: unknown) => unknown;\n}\n\n/** Per-stream control knobs passed to `sendStreamRequest()`. */\nexport interface RpcStreamOptions {\n  /**\n   * When provided, aborting the signal cancels the stream (rejecting the\n   * `StreamBuilder` with a `RequestCancelledError`) and notifies the host to\n   * stop producing.\n   */\n  signal?: AbortSignal;\n}\n\nexport interface RpcClientOptions {\n  miniAppId: string;\n  timeout?: number;\n  retryAttempts?: number;\n  retryDelayMs?: number;\n  maxRetryDelayMs?: number;\n  logger?: Logger;\n  /**\n   * When true, warns once per `namespace.action` about requests to domain\n   * namespaces the host did not negotiate during the handshake. No-op when\n   * false (production). Defaults to false.\n   */\n  devMode?: boolean;\n  /** Enables the optional heartbeat & reconnect (see `HeartbeatOptions`). */\n  heartbeat?: HeartbeatOptions;\n  /** Tuning for the request metrics recorder (percentile window, export hook). */\n  metrics?: RpcMetricsOptions;\n  /**\n   * Optional tracer for RPC observability. When omitted, a no-op tracer is\n   * used and behavior is unchanged. See `observability/tracer.types.ts` for\n   * the minimal `Tracer`/`Span` contract.\n   */\n  tracer?: Tracer;\n}\n\ninterface PendingRequest {\n  resolve: (value: unknown) => void;\n  reject: (error: Error) => void;\n  timer: ReturnType<typeof setTimeout>;\n  namespace: string;\n  action: string;\n  /** `Date.now()` when the request was dispatched, for debug snapshots. */\n  startedAt: number;\n}\n\n/** Metadata the RPC layer keeps per active streamed request. */\ninterface StreamRecord {\n  builder: StreamBuilder;\n  namespace: string;\n  action: string;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_RETRY_ATTEMPTS = 2;\nconst DEFAULT_RETRY_DELAY_MS = 500;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 8_000;\nconst DEFAULT_HEARTBEAT_INTERVAL_MS = 30_000;\nconst DEFAULT_HEARTBEAT_TIMEOUT_MS = 5_000;\nconst DEFAULT_MAX_MISSED_PONGS = 2;\n\n/** How many recent payloads per event the replay buffer retains. */\nconst EVENT_REPLAY_BUFFER_SIZE = 5;\n\n/**\n * Owns everything about *RPC semantics* as opposed to *message delivery*:\n * correlation ids, the pending-request map, timeout enforcement, retry\n * policy, the handshake sequence (including protocol version and\n * capability negotiation), and event subscription.\n *\n * `RpcClient` depends only on the `Transport` interface — it has no\n * knowledge of `postMessage`, `window`, or any other delivery mechanism.\n * SDK modules (`AuthModule`, `HttpModule`, ...) depend on `RpcClient`, not\n * on `Transport` directly.\n */\nexport class RpcClient {\n  private readonly miniAppId: string;\n  private readonly timeout: number;\n  private readonly retryAttempts: number;\n  private readonly retryDelayMs: number;\n  private readonly maxRetryDelayMs: number;\n  private readonly logger: Logger;\n  private readonly devMode: boolean;\n  private readonly transport: Transport;\n  private readonly heartbeatOptions: HeartbeatOptions | null;\n\n  private readonly pending = new Map<string, PendingRequest>();\n  private readonly eventHandlers = new Map<string, Set<EventHandler>>();\n  private readonly streamConsumers = new Map<string, StreamRecord>();\n  private readonly middlewares: RpcMiddleware[] = [];\n  private readonly metricsRecorder: MetricsRecorder;\n  private readonly tracer: Tracer;\n  private readonly warnedUnavailableCapabilities = new Set<string>();\n  private readonly traceId: string;\n  private started = false;\n\n  /** Set while a reconnect (re-run of the handshake) is in progress. */\n  private reconnectInProgress = false;\n  private heartbeatInterval: ReturnType<typeof setInterval> | null = null;\n  private heartbeatMissedPongs = 0;\n  /** Heartbeat pings awaiting a pong, keyed by requestId. */\n  private readonly heartbeatPings = new Map<\n    string,\n    { onPong: () => void; timer: ReturnType<typeof setTimeout> }\n  >();\n\n  /**\n   * Bounded per-event buffer of recent payloads, for `onEvent()` subscriptions\n   * that pass the `replay` option. New subscribers receive the buffered values\n   * immediately so a slow mount doesn't lose events that arrived before it\n   * subscribed.\n   */\n  private readonly eventReplayBuffer = new Map<string, unknown[]>();\n\n  /**\n   * Namespaces the host confirmed support for during the handshake. `null`\n   * until `handshake()` resolves. Populated to `SDK_CAPABILITIES` verbatim\n   * when a host doesn't report its own capabilities at all (an\n   * not-yet-upgraded host), since the safest assumption in that case is\n   * \"everything this SDK build knows how to ask for is fair game\", which\n   * is exactly today's behavior for such a host.\n   */\n  private negotiatedCapabilities: string[] | null = null;\n\n  constructor(transport: Transport, options: RpcClientOptions) {\n    this.transport = transport;\n    this.miniAppId = options.miniAppId;\n    this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n    this.retryAttempts = options.retryAttempts ?? DEFAULT_RETRY_ATTEMPTS;\n    this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n    this.maxRetryDelayMs =\n      options.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n    this.logger = options.logger ?? noopLogger;\n    this.devMode = options.devMode ?? false;\n    this.heartbeatOptions = options.heartbeat ?? null;\n    this.metricsRecorder = new MetricsRecorder(options.metrics);\n    this.tracer = options.tracer ?? noopTracer;\n    this.traceId = generateId();\n  }\n\n  /** Begin listening for inbound messages via the injected `Transport`. */\n  start(): void {\n    if (this.started) return;\n    this.transport.start((message) => this.handleIncomingMessage(message));\n    this.started = true;\n  }\n\n  /**\n   * Stop listening and reject every in-flight request. Safe to call\n   * multiple times and safe to call even if `start` was never called.\n   */\n  stop(): void {\n    this.transport.stop();\n    this.started = false;\n    this.reconnectInProgress = false;\n    this.stopHeartbeat();\n\n    for (const [id, request] of this.pending) {\n      clearTimeout(request.timer);\n      request.reject(\n        new ProtocolError({\n          reason: \"malformed-message\",\n          message: `Request \"${request.namespace}.${request.action}\" was cancelled because the RPC client was stopped`,\n        }),\n      );\n      this.pending.delete(id);\n    }\n\n    for (const [, stream] of this.streamConsumers) {\n      stream.builder.rejectChunk(\n        new ProtocolError({\n          reason: \"malformed-message\",\n          message:\n            \"The stream was cancelled because the RPC client was stopped\",\n        }),\n      );\n    }\n    this.streamConsumers.clear();\n\n    this.eventHandlers.clear();\n    this.eventReplayBuffer.clear();\n  }\n\n  /**\n   * Performs the initial handshake with the host: sends this SDK build's\n   * protocol version and capability list, and waits for the host's\n   * acknowledgement.\n   *\n   * A host that doesn't yet send an acknowledgement payload (an\n   * un-upgraded host that just echoes `{ status: 'ok' }`) completes the\n   * handshake exactly as before — every field on the ack is optional, and\n   * missing fields fall back to permissive defaults. A host that *does*\n   * report an incompatible protocol version, or that explicitly rejects\n   * the connection, causes this to reject with a `HandshakeError` instead\n   * of silently proceeding with a connection that won't actually work.\n   */\n  async handshake(): Promise<void> {\n    const span = this.tracer.startSpan(\"rpc.handshake\", {\n      miniAppId: this.miniAppId,\n      traceId: this.traceId,\n    });\n    try {\n      await this.performHandshake();\n    } finally {\n      span.end();\n    }\n  }\n\n  private async performHandshake(): Promise<void> {\n    const payload: HandshakePayload = {\n      miniAppId: this.miniAppId,\n      sdkVersion: RPC_CLIENT_SDK_VERSION,\n      protocolVersion: PROTOCOL_VERSION,\n      capabilities: SDK_CAPABILITIES,\n    };\n\n    const message = createMessage(\n      \"handshake\",\n      NAMESPACES.HANDSHAKE,\n      ACTIONS.HANDSHAKE.CONNECT,\n      this.miniAppId,\n      HOST_TARGET,\n      payload,\n      {\n        traceId: this.traceId,\n      },\n    );\n\n    return new Promise<void>((resolvePromise, rejectPromise) => {\n      const timer = setTimeout(() => {\n        this.pending.delete(message.requestId);\n        rejectPromise(\n          new HandshakeError({\n            message: \"Handshake with host timed out\",\n            timedOut: true,\n          }),\n        );\n      }, this.timeout);\n\n      this.pending.set(message.requestId, {\n        resolve: (ackPayload) =>\n          this.completeHandshake(ackPayload, resolvePromise, rejectPromise),\n        reject: (error) =>\n          rejectPromise(\n            error instanceof HandshakeError\n              ? error\n              : new HandshakeError({ message: error.message, cause: error }),\n          ),\n        timer,\n        namespace: NAMESPACES.HANDSHAKE,\n        action: ACTIONS.HANDSHAKE.CONNECT,\n        startedAt: Date.now(),\n      });\n\n      this.sendOrFail(message, () => this.pending.delete(message.requestId));\n    });\n  }\n\n  /**\n   * Registers a middleware. Middlewares run in registration order (the\n   * first registered is outermost) and wrap the entire request, including\n   * its retry attempts — see `rpc/middleware.ts` for the execution model.\n   * Safe to call after `start()`; a middleware registered mid-session\n   * applies to every request made from that point on, not to ones already\n   * in flight.\n   */\n  use(middleware: RpcMiddleware): void {\n    this.middlewares.push(middleware);\n  }\n\n  /**\n   * Sends a request and resolves with the host's response payload. Passes\n   * through any registered middleware, then through the retry loop\n   * described on `executeWithRetry`. An optional `AbortSignal` in `options`\n   * cancels the request (including any queued retries) with a\n   * `RequestCancelledError` as soon as it fires.\n   *\n   * A span named `rpc.request` is started for the whole composed call (one\n   * span per logical request, wrapping the retry loop — same granularity as\n   * the middleware chain) and annotated with the namespace, action, and any\n   * terminal error.\n   */\n  async request<T>(\n    namespace: string,\n    action: string,\n    payload?: unknown,\n    options?: RpcRequestOptions,\n  ): Promise<T> {\n    this.warnOnUnavailableCapability(namespace, action);\n    const span = this.tracer.startSpan(\"rpc.request\", {\n      namespace,\n      action,\n      traceId: this.traceId,\n    });\n    try {\n      return await composeMiddleware<T>(\n        this.middlewares,\n        { namespace, action, payload, attempt: 0 },\n        () =>\n          this.executeWithRetry<T>(namespace, action, payload, options, span),\n      );\n    } catch (error) {\n      span.setAttribute(\n        \"error\",\n        error instanceof Error ? error.message : String(error),\n      );\n      span.setAttribute(\n        \"retryable\",\n        error instanceof Error && \"retryable\" in error\n          ? Boolean((error as { retryable?: boolean }).retryable)\n          : false,\n      );\n      throw error;\n    } finally {\n      span.end();\n    }\n  }\n\n  /**\n   * Dev-mode helper: once the handshake has completed, warn once per\n   * `namespace.action` when the namespace is a domain capability this SDK\n   * advertises but the host did not negotiate. Protocol-level namespaces\n   * (`event`, `handshake`) are excluded — hosts never negotiate them, so a\n   * warning would be noise. A no-op when `devMode` is off.\n   */\n  private warnOnUnavailableCapability(namespace: string, action: string): void {\n    if (!this.devMode) return;\n    if (!this.negotiatedCapabilities) return;\n    if (!SDK_CAPABILITIES.includes(namespace)) return;\n    if (this.negotiatedCapabilities.includes(namespace)) return;\n\n    const key = `${namespace}.${action}`;\n    if (this.warnedUnavailableCapabilities.has(key)) return;\n    this.warnedUnavailableCapabilities.add(key);\n    this.logger.warn(\n      `[dev] \"${key}\" requires the \"${namespace}\" capability, but the host did not negotiate it — the request will likely fail`,\n    );\n  }\n\n  /**\n   * The actual retry loop: retryable failures (currently just\n   * `TimeoutError`) are retried up to `retryAttempts` times, waiting an\n   * exponentially increasing, jittered delay between attempts (see\n   * `utils/backoff.ts`) so a burst of mini apps recovering from the same\n   * host hiccup doesn't retry in lockstep. Every attempt — success or\n   * failure — is recorded into `metricsRecorder`.\n   */\n  private async executeWithRetry<T>(\n    namespace: string,\n    action: string,\n    payload?: unknown,\n    options?: RpcRequestOptions,\n    span?: Span,\n  ): Promise<T> {\n    let lastError: Error | undefined;\n\n    for (let attempt = 0; attempt <= this.retryAttempts; attempt++) {\n      if (options?.signal?.aborted) {\n        throw new RequestCancelledError({\n          namespace,\n          action,\n          cause: options.signal.reason,\n        });\n      }\n\n      const startedAt = Date.now();\n      try {\n        const result = await this.sendRequest<T>(\n          namespace,\n          action,\n          payload,\n          options?.signal,\n        );\n        const mapped = options?.mapPayload\n          ? (options.mapPayload(result) as T)\n          : result;\n        this.metricsRecorder.recordSuccess(\n          namespace,\n          action,\n          Date.now() - startedAt,\n        );\n        return mapped;\n      } catch (error) {\n        lastError = error instanceof Error ? error : new Error(String(error));\n        const wasTimeout = lastError instanceof TimeoutError;\n        this.metricsRecorder.recordFailure(\n          namespace,\n          action,\n          Date.now() - startedAt,\n          wasTimeout,\n        );\n\n        const retryable =\n          \"retryable\" in lastError\n            ? Boolean((lastError as { retryable?: boolean }).retryable)\n            : false;\n        if (!retryable) throw lastError;\n        if (attempt < this.retryAttempts) {\n          this.metricsRecorder.recordRetry(namespace, action);\n          span?.setAttribute(\"retryCount\", attempt + 1);\n          await this.abortAwareDelay(\n            computeBackoffMs(attempt, this.retryDelayMs, this.maxRetryDelayMs),\n            namespace,\n            action,\n            options?.signal,\n          );\n        }\n      }\n    }\n\n    throw (\n      lastError ??\n      new ProtocolError({\n        reason: \"malformed-message\",\n        message: `Request \"${namespace}.${action}\" failed for an unknown reason`,\n      })\n    );\n  }\n\n  /**\n   * Delays while watching an `AbortSignal`: aborts reject early with a\n   * `RequestCancelledError` instead of letting the caller wait out a backoff\n   * that no longer matters.\n   */\n  private async abortAwareDelay(\n    ms: number,\n    namespace: string,\n    action: string,\n    signal?: AbortSignal,\n  ): Promise<void> {\n    if (!signal) {\n      await delay(ms);\n      return;\n    }\n    if (signal.aborted) {\n      throw new RequestCancelledError({\n        namespace,\n        action,\n        cause: signal.reason,\n      });\n    }\n    await new Promise<void>((resolve, reject) => {\n      const timer = setTimeout(resolve, ms);\n      signal.addEventListener(\n        \"abort\",\n        () => {\n          clearTimeout(timer);\n          reject(\n            new RequestCancelledError({\n              namespace,\n              action,\n              cause: signal.reason,\n            }),\n          );\n        },\n        { once: true },\n      );\n    });\n  }\n\n  /**\n   * Sends a request whose response the host streams back as a sequence of\n   * `stream` messages. Resolves with a `StreamBuilder` immediately — the\n   * first chunk may arrive before this promise settles — which callers\n   * consume via `builder.iterate()` (per-chunk) or `builder.waitUntilDone()`\n   * (whole-stream completion). See `stream/StreamBuilder.ts`.\n   *\n   * Streams deliberately bypass the middleware and retry machinery: a\n   * stream may already have produced output by the time a failure would be\n   * detected, so an automatic retry can't be spliced in safely. A timeout\n   * still applies, matching every other request.\n   *\n   * An optional `AbortSignal` in `options` cancels the stream: the builder\n   * rejects with a `RequestCancelledError` and the host is told to stop\n   * producing. A mini app can also cancel directly via `builder.cancel()`,\n   * which notifies the host the same way.\n   */\n  async sendStreamRequest(\n    namespace: string,\n    action: string,\n    payload?: unknown,\n    options?: RpcStreamOptions,\n  ): Promise<StreamBuilder> {\n    const message = createMessage(\n      \"request\",\n      namespace,\n      action,\n      this.miniAppId,\n      HOST_TARGET,\n      payload,\n      {\n        traceId: this.traceId,\n      },\n    );\n\n    const builder = new StreamBuilder();\n    const signal = options?.signal;\n    this.streamConsumers.set(message.requestId, { builder, namespace, action });\n    builder.onCancel = () => this.notifyHostStreamCancelled(message.requestId);\n\n    const span = this.tracer.startSpan(\"rpc.stream\", {\n      namespace,\n      action,\n      traceId: this.traceId,\n    });\n\n    const onAbort = (): void => {\n      this.cancelStreamBuilder(\n        message.requestId,\n        new RequestCancelledError({\n          namespace,\n          action,\n          cause: signal?.reason,\n        }),\n      );\n    };\n\n    const timer = setTimeout(() => {\n      this.streamConsumers.delete(message.requestId);\n      builder.rejectChunk(\n        new TimeoutError({ namespace, action, timeoutMs: this.timeout }),\n      );\n    }, this.timeout);\n\n    const cleanup = (): void => {\n      clearTimeout(timer);\n      if (signal) signal.removeEventListener(\"abort\", onAbort);\n      this.streamConsumers.delete(message.requestId);\n    };\n\n    try {\n      this.transport.send(message);\n    } catch (error) {\n      cleanup();\n      builder.rejectChunk(\n        error instanceof Error ? error : new Error(String(error)),\n      );\n    }\n\n    builder.waitUntilDone().then(\n      () => {\n        cleanup();\n        span.setAttribute(\"bytes\", builder.receivedBytes);\n        span.end();\n      },\n      (error: unknown) => {\n        cleanup();\n        span.setAttribute(\n          \"error\",\n          error instanceof Error ? error.message : String(error),\n        );\n        span.end();\n      },\n    );\n\n    if (signal) {\n      if (signal.aborted) {\n        onAbort();\n      } else {\n        signal.addEventListener(\"abort\", onAbort, { once: true });\n      }\n    }\n\n    return builder;\n  }\n\n  /**\n   * Explicitly cancels an active streamed request by its `requestId`,\n   * rejecting its builder and notifying the host to stop producing. No-op if\n   * the stream already settled. The RPC layer owns cancellation semantics —\n   * the `StreamBuilder` itself stays transport-agnostic.\n   */\n  cancelStream(requestId: string): void {\n    const record = this.streamConsumers.get(requestId);\n    if (!record) return;\n    this.cancelStreamBuilder(requestId);\n  }\n\n  /**\n   * Rejects a stream's builder with the given error (defaulting to a\n   * `StreamCancelledError`), also firing the builder's `onCancel` hook so the\n   * host is told to stop. `onAbort` uses this for the signal path.\n   */\n  private cancelStreamBuilder(requestId: string, error?: Error): void {\n    this.streamConsumers.get(requestId)?.builder.cancel(error);\n  }\n\n  /**\n   * Fire-and-forget host notification that a stream is being cancelled, so\n   * the host can stop generating chunks instead of streaming into the void.\n   */\n  private notifyHostStreamCancelled(requestId: string): void {\n    const record = this.streamConsumers.get(requestId);\n    if (!record) return;\n    this.request<unknown>(record.namespace, ACTIONS.AI.CANCEL, {\n      requestId,\n    }).catch((error: unknown) => {\n      this.logger.warn(\n        `Failed to notify the host that stream \"${requestId}\" was cancelled`,\n        {\n          error: error instanceof Error ? error.message : String(error),\n        },\n      );\n    });\n  }\n\n  /**\n   * Subscribes to a namespaced event. Returns an unsubscribe function.\n   *\n   * The first handler registered for a given event name triggers an\n   * `event.subscribe` request to the host, telling it this mini app now\n   * wants that event's data pushed to it — some hosts only start emitting\n   * an event once they've received this. The subscribe call is\n   * fire-and-forget: a host that doesn't require explicit subscription\n   * simply ignores it.\n   *\n   * With `{ replay: true }`, the handler is immediately invoked with the\n   * last few payloads this client has already seen for that event (a small\n   * bounded buffer, kept per event name), so a handler registered after the\n   * host started emitting still observes the most recent value rather than\n   * only future changes.\n   */\n  onEvent<TPayload = unknown>(\n    event: string,\n    handler: EventHandler<TPayload>,\n    options?: OnEventOptions,\n  ): () => void {\n    const isFirstHandlerForEvent = !this.eventHandlers.has(event);\n    if (isFirstHandlerForEvent) {\n      this.eventHandlers.set(event, new Set());\n      this.request(NAMESPACES.EVENT, ACTIONS.EVENT.SUBSCRIBE, {\n        eventType: event,\n      }).catch((error: unknown) => {\n        this.logger.warn(`Failed to subscribe to event \"${event}\"`, {\n          error: error instanceof Error ? error.message : String(error),\n        });\n      });\n    }\n\n    this.eventHandlers.get(event)?.add(handler as EventHandler);\n\n    if (options?.replay) {\n      for (const payload of this.eventReplayBuffer.get(event) ?? []) {\n        try {\n          handler(payload as TPayload);\n        } catch (error) {\n          this.logger.warn(`Event handler for \"${event}\" threw`, {\n            error: error instanceof Error ? error.message : String(error),\n          });\n        }\n      }\n    }\n\n    return () => {\n      this.eventHandlers.get(event)?.delete(handler as EventHandler);\n    };\n  }\n\n  /**\n   * Records a payload into the bounded per-event replay buffer, dropping the\n   * oldest entry once `EVENT_REPLAY_BUFFER_SIZE` is exceeded.\n   */\n  private bufferEvent(event: string, payload: unknown): void {\n    const buffer = this.eventReplayBuffer.get(event) ?? [];\n    buffer.push(payload);\n    if (buffer.length > EVENT_REPLAY_BUFFER_SIZE) buffer.shift();\n    this.eventReplayBuffer.set(event, buffer);\n  }\n\n  getTraceId(): string {\n    return this.traceId;\n  }\n\n  /**\n   * Namespaces the host confirmed support for. Returns an empty array\n   * before `handshake()` resolves — callers that need to feature-detect\n   * before `initialize()` completes should just wait for `initialize()`.\n   */\n  getCapabilities(): readonly string[] {\n    return this.negotiatedCapabilities ?? [];\n  }\n\n  /**\n   * A point-in-time snapshot of every request this client has made:\n   * totals plus a per-`namespace.action` breakdown of counts, timings,\n   * failures, timeouts, and retries. Safe to call at any time, including\n   * before `start()` (it just reports all zeros).\n   */\n  getMetrics(): RpcMetricsSnapshot {\n    return this.metricsRecorder.snapshot();\n  }\n\n  /**\n   * A read-only view of every request currently awaiting a host reply, for\n   * `MiniAppSdk.debug.snapshot()`.\n   */\n  getPendingRequests(): PendingRequestInfo[] {\n    const now = Date.now();\n    const result: PendingRequestInfo[] = [];\n    for (const [requestId, request] of this.pending) {\n      result.push({\n        requestId,\n        namespace: request.namespace,\n        action: request.action,\n        elapsedMs: now - request.startedAt,\n      });\n    }\n    return result;\n  }\n\n  /** The SDK build version reported to the host during the handshake. */\n  getSdkVersion(): string {\n    return RPC_CLIENT_SDK_VERSION;\n  }\n\n  /** Debug-time view of the transport, for `MiniAppSdk.debug.snapshot()`. */\n  getTransportDebugInfo(): TransportDebugInfo {\n    return this.transport.getDebugInfo?.() ?? { started: this.started };\n  }\n\n  /**\n   * Dispatches a local (SDK-originated) event to subscribers without going\n   * through the transport or the host — used for connection-state\n   * notifications that the host itself cannot deliver because the link is\n   * down. Subscribers register exactly as they would for a host event:\n   * `sdk.on(\"connection.lost\", …)`. Matching the host-event routing, the\n   * subscription fires as `event.subscribe` only when at least one handler\n   * exists, so first registering a listener marks the connection \"live\".\n   */\n  private emitLocalEvent(event: string, payload: unknown): void {\n    this.bufferEvent(event, payload);\n    const handlers = this.eventHandlers.get(event);\n    handlers?.forEach((handler) => {\n      try {\n        handler(payload);\n      } catch (error) {\n        this.logger.warn(`Event handler for \"${event}\" threw`, {\n          error: error instanceof Error ? error.message : String(error),\n        });\n      }\n    });\n  }\n\n  private startHeartbeat(): void {\n    if (!this.heartbeatOptions || this.heartbeatInterval) return;\n\n    const intervalMs =\n      this.heartbeatOptions.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;\n    this.heartbeatInterval = setInterval(() => {\n      void this.maybeSendHeartbeat();\n    }, intervalMs);\n  }\n\n  private stopHeartbeat(): void {\n    if (this.heartbeatInterval) {\n      clearInterval(this.heartbeatInterval);\n      this.heartbeatInterval = null;\n    }\n    this.heartbeatMissedPongs = 0;\n    for (const [requestId, ping] of this.heartbeatPings) {\n      clearTimeout(ping.timer);\n      ping.onPong();\n      this.heartbeatPings.delete(requestId);\n    }\n  }\n\n  private maybeSendHeartbeat(): void {\n    if (!this.started) return;\n    if (this.reconnectInProgress) return;\n\n    const timeoutMs =\n      this.heartbeatOptions?.timeoutMs ?? DEFAULT_HEARTBEAT_TIMEOUT_MS;\n    const maxMissedPongs =\n      this.heartbeatOptions?.maxMissedPongs ?? DEFAULT_MAX_MISSED_PONGS;\n\n    const heartbeatId = `${NAMESPACES.HEARTBEAT}.${ACTIONS.HEARTBEAT.PING}`;\n\n    this.request<unknown>(\n      NAMESPACES.HEARTBEAT,\n      ACTIONS.HEARTBEAT.PING,\n      undefined,\n    )\n      .then(() => {\n        const ping = this.heartbeatPings.get(heartbeatId);\n        if (ping) {\n          clearTimeout(ping.timer);\n          ping.onPong();\n          this.heartbeatPings.delete(heartbeatId);\n        }\n      })\n      .catch(() => {\n        // The per-ping timer below already counted the miss; a request-level\n        // failure (timeout after retries, transport error) only means the\n        // host did not answer, which is what the counter records.\n      });\n\n    this.heartbeatPings.set(heartbeatId, {\n      onPong: () => {\n        this.heartbeatMissedPongs = 0;\n      },\n      timer: setTimeout(() => {\n        this.heartbeatPings.delete(heartbeatId);\n        this.heartbeatMissedPongs += 1;\n        if (this.heartbeatMissedPongs >= maxMissedPongs) {\n          this.handleLostConnection();\n        }\n      }, timeoutMs),\n    });\n  }\n\n  private handleLostConnection(): void {\n    if (!this.started || this.reconnectInProgress) return;\n    this.reconnectInProgress = true;\n\n    this.stopHeartbeat();\n    this.emitLocalEvent(CONNECTION_EVENTS.LOST, {\n      timestamp: Date.now(),\n    });\n\n    void this.reconnect();\n  }\n\n  private async reconnect(): Promise<void> {\n    let attempt = 0;\n    while (this.started) {\n      try {\n        await this.handshake();\n        this.reconnectInProgress = false;\n        this.heartbeatMissedPongs = 0;\n        this.emitLocalEvent(CONNECTION_EVENTS.ESTABLISHED, {\n          timestamp: Date.now(),\n        });\n        return;\n      } catch {\n        const maxAttempts = Math.max(1, this.retryAttempts);\n        if (attempt >= maxAttempts) {\n          this.logger.warn(\n            \"Reconnect failed; giving up after repeated handshake failures\",\n            { attempts: attempt + 1 },\n          );\n          this.reconnectInProgress = false;\n          return;\n        }\n        attempt += 1;\n        await delay(\n          computeBackoffMs(attempt, this.retryDelayMs, this.maxRetryDelayMs),\n        );\n      }\n    }\n  }\n\n  private completeHandshake(\n    ackPayload: unknown,\n    resolvePromise: () => void,\n    rejectPromise: (error: Error) => void,\n  ): void {\n    const ack = (\n      ackPayload && typeof ackPayload === \"object\" ? ackPayload : {}\n    ) as HandshakeAckPayload;\n\n    if (ack.status === \"rejected\") {\n      rejectPromise(\n        new HandshakeError({\n          message: ack.reason ?? \"Host rejected the handshake request\",\n        }),\n      );\n      return;\n    }\n\n    if (\n      ack.protocolVersion &&\n      !majorVersionsMatch(ack.protocolVersion, PROTOCOL_VERSION)\n    ) {\n      rejectPromise(\n        new HandshakeError({\n          message: `Host protocol version \"${ack.protocolVersion}\" is incompatible with this SDK's protocol version \"${PROTOCOL_VERSION}\" (major version mismatch)`,\n        }),\n      );\n      return;\n    }\n\n    if (ack.capabilities) {\n      this.negotiatedCapabilities = SDK_CAPABILITIES.filter((capability) =>\n        ack.capabilities?.includes(capability),\n      );\n      this.logger.debug(\"Negotiated capabilities with host\", {\n        capabilities: this.negotiatedCapabilities,\n      });\n    } else {\n      this.negotiatedCapabilities = [...SDK_CAPABILITIES];\n      this.logger.debug(\n        \"Host did not report capabilities during handshake; assuming full support\",\n        {\n          assumed: this.negotiatedCapabilities,\n        },\n      );\n    }\n\n    resolvePromise();\n    this.startHeartbeat();\n  }\n\n  private sendRequest<T>(\n    namespace: string,\n    action: string,\n    payload?: unknown,\n    signal?: AbortSignal,\n  ): Promise<T> {\n    const message = createMessage(\n      \"request\",\n      namespace,\n      action,\n      this.miniAppId,\n      HOST_TARGET,\n      payload,\n      {\n        traceId: this.traceId,\n      },\n    );\n\n    return new Promise<T>((resolve, reject) => {\n      const cleanupSignal = (): void => {\n        signal?.removeEventListener(\"abort\", handleAbort);\n      };\n\n      const handleAbort = (): void => {\n        if (this.pending.has(message.requestId)) {\n          this.pending.delete(message.requestId);\n        }\n        clearTimeout(timer);\n        cleanupSignal();\n        reject(\n          new RequestCancelledError({\n            namespace,\n            action,\n            cause: signal?.reason,\n          }),\n        );\n      };\n\n      const timer = setTimeout(() => {\n        cleanupSignal();\n        this.pending.delete(message.requestId);\n        reject(\n          new TimeoutError({ namespace, action, timeoutMs: this.timeout }),\n        );\n      }, this.timeout);\n\n      if (signal) {\n        if (signal.aborted) {\n          clearTimeout(timer);\n          reject(\n            new RequestCancelledError({\n              namespace,\n              action,\n              cause: signal.reason,\n            }),\n          );\n          return;\n        }\n        signal.addEventListener(\"abort\", handleAbort, { once: true });\n      }\n\n      this.pending.set(message.requestId, {\n        resolve: (value: unknown) => {\n          cleanupSignal();\n          resolve(value as T);\n        },\n        reject: (error: Error) => {\n          cleanupSignal();\n          reject(error);\n        },\n        timer,\n        namespace,\n        action,\n        startedAt: Date.now(),\n      });\n\n      this.sendOrFail(message, () => {\n        clearTimeout(timer);\n        cleanupSignal();\n        this.pending.delete(message.requestId);\n      });\n    });\n  }\n\n  private sendOrFail(message: PlatformMessage, onFailure: () => void): void {\n    try {\n      this.transport.send(message);\n    } catch (error) {\n      const pending = this.pending.get(message.requestId);\n      onFailure();\n      const err = error instanceof Error ? error : new Error(String(error));\n      if (pending) {\n        clearTimeout(pending.timer);\n        pending.reject(err);\n      }\n    }\n  }\n\n  private handleIncomingMessage(message: PlatformMessage): void {\n    if (message.target !== this.miniAppId && message.target !== \"*\") return;\n\n    if (!hasCompatibleMajorVersion(message)) {\n      this.logger.warn(\n        \"Dropped message with an incompatible protocol major version\",\n        {\n          received: message.gsaProtocolVersion,\n          expected: PROTOCOL_VERSION,\n          namespace: message.namespace,\n          action: message.action,\n        },\n      );\n      return;\n    }\n\n    if (message.type === \"response\" || message.type === \"handshake\") {\n      const pending = this.pending.get(message.requestId);\n      if (!pending) {\n        // A streamed request is normally answered entirely with `stream`\n        // messages, but a host that refuses it up front may answer with a\n        // plain `response` carrying an error. Surface that to the stream.\n        const stream = this.streamConsumers.get(message.requestId)?.builder;\n        if (stream && message.error) {\n          stream.rejectChunk(\n            new ProtocolError({\n              reason: \"host-rejected\",\n              platformError: message.error,\n            }),\n          );\n        }\n        return;\n      }\n\n      clearTimeout(pending.timer);\n      this.pending.delete(message.requestId);\n\n      if (message.error) {\n        pending.reject(\n          new ProtocolError({\n            reason: \"host-rejected\",\n            platformError: message.error,\n          }),\n        );\n      } else {\n        pending.resolve(message.payload);\n      }\n      return;\n    }\n\n    if (message.type === \"stream\") {\n      const stream = this.streamConsumers.get(message.requestId)?.builder;\n      if (!stream) return;\n\n      if (message.error) {\n        stream.rejectChunk(\n          new ProtocolError({\n            reason: \"host-rejected\",\n            platformError: message.error,\n          }),\n        );\n        return;\n      }\n\n      const data =\n        typeof message.payload === \"string\" ||\n        message.payload instanceof Uint8Array\n          ? message.payload\n          : \"\";\n      stream.addChunk({\n        data,\n        index: message.streamIndex ?? 0,\n        total: message.streamTotal,\n        last: message.streamLast ?? false,\n      });\n      return;\n    }\n\n    if (message.type === \"event\") {\n      const key = `${message.namespace}.${message.action}`;\n      this.bufferEvent(key, message.payload);\n      const handlers = this.eventHandlers.get(key);\n      handlers?.forEach((handler) => {\n        handler(message.payload);\n      });\n    }\n  }\n}\n","import { BROADCAST_TARGET, PLATFORM_EVENT_NAME } from \"../constants\";\nimport { TransportError } from \"../errors\";\nimport type { Logger } from \"../logging\";\nimport { noopLogger } from \"../logging\";\nimport type { PlatformMessage } from \"../protocol\";\nimport { isValidPlatformMessage } from \"../protocol\";\nimport type { Transport, TransportDebugInfo } from \"./transport\";\n\nexport interface DefaultTransportOptions {\n  logger?: Logger;\n  /**\n   * The exact origin (e.g. `https://shell.example.gov`) this transport is\n   * allowed to talk to. When set, every inbound message from any other\n   * origin is dropped from the moment `start()` is called, and every\n   * outbound message is sent to this origin instead of `'*'`.\n   *\n   * When omitted (the default), the transport trusts nothing about the\n   * host's origin ahead of time — it sends the first message (the\n   * handshake) with target origin `'*'`, since there is no way to know the\n   * host's origin before hearing from it, then learns and pins the origin\n   * of the first valid message it receives. Every message after that must\n   * come from that same pinned origin, and every message sent after that\n   * point goes there directly instead of broadcasting to `'*'`.\n   */\n  allowedOrigin?: string;\n}\n\n/**\n * The SDK's built-in `Transport` implementation. Sends via\n * `window.parent.postMessage` and listens on two inbound channels:\n *\n *  1. The standard `message` event — the primary channel for a browser\n *     iframe host, or a Flutter WebView that intercepts and re-dispatches\n *     `postMessage`.\n *  2. A `gov-platform-event` `CustomEvent` — a secondary channel for hosts\n *     that find it easier to dispatch a custom event than to synthesize a\n *     `MessageEvent`. `CustomEvent`s dispatched within the same window\n *     don't carry a meaningful cross-origin `origin` field, so the origin\n *     checks below only apply to the `message` channel.\n *\n * This is intentionally the *only* file in the SDK that touches `window`.\n */\nexport class DefaultTransport implements Transport {\n  private readonly logger: Logger;\n  private messageListener: ((event: MessageEvent) => void) | null = null;\n  private customEventListener: ((event: Event) => void) | null = null;\n  private started = false;\n\n  /** The origin outbound messages are sent to, and inbound messages are checked against once set. */\n  private pinnedOrigin: string | null;\n  /** True when `allowedOrigin` was explicitly configured — the pinned origin can never change in that case. */\n  private readonly originLocked: boolean;\n\n  constructor(options: DefaultTransportOptions = {}) {\n    this.logger = options.logger ?? noopLogger;\n    this.pinnedOrigin = options.allowedOrigin ?? null;\n    this.originLocked = options.allowedOrigin !== undefined;\n  }\n\n  start(onMessage: (message: PlatformMessage) => void): void {\n    if (typeof window === \"undefined\") {\n      throw new TransportError({\n        code: \"TRANSPORT_NOT_STARTED\",\n        message:\n          \"DefaultTransport requires a `window` global (browser or WebView environment).\",\n      });\n    }\n\n    this.messageListener = (event: MessageEvent) => {\n      if (!this.isFromAllowedOrigin(event.origin)) {\n        this.logger.warn(\"Dropped message from an unexpected origin\", {\n          receivedOrigin: event.origin,\n          pinnedOrigin: this.pinnedOrigin,\n        });\n        return;\n      }\n      if (!isValidPlatformMessage(event.data)) return;\n\n      this.pinOriginIfUnset(event.origin);\n      onMessage(event.data);\n    };\n    window.addEventListener(\"message\", this.messageListener);\n\n    this.customEventListener = (event: Event) => {\n      const detail = (event as CustomEvent<unknown>).detail;\n      if (!isValidPlatformMessage(detail)) return;\n      onMessage(detail);\n    };\n    window.addEventListener(PLATFORM_EVENT_NAME, this.customEventListener);\n\n    this.logger.debug(\"DefaultTransport started\", {\n      allowedOrigin: this.pinnedOrigin ?? \"(learned on first message)\",\n    });\n    this.started = true;\n  }\n\n  stop(): void {\n    if (typeof window === \"undefined\") return;\n\n    if (this.messageListener) {\n      window.removeEventListener(\"message\", this.messageListener);\n      this.messageListener = null;\n    }\n    if (this.customEventListener) {\n      window.removeEventListener(PLATFORM_EVENT_NAME, this.customEventListener);\n      this.customEventListener = null;\n    }\n\n    this.started = false;\n    this.logger.debug(\"DefaultTransport stopped\");\n  }\n\n  getDebugInfo(): TransportDebugInfo {\n    return {\n      started: this.started,\n      pinnedOrigin: this.pinnedOrigin,\n    };\n  }\n\n  send(message: PlatformMessage): void {\n    if (typeof window === \"undefined\") {\n      throw new TransportError({\n        code: \"TRANSPORT_NOT_STARTED\",\n        message:\n          \"DefaultTransport requires a `window` global (browser or WebView environment).\",\n      });\n    }\n\n    const targetOrigin = this.pinnedOrigin ?? BROADCAST_TARGET;\n\n    try {\n      window.parent.postMessage(message, targetOrigin);\n    } catch (cause) {\n      throw new TransportError({\n        message: `Failed to send message \"${message.namespace}.${message.action}\"`,\n        cause,\n      });\n    }\n  }\n\n  private isFromAllowedOrigin(origin: string): boolean {\n    if (this.pinnedOrigin === null) return true;\n    if (this.pinnedOrigin === \"*\") return true;\n    return origin === this.pinnedOrigin;\n  }\n\n  private pinOriginIfUnset(origin: string): void {\n    if (this.originLocked || this.pinnedOrigin !== null) return;\n    this.pinnedOrigin = origin;\n    this.logger.debug(\"Pinned host origin from first message\", { origin });\n  }\n}\n","import {\n  ACTIONS,\n  HOST_DESCRIPTOR_GLOBAL_KEY,\n  NAMESPACES,\n  PROTOCOL_VERSION,\n  SDK_GLOBAL_KEY,\n} from \"../constants\";\nimport { SdkError } from \"../errors\";\nimport type { Logger } from \"../logging\";\nimport { ConsoleLogger, noopLogger } from \"../logging\";\nimport type {\n  AppearanceModuleHandle,\n  ModuleFactory,\n  ResolvedPlatformResponse,\n} from \"../modules\";\nimport {\n  APPEARANCE_EVENTS,\n  createApiModule,\n  createAppearanceModule,\n  createAuthModule,\n  createChatModule,\n  createConfigModule,\n  createDeviceModule,\n  createFlagsModule,\n  createHttpModule,\n  createLinksModule,\n  createNavigationModule,\n  createNotificationsModule,\n  createPermissionsModule,\n  createPlatformModule,\n  createStorageModule,\n  ModuleRegistry,\n} from \"../modules\";\nimport type { RpcMetricsSnapshot, Tracer } from \"../observability\";\nimport type { RpcMiddleware, RpcRequestOptions } from \"../rpc\";\nimport { RpcClient } from \"../rpc\";\nimport type { Transport } from \"../transport\";\nimport { DefaultTransport } from \"../transport\";\nimport type {\n  ApiSdkModule,\n  AppearanceSdkModule,\n  AuthSdkModule,\n  ChatSdkModule,\n  ConfigSdkModule,\n  DeviceSdkModuleWithGuards,\n  EventHandler,\n  FlagsSdkModule,\n  HostDescriptor,\n  HttpSdkModule,\n  LinksSdkModule,\n  MiniAppSdkInterface,\n  MiniAppSdkOptions,\n  NavigationSdkModule,\n  NotificationsSdkModule,\n  PermissionsSdkModule,\n  PlatformSdkModule,\n  PlatformTypeLiteral,\n  SdkDebug,\n  SdkDebugSnapshot,\n  StorageSdkModule,\n} from \"../types\";\nimport type {\n  OnEventOptions,\n  PlatformTypeResponse,\n  SdkEventMap,\n} from \"../types/common.types\";\nimport { delay } from \"../utils\";\n\n/**\n * Extra, internal-only construction knobs. Deliberately **not** part of\n * `MiniAppSdkOptions` (the public, vendor-facing options type) — a vendor\n * mini-app developer configures `miniAppId`/`timeout`/`retryAttempts` the\n * same way they always have. `transport`, `logger`, `allowedOrigin`, and\n * `tracer` are for host SDKs and internal callers: `transport` to inject a\n * non-default delivery mechanism, `logger` to wire up real logging,\n * `allowedOrigin` to pin `DefaultTransport` to a known host origin from the\n * start instead of learning it from the first message (see\n * `transport/DefaultTransport.ts`), and `tracer` to bridge RPC spans into\n * a host's existing tracing setup (OpenTelemetry, ...). `allowedOrigin` is\n * ignored if a custom `transport` is also provided — origin handling is that\n * transport's own concern at that point.\n */\nexport interface MiniAppSdkDependencies {\n  transport?: Transport;\n  logger?: Logger;\n  allowedOrigin?: string;\n  tracer?: Tracer;\n}\n\n/** Upper bound on appearance hydration during `initialize()`. */\nconst APPEARANCE_HYDRATION_BUDGET_MS = 1200;\n\n/**\n * The SDK's composition root. `MiniAppSdk`'s only responsibilities are:\n *  1. composing the `RpcClient`, the `ModuleRegistry`, and all domain\n *     modules,\n *  2. owning instance lifecycle (`initialize` / `destroy`),\n *  3. exposing the public API surface (`MiniAppSdkInterface`).\n *\n * It contains no RPC logic (that's `RpcClient`), no transport wiring\n * (that's `Transport`/`DefaultTransport`), and no per-module business logic\n * (that's `modules/*`). If you're about to add a `namespace`/`action`\n * string or a `.request()` call directly in this file, it almost certainly\n * belongs in a module file instead.\n */\nexport class MiniAppSdk implements MiniAppSdkInterface {\n  readonly miniAppId: string;\n  readonly version = PROTOCOL_VERSION;\n  readonly traceId: string;\n\n  readonly hostDescriptor: HostDescriptor | null;\n\n  readonly auth: AuthSdkModule;\n  readonly permissions: PermissionsSdkModule;\n  readonly flags: FlagsSdkModule;\n  readonly config: ConfigSdkModule;\n  readonly navigation: NavigationSdkModule;\n  readonly api: ApiSdkModule;\n  readonly storage: StorageSdkModule;\n  readonly platform: PlatformSdkModule;\n  readonly device: DeviceSdkModuleWithGuards;\n  readonly http: HttpSdkModule;\n  readonly ai: ChatSdkModule;\n  readonly appearance: AppearanceSdkModule;\n  readonly notifications: NotificationsSdkModule;\n  readonly links: LinksSdkModule;\n  readonly debug: SdkDebug;\n\n  private readonly rpc: RpcClient;\n  private readonly logger: Logger;\n  private readonly registry = new ModuleRegistry();\n  private readonly applyPlatformResponse: (\n    raw: unknown,\n  ) => ResolvedPlatformResponse;\n  private readonly appearanceHandle: AppearanceModuleHandle;\n  private readonly appearanceUnsubscribers: Array<() => void> = [];\n\n  private initialized = false;\n  private destroyed = false;\n  private initializePromise: Promise<void> | null = null;\n\n  constructor(\n    options: MiniAppSdkOptions,\n    dependencies: MiniAppSdkDependencies = {},\n  ) {\n    this.miniAppId = options.miniAppId;\n    const devMode = MiniAppSdk.resolveDevMode(options);\n    this.logger =\n      dependencies.logger ??\n      (options.logLevel !== undefined || devMode\n        ? new ConsoleLogger({ minLevel: options.logLevel })\n        : noopLogger);\n\n    this.hostDescriptor =\n      typeof window !== \"undefined\"\n        ? (((window as unknown as Record<string, unknown>)[\n            HOST_DESCRIPTOR_GLOBAL_KEY\n          ] as HostDescriptor | undefined) ?? null)\n        : null;\n\n    const transport =\n      dependencies.transport ??\n      new DefaultTransport({\n        logger: this.logger,\n        allowedOrigin: dependencies.allowedOrigin,\n      });\n    this.rpc = new RpcClient(transport, {\n      miniAppId: options.miniAppId,\n      timeout: options.timeout,\n      retryAttempts: options.retryAttempts,\n      retryDelayMs: options.retryDelayMs,\n      maxRetryDelayMs: options.maxRetryDelayMs,\n      logger: this.logger,\n      devMode,\n      heartbeat: options.heartbeat,\n      metrics: options.metrics,\n      tracer: dependencies.tracer,\n    });\n    this.traceId = this.rpc.getTraceId();\n\n    // The built-in modules are registered by name instead of being new'd\n    // directly, so `registerModule`/`getModule` work uniformly for built-ins\n    // and anything a host or vendor adds later. `platform` is registered\n    // separately below since its factory needs a slightly different shape\n    // (see `createPlatformModule`'s doc comment).\n    this.registry.register(NAMESPACES.AUTH, createAuthModule);\n    this.registry.register(NAMESPACES.PERMISSIONS, createPermissionsModule);\n    this.registry.register(NAMESPACES.FLAGS, createFlagsModule);\n    this.registry.register(NAMESPACES.CONFIG, createConfigModule);\n    this.registry.register(NAMESPACES.NAVIGATION, createNavigationModule);\n    this.registry.register(NAMESPACES.STORAGE, createStorageModule);\n    this.registry.register(NAMESPACES.DEVICE, createDeviceModule);\n    this.registry.register(NAMESPACES.API, createApiModule);\n    this.registry.register(NAMESPACES.HTTP, createHttpModule);\n    this.registry.register(NAMESPACES.AI, createChatModule);\n    this.registry.register(NAMESPACES.NOTIFICATIONS, createNotificationsModule);\n    this.registry.register(NAMESPACES.LINKS, createLinksModule);\n    this.registry.build(this.rpc);\n\n    this.auth = this.requireModule<AuthSdkModule>(NAMESPACES.AUTH);\n    this.permissions = this.requireModule<PermissionsSdkModule>(\n      NAMESPACES.PERMISSIONS,\n    );\n    this.flags = this.requireModule<FlagsSdkModule>(NAMESPACES.FLAGS);\n    this.config = this.requireModule<ConfigSdkModule>(NAMESPACES.CONFIG);\n    this.navigation = this.requireModule<NavigationSdkModule>(\n      NAMESPACES.NAVIGATION,\n    );\n    this.storage = this.requireModule<StorageSdkModule>(NAMESPACES.STORAGE);\n    this.device = this.requireModule<DeviceSdkModuleWithGuards>(\n      NAMESPACES.DEVICE,\n    );\n    this.api = this.requireModule<ApiSdkModule>(NAMESPACES.API);\n    this.http = this.requireModule<HttpSdkModule>(NAMESPACES.HTTP);\n    this.ai = this.requireModule<ChatSdkModule>(NAMESPACES.AI);\n    this.notifications = this.requireModule<NotificationsSdkModule>(\n      NAMESPACES.NOTIFICATIONS,\n    );\n    this.links = this.requireModule<LinksSdkModule>(NAMESPACES.LINKS);\n\n    const platformHandle = createPlatformModule(\"web\");\n    this.platform = platformHandle.module;\n    this.applyPlatformResponse = platformHandle.applyResponse;\n\n    this.appearanceHandle = createAppearanceModule(this.rpc);\n    this.appearance = this.appearanceHandle.module;\n\n    this.debug = {\n      snapshot: (): SdkDebugSnapshot => ({\n        sdkVersion: this.rpc.getSdkVersion(),\n        protocolVersion: this.version,\n        miniAppId: this.miniAppId,\n        traceId: this.traceId,\n        platformType: this.platform.type,\n        capabilities: this.capabilities,\n        status: this.destroyed\n          ? \"destroyed\"\n          : this.initialized\n            ? \"ready\"\n            : \"initializing\",\n        transport: this.rpc.getTransportDebugInfo(),\n        metrics: this.getMetrics(),\n        pendingRequests: this.rpc.getPendingRequests(),\n        registeredModules: this.registry.list(),\n      }),\n    };\n\n    if (typeof globalThis !== \"undefined\") {\n      (globalThis as unknown as Record<string, unknown>)[SDK_GLOBAL_KEY] = this;\n    }\n  }\n\n  /**\n   * Resolves whether dev-mode warnings/logging should be enabled. An explicit\n   * `options.devMode` always wins; otherwise it's inferred from the bundle's\n   * `NODE_ENV`, defaulting to off when the environment variable is absent.\n   */\n  private static resolveDevMode(options: MiniAppSdkOptions): boolean {\n    if (options.devMode !== undefined) return options.devMode;\n    const env = (\n      globalThis as unknown as {\n        process?: { env?: Record<string, string | undefined> };\n      }\n    ).process?.env;\n    return env?.NODE_ENV !== undefined && env.NODE_ENV !== \"production\";\n  }\n\n  /**\n   * Retrieves a module by namespace, throwing if it hasn't been registered.\n   * Every module assigned in the constructor is registered just above this\n   * helper's call sites, so reaching this code with a missing module is a\n   * programmer error, not a runtime condition.\n   */\n  private requireModule<T>(name: string): T {\n    const module = this.registry.get<T>(name);\n    if (!module) {\n      throw new SdkError({\n        code: \"SDK_NOT_INITIALIZED\",\n        message: `Module \"${name}\" was not registered with the SDK.`,\n      });\n    }\n    return module;\n  }\n\n  /**\n   * Namespaces the host confirmed support for during the handshake. Empty\n   * until `initialize()` resolves.\n   */\n  get capabilities(): readonly string[] {\n    return this.rpc.getCapabilities();\n  }\n\n  /**\n   * Starts the transport, performs the handshake, and resolves the current\n   * platform type. Idempotent and concurrency-safe: calling `initialize()`\n   * multiple times (including while a prior call is still in flight)\n   * returns the same underlying promise instead of re-running the sequence.\n   */\n  async initialize(): Promise<void> {\n    if (this.destroyed) {\n      throw new SdkError({\n        code: \"SDK_ALREADY_DESTROYED\",\n        message: `Cannot initialize MiniAppSdk(\"${this.miniAppId}\") — this instance has already been destroyed.`,\n      });\n    }\n    if (this.initialized) return;\n    if (this.initializePromise) return this.initializePromise;\n\n    this.initializePromise = this.runInitializeSequence();\n    try {\n      await this.initializePromise;\n    } finally {\n      this.initializePromise = null;\n    }\n  }\n\n  private async runInitializeSequence(): Promise<void> {\n    this.rpc.start();\n    await this.rpc.handshake();\n\n    // `platform.getType` answers in one of two shapes — a bare\n    // `\"web\"`/`\"flutter\"` string, or an object that also carries the host's\n    // appearance hint. `applyResponse` accepts both and hands back whichever\n    // hint rode along.\n    const raw = await this.rpc.request<\n      PlatformTypeLiteral | PlatformTypeResponse\n    >(NAMESPACES.PLATFORM, ACTIONS.PLATFORM.GET_TYPE);\n    const { type: platformType, appearance: appearanceHint } =\n      this.applyPlatformResponse(raw);\n\n    // Host changes must be observed on every shell, including the Flutter\n    // one that delivers appearance via the hint and never negotiates the\n    // `appearance` namespace — so this is not gated on capabilities.\n    this.subscribeToAppearanceEvents();\n\n    if (appearanceHint) {\n      // The hint already carries the host's current locale/theme, so the\n      // `appearance.*` round trips below would only re-fetch what we have.\n      this.appearanceHandle.applyHint(appearanceHint);\n    } else if (this.capabilities.includes(NAMESPACES.APPEARANCE)) {\n      await this.hydrateAppearance();\n    } else {\n      this.logger.debug(\n        \"Host sent no appearance hint and did not negotiate appearance; using defaults\",\n        {\n          capabilities: this.capabilities,\n        },\n      );\n    }\n\n    this.initialized = true;\n    this.logger.info(`MiniAppSdk(\"${this.miniAppId}\") initialized`, {\n      platformType,\n    });\n  }\n\n  private subscribeToAppearanceEvents(): void {\n    this.appearanceUnsubscribers.push(\n      this.on(APPEARANCE_EVENTS.LOCALE_CHANGED, (payload) => {\n        this.appearanceHandle.applyHint({ locale: payload });\n      }),\n      this.on(APPEARANCE_EVENTS.THEME_CHANGED, (payload) => {\n        this.appearanceHandle.applyHint({ theme: payload });\n      }),\n    );\n  }\n\n  /**\n   * Fallback for hosts that implement the `appearance` namespace but don't\n   * put the hint on `platform.getType` — i.e. any shell built against an\n   * earlier SDK. Bounded budget: appearance is additive and must never block\n   * first paint. If the host is slow or doesn't answer, initialize() still\n   * resolves and the app falls back to the store defaults.\n   */\n  private async hydrateAppearance(): Promise<void> {\n    const hydration = Promise.all([\n      this.appearance.getLocale(),\n      this.appearance.getTheme(),\n    ]).catch(() => undefined);\n    await Promise.race([hydration, delay(APPEARANCE_HYDRATION_BUDGET_MS)]);\n  }\n\n  /**\n   * Tears down the transport and clears all pending state. Safe to call\n   * more than once. After `destroy()`, this instance cannot be\n   * re-initialized — construct a new `MiniAppSdk` instead.\n   */\n  destroy(): void {\n    if (this.destroyed) return;\n    this.rpc.stop();\n    for (const unsub of this.appearanceUnsubscribers) unsub();\n    this.appearanceUnsubscribers.length = 0;\n    this.initialized = false;\n    this.destroyed = true;\n    if (\n      typeof globalThis !== \"undefined\" &&\n      (globalThis as unknown as Record<string, unknown>)[SDK_GLOBAL_KEY] ===\n        this\n    ) {\n      delete (globalThis as unknown as Record<string, unknown>)[SDK_GLOBAL_KEY];\n    }\n    this.logger.info(`MiniAppSdk(\"${this.miniAppId}\") destroyed`);\n  }\n\n  /**\n   * Subscribes to a host-emitted event. Returns an unsubscribe function.\n   * Delegates entirely to `RpcClient`; the only value this method adds over\n   * calling `rpc.onEvent` directly is that it's part of the stable public\n   * surface consumers already depend on. Known events (see `SdkEventMap`)\n   * get typed payloads; host-defined events outside the map remain usable\n   * through the `string` overload.\n   */\n  on<K extends keyof SdkEventMap>(\n    event: K,\n    handler: (payload: SdkEventMap[K]) => void,\n    options?: OnEventOptions,\n  ): () => void;\n  on(\n    event: string,\n    handler: EventHandler,\n    options?: OnEventOptions,\n  ): () => void;\n  on(\n    event: string,\n    handler: EventHandler,\n    options?: OnEventOptions,\n  ): () => void {\n    return this.rpc.onEvent(event, handler, options);\n  }\n\n  /** {@inheritdoc} */\n  request<T>(\n    namespace: string,\n    action: string,\n    payload?: unknown,\n    options?: RpcRequestOptions,\n  ): Promise<T> {\n    return this.rpc.request<T>(namespace, action, payload, options);\n  }\n\n  /** {@inheritdoc} */\n  emit<K extends keyof SdkEventMap>(event: K, data: SdkEventMap[K]): void;\n  emit(event: string, data?: unknown): void;\n  emit(event: string, data?: unknown): void {\n    this.rpc\n      .request(NAMESPACES.EVENT, ACTIONS.EVENT.EMIT, { event, data })\n      .catch((error: unknown) => {\n        this.logger.warn(`Emit event \"${event}\" failed`, {\n          error: error instanceof Error ? error.message : String(error),\n        });\n      });\n  }\n\n  /**\n   * Registers a middleware that wraps every request made through any\n   * module from this point forward — logging, auth-token refresh, request\n   * shaping, custom metrics, whatever a host or vendor needs. See\n   * `rpc/middleware.ts` for the execution model.\n   */\n  use(middleware: RpcMiddleware): void {\n    this.rpc.use(middleware);\n  }\n\n  /**\n   * A point-in-time snapshot of every request this instance has made:\n   * totals plus a per-`namespace.action` breakdown of counts, timings,\n   * failures, timeouts, and retries.\n   */\n  getMetrics(): RpcMetricsSnapshot {\n    return this.rpc.getMetrics();\n  }\n\n  /**\n   * Adds a module beyond the built-in ones — for a host-specific capability\n   * or a vendor's own namespace — without needing to fork the SDK. The\n   * factory receives the same `RpcClient` every built-in module uses, so a\n   * custom module gets retry, timeout, and middleware behavior for free.\n   * Retrieve it later with `getModule()`.\n   *\n   * ```ts\n   * sdk.registerModule('payments', (rpc) => ({\n   *   charge: (amount: number) => rpc.request('payments', 'charge', { amount }),\n   * }));\n   * const payments = sdk.getModule<{ charge(amount: number): Promise<void> }>('payments');\n   * ```\n   */\n  registerModule<T>(name: string, factory: ModuleFactory<T>): void {\n    this.registry.register(name, factory);\n    this.registry.build(this.rpc);\n  }\n\n  /** Retrieves a module registered via `registerModule()` (or any built-in module, by its namespace name). */\n  getModule<T>(name: string): T | undefined {\n    return this.registry.get<T>(name);\n  }\n}\n","import { MiniAppSdk } from \"./client\";\nimport { SdkError } from \"./errors\";\nimport type { MiniAppSdkOptions } from \"./types\";\n\nexport type { MiniAppSdkDependencies } from \"./client\";\nexport { MiniAppSdk } from \"./client\";\nexport {\n  CONNECTION_EVENTS,\n  HTTP_EVENTS,\n  LINKS_EVENTS,\n  MESSAGE_CHANNEL,\n  NAVIGATION_EVENTS,\n  NOTIFICATIONS_EVENTS,\n  PLATFORM_EVENT_NAME,\n  PROTOCOL_VERSION,\n} from \"./constants\";\nexport type {\n  RequestCancelledErrorOptions,\n  SdkErrorCode,\n  SdkErrorOptions,\n} from \"./errors\";\nexport {\n  HttpClientError,\n  HttpServerError,\n  RequestCancelledError,\n  SdkError,\n  StreamCancelledError,\n} from \"./errors\";\nexport type { ConsoleLoggerOptions, Logger } from \"./logging\";\nexport { ConsoleLogger, NoopLogger } from \"./logging\";\nexport type { AppearanceModuleHandle, ModuleFactory } from \"./modules\";\nexport { ChatMessages } from \"./modules\";\nexport type {\n  ActionMetrics,\n  DurationPercentiles,\n  RpcMetricsOptions,\n  RpcMetricsSnapshot,\n  Span,\n  Tracer,\n} from \"./observability\";\nexport { NoopSpan, noopTracer } from \"./observability\";\nexport type {\n  MessageType,\n  PlatformError,\n  PlatformMessage,\n} from \"./protocol\";\nexport type {\n  RpcMiddleware,\n  RpcMiddlewareContext,\n  RpcNext,\n  RpcRequestOptions,\n  RpcStreamOptions,\n} from \"./rpc\";\nexport { StreamBuilder } from \"./stream\";\nexport type { Transport, TransportDebugInfo } from \"./transport\";\nexport type {\n  ApiRequestParams,\n  ApiResult,\n  ApiSdkModule,\n  AppearanceSdkModule,\n  AppearanceState,\n  AppearanceType,\n  AuthSdkModule,\n  ChatMessage,\n  ChatRequestOptions,\n  ChatSdkModule,\n  ConfigSdkModule,\n  DeviceAction,\n  DeviceBiometricOptions,\n  DeviceBiometricResult,\n  DeviceCameraResult,\n  DeviceExtraOptions,\n  DeviceFileOptions,\n  DeviceFileResult,\n  DeviceGalleryResult,\n  DeviceInfoResult,\n  DeviceLocationResult,\n  DeviceNetworkResult,\n  DeviceNotificationResult,\n  DeviceNotificationsOptions,\n  DevicePermissionBaseResponse,\n  DevicePermissionStatus,\n  DeviceSdkModule,\n  DeviceSdkModuleWithGuards,\n  Direction,\n  EventHandler,\n  FlagsSdkModule,\n  Headers,\n  HeartbeatOptions,\n  HostDescriptor,\n  HttpBodyRequest,\n  HttpDeleteParams,\n  HttpGetParams,\n  HttpMethod,\n  HttpPatchParams,\n  HttpPostParams,\n  HttpProgress,\n  HttpPutParams,\n  HttpQueryRequest,\n  HttpRequestBase,\n  HttpResult,\n  HttpSdkModule,\n  HttpUploadOptions,\n  LinksOpenedEvent,\n  LinksOpenOptions,\n  LinksSdkModule,\n  LocaleState,\n  MiniAppSdkInterface,\n  MiniAppSdkOptions,\n  ModelCompletionOptions,\n  NavigationRouterResult,\n  NavigationRouterSdkModule,\n  NavigationRouterSkdModule,\n  NavigationSdkModule,\n  NavigationState,\n  NavigationTarget,\n  NotificationOpenEvent,\n  NotificationsRegisterOptions,\n  NotificationsRegisterResult,\n  NotificationsSdkModule,\n  OnEventOptions,\n  PendingRequestInfo,\n  PermissionsSdkModule,\n  PlatformSdkModule,\n  PlatformTypeLiteral,\n  PlatformTypeResponse,\n  PlatformTypes,\n  PlatformUser,\n  Query,\n  SdkDebug,\n  SdkDebugSnapshot,\n  SdkEventMap,\n  SdkStatus,\n  StorageSdkModule,\n  StorageSetOptions,\n  StreamChunk,\n  StreamError,\n  ThemeMode,\n  ThemePreference,\n  ThemeState,\n} from \"./types\";\n\n/**\n * Module-scoped \"active instance\" used only by the `createMiniAppSdk` /\n * `getMiniAppSdk` / `initMiniAppSdk` convenience trio below, for\n * consumers who want a single implicit SDK instance instead of managing\n * their own reference. This is a small, explicit, single-purpose piece of\n * state — not a hidden global — and is entirely separate from the\n * `cdn.ts` multi-instance registry, which exists for a different\n * consumer (the `<script>`-tag/IIFE build) and is intentionally not\n * mixed with this one.\n */\nlet activeInstance: MiniAppSdk | null = null;\n\n/** Constructs a `MiniAppSdk` without initializing it. Call `.initialize()` yourself. */\nexport function createMiniAppSdk(options: MiniAppSdkOptions): MiniAppSdk {\n  return new MiniAppSdk(options);\n}\n\n/** Returns the instance created by the most recent `initMiniAppSdk()` call. */\nexport function getMiniAppSdk(): MiniAppSdk {\n  if (!activeInstance) {\n    throw new SdkError({\n      code: \"SDK_NOT_INITIALIZED\",\n      message: \"Mini App SDK not initialized. Call initMiniAppSdk() first.\",\n    });\n  }\n  return activeInstance;\n}\n\n/** Constructs, initializes, and registers a `MiniAppSdk` as the active instance. */\nexport async function initMiniAppSdk(\n  options: MiniAppSdkOptions,\n): Promise<MiniAppSdk> {\n  const sdk = new MiniAppSdk(options);\n  await sdk.initialize();\n  activeInstance = sdk;\n  return sdk;\n}\n"],"mappings":";AAKO,IAAM,aAAa;AAAA,EACxB,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,SAAS;AAAA,EACT,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,IAAI;AAAA,EACJ,eAAe;AAAA,EACf,OAAO;AAAA,EACP,OAAO;AAAA,EACP,WAAW;AAAA,EACX,WAAW;AACb;AAWO,IAAM,mBAA6B;AAAA,EACxC,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AACb;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