/** * @fileoverview Base class for controllable media loading (images and videos). * Provides a state machine, lifecycle events, cache detection and metadata * extraction shared by every concrete media loader. */ import type { ICustomEventEmitter } from '../../../jsdoc/EventEmitter.mjs'; /** @import { ICustomEventEmitter } from '../../../jsdoc/EventEmitter.mjs' */ import TinyMediaProgress from './utils/TinyMediaProgress.mjs'; import TinyMediaCache from './utils/TinyMediaCache.mjs'; import TinyMediaMirror from './utils/TinyMediaMirror.mjs'; export type MediaMirrorEntry = import('./utils/TinyMediaMirror.mjs').MediaMirrorEntry; export type MediaMirrorEvent = import('./utils/TinyMediaMirror.mjs').MediaMirrorEvent; export type MediaLoaderOptions = { /** * - The media source URL. */ src?: string; /** * - Maximum time in milliseconds before the load is aborted. */ timeout?: number; /** * - An existing DOM element to adopt. */ element?: HTMLMainElement | null; /** * - Whether an external `src` change triggers a reload. */ autoReload?: boolean; /** * - Whether the original URL is mirrored into the `original-src` attribute. */ originalSrc?: boolean; /** * - Whether to decode image dimensions from the response headers using WebCodecs. */ earlyDecode?: boolean; /** * - Whether to render progressively during fetch (default true). */ progressive?: boolean; /** * - Whether to perform a HEAD request to fetch HTTP headers before downloading. */ useHeadRequest?: boolean; /** * - Whether concurrent loads of the same source share a single download (default true). */ mirror?: boolean; /** * - An optional shared memory cache. */ cache?: TinyMediaCache | null; /** * - The request body forwarded to the transport. */ body?: BodyInit; }; export type MediaSrcChangePayload = { /** * - The new source URL. */ src: string; /** * - The previous source URL. */ previousSrc: string; }; export type MediaSrcTransitionPayload = { /** * - The original network source URL. */ src: string; /** * - The internal object URL, or null when it is cleared. */ internalSrc: string | null; }; export type MediaMetadata = { /** * - The resolved source URL. */ src: string; /** * - The media MIME type (e.g., "image/png"). */ type: string; /** * - The intrinsic width in pixels. */ width: number; /** * - The intrinsic height in pixels. */ height: number; /** * - The duration in seconds (0 for images). */ duration: number; /** * - The decoded size in bytes (0 when unknown). */ size: number; /** * - Whether the media was served from the cache. */ fromCache: boolean; /** * - The total load time in milliseconds. */ loadTime: number; /** * - The epoch timestamp when the load finished. */ timestamp: number; /** * - The animation data. */ animation: import('./probe/TinyImageProbe.mjs').AnimationProbeData | null; /** * - All HTTP response headers captured during the fetch. */ httpHeaders?: Record; }; export type MediaChunkPayload = { /** * - The binary chunk. */ chunk: Uint8Array; /** * - The total bytes downloaded so far. */ loaded: number; /** * - The total bytes of the media (0 when unknown). */ total: number; }; export type MediaMirrorPayload = { /** * - The source URL shared by both loaders. */ src: string; /** * - The normalized registry key. */ key: string; /** * - The size of the shared payload in bytes. */ size: number; /** * - The number of loaders attached to the download. */ mirrors: number; /** * - The number of historical events caught up on attach. */ replayed: number; }; export type MediaMetadataDetails = { /** * - The media MIME type. */ type: string; /** * - The intrinsic width in pixels. */ width: number; /** * - The intrinsic height in pixels. */ height: number; /** * - The duration in seconds. */ duration: number; /** * - The decoded size in bytes. */ size: number; }; export type DecoderCreator = (mime: string) => MediaEarlyDecoder; export type MediaLoadHandler = (metadata: MediaMetadata) => void; export type MediaErrorHandler = (error: Error) => void; export type MediaStartHandler = (payload: { src: string; }) => void; export type MediaSrcChangeHandler = (payload: MediaSrcChangePayload) => void; export type MediaVoidHandler = () => void; export type MediaStateChangePayload = { /** * - The new state. */ state: string; /** * - The previous state. */ previous: string; /** * - The source URL the transition belongs to. */ src: string; }; export type MediaTimeoutPayload = { /** * - The source URL that timed out. */ src: string; /** * - The configured timeout in milliseconds. */ timeout: number; }; export type MediaEarlyDecoder = { /** * - Pushes a chunk into the decoder. */ write: (chunk: Uint8Array) => void; /** * - Closes the decoder and releases its resources. */ close: () => void; /** * - Flushes the metadata that is only known at the end of the stream. */ finalize?: () => Partial | null; }; export type MediaMetadataType = 'HEAD' | 'GET' | 'PROBE' | 'DECODE' | 'CACHE' | 'LOADED_METADATA' | 'DURATION_CHANGE' | 'PROBE_ANIMATION' | 'MIRROR'; export type MediaLoaderEvents = { /** * - Emitted when a media load process begins. */ loadstart: (payload: { src: string; }) => void; /** * - Emitted when the media has been fully loaded and decoded. */ loaded: (metadata: MediaMetadata) => void; /** * - Emitted when the loading process finishes, regardless of success or failure. */ loadend: (payload: { src: string; state: string; }) => void; /** * - Emitted when the current load operation is cancelled. */ abort: (payload: { src: string; }) => void; /** * - Emitted when an unrecoverable error occurs during loading. */ error: (error: Error) => void; /** * - Emitted when the load operation exceeds the configured timeout. */ timeout: (payload: MediaTimeoutPayload) => void; /** * - Emitted periodically to provide download progress updates. */ progress: (payload: import('./utils/TinyMediaProgress.mjs').MediaProgressSnapshot) => void; /** * - Emitted whenever media metadata is partially or fully resolved. */ metadata: (metadata: MediaMetadata, type: MediaMetadataType) => void; /** * - Emitted when the main HTTP response for the media resource is received. */ response: (response: Response) => void; /** * - Emitted when the HTTP HEAD response is received. */ headResponse: (response: Response) => void; /** * - Emitted when the source URL of the loader is changed. */ srcchange: (payload: MediaSrcChangePayload) => void; /** * - Emitted when the element's source swaps between a network URL and an internal object URL. */ srctransition: (payload: MediaSrcTransitionPayload) => void; /** * - Emitted when the resource is not found in the cache. */ cachemiss: (entry: import('./utils/TinyMediaCache.mjs').MediaCacheEntry) => void; /** * - Emitted when the resource is successfully retrieved from the cache. */ cachehit: (entry: import('./utils/TinyMediaCache.mjs').MediaCacheEntry) => void; /** * - Emitted when the loader transitions from one state to another. */ statechange: (payload: MediaStateChangePayload) => void; /** * - Emitted every time a binary data chunk is received during streaming. */ chunk: (payload: MediaChunkPayload) => void; /** * - Emitted when the download is shared with another loader. */ mirror: (payload: MediaMirrorPayload) => void; /** * - Emitted when the loader is destroyed and its resources are released. */ destroy: () => void; }; /** * @template {string} Name * @template {unknown[]} Args * @typedef {import('./utils/TinyMediaMirror.mjs').MediaMirrorEntry} MediaMirrorEntry */ /** * @template {string} Name * @template {unknown[]} Args * @typedef {import('./utils/TinyMediaMirror.mjs').MediaMirrorEvent} MediaMirrorEvent */ /** * Describes the configuration object accepted by the {@link TinyMediaLoader} constructor. * Every property is optional, so a loader can be created empty and configured later. * @template {HTMLImageElement|HTMLVideoElement|HTMLAudioElement} HTMLMainElement * @typedef {Object} MediaLoaderOptions * @property {string} [src] - The media source URL. * @property {number} [timeout] - Maximum time in milliseconds before the load is aborted. * @property {HTMLMainElement|null} [element] - An existing DOM element to adopt. * @property {boolean} [autoReload] - Whether an external `src` change triggers a reload. * @property {boolean} [originalSrc] - Whether the original URL is mirrored into the `original-src` attribute. * @property {boolean} [earlyDecode] - Whether to decode image dimensions from the response headers using WebCodecs. * @property {boolean} [progressive] - Whether to render progressively during fetch (default true). * @property {boolean} [useHeadRequest] - Whether to perform a HEAD request to fetch HTTP headers before downloading. * @property {boolean} [mirror] - Whether concurrent loads of the same source share a single download (default true). * @property {TinyMediaCache|null} [cache] - An optional shared memory cache. * @property {BodyInit} [body] - The request body forwarded to the transport. */ /** * Describes the payload emitted whenever the source URL changes, whether the change * originated inside the loader or from an external DOM mutation. * @typedef {Object} MediaSrcChangePayload * @property {string} src - The new source URL. * @property {string} previousSrc - The previous source URL. */ /** * Describes the payload emitted when the element swaps the network source for * an internal object URL (or the reverse) during a streamed load. * @typedef {Object} MediaSrcTransitionPayload * @property {string} src - The original network source URL. * @property {string|null} internalSrc - The internal object URL, or null when it is cleared. */ /** * Describes the immutable snapshot of everything known about a finished load. * @typedef {Object} MediaMetadata * @property {string} src - The resolved source URL. * @property {string} type - The media MIME type (e.g., "image/png"). * @property {number} width - The intrinsic width in pixels. * @property {number} height - The intrinsic height in pixels. * @property {number} duration - The duration in seconds (0 for images). * @property {number} size - The decoded size in bytes (0 when unknown). * @property {boolean} fromCache - Whether the media was served from the cache. * @property {number} loadTime - The total load time in milliseconds. * @property {number} timestamp - The epoch timestamp when the load finished. * @property {import('./probe/TinyImageProbe.mjs').AnimationProbeData | null} animation - The animation data. * @property {Record} [httpHeaders] - All HTTP response headers captured during the fetch. */ /** * Describes the payload emitted when a new chunk is downloaded. * @typedef {Object} MediaChunkPayload * @property {Uint8Array} chunk - The binary chunk. * @property {number} loaded - The total bytes downloaded so far. * @property {number} total - The total bytes of the media (0 when unknown). */ /** * Describes the payload emitted when a loader attaches to an in-flight download. * @typedef {Object} MediaMirrorPayload * @property {string} src - The source URL shared by both loaders. * @property {string} key - The normalized registry key. * @property {number} size - The size of the shared payload in bytes. * @property {number} mirrors - The number of loaders attached to the download. * @property {number} replayed - The number of historical events caught up on attach. */ /** * Describes the media specific values returned by the abstract `_getMetadataDetails` hook * and merged into the final {@link MediaMetadata} object. * @typedef {Object} MediaMetadataDetails * @property {string} type - The media MIME type. * @property {number} width - The intrinsic width in pixels. * @property {number} height - The intrinsic height in pixels. * @property {number} duration - The duration in seconds. * @property {number} size - The decoded size in bytes. */ /** * @callback DecoderCreator * Builds a decoder backed by the container header parser. * @param {string} mime - The video MIME type. * @returns {MediaEarlyDecoder} The decoder. */ /** * Handles a successful media load. * @typedef {(metadata: MediaMetadata) => void} MediaLoadHandler */ /** * Handles a failed media load. * @typedef {(error: Error) => void} MediaErrorHandler */ /** * Handles the start of a media load. * @typedef {(payload: { src: string }) => void} MediaStartHandler */ /** * Handles a source URL change. * @typedef {(payload: MediaSrcChangePayload) => void} MediaSrcChangeHandler */ /** * Handles an event that carries no payload. * @typedef {() => void} MediaVoidHandler */ /** * Describes the payload emitted on every state machine transition. * @typedef {Object} MediaStateChangePayload * @property {string} state - The new state. * @property {string} previous - The previous state. * @property {string} src - The source URL the transition belongs to. */ /** * Describes the payload emitted when a load exceeds the configured timeout. * @typedef {Object} MediaTimeoutPayload * @property {string} src - The source URL that timed out. * @property {number} timeout - The configured timeout in milliseconds. */ /** * Handle returned by the early decoder factory. It is a thin wrapper around the * WebCodecs `ImageDecoder` so the loader can push chunks and release the * decoder without knowing whether the API is available. * @typedef {Object} MediaEarlyDecoder * @property {(chunk: Uint8Array) => void} write - Pushes a chunk into the decoder. * @property {() => void} close - Closes the decoder and releases its resources. * @property {() => Partial|null} [finalize] - Flushes the metadata that is only known at the end of the stream. */ /** * @typedef {'HEAD'|'GET'|'PROBE'|'DECODE'|'CACHE'|'LOADED_METADATA'|'DURATION_CHANGE'|'PROBE_ANIMATION'|'MIRROR'} MediaMetadataType */ /** * Describes every event emitted by {@link TinyMediaLoader}. * * The keys are the event names, and the values are the listener signatures. * This is the shape expected by `ICustomEventEmitter`. * @typedef {Object} MediaLoaderEvents * @property {(payload: { src: string }) => void} loadstart - Emitted when a media load process begins. * @property {(metadata: MediaMetadata) => void} loaded - Emitted when the media has been fully loaded and decoded. * @property {(payload: { src: string, state: string }) => void} loadend - Emitted when the loading process finishes, regardless of success or failure. * @property {(payload: { src: string }) => void} abort - Emitted when the current load operation is cancelled. * @property {(error: Error) => void} error - Emitted when an unrecoverable error occurs during loading. * @property {(payload: MediaTimeoutPayload) => void} timeout - Emitted when the load operation exceeds the configured timeout. * @property {(payload: import('./utils/TinyMediaProgress.mjs').MediaProgressSnapshot) => void} progress - Emitted periodically to provide download progress updates. * @property {(metadata: MediaMetadata, type: MediaMetadataType) => void} metadata - Emitted whenever media metadata is partially or fully resolved. * @property {(response: Response) => void} response - Emitted when the main HTTP response for the media resource is received. * @property {(response: Response) => void} headResponse - Emitted when the HTTP HEAD response is received. * @property {(payload: MediaSrcChangePayload) => void} srcchange - Emitted when the source URL of the loader is changed. * @property {(payload: MediaSrcTransitionPayload) => void} srctransition - Emitted when the element's source swaps between a network URL and an internal object URL. * @property {(entry: import('./utils/TinyMediaCache.mjs').MediaCacheEntry) => void} cachemiss - Emitted when the resource is not found in the cache. * @property {(entry: import('./utils/TinyMediaCache.mjs').MediaCacheEntry) => void} cachehit - Emitted when the resource is successfully retrieved from the cache. * @property {(payload: MediaStateChangePayload) => void} statechange - Emitted when the loader transitions from one state to another. * @property {(payload: MediaChunkPayload) => void} chunk - Emitted every time a binary data chunk is received during streaming. * @property {(payload: MediaMirrorPayload) => void} mirror - Emitted when the download is shared with another loader. * @property {() => void} destroy - Emitted when the loader is destroyed and its resources are released. */ /** @type {new () => ICustomEventEmitter} */ declare const TypedEmitter: new () => ICustomEventEmitter; /** * Base class that orchestrates the full lifecycle of a media element. * It must be extended. Concrete subclasses implement `_createElement`, * `_startLoad`, `_getMetadataDetails`, `_abort` and `_cleanup`. * @abstract * @template {HTMLImageElement|HTMLVideoElement|HTMLAudioElement} HTMLMainElement * @augments TypedEmitter */ declare class TinyMediaLoader extends TypedEmitter { #private; /** * The registry that deduplicates concurrent downloads. * @returns {typeof TinyMediaMirror} The shared mirror registry. */ static get TinyMediaMirror(): typeof TinyMediaMirror; /** * Immutable state machine values used by every media loader. */ static MediaState: Readonly<{ IDLE: "idle"; LOADING: "loading"; LOADED: "loaded"; ERROR: "error"; DESTROYED: "destroyed"; }>; /** * The uppercase tag name of the element this loader manages. * Subclasses must override it so the constructor can validate adopted elements. * @returns {string} The uppercase tag name, or an empty string when the subclass does not override it. */ static get tagName(): string; /** * @param {MediaLoaderOptions} [options] - The loader configuration. * @throws {TypeError} If `options` is not a plain object. * @throws {TypeError} If `options.src` is not a string. * @throws {RangeError} If `options.timeout` is not a positive number. * @throws {TypeError} If `options.element` is neither null nor an HTMLElement. * @throws {TypeError} If `options.element` does not match the loader tag name. */ constructor(options?: MediaLoaderOptions); /** * Emits an event and, when this loader leads a mirrored download, broadcasts * it to every attached mirror. The local listeners always run first so a slow * mirror can never delay the loader that owns the network request. * @template {keyof MediaLoaderEvents} K * @param {K} name - The event name. * @param {Parameters} args - The event arguments. * @returns {boolean} True when the event had listeners. */ emit(name: K, ...args: Parameters): boolean; /** * Whether concurrent loads of the same source share a single download. * @returns {boolean} True when mirroring is enabled. */ get mirror(): boolean; /** * Whether the last download was served by another loader. * @returns {boolean} True when the payload was shared by a mirrored download. */ get mirrored(): boolean; /** * The HTTP response received from the media resource. * @returns {Response|null} The response object, or null if no response has been received yet. */ get response(): Response | null; /** * The HTTP response received from the preliminary HEAD request. * @returns {Response|null} The response object, or null if no HEAD request was performed or received. */ get headResponse(): Response | null; /** * Whether to perform a HEAD request to fetch HTTP headers before downloading. * @returns {boolean} */ get useHeadRequest(): boolean; /** * The object URL created for a streamed blob, when one exists. * @returns {string|null} The active object URL, or null when none was created. */ get objectUrl(): string | null; /** * The current source URL. * @returns {string} The current source URL, or an empty string when unset. */ get src(): string; /** * The internal object URL currently assigned to the element. * @returns {string|null} The object URL assigned internally, or null when the element uses the network source. */ get internalSrc(): string | null; /** * Whether the loader mirrors the original URL into the `original-src` attribute. * @returns {boolean} True when the attribute is managed by this loader. */ get originalSrc(): boolean; /** * Whether the loader decodes the image dimensions from the response headers * through the WebCodecs `ImageDecoder`. * @returns {boolean} True when early decoding is enabled. */ get earlyDecode(): boolean; /** * Whether the loader progressively updates the media element while downloading. * @returns {boolean} True when progressive loading is enabled. */ get progressive(): boolean; /** * Updates the source URL and mirrors it into the DOM element. * @param {string} value - The new source URL. * @throws {TypeError} If `value` is not a string. */ set src(value: string); /** * Indicates whether the last load was cancelled through {@link TinyMediaLoader#abort}. * @returns {boolean} True when the in-flight load was aborted. */ get aborted(): boolean; /** * Indicates whether this loader currently holds a reference on a shared cache entry. * @returns {boolean} True while a cache reference is held. */ get cacheAcquired(): boolean; /** * Indicates whether an external `src` change triggers an automatic reload. * @returns {boolean} True when automatic reloading is enabled. */ get autoReload(): boolean; /** * Indicates whether the last load was served from the cache. * @returns {boolean} True when the last load was a cache hit. */ get cacheHint(): boolean; /** * The epoch timestamp, in milliseconds, captured when the last load finished. * @returns {number} The end timestamp, or 0 when no load has finished yet. */ get endTime(): number; /** * The high resolution timestamp captured when the last load started. * @returns {number} The start timestamp, or 0 when no load has started yet. */ get startTime(): number; /** * The current lifecycle state. * @returns {string} One of the {@link TinyMediaLoader.MediaState} values. */ get state(): string; /** * The underlying DOM element (available after construction of the subclass). * @returns {HTMLMainElement|null} The managed element, or null before it is created. */ get element(): HTMLMainElement | null; /** * A defensive copy of the last known metadata. * @returns {MediaMetadata} A shallow copy that is safe for the caller to mutate. */ get metadata(): MediaMetadata; /** * The total size in bytes of the media downloaded through the streaming path. * @returns {number} The number of bytes streamed, or `0` when the media was not streamed. */ get resourceSize(): number; /** * @returns {boolean} True while the media is loading. */ get isLoading(): boolean; /** * @returns {boolean} True when the media has finished loading. */ get isLoaded(): boolean; /** * @returns {boolean} True when the last load failed. */ get hasError(): boolean; /** * The active progress tracker, or null when the load has not started. * @returns {TinyMediaProgress|null} */ get progress(): TinyMediaProgress | null; /** * The shared memory cache, or null when disabled. * @returns {TinyMediaCache|null} */ get cache(): TinyMediaCache | null; /** * @param {TinyMediaCache|null} value - The new cache instance. * @throws {TypeError} If `value` is neither a TinyMediaCache nor null. */ set cache(value: TinyMediaCache | null); /** * The AbortController bound to the current load. * @returns {AbortController} */ get signal(): AbortController; /** * The request body forwarded to the transport. It is ignored by `GET` and * `HEAD`, which the Fetch specification forbids from carrying a body. * @returns {BodyInit|undefined} */ get body(): BodyInit | undefined; /** * @param {BodyInit|undefined} value - The request body. */ set body(value: BodyInit | undefined); /** * Whether another loader is already downloading the current source. * @returns {boolean} True when a mirrored download is in flight. */ get pending(): boolean; /** * The fetch implementation used to download the media. * Subclasses may override it to inject a custom transport. * @returns {typeof globalThis.fetch} The fetch implementation. */ get _fetch(): typeof globalThis.fetch; /** * Replaces the fetch implementation used to download the media. * @param {typeof globalThis.fetch} implementation - The fetch implementation. * @throws {TypeError} If `implementation` is not a function. */ set _fetch(implementation: typeof globalThis.fetch); /** * Extra options forwarded to the fetch implementation. * Subclasses may override it to send headers, credentials or a body. * @returns {RequestInit} The fetch options. */ get _requestInit(): RequestInit; /** * @param {RequestInit} params - The fetch options. */ set _requestInit(params: RequestInit); /** * Checks whether a URL already has a live payload held by the shared memory * cache, without acquiring a reference and without touching the network. * * The lookup is strictly read-only: it never increments the `hits`/`misses` * counters, never revives an expired entry and never creates an object URL. * Use it to decide *whether* to call {@link TinyMediaLoader#load}, never as a * replacement for it. * @param {string} [src] - The URL to test. Defaults to the current source. * @returns {boolean} True when the cache holds a live entry for the URL. * @throws {TypeError} If `src` is not a string. * @throws {Error} If the underlying cache was destroyed. */ isCached(src?: string): boolean; /** * Whether the current source is already available in the shared memory cache. * @returns {boolean} True when the current source can load without a network request. */ get cached(): boolean; /** * Reads the cache entry of a URL without acquiring a reference. * @param {string} [src] - The URL to inspect. Defaults to the current source. * @returns {import('./utils/TinyMediaCache.mjs').MediaCacheEntry|null} The cached entry, or null. * @throws {TypeError} If `src` is not a string. * @throws {Error} If the underlying cache was destroyed. */ peekCache(src?: string): import('./utils/TinyMediaCache.mjs').MediaCacheEntry | null; /** * Registers a decoder factory for a specific MIME type. * This allows the loader to instantiate the correct decoder for different media formats. * @protected * @param {string} mime - The MIME type (or prefix) that this decoder handles. * @param {DecoderCreator} callback - The factory function used to create the decoder. * @returns {void} */ protected _insertDecoder(mime: string, callback: DecoderCreator): void; /** * Creates a fresh progress tracker for the current load. * @protected * @param {number} [total] - The total number of bytes (0 when unknown). * @returns {TinyMediaProgress} The freshly created and already started progress tracker. * @throws {TypeError} If `total` is not a finite number. * @throws {RangeError} If `total` is negative. */ protected _createProgress(total?: number): TinyMediaProgress; /** * Emits a progress snapshot when a tracker is active. * @protected * @returns {void} */ protected _emitProgress(): void; /** * Merges a partial metadata patch into the current snapshot and notifies the * listeners. It is called as soon as the response headers arrive, so a * consumer can render the file type and size before the download finishes. * Keys whose value is `undefined` are ignored, so a decoder that cannot * resolve a dimension never clobbers a value that was already known. * @protected * @param {Partial} patch - The values to merge. * @param {MediaMetadataType} type - The action type. * @returns {void} * @throws {TypeError} If `patch` is not a plain object. */ protected _emitMetadata(patch: Partial, type: MediaMetadataType): void; /** * Registers a DOM listener that is removed on the next load or on destroy. * @protected * @param {HTMLMainElement} element - The source element. * @param {string} type - The DOM event name. * @param {EventListener} handler - The listener to register. * @returns {void} * @throws {TypeError} If any argument has an invalid type. */ protected _on(element: HTMLMainElement, type: string, handler: EventListener): void; /** * Forwards DOM events from an element to this emitter. * @protected * @param {HTMLMainElement} element - The source element. * @param {string[]} events - The DOM event names to forward. * @returns {void} * @throws {TypeError} If `events` is not an array of non-empty strings. */ protected _forwardEvents(element: HTMLMainElement, events: string[]): void; /** * Removes every forwarded DOM listener. * @protected * @returns {void} */ protected _detachEvents(): void; /** * Starts loading the media and resolves with the final metadata. * @returns {Promise} A promise that resolves with the final metadata of the loaded media. * @throws {Error} If the loader was destroyed or has no source. */ load(): Promise; /** * Resets the state machine and loads the current source again. * @returns {Promise} A promise that resolves with the metadata of the new load. * @throws {Error} If the loader is loading or was destroyed. */ reload(): Promise; /** * Cancels the in-flight load, if any. * @returns {boolean} True when a load was cancelled. */ abort(): boolean; /** * Appends the media element to a container. * @param {HTMLMainElement} container - The parent element. * @returns {TinyMediaLoader} The current instance for chaining. * @throws {TypeError} If `container` is not an HTMLElement. * @throws {Error} If the element has not been created yet. */ mount(container: HTMLMainElement): TinyMediaLoader; /** * Releases every resource and detaches all listeners. * @returns {void} */ destroy(): void; /** * Returns the adopted element, creating a new one when none was provided. * Subclasses must call this inside `_startLoad`. * @protected * @returns {HTMLMainElement} */ protected _resolveElement(): HTMLMainElement; /** * Registers a concrete DOM element. Kept for advanced subclasses. * @protected * @param {HTMLMainElement} element - The element to expose through `element`. * @returns {void} * @throws {TypeError} If `element` is not an HTMLElement. */ protected _setElement(element: HTMLMainElement): void; /** * Flags that the media was served from the cache before the network layer ran. * @protected * @param {boolean} value - The cache hint. * @returns {void} * @throws {TypeError} If `value` is not a boolean. */ protected _setCacheHint(value: boolean): void; /** * Records the internal object URL assigned to the element so the mutation * observer treats the swap as an internal transition instead of an external * source change. It also mirrors the network URL into the `original-src` * attribute while an object URL is active. * @protected * @param {string|null} url - The object URL assigned internally, or null to clear it. * @returns {void} * @throws {TypeError} If `url` is neither a string nor null. */ protected _setInternalSrc(url: string | null): void; /** * Waits for a media element to become ready while staying bound to the * current abort signal. The returned promise rejects as soon as the loader is * aborted, which prevents the caller from awaiting a download that will never * finish. * @protected * @param {HTMLMainElement} element - The media element being loaded. * @param {string} [readyEvent] - The DOM event that signals a successful load. * @returns {Promise} Resolves once the media is ready. * @throws {TypeError} If `element` is not an HTMLElement. * @throws {TypeError} If `readyEvent` is not a string. */ protected _waitForMedia(element: HTMLMainElement, readyEvent?: string): Promise; /** * Stores a downloaded blob in the shared cache when one is configured and * returns the URL the element must render. When no cache is present the blob * is exposed through a private object URL instead. An entry that is already * cached is reused, because replacing it would revoke the object URL that * another loader may still be rendering. * @protected * @param {Blob} blob - The downloaded blob. * @returns {string} The URL the element must use as its source. * @throws {TypeError} If `blob` is not a Blob. */ protected _cacheBlob(blob: Blob): string; /** * Downloads a media resource through fetch. When another loader is already * downloading the same URL, the request is not repeated: the promise resolves * with the very same {@link Blob} instance that the leading loader receives. * @protected * @template {keyof MediaLoaderEvents} K * @param {string} url - The resource to download. * @param {(chunk: BlobPart, chunks: BlobPart[]) => void} [onChunk] - Optional chunk callback. * @param {number} [startByte=0] - The byte offset to start downloading from. * @param {AbortSignal|null} [customSignal=null] - Signal to abort only the fetch without aborting the loader. * @returns {Promise} The fully downloaded blob. * @throws {TypeError} If `url` is not a string. */ protected _downloadStream(url: string, onChunk?: (chunk: BlobPart, chunks: BlobPart[]) => void, startByte?: number, customSignal?: AbortSignal | null): Promise; /** * Acquires the current source from the shared cache and remembers the * reference. A successful acquisition flags the metadata so the final * snapshot reports `fromCache: true` and restores the values that the * download path would have recorded, since no network request runs here. * @protected * @returns {import('./utils/TinyMediaCache.mjs').MediaCacheEntry|null} */ protected _acquireFromCache(): import('./utils/TinyMediaCache.mjs').MediaCacheEntry | null; /** * Releases the reference held on the shared cache entry, when present. * @protected * @returns {void} */ protected _releaseFromCache(): void; /** * The total time spent loading, in milliseconds. * @protected * @returns {number} */ protected _getLoadTime(): number; /** * Uses the Resource Timing API to detect a cache hit. * @protected * @returns {boolean} */ protected _detectCache(): boolean; /** * Records the exact byte size of the media when it is known without the * Resource Timing API, for example right after a streamed download. * @protected * @param {number} size - The size in bytes. * @returns {void} * @throws {RangeError} If `size` is not a positive number. */ protected _setResourceSize(size: number): void; /** * Reads the decoded size of the resource. It prefers the size captured from a * streamed blob and falls back to the Resource Timing API, whose entries are * keyed by absolute URL. * @protected * @returns {number} The size in bytes, or 0 when unavailable. */ protected _getResourceSize(): number; /** * Discards every pending mutation record. * Subclasses must call this right after mutating the element internally, * otherwise the observer reports a false external change. * @protected * @returns {void} */ protected _flushMutations(): void; /** * Creates an object URL for a blob and revokes the previous one. * @protected * @param {Blob} blob - The blob to expose through an object URL. * @returns {string} The newly created object URL. * @throws {TypeError} If `blob` is not a Blob. */ protected _createObjectUrl(blob: Blob): string; /** * Revokes the current object URL, if any. * @protected * @returns {void} */ protected _revokeObjectUrl(): void; /** * Creates a brand new element. Must be implemented by subclasses. * @abstract * @protected * @returns {HTMLMainElement} */ protected _createElement(): HTMLMainElement; /** * Performs the actual load. Must be implemented by subclasses. * @abstract * @protected * @returns {Promise} */ protected _startLoad(): Promise; /** * Returns the media-specific metadata. Must be implemented by subclasses. * @abstract * @protected * @returns {MediaMetadataDetails} The media specific metadata details. */ protected _getMetadataDetails(): MediaMetadataDetails; /** * Aborts the network activity of the coupled element. It works for ``, * `