react-smart-copy 1.12.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -3
- package/dist/code.cjs +58 -6
- package/dist/code.cjs.map +1 -1
- package/dist/code.js +58 -6
- package/dist/code.js.map +1 -1
- package/dist/image.cjs +1295 -0
- package/dist/image.cjs.map +1 -0
- package/dist/image.d.cts +217 -0
- package/dist/image.d.ts +217 -0
- package/dist/image.js +1284 -0
- package/dist/image.js.map +1 -0
- package/package.json +50 -18
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image.cjs","names":["IMAGE_CHUNKS"],"sources":["../src/core/errors.ts","../src/image/bytes.ts","../src/image/exif.ts","../src/image/types.ts","../src/image/bmff.ts","../src/image/gif.ts","../src/image/jpeg.ts","../src/image/png.ts","../src/image/webp.ts","../src/image/info.ts","../src/capture/deadline.ts","../src/image/prepare.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { copyFailure } from '../core/errors';\n\n/** Bounds-checked reads over a byte array: out-of-range reads return `null`, never garbage. */\nexport class Bytes {\n readonly data: Uint8Array;\n readonly length: number;\n\n constructor(data: Uint8Array) {\n this.data = data;\n this.length = data.length;\n }\n\n u8(at: number): number | null {\n return at >= 0 && at < this.length ? (this.data[at] as number) : null;\n }\n\n u16(at: number, littleEndian: boolean): number | null {\n if (at < 0 || at + 2 > this.length) return null;\n const a = this.data[at] as number;\n const b = this.data[at + 1] as number;\n return littleEndian ? a | (b << 8) : (a << 8) | b;\n }\n\n u24le(at: number): number | null {\n if (at < 0 || at + 3 > this.length) return null;\n return (this.data[at] as number) | ((this.data[at + 1] as number) << 8) | ((this.data[at + 2] as number) << 16);\n }\n\n u32(at: number, littleEndian: boolean): number | null {\n if (at < 0 || at + 4 > this.length) return null;\n const a = this.data[at] as number;\n const b = this.data[at + 1] as number;\n const c = this.data[at + 2] as number;\n const d = this.data[at + 3] as number;\n // `>>> 0` keeps the result unsigned.\n return (littleEndian ? a | (b << 8) | (c << 16) | (d << 24) : (a << 24) | (b << 16) | (c << 8) | d) >>> 0;\n }\n\n /** `length` bytes as Latin-1 text (four-character codes, signatures), or `null` past the end. */\n ascii(at: number, length: number): string | null {\n if (at < 0 || at + length > this.length) return null;\n return String.fromCharCode(...this.data.subarray(at, at + length));\n }\n\n startsWith(at: number, signature: string): boolean {\n return this.ascii(at, signature.length) === signature;\n }\n\n /** The same bytes, ending at `end`: reads of a box or chunk then can't run into the next one. Offsets don't change. */\n until(end: number): Bytes {\n return end >= this.length ? this : new Bytes(this.data.subarray(0, end));\n }\n\n slice(start: number, end: number): Uint8Array {\n return this.data.subarray(Math.max(0, start), Math.min(this.length, end));\n }\n}\n\nexport const DEFAULT_IMAGE_MAX_INPUT_BYTES = 100 * 1024 * 1024;\n\n/** Reads a Blob into memory, refusing anything larger than `maxBytes`. */\nexport async function readBlob(blob: Blob, maxBytes: number): Promise<Bytes> {\n const candidate: unknown = blob; // Plain-JS callers can pass anything.\n if (typeof candidate !== 'object' || candidate === null || typeof (candidate as { size?: unknown }).size !== 'number') {\n throw copyFailure('invalid-payload', 'Expected an image Blob or File.');\n }\n if (blob.size > maxBytes) {\n throw copyFailure('too-large', `The image is ${String(blob.size)} bytes; maxInputBytes is ${String(maxBytes)}.`);\n }\n return new Bytes(new Uint8Array(await blob.arrayBuffer()));\n}\n\nexport function concat(parts: readonly Uint8Array[]): Uint8Array {\n let length = 0;\n for (const part of parts) length += part.length;\n const out = new Uint8Array(length);\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n}\n\nexport function u32be(value: number): Uint8Array {\n return Uint8Array.of((value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff);\n}\n\nexport function u32le(value: number): Uint8Array {\n return Uint8Array.of(value & 0xff, (value >>> 8) & 0xff, (value >>> 16) & 0xff, (value >>> 24) & 0xff);\n}\n\nexport const latin1 = (text: string): Uint8Array => Uint8Array.from(text, (char) => char.charCodeAt(0));\n\n/** A Blob (or a File with the same name and date, when the input was one) holding `parts`. */\nexport function outputBlob(parts: readonly Uint8Array[], type: string, like: Blob): Blob {\n const data = concat(parts);\n const file = like as Partial<File>;\n if (typeof File === 'function' && typeof file.name === 'string') {\n return new File([data as BlobPart], file.name, { type, lastModified: file.lastModified ?? Date.now() });\n }\n return new Blob([data as BlobPart], { type });\n}\n","import type { Bytes } from './bytes';\n\n/** What an Exif (TIFF) block holds that matters for privacy and display. */\nexport interface TiffSummary {\n /** 1-8, as in the Exif Orientation tag; 1 when absent or invalid. */\n readonly orientation: number;\n /** A GPS IFD with a latitude or longitude. */\n readonly gps: boolean;\n /** A second IFD carrying a thumbnail image. */\n readonly thumbnail: boolean;\n /** Nothing but the orientation: what is left after stripping, not metadata. */\n readonly onlyOrientation: boolean;\n}\n\nconst ORIENTATION = 0x0112;\nconst GPS_IFD = 0x8825;\nconst GPS_LATITUDE = 0x0002;\nconst GPS_LONGITUDE = 0x0004;\nconst THUMBNAIL_OFFSET = 0x0201;\nconst STRIP_OFFSETS = 0x0111;\n/** Real files have a few dozen tags; a bound keeps hostile counts cheap. */\nconst MAX_ENTRIES = 512;\n\ninterface Ifd {\n readonly tags: ReadonlyMap<number, number>;\n /** Offset of the next IFD (relative to the TIFF header), 0 for none. */\n readonly next: number;\n}\n\n/** Reads an IFD's tags (value field only: enough for SHORT / LONG values and offsets). */\nfunction readIfd(bytes: Bytes, base: number, end: number, offset: number, littleEndian: boolean): Ifd | null {\n const at = base + offset;\n const count = bytes.u16(at, littleEndian);\n if (count === null || offset < 8 || at + 2 + count * 12 + 4 > end || count > MAX_ENTRIES) return null;\n const tags = new Map<number, number>();\n for (let index = 0; index < count; index += 1) {\n const entry = at + 2 + index * 12;\n const tag = bytes.u16(entry, littleEndian) as number;\n const type = bytes.u16(entry + 2, littleEndian) as number;\n // SHORT values sit in the first two bytes of the value field; everything else is read as LONG.\n tags.set(tag, type === 3 ? (bytes.u16(entry + 8, littleEndian) as number) : (bytes.u32(entry + 8, littleEndian) as number));\n }\n return { tags, next: bytes.u32(at + 2 + count * 12, littleEndian) as number };\n}\n\n/** Summarises the TIFF structure at `start`-`end` (an Exif payload without its `Exif\\0\\0` prefix). */\nexport function readTiff(file: Bytes, start: number, end: number): TiffSummary | null {\n // Every read stays inside the Exif block: nothing past `end` is ever read.\n const bytes = file.until(end);\n const order = bytes.ascii(start, 2);\n if (order !== 'II' && order !== 'MM') return null;\n const littleEndian = order === 'II';\n if (bytes.u16(start + 2, littleEndian) !== 42) return null;\n const ifd0 = readIfd(bytes, start, end, bytes.u32(start + 4, littleEndian) as number, littleEndian);\n if (ifd0 === null) return null;\n const value = ifd0.tags.get(ORIENTATION);\n const orientation = value !== undefined && value >= 1 && value <= 8 ? value : 1;\n const gpsOffset = ifd0.tags.get(GPS_IFD);\n const gpsIfd = gpsOffset === undefined ? null : readIfd(bytes, start, end, gpsOffset, littleEndian);\n const gps = gpsIfd !== null && (gpsIfd.tags.has(GPS_LATITUDE) || gpsIfd.tags.has(GPS_LONGITUDE));\n const ifd1 = ifd0.next === 0 || ifd0.next === bytes.u32(start + 4, littleEndian) ? null : readIfd(bytes, start, end, ifd0.next, littleEndian);\n const thumbnail = ifd1 !== null && (ifd1.tags.has(THUMBNAIL_OFFSET) || ifd1.tags.has(STRIP_OFFSETS));\n const onlyOrientation = ifd0.tags.size === 1 && value !== undefined && ifd0.next === 0;\n return { orientation, gps, thumbnail, onlyOrientation };\n}\n\n/** Where the TIFF header starts in an Exif payload: after an optional `Exif\\0\\0` prefix. */\nexport function tiffStart(bytes: Bytes, start: number): number {\n return bytes.startsWith(start, 'Exif\\0\\0') ? start + 6 : start;\n}\n\n/**\n * The smallest valid TIFF block with only an Orientation tag: what is kept of\n * Exif so a photo still displays the right way up. 26 bytes, little-endian.\n */\nexport function orientationTiff(orientation: number): Uint8Array {\n return Uint8Array.of(\n 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, // \"II\", 42, IFD0 at 8\n 0x01, 0x00, // one entry\n 0x12, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, orientation, 0x00, 0x00, 0x00, // Orientation, SHORT, 1\n 0x00, 0x00, 0x00, 0x00, // no next IFD\n );\n}\n","import type { TiffSummary } from './exif';\n\n/** Formats recognised from their bytes (never from a file name or a claimed MIME type). */\nexport type ImageFormat = 'jpeg' | 'png' | 'gif' | 'webp' | 'avif' | 'heic' | 'bmp';\n\n/**\n * Kinds of metadata an image can carry.\n *\n * - `exif`: camera, settings, dates, serial numbers (Exif / TIFF tags).\n * - `gps`: a location, inside Exif.\n * - `thumbnail`: an embedded preview, which can show the uncropped original.\n * - `xmp`: Adobe XMP (edit history, authors, often a copy of Exif).\n * - `iptc`: captions, credits and keywords (Photoshop IRB / IPTC).\n * - `comment`: free-text comments (JPEG COM, GIF comment extension).\n * - `text`: text chunks (PNG `tEXt`, `zTXt`, `iTXt`, `tIME`).\n * - `icc`: an ICC colour profile. Kept by default: it changes how colours look.\n * - `other`: anything else outside the image data: vendor segments, multi-picture\n * (MPF) and depth images, content credentials (C2PA), data appended after the\n * image (motion photos), unknown chunks.\n */\nexport type MetadataKind = 'exif' | 'gps' | 'thumbnail' | 'xmp' | 'iptc' | 'comment' | 'text' | 'icc' | 'other';\n\n/** Every metadata kind, in a stable order. */\nexport const METADATA_KINDS: readonly MetadataKind[] = Object.freeze(['exif', 'gps', 'thumbnail', 'xmp', 'iptc', 'comment', 'text', 'icc', 'other']);\n\nexport interface ImageInfo {\n /** `null` when the bytes are not a format this module reads. */\n readonly format: ImageFormat | null;\n /** e.g. `image/jpeg`; `null` when `format` is. */\n readonly mimeType: string | null;\n /** Stored pixel size (before orientation), when the header gives it. */\n readonly width: number | null;\n readonly height: number | null;\n /** Exif orientation, 1-8 (1 = as stored). Browsers apply it when they draw the image. */\n readonly orientation: number;\n /** Several frames: an animated GIF, PNG (APNG), WebP or AVIF. */\n readonly animated: boolean;\n /** What the file carries besides the image itself, in the order of {@link METADATA_KINDS}. */\n readonly metadata: readonly MetadataKind[];\n}\n\nexport const MIME_TYPES: Readonly<Record<ImageFormat, string>> = {\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n heic: 'image/heic',\n bmp: 'image/bmp',\n};\n\n/** Collects findings while a parser walks a file. */\nexport class Found {\n /** An Exif block holding only the orientation (what stripping leaves). */\n orientationOnly = false;\n readonly kinds = new Set<MetadataKind>();\n width: number | null = null;\n height: number | null = null;\n orientation = 1;\n animated = false;\n\n add(kind: MetadataKind): void {\n this.kinds.add(kind);\n }\n\n /** Records an Exif block: `null` when it could not be read (still Exif). */\n exif(summary: TiffSummary | null): void {\n if (summary === null || !summary.onlyOrientation) this.add('exif');\n if (summary === null) return;\n if (summary.onlyOrientation) this.orientationOnly = true;\n this.orientation = summary.orientation;\n if (summary.gps) this.add('gps');\n if (summary.thumbnail) this.add('thumbnail');\n }\n\n info(format: ImageFormat | null): ImageInfo {\n return {\n format,\n mimeType: format === null ? null : MIME_TYPES[format],\n width: this.width,\n height: this.height,\n orientation: this.orientation,\n animated: this.animated,\n metadata: METADATA_KINDS.filter((kind) => this.kinds.has(kind)),\n };\n }\n}\n\nexport interface StripSettings {\n /** Keep the ICC colour profile. */\n readonly colorProfile: boolean;\n /** Keep Exif orientation (as a minimal Exif block) so the image displays the right way up. */\n readonly orientation: boolean;\n}\n\n/** A parsed file: what it holds, and how to write it without its metadata (`null` when the format can't be stripped losslessly). */\nexport interface Parsed {\n readonly info: ImageInfo;\n /** Its only Exif is an orientation-only block (not reported as metadata). */\n readonly orientationOnly?: boolean;\n readonly strip: ((settings: StripSettings) => { readonly parts: readonly Uint8Array[]; readonly removed: ReadonlySet<MetadataKind> }) | null;\n}\n","import type { Bytes } from './bytes';\nimport { readTiff } from './exif';\nimport { Found, type ImageFormat, type Parsed } from './types';\n\ninterface Box {\n readonly type: string;\n /** Start of the payload (after the header). */\n readonly body: number;\n readonly end: number;\n}\n\n/** Boxes between `start` and `end`. Bounded: a hostile file can't make this loop forever. */\nfunction boxes(bytes: Bytes, start: number, end: number): Box[] {\n const out: Box[] = [];\n for (let at = start; at + 8 <= end && out.length < 4096; ) {\n let size = bytes.u32(at, false) as number;\n const type = bytes.ascii(at + 4, 4) as string;\n let body = at + 8;\n if (size === 1) {\n // 64-bit size: files over 4 GiB are never read into memory here, so the high word must be 0.\n if (bytes.u32(at + 8, false) !== 0) break;\n size = bytes.u32(at + 12, false) ?? 0;\n body = at + 16;\n } else if (size === 0) {\n size = end - at;\n }\n if (size < body - at || at + size > end) break;\n out.push({ type, body, end: at + size });\n at += size;\n }\n return out;\n}\n\nconst child = (bytes: Bytes, parent: Box, type: string, skip = 0): Box | undefined =>\n boxes(bytes, parent.body + skip, parent.end).find((box) => box.type === type);\n\n/** Reads an unsigned big-endian integer of 0, 4 or 8 bytes (8-byte values must fit 32 bits). */\nfunction sized(bytes: Bytes, at: number, size: number): number | null {\n if (size === 0) return 0;\n if (size === 4) return bytes.u32(at, false);\n if (size === 8) return bytes.u32(at, false) === 0 ? bytes.u32(at + 4, false) : null;\n return null;\n}\n\n/** Item ids of `Exif` items, and whether there is XMP (a `mime` item). */\nfunction readItemInfo(file: Bytes, iinf: Box): { readonly exif: number[]; readonly xmp: boolean } {\n const bytes = file.until(iinf.end);\n const version = bytes.u8(iinf.body) ?? 0;\n const entriesAt = iinf.body + 4 + (version === 0 ? 2 : 4);\n const exif: number[] = [];\n let xmp = false;\n for (const infe of boxes(bytes, entriesAt, iinf.end)) {\n if (infe.type !== 'infe') continue;\n const view = bytes.until(infe.end);\n const infeVersion = view.u8(infe.body) ?? 0;\n if (infeVersion < 2) continue;\n const id = infeVersion === 2 ? view.u16(infe.body + 4, false) : view.u32(infe.body + 4, false);\n const typeAt = infe.body + 4 + (infeVersion === 2 ? 2 : 4) + 2;\n const itemType = view.ascii(typeAt, 4);\n if (itemType === 'Exif' && id !== null) exif.push(id);\n if (itemType === 'mime') xmp = true;\n }\n return { exif, xmp };\n}\n\n/** Where item `id` is stored in the file (construction method 0, first extent), or `null`. */\nfunction itemLocation(file: Bytes, iloc: Box, id: number): { readonly start: number; readonly end: number } | null {\n const bytes = file.until(iloc.end);\n const version = bytes.u8(iloc.body) ?? 0;\n const sizes = bytes.u16(iloc.body + 4, false) ?? 0;\n const offsetSize = sizes >> 12;\n const lengthSize = (sizes >> 8) & 0x0f;\n const baseSize = (sizes >> 4) & 0x0f;\n const indexSize = version === 1 || version === 2 ? sizes & 0x0f : 0;\n let at = iloc.body + 6;\n const count = version < 2 ? bytes.u16(at, false) : bytes.u32(at, false);\n at += version < 2 ? 2 : 4;\n for (let item = 0; item < (count ?? 0) && item < 4096; item += 1) {\n const itemId = version < 2 ? bytes.u16(at, false) : bytes.u32(at, false);\n at += version < 2 ? 2 : 4;\n let method = 0;\n if (version === 1 || version === 2) {\n method = (bytes.u16(at, false) ?? 0) & 0x0f;\n at += 2;\n }\n at += 2; // data_reference_index\n const base = sized(bytes, at, baseSize);\n at += baseSize;\n const extents = bytes.u16(at, false) ?? 0;\n at += 2;\n let first: { start: number; end: number } | null = null;\n for (let extent = 0; extent < extents; extent += 1) {\n at += indexSize;\n const offset = sized(bytes, at, offsetSize);\n const length = sized(bytes, at + offsetSize, lengthSize);\n at += offsetSize + lengthSize;\n if (extent === 0 && base !== null && offset !== null && length !== null) first = { start: base + offset, end: base + offset + length };\n }\n if (itemId === id) return method === 0 ? first : null;\n }\n return null;\n}\n\n/** AVIF and HEIC (HEIF): size, animation and metadata. Not strippable without re-encoding. */\nexport function parseBmff(bytes: Bytes, format: ImageFormat): Parsed {\n const found = new Found();\n const top = boxes(bytes, 0, bytes.length);\n const ftyp = top[0] as Box;\n const brands = bytes.ascii(ftyp.body, Math.max(0, ftyp.end - ftyp.body)) as string; // Boxes never end past the data.\n found.animated = brands.includes('avis') || brands.includes('msf1') || brands.includes('hevs') || top.some((box) => box.type === 'moov');\n const meta = top.find((box) => box.type === 'meta');\n if (meta !== undefined) {\n // `meta` is a full box: version and flags come first.\n const ipco = ((iprp) => (iprp === undefined ? undefined : child(bytes, iprp, 'ipco')))(child(bytes, meta, 'iprp', 4));\n let area = 0;\n for (const property of ipco === undefined ? [] : boxes(bytes, ipco.body, ipco.end)) {\n if (property.type === 'colr') {\n if (bytes.ascii(property.body, 4) !== 'nclx') found.add('icc');\n }\n // A full box with a width and a height: anything shorter is skipped, never read past its end.\n if (property.type !== 'ispe' || property.end - property.body < 12) continue;\n // The largest image spatial extent is the primary image; smaller ones are thumbnails or tiles.\n const width = bytes.u32(property.body + 4, false) as number;\n const height = bytes.u32(property.body + 8, false) as number;\n if (width * height > area) {\n area = width * height;\n found.width = width;\n found.height = height;\n }\n }\n const iinf = child(bytes, meta, 'iinf', 4);\n const iloc = child(bytes, meta, 'iloc', 4);\n const items = iinf === undefined ? { exif: [], xmp: false } : readItemInfo(bytes, iinf);\n if (items.xmp) found.add('xmp');\n for (const id of items.exif) {\n found.add('exif');\n const location = iloc === undefined ? null : itemLocation(bytes, iloc, id);\n // An Exif item starts with the offset of the TIFF header within it.\n const skip = location === null ? null : bytes.u32(location.start, false);\n if (location === null || skip === null) continue;\n const summary = readTiff(bytes, location.start + 4 + skip, location.end);\n if (summary === null) continue;\n if (summary.gps) found.add('gps');\n if (summary.thumbnail) found.add('thumbnail');\n }\n }\n return { info: found.info(format), strip: null };\n}\n\n/** Which ISO BMFF image format the `ftyp` brands name, if any. */\nexport function bmffFormat(bytes: Bytes): ImageFormat | null {\n if (bytes.ascii(4, 4) !== 'ftyp') return null;\n // `ftyp` at 4 means at least 8 bytes: both reads are in range.\n const size = bytes.u32(0, false) as number;\n const brands = bytes.ascii(8, Math.max(0, Math.min(size, bytes.length) - 8)) as string;\n const list = brands.match(/.{4}/g) ?? [];\n if (list.some((brand) => brand === 'avif' || brand === 'avis')) return 'avif';\n if (list.some((brand) => ['heic', 'heix', 'heim', 'heis', 'hevc', 'hevx', 'mif1', 'msf1'].includes(brand))) return 'heic';\n return null;\n}\n","import type { Bytes } from './bytes';\nimport { Found, type MetadataKind, type Parsed } from './types';\n\ninterface Block {\n readonly start: number;\n readonly end: number;\n /** Metadata kind when the block is metadata, `null` for image data and rendering blocks. */\n readonly kind: MetadataKind | null;\n}\n\n/** The end of a run of data sub-blocks starting at `at` (after its terminating zero), or `null` if cut off. */\nfunction skipSubBlocks(bytes: Bytes, at: number): number | null {\n let position = at;\n for (;;) {\n const size = bytes.u8(position);\n if (size === null) return null;\n position += 1 + size;\n if (size === 0) return position;\n }\n}\n\n/** Application extensions that are part of the picture: looping and the colour profile. */\nconst ANIMATION_APPS = new Set(['NETSCAPE2.0', 'ANIMEXTS1.0']);\n\nexport function parseGif(bytes: Bytes): Parsed {\n const found = new Found();\n found.width = bytes.u16(6, true);\n found.height = bytes.u16(8, true);\n const packed = bytes.u8(10) ?? 0;\n const header = 13 + ((packed & 0x80) !== 0 ? 3 * 2 ** ((packed & 0x07) + 1) : 0);\n const blocks: Block[] = [];\n let frames = 0;\n let at = header;\n let trailer = -1;\n while (at < bytes.length) {\n const introducer = bytes.u8(at);\n if (introducer === 0x3b) {\n trailer = at;\n break;\n }\n let end: number | null = null;\n let kind: MetadataKind | null = null;\n if (introducer === 0x2c) {\n frames += 1;\n const flags = bytes.u8(at + 9) ?? 0;\n const table = (flags & 0x80) !== 0 ? 3 * 2 ** ((flags & 0x07) + 1) : 0;\n // Descriptor (10 bytes), local colour table, LZW minimum code size, then the data sub-blocks.\n end = skipSubBlocks(bytes, at + 10 + table + 1);\n } else if (introducer === 0x21) {\n const label = bytes.u8(at + 1);\n if (label === 0xfe) {\n kind = 'comment';\n } else if (label === 0xff) {\n // The identifier is an 11-byte sub-block; any other size is not a known application.\n const app = bytes.u8(at + 2) === 11 ? (bytes.ascii(at + 3, 11) ?? '') : '';\n if (app === 'ICCRGBG1012') kind = 'icc';\n else if (app === 'XMP DataXMP') kind = 'xmp';\n else if (!ANIMATION_APPS.has(app)) kind = 'other';\n }\n end = skipSubBlocks(bytes, at + 2);\n }\n if (end === null || end > bytes.length) break; // Corrupt or cut off: keep what was read.\n if (kind !== null) found.add(kind);\n blocks.push({ start: at, end, kind });\n at = end;\n }\n found.animated = frames > 1;\n if (trailer >= 0 && trailer + 1 < bytes.length) found.add('other'); // Data after the trailer.\n\n const strip = (settings: { readonly colorProfile: boolean }) => {\n const removed = new Set<MetadataKind>(found.kinds);\n const parts: Uint8Array[] = [bytes.slice(0, header)];\n for (const block of blocks) {\n if (block.kind === 'icc' && settings.colorProfile) removed.delete('icc');\n else if (block.kind !== null) continue;\n parts.push(bytes.slice(block.start, block.end));\n }\n parts.push(Uint8Array.of(0x3b));\n return { parts, removed };\n };\n return { info: found.info('gif'), strip };\n}\n","import { latin1, type Bytes } from './bytes';\nimport { orientationTiff, readTiff, tiffStart } from './exif';\nimport { Found, type MetadataKind, type Parsed, type StripSettings } from './types';\n\ninterface Segment {\n readonly marker: number;\n /** From the 0xFF of the marker to the end of the segment (and, for SOS, its entropy-coded data). */\n readonly start: number;\n readonly end: number;\n /** What it is, when it is metadata; `null` for image data. */\n readonly kind: MetadataKind | null;\n}\n\nconst SOI = 0xd8;\nconst EOI = 0xd9;\nconst SOS = 0xda;\nconst APP0 = 0xe0;\nconst APP1 = 0xe1;\nconst APP2 = 0xe2;\nconst APP13 = 0xed;\nconst APP14 = 0xee;\nconst COM = 0xfe;\n/** SOF markers carry the frame size; C4 (DHT), C8 (JPG) and CC (DAC) are not frames. */\nconst isFrame = (marker: number): boolean => marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;\n/** Markers without a length: TEM and the restart markers. */\nconst isStandalone = (marker: number): boolean => marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7);\n\n/** The JFIF APP0 segment with its thumbnail removed (the 14 fixed bytes after the identifier, size zeroed). */\nfunction jfifWithoutThumbnail(bytes: Bytes, segment: Segment): Uint8Array {\n // Shorter than a full JFIF header: nothing to remove, keep it as it is.\n if (segment.end - segment.start < 18) return bytes.slice(segment.start, segment.end);\n const head = bytes.slice(segment.start, segment.start + 18);\n const out = new Uint8Array(head);\n out[2] = 0;\n out[3] = 16; // Length: 2 + 5 (identifier) + 9.\n out[16] = 0; // Thumbnail width and height.\n out[17] = 0;\n return out;\n}\n\nfunction classify(bytes: Bytes, marker: number, body: number, end: number, found: Found): MetadataKind | null {\n if (marker === APP1) {\n if (bytes.startsWith(body, 'Exif\\0')) {\n found.exif(readTiff(bytes, tiffStart(bytes, body), end));\n return 'exif';\n }\n if (bytes.startsWith(body, 'http://ns.adobe.com/')) {\n found.add('xmp');\n return 'xmp';\n }\n }\n if (marker === APP0) {\n if (bytes.startsWith(body, 'JFIF\\0')) {\n // Thumbnail width and height, when the segment is long enough to hold them.\n if (end - body >= 14 && (bytes.u8(body + 12) as number) * (bytes.u8(body + 13) as number) > 0) found.add('thumbnail');\n return null;\n }\n if (bytes.startsWith(body, 'JFXX\\0')) {\n found.add('thumbnail');\n return 'thumbnail';\n }\n }\n if (marker === APP2 && bytes.startsWith(body, 'ICC_PROFILE\\0')) {\n found.add('icc');\n return 'icc';\n }\n // Adobe's colour transform: needed to decode CMYK and YCCK files correctly.\n if (marker === APP14 && bytes.startsWith(body, 'Adobe')) return null;\n if (marker === APP13) {\n found.add('iptc');\n return 'iptc';\n }\n if (marker === COM) {\n found.add('comment');\n return 'comment';\n }\n // Other APPn: MPF (multi-picture: previews, depth maps), C2PA (APP11), vendor data.\n if (marker >= APP0 && marker <= 0xef) {\n found.add('other');\n return 'other';\n }\n return null;\n}\n\n/** Parses a JPEG from its markers: never decodes the image data, only skips over it. */\nexport function parseJpeg(bytes: Bytes): Parsed {\n const found = new Found();\n const segments: Segment[] = [];\n let at = 2;\n let end = bytes.length;\n while (at + 1 < bytes.length) {\n if (bytes.u8(at) !== 0xff) break; // Corrupt: keep what was read so far.\n const marker = bytes.u8(at + 1) as number;\n if (marker === 0xff) {\n at += 1; // Fill byte.\n continue;\n }\n if (marker === SOI || isStandalone(marker)) {\n segments.push({ marker, start: at, end: at + 2, kind: null });\n at += 2;\n continue;\n }\n if (marker === EOI) {\n end = at + 2;\n break;\n }\n const length = bytes.u16(at + 2, false);\n if (length === null || length < 2 || at + 2 + length > bytes.length) break;\n let segmentEnd = at + 2 + length;\n const body = at + 4;\n if (isFrame(marker)) {\n const frame = bytes.until(segmentEnd);\n found.height = frame.u16(body + 1, false);\n found.width = frame.u16(body + 3, false);\n }\n if (marker === SOS) {\n // Entropy-coded data runs to the next marker that is not a stuffed 0xFF00 or a restart marker.\n let scan = segmentEnd;\n while (scan + 1 < bytes.length) {\n if (bytes.u8(scan) === 0xff) {\n const next = bytes.u8(scan + 1) as number;\n if (next !== 0x00 && next !== 0xff && !isStandalone(next)) break;\n }\n scan += 1;\n }\n segmentEnd = scan + 1 < bytes.length ? scan : bytes.length;\n }\n // Classified from its own bytes only: an empty or short segment never borrows the next one's.\n segments.push({ marker, start: at, end: segmentEnd, kind: classify(bytes.until(segmentEnd), marker, body, segmentEnd, found) });\n at = segmentEnd;\n }\n // Data after the end of the image: motion-photo videos, MPF images, anything appended.\n if (end < bytes.length) found.add('other');\n\n const strip = (settings: StripSettings) => {\n const removed = new Set<MetadataKind>(found.kinds);\n const parts: Uint8Array[] = [Uint8Array.of(0xff, SOI)];\n let wroteExif = false;\n const writeOrientation = (): void => {\n if (wroteExif || !settings.orientation || found.orientation === 1) return;\n const payload = [latin1('Exif\\0\\0'), orientationTiff(found.orientation)];\n const length = 2 + 6 + 26;\n parts.push(Uint8Array.of(0xff, APP1, length >> 8, length & 0xff), ...payload);\n wroteExif = true;\n };\n for (const segment of segments) {\n const { marker, kind } = segment;\n if (marker === APP0 && kind === null) {\n parts.push(jfifWithoutThumbnail(bytes, segment));\n writeOrientation();\n continue;\n }\n if (kind === 'icc' && settings.colorProfile) {\n removed.delete('icc');\n } else if (kind !== null) {\n continue;\n }\n // The orientation block goes before the image data.\n if (marker !== APP0 && (marker < APP0 || marker > 0xef)) writeOrientation();\n parts.push(bytes.slice(segment.start, segment.end));\n }\n writeOrientation();\n parts.push(Uint8Array.of(0xff, EOI));\n return { parts, removed };\n };\n return { info: found.info('jpeg'), strip, orientationOnly: found.orientationOnly };\n}\n","import { concat, latin1, u32be, type Bytes } from './bytes';\nimport { orientationTiff, readTiff } from './exif';\nimport { Found, type MetadataKind, type Parsed, type StripSettings } from './types';\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (ISO 3309), as PNG chunks use it. */\nexport function crc32(data: Uint8Array): number {\n if (table === null) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n += 1) {\n let c = n;\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (const byte of data) crc = (table[(crc ^ byte) & 0xff] as number) ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nexport function pngChunk(type: string, data: Uint8Array): Uint8Array {\n const body = concat([latin1(type), data]);\n return concat([u32be(data.length), body, u32be(crc32(body))]);\n}\n\n/** Chunks that are part of the picture: how it is decoded, coloured, animated or sized. Everything else is dropped. */\nconst IMAGE_CHUNKS = new Set([\n 'IHDR', 'PLTE', 'IDAT', 'IEND', 'tRNS', 'gAMA', 'cHRM', 'sRGB', 'sBIT', 'pHYs', 'bKGD', 'hIST', 'sPLT',\n 'acTL', 'fcTL', 'fdAT', 'cICP', 'mDCV', 'cLLI',\n]);\n\ninterface Chunk {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n}\n\nexport function parsePng(bytes: Bytes): Parsed {\n const found = new Found();\n const chunks: Chunk[] = [];\n found.width = bytes.u32(16, false);\n found.height = bytes.u32(20, false);\n for (let at = 8; at + 12 <= bytes.length; ) {\n const length = bytes.u32(at, false) as number;\n const type = bytes.ascii(at + 4, 4) as string;\n const end = at + 12 + length;\n if (end > bytes.length) break;\n chunks.push({ type, start: at, end });\n const data = at + 8;\n // Read from the chunk's data only, never from the next chunk.\n const chunkBytes = bytes.until(data + length);\n if (type === 'acTL') found.animated = true;\n else if (type === 'iCCP') found.add('icc');\n else if (type === 'eXIf') {\n found.exif(readTiff(chunkBytes, data, data + length));\n } else if (type === 'iTXt' && chunkBytes.startsWith(data, 'XML:com.adobe.xmp\\0')) found.add('xmp');\n else if (type === 'tEXt' || type === 'zTXt' || type === 'iTXt' || type === 'tIME') found.add('text');\n else if (!IMAGE_CHUNKS.has(type)) found.add('other');\n at = end;\n if (type === 'IEND') {\n if (end < bytes.length) found.add('other'); // Data appended after the image.\n break;\n }\n }\n\n const strip = (settings: StripSettings) => {\n const removed = new Set<MetadataKind>(found.kinds);\n const parts: Uint8Array[] = [bytes.slice(0, 8)];\n for (const chunk of chunks) {\n const keepIcc = chunk.type === 'iCCP' && settings.colorProfile;\n if (!IMAGE_CHUNKS.has(chunk.type) && !keepIcc) continue;\n if (keepIcc) removed.delete('icc');\n parts.push(bytes.slice(chunk.start, chunk.end));\n // eXIf must come before the image data: right after the header.\n if (chunk.type === 'IHDR' && settings.orientation && found.orientation !== 1) parts.push(pngChunk('eXIf', orientationTiff(found.orientation)));\n }\n return { parts, removed };\n };\n return { info: found.info('png'), strip, orientationOnly: found.orientationOnly };\n}\n","import { latin1, u32le, type Bytes } from './bytes';\nimport { orientationTiff, readTiff, tiffStart } from './exif';\nimport { Found, type MetadataKind, type Parsed, type StripSettings } from './types';\n\nconst IMAGE_CHUNKS = new Set(['VP8 ', 'VP8L', 'VP8X', 'ALPH', 'ANIM', 'ANMF']);\nconst FLAG_ANIMATION = 0x02;\nconst FLAG_XMP = 0x04;\nconst FLAG_EXIF = 0x08;\nconst FLAG_ICC = 0x20;\n\ninterface Chunk {\n readonly type: string;\n readonly start: number;\n /** End including the padding byte of odd-sized chunks. */\n readonly end: number;\n}\n\n/** A RIFF chunk for data of even length (the orientation block is 26 bytes), so it needs no padding byte. */\nfunction riffChunk(type: string, data: Uint8Array): Uint8Array[] {\n return [latin1(type), u32le(data.length), data];\n}\n\nexport function parseWebp(bytes: Bytes): Parsed {\n const found = new Found();\n const chunks: Chunk[] = [];\n const riffEnd = Math.min(bytes.length, 8 + (bytes.u32(4, true) as number));\n for (let at = 12; at + 8 <= riffEnd; ) {\n const type = bytes.ascii(at, 4) as string;\n const size = bytes.u32(at + 4, true) as number;\n const data = at + 8;\n const end = Math.min(riffEnd, data + size + (size % 2));\n if (data + size > riffEnd) break;\n chunks.push({ type, start: at, end });\n const chunkBytes = bytes.until(data + size);\n if (type === 'VP8X') {\n found.animated = ((chunkBytes.u8(data) ?? 0) & FLAG_ANIMATION) !== 0;\n const width = chunkBytes.u24le(data + 4);\n const height = chunkBytes.u24le(data + 7);\n found.width = width === null ? null : width + 1;\n found.height = height === null ? null : height + 1;\n } else if (type === 'VP8 ' && found.width === null) {\n const width = chunkBytes.u16(data + 6, true);\n const height = chunkBytes.u16(data + 8, true);\n found.width = width === null ? null : width & 0x3fff;\n found.height = height === null ? null : height & 0x3fff;\n } else if (type === 'VP8L' && found.width === null) {\n const bits = chunkBytes.u32(data + 1, true);\n found.width = bits === null ? null : (bits & 0x3fff) + 1;\n found.height = bits === null ? null : ((bits >>> 14) & 0x3fff) + 1;\n } else if (type === 'ANIM') {\n found.animated = true;\n } else if (type === 'ICCP') {\n found.add('icc');\n } else if (type === 'EXIF') {\n found.exif(readTiff(chunkBytes, tiffStart(chunkBytes, data), data + size));\n } else if (type === 'XMP ') {\n found.add('xmp');\n } else if (!IMAGE_CHUNKS.has(type)) {\n found.add('other');\n }\n at = end;\n }\n if (riffEnd < bytes.length) found.add('other'); // Data after the RIFF container.\n\n const strip = (settings: StripSettings) => {\n const removed = new Set<MetadataKind>(found.kinds);\n const keepIcc = settings.colorProfile && found.kinds.has('icc');\n if (keepIcc) removed.delete('icc');\n const exif = settings.orientation && found.orientation !== 1 ? orientationTiff(found.orientation) : null;\n const body: Uint8Array[] = [];\n for (const chunk of chunks) {\n if (chunk.type === 'VP8X') {\n const header = new Uint8Array(bytes.slice(chunk.start, chunk.end));\n let flags = (header[8] as number) & ~(FLAG_XMP | FLAG_EXIF);\n if (!keepIcc) flags &= ~FLAG_ICC;\n if (exif !== null) flags |= FLAG_EXIF;\n header[8] = flags;\n body.push(header);\n } else if (IMAGE_CHUNKS.has(chunk.type) || (chunk.type === 'ICCP' && keepIcc)) {\n body.push(bytes.slice(chunk.start, chunk.end));\n }\n }\n // Exif comes after the image data in the extended format. It only exists in files that have VP8X.\n if (exif !== null) body.push(...riffChunk('EXIF', exif));\n let size = 4;\n for (const part of body) size += part.length;\n return { parts: [latin1('RIFF'), u32le(size), latin1('WEBP'), ...body], removed };\n };\n return { info: found.info('webp'), strip, orientationOnly: found.orientationOnly };\n}\n","import { copyFailure } from '../core/errors';\nimport { DEFAULT_IMAGE_MAX_INPUT_BYTES, outputBlob, readBlob, type Bytes } from './bytes';\nimport { bmffFormat, parseBmff } from './bmff';\nimport { parseGif } from './gif';\nimport { parseJpeg } from './jpeg';\nimport { parsePng } from './png';\nimport { MIME_TYPES, METADATA_KINDS, Found, type ImageInfo, type MetadataKind, type Parsed } from './types';\nimport { parseWebp } from './webp';\n\n/** Recognises the format from the bytes and parses it. */\nexport function parse(bytes: Bytes): Parsed {\n if (bytes.u8(0) === 0xff && bytes.u8(1) === 0xd8 && bytes.u8(2) === 0xff) return parseJpeg(bytes);\n // The PNG signature (0x89 \"PNG\" CR LF 0x1A LF), compared as numbers so no control character is in the code.\n if (bytes.u32(0, false) === 0x89504e47 && bytes.u32(4, false) === 0x0d0a1a0a) return parsePng(bytes);\n if (bytes.startsWith(0, 'GIF87a') || bytes.startsWith(0, 'GIF89a')) return parseGif(bytes);\n if (bytes.startsWith(0, 'RIFF') && bytes.startsWith(8, 'WEBP')) return parseWebp(bytes);\n const bmff = bmffFormat(bytes);\n if (bmff !== null) return parseBmff(bytes, bmff);\n if (bytes.startsWith(0, 'BM') && bytes.length >= 26) {\n const found = new Found();\n found.width = bytes.u32(18, true);\n // Bottom-up files store a positive height, top-down ones a negative one.\n found.height = Math.abs((bytes.u32(22, true) as number) | 0);\n // No metadata to remove: the file is its own clean copy.\n return { info: found.info('bmp'), strip: () => ({ parts: [bytes.data], removed: new Set() }) };\n }\n return { info: new Found().info(null), strip: null };\n}\n\nexport interface ReadImageInfoOptions {\n /** Refuse files larger than this. Default {@link DEFAULT_IMAGE_MAX_INPUT_BYTES} (100 MiB). */\n readonly maxInputBytes?: number;\n}\n\nexport function inputLimit(value: number | undefined): number {\n if (value === undefined) return DEFAULT_IMAGE_MAX_INPUT_BYTES;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`maxInputBytes\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/**\n * What an image file is and what it carries, read from its bytes without\n * decoding the picture: format, stored size, orientation, animation, and the\n * metadata in it (Exif, GPS location, thumbnails, XMP, IPTC, comments, colour\n * profile, appended data). The claimed MIME type and file name are never\n * trusted. Works anywhere, including on the server.\n *\n * @example\n * const info = await readImageInfo(file);\n * if (info.metadata.includes('gps')) warn('This photo contains its location.');\n */\nexport async function readImageInfo(blob: Blob, options: ReadImageInfoOptions = {}): Promise<ImageInfo> {\n return parse(await readBlob(blob, inputLimit(options.maxInputBytes))).info;\n}\n\nexport interface StripMetadataOptions extends ReadImageInfoOptions {\n /** Keep the ICC colour profile, which changes how colours display. Default `true`. */\n readonly keepColorProfile?: boolean;\n /**\n * Keep the Exif orientation (as a 26-byte Exif block with nothing else), so a\n * photo still displays the right way up. Default `true`.\n */\n readonly keepOrientation?: boolean;\n}\n\nexport interface StrippedImage {\n /** The image without its metadata: the same Blob when there was nothing to remove, a File when given one. */\n readonly blob: Blob;\n /** What the input held. */\n readonly info: ImageInfo;\n /** What was removed, in the order of {@link METADATA_KINDS}. */\n readonly removed: readonly MetadataKind[];\n}\n\nexport function flag(value: unknown, fallback: boolean, name: string): boolean {\n if (value === undefined) return fallback;\n if (typeof value === 'boolean') return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a boolean.`);\n}\n\n/** Strips a parsed file; shared with `prepareImage`. Returns `null` when the format can't be stripped losslessly. */\nexport function stripParsed(parsed: Parsed, source: Blob, keepColorProfile: boolean, keepOrientation: boolean): StrippedImage | null {\n if (parsed.strip === null) return null;\n const { parts, removed } = parsed.strip({ colorProfile: keepColorProfile, orientation: keepOrientation });\n // An orientation-only Exif block is not reported as metadata, but removing it is a change.\n const kinds = METADATA_KINDS.filter((kind) => removed.has(kind) || (kind === 'exif' && !keepOrientation && parsed.orientationOnly === true));\n const blob = kinds.length === 0 ? source : outputBlob(parts, MIME_TYPES[parsed.info.format as keyof typeof MIME_TYPES], source);\n return { blob, info: parsed.info, removed: kinds };\n}\n\n/**\n * Removes metadata from a JPEG, PNG, WebP or GIF without re-encoding it: the\n * picture stays bit-for-bit the same. Removes Exif (camera, dates, serial\n * numbers, GPS location), embedded thumbnails, XMP, IPTC, comments, text chunks,\n * multi-picture and depth images, content credentials and data appended after\n * the image. Keeps the colour profile and orientation unless told otherwise.\n * Works anywhere, including on the server.\n *\n * AVIF and HEIC can't be stripped losslessly: this throws `unsupported-format`\n * for them (and for files that aren't images); `prepareImage` re-encodes them.\n *\n * @example\n * const { blob, removed } = await stripMetadata(file);\n * if (removed.includes('gps')) notice('Location removed from the photo.');\n */\nexport async function stripMetadata(blob: Blob, options: StripMetadataOptions = {}): Promise<StrippedImage> {\n const keepColorProfile = flag(options.keepColorProfile, true, 'keepColorProfile');\n const keepOrientation = flag(options.keepOrientation, true, 'keepOrientation');\n const parsed = parse(await readBlob(blob, inputLimit(options.maxInputBytes)));\n const stripped = stripParsed(parsed, blob, keepColorProfile, keepOrientation);\n if (stripped === null) {\n throw copyFailure(\n 'unsupported-format',\n parsed.info.format === null\n ? 'Not an image this module can read (JPEG, PNG, WebP, GIF, BMP, AVIF or HEIC).'\n : `${(parsed.info.mimeType as string)} metadata can't be removed without re-encoding; use prepareImage().`,\n );\n }\n return stripped;\n}\n","import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n","import { CopyFailure, copyFailure } from '../core/errors';\nimport { withDeadline } from '../capture/deadline';\nimport { Bytes, readBlob } from './bytes';\nimport { flag, inputLimit, parse, stripParsed } from './info';\nimport { METADATA_KINDS, type ImageInfo, type MetadataKind } from './types';\n\n/** Formats `prepareImage` can write. */\nexport type OutputImageType = 'image/png' | 'image/jpeg' | 'image/webp';\n\n/** A decoded picture, already turned the right way up. */\nexport interface DecodedImage {\n readonly width: number;\n readonly height: number;\n /** Platform-specific (an `ImageBitmap` in browsers). */\n readonly source: unknown;\n /** Frees the decoded pixels. */\n readonly close: () => void;\n}\n\nexport interface EncodeTarget {\n readonly width: number;\n readonly height: number;\n readonly type: OutputImageType;\n /** 0-1, for JPEG and WebP. */\n readonly quality: number;\n /** CSS colour painted under transparent pixels; always set for JPEG, which has no transparency. */\n readonly background: string | null;\n}\n\n/**\n * Everything `prepareImage` needs from the platform. The default uses\n * `createImageBitmap` and a canvas (`OffscreenCanvas` when there is one, so it\n * also works in workers). Inject your own for other decoders (e.g. a WebAssembly\n * HEIC decoder), native shells or tests.\n */\nexport interface ImageEnvironment {\n readonly decode: (blob: Blob, signal: AbortSignal) => Promise<DecodedImage>;\n /** Draws the image at the target size and encodes it. May return another type when the browser can't encode the one asked for. */\n readonly encode: (image: DecodedImage, target: EncodeTarget, signal: AbortSignal) => Promise<Blob>;\n}\n\ntype Canvas = OffscreenCanvas | HTMLCanvasElement;\n\nfunction createCanvas(width: number, height: number): Canvas {\n if (typeof OffscreenCanvas === 'function') return new OffscreenCanvas(width, height);\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n}\n\nfunction context(canvas: Canvas): OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D {\n const ctx = canvas.getContext('2d');\n if (ctx === null) throw copyFailure('unsupported', 'Canvas 2D rendering is not available.');\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n return ctx;\n}\n\nfunction toBlob(canvas: Canvas, type: string, quality: number): Promise<Blob> {\n if ('convertToBlob' in canvas) return canvas.convertToBlob({ type, quality });\n return new Promise((resolve, reject) => {\n canvas.toBlob(\n (blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'The canvas produced no image (too large for this browser?).'));\n },\n type,\n quality,\n );\n });\n}\n\n/**\n * Draws `image` at the target size. Large reductions halve the size in steps, as\n * one big reduction skips pixels and makes text and edges shimmer.\n */\nfunction draw(image: DecodedImage, target: EncodeTarget): Canvas {\n let source = image.source as CanvasImageSource;\n let width = image.width;\n let height = image.height;\n while (width / 2 >= target.width && height / 2 >= target.height) {\n width = Math.round(width / 2);\n height = Math.round(height / 2);\n const step = createCanvas(width, height);\n context(step).drawImage(source, 0, 0, width, height);\n source = step;\n }\n const canvas = createCanvas(target.width, target.height);\n const ctx = context(canvas);\n if (target.background !== null) {\n ctx.fillStyle = target.background;\n ctx.fillRect(0, 0, target.width, target.height);\n }\n ctx.drawImage(source, 0, 0, target.width, target.height);\n return canvas;\n}\n\n/** The browser environment, or `null` where there is no `createImageBitmap` or canvas (servers, old browsers). */\nexport function getDefaultImageEnvironment(): ImageEnvironment | null {\n if (typeof createImageBitmap !== 'function' || (typeof OffscreenCanvas !== 'function' && typeof document === 'undefined')) return null;\n return {\n decode: async (blob) => {\n // `from-image` turns the picture by its Exif orientation, so the result is upright.\n const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });\n return { width: bitmap.width, height: bitmap.height, source: bitmap, close: () => { bitmap.close(); } };\n },\n encode: (image, target) => toBlob(draw(image, target), target.type, target.quality),\n };\n}\n\n/* ------------------------------------------------------------------ Options */\n\nexport const DEFAULT_IMAGE_MAX_INPUT_PIXELS = 100_000_000;\n/** 4096 x 4096: the canvas area limit of Safari and iOS, the strictest mainstream engine. */\nexport const DEFAULT_IMAGE_MAX_PIXELS = 16_777_216;\nexport const DEFAULT_IMAGE_QUALITY = 0.85;\nexport const DEFAULT_IMAGE_MIN_QUALITY = 0.5;\nexport const DEFAULT_IMAGE_TIMEOUT_MS = 30_000;\n\nexport interface PrepareImageOptions {\n /** Largest width and height of the result, in pixels. Default: no limit. Images are only made smaller, never larger. */\n readonly maxWidth?: number;\n readonly maxHeight?: number;\n /** Largest pixel area of the result. Default {@link DEFAULT_IMAGE_MAX_PIXELS} (fits Safari's canvas limit). */\n readonly maxPixels?: number;\n /**\n * Largest file size of the result, in bytes. Default: no limit. Lossy formats\n * lower their quality down to `minQuality` first, then the size is reduced.\n * When it can't be met, a `too-large` error says so; the file is never left too big.\n */\n readonly maxBytes?: number;\n /**\n * The format to write. `'auto'` (the default) keeps PNG, JPEG and WebP as they\n * are; GIF and BMP become PNG, AVIF and HEIC become JPEG; and a PNG that can't\n * fit `maxBytes` becomes WebP (or JPEG where WebP can't be encoded).\n */\n readonly type?: 'auto' | OutputImageType;\n /** Quality to start from for JPEG and WebP, 0-1. Default 0.85. */\n readonly quality?: number;\n /** Lowest quality to go to before reducing the size. Default 0.5. */\n readonly minQuality?: number;\n /** CSS colour under transparent pixels when writing JPEG. Default `'#fff'`. */\n readonly background?: string;\n /**\n * Animated GIF, PNG and WebP: `'keep'` (the default) keeps every frame and only\n * removes metadata, so a resize or `maxBytes` it can't meet is a `too-large` error;\n * `'first-frame'` turns it into a still image; `'reject'` refuses it with `unsupported-format`.\n */\n readonly animated?: 'keep' | 'first-frame' | 'reject';\n /** Keep the colour profile when no re-encoding is needed. Re-encoded images are written in sRGB. Default `true`. */\n readonly keepColorProfile?: boolean;\n /** Refuse inputs with more pixels than this, before decoding them (decompression bombs). Default 100 000 000. */\n readonly maxInputPixels?: number;\n /** Refuse files larger than this. Default 100 MiB. */\n readonly maxInputBytes?: number;\n /** Give up after this long. Default 30 000 ms. `Infinity` disables. */\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n /** Platform hooks. Defaults to the browser. */\n readonly environment?: ImageEnvironment;\n}\n\nexport interface PreparedImage {\n /** The result: a File (named like the input, with the new extension) when given a File, else a Blob. */\n readonly file: Blob;\n readonly type: string;\n /** Pixel size as displayed (orientation applied). `null` when the image was only stripped and its size is unknown. */\n readonly width: number | null;\n readonly height: number | null;\n /** Bytes. */\n readonly size: number;\n /** Whether the picture was decoded and written again (`false`: only metadata was removed, losslessly). */\n readonly reencoded: boolean;\n /** Whether it was made smaller. */\n readonly resized: boolean;\n /** The JPEG or WebP quality used, else `null`. */\n readonly quality: number | null;\n /** Metadata the input had and the result doesn't, in the order of {@link METADATA_KINDS}. */\n readonly removed: readonly MetadataKind[];\n /** The input. */\n readonly original: { readonly info: ImageInfo; readonly size: number };\n}\n\nconst invalid = (message: string): CopyFailure => copyFailure('invalid-payload', message);\n\nfunction limit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw invalid(`\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\nfunction unit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (typeof value === 'number' && value > 0 && value <= 1) return value;\n throw invalid(`\\`${name}\\` must be greater than 0 and at most 1 (received ${String(value)}).`);\n}\n\nfunction oneOf<const T extends string>(value: unknown, allowed: readonly T[], fallback: NoInfer<T>, name: string): T {\n if (value === undefined) return fallback;\n if ((allowed as readonly unknown[]).includes(value)) return value as T;\n throw invalid(`\\`${name}\\` must be one of: ${allowed.map((option) => JSON.stringify(option)).join(', ')}.`);\n}\n\nconst EXTENSIONS: Readonly<Record<OutputImageType, string>> = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };\nconst LOSSLESS: ReadonlySet<string> = new Set(['image/png']);\n\n/** The input's name with the extension of `type`. */\nfunction renamed(source: Blob, type: OutputImageType): string | undefined {\n const name = (source as Partial<File>).name;\n if (typeof name !== 'string') return undefined;\n const dot = name.lastIndexOf('.');\n return `${dot > 0 ? name.slice(0, dot) : name}.${EXTENSIONS[type]}`;\n}\n\n/** Output types to try, best first. */\nfunction candidates(requested: 'auto' | OutputImageType, info: ImageInfo): OutputImageType[] {\n if (requested !== 'auto') return [requested];\n switch (info.format) {\n case 'jpeg':\n return ['image/jpeg'];\n case 'webp':\n return ['image/webp', 'image/jpeg'];\n case 'png':\n case 'gif':\n case 'bmp':\n return ['image/png', 'image/webp', 'image/jpeg'];\n default:\n return ['image/jpeg'];\n }\n}\n\n/**\n * Prepares an image for upload: removes metadata (location, camera, thumbnails),\n * makes it fit `maxWidth` / `maxHeight` / `maxPixels`, and compresses it under\n * `maxBytes`. When nothing has to change but the metadata, the picture is not\n * re-encoded at all, so screenshots and photos keep every pixel. Inputs are\n * checked against `maxInputPixels` from their header, before decoding.\n *\n * Needs a browser (`createImageBitmap` and a canvas) only when it has to\n * re-encode; elsewhere that is an `unsupported` error. Every failure is a typed\n * `CopyFailure`: `too-large`, `unsupported-format`, `timeout`, `aborted`, ...\n *\n * @example\n * usePaste({ accept: ['image'], onPaste: async ({ imageFiles }) => {\n * const image = await prepareImage(imageFiles[0], { maxWidth: 2048, maxBytes: 1_000_000 });\n * upload(image.file);\n * } });\n */\nexport async function prepareImage(source: Blob, options: PrepareImageOptions = {}): Promise<PreparedImage> {\n const maxWidth = limit(options.maxWidth, Infinity, 'maxWidth');\n const maxHeight = limit(options.maxHeight, Infinity, 'maxHeight');\n const maxPixels = limit(options.maxPixels, DEFAULT_IMAGE_MAX_PIXELS, 'maxPixels');\n const maxBytes = limit(options.maxBytes, Infinity, 'maxBytes');\n const maxInputPixels = limit(options.maxInputPixels, DEFAULT_IMAGE_MAX_INPUT_PIXELS, 'maxInputPixels');\n const timeoutMs = options.timeoutMs ?? DEFAULT_IMAGE_TIMEOUT_MS;\n if (timeoutMs !== Infinity && !(typeof timeoutMs === 'number' && timeoutMs > 0 && Number.isFinite(timeoutMs))) {\n throw invalid(`\\`timeoutMs\\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);\n }\n const quality = unit(options.quality, DEFAULT_IMAGE_QUALITY, 'quality');\n const minQuality = unit(options.minQuality, Math.min(DEFAULT_IMAGE_MIN_QUALITY, quality), 'minQuality');\n if (minQuality > quality) throw invalid('`minQuality` must not be above `quality`.');\n const requested = oneOf(options.type, ['auto', 'image/png', 'image/jpeg', 'image/webp'], 'auto', 'type');\n const animated = oneOf(options.animated, ['keep', 'first-frame', 'reject'], 'keep', 'animated');\n const keepColorProfile = flag(options.keepColorProfile, true, 'keepColorProfile');\n const background = options.background ?? '#fff';\n if (typeof background !== 'string') throw invalid('`background` must be a CSS colour string.');\n const maxInputBytes = inputLimit(options.maxInputBytes);\n\n return withDeadline(\n async (signal) => {\n const parsed = parse(await readBlob(source, maxInputBytes));\n const { info } = parsed;\n const original = { info, size: source.size };\n if (info.format === null && !source.type.startsWith('image/')) {\n throw copyFailure('unsupported-format', 'Not an image: the bytes match no image format and the type is not image/*.');\n }\n if (info.width !== null && info.height !== null && info.width * info.height > maxInputPixels) {\n throw copyFailure('too-large', `The image has ${String(info.width * info.height)} pixels; maxInputPixels is ${String(maxInputPixels)}.`);\n }\n if (info.animated && animated === 'reject') throw copyFailure('unsupported-format', 'Animated images are not accepted (animated: \"reject\").');\n\n const fits = (width: number | null, height: number | null): boolean =>\n width === null || height === null || (width <= maxWidth && height <= maxHeight && width * height <= maxPixels);\n // Orientations 5-8 swap width and height when displayed. Browsers apply Exif orientation to JPEG and PNG\n // (Chromium doesn't to WebP), so only those are swapped here.\n const swapped = info.orientation >= 5 && (info.format === 'jpeg' || info.format === 'png');\n const shownWidth = swapped ? info.height : info.width;\n const shownHeight = swapped ? info.width : info.height;\n\n // Lossless first: when only the metadata has to go, the pixels stay exactly as they are.\n const keepsType = requested === 'auto' || requested === info.mimeType;\n const keepAnimation = info.animated && animated === 'keep';\n if (keepsType && (fits(shownWidth, shownHeight) || keepAnimation)) {\n const stripped = stripParsed(parsed, source, keepColorProfile, true);\n if (stripped !== null && stripped.blob.size <= maxBytes && fits(shownWidth, shownHeight)) {\n return {\n file: stripped.blob,\n type: info.mimeType as string,\n width: shownWidth,\n height: shownHeight,\n size: stripped.blob.size,\n reencoded: false,\n resized: false,\n quality: null,\n removed: stripped.removed,\n original,\n };\n }\n }\n if (keepAnimation) {\n throw copyFailure('too-large', 'An animated image can only fit the size limits by losing its frames: use animated: \"first-frame\".');\n }\n\n const environment = options.environment ?? getDefaultImageEnvironment();\n if (environment === null) throw copyFailure('unsupported', 'Re-encoding an image needs createImageBitmap and a canvas (a browser).');\n let image: DecodedImage;\n try {\n image = await environment.decode(source, signal);\n } catch (cause) {\n throw cause instanceof CopyFailure ? cause : copyFailure('unsupported-format', 'This browser could not decode the image.', cause);\n }\n try {\n if (image.width * image.height > maxInputPixels) {\n throw copyFailure('too-large', `The image has ${String(image.width * image.height)} pixels; maxInputPixels is ${String(maxInputPixels)}.`);\n }\n const fit = Math.min(1, maxWidth / image.width, maxHeight / image.height, Math.sqrt(maxPixels / (image.width * image.height)));\n return await encodeWithin(environment, image, { info, source, requested, quality, minQuality, maxBytes, background, fit, signal, original });\n } finally {\n image.close();\n }\n },\n { timeoutMs, signal: options.signal, label: 'Preparing the image' },\n );\n}\n\ninterface EncodeSettings {\n readonly info: ImageInfo;\n readonly source: Blob;\n readonly requested: 'auto' | OutputImageType;\n readonly quality: number;\n readonly minQuality: number;\n readonly maxBytes: number;\n readonly background: string;\n readonly fit: number;\n readonly signal: AbortSignal;\n readonly original: PreparedImage['original'];\n}\n\n/** Most encodes one image may take: a few quality steps at a few sizes. */\nconst MAX_ENCODES = 24;\n\n/**\n * Thrown inside the search, never out of it: `unavailable` (this type can't be\n * encoded here, so 'auto' tries the next one) or `exhausted` (the encode budget is spent).\n */\nclass SearchSignal extends Error {\n constructor(readonly reason: 'unavailable' | 'exhausted') {\n super(reason);\n }\n}\n\n/** Finds the best result under `maxBytes`: highest quality first, then the largest size. */\nasync function encodeWithin(environment: ImageEnvironment, image: DecodedImage, settings: EncodeSettings): Promise<PreparedImage> {\n const { info, requested, maxBytes, signal } = settings;\n let encodes = 0;\n let smallest = Infinity;\n const encode = async (type: OutputImageType, scale: number, quality: number): Promise<Blob> => {\n if (signal.aborted) throw copyFailure('aborted', 'Preparing the image was aborted.');\n if (encodes >= MAX_ENCODES) throw new SearchSignal('exhausted');\n encodes += 1;\n const width = Math.max(1, Math.round(image.width * scale));\n const height = Math.max(1, Math.round(image.height * scale));\n let blob: Blob;\n try {\n blob = await environment.encode(image, { width, height, type, quality, background: type === 'image/jpeg' ? settings.background : null }, signal);\n } catch (cause) {\n throw cause instanceof CopyFailure ? cause : copyFailure('blob-generation-failed', `Encoding ${type} failed.`, cause);\n }\n if (blob.type !== type) {\n if (requested !== 'auto') throw copyFailure('unsupported-format', `This browser can't encode ${type}.`);\n throw new SearchSignal('unavailable');\n }\n smallest = Math.min(smallest, blob.size);\n return blob;\n };\n const done = async (blob: Blob, type: OutputImageType, scale: number, quality: number | null): Promise<PreparedImage> => {\n const written = parse(new Bytes(new Uint8Array(await blob.arrayBuffer()))).info;\n const name = renamed(settings.source, type);\n const file =\n typeof File === 'function' && name !== undefined\n ? new File([blob], name, { type, lastModified: (settings.source as Partial<File>).lastModified ?? Date.now() })\n : blob;\n return {\n file,\n type,\n width: Math.max(1, Math.round(image.width * scale)),\n height: Math.max(1, Math.round(image.height * scale)),\n size: blob.size,\n reencoded: true,\n resized: scale < 1,\n quality,\n // Read from the output, not assumed: some encoders add their own colour profile.\n removed: METADATA_KINDS.filter((kind) => info.metadata.includes(kind) && !written.metadata.includes(kind)),\n original: settings.original,\n };\n };\n /** Shrinks the scale by what the bytes say, between 50 % and 90 % per step. */\n const shrink = (scale: number, size: number): number => scale * Math.max(0.5, Math.min(0.9, Math.sqrt(maxBytes / size) * 0.95));\n\n /** One output type: the best fit, or `null` when it can't fit. */\n const search = async (type: OutputImageType): Promise<PreparedImage | null> => {\n let scale = settings.fit;\n if (LOSSLESS.has(type)) {\n // 'auto' tries a lossless format once, at full size, before going lossy.\n for (let attempt = 0; attempt < (requested === 'auto' ? 1 : 8); attempt += 1) {\n const blob = await encode(type, scale, settings.quality);\n if (blob.size <= maxBytes) return done(blob, type, scale, null);\n scale = shrink(scale, blob.size);\n }\n return null;\n }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const top = await encode(type, scale, settings.quality);\n if (top.size <= maxBytes) return done(top, type, scale, settings.quality);\n let low = settings.minQuality;\n let high = settings.quality;\n const floor = await encode(type, scale, low);\n if (floor.size > maxBytes) {\n scale = shrink(scale, floor.size);\n continue;\n }\n // Binary search for the highest quality that fits.\n let best = { blob: floor, quality: low };\n for (let step = 0; step < 4 && high - low > 0.02 && encodes < MAX_ENCODES; step += 1) {\n const middle = Math.round(((low + high) / 2) * 100) / 100;\n const blob = await encode(type, scale, middle);\n if (blob.size <= maxBytes) {\n best = { blob, quality: middle };\n low = middle;\n } else {\n high = middle;\n }\n }\n return done(best.blob, type, scale, best.quality);\n }\n return null;\n };\n\n for (const type of candidates(requested, info)) {\n try {\n const result = await search(type);\n if (result !== null) return result;\n } catch (signalled) {\n if (!(signalled instanceof SearchSignal)) throw signalled;\n if (signalled.reason === 'exhausted') break;\n }\n }\n throw copyFailure(\n 'too-large',\n smallest === Infinity\n ? 'No output format could be encoded here.'\n : `Could not get the image under maxBytes (${String(maxBytes)}); the smallest result was ${String(smallest)} bytes.`,\n );\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;;AAWA,SAAgB,YAAY,MAAqB,S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,qBAAqB,eAAe,MAAM;EAChD,IAAI,UAAU,WAAW,aAAa;CACxC;CAEF,MAAM,YACJ,aACA,aAAa,WACT,4CACA,2CAA2C,OAAO,QAAQ,EAAE,6BAA6B,OAAO,QAAQ,EAAE,QAChH;AACF"}
|
package/dist/image.d.cts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
//#region src/image/bytes.d.ts
|
|
2
|
+
export declare const DEFAULT_IMAGE_MAX_INPUT_BYTES: number;
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/image/types.d.ts
|
|
5
|
+
/** Formats recognised from their bytes (never from a file name or a claimed MIME type). */
|
|
6
|
+
type ImageFormat = 'jpeg' | 'png' | 'gif' | 'webp' | 'avif' | 'heic' | 'bmp';
|
|
7
|
+
/**
|
|
8
|
+
* Kinds of metadata an image can carry.
|
|
9
|
+
*
|
|
10
|
+
* - `exif`: camera, settings, dates, serial numbers (Exif / TIFF tags).
|
|
11
|
+
* - `gps`: a location, inside Exif.
|
|
12
|
+
* - `thumbnail`: an embedded preview, which can show the uncropped original.
|
|
13
|
+
* - `xmp`: Adobe XMP (edit history, authors, often a copy of Exif).
|
|
14
|
+
* - `iptc`: captions, credits and keywords (Photoshop IRB / IPTC).
|
|
15
|
+
* - `comment`: free-text comments (JPEG COM, GIF comment extension).
|
|
16
|
+
* - `text`: text chunks (PNG `tEXt`, `zTXt`, `iTXt`, `tIME`).
|
|
17
|
+
* - `icc`: an ICC colour profile. Kept by default: it changes how colours look.
|
|
18
|
+
* - `other`: anything else outside the image data: vendor segments, multi-picture
|
|
19
|
+
* (MPF) and depth images, content credentials (C2PA), data appended after the
|
|
20
|
+
* image (motion photos), unknown chunks.
|
|
21
|
+
*/
|
|
22
|
+
type MetadataKind = 'exif' | 'gps' | 'thumbnail' | 'xmp' | 'iptc' | 'comment' | 'text' | 'icc' | 'other';
|
|
23
|
+
/** Every metadata kind, in a stable order. */
|
|
24
|
+
export declare const METADATA_KINDS: readonly MetadataKind[];
|
|
25
|
+
interface ImageInfo {
|
|
26
|
+
/** `null` when the bytes are not a format this module reads. */
|
|
27
|
+
readonly format: ImageFormat | null;
|
|
28
|
+
/** e.g. `image/jpeg`; `null` when `format` is. */
|
|
29
|
+
readonly mimeType: string | null;
|
|
30
|
+
/** Stored pixel size (before orientation), when the header gives it. */
|
|
31
|
+
readonly width: number | null;
|
|
32
|
+
readonly height: number | null;
|
|
33
|
+
/** Exif orientation, 1-8 (1 = as stored). Browsers apply it when they draw the image. */
|
|
34
|
+
readonly orientation: number;
|
|
35
|
+
/** Several frames: an animated GIF, PNG (APNG), WebP or AVIF. */
|
|
36
|
+
readonly animated: boolean;
|
|
37
|
+
/** What the file carries besides the image itself, in the order of {@link METADATA_KINDS}. */
|
|
38
|
+
readonly metadata: readonly MetadataKind[];
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/image/info.d.ts
|
|
42
|
+
interface ReadImageInfoOptions {
|
|
43
|
+
/** Refuse files larger than this. Default {@link DEFAULT_IMAGE_MAX_INPUT_BYTES} (100 MiB). */
|
|
44
|
+
readonly maxInputBytes?: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* What an image file is and what it carries, read from its bytes without
|
|
48
|
+
* decoding the picture: format, stored size, orientation, animation, and the
|
|
49
|
+
* metadata in it (Exif, GPS location, thumbnails, XMP, IPTC, comments, colour
|
|
50
|
+
* profile, appended data). The claimed MIME type and file name are never
|
|
51
|
+
* trusted. Works anywhere, including on the server.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* const info = await readImageInfo(file);
|
|
55
|
+
* if (info.metadata.includes('gps')) warn('This photo contains its location.');
|
|
56
|
+
*/
|
|
57
|
+
export declare function readImageInfo(blob: Blob, options?: ReadImageInfoOptions): Promise<ImageInfo>;
|
|
58
|
+
interface StripMetadataOptions extends ReadImageInfoOptions {
|
|
59
|
+
/** Keep the ICC colour profile, which changes how colours display. Default `true`. */
|
|
60
|
+
readonly keepColorProfile?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Keep the Exif orientation (as a 26-byte Exif block with nothing else), so a
|
|
63
|
+
* photo still displays the right way up. Default `true`.
|
|
64
|
+
*/
|
|
65
|
+
readonly keepOrientation?: boolean;
|
|
66
|
+
}
|
|
67
|
+
interface StrippedImage {
|
|
68
|
+
/** The image without its metadata: the same Blob when there was nothing to remove, a File when given one. */
|
|
69
|
+
readonly blob: Blob;
|
|
70
|
+
/** What the input held. */
|
|
71
|
+
readonly info: ImageInfo;
|
|
72
|
+
/** What was removed, in the order of {@link METADATA_KINDS}. */
|
|
73
|
+
readonly removed: readonly MetadataKind[];
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Removes metadata from a JPEG, PNG, WebP or GIF without re-encoding it: the
|
|
77
|
+
* picture stays bit-for-bit the same. Removes Exif (camera, dates, serial
|
|
78
|
+
* numbers, GPS location), embedded thumbnails, XMP, IPTC, comments, text chunks,
|
|
79
|
+
* multi-picture and depth images, content credentials and data appended after
|
|
80
|
+
* the image. Keeps the colour profile and orientation unless told otherwise.
|
|
81
|
+
* Works anywhere, including on the server.
|
|
82
|
+
*
|
|
83
|
+
* AVIF and HEIC can't be stripped losslessly: this throws `unsupported-format`
|
|
84
|
+
* for them (and for files that aren't images); `prepareImage` re-encodes them.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* const { blob, removed } = await stripMetadata(file);
|
|
88
|
+
* if (removed.includes('gps')) notice('Location removed from the photo.');
|
|
89
|
+
*/
|
|
90
|
+
export declare function stripMetadata(blob: Blob, options?: StripMetadataOptions): Promise<StrippedImage>;
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/image/prepare.d.ts
|
|
93
|
+
/** Formats `prepareImage` can write. */
|
|
94
|
+
type OutputImageType = 'image/png' | 'image/jpeg' | 'image/webp';
|
|
95
|
+
/** A decoded picture, already turned the right way up. */
|
|
96
|
+
interface DecodedImage {
|
|
97
|
+
readonly width: number;
|
|
98
|
+
readonly height: number;
|
|
99
|
+
/** Platform-specific (an `ImageBitmap` in browsers). */
|
|
100
|
+
readonly source: unknown;
|
|
101
|
+
/** Frees the decoded pixels. */
|
|
102
|
+
readonly close: () => void;
|
|
103
|
+
}
|
|
104
|
+
interface EncodeTarget {
|
|
105
|
+
readonly width: number;
|
|
106
|
+
readonly height: number;
|
|
107
|
+
readonly type: OutputImageType;
|
|
108
|
+
/** 0-1, for JPEG and WebP. */
|
|
109
|
+
readonly quality: number;
|
|
110
|
+
/** CSS colour painted under transparent pixels; always set for JPEG, which has no transparency. */
|
|
111
|
+
readonly background: string | null;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Everything `prepareImage` needs from the platform. The default uses
|
|
115
|
+
* `createImageBitmap` and a canvas (`OffscreenCanvas` when there is one, so it
|
|
116
|
+
* also works in workers). Inject your own for other decoders (e.g. a WebAssembly
|
|
117
|
+
* HEIC decoder), native shells or tests.
|
|
118
|
+
*/
|
|
119
|
+
interface ImageEnvironment {
|
|
120
|
+
readonly decode: (blob: Blob, signal: AbortSignal) => Promise<DecodedImage>;
|
|
121
|
+
/** Draws the image at the target size and encodes it. May return another type when the browser can't encode the one asked for. */
|
|
122
|
+
readonly encode: (image: DecodedImage, target: EncodeTarget, signal: AbortSignal) => Promise<Blob>;
|
|
123
|
+
}
|
|
124
|
+
/** The browser environment, or `null` where there is no `createImageBitmap` or canvas (servers, old browsers). */
|
|
125
|
+
export declare function getDefaultImageEnvironment(): ImageEnvironment | null;
|
|
126
|
+
export declare const DEFAULT_IMAGE_MAX_INPUT_PIXELS = 100000000;
|
|
127
|
+
/** 4096 x 4096: the canvas area limit of Safari and iOS, the strictest mainstream engine. */
|
|
128
|
+
export declare const DEFAULT_IMAGE_MAX_PIXELS = 16777216;
|
|
129
|
+
export declare const DEFAULT_IMAGE_QUALITY = 0.85;
|
|
130
|
+
export declare const DEFAULT_IMAGE_MIN_QUALITY = 0.5;
|
|
131
|
+
export declare const DEFAULT_IMAGE_TIMEOUT_MS = 30000;
|
|
132
|
+
interface PrepareImageOptions {
|
|
133
|
+
/** Largest width and height of the result, in pixels. Default: no limit. Images are only made smaller, never larger. */
|
|
134
|
+
readonly maxWidth?: number;
|
|
135
|
+
readonly maxHeight?: number;
|
|
136
|
+
/** Largest pixel area of the result. Default {@link DEFAULT_IMAGE_MAX_PIXELS} (fits Safari's canvas limit). */
|
|
137
|
+
readonly maxPixels?: number;
|
|
138
|
+
/**
|
|
139
|
+
* Largest file size of the result, in bytes. Default: no limit. Lossy formats
|
|
140
|
+
* lower their quality down to `minQuality` first, then the size is reduced.
|
|
141
|
+
* When it can't be met, a `too-large` error says so; the file is never left too big.
|
|
142
|
+
*/
|
|
143
|
+
readonly maxBytes?: number;
|
|
144
|
+
/**
|
|
145
|
+
* The format to write. `'auto'` (the default) keeps PNG, JPEG and WebP as they
|
|
146
|
+
* are; GIF and BMP become PNG, AVIF and HEIC become JPEG; and a PNG that can't
|
|
147
|
+
* fit `maxBytes` becomes WebP (or JPEG where WebP can't be encoded).
|
|
148
|
+
*/
|
|
149
|
+
readonly type?: 'auto' | OutputImageType;
|
|
150
|
+
/** Quality to start from for JPEG and WebP, 0-1. Default 0.85. */
|
|
151
|
+
readonly quality?: number;
|
|
152
|
+
/** Lowest quality to go to before reducing the size. Default 0.5. */
|
|
153
|
+
readonly minQuality?: number;
|
|
154
|
+
/** CSS colour under transparent pixels when writing JPEG. Default `'#fff'`. */
|
|
155
|
+
readonly background?: string;
|
|
156
|
+
/**
|
|
157
|
+
* Animated GIF, PNG and WebP: `'keep'` (the default) keeps every frame and only
|
|
158
|
+
* removes metadata, so a resize or `maxBytes` it can't meet is a `too-large` error;
|
|
159
|
+
* `'first-frame'` turns it into a still image; `'reject'` refuses it with `unsupported-format`.
|
|
160
|
+
*/
|
|
161
|
+
readonly animated?: 'keep' | 'first-frame' | 'reject';
|
|
162
|
+
/** Keep the colour profile when no re-encoding is needed. Re-encoded images are written in sRGB. Default `true`. */
|
|
163
|
+
readonly keepColorProfile?: boolean;
|
|
164
|
+
/** Refuse inputs with more pixels than this, before decoding them (decompression bombs). Default 100 000 000. */
|
|
165
|
+
readonly maxInputPixels?: number;
|
|
166
|
+
/** Refuse files larger than this. Default 100 MiB. */
|
|
167
|
+
readonly maxInputBytes?: number;
|
|
168
|
+
/** Give up after this long. Default 30 000 ms. `Infinity` disables. */
|
|
169
|
+
readonly timeoutMs?: number;
|
|
170
|
+
readonly signal?: AbortSignal;
|
|
171
|
+
/** Platform hooks. Defaults to the browser. */
|
|
172
|
+
readonly environment?: ImageEnvironment;
|
|
173
|
+
}
|
|
174
|
+
interface PreparedImage {
|
|
175
|
+
/** The result: a File (named like the input, with the new extension) when given a File, else a Blob. */
|
|
176
|
+
readonly file: Blob;
|
|
177
|
+
readonly type: string;
|
|
178
|
+
/** Pixel size as displayed (orientation applied). `null` when the image was only stripped and its size is unknown. */
|
|
179
|
+
readonly width: number | null;
|
|
180
|
+
readonly height: number | null;
|
|
181
|
+
/** Bytes. */
|
|
182
|
+
readonly size: number;
|
|
183
|
+
/** Whether the picture was decoded and written again (`false`: only metadata was removed, losslessly). */
|
|
184
|
+
readonly reencoded: boolean;
|
|
185
|
+
/** Whether it was made smaller. */
|
|
186
|
+
readonly resized: boolean;
|
|
187
|
+
/** The JPEG or WebP quality used, else `null`. */
|
|
188
|
+
readonly quality: number | null;
|
|
189
|
+
/** Metadata the input had and the result doesn't, in the order of {@link METADATA_KINDS}. */
|
|
190
|
+
readonly removed: readonly MetadataKind[];
|
|
191
|
+
/** The input. */
|
|
192
|
+
readonly original: {
|
|
193
|
+
readonly info: ImageInfo;
|
|
194
|
+
readonly size: number;
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Prepares an image for upload: removes metadata (location, camera, thumbnails),
|
|
199
|
+
* makes it fit `maxWidth` / `maxHeight` / `maxPixels`, and compresses it under
|
|
200
|
+
* `maxBytes`. When nothing has to change but the metadata, the picture is not
|
|
201
|
+
* re-encoded at all, so screenshots and photos keep every pixel. Inputs are
|
|
202
|
+
* checked against `maxInputPixels` from their header, before decoding.
|
|
203
|
+
*
|
|
204
|
+
* Needs a browser (`createImageBitmap` and a canvas) only when it has to
|
|
205
|
+
* re-encode; elsewhere that is an `unsupported` error. Every failure is a typed
|
|
206
|
+
* `CopyFailure`: `too-large`, `unsupported-format`, `timeout`, `aborted`, ...
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* usePaste({ accept: ['image'], onPaste: async ({ imageFiles }) => {
|
|
210
|
+
* const image = await prepareImage(imageFiles[0], { maxWidth: 2048, maxBytes: 1_000_000 });
|
|
211
|
+
* upload(image.file);
|
|
212
|
+
* } });
|
|
213
|
+
*/
|
|
214
|
+
export declare function prepareImage(source: Blob, options?: PrepareImageOptions): Promise<PreparedImage>;
|
|
215
|
+
//#endregion
|
|
216
|
+
export type { DecodedImage, EncodeTarget, ImageEnvironment, ImageFormat, ImageInfo, MetadataKind, OutputImageType, PrepareImageOptions, PreparedImage, ReadImageInfoOptions, StripMetadataOptions, StrippedImage };
|
|
217
|
+
//# sourceMappingURL=image.d.cts.map
|