{"version":3,"file":"extensions.mjs","sources":["../../../src/room/extensions.ts"],"sourcesContent":["import type {\n  DataPacket,\n  Encryption_Type,\n  ParticipantInfo,\n  PublishDataTrackResponse,\n  Room as RoomModel,\n  Transcription as TranscriptionModel,\n} from '@livekit/protocol';\nimport type { BaseE2EEManager } from '../e2ee/E2eeManager';\nimport type { FrameMetadataOptions } from '../frameMetadata/FrameMetadataManager';\nimport type { StructuredLogger } from '../logger';\nimport type { CoreRoom } from './CoreRoom';\nimport type RTCEngine from './RTCEngine';\nimport type { ByteStreamWriter } from './data-stream/outgoing/StreamWriter';\nimport type { VideoPublisher } from './participant/LocalParticipant';\nimport type RemoteParticipant from './participant/RemoteParticipant';\nimport type { StreamBytesOptions } from './types';\n\n/**\n * A feature that `createRoom(options, [...])` (or the full `Room`) installs on a room. The\n * methods returned from `install` are copied onto the room (`room`) and its local participant\n * (`local`) under the same names the full SDK uses, so code moves between the light and full\n * builds unchanged.\n *\n * `install` runs synchronously right after the room is constructed, before any user code, so\n * handlers registered there are in place before `connect()`.\n * @experimental\n */\nexport interface RoomExtension<RoomApi = {}, LocalParticipantApi = {}> {\n  readonly key: symbol;\n  /** Hard dependencies. They install first; an instance the app lists explicitly wins over them. */\n  readonly requires?: readonly RoomExtension<any, any>[];\n  install(room: CoreRoom, ctx: ExtensionContext): ExtensionResult<RoomApi, LocalParticipantApi>;\n}\n\n/**\n * What an extension contributes to the engine.\n * @experimental\n */\nexport interface EngineHooks {\n  /**\n   * Runs once every extension of the list is installed, with the current engine, and again\n   * whenever the room replaces it (after a close). The room's own engine listeners are registered\n   * first, so a listener on the same engine event sees room state already updated.\n   */\n  onEngineCreated?(engine: RTCEngine): void;\n}\n\n/**\n * What an extension contributes to the connection lifecycle.\n * @experimental\n */\nexport interface ConnectionHooks {\n  /**\n   * Runs at the start of every disconnect, including one that reaches an already disconnected\n   * room, before the room emits `RoomEvent.Disconnected`.\n   */\n  onDisconnect?(): void;\n}\n\n/**\n * What an extension contributes to remote participant bookkeeping.\n * @experimental\n */\nexport interface ParticipantHooks {\n  /** Runs after the room creates a remote participant from a `ParticipantInfo`. */\n  onParticipantCreated?(participant: RemoteParticipant, info: ParticipantInfo): void;\n  /** Runs after the room applied a participant update (join, update, reconnect). */\n  onParticipantUpdates?(infos: ParticipantInfo[]): void;\n}\n\n/**\n * An extension that owns `DataPacket` oneof cases. A second owner of a case throws at install.\n * @experimental\n */\nexport interface DataPacketOwner {\n  dataPackets?: { [C in DataPacketCase]?: DataPacketHandler<C> };\n}\n\n/**\n * An extension that contributes to the sync state the room sends on resume.\n * @experimental\n */\nexport interface SyncStateProvider {\n  /** Local data track publications. */\n  syncState?(): PublishDataTrackResponse[];\n}\n\n/**\n * An extension that adds methods to the room, copied onto it under the SDK's method names.\n * @experimental\n */\nexport interface RoomApiProvider<RoomApi = {}> {\n  room: RoomApi;\n}\n\n/**\n * An extension that adds methods to the local participant, copied onto it.\n * @experimental\n */\nexport interface LocalParticipantApiProvider<LocalParticipantApi = {}> {\n  localParticipant: LocalParticipantApi;\n}\n\n/**\n * An extension with something to release.\n * @experimental\n */\nexport interface Disposable {\n  /** Called from `Room.dispose()`, in reverse install order. Must be synchronous. */\n  dispose(): void;\n}\n\n/**\n * What `install` returns: the APIs plus every contribution to core an extension can opt into,\n * all optional. An extension declares the narrower type it uses, such as\n * `RoomApiProvider<RpcRoomApi> & LocalParticipantApiProvider<RpcLocalParticipantApi> & DataPacketOwner`, so a missing\n * API or an undeclared contribution is a type error. Extra members are not copied anywhere;\n * dependent extensions read them through `ctx.get(extension)`. The room's own typing\n * (`ExtensionApis`) comes from the `RoomExtension<RoomApi, LocalParticipantApi>` generics, which each\n * extension pins with `satisfies`.\n * @experimental\n */\nexport type ExtensionResult<RoomApi = {}, LocalParticipantApi = {}> = Partial<\n  RoomApiProvider<RoomApi> & LocalParticipantApiProvider<LocalParticipantApi> & Disposable\n> &\n  EngineHooks &\n  ConnectionHooks &\n  ParticipantHooks &\n  DataPacketOwner &\n  Partial<CoreSlots> &\n  SyncStateProvider;\n\n/** @experimental */\nexport type DataPacketHandler<C extends DataPacketCase> = (\n  value: DataPacketValue<C>,\n  packet: DataPacket,\n  encryptionType: Encryption_Type,\n  participant: RemoteParticipant | undefined,\n) => void;\n\n/**\n * The values core reads from extensions. Core copies them off every install result into one\n * store that it and the local participant read; `ctx.slot()` reads it too. Adding one is a\n * member here, its key in `SLOT_KEYS`, and the read in core.\n * @experimental\n */\nexport interface CoreSlots {\n  /** The E2EE manager `RTCEngine` and the publish path encrypt through (`e2ee`). */\n  e2eeManager: BaseE2EEManager;\n  /**\n   * The frame metadata options the engine's sender transform, the join capability and\n   * `publishTrack` read (`frameMetadata`).\n   */\n  frameMetadataOptions: FrameMetadataOptions;\n  /** Opens an outgoing byte stream (`dataStreams`); the preconnect audio buffer goes through it. */\n  byteStreamOpener: (options?: StreamBytesOptions) => Promise<ByteStreamWriter>;\n  /** The video publish pipeline (`video`). Without one, publishing a video track throws. */\n  videoPublisher: VideoPublisher;\n}\n\n/**\n * An extension that supplies the named slots: `SlotProvider<'byteStreamOpener'>`. A provider\n * whose value is conditional declares `Partial<SlotProvider<...>>`.\n * @experimental\n */\nexport type SlotProvider<K extends keyof CoreSlots> = Pick<CoreSlots, K>;\n\n/** @internal the keys core copies off an install result */\nexport const SLOT_KEYS = [\n  'e2eeManager',\n  'frameMetadataOptions',\n  'byteStreamOpener',\n  'videoPublisher',\n] as const satisfies readonly (keyof CoreSlots)[];\n\n/** @experimental */\nexport type DataPacketCase = NonNullable<DataPacket['value']['case']>;\n/** @experimental */\nexport type DataPacketValue<C extends DataPacketCase> = Extract<\n  DataPacket['value'],\n  { case: C }\n>['value'];\n\n/**\n * What core exposes to an extension at install time. Everything the extension contributes goes\n * through its install result instead. Everything else it needs (`remoteParticipants`,\n * `localParticipant`, `emit`, `options`, `engine`) is public on the room already.\n * @experimental\n */\nexport interface ExtensionContext {\n  log: StructuredLogger;\n  /** The `install` result of an already installed extension (a hard dependency). */\n  get<E extends RoomExtension<any, any>>(ext: E): ReturnType<E['install']>;\n  /** Reads a slot. Slots of the whole list are filled before any `onEngineCreated` runs. */\n  slot<K extends keyof CoreSlots>(slot: K): CoreSlots[K] | undefined;\n  /** Returns the remote participant for an identity, creating it from `info` when new. */\n  getOrCreateParticipant(identity: string, info: ParticipantInfo): RemoteParticipant;\n  /** Puts the room into the connected state without a server (`simulatedParticipants`). */\n  simulateConnected(roomInfo: RoomModel, localParticipantInfo: ParticipantInfo): void;\n  /** A silent audio track the room hands back to the shared source on disconnect. */\n  acquireEmptyAudioStreamTrack(): MediaStreamTrack;\n  /** Emits the transcription events for a transcription rebuilt from `lk.transcription` streams. */\n  handleTranscription(transcription: TranscriptionModel): void;\n}\n\ntype UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void\n  ? I\n  : never;\n\n// An extension without a room or participant API infers `unknown` there, which would swallow the\n// other extensions' APIs in the union below, so it counts as `{}`.\ntype Known<T> = unknown extends T ? {} : T;\ntype ApiOf<E> = E extends RoomExtension<infer R, any> ? Known<R> : never;\ntype LocalOf<E> = E extends RoomExtension<any, infer L> ? Known<L> : never;\ntype Deps<E> = E extends { requires: readonly (infer D)[] } ? D | Deps<D> : never;\ntype All<E> = E | Deps<E>;\n\n/**\n * The methods a set of extensions (and their dependencies) adds to a room and its local participant.\n * @experimental\n */\nexport type ExtensionApis<E> = UnionToIntersection<ApiOf<All<E>>> & {\n  localParticipant: UnionToIntersection<LocalOf<All<E>>>;\n};\n\n/**\n * An extension with its options bound.\n * @experimental\n */\nexport type ConfiguredExtension<\n  Result extends ExtensionResult<any, any>,\n  Requires extends readonly RoomExtension<any, any>[],\n> = {\n  readonly key: symbol;\n  readonly requires: Requires;\n  install(room: CoreRoom, ctx: ExtensionContext): Result;\n};\n\n/**\n * An extension that takes options. Listed bare (`[e2ee]`) it installs from the room options the\n * full `Room` uses today; called (`[e2ee(options)]`) it installs with those options. A function\n * (`e2ee(() => options)`) is evaluated inside each room's constructor, for resources such as\n * workers that must be per room.\n * @experimental\n */\nexport type ConfigurableExtension<\n  Result extends ExtensionResult<any, any>,\n  Options,\n  Requires extends readonly RoomExtension<any, any>[],\n> = ConfiguredExtension<Result, Requires> &\n  ((options: Options | (() => Options)) => ConfiguredExtension<Result, Requires>);\n\n/**\n * Builds a {@link ConfigurableExtension}. The option type comes from the `options` parameter.\n * @experimental\n */\nexport function defineExtension<\n  Result extends ExtensionResult<any, any>,\n  Options,\n  const Requires extends readonly RoomExtension<any, any>[] = [],\n>(\n  name: string,\n  requires: Requires,\n  install: (room: CoreRoom, ctx: ExtensionContext, options: Options | undefined) => Result,\n): ConfigurableExtension<Result, Options, Requires> {\n  const key = Symbol(`lk.extension.${name}`);\n  const configure = (\n    options?: Options | (() => Options),\n  ): ConfiguredExtension<Result, Requires> => ({\n    key,\n    requires,\n    install: (room, ctx) =>\n      install(room, ctx, typeof options === 'function' ? (options as () => Options)() : options),\n  });\n  return Object.assign((options: Options | (() => Options)) => configure(options), configure());\n}\n\n/**\n * Installs extensions on a room: dependencies first, each key once. An extension the caller\n * lists explicitly wins over the default a dependency would pull in, whatever the order.\n * @experimental\n */\nexport function installExtensions(\n  room: CoreRoom,\n  extensions: readonly RoomExtension<any, any>[],\n): void {\n  const explicit = new Map<symbol, RoomExtension<any, any>>();\n  for (const ext of extensions) {\n    if (explicit.has(ext.key)) {\n      // @throws-transformer ignore - programmer error\n      throw new Error(`extension '${String(ext.key)}' is listed twice`);\n    }\n    explicit.set(ext.key, ext);\n  }\n  const resolved: RoomExtension<any, any>[] = [];\n  const resolvedKeys = new Set<symbol>();\n  const add = (ext: RoomExtension<any, any>, stack: symbol[]) => {\n    const chosen = explicit.get(ext.key) ?? ext;\n    if (stack.includes(chosen.key)) {\n      // @throws-transformer ignore - programmer error\n      throw new Error(`extension '${String(chosen.key)}' depends on itself`);\n    }\n    if (resolvedKeys.has(chosen.key)) {\n      return;\n    }\n    resolvedKeys.add(chosen.key);\n    chosen.requires?.forEach((dep) => add(dep, [...stack, chosen.key]));\n    resolved.push(chosen);\n  };\n  extensions.forEach((ext) => add(ext, []));\n  room.installExtensions(resolved);\n}\n"],"names":["SLOT_KEYS","defineExtension","name","requires","install","key","Symbol","concat","configure","options","room","ctx","Object","assign","installExtensions","extensions","explicit","Map","ext","has","Error","String","set","resolved","resolvedKeys","Set","add","stack","chosen","_a","get","includes","_b","forEach","dep","push"],"mappings":"AAwKA;AACO,MAAMA,SAAS,GAAG,CACvB,aAAa,EACb,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB;AAgFlB;;;AAGG;SACaC,eAAeA,CAK7BC,IAAY,EACZC,QAAkB,EAClBC,OAAwF,EAAA;EAExF,MAAMC,GAAG,GAAGC,MAAM,CAAA,eAAA,CAAAC,MAAA,CAAiBL,IAAI,CAAE,CAAC;EAC1C,MAAMM,SAAS,GACbC,OAAmC,KACQ;IAC3CJ,GAAG;IACHF,QAAQ;IACRC,OAAO,EAAEA,CAACM,IAAI,EAAEC,GAAG,KACjBP,OAAO,CAACM,IAAI,EAAEC,GAAG,EAAE,OAAOF,OAAO,KAAK,UAAU,GAAIA,OAAyB,EAAE,GAAGA,OAAO;AAC5F,GAAA,CAAC;AACF,EAAA,OAAOG,MAAM,CAACC,MAAM,CAAEJ,OAAkC,IAAKD,SAAS,CAACC,OAAO,CAAC,EAAED,SAAS,EAAE,CAAC;AAC/F;AAEA;;;;AAIG;AACG,SAAUM,iBAAiBA,CAC/BJ,IAAc,EACdK,UAA8C,EAAA;AAE9C,EAAA,MAAMC,QAAQ,GAAG,IAAIC,GAAG,EAAmC;AAC3D,EAAA,KAAK,MAAMC,GAAG,IAAIH,UAAU,EAAE;IAC5B,IAAIC,QAAQ,CAACG,GAAG,CAACD,GAAG,CAACb,GAAG,CAAC,EAAE;AACzB;AACA,MAAA,MAAM,IAAIe,KAAK,CAAA,aAAA,CAAAb,MAAA,CAAec,MAAM,CAACH,GAAG,CAACb,GAAG,CAAC,EAAA,mBAAA,CAAmB,CAAC;AACnE,IAAA;I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