@character-foundry/character-foundry 0.4.2-dev.1765942273 → 0.4.2

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.
Files changed (53) hide show
  1. package/dist/charx.cjs +2 -2
  2. package/dist/charx.cjs.map +1 -1
  3. package/dist/charx.d.cts +9 -18
  4. package/dist/charx.d.ts +9 -18
  5. package/dist/charx.js +2 -2
  6. package/dist/charx.js.map +1 -1
  7. package/dist/exporter.cjs +2 -2
  8. package/dist/exporter.cjs.map +1 -1
  9. package/dist/exporter.d.cts +9 -18
  10. package/dist/exporter.d.ts +9 -18
  11. package/dist/exporter.js +2 -2
  12. package/dist/exporter.js.map +1 -1
  13. package/dist/federation.d.cts +9 -18
  14. package/dist/federation.d.ts +9 -18
  15. package/dist/index.cjs +2 -2
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +21 -42
  18. package/dist/index.d.ts +21 -42
  19. package/dist/index.js +2 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/loader.cjs +2 -2
  22. package/dist/loader.cjs.map +1 -1
  23. package/dist/loader.d.cts +14 -28
  24. package/dist/loader.d.ts +14 -28
  25. package/dist/loader.js +2 -2
  26. package/dist/loader.js.map +1 -1
  27. package/dist/lorebook.d.cts +17 -34
  28. package/dist/lorebook.d.ts +17 -34
  29. package/dist/normalizer.cjs +2 -2
  30. package/dist/normalizer.cjs.map +1 -1
  31. package/dist/normalizer.d.cts +30 -60
  32. package/dist/normalizer.d.ts +30 -60
  33. package/dist/normalizer.js +2 -2
  34. package/dist/normalizer.js.map +1 -1
  35. package/dist/png.cjs +2 -2
  36. package/dist/png.cjs.map +1 -1
  37. package/dist/png.d.cts +16 -32
  38. package/dist/png.d.ts +16 -32
  39. package/dist/png.js +2 -2
  40. package/dist/png.js.map +1 -1
  41. package/dist/schemas.cjs +2 -2
  42. package/dist/schemas.cjs.map +1 -1
  43. package/dist/schemas.d.cts +48 -96
  44. package/dist/schemas.d.ts +48 -96
  45. package/dist/schemas.js +2 -2
  46. package/dist/schemas.js.map +1 -1
  47. package/dist/voxta.cjs +2 -2
  48. package/dist/voxta.cjs.map +1 -1
  49. package/dist/voxta.d.cts +14 -28
  50. package/dist/voxta.d.ts +14 -28
  51. package/dist/voxta.js +2 -2
  52. package/dist/voxta.js.map +1 -1
  53. package/package.json +4 -4
package/dist/voxta.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../core/src/binary.ts","../../core/src/base64.ts","../../core/src/errors.ts","../../core/src/data-url.ts","../../core/src/uri.ts","../../core/src/image.ts","../../core/src/uuid.ts","../../core/src/binary.ts","../../core/src/zip.ts","../../voxta/src/types.ts","../../voxta/src/reader.ts","../../voxta/src/writer.ts","../../voxta/src/macros.ts","../../voxta/src/mapper.ts","../../voxta/src/merge.ts","../../voxta/src/loss.ts","../../voxta/src/enricher.ts","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/is.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/filesystem.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/elf.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/detect-libc.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/re.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/parse-options.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/identifiers.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/parse.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/coerce.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gte.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/lrucache.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/eq.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/neq.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gt.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lt.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lte.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/cmp.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/comparator.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/range.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/satisfies.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/package.json","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/libvips.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/sharp.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/constructor.js","../../../node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js","../../../node_modules/.pnpm/is-arrayish@0.3.4/node_modules/is-arrayish/index.js","../../../node_modules/.pnpm/simple-swizzle@0.2.4/node_modules/simple-swizzle/index.js","../../../node_modules/.pnpm/color-string@1.9.1/node_modules/color-string/index.js","../../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js","../../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js","../../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js","../../../node_modules/.pnpm/color@4.2.3/node_modules/color/index.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/input.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/resize.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/composite.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/operation.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/colour.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/channel.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/output.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/utility.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/index.js","../../media/src/format.ts","../../media/src/dimensions.ts","../../media/src/thumbnail.ts","../../schemas/src/common.ts","../../schemas/src/ccv2.ts","../../schemas/src/ccv3.ts","../../schemas/src/risu.ts","../../schemas/src/normalized.ts","../../schemas/src/feature-deriver.ts","../../schemas/src/detection.ts","../../schemas/src/normalizer.ts","../../schemas/src/validation.ts"],"sourcesContent":["/**\n * Binary Data Utilities\n *\n * Universal binary data operations using Uint8Array.\n * Works in both Node.js and browser environments.\n */\n\n/**\n * Universal binary data type (works in both environments)\n */\nexport type BinaryData = Uint8Array;\n\n/**\n * Read a 32-bit big-endian unsigned integer\n */\nexport function readUInt32BE(data: BinaryData, offset: number): number {\n return (\n (data[offset]! << 24) |\n (data[offset + 1]! << 16) |\n (data[offset + 2]! << 8) |\n data[offset + 3]!\n ) >>> 0;\n}\n\n/**\n * Write a 32-bit big-endian unsigned integer\n */\nexport function writeUInt32BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 24) & 0xff;\n data[offset + 1] = (value >>> 16) & 0xff;\n data[offset + 2] = (value >>> 8) & 0xff;\n data[offset + 3] = value & 0xff;\n}\n\n/**\n * Read a 16-bit big-endian unsigned integer\n */\nexport function readUInt16BE(data: BinaryData, offset: number): number {\n return ((data[offset]! << 8) | data[offset + 1]!) >>> 0;\n}\n\n/**\n * Write a 16-bit big-endian unsigned integer\n */\nexport function writeUInt16BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 8) & 0xff;\n data[offset + 1] = value & 0xff;\n}\n\n/**\n * Find a byte sequence in binary data\n */\nexport function indexOf(data: BinaryData, search: BinaryData, fromIndex = 0): number {\n outer: for (let i = fromIndex; i <= data.length - search.length; i++) {\n for (let j = 0; j < search.length; j++) {\n if (data[i + j] !== search[j]) continue outer;\n }\n return i;\n }\n return -1;\n}\n\n/**\n * Concatenate multiple binary arrays\n */\nexport function concat(...arrays: BinaryData[]): BinaryData {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Slice binary data (returns a view, not a copy)\n */\nexport function slice(data: BinaryData, start: number, end?: number): BinaryData {\n return data.subarray(start, end);\n}\n\n/**\n * Copy a portion of binary data (returns a new array)\n */\nexport function copy(data: BinaryData, start: number, end?: number): BinaryData {\n return data.slice(start, end);\n}\n\n/**\n * Convert string to binary (UTF-8)\n */\nexport function fromString(str: string): BinaryData {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Convert binary to string (UTF-8)\n */\nexport function toString(data: BinaryData): string {\n return new TextDecoder().decode(data);\n}\n\n/**\n * Convert string to binary (Latin1 - for PNG keywords and similar)\n */\nexport function fromLatin1(str: string): BinaryData {\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i) & 0xff;\n }\n return result;\n}\n\n/**\n * Convert binary to string (Latin1)\n */\nexport function toLatin1(data: BinaryData): string {\n let result = '';\n for (let i = 0; i < data.length; i++) {\n result += String.fromCharCode(data[i]!);\n }\n return result;\n}\n\n/**\n * Compare two binary arrays for equality\n */\nexport function equals(a: BinaryData, b: BinaryData): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Create a new Uint8Array filled with zeros\n */\nexport function alloc(size: number): BinaryData {\n return new Uint8Array(size);\n}\n\n/**\n * Create a Uint8Array from an array of numbers\n */\nexport function from(data: number[] | ArrayBuffer | BinaryData): BinaryData {\n if (data instanceof Uint8Array) {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n return new Uint8Array(data);\n}\n\n/**\n * Check if value is a Uint8Array\n */\nexport function isBinaryData(value: unknown): value is BinaryData {\n return value instanceof Uint8Array;\n}\n\n/**\n * Convert Node.js Buffer to Uint8Array (no-op if already Uint8Array)\n * This provides compatibility when interfacing with Node.js code\n */\nexport function toUint8Array(data: BinaryData | Buffer): BinaryData {\n if (data instanceof Uint8Array) {\n // Buffer extends Uint8Array, but we want a plain Uint8Array\n // This ensures we get a proper Uint8Array in all cases\n if (Object.getPrototypeOf(data).constructor.name === 'Buffer') {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n return data;\n }\n return new Uint8Array(data);\n}\n\n/**\n * Convert binary data to hex string\n */\nexport function toHex(data: BinaryData): string {\n return Array.from(data)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to binary data\n */\nexport function fromHex(hex: string): BinaryData {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n","/**\n * Universal Base64 Encoding/Decoding\n *\n * Works in both Node.js and browser environments.\n */\n\nimport type { BinaryData } from './binary.js';\n\n/**\n * Check if we're in a Node.js environment\n */\nconst isNode = typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null;\n\n/**\n * Threshold for switching to chunked encoding in browsers (1MB)\n * Below this, simple string concatenation is fast enough.\n * Above this, quadratic string growth becomes a problem.\n */\nconst LARGE_BUFFER_THRESHOLD = 1024 * 1024;\n\n/**\n * Encode binary data to base64 string\n *\n * PERFORMANCE: For large buffers (>1MB) in browsers, this automatically\n * uses the chunked implementation to avoid quadratic string concatenation.\n */\nexport function encode(data: BinaryData): string {\n if (isNode) {\n // Node.js: Buffer handles large data efficiently\n return Buffer.from(data).toString('base64');\n }\n\n // Browser: use chunked encoding for large buffers to avoid O(n²) string growth\n if (data.length > LARGE_BUFFER_THRESHOLD) {\n return encodeChunked(data);\n }\n\n // Small buffers: simple approach is fast enough\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]!);\n }\n return btoa(binary);\n}\n\n/**\n * Decode base64 string to binary data\n */\nexport function decode(base64: string): BinaryData {\n if (isNode) {\n // Node.js: use Buffer\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n\n // Browser: use atob\n const binary = atob(base64);\n const result = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n result[i] = binary.charCodeAt(i);\n }\n return result;\n}\n\n/**\n * Check if a string is valid base64\n */\nexport function isBase64(str: string): boolean {\n if (str.length === 0) return false;\n // Base64 regex: only valid base64 characters, length multiple of 4 (with padding)\n const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;\n return base64Regex.test(str) && str.length % 4 === 0;\n}\n\n/**\n * Encode binary data to URL-safe base64 string\n * Replaces + with -, / with _, and removes padding\n */\nexport function encodeUrlSafe(data: BinaryData): string {\n return encode(data)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decode URL-safe base64 string to binary data\n */\nexport function decodeUrlSafe(base64: string): BinaryData {\n // Add back padding if needed\n let padded = base64\n .replace(/-/g, '+')\n .replace(/_/g, '/');\n\n while (padded.length % 4 !== 0) {\n padded += '=';\n }\n\n return decode(padded);\n}\n\n/**\n * Chunk size for encoding large buffers (64KB)\n * Prevents stack overflow when using String.fromCharCode with spread operator\n */\nconst ENCODE_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Encode binary data to base64 string with chunking for large buffers.\n * Handles buffers >10MB without stack overflow.\n *\n * @param data - Binary data to encode\n * @returns Base64 encoded string\n *\n * @example\n * ```typescript\n * const largeBuffer = new Uint8Array(20 * 1024 * 1024); // 20MB\n * const base64 = encodeChunked(largeBuffer); // No stack overflow\n * ```\n */\nexport function encodeChunked(data: BinaryData): string {\n if (isNode) {\n // Node.js: Buffer handles large data efficiently\n return Buffer.from(data).toString('base64');\n }\n\n // Browser: process in chunks to avoid stack overflow\n const chunks: string[] = [];\n\n for (let i = 0; i < data.length; i += ENCODE_CHUNK_SIZE) {\n const chunk = data.subarray(i, Math.min(i + ENCODE_CHUNK_SIZE, data.length));\n let binary = '';\n for (let j = 0; j < chunk.length; j++) {\n binary += String.fromCharCode(chunk[j]!);\n }\n chunks.push(binary);\n }\n\n return btoa(chunks.join(''));\n}\n","/**\n * Error Classes\n *\n * Specific error types for character card operations.\n * All errors extend FoundryError for consistent handling.\n */\n\n/** Symbol to identify FoundryError instances across ESM/CJS boundaries */\nconst FOUNDRY_ERROR_MARKER = Symbol.for('@character-foundry/core:FoundryError');\n\n/**\n * Base error class for all Character Foundry errors\n */\nexport class FoundryError extends Error {\n /** @internal Marker for cross-module identification */\n readonly [FOUNDRY_ERROR_MARKER] = true;\n\n constructor(message: string, public readonly code: string) {\n super(message);\n this.name = 'FoundryError';\n // Maintains proper stack trace in V8 environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error during card parsing\n */\nexport class ParseError extends FoundryError {\n constructor(message: string, public readonly format?: string) {\n super(message, 'PARSE_ERROR');\n this.name = 'ParseError';\n }\n}\n\n/**\n * Error during card validation\n */\nexport class ValidationError extends FoundryError {\n constructor(message: string, public readonly field?: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Asset not found in card or archive\n */\nexport class AssetNotFoundError extends FoundryError {\n constructor(public readonly uri: string) {\n super(`Asset not found: ${uri}`, 'ASSET_NOT_FOUND');\n this.name = 'AssetNotFoundError';\n }\n}\n\n/**\n * Format not supported for operation\n */\nexport class FormatNotSupportedError extends FoundryError {\n constructor(public readonly format: string, operation?: string) {\n const msg = operation\n ? `Format '${format}' not supported for ${operation}`\n : `Format not supported: ${format}`;\n super(msg, 'FORMAT_NOT_SUPPORTED');\n this.name = 'FormatNotSupportedError';\n }\n}\n\n/**\n * File size exceeds limits\n */\nexport class SizeLimitError extends FoundryError {\n constructor(\n public readonly actualSize: number,\n public readonly maxSize: number,\n context?: string\n ) {\n const actualMB = (actualSize / 1024 / 1024).toFixed(2);\n const maxMB = (maxSize / 1024 / 1024).toFixed(2);\n const msg = context\n ? `${context}: Size ${actualMB}MB exceeds limit ${maxMB}MB`\n : `Size ${actualMB}MB exceeds limit ${maxMB}MB`;\n super(msg, 'SIZE_LIMIT_EXCEEDED');\n this.name = 'SizeLimitError';\n }\n}\n\n/**\n * Path traversal or unsafe path detected\n */\nexport class PathTraversalError extends FoundryError {\n constructor(public readonly path: string) {\n super(`Unsafe path detected: ${path}`, 'PATH_TRAVERSAL');\n this.name = 'PathTraversalError';\n }\n}\n\n/**\n * Export operation would lose data\n */\nexport class DataLossError extends FoundryError {\n constructor(\n public readonly lostFields: string[],\n public readonly targetFormat: string\n ) {\n const fields = lostFields.slice(0, 3).join(', ');\n const more = lostFields.length > 3 ? ` and ${lostFields.length - 3} more` : '';\n super(\n `Export to ${targetFormat} would lose: ${fields}${more}`,\n 'DATA_LOSS'\n );\n this.name = 'DataLossError';\n }\n}\n\n/**\n * Check if an error is a FoundryError\n *\n * Uses Symbol.for() marker instead of instanceof to handle dual ESM/CJS package loading.\n * In dual-package environments, instanceof can fail if the error comes from a different\n * module instance (e.g., ESM vs CJS version of the same package). Symbol.for() creates\n * a global symbol shared across all module instances.\n */\nexport function isFoundryError(error: unknown): error is FoundryError {\n return (\n error instanceof Error &&\n FOUNDRY_ERROR_MARKER in error &&\n (error as Record<symbol, unknown>)[FOUNDRY_ERROR_MARKER] === true\n );\n}\n\n/**\n * Wrap unknown errors in a FoundryError\n */\nexport function wrapError(error: unknown, context?: string): FoundryError {\n if (isFoundryError(error)) {\n return error;\n }\n\n const message = error instanceof Error\n ? error.message\n : String(error);\n\n return new FoundryError(\n context ? `${context}: ${message}` : message,\n 'UNKNOWN_ERROR'\n );\n}\n","/**\n * Data URL Utilities\n *\n * Convert between Uint8Array buffers and data URLs.\n * Handles large buffers (>10MB) without stack overflow by processing in chunks.\n */\n\nimport type { BinaryData } from './binary.js';\nimport { encodeChunked as base64Encode, decode as base64Decode } from './base64.js';\nimport { ValidationError } from './errors.js';\n\n/**\n * Convert Uint8Array to data URL.\n * Handles large buffers (>10MB) without stack overflow by processing in chunks.\n *\n * @param buffer - Binary data to encode\n * @param mimeType - MIME type for the data URL (e.g., 'image/png', 'application/octet-stream')\n * @returns Data URL string\n *\n * @example\n * ```typescript\n * const png = new Uint8Array([...]);\n * const dataUrl = toDataURL(png, 'image/png');\n * // => \"data:image/png;base64,iVBORw0KGgo...\"\n * ```\n */\nexport function toDataURL(buffer: BinaryData, mimeType: string): string {\n // Use chunked encoding to handle large buffers without stack overflow\n const base64 = base64Encode(buffer);\n return `data:${mimeType};base64,${base64}`;\n}\n\n/**\n * Parse a data URL back to buffer and MIME type.\n * Validates the data URL format before parsing.\n *\n * @param dataUrl - Data URL string to parse\n * @returns Object containing the decoded buffer and MIME type\n * @throws Error if the data URL format is invalid\n *\n * @example\n * ```typescript\n * const { buffer, mimeType } = fromDataURL('data:image/png;base64,iVBORw0KGgo...');\n * // buffer: Uint8Array\n * // mimeType: 'image/png'\n * ```\n */\nexport function fromDataURL(dataUrl: string): { buffer: Uint8Array; mimeType: string } {\n // Validate data URL format\n if (!dataUrl.startsWith('data:')) {\n throw new ValidationError('Invalid data URL: must start with \"data:\"', 'dataUrl');\n }\n\n const commaIndex = dataUrl.indexOf(',');\n if (commaIndex === -1) {\n throw new ValidationError('Invalid data URL: missing comma separator', 'dataUrl');\n }\n\n const header = dataUrl.slice(5, commaIndex); // Skip 'data:'\n const data = dataUrl.slice(commaIndex + 1);\n\n // Parse header: [<mediatype>][;base64]\n let mimeType = 'text/plain';\n let isBase64 = false;\n\n const parts = header.split(';');\n for (const part of parts) {\n if (part === 'base64') {\n isBase64 = true;\n } else if (part && !part.includes('=')) {\n // MIME type (not a parameter like charset=utf-8)\n mimeType = part;\n }\n }\n\n if (!isBase64) {\n // URL-encoded text data\n throw new ValidationError('Non-base64 data URLs are not supported', 'dataUrl');\n }\n\n const buffer = base64Decode(data);\n return { buffer, mimeType };\n}\n\n/**\n * Check if a string is a valid data URL\n *\n * @param str - String to check\n * @returns true if the string is a valid data URL format\n */\nexport function isDataURL(str: string): boolean {\n if (!str.startsWith('data:')) return false;\n const commaIndex = str.indexOf(',');\n if (commaIndex === -1) return false;\n const header = str.slice(5, commaIndex);\n return header.includes('base64');\n}\n","/**\n * URI Utilities\n *\n * Handles different asset URI schemes used in character cards.\n * Supports: embeded://, embedded://, ccdefault:, https://, http://,\n * data:, file://, __asset:, asset:, chara-ext-asset_\n */\n\nexport type URIScheme =\n | 'embeded' // embeded:// (CharX standard, note intentional typo)\n | 'ccdefault' // ccdefault:\n | 'https' // https://\n | 'http' // http://\n | 'data' // data:mime;base64,...\n | 'file' // file://\n | 'internal' // Internal asset ID (UUID/string)\n | 'pngchunk' // PNG chunk reference (__asset:, asset:, chara-ext-asset_)\n | 'unknown';\n\nexport interface ParsedURI {\n scheme: URIScheme;\n originalUri: string;\n normalizedUri: string; // Normalized form of the URI\n path?: string; // For embeded://, file://\n url?: string; // For http://, https://\n data?: string; // For data: URIs\n mimeType?: string; // For data: URIs\n encoding?: string; // For data: URIs (e.g., base64)\n chunkKey?: string; // For pngchunk - the key/index to look up\n chunkCandidates?: string[]; // For pngchunk - all possible chunk keys to search\n}\n\n/**\n * Normalize a URI to its canonical form\n * Handles common typos and variant formats\n */\nexport function normalizeURI(uri: string): string {\n const trimmed = uri.trim();\n\n // Fix embedded:// -> embeded:// (common typo, CharX spec uses single 'd')\n if (trimmed.startsWith('embedded://')) {\n return 'embeded://' + trimmed.substring('embedded://'.length);\n }\n\n // Normalize PNG chunk references to pngchunk: scheme\n if (trimmed.startsWith('__asset:')) {\n const id = trimmed.substring('__asset:'.length);\n return `pngchunk:${id}`;\n }\n if (trimmed.startsWith('asset:')) {\n const id = trimmed.substring('asset:'.length);\n return `pngchunk:${id}`;\n }\n if (trimmed.startsWith('chara-ext-asset_:')) {\n const id = trimmed.substring('chara-ext-asset_:'.length);\n return `pngchunk:${id}`;\n }\n if (trimmed.startsWith('chara-ext-asset_')) {\n const id = trimmed.substring('chara-ext-asset_'.length);\n return `pngchunk:${id}`;\n }\n\n return trimmed;\n}\n\n/**\n * Parse a URI and determine its scheme and components\n */\nexport function parseURI(uri: string): ParsedURI {\n const trimmed = uri.trim();\n const normalized = normalizeURI(trimmed);\n\n // PNG chunk references (__asset:, asset:, chara-ext-asset_, pngchunk:)\n if (\n trimmed.startsWith('__asset:') ||\n trimmed.startsWith('asset:') ||\n trimmed.startsWith('chara-ext-asset_') ||\n trimmed.startsWith('pngchunk:')\n ) {\n let assetId: string;\n if (trimmed.startsWith('__asset:')) {\n assetId = trimmed.substring('__asset:'.length);\n } else if (trimmed.startsWith('asset:')) {\n assetId = trimmed.substring('asset:'.length);\n } else if (trimmed.startsWith('chara-ext-asset_:')) {\n assetId = trimmed.substring('chara-ext-asset_:'.length);\n } else if (trimmed.startsWith('pngchunk:')) {\n assetId = trimmed.substring('pngchunk:'.length);\n } else {\n assetId = trimmed.substring('chara-ext-asset_'.length);\n }\n\n // Generate all possible chunk key variations for lookup\n const candidates = [\n assetId, // \"0\" or \"filename.png\"\n trimmed, // Original URI\n `asset:${assetId}`, // \"asset:0\"\n `__asset:${assetId}`, // \"__asset:0\"\n `__asset_${assetId}`, // \"__asset_0\"\n `chara-ext-asset_${assetId}`, // \"chara-ext-asset_0\"\n `chara-ext-asset_:${assetId}`, // \"chara-ext-asset_:0\"\n `pngchunk:${assetId}`, // \"pngchunk:0\"\n ];\n\n return {\n scheme: 'pngchunk',\n originalUri: uri,\n normalizedUri: normalized,\n chunkKey: assetId,\n chunkCandidates: candidates,\n };\n }\n\n // ccdefault: - use default asset\n if (trimmed === 'ccdefault:' || trimmed.startsWith('ccdefault:')) {\n return {\n scheme: 'ccdefault',\n originalUri: uri,\n normalizedUri: normalized,\n };\n }\n\n // embeded:// or embedded:// (normalize typo)\n if (trimmed.startsWith('embeded://') || trimmed.startsWith('embedded://')) {\n const path = trimmed.startsWith('embeded://')\n ? trimmed.substring('embeded://'.length)\n : trimmed.substring('embedded://'.length);\n return {\n scheme: 'embeded',\n originalUri: uri,\n normalizedUri: normalized,\n path,\n };\n }\n\n // https://\n if (trimmed.startsWith('https://')) {\n return {\n scheme: 'https',\n originalUri: uri,\n normalizedUri: normalized,\n url: trimmed,\n };\n }\n\n // http://\n if (trimmed.startsWith('http://')) {\n return {\n scheme: 'http',\n originalUri: uri,\n normalizedUri: normalized,\n url: trimmed,\n };\n }\n\n // data: URIs\n if (trimmed.startsWith('data:')) {\n const parsed = parseDataURI(trimmed);\n return {\n scheme: 'data',\n originalUri: uri,\n normalizedUri: normalized,\n ...parsed,\n };\n }\n\n // file://\n if (trimmed.startsWith('file://')) {\n const path = trimmed.substring('file://'.length);\n return {\n scheme: 'file',\n originalUri: uri,\n normalizedUri: normalized,\n path,\n };\n }\n\n // Internal asset ID (alphanumeric/UUID format)\n if (/^[a-zA-Z0-9_-]+$/.test(trimmed)) {\n return {\n scheme: 'internal',\n originalUri: uri,\n normalizedUri: normalized,\n path: trimmed,\n };\n }\n\n // Unknown scheme\n return {\n scheme: 'unknown',\n originalUri: uri,\n normalizedUri: normalized,\n };\n}\n\n/**\n * Parse a data URI into its components\n * Format: data:[<mediatype>][;base64],<data>\n */\nfunction parseDataURI(uri: string): { mimeType?: string; encoding?: string; data?: string } {\n const match = uri.match(/^data:([^;,]+)?(;base64)?,(.*)$/);\n\n if (!match) {\n return {};\n }\n\n return {\n mimeType: match[1] || 'text/plain',\n encoding: match[2] ? 'base64' : undefined,\n data: match[3],\n };\n}\n\n/**\n * Check if extension is an image format\n */\nexport function isImageExt(ext: string): boolean {\n const imageExts = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'];\n return imageExts.includes(ext.toLowerCase());\n}\n\n/**\n * Check if extension is an audio format\n */\nexport function isAudioExt(ext: string): boolean {\n const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac'];\n return audioExts.includes(ext.toLowerCase());\n}\n\n/**\n * Check if extension is a video format\n */\nexport function isVideoExt(ext: string): boolean {\n const videoExts = ['mp4', 'webm', 'avi', 'mov', 'mkv'];\n return videoExts.includes(ext.toLowerCase());\n}\n\n/** Safe MIME types for data: URIs that can be used in href/src */\nconst SAFE_DATA_URI_MIME_TYPES = new Set([\n // Images (safe for img src)\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n // Audio (safe for audio src)\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n 'audio/flac',\n 'audio/mp4',\n 'audio/aac',\n // Video (safe for video src)\n 'video/mp4',\n 'video/webm',\n // Text/data (generally safe)\n 'text/plain',\n 'application/json',\n 'application/octet-stream',\n]);\n\n/** Potentially dangerous MIME types that should NOT be used in href/src */\nconst DANGEROUS_DATA_URI_MIME_TYPES = new Set([\n // Executable/script content\n 'text/html',\n 'text/javascript',\n 'application/javascript',\n 'application/x-javascript',\n 'text/css',\n 'image/svg+xml', // SVG can contain scripts\n 'application/xhtml+xml',\n 'application/xml',\n]);\n\n/**\n * Options for URI safety validation\n */\nexport interface URISafetyOptions {\n /** Allow http:// URIs (default: false) */\n allowHttp?: boolean;\n /** Allow file:// URIs (default: false) */\n allowFile?: boolean;\n /**\n * Allowed MIME types for data: URIs (default: all safe types).\n * Set to empty array to reject all data: URIs.\n * Set to undefined to use default safe list.\n */\n allowedDataMimes?: string[];\n}\n\n/**\n * Result of URI safety check with detailed information\n */\nexport interface URISafetyResult {\n /** Whether the URI is safe to use */\n safe: boolean;\n /** Reason if unsafe */\n reason?: string;\n /** Detected scheme */\n scheme: URIScheme;\n /** MIME type for data: URIs */\n mimeType?: string;\n}\n\n/**\n * Validate if a URI is safe to use (detailed version)\n *\n * @param uri - URI to validate\n * @param options - Safety options\n * @returns Detailed safety result\n */\nexport function checkURISafety(uri: string, options: URISafetyOptions = {}): URISafetyResult {\n const parsed = parseURI(uri);\n\n switch (parsed.scheme) {\n case 'embeded':\n case 'ccdefault':\n case 'internal':\n case 'https':\n case 'pngchunk':\n return { safe: true, scheme: parsed.scheme };\n\n case 'data': {\n const mimeType = parsed.mimeType || 'text/plain';\n\n // Check for explicitly dangerous MIME types\n if (DANGEROUS_DATA_URI_MIME_TYPES.has(mimeType)) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: `Data URI with potentially dangerous MIME type: ${mimeType}`,\n };\n }\n\n // If custom allowed list is provided, check against it\n if (options.allowedDataMimes !== undefined) {\n if (options.allowedDataMimes.length === 0) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: 'Data URIs are not allowed',\n };\n }\n if (!options.allowedDataMimes.includes(mimeType)) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: `Data URI MIME type not in allowed list: ${mimeType}`,\n };\n }\n }\n\n // Otherwise use default safe list\n if (!SAFE_DATA_URI_MIME_TYPES.has(mimeType)) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: `Unknown data URI MIME type: ${mimeType}`,\n };\n }\n\n return { safe: true, scheme: parsed.scheme, mimeType };\n }\n\n case 'http':\n if (options.allowHttp === true) {\n return { safe: true, scheme: parsed.scheme };\n }\n return { safe: false, scheme: parsed.scheme, reason: 'HTTP URIs are not allowed' };\n\n case 'file':\n if (options.allowFile === true) {\n return { safe: true, scheme: parsed.scheme };\n }\n return { safe: false, scheme: parsed.scheme, reason: 'File URIs are not allowed' };\n\n case 'unknown':\n default:\n return { safe: false, scheme: parsed.scheme, reason: 'Unknown URI scheme' };\n }\n}\n\n/**\n * Validate if a URI is safe to use (simple boolean version for backwards compatibility)\n *\n * @deprecated Use checkURISafety() for detailed safety information\n */\nexport function isURISafe(uri: string, options: { allowHttp?: boolean; allowFile?: boolean } = {}): boolean {\n return checkURISafety(uri, options).safe;\n}\n\n/**\n * Extract file extension from URI\n */\nexport function getExtensionFromURI(uri: string): string {\n const parsed = parseURI(uri);\n\n if (parsed.path) {\n const parts = parsed.path.split('.');\n if (parts.length > 1) {\n return parts[parts.length - 1]!.toLowerCase();\n }\n }\n\n if (parsed.url) {\n const urlParts = parsed.url.split('?')[0]!.split('.');\n if (urlParts.length > 1) {\n return urlParts[urlParts.length - 1]!.toLowerCase();\n }\n }\n\n if (parsed.mimeType) {\n return getExtFromMimeType(parsed.mimeType);\n }\n\n return 'unknown';\n}\n\n/**\n * Get MIME type from file extension\n */\nexport function getMimeTypeFromExt(ext: string): string {\n const extToMime: Record<string, string> = {\n // Images\n 'png': 'image/png',\n 'jpg': 'image/jpeg',\n 'jpeg': 'image/jpeg',\n 'webp': 'image/webp',\n 'gif': 'image/gif',\n 'avif': 'image/avif',\n 'svg': 'image/svg+xml',\n 'bmp': 'image/bmp',\n 'ico': 'image/x-icon',\n\n // Audio\n 'mp3': 'audio/mpeg',\n 'wav': 'audio/wav',\n 'ogg': 'audio/ogg',\n 'flac': 'audio/flac',\n 'm4a': 'audio/mp4',\n 'aac': 'audio/aac',\n\n // Video\n 'mp4': 'video/mp4',\n 'webm': 'video/webm',\n 'avi': 'video/x-msvideo',\n 'mov': 'video/quicktime',\n 'mkv': 'video/x-matroska',\n\n // Text/Data\n 'json': 'application/json',\n 'txt': 'text/plain',\n 'html': 'text/html',\n 'css': 'text/css',\n 'js': 'application/javascript',\n };\n\n return extToMime[ext.toLowerCase()] || 'application/octet-stream';\n}\n\n/**\n * Get file extension from MIME type\n */\nexport function getExtFromMimeType(mimeType: string): string {\n const mimeToExt: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/avif': 'avif',\n 'image/svg+xml': 'svg',\n 'image/bmp': 'bmp',\n 'image/x-icon': 'ico',\n 'audio/mpeg': 'mp3',\n 'audio/wav': 'wav',\n 'audio/ogg': 'ogg',\n 'audio/flac': 'flac',\n 'audio/mp4': 'm4a',\n 'audio/aac': 'aac',\n 'video/mp4': 'mp4',\n 'video/webm': 'webm',\n 'video/x-msvideo': 'avi',\n 'video/quicktime': 'mov',\n 'video/x-matroska': 'mkv',\n 'application/json': 'json',\n 'text/plain': 'txt',\n 'text/html': 'html',\n 'text/css': 'css',\n 'application/javascript': 'js',\n };\n\n return mimeToExt[mimeType] || 'bin';\n}\n\n/**\n * Build a data URI from binary data and MIME type\n */\nexport function buildDataURI(data: string, mimeType: string, isBase64 = true): string {\n if (isBase64) {\n return `data:${mimeType};base64,${data}`;\n }\n return `data:${mimeType},${encodeURIComponent(data)}`;\n}\n","/**\n * Image Analysis Utilities\n *\n * Detect properties of image files from binary data.\n */\n\nimport {\n type BinaryData,\n indexOf,\n fromLatin1,\n} from './binary.js';\n\n/**\n * Check if an image buffer contains animation data.\n * Supports: APNG, WebP (Animated), GIF\n */\nexport function isAnimatedImage(data: BinaryData, _mimeType?: string): boolean {\n // 1. WebP Detection\n // RIFF .... WEBP\n if (\n data.length > 12 &&\n data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 && // RIFF\n data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50 // WEBP\n ) {\n // Check for VP8X chunk\n // VP8X chunk header: 'VP8X' (bytes 12-15)\n if (\n data[12] === 0x56 && data[13] === 0x50 && data[14] === 0x38 && data[15] === 0x58\n ) {\n // Flags byte is at offset 20 (16 + 4 bytes chunk size)\n // Animation bit is bit 1 (0x02)\n const flags = data[20];\n return (flags! & 0x02) !== 0;\n }\n return false;\n }\n\n // 2. PNG/APNG Detection\n // Signature: 89 50 4E 47 0D 0A 1A 0A\n if (\n data.length > 8 &&\n data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4E && data[3] === 0x47\n ) {\n // Search for 'acTL' chunk (Animation Control)\n // It must appear before IDAT.\n // Simple search: indexOf('acTL')\n // Note: theoretically 'acTL' string could appear in other data, but highly unlikely in valid PNG structure before IDAT\n // We can iterate chunks to be safe, but indexOf is faster for a quick check\n const actlSig = fromLatin1('acTL');\n const idatSig = fromLatin1('IDAT');\n \n const actlIndex = indexOf(data, actlSig);\n if (actlIndex === -1) return false;\n\n const idatIndex = indexOf(data, idatSig);\n // If acTL exists and is before the first IDAT (or IDAT not found yet), it's APNG\n return idatIndex === -1 || actlIndex < idatIndex;\n }\n\n // 3. GIF Detection\n // Signature: GIF87a or GIF89a\n if (\n data.length > 6 &&\n data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 // GIF\n ) {\n // Check for NETSCAPE2.0 extension (looping animation)\n // This is a heuristic. Static GIFs are rare in this domain but possible.\n // Full frame counting is expensive. Presence of NETSCAPE block is a strong indicator.\n const netscape = fromLatin1('NETSCAPE2.0');\n return indexOf(data, netscape) !== -1;\n }\n\n return false;\n}\n","/**\n * UUID Generation Utilities\n *\n * Provides crypto-grade UUID v4 generation that works in Node.js,\n * browsers (secure contexts), and falls back gracefully.\n */\n\n/**\n * Format 16 random bytes as a UUID v4 string\n */\nfunction formatUUID(bytes: Uint8Array): string {\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Fallback UUID generation using Math.random()\n * Only used when crypto APIs are unavailable (rare)\n */\nfunction mathRandomUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generate a cryptographically secure UUID v4.\n *\n * Uses crypto.randomUUID() when available (Node.js 19+, modern browsers).\n * Falls back to crypto.getRandomValues() if randomUUID is unavailable.\n * Last resort uses Math.random() (non-secure, emits warning in dev).\n *\n * @returns A valid RFC 4122 UUID v4 string\n *\n * @example\n * ```typescript\n * const id = generateUUID();\n * // => \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateUUID(): string {\n // Node.js 19+ or browser with secure context\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n\n // Fallback using crypto.getRandomValues (older Node/browsers)\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n // Set version (4) and variant (RFC 4122)\n bytes[6] = (bytes[6]! & 0x0f) | 0x40; // Version 4\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // Variant 1\n return formatUUID(bytes);\n }\n\n // Last resort - non-secure fallback\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'development') {\n console.warn('[character-foundry/core] generateUUID: Using insecure Math.random() fallback');\n }\n return mathRandomUUID();\n}\n\n/**\n * Validate if a string is a valid UUID v4\n *\n * @param uuid - String to validate\n * @returns true if valid UUID v4 format\n */\nexport function isValidUUID(uuid: string): boolean {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid);\n}\n","/**\n * Binary Data Utilities\n *\n * Universal binary data operations using Uint8Array.\n * Works in both Node.js and browser environments.\n */\n\n/**\n * Universal binary data type (works in both environments)\n */\nexport type BinaryData = Uint8Array;\n\n/**\n * Read a 32-bit big-endian unsigned integer\n */\nexport function readUInt32BE(data: BinaryData, offset: number): number {\n return (\n (data[offset]! << 24) |\n (data[offset + 1]! << 16) |\n (data[offset + 2]! << 8) |\n data[offset + 3]!\n ) >>> 0;\n}\n\n/**\n * Write a 32-bit big-endian unsigned integer\n */\nexport function writeUInt32BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 24) & 0xff;\n data[offset + 1] = (value >>> 16) & 0xff;\n data[offset + 2] = (value >>> 8) & 0xff;\n data[offset + 3] = value & 0xff;\n}\n\n/**\n * Read a 16-bit big-endian unsigned integer\n */\nexport function readUInt16BE(data: BinaryData, offset: number): number {\n return ((data[offset]! << 8) | data[offset + 1]!) >>> 0;\n}\n\n/**\n * Write a 16-bit big-endian unsigned integer\n */\nexport function writeUInt16BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 8) & 0xff;\n data[offset + 1] = value & 0xff;\n}\n\n/**\n * Find a byte sequence in binary data\n */\nexport function indexOf(data: BinaryData, search: BinaryData, fromIndex = 0): number {\n outer: for (let i = fromIndex; i <= data.length - search.length; i++) {\n for (let j = 0; j < search.length; j++) {\n if (data[i + j] !== search[j]) continue outer;\n }\n return i;\n }\n return -1;\n}\n\n/**\n * Concatenate multiple binary arrays\n */\nexport function concat(...arrays: BinaryData[]): BinaryData {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Slice binary data (returns a view, not a copy)\n */\nexport function slice(data: BinaryData, start: number, end?: number): BinaryData {\n return data.subarray(start, end);\n}\n\n/**\n * Copy a portion of binary data (returns a new array)\n */\nexport function copy(data: BinaryData, start: number, end?: number): BinaryData {\n return data.slice(start, end);\n}\n\n/**\n * Convert string to binary (UTF-8)\n */\nexport function fromString(str: string): BinaryData {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Convert binary to string (UTF-8)\n */\nexport function toString(data: BinaryData): string {\n return new TextDecoder().decode(data);\n}\n\n/**\n * Convert string to binary (Latin1 - for PNG keywords and similar)\n */\nexport function fromLatin1(str: string): BinaryData {\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i) & 0xff;\n }\n return result;\n}\n\n/**\n * Convert binary to string (Latin1)\n */\nexport function toLatin1(data: BinaryData): string {\n let result = '';\n for (let i = 0; i < data.length; i++) {\n result += String.fromCharCode(data[i]!);\n }\n return result;\n}\n\n/**\n * Compare two binary arrays for equality\n */\nexport function equals(a: BinaryData, b: BinaryData): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Create a new Uint8Array filled with zeros\n */\nexport function alloc(size: number): BinaryData {\n return new Uint8Array(size);\n}\n\n/**\n * Create a Uint8Array from an array of numbers\n */\nexport function from(data: number[] | ArrayBuffer | BinaryData): BinaryData {\n if (data instanceof Uint8Array) {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n return new Uint8Array(data);\n}\n\n/**\n * Check if value is a Uint8Array\n */\nexport function isBinaryData(value: unknown): value is BinaryData {\n return value instanceof Uint8Array;\n}\n\n/**\n * Convert Node.js Buffer to Uint8Array (no-op if already Uint8Array)\n * This provides compatibility when interfacing with Node.js code\n */\nexport function toUint8Array(data: BinaryData | Buffer): BinaryData {\n if (data instanceof Uint8Array) {\n // Buffer extends Uint8Array, but we want a plain Uint8Array\n // This ensures we get a proper Uint8Array in all cases\n if (Object.getPrototypeOf(data).constructor.name === 'Buffer') {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n return data;\n }\n return new Uint8Array(data);\n}\n\n/**\n * Convert binary data to hex string\n */\nexport function toHex(data: BinaryData): string {\n return Array.from(data)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to binary data\n */\nexport function fromHex(hex: string): BinaryData {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n","/**\n * ZIP Utility Functions\n *\n * Handles ZIP format detection and SFX (self-extracting) archive support.\n * Uses Uint8Array for universal browser/Node.js compatibility.\n */\n\nimport { indexOf, concat, type BinaryData } from './binary.js';\nimport { Unzip, UnzipInflate, UnzipPassThrough, type Unzipped, type UnzipFile } from 'fflate';\n\n// ZIP local file header signature: PK\\x03\\x04\nexport const ZIP_SIGNATURE = new Uint8Array([0x50, 0x4b, 0x03, 0x04]);\n\n// JPEG signatures\nexport const JPEG_SIGNATURE = new Uint8Array([0xff, 0xd8, 0xff]);\n\n/**\n * How to handle unsafe paths (with .. or absolute paths) during extraction.\n *\n * - 'skip': Silently skip unsafe files (default, backwards compatible)\n * - 'warn': Skip and call onUnsafePath callback for logging/monitoring\n * - 'reject': Throw ZipPreflightError immediately (strictest, recommended for untrusted input)\n */\nexport type UnsafePathHandling = 'skip' | 'warn' | 'reject';\n\n/**\n * Size limits for ZIP operations\n */\nexport interface ZipSizeLimits {\n /** Max size per file (default 50MB) */\n maxFileSize: number;\n /** Max total size (default 200MB) */\n maxTotalSize: number;\n /** Max number of files (default 1000) */\n maxFiles: number;\n /**\n * How to handle files with unsafe paths (path traversal attempts).\n *\n * Default: 'skip' (backwards compatible - silently ignores unsafe paths)\n * Recommended: 'reject' for untrusted input (throws on path traversal)\n *\n * @security Path traversal (../) in ZIP entries can lead to arbitrary file\n * overwrites when extracted to disk. While this library returns files in\n * memory, consumers may write to disk using the paths.\n */\n unsafePathHandling?: UnsafePathHandling;\n /**\n * Callback invoked when unsafe path is detected (only with 'warn' handling).\n * Use for logging/monitoring path traversal attempts.\n */\n onUnsafePath?: (path: string, reason: string) => void;\n}\n\nexport const DEFAULT_ZIP_LIMITS: ZipSizeLimits = {\n maxFileSize: 50 * 1024 * 1024, // 50MB per file (Risu standard)\n maxTotalSize: 500 * 1024 * 1024, // 500MB total (CharX can have many expression assets)\n maxFiles: 10000, // CharX cards can have 2k+ expression assets\n unsafePathHandling: 'skip', // Backwards compatible default\n};\n\n/**\n * Check if a buffer contains ZIP data (anywhere in the buffer).\n * This handles both regular ZIPs and SFX (self-extracting) archives.\n * @param data - Binary data to check\n * @returns true if ZIP signature found\n */\nexport function isZipBuffer(data: BinaryData): boolean {\n return indexOf(data, ZIP_SIGNATURE) >= 0;\n}\n\n/**\n * Check if a buffer starts with ZIP signature (standard ZIP detection).\n * @param data - Binary data to check\n * @returns true if data starts with PK\\x03\\x04\n */\nexport function startsWithZipSignature(data: BinaryData): boolean {\n return (\n data.length >= 4 &&\n data[0] === 0x50 &&\n data[1] === 0x4b &&\n data[2] === 0x03 &&\n data[3] === 0x04\n );\n}\n\n/**\n * Check if data starts with JPEG signature\n */\nexport function isJPEG(data: BinaryData): boolean {\n return (\n data.length >= 3 &&\n data[0] === 0xff &&\n data[1] === 0xd8 &&\n data[2] === 0xff\n );\n}\n\n/**\n * Check if data is a JPEG with appended ZIP (JPEG+CharX hybrid)\n */\nexport function isJpegCharX(data: BinaryData): boolean {\n if (!isJPEG(data)) return false;\n // Look for ZIP signature after JPEG data\n return indexOf(data, ZIP_SIGNATURE) > 0;\n}\n\n/**\n * Find ZIP data start in buffer (handles SFX/self-extracting archives).\n * SFX archives have an executable stub prepended to the ZIP data.\n *\n * @param data - Binary data that may contain ZIP data (possibly with SFX prefix)\n * @returns Binary data starting at ZIP signature, or original data if not found/already at start\n */\nexport function findZipStart(data: BinaryData): BinaryData {\n const index = indexOf(data, ZIP_SIGNATURE);\n\n if (index > 0) {\n // SFX archive detected - return data starting at ZIP signature\n return data.subarray(index);\n }\n\n // Either ZIP starts at 0, or no ZIP signature found - return original\n return data;\n}\n\n/**\n * Get the offset of ZIP data within a buffer.\n * @param data - Binary data to search\n * @returns Offset of ZIP signature, or -1 if not found\n */\nexport function getZipOffset(data: BinaryData): number {\n return indexOf(data, ZIP_SIGNATURE);\n}\n\n/**\n * Check if data is a valid ZIP archive (has signature at start or is SFX)\n * @param data - Binary data to check\n * @returns true if data contains valid ZIP structure\n */\nexport function isValidZip(data: BinaryData): boolean {\n const offset = getZipOffset(data);\n if (offset < 0) return false;\n\n // Check if there's enough data after the signature for a minimal ZIP\n // Minimum ZIP: local file header (30 bytes) + central directory (46 bytes) + end of central dir (22 bytes)\n return data.length - offset >= 98;\n}\n\n/**\n * Validate a path for directory traversal attacks\n * @param path - File path to validate\n * @returns true if path is safe\n */\nexport function isPathSafe(path: string): boolean {\n // Reject absolute paths\n if (path.startsWith('/') || /^[a-zA-Z]:/.test(path)) {\n return false;\n }\n\n // Reject path traversal\n if (path.includes('..')) {\n return false;\n }\n\n // Reject backslashes (Windows-style paths that might be used for traversal)\n if (path.includes('\\\\')) {\n return false;\n }\n\n return true;\n}\n\n/**\n * ZIP Central Directory File Header structure\n */\nexport interface ZipCentralDirEntry {\n fileName: string;\n compressedSize: number;\n uncompressedSize: number;\n}\n\n/**\n * Result of preflight ZIP size check\n */\nexport interface ZipPreflightResult {\n entries: ZipCentralDirEntry[];\n totalUncompressedSize: number;\n fileCount: number;\n}\n\n/**\n * Error thrown when ZIP preflight fails due to size limits\n */\nexport class ZipPreflightError extends Error {\n constructor(\n message: string,\n public readonly totalSize?: number,\n public readonly maxSize?: number,\n public readonly oversizedEntry?: string,\n public readonly entrySize?: number,\n public readonly maxEntrySize?: number\n ) {\n super(message);\n this.name = 'ZipPreflightError';\n }\n}\n\n/**\n * Preflight check ZIP central directory to get uncompressed sizes BEFORE extraction.\n * This prevents zip bomb attacks by rejecting archives with dangerous compression ratios\n * or oversized entries without fully decompressing them.\n *\n * The ZIP format stores uncompressed sizes in the central directory at the end of the file.\n * This function reads that metadata without decompressing any actual data.\n *\n * @param data - ZIP file data (can be SFX/self-extracting, will find ZIP start)\n * @param limits - Size limits to enforce\n * @returns Preflight result with entry info and totals\n * @throws ZipPreflightError if limits would be exceeded\n */\nexport function preflightZipSizes(\n data: BinaryData,\n limits: ZipSizeLimits = DEFAULT_ZIP_LIMITS\n): ZipPreflightResult {\n // Find ZIP start (handles SFX/hybrid archives)\n const zipData = findZipStart(data);\n\n // Find End of Central Directory (EOCD) signature: PK\\x05\\x06\n // EOCD is at the end of the file, max comment size is 65535 bytes\n const eocdSignature = new Uint8Array([0x50, 0x4b, 0x05, 0x06]);\n const searchStart = Math.max(0, zipData.length - 65535 - 22);\n\n let eocdOffset = -1;\n for (let i = zipData.length - 22; i >= searchStart; i--) {\n if (\n zipData[i] === eocdSignature[0] &&\n zipData[i + 1] === eocdSignature[1] &&\n zipData[i + 2] === eocdSignature[2] &&\n zipData[i + 3] === eocdSignature[3]\n ) {\n // SECURITY: Validate comment length to avoid false positives\n // If the ZIP comment contains the EOCD signature bytes, we could\n // find the wrong location. Verify by checking comment length.\n // Comment length is at offset +20 (2 bytes, little-endian)\n if (i + 21 < zipData.length) {\n const commentLength = zipData[i + 20]! | (zipData[i + 21]! << 8);\n // True EOCD should be at: file_size - 22 - comment_length\n const expectedOffset = zipData.length - 22 - commentLength;\n if (i === expectedOffset) {\n eocdOffset = i;\n break;\n }\n // Otherwise, this is a false positive (signature in comment), continue searching\n }\n }\n }\n\n if (eocdOffset < 0) {\n throw new ZipPreflightError('Invalid ZIP: End of Central Directory not found');\n }\n\n // Parse EOCD\n // Offset 8: Total number of central directory records\n // Offset 12: Size of central directory\n // Offset 16: Offset of start of central directory\n const totalEntries = zipData[eocdOffset + 8]! | (zipData[eocdOffset + 9]! << 8);\n const _cdSize = readUInt32LEFromBytes(zipData, eocdOffset + 12);\n const cdOffset = readUInt32LEFromBytes(zipData, eocdOffset + 16);\n\n // Check file count limit\n if (totalEntries > limits.maxFiles) {\n throw new ZipPreflightError(\n `ZIP contains ${totalEntries} files, exceeds limit of ${limits.maxFiles}`,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined\n );\n }\n\n // Parse Central Directory entries\n const entries: ZipCentralDirEntry[] = [];\n let totalUncompressedSize = 0;\n let offset = cdOffset;\n\n for (let i = 0; i < totalEntries && offset < eocdOffset; i++) {\n // Central Directory File Header signature: PK\\x01\\x02\n if (\n zipData[offset] !== 0x50 ||\n zipData[offset + 1] !== 0x4b ||\n zipData[offset + 2] !== 0x01 ||\n zipData[offset + 3] !== 0x02\n ) {\n throw new ZipPreflightError('Invalid ZIP: Central Directory header corrupted');\n }\n\n // Offset 20: Compressed size (4 bytes)\n const compressedSize = readUInt32LEFromBytes(zipData, offset + 20);\n // Offset 24: Uncompressed size (4 bytes)\n const uncompressedSize = readUInt32LEFromBytes(zipData, offset + 24);\n // Offset 28: File name length (2 bytes)\n const fileNameLength = zipData[offset + 28]! | (zipData[offset + 29]! << 8);\n // Offset 30: Extra field length (2 bytes)\n const extraLength = zipData[offset + 30]! | (zipData[offset + 31]! << 8);\n // Offset 32: File comment length (2 bytes)\n const commentLength = zipData[offset + 32]! | (zipData[offset + 33]! << 8);\n\n // Read file name\n const fileName = new TextDecoder().decode(\n zipData.subarray(offset + 46, offset + 46 + fileNameLength)\n );\n\n // Skip directories (names ending with /)\n if (!fileName.endsWith('/')) {\n // Check per-entry size limit\n if (uncompressedSize > limits.maxFileSize) {\n throw new ZipPreflightError(\n `File \"${fileName}\" uncompressed size ${uncompressedSize} exceeds limit ${limits.maxFileSize}`,\n undefined,\n undefined,\n fileName,\n uncompressedSize,\n limits.maxFileSize\n );\n }\n\n totalUncompressedSize += uncompressedSize;\n\n // Check total size limit early to fail fast\n if (totalUncompressedSize > limits.maxTotalSize) {\n throw new ZipPreflightError(\n `Total uncompressed size ${totalUncompressedSize} exceeds limit ${limits.maxTotalSize}`,\n totalUncompressedSize,\n limits.maxTotalSize\n );\n }\n\n entries.push({\n fileName,\n compressedSize,\n uncompressedSize,\n });\n }\n\n // Move to next entry\n offset += 46 + fileNameLength + extraLength + commentLength;\n }\n\n return {\n entries,\n totalUncompressedSize,\n fileCount: entries.length,\n };\n}\n\n/**\n * Read a 32-bit little-endian unsigned integer from bytes\n */\nfunction readUInt32LEFromBytes(data: BinaryData, offset: number): number {\n return (\n data[offset]! |\n (data[offset + 1]! << 8) |\n (data[offset + 2]! << 16) |\n (data[offset + 3]! << 24)\n ) >>> 0; // Convert to unsigned\n}\n\n/**\n * Streaming ZIP extraction with real-time byte limit enforcement.\n *\n * Unlike preflightZipSizes which only checks central directory metadata,\n * this function tracks ACTUAL decompressed bytes during extraction and\n * aborts immediately if limits are exceeded. This protects against\n * malicious archives that lie about sizes in their central directory.\n *\n * @security Path safety is enforced based on `limits.unsafePathHandling`:\n * - 'skip' (default): Silently ignores files with unsafe paths\n * - 'warn': Skips unsafe files and calls onUnsafePath callback\n * - 'reject': Throws ZipPreflightError on unsafe paths\n *\n * @performance SYNCHRONOUS BLOCKING OPERATION\n * This function runs synchronously and will block the event loop during\n * decompression. For large archives (>50MB), this can cause UI freezes\n * in browser environments or block the Node.js event loop.\n *\n * Recommendations:\n * - Browser: Use Web Workers for archives >10MB to avoid freezing the UI\n * - Node.js: Consider worker threads for archives >50MB\n * - All environments: Call preflightZipSizes() first to validate before extraction\n *\n * @param data - ZIP file data (can be SFX/self-extracting)\n * @param limits - Size limits to enforce\n * @returns Extracted files (synchronously)\n * @throws ZipPreflightError if limits are exceeded during extraction\n */\nexport function streamingUnzipSync(\n data: BinaryData,\n limits: ZipSizeLimits = DEFAULT_ZIP_LIMITS\n): Unzipped {\n // Find ZIP start (handles SFX/hybrid archives)\n const zipData = findZipStart(data);\n\n const result: Unzipped = {};\n let totalBytes = 0;\n let fileCount = 0;\n let error: Error | null = null;\n\n // Get path handling mode (default to 'skip' for backwards compatibility)\n const unsafePathHandling = limits.unsafePathHandling ?? 'skip';\n\n // Track chunks per file for concatenation\n const fileChunks = new Map<string, Uint8Array[]>();\n\n const unzipper = new Unzip((file: UnzipFile) => {\n if (error) return;\n\n // Skip directories\n if (file.name.endsWith('/')) {\n file.start();\n return;\n }\n\n // SECURITY: Check for path traversal attacks\n if (!isPathSafe(file.name)) {\n const reason = file.name.includes('..')\n ? 'path traversal (..)'\n : file.name.startsWith('/') || /^[a-zA-Z]:/.test(file.name)\n ? 'absolute path'\n : 'backslash in path';\n\n if (unsafePathHandling === 'reject') {\n error = new ZipPreflightError(\n `Unsafe path detected: \"${file.name}\" - ${reason}. ` +\n `This may be a path traversal attack.`\n );\n file.terminate();\n return;\n }\n\n if (unsafePathHandling === 'warn' && limits.onUnsafePath) {\n limits.onUnsafePath(file.name, reason);\n }\n\n // Skip this file (consume but don't store) for 'skip' and 'warn' modes\n // SECURITY: Still count bytes to prevent zip bombs hidden behind unsafe paths\n file.ondata = (err, chunk, _final) => {\n if (error) return;\n if (err) {\n error = err;\n return;\n }\n if (chunk && chunk.length > 0) {\n totalBytes += chunk.length;\n if (totalBytes > limits.maxTotalSize) {\n error = new ZipPreflightError(\n `Total actual size ${totalBytes} exceeds limit ${limits.maxTotalSize}`,\n totalBytes,\n limits.maxTotalSize\n );\n file.terminate();\n }\n }\n };\n file.start();\n return;\n }\n\n fileCount++;\n if (fileCount > limits.maxFiles) {\n error = new ZipPreflightError(\n `File count ${fileCount} exceeds limit ${limits.maxFiles}`\n );\n file.terminate();\n return;\n }\n\n const chunks: Uint8Array[] = [];\n fileChunks.set(file.name, chunks);\n let fileBytes = 0;\n\n file.ondata = (err, chunk, final) => {\n if (error) return;\n\n if (err) {\n error = err;\n return;\n }\n\n if (chunk && chunk.length > 0) {\n fileBytes += chunk.length;\n totalBytes += chunk.length;\n\n // Check per-file size limit (actual decompressed bytes)\n if (fileBytes > limits.maxFileSize) {\n error = new ZipPreflightError(\n `File \"${file.name}\" actual size ${fileBytes} exceeds limit ${limits.maxFileSize}`,\n undefined,\n undefined,\n file.name,\n fileBytes,\n limits.maxFileSize\n );\n file.terminate();\n return;\n }\n\n // Check total size limit (actual decompressed bytes)\n if (totalBytes > limits.maxTotalSize) {\n error = new ZipPreflightError(\n `Total actual size ${totalBytes} exceeds limit ${limits.maxTotalSize}`,\n totalBytes,\n limits.maxTotalSize\n );\n file.terminate();\n return;\n }\n\n chunks.push(chunk);\n }\n\n if (final && !error) {\n // Concatenate all chunks for this file\n result[file.name] = concat(...chunks);\n }\n };\n\n file.start();\n });\n\n // Register decompression handlers\n unzipper.register(UnzipInflate); // DEFLATE (compression method 8)\n unzipper.register(UnzipPassThrough); // Stored (compression method 0)\n\n // Push all data - fflate processes synchronously when given full buffer\n unzipper.push(zipData, true);\n\n // If an error occurred during processing, throw it\n if (error) {\n throw error;\n }\n\n return result;\n}\n\n/**\n * Re-export Unzipped type for convenience\n */\nexport type { Unzipped };\n","/**\n * Voxta Types\n *\n * Type definitions for Voxta package format.\n */\n\nimport type { BinaryData } from '@character-foundry/core';\n\n/**\n * Valid compression levels\n */\nexport type CompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\n\n/**\n * Voxta resource kind enumeration\n * Used in EntryResource, ThumbnailResource, and Collection references\n */\nexport enum VoxtaResourceKind {\n Character = 1,\n Book = 2,\n Scenario = 3,\n}\n\n/**\n * Voxta resource reference\n */\nexport interface VoxtaResourceRef {\n Kind: VoxtaResourceKind | number;\n Id: string;\n}\n\n/**\n * Voxta package metadata\n */\nexport interface VoxtaPackage {\n $type: 'package';\n Id: string;\n Name: string;\n Version: string;\n Description?: string;\n Creator?: string;\n ExplicitContent?: boolean;\n EntryResource?: VoxtaResourceRef;\n ThumbnailResource?: VoxtaResourceRef;\n DateCreated?: string;\n DateModified?: string;\n}\n\n/**\n * Voxta TTS configuration\n */\nexport interface VoxtaTtsConfig {\n Voice: {\n parameters: {\n VoiceBackend?: string;\n VoiceId?: string;\n Gender?: string;\n Filename?: string;\n FinetuneVoice?: string;\n [key: string]: unknown;\n };\n label: string;\n };\n Service: {\n ServiceName: string;\n ServiceId: string;\n };\n}\n\n/**\n * Voxta script\n */\nexport interface VoxtaScript {\n Name: string;\n Content: string;\n}\n\n/**\n * Voxta character\n */\nexport interface VoxtaCharacter {\n $type: 'character';\n Id: string;\n Name: string;\n Label?: string; // Optional nickname/display name\n Version?: string;\n PackageId?: string;\n\n // Core Info\n Description?: string; // Physical/visual appearance\n Personality?: string;\n Profile?: string; // Profile/Backstory\n Scenario?: string;\n FirstMessage?: string;\n AlternativeFirstMessages?: string[]; // Alternate greetings (maps to CCv3 alternate_greetings)\n MessageExamples?: string;\n\n // System prompts\n SystemPrompt?: string; // System prompt (additive)\n PostHistoryInstructions?: string; // UJB - added at end of messages\n Context?: string; // Context field\n Instructions?: string; // User instructions (not read by LLM)\n\n // Persona overrides\n UserNameOverride?: string;\n UserDescriptionOverride?: string;\n\n // Metadata\n Creator?: string;\n CreatorNotes?: string;\n Tags?: string[];\n ExplicitContent?: boolean;\n Culture?: string;\n ImportedFrom?: string; // Source tracking\n\n // References\n MemoryBooks?: string[];\n DefaultScenarios?: string[];\n\n // TTS\n TextToSpeech?: VoxtaTtsConfig[];\n\n // AI Settings\n ChatStyle?: number;\n EnableThinkingSpeech?: boolean;\n NotifyUserAwayReturn?: boolean;\n TimeAware?: boolean;\n UseMemory?: boolean;\n MaxTokens?: number;\n MaxSentences?: number;\n SystemPromptOverrideType?: number;\n\n // Simulation Settings\n ClimaxSensitivity?: number;\n PleasureDecay?: number;\n\n // Advanced\n Scripts?: VoxtaScript[];\n Augmentations?: unknown[];\n\n Thumbnail?: {\n RandomizedETag?: string;\n ContentType?: string;\n };\n\n DateCreated?: string; // ISO timestamp\n DateModified?: string; // ISO timestamp\n}\n\n/**\n * Voxta book item\n */\nexport interface VoxtaBookItem {\n Id: string;\n Keywords: string[];\n Text: string;\n Weight?: number;\n Deleted?: boolean;\n CreatedAt?: string;\n LastUpdated?: string;\n DeletedAt?: string;\n}\n\n/**\n * Voxta book (lorebook)\n */\nexport interface VoxtaBook {\n $type: 'book';\n Id: string;\n Name: string;\n Version?: string;\n PackageId?: string;\n Description?: string;\n ExplicitContent?: boolean;\n Creator?: string;\n Items: VoxtaBookItem[];\n DateCreated?: string;\n DateModified?: string;\n}\n\n/**\n * Voxta collection item (reference to a resource)\n */\nexport interface VoxtaCollectionItem {\n Resource: VoxtaResourceRef;\n}\n\n/**\n * Voxta collection folder (organizational grouping)\n */\nexport interface VoxtaCollectionFolder {\n Name: string;\n Description?: string;\n /** Kind of resources in this folder (1=Character, 2=Book, 3=Scenario) */\n Kind: VoxtaResourceKind | number;\n Items: VoxtaCollectionItem[];\n /** Nested folders (if any) */\n Folders?: VoxtaCollectionFolder[];\n}\n\n/**\n * Voxta collection root structure\n */\nexport interface VoxtaCollectionRoot {\n Folders: VoxtaCollectionFolder[];\n}\n\n/**\n * Voxta collection - organizes resources into themed groups\n */\nexport interface VoxtaCollection {\n $type: 'collection';\n Id: string;\n Name: string;\n Version?: string;\n PackageId?: string;\n ExplicitContent?: boolean;\n Root: VoxtaCollectionRoot;\n Thumbnail?: {\n RandomizedETag?: string;\n ContentType?: string;\n };\n DateCreated?: string;\n DateModified?: string;\n}\n\n/**\n * Voxta scenario action\n */\nexport interface VoxtaAction {\n Name: string;\n Layer?: string;\n Arguments?: unknown[];\n FinalLayer?: boolean;\n Timing?: number;\n Description?: string;\n Disabled?: boolean;\n Once?: boolean;\n FlagsFilter?: string;\n EvaluateNextEvent?: boolean;\n Effect?: {\n SetFlags?: string[];\n Script?: string;\n Event?: string;\n Story?: string;\n Secret?: string;\n Instructions?: string;\n MaxSentences?: number;\n MaxTokens?: number;\n [key: string]: unknown;\n };\n}\n\n/**\n * Voxta scenario event (similar to action but for event triggers)\n */\nexport interface VoxtaEvent {\n Id?: string;\n Name: string;\n Layer?: string;\n Timing?: number;\n Description?: string;\n Arguments?: unknown[];\n Disabled?: boolean;\n FinalLayer?: boolean;\n Once?: boolean;\n FlagsFilter?: string;\n EvaluateNextEvent?: boolean;\n Effect?: {\n SetFlags?: string[];\n Script?: string;\n Event?: string;\n Story?: string;\n Secret?: string;\n Instructions?: string;\n MaxSentences?: number;\n MaxTokens?: number;\n [key: string]: unknown;\n };\n}\n\n/**\n * Voxta scenario context (conditional context blocks)\n */\nexport interface VoxtaContext {\n Name: string;\n Text: string;\n FlagsFilter?: string;\n Disabled?: boolean;\n}\n\n/**\n * Voxta scenario role - maps characters to scenario slots\n */\nexport interface VoxtaRole {\n Name: string;\n Description?: string;\n DefaultCharacterId: string;\n EnabledOnStart?: boolean;\n}\n\n/**\n * Voxta impersonation (user persona override)\n */\nexport interface VoxtaImpersonation {\n Name: string;\n Description?: string;\n}\n\n/**\n * Voxta scenario\n */\nexport interface VoxtaScenario {\n $type: 'scenario';\n Id: string;\n Name: string;\n Version?: string;\n ParentId?: string;\n PackageId?: string;\n Client?: string;\n Creator?: string;\n Description?: string;\n\n // Core content\n Template?: string;\n Messages?: string;\n SystemPrompt?: string;\n SystemPromptOverrideType?: number;\n\n // Character mappings\n Roles?: VoxtaRole[];\n NarratorCharacterId?: string;\n Impersonation?: VoxtaImpersonation;\n\n // Scripting/automation\n SharedScripts?: VoxtaScript[];\n Actions?: VoxtaAction[];\n Events?: VoxtaEvent[];\n Contexts?: VoxtaContext[];\n\n // Settings\n ExplicitContent?: boolean;\n ChatFlow?: number;\n ChatStyle?: number;\n MemoryBooks?: string[];\n\n // Metadata\n Thumbnail?: {\n ETag?: number;\n RandomizedETag?: string;\n ContentType?: string;\n };\n DateCreated?: string;\n DateModified?: string;\n\n // App control (optional)\n UserId?: string;\n AppControlled?: boolean;\n Locked?: boolean;\n}\n\n/**\n * Extracted Voxta asset\n */\nexport interface ExtractedVoxtaAsset {\n path: string;\n buffer: BinaryData;\n characterId?: string;\n}\n\n/**\n * Extracted Voxta character with assets\n */\nexport interface ExtractedVoxtaCharacter {\n id: string;\n data: VoxtaCharacter;\n thumbnail?: BinaryData;\n assets: ExtractedVoxtaAsset[];\n}\n\n/**\n * Extracted Voxta scenario\n */\nexport interface ExtractedVoxtaScenario {\n id: string;\n data: VoxtaScenario;\n thumbnail?: BinaryData;\n}\n\n/**\n * Extracted Voxta book\n */\nexport interface ExtractedVoxtaBook {\n id: string;\n data: VoxtaBook;\n}\n\n/**\n * Extracted Voxta collection with assets\n */\nexport interface ExtractedVoxtaCollection {\n id: string;\n data: VoxtaCollection;\n thumbnail?: BinaryData;\n}\n\n/**\n * Voxta export type\n * - 'package': Has package.json with full metadata\n * - 'scenario': Has Scenarios/ folder but no package.json (scenario export)\n * - 'character': Only has Characters/ folder (single/multi character export)\n * - 'collection': Has Collections/ folder (bundled content with organization)\n */\nexport type VoxtaExportType = 'package' | 'scenario' | 'character' | 'collection';\n\n/**\n * Complete extracted Voxta data\n */\nexport interface VoxtaData {\n package?: VoxtaPackage;\n characters: ExtractedVoxtaCharacter[];\n scenarios: ExtractedVoxtaScenario[];\n books: ExtractedVoxtaBook[];\n collections: ExtractedVoxtaCollection[];\n\n /**\n * Type of export detected:\n * - 'package': Has package.json\n * - 'scenario': Has Scenarios/ but no package.json\n * - 'character': Only Characters/ (no package.json or Scenarios/)\n * - 'collection': Has Collections/ folder\n */\n exportType: VoxtaExportType;\n}\n\n/**\n * Options for Voxta extraction\n */\nexport interface VoxtaReadOptions {\n maxFileSize?: number;\n maxAssetSize?: number;\n maxTotalSize?: number;\n}\n\n/**\n * Asset to include in Voxta export\n */\nexport interface VoxtaWriteAsset {\n type: string;\n name: string;\n ext: string;\n data: BinaryData;\n tags?: string[];\n isMain?: boolean;\n}\n\n/**\n * Options for building Voxta package\n */\nexport interface VoxtaWriteOptions {\n compressionLevel?: CompressionLevel;\n includePackageJson?: boolean;\n characterId?: string;\n packageId?: string;\n /** Scenario to include - uses scenario.Id as the key */\n scenario?: VoxtaScenario;\n /** Scenario thumbnail */\n scenarioThumbnail?: BinaryData;\n}\n\n/**\n * Result of building a Voxta package\n */\nexport interface VoxtaBuildResult {\n buffer: BinaryData;\n assetCount: number;\n totalSize: number;\n characterId: string;\n /** Scenario ID if a scenario was included */\n scenarioId?: string;\n}\n\n/**\n * Voxta extension data stored in CCv3 extensions\n */\nexport interface VoxtaExtensionData {\n id: string;\n version?: string;\n packageId?: string;\n label?: string;\n textToSpeech?: VoxtaTtsConfig[];\n appearance?: string;\n context?: string;\n instructions?: string;\n userNameOverride?: string;\n userDescriptionOverride?: string;\n culture?: string;\n importedFrom?: string;\n chatSettings?: {\n chatStyle?: number;\n enableThinkingSpeech?: boolean;\n notifyUserAwayReturn?: boolean;\n timeAware?: boolean;\n useMemory?: boolean;\n maxTokens?: number;\n maxSentences?: number;\n systemPromptOverrideType?: number;\n };\n simulationSettings?: {\n climaxSensitivity?: number;\n pleasureDecay?: number;\n };\n scripts?: VoxtaScript[];\n augmentations?: unknown[];\n scenario?: {\n actions?: VoxtaAction[];\n sharedScripts?: VoxtaScript[];\n };\n original?: Partial<VoxtaCharacter>;\n}\n\n/**\n * Loss report for Voxta export\n */\nexport interface VoxtaLossReport {\n lostFields: string[];\n lostAssets: string[];\n warnings: string[];\n reason: string;\n}\n","/**\n * Voxta Reader\n *\n * Extracts and parses .voxpkg files.\n */\n\nimport {\n type BinaryData,\n toString,\n ParseError,\n SizeLimitError,\n} from '@character-foundry/core';\nimport {\n type Unzipped,\n getZipOffset,\n streamingUnzipSync,\n ZipPreflightError,\n} from '@character-foundry/core/zip';\nimport type {\n VoxtaData,\n VoxtaReadOptions,\n ExtractedVoxtaCharacter,\n ExtractedVoxtaScenario,\n ExtractedVoxtaBook,\n ExtractedVoxtaCollection,\n VoxtaPackage,\n VoxtaCharacter,\n VoxtaScenario,\n VoxtaBook,\n VoxtaCollection,\n} from './types.js';\n\nconst DEFAULT_OPTIONS: Required<VoxtaReadOptions> = {\n maxFileSize: 50 * 1024 * 1024, // 50MB\n maxAssetSize: 50 * 1024 * 1024, // 50MB\n maxTotalSize: 500 * 1024 * 1024, // 500MB - Voxta packages can be large\n};\n\n// ZIP End of Central Directory signature\nconst EOCD_SIGNATURE = new Uint8Array([0x50, 0x4b, 0x05, 0x06]);\n// ZIP Central Directory File Header signature\nconst CDFH_SIGNATURE = new Uint8Array([0x50, 0x4b, 0x01, 0x02]);\n\n/**\n * Scan ZIP central directory for filenames matching Voxta markers.\n * The central directory is at the END of the ZIP file, so we must parse\n * the EOCD record to find it.\n */\nfunction scanZipCentralDirectory(zipData: BinaryData, markers: string[]): boolean {\n // Find EOCD (End of Central Directory) - scan from end\n // EOCD is at least 22 bytes, search within last 64KB (comment can be up to 64KB)\n const searchSize = Math.min(zipData.length, 65536 + 22);\n let eocdOffset = -1;\n\n for (let i = zipData.length - 22; i >= zipData.length - searchSize; i--) {\n if (\n zipData[i] === EOCD_SIGNATURE[0] &&\n zipData[i + 1] === EOCD_SIGNATURE[1] &&\n zipData[i + 2] === EOCD_SIGNATURE[2] &&\n zipData[i + 3] === EOCD_SIGNATURE[3]\n ) {\n eocdOffset = i;\n break;\n }\n }\n\n if (eocdOffset < 0) return false;\n\n // EOCD structure (22 bytes minimum):\n // 0-3: signature (PK\\x05\\x06)\n // 4-5: disk number\n // 6-7: disk with central directory\n // 8-9: entries on this disk\n // 10-11: total entries\n // 12-15: central directory size\n // 16-19: central directory offset\n // 20-21: comment length\n\n // Read central directory offset (little-endian uint32 at offset 16)\n const cdOffset =\n zipData[eocdOffset + 16]! |\n (zipData[eocdOffset + 17]! << 8) |\n (zipData[eocdOffset + 18]! << 16) |\n (zipData[eocdOffset + 19]! << 24);\n\n // Read number of entries (little-endian uint16 at offset 10)\n const numEntries = zipData[eocdOffset + 10]! | (zipData[eocdOffset + 11]! << 8);\n\n if (cdOffset < 0 || cdOffset >= zipData.length) return false;\n\n // Iterate through central directory entries\n let pos = cdOffset;\n const decoder = new TextDecoder();\n\n for (let entry = 0; entry < numEntries && pos < eocdOffset; entry++) {\n // Verify CDFH signature\n if (\n zipData[pos] !== CDFH_SIGNATURE[0] ||\n zipData[pos + 1] !== CDFH_SIGNATURE[1] ||\n zipData[pos + 2] !== CDFH_SIGNATURE[2] ||\n zipData[pos + 3] !== CDFH_SIGNATURE[3]\n ) {\n break; // Invalid entry, stop parsing\n }\n\n // Central Directory File Header structure:\n // 0-3: signature\n // 4-5: version made by\n // 6-7: version needed\n // 8-9: flags\n // 10-11: compression method\n // 12-13: last mod time\n // 14-15: last mod date\n // 16-19: CRC-32\n // 20-23: compressed size\n // 24-27: uncompressed size\n // 28-29: filename length\n // 30-31: extra field length\n // 32-33: comment length\n // 34-35: disk number start\n // 36-37: internal attributes\n // 38-41: external attributes\n // 42-45: local header offset\n // 46+: filename, extra field, comment\n\n const fileNameLen = zipData[pos + 28]! | (zipData[pos + 29]! << 8);\n const extraLen = zipData[pos + 30]! | (zipData[pos + 31]! << 8);\n const commentLen = zipData[pos + 32]! | (zipData[pos + 33]! << 8);\n\n if (pos + 46 + fileNameLen > zipData.length) break;\n\n // Extract filename\n const fileName = decoder.decode(zipData.subarray(pos + 46, pos + 46 + fileNameLen));\n\n // Check against markers\n for (const marker of markers) {\n if (fileName === marker || fileName.startsWith(marker)) {\n return true;\n }\n }\n\n // Move to next entry\n pos += 46 + fileNameLen + extraLen + commentLen;\n }\n\n return false;\n}\n\n/**\n * Check if data is a Voxta package\n */\nexport function isVoxta(data: BinaryData): boolean {\n const zipOffset = getZipOffset(data);\n if (zipOffset < 0) return false;\n\n const zipData = data.subarray(zipOffset);\n\n // Voxta markers - package.json is the primary indicator\n const markers = [\n 'package.json',\n 'character.json',\n 'Characters/',\n 'MemoryBooks/',\n 'Scenarios/',\n 'Collections/',\n ];\n\n return scanZipCentralDirectory(zipData, markers);\n}\n\n/**\n * Extract and parse a Voxta package\n */\nexport function readVoxta(\n data: BinaryData,\n options: VoxtaReadOptions = {}\n): VoxtaData {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n // SECURITY: Streaming unzip with real-time byte limit enforcement\n // This tracks ACTUAL decompressed bytes and aborts if limits exceeded,\n // protecting against malicious archives that lie about sizes in central directory\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(data, {\n maxFileSize: opts.maxAssetSize,\n maxTotalSize: opts.maxTotalSize,\n maxFiles: 10000, // Voxta packages can have many files\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || opts.maxTotalSize,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n const result: VoxtaData = {\n characters: [],\n scenarios: [],\n books: [],\n collections: [],\n exportType: 'character', // Default, will be updated based on contents\n };\n\n // Temporary maps to aggregate data parts\n const charMap = new Map<string, Partial<ExtractedVoxtaCharacter>>();\n const scenarioMap = new Map<string, Partial<ExtractedVoxtaScenario>>();\n const bookMap = new Map<string, Partial<ExtractedVoxtaBook>>();\n const collectionMap = new Map<string, Partial<ExtractedVoxtaCollection>>();\n\n // Process entries (size limits already enforced by streamingUnzipSync)\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n // Skip directories\n if (fileName.endsWith('/') || fileData.length === 0) continue;\n\n // 1. Package Metadata\n if (fileName === 'package.json') {\n if (fileData.length > opts.maxFileSize) {\n throw new SizeLimitError(fileData.length, opts.maxFileSize, 'package.json');\n }\n try {\n result.package = JSON.parse(toString(fileData)) as VoxtaPackage;\n } catch (err) {\n throw new ParseError(\n `Failed to parse package.json: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n continue;\n }\n\n // 2. Characters - Path: Characters/{uuid}/...\n const charMatch = fileName.match(/^Characters\\/([^/]+)\\/(.+)$/);\n if (charMatch) {\n const [, charId, subPath] = charMatch;\n\n if (!charMap.has(charId!)) {\n charMap.set(charId!, { id: charId, assets: [] });\n }\n const charEntry = charMap.get(charId!)!;\n\n if (subPath === 'character.json') {\n try {\n charEntry.data = JSON.parse(toString(fileData)) as VoxtaCharacter;\n } catch (err) {\n throw new ParseError(\n `Failed to parse character.json for ${charId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n } else if (subPath!.startsWith('thumbnail.')) {\n charEntry.thumbnail = fileData;\n } else if (subPath!.startsWith('Assets/')) {\n charEntry.assets!.push({\n path: subPath!,\n buffer: fileData,\n characterId: charId,\n });\n }\n continue;\n }\n\n // 3. Scenarios - Path: Scenarios/{uuid}/...\n const scenarioMatch = fileName.match(/^Scenarios\\/([^/]+)\\/(.+)$/);\n if (scenarioMatch) {\n const [, scenarioId, subPath] = scenarioMatch;\n\n if (!scenarioMap.has(scenarioId!)) {\n scenarioMap.set(scenarioId!, { id: scenarioId });\n }\n const scenarioEntry = scenarioMap.get(scenarioId!)!;\n\n if (subPath === 'scenario.json') {\n try {\n scenarioEntry.data = JSON.parse(toString(fileData)) as VoxtaScenario;\n } catch (err) {\n throw new ParseError(\n `Failed to parse scenario.json for ${scenarioId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n } else if (subPath!.startsWith('thumbnail.')) {\n scenarioEntry.thumbnail = fileData;\n }\n continue;\n }\n\n // 4. Books - Path: Books/{uuid}/...\n const bookMatch = fileName.match(/^Books\\/([^/]+)\\/(.+)$/);\n if (bookMatch) {\n const [, bookId, subPath] = bookMatch;\n\n if (!bookMap.has(bookId!)) {\n bookMap.set(bookId!, { id: bookId });\n }\n const bookEntry = bookMap.get(bookId!)!;\n\n if (subPath === 'book.json') {\n try {\n bookEntry.data = JSON.parse(toString(fileData)) as VoxtaBook;\n } catch (err) {\n throw new ParseError(\n `Failed to parse book.json for ${bookId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n }\n continue;\n }\n\n // 5. Collections - Path: Collections/{uuid}/...\n const collectionMatch = fileName.match(/^Collections\\/([^/]+)\\/(.+)$/);\n if (collectionMatch) {\n const [, collectionId, subPath] = collectionMatch;\n\n if (!collectionMap.has(collectionId!)) {\n collectionMap.set(collectionId!, { id: collectionId });\n }\n const collectionEntry = collectionMap.get(collectionId!)!;\n\n if (subPath === 'collection.json') {\n try {\n collectionEntry.data = JSON.parse(toString(fileData)) as VoxtaCollection;\n } catch (err) {\n throw new ParseError(\n `Failed to parse collection.json for ${collectionId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n } else if (subPath!.startsWith('thumbnail.')) {\n collectionEntry.thumbnail = fileData;\n }\n continue;\n }\n }\n\n // Assemble final results - filter incomplete entries\n for (const [, char] of charMap) {\n if (char.data) {\n result.characters.push(char as ExtractedVoxtaCharacter);\n }\n }\n\n for (const [, scenario] of scenarioMap) {\n if (scenario.data) {\n result.scenarios.push(scenario as ExtractedVoxtaScenario);\n }\n }\n\n for (const [, book] of bookMap) {\n if (book.data) {\n result.books.push(book as ExtractedVoxtaBook);\n }\n }\n\n for (const [, collection] of collectionMap) {\n if (collection.data) {\n result.collections.push(collection as ExtractedVoxtaCollection);\n }\n }\n\n // Determine export type based on contents\n if (result.package) {\n result.exportType = 'package';\n } else if (result.collections.length > 0) {\n // Collections without package.json = collection export\n result.exportType = 'collection';\n } else if (result.scenarios.length > 0) {\n result.exportType = 'scenario';\n }\n // else stays 'character' (default)\n\n return result;\n}\n\n/**\n * Async version of readVoxta\n */\nexport async function readVoxtaAsync(\n data: BinaryData,\n options: VoxtaReadOptions = {}\n): Promise<VoxtaData> {\n return readVoxta(data, options);\n}\n","/**\n * Voxta Writer\n *\n * Creates .voxpkg files from CCv3 card data.\n */\n\nimport { zipSync, type Zippable } from 'fflate';\nimport { fromString, generateUUID } from '@character-foundry/core';\nimport { detectImageFormat, getExtension } from '@character-foundry/media';\nimport type { CCv3Data } from '@character-foundry/schemas';\nimport type {\n VoxtaWriteAsset,\n VoxtaWriteOptions,\n VoxtaBuildResult,\n VoxtaCharacter,\n VoxtaScenario,\n VoxtaExtensionData,\n CompressionLevel,\n} from './types.js';\nimport { standardToVoxta } from './macros.js';\nimport { ccv3LorebookToVoxtaBook } from './mapper.js';\n\n/**\n * Sanitize a name for use in file paths\n */\nfunction sanitizeName(name: string, ext: string): string {\n let safeName = name;\n\n if (safeName.toLowerCase().endsWith(`.${ext.toLowerCase()}`)) {\n safeName = safeName.substring(0, safeName.length - (ext.length + 1));\n }\n\n safeName = safeName\n .replace(/[._]/g, '-')\n .replace(/[^a-zA-Z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '');\n\n if (!safeName) safeName = 'asset';\n\n return safeName;\n}\n\n/**\n * Build a Voxta package from CCv3 card data\n */\nexport function writeVoxta(\n card: CCv3Data,\n assets: VoxtaWriteAsset[],\n options: VoxtaWriteOptions = {}\n): VoxtaBuildResult {\n const { compressionLevel = 6, includePackageJson = false } = options;\n const cardData = card.data;\n\n // Get Voxta extension data if present\n const extensions = cardData.extensions as Record<string, unknown> | undefined;\n const voxtaExt = extensions?.voxta as VoxtaExtensionData | undefined;\n\n // Generate IDs\n const characterId = options.characterId || voxtaExt?.id || generateUUID();\n const packageId = options.packageId || voxtaExt?.packageId || generateUUID();\n const dateNow = new Date().toISOString();\n\n // Get appearance from voxta extension or visual_description\n const appearance = voxtaExt?.appearance || (extensions?.visual_description as string) || '';\n\n // Create ZIP entries\n const zipEntries: Zippable = {};\n\n // Handle Lorebook (MemoryBook)\n const book = ccv3LorebookToVoxtaBook(card);\n const memoryBooks: string[] = voxtaExt?.original?.MemoryBooks || [];\n\n if (book) {\n // Ensure we have a unique ID for the book\n if (!book.Id) book.Id = generateUUID();\n\n // Add to memory books list if not already present\n if (!memoryBooks.includes(book.Id)) {\n memoryBooks.push(book.Id);\n }\n\n // Write book to ZIP - character will reference it via MemoryBooks\n zipEntries[`Books/${book.Id}/book.json`] = [\n fromString(JSON.stringify(book, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n\n // Note: We no longer force includePackageJson = true here.\n // The Books/ folder is valid alongside Characters/ without package.json.\n // This allows single-character exports with lorebooks.\n }\n\n // 1. Package.json (optional)\n if (includePackageJson) {\n const packageMeta = {\n $type: 'package',\n Id: packageId,\n Name: cardData.name,\n Version: cardData.character_version || '1.0.0',\n Description: cardData.description,\n Creator: cardData.creator,\n ExplicitContent: true,\n EntryResource: { Kind: 1, Id: characterId },\n ThumbnailResource: { Kind: 1, Id: characterId },\n DateCreated: voxtaExt?.original?.DateCreated || dateNow,\n DateModified: dateNow,\n };\n zipEntries['package.json'] = [\n fromString(JSON.stringify(packageMeta, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n }\n\n // 2. Character.json\n const character: VoxtaCharacter = {\n $type: 'character',\n Id: characterId,\n PackageId: packageId,\n Name: cardData.name,\n Version: cardData.character_version,\n\n // Core Info - apply macro conversion (handle nullable personality/mes_example)\n Description: appearance,\n Personality: standardToVoxta(cardData.personality ?? ''),\n Profile: standardToVoxta(cardData.description),\n Scenario: standardToVoxta(cardData.scenario),\n FirstMessage: standardToVoxta(cardData.first_mes),\n AlternativeFirstMessages: (cardData.alternate_greetings || []).map(standardToVoxta),\n MessageExamples: standardToVoxta(cardData.mes_example ?? ''),\n\n // System prompts - Voxta supports these\n SystemPrompt: cardData.system_prompt ? standardToVoxta(cardData.system_prompt) : undefined,\n PostHistoryInstructions: cardData.post_history_instructions ? standardToVoxta(cardData.post_history_instructions) : undefined,\n\n // Metadata\n Creator: cardData.creator,\n CreatorNotes: cardData.creator_notes,\n Tags: cardData.tags,\n\n // References\n MemoryBooks: memoryBooks.length > 0 ? memoryBooks : undefined,\n\n // Voxta-specific from extension\n TextToSpeech: voxtaExt?.textToSpeech,\n ChatStyle: voxtaExt?.chatSettings?.chatStyle,\n EnableThinkingSpeech: voxtaExt?.chatSettings?.enableThinkingSpeech,\n NotifyUserAwayReturn: voxtaExt?.chatSettings?.notifyUserAwayReturn,\n TimeAware: voxtaExt?.chatSettings?.timeAware,\n UseMemory: voxtaExt?.chatSettings?.useMemory,\n MaxTokens: voxtaExt?.chatSettings?.maxTokens,\n MaxSentences: voxtaExt?.chatSettings?.maxSentences,\n SystemPromptOverrideType: voxtaExt?.chatSettings?.systemPromptOverrideType,\n \n // Simulation Settings\n ClimaxSensitivity: voxtaExt?.simulationSettings?.climaxSensitivity,\n PleasureDecay: voxtaExt?.simulationSettings?.pleasureDecay,\n\n Scripts: voxtaExt?.scripts,\n\n DateCreated: voxtaExt?.original?.DateCreated || dateNow,\n DateModified: dateNow,\n };\n\n zipEntries[`Characters/${characterId}/character.json`] = [\n fromString(JSON.stringify(character, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n\n // 3. Add assets\n let assetCount = 0;\n let mainThumbnail: VoxtaWriteAsset | undefined;\n\n for (const asset of assets) {\n const safeName = sanitizeName(asset.name, asset.ext);\n const finalFilename = `${safeName}.${asset.ext}`;\n let voxtaPath = '';\n\n const tags = asset.tags || [];\n\n // Check if this is the main icon (used as thumbnail only, not in Assets folder)\n const isMainIcon = asset.type === 'icon' && (\n tags.includes('portrait-override') ||\n asset.name === 'main' ||\n asset.isMain\n );\n\n if (asset.type === 'sound' || tags.includes('voice')) {\n voxtaPath = `Characters/${characterId}/Assets/VoiceSamples/${finalFilename}`;\n } else if (asset.type === 'icon' || asset.type === 'emotion') {\n // Track main icon for thumbnail (but don't add to Assets folder)\n if (asset.type === 'icon') {\n if (tags.includes('portrait-override')) {\n mainThumbnail = asset;\n } else if (!mainThumbnail && (asset.name === 'main' || asset.isMain)) {\n mainThumbnail = asset;\n }\n }\n\n // Skip adding main icon to Assets folder - it will only be the thumbnail\n if (isMainIcon) {\n continue;\n }\n\n voxtaPath = `Characters/${characterId}/Assets/Avatars/Default/${finalFilename}`;\n } else {\n voxtaPath = `Characters/${characterId}/Assets/Misc/${finalFilename}`;\n }\n\n zipEntries[voxtaPath] = [asset.data, { level: compressionLevel as CompressionLevel }];\n assetCount++;\n }\n\n // 4. Add thumbnail (detect format - supports PNG, WebP, JPEG)\n if (!mainThumbnail && assets.length > 0) {\n mainThumbnail = assets.find((a) => a.type === 'icon');\n }\n\n if (mainThumbnail) {\n const thumbData =\n mainThumbnail.data instanceof Uint8Array\n ? mainThumbnail.data\n : new Uint8Array(mainThumbnail.data);\n const thumbFormat = detectImageFormat(thumbData);\n const thumbExt = thumbFormat ? getExtension(thumbFormat) : 'png';\n\n zipEntries[`Characters/${characterId}/thumbnail.${thumbExt}`] = [\n mainThumbnail.data,\n { level: compressionLevel as CompressionLevel },\n ];\n }\n\n // 5. Add scenario if provided (uses scenario.Id as key)\n let scenarioId: string | undefined;\n if (options.scenario) {\n const scenario = options.scenario;\n scenarioId = scenario.Id;\n\n // Ensure scenario has required fields\n const scenarioData: VoxtaScenario = {\n ...scenario,\n $type: 'scenario',\n PackageId: packageId,\n DateModified: dateNow,\n };\n\n // Write scenario.json\n zipEntries[`Scenarios/${scenarioId}/scenario.json`] = [\n fromString(JSON.stringify(scenarioData, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n\n // Add scenario thumbnail if provided (detect format)\n if (options.scenarioThumbnail) {\n const scenarioThumbData =\n options.scenarioThumbnail instanceof Uint8Array\n ? options.scenarioThumbnail\n : new Uint8Array(options.scenarioThumbnail);\n const scenarioThumbFormat = detectImageFormat(scenarioThumbData);\n const scenarioThumbExt = scenarioThumbFormat ? getExtension(scenarioThumbFormat) : 'png';\n\n zipEntries[`Scenarios/${scenarioId}/thumbnail.${scenarioThumbExt}`] = [\n options.scenarioThumbnail,\n { level: compressionLevel as CompressionLevel },\n ];\n }\n\n // Update package.json EntryResource to point to scenario (Kind: 3)\n if (includePackageJson) {\n const packageMeta = {\n $type: 'package',\n Id: packageId,\n Name: scenario.Name || cardData.name,\n Version: scenario.Version || cardData.character_version || '1.0.0',\n Description: scenario.Description || cardData.description,\n Creator: scenario.Creator || cardData.creator,\n ExplicitContent: scenario.ExplicitContent ?? true,\n EntryResource: { Kind: 3, Id: scenarioId }, // Kind 3 = Scenario\n ThumbnailResource: { Kind: 3, Id: scenarioId },\n DateCreated: scenario.DateCreated || voxtaExt?.original?.DateCreated || dateNow,\n DateModified: dateNow,\n };\n zipEntries['package.json'] = [\n fromString(JSON.stringify(packageMeta, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n }\n }\n\n // Create ZIP\n const buffer = zipSync(zipEntries);\n\n return {\n buffer,\n assetCount,\n totalSize: buffer.length,\n characterId,\n scenarioId,\n };\n}\n\n/**\n * Async version of writeVoxta\n */\nexport async function writeVoxtaAsync(\n card: CCv3Data,\n assets: VoxtaWriteAsset[],\n options: VoxtaWriteOptions = {}\n): Promise<VoxtaBuildResult> {\n return writeVoxta(card, assets, options);\n}\n","/**\n * Macro Conversion\n *\n * Converts between Voxta-style macros (with spaces) and standard macros.\n *\n * Voxta uses: {{ user }}, {{ char }}\n * Standard uses: {{user}}, {{char}}\n */\n\n/**\n * Convert Voxta-style macros to standard format (no spaces)\n */\nexport function voxtaToStandard(text: string): string {\n if (!text) return text;\n\n let result = text;\n\n // Replace {{ user }} variants with {{user}}\n result = result.replace(/\\{\\{\\s*user\\s*\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('User') || match.includes('USER');\n return isUpperCase ? '{{User}}' : '{{user}}';\n });\n\n // Replace {{ char }} variants with {{char}}\n result = result.replace(/\\{\\{\\s*char\\s*\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('Char') || match.includes('CHAR');\n return isUpperCase ? '{{Char}}' : '{{char}}';\n });\n\n return result;\n}\n\n/**\n * Convert standard macros to Voxta-style format (with spaces)\n */\nexport function standardToVoxta(text: string): string {\n if (!text) return text;\n\n let result = text;\n\n // Replace {{user}} variants with {{ user }}\n result = result.replace(/\\{\\{user\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('User') || match.includes('USER');\n return isUpperCase ? '{{ User }}' : '{{ user }}';\n });\n\n // Replace {{char}} variants with {{ char }}\n result = result.replace(/\\{\\{char\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('Char') || match.includes('CHAR');\n return isUpperCase ? '{{ Char }}' : '{{ char }}';\n });\n\n return result;\n}\n","/**\n * Voxta <-> CCv3 Mapping\n *\n * Conversion utilities between Voxta format and CCv3 format.\n */\n\nimport type {\n CCv3Data,\n CCv3CharacterBook,\n CCv3LorebookEntry,\n} from '@character-foundry/schemas';\nimport { generateUUID } from '@character-foundry/core';\nimport type {\n VoxtaCharacter,\n VoxtaBook,\n VoxtaExtensionData,\n} from './types.js';\nimport { voxtaToStandard, standardToVoxta } from './macros.js';\n\n/**\n * Convert a Voxta character to CCv3 format\n */\nexport function voxtaToCCv3(character: VoxtaCharacter, books?: VoxtaBook[]): CCv3Data {\n // Build voxta extension data to preserve Voxta-specific fields\n const voxtaExt: VoxtaExtensionData = {\n id: character.Id,\n packageId: character.PackageId,\n label: character.Label,\n appearance: character.Description,\n context: character.Context,\n instructions: character.Instructions,\n userNameOverride: character.UserNameOverride,\n userDescriptionOverride: character.UserDescriptionOverride,\n culture: character.Culture,\n importedFrom: character.ImportedFrom,\n textToSpeech: character.TextToSpeech,\n chatSettings: {\n chatStyle: character.ChatStyle,\n enableThinkingSpeech: character.EnableThinkingSpeech,\n notifyUserAwayReturn: character.NotifyUserAwayReturn,\n timeAware: character.TimeAware,\n useMemory: character.UseMemory,\n maxTokens: character.MaxTokens,\n maxSentences: character.MaxSentences,\n systemPromptOverrideType: character.SystemPromptOverrideType,\n },\n simulationSettings: {\n climaxSensitivity: character.ClimaxSensitivity,\n pleasureDecay: character.PleasureDecay,\n },\n scripts: character.Scripts,\n augmentations: character.Augmentations,\n original: {\n DateCreated: character.DateCreated,\n DateModified: character.DateModified,\n },\n };\n\n // Convert lorebook from VoxtaBooks\n let characterBook: CCv3CharacterBook | undefined;\n\n if (books && books.length > 0) {\n const entries: CCv3LorebookEntry[] = [];\n const linkedBookIds = new Set(character.MemoryBooks || []);\n\n for (const book of books) {\n // Only include if linked or if no links defined (legacy/implicit)\n if (linkedBookIds.size === 0 || linkedBookIds.has(book.Id)) {\n if (book.Items) {\n for (let i = 0; i < book.Items.length; i++) {\n const item = book.Items[i]!;\n entries.push({\n keys: item.Keywords || [],\n content: voxtaToStandard(item.Text || ''),\n enabled: item.Deleted !== true,\n insertion_order: i,\n name: item.Id || '',\n priority: item.Weight || 10,\n id: i,\n comment: '',\n selective: false,\n secondary_keys: [],\n constant: false,\n position: 'before_char',\n });\n }\n }\n }\n }\n\n if (entries.length > 0) {\n characterBook = {\n entries,\n name: books[0]!.Name || 'Imported Lorebook',\n };\n }\n }\n\n // Convert timestamps (ISO string -> Unix seconds)\n // Sanitize .NET default dates (0001-01-01) which produce negative timestamps\n const rawCreationDate = character.DateCreated\n ? Math.floor(new Date(character.DateCreated).getTime() / 1000)\n : undefined;\n const rawModificationDate = character.DateModified\n ? Math.floor(new Date(character.DateModified).getTime() / 1000)\n : undefined;\n const creationDate = rawCreationDate !== undefined && rawCreationDate >= 0 ? rawCreationDate : undefined;\n const modificationDate = rawModificationDate !== undefined && rawModificationDate >= 0 ? rawModificationDate : undefined;\n\n // SPEC-COMPLIANT MAPPING (per CHARX_vs_VOXPKG_COMPARISON.md):\n // - Voxta Description (physical appearance) → CCv3 visual_description extension\n // - Voxta Personality → CCv3 personality\n // - Voxta Profile (backstory/details) → CCv3 description\n // Pure 1:1 mapping - no extraction, no magic\n\n // Build CCv3 card\n const card: CCv3Data = {\n spec: 'chara_card_v3',\n spec_version: '3.0',\n data: {\n name: character.Name || 'Unknown',\n nickname: character.Label,\n description: voxtaToStandard(character.Profile || ''),\n personality: voxtaToStandard(character.Personality || ''),\n scenario: voxtaToStandard(character.Scenario || ''),\n first_mes: voxtaToStandard(character.FirstMessage || ''),\n mes_example: voxtaToStandard(character.MessageExamples || ''),\n creator_notes: character.CreatorNotes || '',\n system_prompt: voxtaToStandard(character.SystemPrompt || ''),\n post_history_instructions: voxtaToStandard(character.PostHistoryInstructions || ''),\n alternate_greetings: (character.AlternativeFirstMessages || []).map(voxtaToStandard),\n group_only_greetings: [],\n tags: character.Tags || [],\n creator: character.Creator || '',\n character_version: character.Version || '1.0',\n creation_date: creationDate,\n modification_date: modificationDate,\n character_book: characterBook,\n extensions: {\n voxta: voxtaExt,\n visual_description: character.Description || undefined,\n },\n },\n };\n\n return card;\n}\n\n/**\n * Convert CCv3 card to Voxta character format\n */\nexport function ccv3ToVoxta(card: CCv3Data): VoxtaCharacter {\n const cardData = card.data;\n const extensions = cardData.extensions as Record<string, unknown> | undefined;\n const voxtaExt = extensions?.voxta as VoxtaExtensionData | undefined;\n const dateNow = new Date().toISOString();\n\n const appearance = voxtaExt?.appearance || (extensions?.visual_description as string) || '';\n\n // Convert timestamps (Unix seconds -> ISO string)\n const dateCreated = cardData.creation_date\n ? new Date(cardData.creation_date * 1000).toISOString()\n : voxtaExt?.original?.DateCreated || dateNow;\n const dateModified = cardData.modification_date\n ? new Date(cardData.modification_date * 1000).toISOString()\n : dateNow;\n\n const character: VoxtaCharacter = {\n $type: 'character',\n Id: voxtaExt?.id || generateUUID(),\n PackageId: voxtaExt?.packageId || generateUUID(),\n Name: cardData.name,\n Label: cardData.nickname || voxtaExt?.label,\n Version: cardData.character_version,\n\n // Core content (handle nullable personality/mes_example)\n Description: appearance,\n Personality: standardToVoxta(cardData.personality ?? ''),\n Profile: standardToVoxta(cardData.description),\n Scenario: standardToVoxta(cardData.scenario),\n FirstMessage: standardToVoxta(cardData.first_mes),\n AlternativeFirstMessages: (cardData.alternate_greetings || []).map(standardToVoxta),\n MessageExamples: standardToVoxta(cardData.mes_example ?? ''),\n\n // System prompts\n SystemPrompt: standardToVoxta(cardData.system_prompt || ''),\n PostHistoryInstructions: standardToVoxta(cardData.post_history_instructions || ''),\n Context: voxtaExt?.context,\n Instructions: voxtaExt?.instructions,\n\n // Persona overrides\n UserNameOverride: voxtaExt?.userNameOverride,\n UserDescriptionOverride: voxtaExt?.userDescriptionOverride,\n\n // Metadata\n Creator: cardData.creator,\n CreatorNotes: cardData.creator_notes,\n Tags: cardData.tags,\n Culture: voxtaExt?.culture,\n ImportedFrom: voxtaExt?.importedFrom,\n\n // TTS & AI settings\n TextToSpeech: voxtaExt?.textToSpeech,\n ChatStyle: voxtaExt?.chatSettings?.chatStyle,\n EnableThinkingSpeech: voxtaExt?.chatSettings?.enableThinkingSpeech,\n NotifyUserAwayReturn: voxtaExt?.chatSettings?.notifyUserAwayReturn,\n TimeAware: voxtaExt?.chatSettings?.timeAware,\n UseMemory: voxtaExt?.chatSettings?.useMemory,\n MaxTokens: voxtaExt?.chatSettings?.maxTokens,\n MaxSentences: voxtaExt?.chatSettings?.maxSentences,\n SystemPromptOverrideType: voxtaExt?.chatSettings?.systemPromptOverrideType,\n\n // Simulation settings\n ClimaxSensitivity: voxtaExt?.simulationSettings?.climaxSensitivity,\n PleasureDecay: voxtaExt?.simulationSettings?.pleasureDecay,\n\n // Advanced\n Scripts: voxtaExt?.scripts,\n Augmentations: voxtaExt?.augmentations,\n\n DateCreated: dateCreated,\n DateModified: dateModified,\n };\n\n return character;\n}\n\n/**\n * Convert CCv3 lorebook to Voxta book format\n */\nexport function ccv3LorebookToVoxtaBook(card: CCv3Data): VoxtaBook | null {\n const characterBook = card.data.character_book;\n if (!characterBook?.entries || characterBook.entries.length === 0) {\n return null;\n }\n\n const book: VoxtaBook = {\n $type: 'book',\n Id: generateUUID(),\n Name: characterBook.name || `${card.data.name}'s Lorebook`,\n Items: characterBook.entries.map((entry) => ({\n Id: generateUUID(),\n Keywords: entry.keys || [],\n Text: standardToVoxta(entry.content || ''),\n Weight: entry.priority || 10,\n Deleted: entry.enabled === false,\n })),\n };\n\n return book;\n}\n","/**\n * Voxta Merge Utilities\n *\n * Functions for merging CCv3 edits into Voxta structures.\n */\n\nimport { zipSync, type Zippable } from 'fflate';\nimport {\n type BinaryData,\n fromString,\n ParseError,\n SizeLimitError,\n generateUUID,\n} from '@character-foundry/core';\nimport {\n findZipStart,\n streamingUnzipSync,\n ZipPreflightError,\n type Unzipped,\n} from '@character-foundry/core/zip';\nimport { detectImageFormat, getExtension } from '@character-foundry/media';\nimport type { CCv3Data, CCv3CharacterBook } from '@character-foundry/schemas';\nimport type {\n VoxtaCharacter,\n VoxtaBook,\n VoxtaBookItem,\n VoxtaPackage,\n ExtractedVoxtaCharacter,\n ExtractedVoxtaBook,\n CompressionLevel,\n} from './types.js';\nimport { standardToVoxta } from './macros.js';\n\n/**\n * Editable CCv3 fields (subset that can be changed in editors)\n */\nexport type CCv3Edits = Partial<CCv3Data['data']>;\n\n/**\n * Merge partial CCv3 edits into an existing Voxta character.\n *\n * This function applies only the fields present in `edits` to the original\n * character, preserving Voxta-specific fields like Scripts, TTS, and\n * Augmentations that CCv3 cannot represent.\n *\n * @param original - The original extracted Voxta character\n * @param edits - Partial CCv3 data fields to apply\n * @returns Updated VoxtaCharacter with edits merged\n */\nexport function mergeCharacterEdits(\n original: ExtractedVoxtaCharacter | VoxtaCharacter,\n edits: CCv3Edits\n): VoxtaCharacter {\n // Get the base character data\n const char: VoxtaCharacter =\n 'data' in original ? { ...original.data } : { ...original };\n\n const dateNow = new Date().toISOString();\n\n // Core text fields - only update if present in edits\n if (edits.name !== undefined) {\n char.Name = edits.name;\n }\n\n if (edits.nickname !== undefined) {\n char.Label = edits.nickname || undefined;\n }\n\n if (edits.description !== undefined) {\n char.Profile = standardToVoxta(edits.description);\n }\n\n if (edits.personality !== undefined) {\n char.Personality = standardToVoxta(edits.personality ?? '');\n }\n\n if (edits.scenario !== undefined) {\n char.Scenario = standardToVoxta(edits.scenario);\n }\n\n if (edits.first_mes !== undefined) {\n char.FirstMessage = standardToVoxta(edits.first_mes);\n }\n\n if (edits.alternate_greetings !== undefined) {\n char.AlternativeFirstMessages = edits.alternate_greetings.map(standardToVoxta);\n }\n\n if (edits.mes_example !== undefined) {\n char.MessageExamples = standardToVoxta(edits.mes_example ?? '');\n }\n\n // System prompts\n if (edits.system_prompt !== undefined) {\n char.SystemPrompt = standardToVoxta(edits.system_prompt);\n }\n\n if (edits.post_history_instructions !== undefined) {\n char.PostHistoryInstructions = standardToVoxta(edits.post_history_instructions);\n }\n\n // Metadata\n if (edits.creator !== undefined) {\n char.Creator = edits.creator || undefined;\n }\n\n if (edits.creator_notes !== undefined) {\n char.CreatorNotes = edits.creator_notes || undefined;\n }\n\n if (edits.tags !== undefined) {\n char.Tags = edits.tags;\n }\n\n if (edits.character_version !== undefined) {\n char.Version = edits.character_version || undefined;\n }\n\n // Handle visual_description from extensions\n if (edits.extensions !== undefined) {\n const ext = edits.extensions as Record<string, unknown> | undefined;\n if (ext?.visual_description !== undefined) {\n char.Description = (ext.visual_description as string) || undefined;\n }\n }\n\n // Update modification timestamp\n char.DateModified = dateNow;\n\n return char;\n}\n\n/**\n * Merge partial CCv3 lorebook edits into an existing Voxta book.\n *\n * @param original - The original extracted Voxta book\n * @param edits - CCv3 character_book to merge\n * @returns Updated VoxtaBook with edits merged\n */\nexport function mergeBookEdits(\n original: ExtractedVoxtaBook | VoxtaBook,\n edits: CCv3CharacterBook\n): VoxtaBook {\n const book: VoxtaBook = 'data' in original ? { ...original.data } : { ...original };\n const dateNow = new Date().toISOString();\n\n // Update book name if provided\n if (edits.name !== undefined) {\n book.Name = edits.name;\n }\n\n // Merge entries - match by name (stored as entry ID) or create new\n if (edits.entries !== undefined) {\n const existingById = new Map<string, VoxtaBookItem>();\n for (const item of book.Items || []) {\n existingById.set(item.Id, item);\n }\n\n const newItems: VoxtaBookItem[] = [];\n\n for (const entry of edits.entries) {\n // Try to match existing entry by name (which stores the original ID)\n const existingId = entry.name || '';\n const existing = existingById.get(existingId);\n\n if (existing) {\n // Update existing entry\n newItems.push({\n ...existing,\n Keywords: entry.keys || [],\n Text: standardToVoxta(entry.content || ''),\n Weight: entry.priority ?? existing.Weight ?? 10,\n Deleted: entry.enabled === false,\n LastUpdated: dateNow,\n });\n existingById.delete(existingId);\n } else {\n // Create new entry\n newItems.push({\n Id: generateUUID(),\n Keywords: entry.keys || [],\n Text: standardToVoxta(entry.content || ''),\n Weight: entry.priority ?? 10,\n Deleted: entry.enabled === false,\n CreatedAt: dateNow,\n LastUpdated: dateNow,\n });\n }\n }\n\n // Mark remaining entries as deleted (soft delete)\n for (const remaining of existingById.values()) {\n newItems.push({\n ...remaining,\n Deleted: true,\n DeletedAt: dateNow,\n });\n }\n\n book.Items = newItems;\n }\n\n book.DateModified = dateNow;\n\n return book;\n}\n\n/**\n * Delta changes to apply to a Voxta package\n */\nexport interface VoxtaDeltas {\n /** Updated characters by ID */\n characters?: Map<string, VoxtaCharacter>;\n /** Updated books by ID */\n books?: Map<string, VoxtaBook>;\n /** Updated package metadata (optional) */\n package?: Partial<VoxtaPackage>;\n}\n\n/**\n * Options for applying deltas\n */\nexport interface ApplyDeltaOptions {\n compressionLevel?: CompressionLevel;\n}\n\n/** Max total size for delta operations (500MB) */\nconst DELTA_MAX_TOTAL_SIZE = 500 * 1024 * 1024;\n/** Max file size for delta operations (50MB) */\nconst DELTA_MAX_FILE_SIZE = 50 * 1024 * 1024;\n\n/**\n * Apply delta changes to an existing Voxta package.\n *\n * This performs a minimal update - only files that have changed are rewritten.\n * All other files (assets, scenarios, unchanged characters/books) are preserved\n * exactly as they were in the original package.\n *\n * @param originalBuffer - The original .voxpkg file buffer\n * @param deltas - Changes to apply\n * @param options - Compression options\n * @returns New package buffer with changes applied\n */\nexport function applyVoxtaDeltas(\n originalBuffer: BinaryData,\n deltas: VoxtaDeltas,\n options: ApplyDeltaOptions = {}\n): Uint8Array {\n const { compressionLevel = 6 } = options;\n\n // Handle SFX archives\n const zipData = findZipStart(originalBuffer);\n\n // SECURITY: Use streaming unzip with actual byte tracking and path validation\n // This protects against:\n // 1. Zip bombs (archives that lie about sizes in central directory)\n // 2. Path traversal attacks (Zip Slip)\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(zipData, {\n maxFileSize: DELTA_MAX_FILE_SIZE,\n maxTotalSize: DELTA_MAX_TOTAL_SIZE,\n maxFiles: 10000,\n unsafePathHandling: 'reject', // Fail on path traversal attempts\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || DELTA_MAX_TOTAL_SIZE,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n // Build new ZIP entries, starting with all originals\n const zipEntries: Zippable = {};\n\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n // Check if this file should be replaced\n let replaced = false;\n\n // Check for character.json updates\n const charMatch = fileName.match(/^Characters\\/([^/]+)\\/character\\.json$/);\n if (charMatch && deltas.characters?.has(charMatch[1]!)) {\n const updatedChar = deltas.characters.get(charMatch[1]!)!;\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedChar, null, 2)),\n { level: compressionLevel },\n ];\n replaced = true;\n }\n\n // Check for book.json updates\n const bookMatch = fileName.match(/^Books\\/([^/]+)\\/book\\.json$/);\n if (bookMatch && deltas.books?.has(bookMatch[1]!)) {\n const updatedBook = deltas.books.get(bookMatch[1]!)!;\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedBook, null, 2)),\n { level: compressionLevel },\n ];\n replaced = true;\n }\n\n // Check for package.json update\n if (fileName === 'package.json' && deltas.package) {\n // Merge with existing package metadata\n const existing = JSON.parse(new TextDecoder().decode(fileData)) as VoxtaPackage;\n const updated: VoxtaPackage = {\n ...existing,\n ...deltas.package,\n DateModified: new Date().toISOString(),\n };\n zipEntries[fileName] = [\n fromString(JSON.stringify(updated, null, 2)),\n { level: compressionLevel },\n ];\n replaced = true;\n }\n\n // Keep original if not replaced\n if (!replaced) {\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n }\n\n // Create new ZIP\n return zipSync(zipEntries);\n}\n\n/**\n * Async version of applyVoxtaDeltas\n */\nexport async function applyVoxtaDeltasAsync(\n originalBuffer: BinaryData,\n deltas: VoxtaDeltas,\n options: ApplyDeltaOptions = {}\n): Promise<Uint8Array> {\n return applyVoxtaDeltas(originalBuffer, deltas, options);\n}\n\n/**\n * Character info in package manifest\n */\nexport interface ManifestCharacter {\n id: string;\n name: string;\n}\n\n/**\n * Book info in package manifest\n */\nexport interface ManifestBook {\n id: string;\n name: string;\n /** Character IDs that reference this book */\n usedBy: string[];\n}\n\n/**\n * Scenario info in package manifest\n */\nexport interface ManifestScenario {\n id: string;\n name: string;\n}\n\n/**\n * Package manifest for UI display\n */\nexport interface PackageManifest {\n packageId?: string;\n packageName?: string;\n characters: ManifestCharacter[];\n books: ManifestBook[];\n scenarios: ManifestScenario[];\n}\n\n/**\n * Get a manifest summary of a Voxta package for UI display.\n *\n * This provides a quick overview of package contents with relationship\n * information (which characters use which books).\n *\n * @param data - Extracted Voxta data from readVoxta()\n * @returns Package manifest for UI display\n */\nexport function getPackageManifest(data: import('./types.js').VoxtaData): PackageManifest {\n const characters: ManifestCharacter[] = data.characters.map((c) => ({\n id: c.id,\n name: c.data.Name,\n }));\n\n // Build a map of book ID -> character IDs that use it\n const bookUsers = new Map<string, string[]>();\n for (const char of data.characters) {\n const memoryBooks = char.data.MemoryBooks || [];\n for (const bookId of memoryBooks) {\n if (!bookUsers.has(bookId)) {\n bookUsers.set(bookId, []);\n }\n bookUsers.get(bookId)!.push(char.id);\n }\n }\n\n const books: ManifestBook[] = data.books.map((b) => ({\n id: b.id,\n name: b.data.Name,\n usedBy: bookUsers.get(b.id) || [],\n }));\n\n const scenarios: ManifestScenario[] = data.scenarios.map((s) => ({\n id: s.id,\n name: s.data.Name,\n }));\n\n return {\n packageId: data.package?.Id,\n packageName: data.package?.Name,\n characters,\n books,\n scenarios,\n };\n}\n\n/**\n * Options for extracting a character package\n */\nexport interface ExtractCharacterOptions {\n compressionLevel?: CompressionLevel;\n /** Include books referenced by the character */\n includeBooks?: boolean;\n /** New package name (defaults to character name) */\n packageName?: string;\n}\n\n/**\n * Extract a single character from a multi-character package.\n *\n * Creates a new standalone .voxpkg containing just the specified character,\n * their assets, and optionally their referenced books.\n *\n * NOTE: Scenarios are NOT extracted since they may contain scripts that\n * reference other characters in the package.\n *\n * @param originalBuffer - The original .voxpkg file buffer\n * @param characterId - ID of the character to extract\n * @param options - Extraction options\n * @returns New package buffer with just the specified character\n */\nexport function extractCharacterPackage(\n originalBuffer: BinaryData,\n characterId: string,\n options: ExtractCharacterOptions = {}\n): Uint8Array {\n const { compressionLevel = 6, includeBooks = true, packageName } = options;\n\n // Handle SFX archives\n const zipData = findZipStart(originalBuffer);\n\n // SECURITY: Use streaming unzip with actual byte tracking and path validation\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(zipData, {\n maxFileSize: DELTA_MAX_FILE_SIZE,\n maxTotalSize: DELTA_MAX_TOTAL_SIZE,\n maxFiles: 10000,\n unsafePathHandling: 'reject',\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || DELTA_MAX_TOTAL_SIZE,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n // Find the character's data to get their name and book refs\n const charJsonPath = `Characters/${characterId}/character.json`;\n const charJsonData = unzipped[charJsonPath];\n if (!charJsonData) {\n throw new ParseError(`Character ${characterId} not found in package`, 'voxta');\n }\n\n const charData = JSON.parse(new TextDecoder().decode(charJsonData)) as VoxtaCharacter;\n const memoryBooks = new Set(charData.MemoryBooks || []);\n\n // Generate new package ID\n const newPackageId = generateUUID();\n const dateNow = new Date().toISOString();\n\n // Build new ZIP with only this character's files\n const zipEntries: Zippable = {};\n\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n // Skip empty directories\n if (fileName.endsWith('/') || fileData.length === 0) continue;\n\n // Include all files under this character's directory\n if (fileName.startsWith(`Characters/${characterId}/`)) {\n // Update character.json with new package ID\n if (fileName === charJsonPath) {\n const updatedChar: VoxtaCharacter = {\n ...charData,\n PackageId: newPackageId,\n DateModified: dateNow,\n };\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedChar, null, 2)),\n { level: compressionLevel },\n ];\n } else {\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n continue;\n }\n\n // Include books if requested and referenced by this character\n if (includeBooks) {\n const bookMatch = fileName.match(/^Books\\/([^/]+)\\//);\n if (bookMatch && memoryBooks.has(bookMatch[1]!)) {\n // Update book.json with new package ID\n if (fileName.endsWith('/book.json')) {\n const bookData = JSON.parse(new TextDecoder().decode(fileData)) as VoxtaBook;\n const updatedBook: VoxtaBook = {\n ...bookData,\n PackageId: newPackageId,\n DateModified: dateNow,\n };\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedBook, null, 2)),\n { level: compressionLevel },\n ];\n } else {\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n continue;\n }\n }\n }\n\n // Create new package.json\n const newPackage: VoxtaPackage = {\n $type: 'package',\n Id: newPackageId,\n Name: packageName || charData.Name,\n Version: charData.Version || '1.0.0',\n Description: charData.Profile || undefined,\n Creator: charData.Creator,\n ExplicitContent: charData.ExplicitContent,\n EntryResource: { Kind: 1, Id: characterId },\n ThumbnailResource: { Kind: 1, Id: characterId },\n DateCreated: charData.DateCreated || dateNow,\n DateModified: dateNow,\n };\n\n zipEntries['package.json'] = [\n fromString(JSON.stringify(newPackage, null, 2)),\n { level: compressionLevel },\n ];\n\n return zipSync(zipEntries);\n}\n\n/**\n * Options for adding a character to a package\n */\nexport interface AddCharacterOptions {\n compressionLevel?: CompressionLevel;\n /** Books to include with the character */\n books?: VoxtaBook[];\n /** Assets to include (path relative to character dir -> data) */\n assets?: Map<string, BinaryData>;\n /** Thumbnail image */\n thumbnail?: BinaryData;\n}\n\n/**\n * Add a character to an existing Voxta package.\n *\n * @param originalBuffer - The original .voxpkg file buffer\n * @param character - The character to add\n * @param options - Options including books and assets\n * @returns New package buffer with the character added\n */\nexport function addCharacterToPackage(\n originalBuffer: BinaryData,\n character: VoxtaCharacter,\n options: AddCharacterOptions = {}\n): Uint8Array {\n const { compressionLevel = 6, books = [], assets, thumbnail } = options;\n\n // Handle SFX archives\n const zipData = findZipStart(originalBuffer);\n\n // SECURITY: Use streaming unzip with actual byte tracking and path validation\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(zipData, {\n maxFileSize: DELTA_MAX_FILE_SIZE,\n maxTotalSize: DELTA_MAX_TOTAL_SIZE,\n maxFiles: 10000,\n unsafePathHandling: 'reject',\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || DELTA_MAX_TOTAL_SIZE,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n // Get existing package metadata\n const packageJsonData = unzipped['package.json'];\n let packageMeta: VoxtaPackage | undefined;\n if (packageJsonData) {\n packageMeta = JSON.parse(new TextDecoder().decode(packageJsonData)) as VoxtaPackage;\n }\n\n const packageId = packageMeta?.Id || generateUUID();\n const dateNow = new Date().toISOString();\n\n // Build new ZIP with all original files plus new character\n const zipEntries: Zippable = {};\n\n // Copy all original files\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n if (fileName === 'package.json') continue; // Will update separately\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n\n // Ensure character has the right package ID\n const charToAdd: VoxtaCharacter = {\n ...character,\n PackageId: packageId,\n DateModified: dateNow,\n };\n\n // Add character.json\n const charId = charToAdd.Id;\n zipEntries[`Characters/${charId}/character.json`] = [\n fromString(JSON.stringify(charToAdd, null, 2)),\n { level: compressionLevel },\n ];\n\n // Add thumbnail if provided (detect format)\n if (thumbnail) {\n const thumbData = thumbnail instanceof Uint8Array ? thumbnail : new Uint8Array(thumbnail);\n const thumbFormat = detectImageFormat(thumbData);\n const thumbExt = thumbFormat ? getExtension(thumbFormat) : 'png';\n zipEntries[`Characters/${charId}/thumbnail.${thumbExt}`] = [thumbnail, { level: compressionLevel }];\n }\n\n // Add assets if provided\n if (assets) {\n for (const [assetPath, assetData] of assets) {\n zipEntries[`Characters/${charId}/${assetPath}`] = [assetData, { level: compressionLevel }];\n }\n }\n\n // Add books\n for (const book of books) {\n const bookToAdd: VoxtaBook = {\n ...book,\n PackageId: packageId,\n DateModified: dateNow,\n };\n zipEntries[`Books/${book.Id}/book.json`] = [\n fromString(JSON.stringify(bookToAdd, null, 2)),\n { level: compressionLevel },\n ];\n }\n\n // Update package.json\n const updatedPackage: VoxtaPackage = packageMeta\n ? { ...packageMeta, DateModified: dateNow }\n : {\n $type: 'package',\n Id: packageId,\n Name: charToAdd.Name,\n Version: '1.0.0',\n EntryResource: { Kind: 1, Id: charId },\n ThumbnailResource: { Kind: 1, Id: charId },\n DateCreated: dateNow,\n DateModified: dateNow,\n };\n\n zipEntries['package.json'] = [\n fromString(JSON.stringify(updatedPackage, null, 2)),\n { level: compressionLevel },\n ];\n\n return zipSync(zipEntries);\n}\n","/**\n * Voxta Loss Reporting\n *\n * Documents what data is lost when exporting to Voxta format.\n */\n\nimport type { NormalizedCard } from '@character-foundry/schemas';\nimport { hasRisuExtensions, hasRisuScripts, hasDepthPrompt } from '@character-foundry/schemas';\nimport type { VoxtaLossReport } from './types.js';\n\n/**\n * Fields that cannot be represented in Voxta format\n */\nconst _ALWAYS_LOST_FIELDS = [\n 'group_only_greetings', // Voxta doesn't support groups\n];\n\n/**\n * Extension namespaces that are always lost\n */\nconst LOST_EXTENSION_NAMESPACES = [\n 'risuai', // All Risu extensions\n 'chub', // Chub metadata\n 'depth_prompt', // SillyTavern depth prompts\n];\n\n/**\n * Check what would be lost when exporting a card to Voxta format\n */\nexport function checkVoxtaLoss(card: NormalizedCard): VoxtaLossReport {\n const lostFields: string[] = [];\n const lostAssets: string[] = [];\n const warnings: string[] = [];\n\n // Check always-lost fields that have content\n // Note: system_prompt, post_history_instructions, and alternate_greetings ARE supported by Voxta\n if (card.groupOnlyGreetings.length > 0) {\n lostFields.push(`group_only_greetings (${card.groupOnlyGreetings.length} entries)`);\n }\n\n // Check extensions\n const extensions = card.extensions;\n\n if (hasRisuExtensions(extensions)) {\n lostFields.push('extensions.risuai.*');\n\n if (hasRisuScripts(extensions)) {\n warnings.push('Risu scripts (triggerscript, customScripts) will be lost');\n }\n }\n\n if (hasDepthPrompt(extensions)) {\n lostFields.push('extensions.depth_prompt');\n warnings.push('SillyTavern depth prompt will be lost');\n }\n\n if (extensions?.chub) {\n lostFields.push('extensions.chub.*');\n }\n\n // Check for any other unknown extensions\n for (const key of Object.keys(extensions)) {\n if (key !== 'voxta' && key !== 'visual_description' && !LOST_EXTENSION_NAMESPACES.includes(key)) {\n lostFields.push(`extensions.${key}`);\n }\n }\n\n // Check character book extensions\n if (card.characterBook?.extensions) {\n lostFields.push('character_book.extensions');\n }\n\n // Check lorebook entry extensions\n if (card.characterBook?.entries) {\n const entriesWithExtensions = card.characterBook.entries.filter(e => e.extensions && Object.keys(e.extensions).length > 0);\n if (entriesWithExtensions.length > 0) {\n lostFields.push(`lorebook entries extensions (${entriesWithExtensions.length} entries)`);\n }\n }\n\n return {\n lostFields,\n lostAssets,\n warnings,\n reason: 'Voxta format does not support extensions field',\n };\n}\n\n/**\n * Check if export would be lossless\n */\nexport function isVoxtaExportLossless(card: NormalizedCard): boolean {\n const report = checkVoxtaLoss(card);\n return report.lostFields.length === 0 && report.lostAssets.length === 0;\n}\n\n/**\n * Format loss report as human-readable string\n */\nexport function formatVoxtaLossReport(report: VoxtaLossReport): string {\n const lines: string[] = [];\n\n if (report.lostFields.length === 0 && report.lostAssets.length === 0 && report.warnings.length === 0) {\n return 'No data will be lost in this export.';\n }\n\n lines.push('Voxta Export Loss Report');\n lines.push('========================');\n lines.push('');\n lines.push(`Reason: ${report.reason}`);\n lines.push('');\n\n if (report.lostFields.length > 0) {\n lines.push('Lost Fields:');\n for (const field of report.lostFields) {\n lines.push(` - ${field}`);\n }\n lines.push('');\n }\n\n if (report.lostAssets.length > 0) {\n lines.push('Lost Assets:');\n for (const asset of report.lostAssets) {\n lines.push(` - ${asset}`);\n }\n lines.push('');\n }\n\n if (report.warnings.length > 0) {\n lines.push('Warnings:');\n for (const warning of report.warnings) {\n lines.push(` ! ${warning}`);\n }\n }\n\n return lines.join('\\n');\n}\n","/**\n * Voxta Asset Enricher\n *\n * Analyzes Voxta asset paths to extract semantic tags and types.\n * e.g. \"Avatars/Default/happy_idle_01.webp\" -> tags: [emotion:happy, state:idle, variant:01]\n */\n\nimport type { ExtractedVoxtaAsset } from './types.js';\n\nexport interface EnrichedAssetMetadata {\n type: 'icon' | 'sound' | 'custom';\n tags: string[];\n}\n\n/**\n * Extract metadata from a Voxta asset path/filename\n */\nexport function enrichVoxtaAsset(asset: ExtractedVoxtaAsset): EnrichedAssetMetadata {\n const tags: string[] = [];\n let type: EnrichedAssetMetadata['type'] = 'custom';\n\n const parts = asset.path.split('/');\n const filename = parts[parts.length - 1] || '';\n \n // 1. Determine Type\n if (asset.path.includes('/Avatars/')) {\n type = 'icon';\n \n // 2. Extract Semantic Tags from Filename\n // Format: {Emotion}_{State}_{Variant}.ext\n const nameNoExt = filename.substring(0, filename.lastIndexOf('.'));\n const nameParts = nameNoExt.split('_');\n \n if (nameParts.length >= 3) {\n const [emotion, state, variant] = nameParts;\n if (emotion) tags.push(`emotion:${emotion.toLowerCase()}`);\n if (state) tags.push(`state:${state.toLowerCase()}`);\n if (variant) tags.push(`variant:${variant}`);\n } else if (nameParts.length === 2) {\n const [emotion, state] = nameParts;\n if (emotion) tags.push(`emotion:${emotion.toLowerCase()}`);\n if (state) tags.push(`state:${state.toLowerCase()}`);\n } else if (nameParts.length === 1) {\n if (nameParts[0]) tags.push(`emotion:${nameParts[0].toLowerCase()}`);\n }\n \n } else if (asset.path.includes('/VoiceSamples/')) {\n type = 'sound';\n tags.push('voice');\n }\n\n return { type, tags };\n}\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\n/**\n * Is this value defined and not null?\n * @private\n */\nconst defined = function (val) {\n return typeof val !== 'undefined' && val !== null;\n};\n\n/**\n * Is this value an object?\n * @private\n */\nconst object = function (val) {\n return typeof val === 'object';\n};\n\n/**\n * Is this value a plain object?\n * @private\n */\nconst plainObject = function (val) {\n return Object.prototype.toString.call(val) === '[object Object]';\n};\n\n/**\n * Is this value a function?\n * @private\n */\nconst fn = function (val) {\n return typeof val === 'function';\n};\n\n/**\n * Is this value a boolean?\n * @private\n */\nconst bool = function (val) {\n return typeof val === 'boolean';\n};\n\n/**\n * Is this value a Buffer object?\n * @private\n */\nconst buffer = function (val) {\n return val instanceof Buffer;\n};\n\n/**\n * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray?\n * @private\n */\nconst typedArray = function (val) {\n if (defined(val)) {\n switch (val.constructor) {\n case Uint8Array:\n case Uint8ClampedArray:\n case Int8Array:\n case Uint16Array:\n case Int16Array:\n case Uint32Array:\n case Int32Array:\n case Float32Array:\n case Float64Array:\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * Is this value an ArrayBuffer object?\n * @private\n */\nconst arrayBuffer = function (val) {\n return val instanceof ArrayBuffer;\n};\n\n/**\n * Is this value a non-empty string?\n * @private\n */\nconst string = function (val) {\n return typeof val === 'string' && val.length > 0;\n};\n\n/**\n * Is this value a real number?\n * @private\n */\nconst number = function (val) {\n return typeof val === 'number' && !Number.isNaN(val);\n};\n\n/**\n * Is this value an integer?\n * @private\n */\nconst integer = function (val) {\n return Number.isInteger(val);\n};\n\n/**\n * Is this value within an inclusive given range?\n * @private\n */\nconst inRange = function (val, min, max) {\n return val >= min && val <= max;\n};\n\n/**\n * Is this value within the elements of an array?\n * @private\n */\nconst inArray = function (val, list) {\n return list.includes(val);\n};\n\n/**\n * Create an Error with a message relating to an invalid parameter.\n *\n * @param {string} name - parameter name.\n * @param {string} expected - description of the type/value/range expected.\n * @param {*} actual - the value received.\n * @returns {Error} Containing the formatted message.\n * @private\n */\nconst invalidParameterError = function (name, expected, actual) {\n return new Error(\n `Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}`\n );\n};\n\n/**\n * Ensures an Error from C++ contains a JS stack.\n *\n * @param {Error} native - Error with message from C++.\n * @param {Error} context - Error with stack from JS.\n * @returns {Error} Error with message and stack.\n * @private\n */\nconst nativeError = function (native, context) {\n context.message = native.message;\n return context;\n};\n\nmodule.exports = {\n defined,\n object,\n plainObject,\n fn,\n bool,\n buffer,\n typedArray,\n arrayBuffer,\n string,\n number,\n integer,\n inRange,\n inArray,\n invalidParameterError,\n nativeError\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst isLinux = () => process.platform === 'linux';\n\nlet report = null;\nconst getReport = () => {\n if (!report) {\n /* istanbul ignore next */\n if (isLinux() && process.report) {\n const orig = process.report.excludeNetwork;\n process.report.excludeNetwork = true;\n report = process.report.getReport();\n process.report.excludeNetwork = orig;\n } else {\n report = {};\n }\n }\n return report;\n};\n\nmodule.exports = { isLinux, getReport };\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst fs = require('fs');\n\nconst LDD_PATH = '/usr/bin/ldd';\nconst SELF_PATH = '/proc/self/exe';\nconst MAX_LENGTH = 2048;\n\n/**\n * Read the content of a file synchronous\n *\n * @param {string} path\n * @returns {Buffer}\n */\nconst readFileSync = (path) => {\n const fd = fs.openSync(path, 'r');\n const buffer = Buffer.alloc(MAX_LENGTH);\n const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0);\n fs.close(fd, () => {});\n return buffer.subarray(0, bytesRead);\n};\n\n/**\n * Read the content of a file\n *\n * @param {string} path\n * @returns {Promise<Buffer>}\n */\nconst readFile = (path) => new Promise((resolve, reject) => {\n fs.open(path, 'r', (err, fd) => {\n if (err) {\n reject(err);\n } else {\n const buffer = Buffer.alloc(MAX_LENGTH);\n fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {\n resolve(buffer.subarray(0, bytesRead));\n fs.close(fd, () => {});\n });\n }\n });\n});\n\nmodule.exports = {\n LDD_PATH,\n SELF_PATH,\n readFileSync,\n readFile\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst interpreterPath = (elf) => {\n if (elf.length < 64) {\n return null;\n }\n if (elf.readUInt32BE(0) !== 0x7F454C46) {\n // Unexpected magic bytes\n return null;\n }\n if (elf.readUInt8(4) !== 2) {\n // Not a 64-bit ELF\n return null;\n }\n if (elf.readUInt8(5) !== 1) {\n // Not little-endian\n return null;\n }\n const offset = elf.readUInt32LE(32);\n const size = elf.readUInt16LE(54);\n const count = elf.readUInt16LE(56);\n for (let i = 0; i < count; i++) {\n const headerOffset = offset + (i * size);\n const type = elf.readUInt32LE(headerOffset);\n if (type === 3) {\n const fileOffset = elf.readUInt32LE(headerOffset + 8);\n const fileSize = elf.readUInt32LE(headerOffset + 32);\n return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\\0.*$/g, '');\n }\n }\n return null;\n};\n\nmodule.exports = {\n interpreterPath\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst childProcess = require('child_process');\nconst { isLinux, getReport } = require('./process');\nconst { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem');\nconst { interpreterPath } = require('./elf');\n\nlet cachedFamilyInterpreter;\nlet cachedFamilyFilesystem;\nlet cachedVersionFilesystem;\n\nconst command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true';\nlet commandOut = '';\n\nconst safeCommand = () => {\n if (!commandOut) {\n return new Promise((resolve) => {\n childProcess.exec(command, (err, out) => {\n commandOut = err ? ' ' : out;\n resolve(commandOut);\n });\n });\n }\n return commandOut;\n};\n\nconst safeCommandSync = () => {\n if (!commandOut) {\n try {\n commandOut = childProcess.execSync(command, { encoding: 'utf8' });\n } catch (_err) {\n commandOut = ' ';\n }\n }\n return commandOut;\n};\n\n/**\n * A String constant containing the value `glibc`.\n * @type {string}\n * @public\n */\nconst GLIBC = 'glibc';\n\n/**\n * A Regexp constant to get the GLIBC Version.\n * @type {string}\n */\nconst RE_GLIBC_VERSION = /LIBC[a-z0-9 \\-).]*?(\\d+\\.\\d+)/i;\n\n/**\n * A String constant containing the value `musl`.\n * @type {string}\n * @public\n */\nconst MUSL = 'musl';\n\nconst isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-');\n\nconst familyFromReport = () => {\n const report = getReport();\n if (report.header && report.header.glibcVersionRuntime) {\n return GLIBC;\n }\n if (Array.isArray(report.sharedObjects)) {\n if (report.sharedObjects.some(isFileMusl)) {\n return MUSL;\n }\n }\n return null;\n};\n\nconst familyFromCommand = (out) => {\n const [getconf, ldd1] = out.split(/[\\r\\n]+/);\n if (getconf && getconf.includes(GLIBC)) {\n return GLIBC;\n }\n if (ldd1 && ldd1.includes(MUSL)) {\n return MUSL;\n }\n return null;\n};\n\nconst familyFromInterpreterPath = (path) => {\n if (path) {\n if (path.includes('/ld-musl-')) {\n return MUSL;\n } else if (path.includes('/ld-linux-')) {\n return GLIBC;\n }\n }\n return null;\n};\n\nconst getFamilyFromLddContent = (content) => {\n content = content.toString();\n if (content.includes('musl')) {\n return MUSL;\n }\n if (content.includes('GNU C Library')) {\n return GLIBC;\n }\n return null;\n};\n\nconst familyFromFilesystem = async () => {\n if (cachedFamilyFilesystem !== undefined) {\n return cachedFamilyFilesystem;\n }\n cachedFamilyFilesystem = null;\n try {\n const lddContent = await readFile(LDD_PATH);\n cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n } catch (e) {}\n return cachedFamilyFilesystem;\n};\n\nconst familyFromFilesystemSync = () => {\n if (cachedFamilyFilesystem !== undefined) {\n return cachedFamilyFilesystem;\n }\n cachedFamilyFilesystem = null;\n try {\n const lddContent = readFileSync(LDD_PATH);\n cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n } catch (e) {}\n return cachedFamilyFilesystem;\n};\n\nconst familyFromInterpreter = async () => {\n if (cachedFamilyInterpreter !== undefined) {\n return cachedFamilyInterpreter;\n }\n cachedFamilyInterpreter = null;\n try {\n const selfContent = await readFile(SELF_PATH);\n const path = interpreterPath(selfContent);\n cachedFamilyInterpreter = familyFromInterpreterPath(path);\n } catch (e) {}\n return cachedFamilyInterpreter;\n};\n\nconst familyFromInterpreterSync = () => {\n if (cachedFamilyInterpreter !== undefined) {\n return cachedFamilyInterpreter;\n }\n cachedFamilyInterpreter = null;\n try {\n const selfContent = readFileSync(SELF_PATH);\n const path = interpreterPath(selfContent);\n cachedFamilyInterpreter = familyFromInterpreterPath(path);\n } catch (e) {}\n return cachedFamilyInterpreter;\n};\n\n/**\n * Resolves with the libc family when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst family = async () => {\n let family = null;\n if (isLinux()) {\n family = await familyFromInterpreter();\n if (!family) {\n family = await familyFromFilesystem();\n if (!family) {\n family = familyFromReport();\n }\n if (!family) {\n const out = await safeCommand();\n family = familyFromCommand(out);\n }\n }\n }\n return family;\n};\n\n/**\n * Returns the libc family when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst familySync = () => {\n let family = null;\n if (isLinux()) {\n family = familyFromInterpreterSync();\n if (!family) {\n family = familyFromFilesystemSync();\n if (!family) {\n family = familyFromReport();\n }\n if (!family) {\n const out = safeCommandSync();\n family = familyFromCommand(out);\n }\n }\n }\n return family;\n};\n\n/**\n * Resolves `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {Promise<boolean>}\n */\nconst isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC;\n\n/**\n * Returns `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {boolean}\n */\nconst isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC;\n\nconst versionFromFilesystem = async () => {\n if (cachedVersionFilesystem !== undefined) {\n return cachedVersionFilesystem;\n }\n cachedVersionFilesystem = null;\n try {\n const lddContent = await readFile(LDD_PATH);\n const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n if (versionMatch) {\n cachedVersionFilesystem = versionMatch[1];\n }\n } catch (e) {}\n return cachedVersionFilesystem;\n};\n\nconst versionFromFilesystemSync = () => {\n if (cachedVersionFilesystem !== undefined) {\n return cachedVersionFilesystem;\n }\n cachedVersionFilesystem = null;\n try {\n const lddContent = readFileSync(LDD_PATH);\n const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n if (versionMatch) {\n cachedVersionFilesystem = versionMatch[1];\n }\n } catch (e) {}\n return cachedVersionFilesystem;\n};\n\nconst versionFromReport = () => {\n const report = getReport();\n if (report.header && report.header.glibcVersionRuntime) {\n return report.header.glibcVersionRuntime;\n }\n return null;\n};\n\nconst versionSuffix = (s) => s.trim().split(/\\s+/)[1];\n\nconst versionFromCommand = (out) => {\n const [getconf, ldd1, ldd2] = out.split(/[\\r\\n]+/);\n if (getconf && getconf.includes(GLIBC)) {\n return versionSuffix(getconf);\n }\n if (ldd1 && ldd2 && ldd1.includes(MUSL)) {\n return versionSuffix(ldd2);\n }\n return null;\n};\n\n/**\n * Resolves with the libc version when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst version = async () => {\n let version = null;\n if (isLinux()) {\n version = await versionFromFilesystem();\n if (!version) {\n version = versionFromReport();\n }\n if (!version) {\n const out = await safeCommand();\n version = versionFromCommand(out);\n }\n }\n return version;\n};\n\n/**\n * Returns the libc version when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst versionSync = () => {\n let version = null;\n if (isLinux()) {\n version = versionFromFilesystemSync();\n if (!version) {\n version = versionFromReport();\n }\n if (!version) {\n const out = safeCommandSync();\n version = versionFromCommand(out);\n }\n }\n return version;\n};\n\nmodule.exports = {\n GLIBC,\n MUSL,\n family,\n familySync,\n isNonGlibcLinux,\n isNonGlibcLinuxSync,\n version,\n versionSync\n};\n","'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n","'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n","'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numberic identifiers include numberic identifiers but can be longer.\n// Therefore non-numberic identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n","'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n","'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n","'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n","'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n","'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n","'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n","'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n","'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n","'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n","'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n","'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n","{\n \"name\": \"sharp\",\n \"description\": \"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images\",\n \"version\": \"0.33.5\",\n \"author\": \"Lovell Fuller <npm@lovell.info>\",\n \"homepage\": \"https://sharp.pixelplumbing.com\",\n \"contributors\": [\n \"Pierre Inglebert <pierre.inglebert@gmail.com>\",\n \"Jonathan Ong <jonathanrichardong@gmail.com>\",\n \"Chanon Sajjamanochai <chanon.s@gmail.com>\",\n \"Juliano Julio <julianojulio@gmail.com>\",\n \"Daniel Gasienica <daniel@gasienica.ch>\",\n \"Julian Walker <julian@fiftythree.com>\",\n \"Amit Pitaru <pitaru.amit@gmail.com>\",\n \"Brandon Aaron <hello.brandon@aaron.sh>\",\n \"Andreas Lind <andreas@one.com>\",\n \"Maurus Cuelenaere <mcuelenaere@gmail.com>\",\n \"Linus Unnebäck <linus@folkdatorn.se>\",\n \"Victor Mateevitsi <mvictoras@gmail.com>\",\n \"Alaric Holloway <alaric.holloway@gmail.com>\",\n \"Bernhard K. Weisshuhn <bkw@codingforce.com>\",\n \"Chris Riley <criley@primedia.com>\",\n \"David Carley <dacarley@gmail.com>\",\n \"John Tobin <john@limelightmobileinc.com>\",\n \"Kenton Gray <kentongray@gmail.com>\",\n \"Felix Bünemann <Felix.Buenemann@gmail.com>\",\n \"Samy Al Zahrani <samyalzahrany@gmail.com>\",\n \"Chintan Thakkar <lemnisk8@gmail.com>\",\n \"F. Orlando Galashan <frulo@gmx.de>\",\n \"Kleis Auke Wolthuizen <info@kleisauke.nl>\",\n \"Matt Hirsch <mhirsch@media.mit.edu>\",\n \"Matthias Thoemmes <thoemmes@gmail.com>\",\n \"Patrick Paskaris <patrick@paskaris.gr>\",\n \"Jérémy Lal <kapouer@melix.org>\",\n \"Rahul Nanwani <r.nanwani@gmail.com>\",\n \"Alice Monday <alice0meta@gmail.com>\",\n \"Kristo Jorgenson <kristo.jorgenson@gmail.com>\",\n \"YvesBos <yves_bos@outlook.com>\",\n \"Guy Maliar <guy@tailorbrands.com>\",\n \"Nicolas Coden <nicolas@ncoden.fr>\",\n \"Matt Parrish <matt.r.parrish@gmail.com>\",\n \"Marcel Bretschneider <marcel.bretschneider@gmail.com>\",\n \"Matthew McEachen <matthew+github@mceachen.org>\",\n \"Jarda Kotěšovec <jarda.kotesovec@gmail.com>\",\n \"Kenric D'Souza <kenric.dsouza@gmail.com>\",\n \"Oleh Aleinyk <oleg.aleynik@gmail.com>\",\n \"Marcel Bretschneider <marcel.bretschneider@gmail.com>\",\n \"Andrea Bianco <andrea.bianco@unibas.ch>\",\n \"Rik Heywood <rik@rik.org>\",\n \"Thomas Parisot <hi@oncletom.io>\",\n \"Nathan Graves <nathanrgraves+github@gmail.com>\",\n \"Tom Lokhorst <tom@lokhorst.eu>\",\n \"Espen Hovlandsdal <espen@hovlandsdal.com>\",\n \"Sylvain Dumont <sylvain.dumont35@gmail.com>\",\n \"Alun Davies <alun.owain.davies@googlemail.com>\",\n \"Aidan Hoolachan <ajhoolachan21@gmail.com>\",\n \"Axel Eirola <axel.eirola@iki.fi>\",\n \"Freezy <freezy@xbmc.org>\",\n \"Daiz <taneli.vatanen@gmail.com>\",\n \"Julian Aubourg <j@ubourg.net>\",\n \"Keith Belovay <keith@picthrive.com>\",\n \"Michael B. Klein <mbklein@gmail.com>\",\n \"Jordan Prudhomme <jordan@raboland.fr>\",\n \"Ilya Ovdin <iovdin@gmail.com>\",\n \"Andargor <andargor@yahoo.com>\",\n \"Paul Neave <paul.neave@gmail.com>\",\n \"Brendan Kennedy <brenwken@gmail.com>\",\n \"Brychan Bennett-Odlum <git@brychan.io>\",\n \"Edward Silverton <e.silverton@gmail.com>\",\n \"Roman Malieiev <aromaleev@gmail.com>\",\n \"Tomas Szabo <tomas.szabo@deftomat.com>\",\n \"Robert O'Rourke <robert@o-rourke.org>\",\n \"Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>\",\n \"Christian Flintrup <chr@gigahost.dk>\",\n \"Manan Jadhav <manan@motionden.com>\",\n \"Leon Radley <leon@radley.se>\",\n \"alza54 <alza54@thiocod.in>\",\n \"Jacob Smith <jacob@frende.me>\",\n \"Michael Nutt <michael@nutt.im>\",\n \"Brad Parham <baparham@gmail.com>\",\n \"Taneli Vatanen <taneli.vatanen@gmail.com>\",\n \"Joris Dugué <zaruike10@gmail.com>\",\n \"Chris Banks <christopher.bradley.banks@gmail.com>\",\n \"Ompal Singh <ompal.hitm09@gmail.com>\",\n \"Brodan <christopher.hranj@gmail.com>\",\n \"Ankur Parihar <ankur.github@gmail.com>\",\n \"Brahim Ait elhaj <brahima@gmail.com>\",\n \"Mart Jansink <m.jansink@gmail.com>\",\n \"Lachlan Newman <lachnewman007@gmail.com>\",\n \"Dennis Beatty <dennis@dcbeatty.com>\",\n \"Ingvar Stepanyan <me@rreverser.com>\",\n \"Don Denton <don@happycollision.com>\"\n ],\n \"scripts\": {\n \"install\": \"node install/check\",\n \"clean\": \"rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*\",\n \"test\": \"npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types\",\n \"test-lint\": \"semistandard && cpplint\",\n \"test-unit\": \"nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha\",\n \"test-licensing\": \"license-checker --production --summary --onlyAllow=\\\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\\\"\",\n \"test-leak\": \"./test/leak/leak.sh\",\n \"test-types\": \"tsd\",\n \"package-from-local-build\": \"node npm/from-local-build\",\n \"package-from-github-release\": \"node npm/from-github-release\",\n \"docs-build\": \"node docs/build && node docs/search-index/build\",\n \"docs-serve\": \"cd docs && npx serve\",\n \"docs-publish\": \"cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp\"\n },\n \"type\": \"commonjs\",\n \"main\": \"lib/index.js\",\n \"types\": \"lib/index.d.ts\",\n \"files\": [\n \"install\",\n \"lib\",\n \"src/*.{cc,h,gyp}\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/lovell/sharp.git\"\n },\n \"keywords\": [\n \"jpeg\",\n \"png\",\n \"webp\",\n \"avif\",\n \"tiff\",\n \"gif\",\n \"svg\",\n \"jp2\",\n \"dzi\",\n \"image\",\n \"resize\",\n \"thumbnail\",\n \"crop\",\n \"embed\",\n \"libvips\",\n \"vips\"\n ],\n \"dependencies\": {\n \"color\": \"^4.2.3\",\n \"detect-libc\": \"^2.0.3\",\n \"semver\": \"^7.6.3\"\n },\n \"optionalDependencies\": {\n \"@img/sharp-darwin-arm64\": \"0.33.5\",\n \"@img/sharp-darwin-x64\": \"0.33.5\",\n \"@img/sharp-libvips-darwin-arm64\": \"1.0.4\",\n \"@img/sharp-libvips-darwin-x64\": \"1.0.4\",\n \"@img/sharp-libvips-linux-arm\": \"1.0.5\",\n \"@img/sharp-libvips-linux-arm64\": \"1.0.4\",\n \"@img/sharp-libvips-linux-s390x\": \"1.0.4\",\n \"@img/sharp-libvips-linux-x64\": \"1.0.4\",\n \"@img/sharp-libvips-linuxmusl-arm64\": \"1.0.4\",\n \"@img/sharp-libvips-linuxmusl-x64\": \"1.0.4\",\n \"@img/sharp-linux-arm\": \"0.33.5\",\n \"@img/sharp-linux-arm64\": \"0.33.5\",\n \"@img/sharp-linux-s390x\": \"0.33.5\",\n \"@img/sharp-linux-x64\": \"0.33.5\",\n \"@img/sharp-linuxmusl-arm64\": \"0.33.5\",\n \"@img/sharp-linuxmusl-x64\": \"0.33.5\",\n \"@img/sharp-wasm32\": \"0.33.5\",\n \"@img/sharp-win32-ia32\": \"0.33.5\",\n \"@img/sharp-win32-x64\": \"0.33.5\"\n },\n \"devDependencies\": {\n \"@emnapi/runtime\": \"^1.2.0\",\n \"@img/sharp-libvips-dev\": \"1.0.4\",\n \"@img/sharp-libvips-dev-wasm32\": \"1.0.5\",\n \"@img/sharp-libvips-win32-ia32\": \"1.0.4\",\n \"@img/sharp-libvips-win32-x64\": \"1.0.4\",\n \"@types/node\": \"*\",\n \"async\": \"^3.2.5\",\n \"cc\": \"^3.0.1\",\n \"emnapi\": \"^1.2.0\",\n \"exif-reader\": \"^2.0.1\",\n \"extract-zip\": \"^2.0.1\",\n \"icc\": \"^3.0.0\",\n \"jsdoc-to-markdown\": \"^8.0.3\",\n \"license-checker\": \"^25.0.1\",\n \"mocha\": \"^10.7.3\",\n \"node-addon-api\": \"^8.1.0\",\n \"nyc\": \"^17.0.0\",\n \"prebuild\": \"^13.0.1\",\n \"semistandard\": \"^17.0.0\",\n \"tar-fs\": \"^3.0.6\",\n \"tsd\": \"^0.31.1\"\n },\n \"license\": \"Apache-2.0\",\n \"engines\": {\n \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n },\n \"config\": {\n \"libvips\": \">=8.15.3\"\n },\n \"funding\": {\n \"url\": \"https://opencollective.com/libvips\"\n },\n \"binary\": {\n \"napi_versions\": [\n 9\n ]\n },\n \"semistandard\": {\n \"env\": [\n \"mocha\"\n ]\n },\n \"cc\": {\n \"linelength\": \"120\",\n \"filter\": [\n \"build/include\"\n ]\n },\n \"nyc\": {\n \"include\": [\n \"lib\"\n ]\n },\n \"tsd\": {\n \"directory\": \"test/types/\"\n }\n}\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst { spawnSync } = require('node:child_process');\nconst { createHash } = require('node:crypto');\nconst semverCoerce = require('semver/functions/coerce');\nconst semverGreaterThanOrEqualTo = require('semver/functions/gte');\nconst semverSatisfies = require('semver/functions/satisfies');\nconst detectLibc = require('detect-libc');\n\nconst { config, engines, optionalDependencies } = require('../package.json');\n\nconst minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */\n config.libvips;\nconst minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;\n\nconst prebuiltPlatforms = [\n 'darwin-arm64', 'darwin-x64',\n 'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64',\n 'linuxmusl-arm64', 'linuxmusl-x64',\n 'win32-ia32', 'win32-x64'\n];\n\nconst spawnSyncOptions = {\n encoding: 'utf8',\n shell: true\n};\n\nconst log = (item) => {\n if (item instanceof Error) {\n console.error(`sharp: Installation error: ${item.message}`);\n } else {\n console.log(`sharp: ${item}`);\n }\n};\n\n/* istanbul ignore next */\nconst runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '';\n\nconst runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`;\n\n/* istanbul ignore next */\nconst buildPlatformArch = () => {\n if (isEmscripten()) {\n return 'wasm32';\n }\n /* eslint camelcase: [\"error\", { allow: [\"^npm_config_\"] }] */\n const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;\n const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc();\n return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`;\n};\n\nconst buildSharpLibvipsIncludeDir = () => {\n try {\n return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`);\n } catch {\n try {\n return require('@img/sharp-libvips-dev/include');\n } catch {}\n }\n /* istanbul ignore next */\n return '';\n};\n\nconst buildSharpLibvipsCPlusPlusDir = () => {\n try {\n return require('@img/sharp-libvips-dev/cplusplus');\n } catch {}\n /* istanbul ignore next */\n return '';\n};\n\nconst buildSharpLibvipsLibDir = () => {\n try {\n return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`);\n } catch {\n try {\n return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`);\n } catch {}\n }\n /* istanbul ignore next */\n return '';\n};\n\nconst isUnsupportedNodeRuntime = () => {\n /* istanbul ignore next */\n if (process.release?.name === 'node' && process.versions) {\n if (!semverSatisfies(process.versions.node, engines.node)) {\n return { found: process.versions.node, expected: engines.node };\n }\n }\n};\n\n/* istanbul ignore next */\nconst isEmscripten = () => {\n const { CC } = process.env;\n return Boolean(CC && CC.endsWith('/emcc'));\n};\n\nconst isRosetta = () => {\n /* istanbul ignore next */\n if (process.platform === 'darwin' && process.arch === 'x64') {\n const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;\n return (translated || '').trim() === 'sysctl.proc_translated: 1';\n }\n return false;\n};\n\nconst sha512 = (s) => createHash('sha512').update(s).digest('hex');\n\nconst yarnLocator = () => {\n try {\n const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);\n const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`]).version;\n return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);\n } catch {}\n return '';\n};\n\n/* istanbul ignore next */\nconst spawnRebuild = () =>\n spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {\n ...spawnSyncOptions,\n stdio: 'inherit'\n }).status;\n\nconst globalLibvipsVersion = () => {\n if (process.platform !== 'win32') {\n const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {\n ...spawnSyncOptions,\n env: {\n ...process.env,\n PKG_CONFIG_PATH: pkgConfigPath()\n }\n }).stdout;\n /* istanbul ignore next */\n return (globalLibvipsVersion || '').trim();\n } else {\n return '';\n }\n};\n\n/* istanbul ignore next */\nconst pkgConfigPath = () => {\n if (process.platform !== 'win32') {\n const brewPkgConfigPath = spawnSync(\n 'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d\" \" -f2',\n spawnSyncOptions\n ).stdout || '';\n return [\n brewPkgConfigPath.trim(),\n process.env.PKG_CONFIG_PATH,\n '/usr/local/lib/pkgconfig',\n '/usr/lib/pkgconfig',\n '/usr/local/libdata/pkgconfig',\n '/usr/libdata/pkgconfig'\n ].filter(Boolean).join(':');\n } else {\n return '';\n }\n};\n\nconst skipSearch = (status, reason, logger) => {\n if (logger) {\n logger(`Detected ${reason}, skipping search for globally-installed libvips`);\n }\n return status;\n};\n\nconst useGlobalLibvips = (logger) => {\n if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {\n return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger);\n }\n if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {\n return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger);\n }\n /* istanbul ignore next */\n if (isRosetta()) {\n return skipSearch(false, 'Rosetta', logger);\n }\n const globalVipsVersion = globalLibvipsVersion();\n return !!globalVipsVersion && /* istanbul ignore next */\n semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion);\n};\n\nmodule.exports = {\n minimumLibvipsVersion,\n prebuiltPlatforms,\n buildPlatformArch,\n buildSharpLibvipsIncludeDir,\n buildSharpLibvipsCPlusPlusDir,\n buildSharpLibvipsLibDir,\n isUnsupportedNodeRuntime,\n runtimePlatformArch,\n log,\n yarnLocator,\n spawnRebuild,\n globalLibvipsVersion,\n pkgConfigPath,\n useGlobalLibvips\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\n// Inspects the runtime environment and exports the relevant sharp.node binary\n\nconst { familySync, versionSync } = require('detect-libc');\n\nconst { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');\nconst runtimePlatform = runtimePlatformArch();\n\nconst paths = [\n `../src/build/Release/sharp-${runtimePlatform}.node`,\n '../src/build/Release/sharp-wasm32.node',\n `@img/sharp-${runtimePlatform}/sharp.node`,\n '@img/sharp-wasm32/sharp.node'\n];\n\nlet sharp;\nconst errors = [];\nfor (const path of paths) {\n try {\n sharp = require(path);\n break;\n } catch (err) {\n /* istanbul ignore next */\n errors.push(err);\n }\n}\n\n/* istanbul ignore next */\nif (sharp) {\n module.exports = sharp;\n} else {\n const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));\n\n const help = [`Could not load the \"sharp\" module using the ${runtimePlatform} runtime`];\n errors.forEach(err => {\n if (err.code !== 'MODULE_NOT_FOUND') {\n help.push(`${err.code}: ${err.message}`);\n }\n });\n const messages = errors.map(err => err.message).join(' ');\n help.push('Possible solutions:');\n // Common error messages\n if (isUnsupportedNodeRuntime()) {\n const { found, expected } = isUnsupportedNodeRuntime();\n help.push(\n '- Please upgrade Node.js:',\n ` Found ${found}`,\n ` Requires ${expected}`\n );\n } else if (prebuiltPlatforms.includes(runtimePlatform)) {\n const [os, cpu] = runtimePlatform.split('-');\n const libc = os.endsWith('musl') ? ' --libc=musl' : '';\n help.push(\n '- Ensure optional dependencies can be installed:',\n ' npm install --include=optional sharp',\n '- Ensure your package manager supports multi-platform installation:',\n ' See https://sharp.pixelplumbing.com/install#cross-platform',\n '- Add platform-specific dependencies:',\n ` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp`\n );\n } else {\n help.push(\n `- Manually install libvips >= ${minimumLibvipsVersion}`,\n '- Add experimental WebAssembly-based dependencies:',\n ' npm install --cpu=wasm32 sharp',\n ' npm install @img/sharp-wasm32'\n );\n }\n if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) {\n try {\n const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);\n const libcFound = `${familySync()} ${versionSync()}`;\n const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`;\n help.push(\n '- Update your OS:',\n ` Found ${libcFound}`,\n ` Requires ${libcRequires}`\n );\n } catch (errEngines) {}\n }\n if (isLinux && /\\/snap\\/core[0-9]{2}/.test(messages)) {\n help.push(\n '- Remove the Node.js Snap, which does not support native modules',\n ' snap remove node'\n );\n }\n if (isMacOs && /Incompatible library version/.test(messages)) {\n help.push(\n '- Update Homebrew:',\n ' brew update && brew upgrade vips'\n );\n }\n if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) {\n help.push('- Run Node.js without using the --no-addons flag');\n }\n // Link to installation docs\n if (isWindows && /The specified procedure could not be found/.test(messages)) {\n help.push(\n '- Using the canvas package on Windows?',\n ' See https://sharp.pixelplumbing.com/install#canvas-and-windows',\n '- Check for outdated versions of sharp in the dependency tree:',\n ' npm ls sharp'\n );\n }\n help.push(\n '- Consult the installation documentation:',\n ' See https://sharp.pixelplumbing.com/install'\n );\n throw new Error(help.join('\\n'));\n}\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst util = require('node:util');\nconst stream = require('node:stream');\nconst is = require('./is');\n\nrequire('./sharp');\n\n// Use NODE_DEBUG=sharp to enable libvips warnings\nconst debuglog = util.debuglog('sharp');\n\n/**\n * Constructor factory to create an instance of `sharp`, to which further methods are chained.\n *\n * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.\n * When using Stream based output, derived attributes are available from the `info` event.\n *\n * Non-critical problems encountered during processing are emitted as `warning` events.\n *\n * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.\n *\n * When loading more than one page/frame of an animated image,\n * these are combined as a vertically-stacked \"toilet roll\" image\n * where the overall height is the `pageHeight` multiplied by the number of `pages`.\n *\n * @constructs Sharp\n *\n * @emits Sharp#info\n * @emits Sharp#warning\n *\n * @example\n * sharp('input.jpg')\n * .resize(300, 200)\n * .toFile('output.jpg', function(err) {\n * // output.jpg is a 300 pixels wide and 200 pixels high image\n * // containing a scaled and cropped version of input.jpg\n * });\n *\n * @example\n * // Read image data from remote URL,\n * // resize to 300 pixels wide,\n * // emit an 'info' event with calculated dimensions\n * // and finally write image data to writableStream\n * const { body } = fetch('https://...');\n * const readableStream = Readable.fromWeb(body);\n * const transformer = sharp()\n * .resize(300)\n * .on('info', ({ height }) => {\n * console.log(`Image height is ${height}`);\n * });\n * readableStream.pipe(transformer).pipe(writableStream);\n *\n * @example\n * // Create a blank 300x200 PNG image of semi-translucent red pixels\n * sharp({\n * create: {\n * width: 300,\n * height: 200,\n * channels: 4,\n * background: { r: 255, g: 0, b: 0, alpha: 0.5 }\n * }\n * })\n * .png()\n * .toBuffer()\n * .then( ... );\n *\n * @example\n * // Convert an animated GIF to an animated WebP\n * await sharp('in.gif', { animated: true }).toFile('out.webp');\n *\n * @example\n * // Read a raw array of pixels and save it to a png\n * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray\n * const image = sharp(input, {\n * // because the input does not contain its dimensions or how many channels it has\n * // we need to specify it in the constructor options\n * raw: {\n * width: 2,\n * height: 1,\n * channels: 3\n * }\n * });\n * await image.toFile('my-two-pixels.png');\n *\n * @example\n * // Generate RGB Gaussian noise\n * await sharp({\n * create: {\n * width: 300,\n * height: 200,\n * channels: 3,\n * noise: {\n * type: 'gaussian',\n * mean: 128,\n * sigma: 30\n * }\n * }\n * }).toFile('noise.png');\n *\n * @example\n * // Generate an image from text\n * await sharp({\n * text: {\n * text: 'Hello, world!',\n * width: 400, // max width\n * height: 300 // max height\n * }\n * }).toFile('text_bw.png');\n *\n * @example\n * // Generate an rgba image from text using pango markup and font\n * await sharp({\n * text: {\n * text: '<span foreground=\"red\">Red!</span><span background=\"cyan\">blue</span>',\n * font: 'sans',\n * rgba: true,\n * dpi: 300\n * }\n * }).toFile('text_rgba.png');\n *\n * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be\n * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or\n * a TypedArray containing raw pixel image data, or\n * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.\n * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.\n * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels\n * (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.\n * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).\n * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).\n * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.\n * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.\n * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.\n * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.\n * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.\n * @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.\n * @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.\n * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.\n * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.\n * @param {number} [options.raw.width] - integral number of pixels wide.\n * @param {number} [options.raw.height] - integral number of pixels high.\n * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.\n * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`\n * to avoid sharp premultiplying the image. (optional, default `false`)\n * @param {Object} [options.create] - describes a new image to be created.\n * @param {number} [options.create.width] - integral number of pixels wide.\n * @param {number} [options.create.height] - integral number of pixels high.\n * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).\n * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Object} [options.create.noise] - describes a noise to be created.\n * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.\n * @param {number} [options.create.noise.mean] - mean of pixels in generated noise.\n * @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.\n * @param {Object} [options.text] - describes a new text image to be created.\n * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.\n * @param {string} [options.text.font] - font name to render with.\n * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.\n * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.\n * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.\n * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.\n * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.\n * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground=\"red\">Red!</span>`.\n * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.\n * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nconst Sharp = function (input, options) {\n if (arguments.length === 1 && !is.defined(input)) {\n throw new Error('Invalid input');\n }\n if (!(this instanceof Sharp)) {\n return new Sharp(input, options);\n }\n stream.Duplex.call(this);\n this.options = {\n // resize options\n topOffsetPre: -1,\n leftOffsetPre: -1,\n widthPre: -1,\n heightPre: -1,\n topOffsetPost: -1,\n leftOffsetPost: -1,\n widthPost: -1,\n heightPost: -1,\n width: -1,\n height: -1,\n canvas: 'crop',\n position: 0,\n resizeBackground: [0, 0, 0, 255],\n useExifOrientation: false,\n angle: 0,\n rotationAngle: 0,\n rotationBackground: [0, 0, 0, 255],\n rotateBeforePreExtract: false,\n flip: false,\n flop: false,\n extendTop: 0,\n extendBottom: 0,\n extendLeft: 0,\n extendRight: 0,\n extendBackground: [0, 0, 0, 255],\n extendWith: 'background',\n withoutEnlargement: false,\n withoutReduction: false,\n affineMatrix: [],\n affineBackground: [0, 0, 0, 255],\n affineIdx: 0,\n affineIdy: 0,\n affineOdx: 0,\n affineOdy: 0,\n affineInterpolator: this.constructor.interpolators.bilinear,\n kernel: 'lanczos3',\n fastShrinkOnLoad: true,\n // operations\n tint: [-1, 0, 0, 0],\n flatten: false,\n flattenBackground: [0, 0, 0],\n unflatten: false,\n negate: false,\n negateAlpha: true,\n medianSize: 0,\n blurSigma: 0,\n precision: 'integer',\n minAmpl: 0.2,\n sharpenSigma: 0,\n sharpenM1: 1,\n sharpenM2: 2,\n sharpenX1: 2,\n sharpenY2: 10,\n sharpenY3: 20,\n threshold: 0,\n thresholdGrayscale: true,\n trimBackground: [],\n trimThreshold: -1,\n trimLineArt: false,\n gamma: 0,\n gammaOut: 0,\n greyscale: false,\n normalise: false,\n normaliseLower: 1,\n normaliseUpper: 99,\n claheWidth: 0,\n claheHeight: 0,\n claheMaxSlope: 3,\n brightness: 1,\n saturation: 1,\n hue: 0,\n lightness: 0,\n booleanBufferIn: null,\n booleanFileIn: '',\n joinChannelIn: [],\n extractChannel: -1,\n removeAlpha: false,\n ensureAlpha: -1,\n colourspace: 'srgb',\n colourspacePipeline: 'last',\n composite: [],\n // output\n fileOut: '',\n formatOut: 'input',\n streamOut: false,\n keepMetadata: 0,\n withMetadataOrientation: -1,\n withMetadataDensity: 0,\n withIccProfile: '',\n withExif: {},\n withExifMerge: true,\n resolveWithObject: false,\n // output format\n jpegQuality: 80,\n jpegProgressive: false,\n jpegChromaSubsampling: '4:2:0',\n jpegTrellisQuantisation: false,\n jpegOvershootDeringing: false,\n jpegOptimiseScans: false,\n jpegOptimiseCoding: true,\n jpegQuantisationTable: 0,\n pngProgressive: false,\n pngCompressionLevel: 6,\n pngAdaptiveFiltering: false,\n pngPalette: false,\n pngQuality: 100,\n pngEffort: 7,\n pngBitdepth: 8,\n pngDither: 1,\n jp2Quality: 80,\n jp2TileHeight: 512,\n jp2TileWidth: 512,\n jp2Lossless: false,\n jp2ChromaSubsampling: '4:4:4',\n webpQuality: 80,\n webpAlphaQuality: 100,\n webpLossless: false,\n webpNearLossless: false,\n webpSmartSubsample: false,\n webpPreset: 'default',\n webpEffort: 4,\n webpMinSize: false,\n webpMixed: false,\n gifBitdepth: 8,\n gifEffort: 7,\n gifDither: 1,\n gifInterFrameMaxError: 0,\n gifInterPaletteMaxError: 3,\n gifReuse: true,\n gifProgressive: false,\n tiffQuality: 80,\n tiffCompression: 'jpeg',\n tiffPredictor: 'horizontal',\n tiffPyramid: false,\n tiffMiniswhite: false,\n tiffBitdepth: 8,\n tiffTile: false,\n tiffTileHeight: 256,\n tiffTileWidth: 256,\n tiffXres: 1.0,\n tiffYres: 1.0,\n tiffResolutionUnit: 'inch',\n heifQuality: 50,\n heifLossless: false,\n heifCompression: 'av1',\n heifEffort: 4,\n heifChromaSubsampling: '4:4:4',\n heifBitdepth: 8,\n jxlDistance: 1,\n jxlDecodingTier: 0,\n jxlEffort: 7,\n jxlLossless: false,\n rawDepth: 'uchar',\n tileSize: 256,\n tileOverlap: 0,\n tileContainer: 'fs',\n tileLayout: 'dz',\n tileFormat: 'last',\n tileDepth: 'last',\n tileAngle: 0,\n tileSkipBlanks: -1,\n tileBackground: [255, 255, 255, 255],\n tileCentre: false,\n tileId: 'https://example.com/iiif',\n tileBasename: '',\n timeoutSeconds: 0,\n linearA: [],\n linearB: [],\n // Function to notify of libvips warnings\n debuglog: warning => {\n this.emit('warning', warning);\n debuglog(warning);\n },\n // Function to notify of queue length changes\n queueListener: function (queueLength) {\n Sharp.queue.emit('change', queueLength);\n }\n };\n this.options.input = this._createInputDescriptor(input, options, { allowStream: true });\n return this;\n};\nObject.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype);\nObject.setPrototypeOf(Sharp, stream.Duplex);\n\n/**\n * Take a \"snapshot\" of the Sharp instance, returning a new instance.\n * Cloned instances inherit the input of their parent instance.\n * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.\n *\n * @example\n * const pipeline = sharp().rotate();\n * pipeline.clone().resize(800, 600).pipe(firstWritableStream);\n * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);\n * readableStream.pipe(pipeline);\n * // firstWritableStream receives auto-rotated, resized readableStream\n * // secondWritableStream receives auto-rotated, extracted region of readableStream\n *\n * @example\n * // Create a pipeline that will download an image, resize it and format it to different files\n * // Using Promises to know when the pipeline is complete\n * const fs = require(\"fs\");\n * const got = require(\"got\");\n * const sharpStream = sharp({ failOn: 'none' });\n *\n * const promises = [];\n *\n * promises.push(\n * sharpStream\n * .clone()\n * .jpeg({ quality: 100 })\n * .toFile(\"originalFile.jpg\")\n * );\n *\n * promises.push(\n * sharpStream\n * .clone()\n * .resize({ width: 500 })\n * .jpeg({ quality: 80 })\n * .toFile(\"optimized-500.jpg\")\n * );\n *\n * promises.push(\n * sharpStream\n * .clone()\n * .resize({ width: 500 })\n * .webp({ quality: 80 })\n * .toFile(\"optimized-500.webp\")\n * );\n *\n * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md\n * got.stream(\"https://www.example.com/some-file.jpg\").pipe(sharpStream);\n *\n * Promise.all(promises)\n * .then(res => { console.log(\"Done!\", res); })\n * .catch(err => {\n * console.error(\"Error processing files, let's clean it up\", err);\n * try {\n * fs.unlinkSync(\"originalFile.jpg\");\n * fs.unlinkSync(\"optimized-500.jpg\");\n * fs.unlinkSync(\"optimized-500.webp\");\n * } catch (e) {}\n * });\n *\n * @returns {Sharp}\n */\nfunction clone () {\n // Clone existing options\n const clone = this.constructor.call();\n const { debuglog, queueListener, ...options } = this.options;\n clone.options = structuredClone(options);\n clone.options.debuglog = debuglog;\n clone.options.queueListener = queueListener;\n // Pass 'finish' event to clone for Stream-based input\n if (this._isStreamInput()) {\n this.on('finish', () => {\n // Clone inherits input data\n this._flattenBufferIn();\n clone.options.input.buffer = this.options.input.buffer;\n clone.emit('finish');\n });\n }\n return clone;\n}\nObject.assign(Sharp.prototype, { clone });\n\n/**\n * Export constructor.\n * @private\n */\nmodule.exports = Sharp;\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","module.exports = function isArrayish(obj) {\n\tif (!obj || typeof obj === 'string') {\n\t\treturn false;\n\t}\n\n\treturn obj instanceof Array || Array.isArray(obj) ||\n\t\t(obj.length >= 0 && (obj.splice instanceof Function ||\n\t\t\t(Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String')));\n};\n","'use strict';\n\nvar isArrayish = require('is-arrayish');\n\nvar concat = Array.prototype.concat;\nvar slice = Array.prototype.slice;\n\nvar swizzle = module.exports = function swizzle(args) {\n\tvar results = [];\n\n\tfor (var i = 0, len = args.length; i < len; i++) {\n\t\tvar arg = args[i];\n\n\t\tif (isArrayish(arg)) {\n\t\t\t// http://jsperf.com/javascript-array-concat-vs-push/98\n\t\t\tresults = concat.call(results, slice.call(arg));\n\t\t} else {\n\t\t\tresults.push(arg);\n\t\t}\n\t}\n\n\treturn results;\n};\n\nswizzle.wrap = function (fn) {\n\treturn function () {\n\t\treturn fn(swizzle(arguments));\n\t};\n};\n","/* MIT license */\nvar colorNames = require('color-name');\nvar swizzle = require('simple-swizzle');\nvar hasOwnProperty = Object.hasOwnProperty;\n\nvar reverseNames = Object.create(null);\n\n// create a list of reverse color names\nfor (var name in colorNames) {\n\tif (hasOwnProperty.call(colorNames, name)) {\n\t\treverseNames[colorNames[name]] = name;\n\t}\n}\n\nvar cs = module.exports = {\n\tto: {},\n\tget: {}\n};\n\ncs.get = function (string) {\n\tvar prefix = string.substring(0, 3).toLowerCase();\n\tvar val;\n\tvar model;\n\tswitch (prefix) {\n\t\tcase 'hsl':\n\t\t\tval = cs.get.hsl(string);\n\t\t\tmodel = 'hsl';\n\t\t\tbreak;\n\t\tcase 'hwb':\n\t\t\tval = cs.get.hwb(string);\n\t\t\tmodel = 'hwb';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tval = cs.get.rgb(string);\n\t\t\tmodel = 'rgb';\n\t\t\tbreak;\n\t}\n\n\tif (!val) {\n\t\treturn null;\n\t}\n\n\treturn {model: model, value: val};\n};\n\ncs.get.rgb = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar abbr = /^#([a-f0-9]{3,4})$/i;\n\tvar hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;\n\tvar rgba = /^rgba?\\(\\s*([+-]?\\d+)(?=[\\s,])\\s*(?:,\\s*)?([+-]?\\d+)(?=[\\s,])\\s*(?:,\\s*)?([+-]?\\d+)\\s*(?:[,|\\/]\\s*([+-]?[\\d\\.]+)(%?)\\s*)?\\)$/;\n\tvar per = /^rgba?\\(\\s*([+-]?[\\d\\.]+)\\%\\s*,?\\s*([+-]?[\\d\\.]+)\\%\\s*,?\\s*([+-]?[\\d\\.]+)\\%\\s*(?:[,|\\/]\\s*([+-]?[\\d\\.]+)(%?)\\s*)?\\)$/;\n\tvar keyword = /^(\\w+)$/;\n\n\tvar rgb = [0, 0, 0, 1];\n\tvar match;\n\tvar i;\n\tvar hexAlpha;\n\n\tif (match = string.match(hex)) {\n\t\thexAlpha = match[2];\n\t\tmatch = match[1];\n\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\t// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19\n\t\t\tvar i2 = i * 2;\n\t\t\trgb[i] = parseInt(match.slice(i2, i2 + 2), 16);\n\t\t}\n\n\t\tif (hexAlpha) {\n\t\t\trgb[3] = parseInt(hexAlpha, 16) / 255;\n\t\t}\n\t} else if (match = string.match(abbr)) {\n\t\tmatch = match[1];\n\t\thexAlpha = match[3];\n\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = parseInt(match[i] + match[i], 16);\n\t\t}\n\n\t\tif (hexAlpha) {\n\t\t\trgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;\n\t\t}\n\t} else if (match = string.match(rgba)) {\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = parseInt(match[i + 1], 0);\n\t\t}\n\n\t\tif (match[4]) {\n\t\t\tif (match[5]) {\n\t\t\t\trgb[3] = parseFloat(match[4]) * 0.01;\n\t\t\t} else {\n\t\t\t\trgb[3] = parseFloat(match[4]);\n\t\t\t}\n\t\t}\n\t} else if (match = string.match(per)) {\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);\n\t\t}\n\n\t\tif (match[4]) {\n\t\t\tif (match[5]) {\n\t\t\t\trgb[3] = parseFloat(match[4]) * 0.01;\n\t\t\t} else {\n\t\t\t\trgb[3] = parseFloat(match[4]);\n\t\t\t}\n\t\t}\n\t} else if (match = string.match(keyword)) {\n\t\tif (match[1] === 'transparent') {\n\t\t\treturn [0, 0, 0, 0];\n\t\t}\n\n\t\tif (!hasOwnProperty.call(colorNames, match[1])) {\n\t\t\treturn null;\n\t\t}\n\n\t\trgb = colorNames[match[1]];\n\t\trgb[3] = 1;\n\n\t\treturn rgb;\n\t} else {\n\t\treturn null;\n\t}\n\n\tfor (i = 0; i < 3; i++) {\n\t\trgb[i] = clamp(rgb[i], 0, 255);\n\t}\n\trgb[3] = clamp(rgb[3], 0, 1);\n\n\treturn rgb;\n};\n\ncs.get.hsl = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar hsl = /^hsla?\\(\\s*([+-]?(?:\\d{0,3}\\.)?\\d+)(?:deg)?\\s*,?\\s*([+-]?[\\d\\.]+)%\\s*,?\\s*([+-]?[\\d\\.]+)%\\s*(?:[,|\\/]\\s*([+-]?(?=\\.\\d|\\d)(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)\\s*)?\\)$/;\n\tvar match = string.match(hsl);\n\n\tif (match) {\n\t\tvar alpha = parseFloat(match[4]);\n\t\tvar h = ((parseFloat(match[1]) % 360) + 360) % 360;\n\t\tvar s = clamp(parseFloat(match[2]), 0, 100);\n\t\tvar l = clamp(parseFloat(match[3]), 0, 100);\n\t\tvar a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);\n\n\t\treturn [h, s, l, a];\n\t}\n\n\treturn null;\n};\n\ncs.get.hwb = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar hwb = /^hwb\\(\\s*([+-]?\\d{0,3}(?:\\.\\d+)?)(?:deg)?\\s*,\\s*([+-]?[\\d\\.]+)%\\s*,\\s*([+-]?[\\d\\.]+)%\\s*(?:,\\s*([+-]?(?=\\.\\d|\\d)(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)\\s*)?\\)$/;\n\tvar match = string.match(hwb);\n\n\tif (match) {\n\t\tvar alpha = parseFloat(match[4]);\n\t\tvar h = ((parseFloat(match[1]) % 360) + 360) % 360;\n\t\tvar w = clamp(parseFloat(match[2]), 0, 100);\n\t\tvar b = clamp(parseFloat(match[3]), 0, 100);\n\t\tvar a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);\n\t\treturn [h, w, b, a];\n\t}\n\n\treturn null;\n};\n\ncs.to.hex = function () {\n\tvar rgba = swizzle(arguments);\n\n\treturn (\n\t\t'#' +\n\t\thexDouble(rgba[0]) +\n\t\thexDouble(rgba[1]) +\n\t\thexDouble(rgba[2]) +\n\t\t(rgba[3] < 1\n\t\t\t? (hexDouble(Math.round(rgba[3] * 255)))\n\t\t\t: '')\n\t);\n};\n\ncs.to.rgb = function () {\n\tvar rgba = swizzle(arguments);\n\n\treturn rgba.length < 4 || rgba[3] === 1\n\t\t? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'\n\t\t: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';\n};\n\ncs.to.rgb.percent = function () {\n\tvar rgba = swizzle(arguments);\n\n\tvar r = Math.round(rgba[0] / 255 * 100);\n\tvar g = Math.round(rgba[1] / 255 * 100);\n\tvar b = Math.round(rgba[2] / 255 * 100);\n\n\treturn rgba.length < 4 || rgba[3] === 1\n\t\t? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'\n\t\t: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';\n};\n\ncs.to.hsl = function () {\n\tvar hsla = swizzle(arguments);\n\treturn hsla.length < 4 || hsla[3] === 1\n\t\t? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'\n\t\t: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';\n};\n\n// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax\n// (hwb have alpha optional & 1 is default value)\ncs.to.hwb = function () {\n\tvar hwba = swizzle(arguments);\n\n\tvar a = '';\n\tif (hwba.length >= 4 && hwba[3] !== 1) {\n\t\ta = ', ' + hwba[3];\n\t}\n\n\treturn 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';\n};\n\ncs.to.keyword = function (rgb) {\n\treturn reverseNames[rgb.slice(0, 3)];\n};\n\n// helpers\nfunction clamp(num, min, max) {\n\treturn Math.min(Math.max(min, num), max);\n}\n\nfunction hexDouble(num) {\n\tvar str = Math.round(num).toString(16).toUpperCase();\n\treturn (str.length < 2) ? '0' + str : str;\n}\n","/* MIT license */\n/* eslint-disable no-mixed-operators */\nconst cssKeywords = require('color-name');\n\n// NOTE: conversions should only return primitive values (i.e. arrays, or\n// values that give correct `typeof` results).\n// do not use box values types (i.e. Number(), String(), etc.)\n\nconst reverseKeywords = {};\nfor (const key of Object.keys(cssKeywords)) {\n\treverseKeywords[cssKeywords[key]] = key;\n}\n\nconst convert = {\n\trgb: {channels: 3, labels: 'rgb'},\n\thsl: {channels: 3, labels: 'hsl'},\n\thsv: {channels: 3, labels: 'hsv'},\n\thwb: {channels: 3, labels: 'hwb'},\n\tcmyk: {channels: 4, labels: 'cmyk'},\n\txyz: {channels: 3, labels: 'xyz'},\n\tlab: {channels: 3, labels: 'lab'},\n\tlch: {channels: 3, labels: 'lch'},\n\thex: {channels: 1, labels: ['hex']},\n\tkeyword: {channels: 1, labels: ['keyword']},\n\tansi16: {channels: 1, labels: ['ansi16']},\n\tansi256: {channels: 1, labels: ['ansi256']},\n\thcg: {channels: 3, labels: ['h', 'c', 'g']},\n\tapple: {channels: 3, labels: ['r16', 'g16', 'b16']},\n\tgray: {channels: 1, labels: ['gray']}\n};\n\nmodule.exports = convert;\n\n// Hide .channels and .labels properties\nfor (const model of Object.keys(convert)) {\n\tif (!('channels' in convert[model])) {\n\t\tthrow new Error('missing channels property: ' + model);\n\t}\n\n\tif (!('labels' in convert[model])) {\n\t\tthrow new Error('missing channel labels property: ' + model);\n\t}\n\n\tif (convert[model].labels.length !== convert[model].channels) {\n\t\tthrow new Error('channel and label counts mismatch: ' + model);\n\t}\n\n\tconst {channels, labels} = convert[model];\n\tdelete convert[model].channels;\n\tdelete convert[model].labels;\n\tObject.defineProperty(convert[model], 'channels', {value: channels});\n\tObject.defineProperty(convert[model], 'labels', {value: labels});\n}\n\nconvert.rgb.hsl = function (rgb) {\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\tconst min = Math.min(r, g, b);\n\tconst max = Math.max(r, g, b);\n\tconst delta = max - min;\n\tlet h;\n\tlet s;\n\n\tif (max === min) {\n\t\th = 0;\n\t} else if (r === max) {\n\t\th = (g - b) / delta;\n\t} else if (g === max) {\n\t\th = 2 + (b - r) / delta;\n\t} else if (b === max) {\n\t\th = 4 + (r - g) / delta;\n\t}\n\n\th = Math.min(h * 60, 360);\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tconst l = (min + max) / 2;\n\n\tif (max === min) {\n\t\ts = 0;\n\t} else if (l <= 0.5) {\n\t\ts = delta / (max + min);\n\t} else {\n\t\ts = delta / (2 - max - min);\n\t}\n\n\treturn [h, s * 100, l * 100];\n};\n\nconvert.rgb.hsv = function (rgb) {\n\tlet rdif;\n\tlet gdif;\n\tlet bdif;\n\tlet h;\n\tlet s;\n\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\tconst v = Math.max(r, g, b);\n\tconst diff = v - Math.min(r, g, b);\n\tconst diffc = function (c) {\n\t\treturn (v - c) / 6 / diff + 1 / 2;\n\t};\n\n\tif (diff === 0) {\n\t\th = 0;\n\t\ts = 0;\n\t} else {\n\t\ts = diff / v;\n\t\trdif = diffc(r);\n\t\tgdif = diffc(g);\n\t\tbdif = diffc(b);\n\n\t\tif (r === v) {\n\t\t\th = bdif - gdif;\n\t\t} else if (g === v) {\n\t\t\th = (1 / 3) + rdif - bdif;\n\t\t} else if (b === v) {\n\t\t\th = (2 / 3) + gdif - rdif;\n\t\t}\n\n\t\tif (h < 0) {\n\t\t\th += 1;\n\t\t} else if (h > 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tconst r = rgb[0];\n\tconst g = rgb[1];\n\tlet b = rgb[2];\n\tconst h = convert.rgb.hsl(rgb)[0];\n\tconst w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\n\tconst k = Math.min(1 - r, 1 - g, 1 - b);\n\tconst c = (1 - r - k) / (1 - k) || 0;\n\tconst m = (1 - g - k) / (1 - k) || 0;\n\tconst y = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\nfunction comparativeDistance(x, y) {\n\t/*\n\t\tSee https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n\t*/\n\treturn (\n\t\t((x[0] - y[0]) ** 2) +\n\t\t((x[1] - y[1]) ** 2) +\n\t\t((x[2] - y[2]) ** 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tconst reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tlet currentClosestDistance = Infinity;\n\tlet currentClosestKeyword;\n\n\tfor (const keyword of Object.keys(cssKeywords)) {\n\t\tconst value = cssKeywords[keyword];\n\n\t\t// Compute comparative distance\n\t\tconst distance = comparativeDistance(rgb, value);\n\n\t\t// Check if its less, if so set as closest\n\t\tif (distance < currentClosestDistance) {\n\t\t\tcurrentClosestDistance = distance;\n\t\t\tcurrentClosestKeyword = keyword;\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tlet r = rgb[0] / 255;\n\tlet g = rgb[1] / 255;\n\tlet b = rgb[2] / 255;\n\n\t// Assume sRGB\n\tr = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);\n\n\tconst x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tconst y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tconst z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tconst xyz = convert.rgb.xyz(rgb);\n\tlet x = xyz[0];\n\tlet y = xyz[1];\n\tlet z = xyz[2];\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);\n\n\tconst l = (116 * y) - 16;\n\tconst a = 500 * (x - y);\n\tconst b = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tconst h = hsl[0] / 360;\n\tconst s = hsl[1] / 100;\n\tconst l = hsl[2] / 100;\n\tlet t2;\n\tlet t3;\n\tlet val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tconst t1 = 2 * l - t2;\n\n\tconst rgb = [0, 0, 0];\n\tfor (let i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tconst h = hsl[0];\n\tlet s = hsl[1] / 100;\n\tlet l = hsl[2] / 100;\n\tlet smin = s;\n\tconst lmin = Math.max(l, 0.01);\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tconst v = (l + s) / 2;\n\tconst sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tconst h = hsv[0] / 60;\n\tconst s = hsv[1] / 100;\n\tlet v = hsv[2] / 100;\n\tconst hi = Math.floor(h) % 6;\n\n\tconst f = h - Math.floor(h);\n\tconst p = 255 * v * (1 - s);\n\tconst q = 255 * v * (1 - (s * f));\n\tconst t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tconst h = hsv[0];\n\tconst s = hsv[1] / 100;\n\tconst v = hsv[2] / 100;\n\tconst vmin = Math.max(v, 0.01);\n\tlet sl;\n\tlet l;\n\n\tl = (2 - s) * v;\n\tconst lmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tconst h = hwb[0] / 360;\n\tlet wh = hwb[1] / 100;\n\tlet bl = hwb[2] / 100;\n\tconst ratio = wh + bl;\n\tlet f;\n\n\t// Wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\tconst i = Math.floor(6 * h);\n\tconst v = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tconst n = wh + f * (v - wh); // Linear interpolation\n\n\tlet r;\n\tlet g;\n\tlet b;\n\t/* eslint-disable max-statements-per-line,no-multi-spaces */\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\t/* eslint-enable max-statements-per-line,no-multi-spaces */\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tconst c = cmyk[0] / 100;\n\tconst m = cmyk[1] / 100;\n\tconst y = cmyk[2] / 100;\n\tconst k = cmyk[3] / 100;\n\n\tconst r = 1 - Math.min(1, c * (1 - k) + k);\n\tconst g = 1 - Math.min(1, m * (1 - k) + k);\n\tconst b = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tconst x = xyz[0] / 100;\n\tconst y = xyz[1] / 100;\n\tconst z = xyz[2] / 100;\n\tlet r;\n\tlet g;\n\tlet b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// Assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tlet x = xyz[0];\n\tlet y = xyz[1];\n\tlet z = xyz[2];\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);\n\n\tconst l = (116 * y) - 16;\n\tconst a = 500 * (x - y);\n\tconst b = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tconst l = lab[0];\n\tconst a = lab[1];\n\tconst b = lab[2];\n\tlet x;\n\tlet y;\n\tlet z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tconst y2 = y ** 3;\n\tconst x2 = x ** 3;\n\tconst z2 = z ** 3;\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tconst l = lab[0];\n\tconst a = lab[1];\n\tconst b = lab[2];\n\tlet h;\n\n\tconst hr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tconst c = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tconst l = lch[0];\n\tconst c = lch[1];\n\tconst h = lch[2];\n\n\tconst hr = h / 360 * 2 * Math.PI;\n\tconst a = c * Math.cos(hr);\n\tconst b = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args, saturation = null) {\n\tconst [r, g, b] = args;\n\tlet value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tlet ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// Optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tconst r = args[0];\n\tconst g = args[1];\n\tconst b = args[2];\n\n\t// We use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tconst ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tlet color = args % 10;\n\n\t// Handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tconst mult = (~~(args > 50) + 1) * 0.5;\n\tconst r = ((color & 1) * mult) * 255;\n\tconst g = (((color >> 1) & 1) * mult) * 255;\n\tconst b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// Handle greyscale\n\tif (args >= 232) {\n\t\tconst c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tlet rem;\n\tconst r = Math.floor(args / 36) / 5 * 255;\n\tconst g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tconst b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tconst integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tconst string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tconst match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tlet colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(char => {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tconst integer = parseInt(colorString, 16);\n\tconst r = (integer >> 16) & 0xFF;\n\tconst g = (integer >> 8) & 0xFF;\n\tconst b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\tconst max = Math.max(Math.max(r, g), b);\n\tconst min = Math.min(Math.min(r, g), b);\n\tconst chroma = (max - min);\n\tlet grayscale;\n\tlet hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tconst s = hsl[1] / 100;\n\tconst l = hsl[2] / 100;\n\n\tconst c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));\n\n\tlet f = 0;\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tconst s = hsv[1] / 100;\n\tconst v = hsv[2] / 100;\n\n\tconst c = s * v;\n\tlet f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tconst h = hcg[0] / 360;\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tconst pure = [0, 0, 0];\n\tconst hi = (h % 1) * 6;\n\tconst v = hi % 1;\n\tconst w = 1 - v;\n\tlet mg = 0;\n\n\t/* eslint-disable max-statements-per-line */\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\t/* eslint-enable max-statements-per-line */\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\n\tconst v = c + g * (1.0 - c);\n\tlet f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\n\tconst l = g * (1.0 - c) + 0.5 * c;\n\tlet s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\tconst v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tconst w = hwb[1] / 100;\n\tconst b = hwb[2] / 100;\n\tconst v = 1 - b;\n\tconst c = v - w;\n\tlet g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hsv = convert.gray.hsl;\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tconst val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tconst integer = (val << 16) + (val << 8) + val;\n\n\tconst string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tconst val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","const conversions = require('./conversions');\n\n/*\n\tThis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tconst graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tconst models = Object.keys(conversions);\n\n\tfor (let len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tconst graph = buildGraph();\n\tconst queue = [fromModel]; // Unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tconst current = queue.pop();\n\t\tconst adjacents = Object.keys(conversions[current]);\n\n\t\tfor (let len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tconst adjacent = adjacents[i];\n\t\t\tconst node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tconst path = [graph[toModel].parent, toModel];\n\tlet fn = conversions[graph[toModel].parent][toModel];\n\n\tlet cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tconst graph = deriveBFS(fromModel);\n\tconst conversion = {};\n\n\tconst models = Object.keys(graph);\n\tfor (let len = models.length, i = 0; i < len; i++) {\n\t\tconst toModel = models[i];\n\t\tconst node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// No possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","const conversions = require('./conversions');\nconst route = require('./route');\n\nconst convert = {};\n\nconst models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tconst wrappedFn = function (...args) {\n\t\tconst arg0 = args[0];\n\t\tif (arg0 === undefined || arg0 === null) {\n\t\t\treturn arg0;\n\t\t}\n\n\t\tif (arg0.length > 1) {\n\t\t\targs = arg0;\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// Preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tconst wrappedFn = function (...args) {\n\t\tconst arg0 = args[0];\n\n\t\tif (arg0 === undefined || arg0 === null) {\n\t\t\treturn arg0;\n\t\t}\n\n\t\tif (arg0.length > 1) {\n\t\t\targs = arg0;\n\t\t}\n\n\t\tconst result = fn(args);\n\n\t\t// We're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (let len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// Preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(fromModel => {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tconst routes = route(fromModel);\n\tconst routeModels = Object.keys(routes);\n\n\trouteModels.forEach(toModel => {\n\t\tconst fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","const colorString = require('color-string');\nconst convert = require('color-convert');\n\nconst skippedModels = [\n\t// To be honest, I don't really feel like keyword belongs in color convert, but eh.\n\t'keyword',\n\n\t// Gray conflicts with some method names, and has its own method defined.\n\t'gray',\n\n\t// Shouldn't really be in color-convert either...\n\t'hex',\n];\n\nconst hashedModelKeys = {};\nfor (const model of Object.keys(convert)) {\n\thashedModelKeys[[...convert[model].labels].sort().join('')] = model;\n}\n\nconst limiters = {};\n\nfunction Color(object, model) {\n\tif (!(this instanceof Color)) {\n\t\treturn new Color(object, model);\n\t}\n\n\tif (model && model in skippedModels) {\n\t\tmodel = null;\n\t}\n\n\tif (model && !(model in convert)) {\n\t\tthrow new Error('Unknown model: ' + model);\n\t}\n\n\tlet i;\n\tlet channels;\n\n\tif (object == null) { // eslint-disable-line no-eq-null,eqeqeq\n\t\tthis.model = 'rgb';\n\t\tthis.color = [0, 0, 0];\n\t\tthis.valpha = 1;\n\t} else if (object instanceof Color) {\n\t\tthis.model = object.model;\n\t\tthis.color = [...object.color];\n\t\tthis.valpha = object.valpha;\n\t} else if (typeof object === 'string') {\n\t\tconst result = colorString.get(object);\n\t\tif (result === null) {\n\t\t\tthrow new Error('Unable to parse color from string: ' + object);\n\t\t}\n\n\t\tthis.model = result.model;\n\t\tchannels = convert[this.model].channels;\n\t\tthis.color = result.value.slice(0, channels);\n\t\tthis.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;\n\t} else if (object.length > 0) {\n\t\tthis.model = model || 'rgb';\n\t\tchannels = convert[this.model].channels;\n\t\tconst newArray = Array.prototype.slice.call(object, 0, channels);\n\t\tthis.color = zeroArray(newArray, channels);\n\t\tthis.valpha = typeof object[channels] === 'number' ? object[channels] : 1;\n\t} else if (typeof object === 'number') {\n\t\t// This is always RGB - can be converted later on.\n\t\tthis.model = 'rgb';\n\t\tthis.color = [\n\t\t\t(object >> 16) & 0xFF,\n\t\t\t(object >> 8) & 0xFF,\n\t\t\tobject & 0xFF,\n\t\t];\n\t\tthis.valpha = 1;\n\t} else {\n\t\tthis.valpha = 1;\n\n\t\tconst keys = Object.keys(object);\n\t\tif ('alpha' in object) {\n\t\t\tkeys.splice(keys.indexOf('alpha'), 1);\n\t\t\tthis.valpha = typeof object.alpha === 'number' ? object.alpha : 0;\n\t\t}\n\n\t\tconst hashedKeys = keys.sort().join('');\n\t\tif (!(hashedKeys in hashedModelKeys)) {\n\t\t\tthrow new Error('Unable to parse color from object: ' + JSON.stringify(object));\n\t\t}\n\n\t\tthis.model = hashedModelKeys[hashedKeys];\n\n\t\tconst {labels} = convert[this.model];\n\t\tconst color = [];\n\t\tfor (i = 0; i < labels.length; i++) {\n\t\t\tcolor.push(object[labels[i]]);\n\t\t}\n\n\t\tthis.color = zeroArray(color);\n\t}\n\n\t// Perform limitations (clamping, etc.)\n\tif (limiters[this.model]) {\n\t\tchannels = convert[this.model].channels;\n\t\tfor (i = 0; i < channels; i++) {\n\t\t\tconst limit = limiters[this.model][i];\n\t\t\tif (limit) {\n\t\t\t\tthis.color[i] = limit(this.color[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\tthis.valpha = Math.max(0, Math.min(1, this.valpha));\n\n\tif (Object.freeze) {\n\t\tObject.freeze(this);\n\t}\n}\n\nColor.prototype = {\n\ttoString() {\n\t\treturn this.string();\n\t},\n\n\ttoJSON() {\n\t\treturn this[this.model]();\n\t},\n\n\tstring(places) {\n\t\tlet self = this.model in colorString.to ? this : this.rgb();\n\t\tself = self.round(typeof places === 'number' ? places : 1);\n\t\tconst args = self.valpha === 1 ? self.color : [...self.color, this.valpha];\n\t\treturn colorString.to[self.model](args);\n\t},\n\n\tpercentString(places) {\n\t\tconst self = this.rgb().round(typeof places === 'number' ? places : 1);\n\t\tconst args = self.valpha === 1 ? self.color : [...self.color, this.valpha];\n\t\treturn colorString.to.rgb.percent(args);\n\t},\n\n\tarray() {\n\t\treturn this.valpha === 1 ? [...this.color] : [...this.color, this.valpha];\n\t},\n\n\tobject() {\n\t\tconst result = {};\n\t\tconst {channels} = convert[this.model];\n\t\tconst {labels} = convert[this.model];\n\n\t\tfor (let i = 0; i < channels; i++) {\n\t\t\tresult[labels[i]] = this.color[i];\n\t\t}\n\n\t\tif (this.valpha !== 1) {\n\t\t\tresult.alpha = this.valpha;\n\t\t}\n\n\t\treturn result;\n\t},\n\n\tunitArray() {\n\t\tconst rgb = this.rgb().color;\n\t\trgb[0] /= 255;\n\t\trgb[1] /= 255;\n\t\trgb[2] /= 255;\n\n\t\tif (this.valpha !== 1) {\n\t\t\trgb.push(this.valpha);\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tunitObject() {\n\t\tconst rgb = this.rgb().object();\n\t\trgb.r /= 255;\n\t\trgb.g /= 255;\n\t\trgb.b /= 255;\n\n\t\tif (this.valpha !== 1) {\n\t\t\trgb.alpha = this.valpha;\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tround(places) {\n\t\tplaces = Math.max(places || 0, 0);\n\t\treturn new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model);\n\t},\n\n\talpha(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color([...this.color, Math.max(0, Math.min(1, value))], this.model);\n\t\t}\n\n\t\treturn this.valpha;\n\t},\n\n\t// Rgb\n\tred: getset('rgb', 0, maxfn(255)),\n\tgreen: getset('rgb', 1, maxfn(255)),\n\tblue: getset('rgb', 2, maxfn(255)),\n\n\thue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360),\n\n\tsaturationl: getset('hsl', 1, maxfn(100)),\n\tlightness: getset('hsl', 2, maxfn(100)),\n\n\tsaturationv: getset('hsv', 1, maxfn(100)),\n\tvalue: getset('hsv', 2, maxfn(100)),\n\n\tchroma: getset('hcg', 1, maxfn(100)),\n\tgray: getset('hcg', 2, maxfn(100)),\n\n\twhite: getset('hwb', 1, maxfn(100)),\n\twblack: getset('hwb', 2, maxfn(100)),\n\n\tcyan: getset('cmyk', 0, maxfn(100)),\n\tmagenta: getset('cmyk', 1, maxfn(100)),\n\tyellow: getset('cmyk', 2, maxfn(100)),\n\tblack: getset('cmyk', 3, maxfn(100)),\n\n\tx: getset('xyz', 0, maxfn(95.047)),\n\ty: getset('xyz', 1, maxfn(100)),\n\tz: getset('xyz', 2, maxfn(108.833)),\n\n\tl: getset('lab', 0, maxfn(100)),\n\ta: getset('lab', 1),\n\tb: getset('lab', 2),\n\n\tkeyword(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color(value);\n\t\t}\n\n\t\treturn convert[this.model].keyword(this.color);\n\t},\n\n\thex(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color(value);\n\t\t}\n\n\t\treturn colorString.to.hex(this.rgb().round().color);\n\t},\n\n\thexa(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color(value);\n\t\t}\n\n\t\tconst rgbArray = this.rgb().round().color;\n\n\t\tlet alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();\n\t\tif (alphaHex.length === 1) {\n\t\t\talphaHex = '0' + alphaHex;\n\t\t}\n\n\t\treturn colorString.to.hex(rgbArray) + alphaHex;\n\t},\n\n\trgbNumber() {\n\t\tconst rgb = this.rgb().color;\n\t\treturn ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);\n\t},\n\n\tluminosity() {\n\t\t// http://www.w3.org/TR/WCAG20/#relativeluminancedef\n\t\tconst rgb = this.rgb().color;\n\n\t\tconst lum = [];\n\t\tfor (const [i, element] of rgb.entries()) {\n\t\t\tconst chan = element / 255;\n\t\t\tlum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;\n\t\t}\n\n\t\treturn 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];\n\t},\n\n\tcontrast(color2) {\n\t\t// http://www.w3.org/TR/WCAG20/#contrast-ratiodef\n\t\tconst lum1 = this.luminosity();\n\t\tconst lum2 = color2.luminosity();\n\n\t\tif (lum1 > lum2) {\n\t\t\treturn (lum1 + 0.05) / (lum2 + 0.05);\n\t\t}\n\n\t\treturn (lum2 + 0.05) / (lum1 + 0.05);\n\t},\n\n\tlevel(color2) {\n\t\t// https://www.w3.org/TR/WCAG/#contrast-enhanced\n\t\tconst contrastRatio = this.contrast(color2);\n\t\tif (contrastRatio >= 7) {\n\t\t\treturn 'AAA';\n\t\t}\n\n\t\treturn (contrastRatio >= 4.5) ? 'AA' : '';\n\t},\n\n\tisDark() {\n\t\t// YIQ equation from http://24ways.org/2010/calculating-color-contrast\n\t\tconst rgb = this.rgb().color;\n\t\tconst yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000;\n\t\treturn yiq < 128;\n\t},\n\n\tisLight() {\n\t\treturn !this.isDark();\n\t},\n\n\tnegate() {\n\t\tconst rgb = this.rgb();\n\t\tfor (let i = 0; i < 3; i++) {\n\t\t\trgb.color[i] = 255 - rgb.color[i];\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tlighten(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[2] += hsl.color[2] * ratio;\n\t\treturn hsl;\n\t},\n\n\tdarken(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[2] -= hsl.color[2] * ratio;\n\t\treturn hsl;\n\t},\n\n\tsaturate(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[1] += hsl.color[1] * ratio;\n\t\treturn hsl;\n\t},\n\n\tdesaturate(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[1] -= hsl.color[1] * ratio;\n\t\treturn hsl;\n\t},\n\n\twhiten(ratio) {\n\t\tconst hwb = this.hwb();\n\t\thwb.color[1] += hwb.color[1] * ratio;\n\t\treturn hwb;\n\t},\n\n\tblacken(ratio) {\n\t\tconst hwb = this.hwb();\n\t\thwb.color[2] += hwb.color[2] * ratio;\n\t\treturn hwb;\n\t},\n\n\tgrayscale() {\n\t\t// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale\n\t\tconst rgb = this.rgb().color;\n\t\tconst value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;\n\t\treturn Color.rgb(value, value, value);\n\t},\n\n\tfade(ratio) {\n\t\treturn this.alpha(this.valpha - (this.valpha * ratio));\n\t},\n\n\topaquer(ratio) {\n\t\treturn this.alpha(this.valpha + (this.valpha * ratio));\n\t},\n\n\trotate(degrees) {\n\t\tconst hsl = this.hsl();\n\t\tlet hue = hsl.color[0];\n\t\thue = (hue + degrees) % 360;\n\t\thue = hue < 0 ? 360 + hue : hue;\n\t\thsl.color[0] = hue;\n\t\treturn hsl;\n\t},\n\n\tmix(mixinColor, weight) {\n\t\t// Ported from sass implementation in C\n\t\t// https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209\n\t\tif (!mixinColor || !mixinColor.rgb) {\n\t\t\tthrow new Error('Argument to \"mix\" was not a Color instance, but rather an instance of ' + typeof mixinColor);\n\t\t}\n\n\t\tconst color1 = mixinColor.rgb();\n\t\tconst color2 = this.rgb();\n\t\tconst p = weight === undefined ? 0.5 : weight;\n\n\t\tconst w = 2 * p - 1;\n\t\tconst a = color1.alpha() - color2.alpha();\n\n\t\tconst w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2;\n\t\tconst w2 = 1 - w1;\n\n\t\treturn Color.rgb(\n\t\t\tw1 * color1.red() + w2 * color2.red(),\n\t\t\tw1 * color1.green() + w2 * color2.green(),\n\t\t\tw1 * color1.blue() + w2 * color2.blue(),\n\t\t\tcolor1.alpha() * p + color2.alpha() * (1 - p));\n\t},\n};\n\n// Model conversion methods and static constructors\nfor (const model of Object.keys(convert)) {\n\tif (skippedModels.includes(model)) {\n\t\tcontinue;\n\t}\n\n\tconst {channels} = convert[model];\n\n\t// Conversion methods\n\tColor.prototype[model] = function (...args) {\n\t\tif (this.model === model) {\n\t\t\treturn new Color(this);\n\t\t}\n\n\t\tif (args.length > 0) {\n\t\t\treturn new Color(args, model);\n\t\t}\n\n\t\treturn new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model);\n\t};\n\n\t// 'static' construction methods\n\tColor[model] = function (...args) {\n\t\tlet color = args[0];\n\t\tif (typeof color === 'number') {\n\t\t\tcolor = zeroArray(args, channels);\n\t\t}\n\n\t\treturn new Color(color, model);\n\t};\n}\n\nfunction roundTo(number, places) {\n\treturn Number(number.toFixed(places));\n}\n\nfunction roundToPlace(places) {\n\treturn function (number) {\n\t\treturn roundTo(number, places);\n\t};\n}\n\nfunction getset(model, channel, modifier) {\n\tmodel = Array.isArray(model) ? model : [model];\n\n\tfor (const m of model) {\n\t\t(limiters[m] || (limiters[m] = []))[channel] = modifier;\n\t}\n\n\tmodel = model[0];\n\n\treturn function (value) {\n\t\tlet result;\n\n\t\tif (value !== undefined) {\n\t\t\tif (modifier) {\n\t\t\t\tvalue = modifier(value);\n\t\t\t}\n\n\t\t\tresult = this[model]();\n\t\t\tresult.color[channel] = value;\n\t\t\treturn result;\n\t\t}\n\n\t\tresult = this[model]().color[channel];\n\t\tif (modifier) {\n\t\t\tresult = modifier(result);\n\t\t}\n\n\t\treturn result;\n\t};\n}\n\nfunction maxfn(max) {\n\treturn function (v) {\n\t\treturn Math.max(0, Math.min(max, v));\n\t};\n}\n\nfunction assertArray(value) {\n\treturn Array.isArray(value) ? value : [value];\n}\n\nfunction zeroArray(array, length) {\n\tfor (let i = 0; i < length; i++) {\n\t\tif (typeof array[i] !== 'number') {\n\t\t\tarray[i] = 0;\n\t\t}\n\t}\n\n\treturn array;\n}\n\nmodule.exports = Color;\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst color = require('color');\nconst is = require('./is');\nconst sharp = require('./sharp');\n\n/**\n * Justication alignment\n * @member\n * @private\n */\nconst align = {\n left: 'low',\n center: 'centre',\n centre: 'centre',\n right: 'high'\n};\n\n/**\n * Extract input options, if any, from an object.\n * @private\n */\nfunction _inputOptionsFromObject (obj) {\n const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj;\n return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined)\n ? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd }\n : undefined;\n}\n\n/**\n * Create Object containing input and input-related options.\n * @private\n */\nfunction _createInputDescriptor (input, inputOptions, containerOptions) {\n const inputDescriptor = {\n failOn: 'warning',\n limitInputPixels: Math.pow(0x3FFF, 2),\n ignoreIcc: false,\n unlimited: false,\n sequentialRead: true\n };\n if (is.string(input)) {\n // filesystem\n inputDescriptor.file = input;\n } else if (is.buffer(input)) {\n // Buffer\n if (input.length === 0) {\n throw Error('Input Buffer is empty');\n }\n inputDescriptor.buffer = input;\n } else if (is.arrayBuffer(input)) {\n if (input.byteLength === 0) {\n throw Error('Input bit Array is empty');\n }\n inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength);\n } else if (is.typedArray(input)) {\n if (input.length === 0) {\n throw Error('Input Bit Array is empty');\n }\n inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);\n } else if (is.plainObject(input) && !is.defined(inputOptions)) {\n // Plain Object descriptor, e.g. create\n inputOptions = input;\n if (_inputOptionsFromObject(inputOptions)) {\n // Stream with options\n inputDescriptor.buffer = [];\n }\n } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {\n // Stream without options\n inputDescriptor.buffer = [];\n } else {\n throw new Error(`Unsupported input '${input}' of type ${typeof input}${\n is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''\n }`);\n }\n if (is.object(inputOptions)) {\n // Deprecated: failOnError\n if (is.defined(inputOptions.failOnError)) {\n if (is.bool(inputOptions.failOnError)) {\n inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';\n } else {\n throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError);\n }\n }\n // failOn\n if (is.defined(inputOptions.failOn)) {\n if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) {\n inputDescriptor.failOn = inputOptions.failOn;\n } else {\n throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);\n }\n }\n // Density\n if (is.defined(inputOptions.density)) {\n if (is.inRange(inputOptions.density, 1, 100000)) {\n inputDescriptor.density = inputOptions.density;\n } else {\n throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density);\n }\n }\n // Ignore embeddded ICC profile\n if (is.defined(inputOptions.ignoreIcc)) {\n if (is.bool(inputOptions.ignoreIcc)) {\n inputDescriptor.ignoreIcc = inputOptions.ignoreIcc;\n } else {\n throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc);\n }\n }\n // limitInputPixels\n if (is.defined(inputOptions.limitInputPixels)) {\n if (is.bool(inputOptions.limitInputPixels)) {\n inputDescriptor.limitInputPixels = inputOptions.limitInputPixels\n ? Math.pow(0x3FFF, 2)\n : 0;\n } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {\n inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;\n } else {\n throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);\n }\n }\n // unlimited\n if (is.defined(inputOptions.unlimited)) {\n if (is.bool(inputOptions.unlimited)) {\n inputDescriptor.unlimited = inputOptions.unlimited;\n } else {\n throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited);\n }\n }\n // sequentialRead\n if (is.defined(inputOptions.sequentialRead)) {\n if (is.bool(inputOptions.sequentialRead)) {\n inputDescriptor.sequentialRead = inputOptions.sequentialRead;\n } else {\n throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead);\n }\n }\n // Raw pixel input\n if (is.defined(inputOptions.raw)) {\n if (\n is.object(inputOptions.raw) &&\n is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 &&\n is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 &&\n is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4)\n ) {\n inputDescriptor.rawWidth = inputOptions.raw.width;\n inputDescriptor.rawHeight = inputOptions.raw.height;\n inputDescriptor.rawChannels = inputOptions.raw.channels;\n inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;\n\n switch (input.constructor) {\n case Uint8Array:\n case Uint8ClampedArray:\n inputDescriptor.rawDepth = 'uchar';\n break;\n case Int8Array:\n inputDescriptor.rawDepth = 'char';\n break;\n case Uint16Array:\n inputDescriptor.rawDepth = 'ushort';\n break;\n case Int16Array:\n inputDescriptor.rawDepth = 'short';\n break;\n case Uint32Array:\n inputDescriptor.rawDepth = 'uint';\n break;\n case Int32Array:\n inputDescriptor.rawDepth = 'int';\n break;\n case Float32Array:\n inputDescriptor.rawDepth = 'float';\n break;\n case Float64Array:\n inputDescriptor.rawDepth = 'double';\n break;\n default:\n inputDescriptor.rawDepth = 'uchar';\n break;\n }\n } else {\n throw new Error('Expected width, height and channels for raw pixel input');\n }\n }\n // Multi-page input (GIF, TIFF, PDF)\n if (is.defined(inputOptions.animated)) {\n if (is.bool(inputOptions.animated)) {\n inputDescriptor.pages = inputOptions.animated ? -1 : 1;\n } else {\n throw is.invalidParameterError('animated', 'boolean', inputOptions.animated);\n }\n }\n if (is.defined(inputOptions.pages)) {\n if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) {\n inputDescriptor.pages = inputOptions.pages;\n } else {\n throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages);\n }\n }\n if (is.defined(inputOptions.page)) {\n if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) {\n inputDescriptor.page = inputOptions.page;\n } else {\n throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);\n }\n }\n // Multi-level input (OpenSlide)\n if (is.defined(inputOptions.level)) {\n if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {\n inputDescriptor.level = inputOptions.level;\n } else {\n throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);\n }\n }\n // Sub Image File Directory (TIFF)\n if (is.defined(inputOptions.subifd)) {\n if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {\n inputDescriptor.subifd = inputOptions.subifd;\n } else {\n throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);\n }\n }\n // Create new image\n if (is.defined(inputOptions.create)) {\n if (\n is.object(inputOptions.create) &&\n is.integer(inputOptions.create.width) && inputOptions.create.width > 0 &&\n is.integer(inputOptions.create.height) && inputOptions.create.height > 0 &&\n is.integer(inputOptions.create.channels)\n ) {\n inputDescriptor.createWidth = inputOptions.create.width;\n inputDescriptor.createHeight = inputOptions.create.height;\n inputDescriptor.createChannels = inputOptions.create.channels;\n // Noise\n if (is.defined(inputOptions.create.noise)) {\n if (!is.object(inputOptions.create.noise)) {\n throw new Error('Expected noise to be an object');\n }\n if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) {\n throw new Error('Only gaussian noise is supported at the moment');\n }\n if (!is.inRange(inputOptions.create.channels, 1, 4)) {\n throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);\n }\n inputDescriptor.createNoiseType = inputOptions.create.noise.type;\n if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {\n inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;\n } else {\n throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);\n }\n if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {\n inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;\n } else {\n throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);\n }\n } else if (is.defined(inputOptions.create.background)) {\n if (!is.inRange(inputOptions.create.channels, 3, 4)) {\n throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);\n }\n const background = color(inputOptions.create.background);\n inputDescriptor.createBackground = [\n background.red(),\n background.green(),\n background.blue(),\n Math.round(background.alpha() * 255)\n ];\n } else {\n throw new Error('Expected valid noise or background to create a new input image');\n }\n delete inputDescriptor.buffer;\n } else {\n throw new Error('Expected valid width, height and channels to create a new input image');\n }\n }\n // Create a new image with text\n if (is.defined(inputOptions.text)) {\n if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) {\n inputDescriptor.textValue = inputOptions.text.text;\n if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) {\n throw new Error('Expected only one of dpi or height');\n }\n if (is.defined(inputOptions.text.font)) {\n if (is.string(inputOptions.text.font)) {\n inputDescriptor.textFont = inputOptions.text.font;\n } else {\n throw is.invalidParameterError('text.font', 'string', inputOptions.text.font);\n }\n }\n if (is.defined(inputOptions.text.fontfile)) {\n if (is.string(inputOptions.text.fontfile)) {\n inputDescriptor.textFontfile = inputOptions.text.fontfile;\n } else {\n throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile);\n }\n }\n if (is.defined(inputOptions.text.width)) {\n if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {\n inputDescriptor.textWidth = inputOptions.text.width;\n } else {\n throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);\n }\n }\n if (is.defined(inputOptions.text.height)) {\n if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {\n inputDescriptor.textHeight = inputOptions.text.height;\n } else {\n throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);\n }\n }\n if (is.defined(inputOptions.text.align)) {\n if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) {\n inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align];\n } else {\n throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align);\n }\n }\n if (is.defined(inputOptions.text.justify)) {\n if (is.bool(inputOptions.text.justify)) {\n inputDescriptor.textJustify = inputOptions.text.justify;\n } else {\n throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify);\n }\n }\n if (is.defined(inputOptions.text.dpi)) {\n if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {\n inputDescriptor.textDpi = inputOptions.text.dpi;\n } else {\n throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);\n }\n }\n if (is.defined(inputOptions.text.rgba)) {\n if (is.bool(inputOptions.text.rgba)) {\n inputDescriptor.textRgba = inputOptions.text.rgba;\n } else {\n throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba);\n }\n }\n if (is.defined(inputOptions.text.spacing)) {\n if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {\n inputDescriptor.textSpacing = inputOptions.text.spacing;\n } else {\n throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);\n }\n }\n if (is.defined(inputOptions.text.wrap)) {\n if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {\n inputDescriptor.textWrap = inputOptions.text.wrap;\n } else {\n throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);\n }\n }\n delete inputDescriptor.buffer;\n } else {\n throw new Error('Expected a valid string to create an image with text.');\n }\n }\n } else if (is.defined(inputOptions)) {\n throw new Error('Invalid input options ' + inputOptions);\n }\n return inputDescriptor;\n}\n\n/**\n * Handle incoming Buffer chunk on Writable Stream.\n * @private\n * @param {Buffer} chunk\n * @param {string} encoding - unused\n * @param {Function} callback\n */\nfunction _write (chunk, encoding, callback) {\n /* istanbul ignore else */\n if (Array.isArray(this.options.input.buffer)) {\n /* istanbul ignore else */\n if (is.buffer(chunk)) {\n if (this.options.input.buffer.length === 0) {\n this.on('finish', () => {\n this.streamInFinished = true;\n });\n }\n this.options.input.buffer.push(chunk);\n callback();\n } else {\n callback(new Error('Non-Buffer data on Writable Stream'));\n }\n } else {\n callback(new Error('Unexpected data on Writable Stream'));\n }\n}\n\n/**\n * Flattens the array of chunks accumulated in input.buffer.\n * @private\n */\nfunction _flattenBufferIn () {\n if (this._isStreamInput()) {\n this.options.input.buffer = Buffer.concat(this.options.input.buffer);\n }\n}\n\n/**\n * Are we expecting Stream-based input?\n * @private\n * @returns {boolean}\n */\nfunction _isStreamInput () {\n return Array.isArray(this.options.input.buffer);\n}\n\n/**\n * Fast access to (uncached) image metadata without decoding any compressed pixel data.\n *\n * This is read from the header of the input image.\n * It does not take into consideration any operations to be applied to the output image,\n * such as resize or rotate.\n *\n * Dimensions in the response will respect the `page` and `pages` properties of the\n * {@link /api-constructor#parameters|constructor parameters}.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`\n * - `size`: Total size of image in bytes, for Stream and Buffer input only\n * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)\n * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)\n * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation)\n * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK\n * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat)\n * - `density`: Number of pixels per inch (DPI), if present\n * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK\n * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan\n * - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP\n * - `pageHeight`: Number of pixels high each page in a multi-page image will be.\n * - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG).\n * - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.\n * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers.\n * - `pagePrimary`: Number of the primary page in a HEIF image\n * - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide\n * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image\n * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value\n * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)\n * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present\n * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile\n * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel\n * - `orientation`: Number value of the EXIF Orientation header, if present\n * - `exif`: Buffer containing raw EXIF data, if present\n * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present\n * - `iptc`: Buffer containing raw IPTC data, if present\n * - `xmp`: Buffer containing raw XMP data, if present\n * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present\n * - `formatMagick`: String containing format for images loaded via *magick\n * - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.\n *\n * @example\n * const metadata = await sharp(input).metadata();\n *\n * @example\n * const image = sharp(inputJpg);\n * image\n * .metadata()\n * .then(function(metadata) {\n * return image\n * .resize(Math.round(metadata.width / 2))\n * .webp()\n * .toBuffer();\n * })\n * .then(function(data) {\n * // data contains a WebP image half the width and height of the original JPEG\n * });\n *\n * @example\n * // Based on EXIF rotation metadata, get the right-side-up width and height:\n *\n * const size = getNormalSize(await sharp(input).metadata());\n *\n * function getNormalSize({ width, height, orientation }) {\n * return (orientation || 0) >= 5\n * ? { width: height, height: width }\n * : { width, height };\n * }\n *\n * @param {Function} [callback] - called with the arguments `(err, metadata)`\n * @returns {Promise<Object>|Sharp}\n */\nfunction metadata (callback) {\n const stack = Error();\n if (is.fn(callback)) {\n if (this._isStreamInput()) {\n this.on('finish', () => {\n this._flattenBufferIn();\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, metadata);\n }\n });\n });\n } else {\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, metadata);\n }\n });\n }\n return this;\n } else {\n if (this._isStreamInput()) {\n return new Promise((resolve, reject) => {\n const finished = () => {\n this._flattenBufferIn();\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(metadata);\n }\n });\n };\n if (this.writableFinished) {\n finished();\n } else {\n this.once('finish', finished);\n }\n });\n } else {\n return new Promise((resolve, reject) => {\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(metadata);\n }\n });\n });\n }\n }\n}\n\n/**\n * Access to pixel-derived image statistics for every channel in the image.\n * A `Promise` is returned when `callback` is not provided.\n *\n * - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains\n * - `min` (minimum value in the channel)\n * - `max` (maximum value in the channel)\n * - `sum` (sum of all values in a channel)\n * - `squaresSum` (sum of squared values in a channel)\n * - `mean` (mean of the values in a channel)\n * - `stdev` (standard deviation for the values in a channel)\n * - `minX` (x-coordinate of one of the pixel where the minimum lies)\n * - `minY` (y-coordinate of one of the pixel where the minimum lies)\n * - `maxX` (x-coordinate of one of the pixel where the maximum lies)\n * - `maxY` (y-coordinate of one of the pixel where the maximum lies)\n * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.\n * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.\n * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.\n * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.\n *\n * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be\n * written to a buffer in order to run `stats` on the result (see third example).\n *\n * @example\n * const image = sharp(inputJpg);\n * image\n * .stats()\n * .then(function(stats) {\n * // stats contains the channel-wise statistics array and the isOpaque value\n * });\n *\n * @example\n * const { entropy, sharpness, dominant } = await sharp(input).stats();\n * const { r, g, b } = dominant;\n *\n * @example\n * const image = sharp(input);\n * // store intermediate result\n * const part = await image.extract(region).toBuffer();\n * // create new instance to obtain statistics of extracted region\n * const stats = await sharp(part).stats();\n *\n * @param {Function} [callback] - called with the arguments `(err, stats)`\n * @returns {Promise<Object>}\n */\nfunction stats (callback) {\n const stack = Error();\n if (is.fn(callback)) {\n if (this._isStreamInput()) {\n this.on('finish', () => {\n this._flattenBufferIn();\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, stats);\n }\n });\n });\n } else {\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, stats);\n }\n });\n }\n return this;\n } else {\n if (this._isStreamInput()) {\n return new Promise((resolve, reject) => {\n this.on('finish', function () {\n this._flattenBufferIn();\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(stats);\n }\n });\n });\n });\n } else {\n return new Promise((resolve, reject) => {\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(stats);\n }\n });\n });\n }\n }\n}\n\n/**\n * Decorate the Sharp prototype with input-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Private\n _inputOptionsFromObject,\n _createInputDescriptor,\n _write,\n _flattenBufferIn,\n _isStreamInput,\n // Public\n metadata,\n stats\n });\n // Class attributes\n Sharp.align = align;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst is = require('./is');\n\n/**\n * Weighting to apply when using contain/cover fit.\n * @member\n * @private\n */\nconst gravity = {\n center: 0,\n centre: 0,\n north: 1,\n east: 2,\n south: 3,\n west: 4,\n northeast: 5,\n southeast: 6,\n southwest: 7,\n northwest: 8\n};\n\n/**\n * Position to apply when using contain/cover fit.\n * @member\n * @private\n */\nconst position = {\n top: 1,\n right: 2,\n bottom: 3,\n left: 4,\n 'right top': 5,\n 'right bottom': 6,\n 'left bottom': 7,\n 'left top': 8\n};\n\n/**\n * How to extend the image.\n * @member\n * @private\n */\nconst extendWith = {\n background: 'background',\n copy: 'copy',\n repeat: 'repeat',\n mirror: 'mirror'\n};\n\n/**\n * Strategies for automagic cover behaviour.\n * @member\n * @private\n */\nconst strategy = {\n entropy: 16,\n attention: 17\n};\n\n/**\n * Reduction kernels.\n * @member\n * @private\n */\nconst kernel = {\n nearest: 'nearest',\n linear: 'linear',\n cubic: 'cubic',\n mitchell: 'mitchell',\n lanczos2: 'lanczos2',\n lanczos3: 'lanczos3'\n};\n\n/**\n * Methods by which an image can be resized to fit the provided dimensions.\n * @member\n * @private\n */\nconst fit = {\n contain: 'contain',\n cover: 'cover',\n fill: 'fill',\n inside: 'inside',\n outside: 'outside'\n};\n\n/**\n * Map external fit property to internal canvas property.\n * @member\n * @private\n */\nconst mapFitToCanvas = {\n contain: 'embed',\n cover: 'crop',\n fill: 'ignore_aspect',\n inside: 'max',\n outside: 'min'\n};\n\n/**\n * @private\n */\nfunction isRotationExpected (options) {\n return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;\n}\n\n/**\n * @private\n */\nfunction isResizeExpected (options) {\n return options.width !== -1 || options.height !== -1;\n}\n\n/**\n * Resize image to `width`, `height` or `width x height`.\n *\n * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:\n * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.\n * - `contain`: Preserving aspect ratio, contain within both provided dimensions using \"letterboxing\" where necessary.\n * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.\n * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.\n * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.\n *\n * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.\n *\n * <img alt=\"Examples of various values for the fit property when resizing\" width=\"100%\" style=\"aspect-ratio: 998/243\" src=\"https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg\">\n *\n * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:\n * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.\n * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.\n * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.\n *\n * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.\n *\n * The strategy-based approach initially resizes so one dimension is at its target length\n * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.\n * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).\n * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.\n *\n * Possible downsizing kernels are:\n * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).\n * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).\n * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).\n * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).\n * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.\n * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).\n *\n * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.\n * Downsampling kernels without a matching upsampling interpolator map to `cubic`.\n *\n * Only one resize can occur per pipeline.\n * Previous calls to `resize` in the same pipeline will be ignored.\n *\n * @example\n * sharp(input)\n * .resize({ width: 100 })\n * .toBuffer()\n * .then(data => {\n * // 100 pixels wide, auto-scaled height\n * });\n *\n * @example\n * sharp(input)\n * .resize({ height: 100 })\n * .toBuffer()\n * .then(data => {\n * // 100 pixels high, auto-scaled width\n * });\n *\n * @example\n * sharp(input)\n * .resize(200, 300, {\n * kernel: sharp.kernel.nearest,\n * fit: 'contain',\n * position: 'right top',\n * background: { r: 255, g: 255, b: 255, alpha: 0.5 }\n * })\n * .toFile('output.png')\n * .then(() => {\n * // output.png is a 200 pixels wide and 300 pixels high image\n * // containing a nearest-neighbour scaled version\n * // contained within the north-east corner of a semi-transparent white canvas\n * });\n *\n * @example\n * const transformer = sharp()\n * .resize({\n * width: 200,\n * height: 200,\n * fit: sharp.fit.cover,\n * position: sharp.strategy.entropy\n * });\n * // Read image data from readableStream\n * // Write 200px square auto-cropped image data to writableStream\n * readableStream\n * .pipe(transformer)\n * .pipe(writableStream);\n *\n * @example\n * sharp(input)\n * .resize(200, 200, {\n * fit: sharp.fit.inside,\n * withoutEnlargement: true\n * })\n * .toFormat('jpeg')\n * .toBuffer()\n * .then(function(outputBuffer) {\n * // outputBuffer contains JPEG image data\n * // no wider and no higher than 200 pixels\n * // and no larger than the input image\n * });\n *\n * @example\n * sharp(input)\n * .resize(200, 200, {\n * fit: sharp.fit.outside,\n * withoutReduction: true\n * })\n * .toFormat('jpeg')\n * .toBuffer()\n * .then(function(outputBuffer) {\n * // outputBuffer contains JPEG image data\n * // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio\n * // and no smaller than the input image\n * });\n *\n * @example\n * const scaleByHalf = await sharp(input)\n * .metadata()\n * .then(({ width }) => sharp(input)\n * .resize(Math.round(width * 0.5))\n * .toBuffer()\n * );\n *\n * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.\n * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.\n * @param {Object} [options]\n * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.\n * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority.\n * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`.\n * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.\n * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.\n * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.\n * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.\n * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.\n * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction resize (widthOrOptions, height, options) {\n if (isResizeExpected(this.options)) {\n this.options.debuglog('ignoring previous resize options');\n }\n if (this.options.widthPost !== -1) {\n this.options.debuglog('operation order will be: extract, resize, extract');\n }\n if (is.defined(widthOrOptions)) {\n if (is.object(widthOrOptions) && !is.defined(options)) {\n options = widthOrOptions;\n } else if (is.integer(widthOrOptions) && widthOrOptions > 0) {\n this.options.width = widthOrOptions;\n } else {\n throw is.invalidParameterError('width', 'positive integer', widthOrOptions);\n }\n } else {\n this.options.width = -1;\n }\n if (is.defined(height)) {\n if (is.integer(height) && height > 0) {\n this.options.height = height;\n } else {\n throw is.invalidParameterError('height', 'positive integer', height);\n }\n } else {\n this.options.height = -1;\n }\n if (is.object(options)) {\n // Width\n if (is.defined(options.width)) {\n if (is.integer(options.width) && options.width > 0) {\n this.options.width = options.width;\n } else {\n throw is.invalidParameterError('width', 'positive integer', options.width);\n }\n }\n // Height\n if (is.defined(options.height)) {\n if (is.integer(options.height) && options.height > 0) {\n this.options.height = options.height;\n } else {\n throw is.invalidParameterError('height', 'positive integer', options.height);\n }\n }\n // Fit\n if (is.defined(options.fit)) {\n const canvas = mapFitToCanvas[options.fit];\n if (is.string(canvas)) {\n this.options.canvas = canvas;\n } else {\n throw is.invalidParameterError('fit', 'valid fit', options.fit);\n }\n }\n // Position\n if (is.defined(options.position)) {\n const pos = is.integer(options.position)\n ? options.position\n : strategy[options.position] || position[options.position] || gravity[options.position];\n if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) {\n this.options.position = pos;\n } else {\n throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position);\n }\n }\n // Background\n this._setBackgroundColourOption('resizeBackground', options.background);\n // Kernel\n if (is.defined(options.kernel)) {\n if (is.string(kernel[options.kernel])) {\n this.options.kernel = kernel[options.kernel];\n } else {\n throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel);\n }\n }\n // Without enlargement\n if (is.defined(options.withoutEnlargement)) {\n this._setBooleanOption('withoutEnlargement', options.withoutEnlargement);\n }\n // Without reduction\n if (is.defined(options.withoutReduction)) {\n this._setBooleanOption('withoutReduction', options.withoutReduction);\n }\n // Shrink on load\n if (is.defined(options.fastShrinkOnLoad)) {\n this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);\n }\n }\n if (isRotationExpected(this.options) && isResizeExpected(this.options)) {\n this.options.rotateBeforePreExtract = true;\n }\n return this;\n}\n\n/**\n * Extend / pad / extrude one or more edges of the image with either\n * the provided background colour or pixels derived from the image.\n * This operation will always occur after resizing and extraction, if any.\n *\n * @example\n * // Resize to 140 pixels wide, then add 10 transparent pixels\n * // to the top, left and right edges and 20 to the bottom edge\n * sharp(input)\n * .resize(140)\n * .extend({\n * top: 10,\n * bottom: 20,\n * left: 10,\n * right: 10,\n * background: { r: 0, g: 0, b: 0, alpha: 0 }\n * })\n * ...\n *\n* @example\n * // Add a row of 10 red pixels to the bottom\n * sharp(input)\n * .extend({\n * bottom: 10,\n * background: 'red'\n * })\n * ...\n *\n * @example\n * // Extrude image by 8 pixels to the right, mirroring existing right hand edge\n * sharp(input)\n * .extend({\n * right: 8,\n * background: 'mirror'\n * })\n * ...\n *\n * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts\n * @param {number} [extend.top=0]\n * @param {number} [extend.left=0]\n * @param {number} [extend.bottom=0]\n * @param {number} [extend.right=0]\n * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror.\n * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n*/\nfunction extend (extend) {\n if (is.integer(extend) && extend > 0) {\n this.options.extendTop = extend;\n this.options.extendBottom = extend;\n this.options.extendLeft = extend;\n this.options.extendRight = extend;\n } else if (is.object(extend)) {\n if (is.defined(extend.top)) {\n if (is.integer(extend.top) && extend.top >= 0) {\n this.options.extendTop = extend.top;\n } else {\n throw is.invalidParameterError('top', 'positive integer', extend.top);\n }\n }\n if (is.defined(extend.bottom)) {\n if (is.integer(extend.bottom) && extend.bottom >= 0) {\n this.options.extendBottom = extend.bottom;\n } else {\n throw is.invalidParameterError('bottom', 'positive integer', extend.bottom);\n }\n }\n if (is.defined(extend.left)) {\n if (is.integer(extend.left) && extend.left >= 0) {\n this.options.extendLeft = extend.left;\n } else {\n throw is.invalidParameterError('left', 'positive integer', extend.left);\n }\n }\n if (is.defined(extend.right)) {\n if (is.integer(extend.right) && extend.right >= 0) {\n this.options.extendRight = extend.right;\n } else {\n throw is.invalidParameterError('right', 'positive integer', extend.right);\n }\n }\n this._setBackgroundColourOption('extendBackground', extend.background);\n if (is.defined(extend.extendWith)) {\n if (is.string(extendWith[extend.extendWith])) {\n this.options.extendWith = extendWith[extend.extendWith];\n } else {\n throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith);\n }\n }\n } else {\n throw is.invalidParameterError('extend', 'integer or object', extend);\n }\n return this;\n}\n\n/**\n * Extract/crop a region of the image.\n *\n * - Use `extract` before `resize` for pre-resize extraction.\n * - Use `extract` after `resize` for post-resize extraction.\n * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.\n *\n * @example\n * sharp(input)\n * .extract({ left: left, top: top, width: width, height: height })\n * .toFile(output, function(err) {\n * // Extract a region of the input image, saving in the same format.\n * });\n * @example\n * sharp(input)\n * .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })\n * .resize(width, height)\n * .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })\n * .toFile(output, function(err) {\n * // Extract a region, resize, then extract from the resized image\n * });\n *\n * @param {Object} options - describes the region to extract using integral pixel values\n * @param {number} options.left - zero-indexed offset from left edge\n * @param {number} options.top - zero-indexed offset from top edge\n * @param {number} options.width - width of region to extract\n * @param {number} options.height - height of region to extract\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction extract (options) {\n const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';\n if (this.options[`width${suffix}`] !== -1) {\n this.options.debuglog('ignoring previous extract options');\n }\n ['left', 'top', 'width', 'height'].forEach(function (name) {\n const value = options[name];\n if (is.integer(value) && value >= 0) {\n this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value;\n } else {\n throw is.invalidParameterError(name, 'integer', value);\n }\n }, this);\n // Ensure existing rotation occurs before pre-resize extraction\n if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {\n if (this.options.widthPre === -1 || this.options.widthPost === -1) {\n this.options.rotateBeforePreExtract = true;\n }\n }\n return this;\n}\n\n/**\n * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.\n *\n * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.\n *\n * If the result of this operation would trim an image to nothing then no change is made.\n *\n * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.\n *\n * @example\n * // Trim pixels with a colour similar to that of the top-left pixel.\n * await sharp(input)\n * .trim()\n * .toFile(output);\n *\n * @example\n * // Trim pixels with the exact same colour as that of the top-left pixel.\n * await sharp(input)\n * .trim({\n * threshold: 0\n * })\n * .toFile(output);\n *\n * @example\n * // Assume input is line art and trim only pixels with a similar colour to red.\n * const output = await sharp(input)\n * .trim({\n * background: \"#FF0000\",\n * lineArt: true\n * })\n * .toBuffer();\n *\n * @example\n * // Trim all \"yellow-ish\" pixels, being more lenient with the higher threshold.\n * const output = await sharp(input)\n * .trim({\n * background: \"yellow\",\n * threshold: 42,\n * })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.\n * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.\n * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction trim (options) {\n this.options.trimThreshold = 10;\n if (is.defined(options)) {\n if (is.object(options)) {\n if (is.defined(options.background)) {\n this._setBackgroundColourOption('trimBackground', options.background);\n }\n if (is.defined(options.threshold)) {\n if (is.number(options.threshold) && options.threshold >= 0) {\n this.options.trimThreshold = options.threshold;\n } else {\n throw is.invalidParameterError('threshold', 'positive number', options.threshold);\n }\n }\n if (is.defined(options.lineArt)) {\n this._setBooleanOption('trimLineArt', options.lineArt);\n }\n } else {\n throw is.invalidParameterError('trim', 'object', options);\n }\n }\n if (isRotationExpected(this.options)) {\n this.options.rotateBeforePreExtract = true;\n }\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with resize-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n resize,\n extend,\n extract,\n trim\n });\n // Class attributes\n Sharp.gravity = gravity;\n Sharp.strategy = strategy;\n Sharp.kernel = kernel;\n Sharp.fit = fit;\n Sharp.position = position;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst is = require('./is');\n\n/**\n * Blend modes.\n * @member\n * @private\n */\nconst blend = {\n clear: 'clear',\n source: 'source',\n over: 'over',\n in: 'in',\n out: 'out',\n atop: 'atop',\n dest: 'dest',\n 'dest-over': 'dest-over',\n 'dest-in': 'dest-in',\n 'dest-out': 'dest-out',\n 'dest-atop': 'dest-atop',\n xor: 'xor',\n add: 'add',\n saturate: 'saturate',\n multiply: 'multiply',\n screen: 'screen',\n overlay: 'overlay',\n darken: 'darken',\n lighten: 'lighten',\n 'colour-dodge': 'colour-dodge',\n 'color-dodge': 'colour-dodge',\n 'colour-burn': 'colour-burn',\n 'color-burn': 'colour-burn',\n 'hard-light': 'hard-light',\n 'soft-light': 'soft-light',\n difference: 'difference',\n exclusion: 'exclusion'\n};\n\n/**\n * Composite image(s) over the processed (resized, extracted etc.) image.\n *\n * The images to composite must be the same size or smaller than the processed image.\n * If both `top` and `left` options are provided, they take precedence over `gravity`.\n *\n * Any resize, rotate or extract operations in the same processing pipeline\n * will always be applied to the input image before composition.\n *\n * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,\n * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,\n * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,\n * `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`,\n * `hard-light`, `soft-light`, `difference`, `exclusion`.\n *\n * More information about blend modes can be found at\n * https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode\n * and https://www.cairographics.org/operators/\n *\n * @since 0.22.0\n *\n * @example\n * await sharp(background)\n * .composite([\n * { input: layer1, gravity: 'northwest' },\n * { input: layer2, gravity: 'southeast' },\n * ])\n * .toFile('combined.png');\n *\n * @example\n * const output = await sharp('input.gif', { animated: true })\n * .composite([\n * { input: 'overlay.png', tile: true, blend: 'saturate' }\n * ])\n * .toBuffer();\n *\n * @example\n * sharp('input.png')\n * .rotate(180)\n * .resize(300)\n * .flatten( { background: '#ff6600' } )\n * .composite([{ input: 'overlay.png', gravity: 'southeast' }])\n * .sharpen()\n * .withMetadata()\n * .webp( { quality: 90 } )\n * .toBuffer()\n * .then(function(outputBuffer) {\n * // outputBuffer contains upside down, 300px wide, alpha channel flattened\n * // onto orange background, composited with overlay.png with SE gravity,\n * // sharpened, with metadata, 90% quality WebP image data. Phew!\n * });\n *\n * @param {Object[]} images - Ordered list of images to composite\n * @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below)\n * @param {Object} [images[].input.create] - describes a blank overlay to be created.\n * @param {Number} [images[].input.create.width]\n * @param {Number} [images[].input.create.height]\n * @param {Number} [images[].input.create.channels] - 3-4\n * @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Object} [images[].input.text] - describes a new text image to be created.\n * @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.\n * @param {string} [images[].input.text.font] - font name to render with.\n * @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.\n * @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.\n * @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.\n * @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text.\n * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.\n * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground=\"red\">Red!</span>`.\n * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.\n * @param {String} [images[].blend='over'] - how to blend this image with the image below.\n * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.\n * @param {Number} [images[].top] - the pixel offset from the top edge.\n * @param {Number} [images[].left] - the pixel offset from the left edge.\n * @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`.\n * @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option.\n * @param {Number} [images[].density=72] - number representing the DPI for vector overlay image.\n * @param {Object} [images[].raw] - describes overlay when using raw pixel data.\n * @param {Number} [images[].raw.width]\n * @param {Number} [images[].raw.height]\n * @param {Number} [images[].raw.channels]\n * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image.\n * @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters}\n * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters}\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction composite (images) {\n if (!Array.isArray(images)) {\n throw is.invalidParameterError('images to composite', 'array', images);\n }\n this.options.composite = images.map(image => {\n if (!is.object(image)) {\n throw is.invalidParameterError('image to composite', 'object', image);\n }\n const inputOptions = this._inputOptionsFromObject(image);\n const composite = {\n input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }),\n blend: 'over',\n tile: false,\n left: 0,\n top: 0,\n hasOffset: false,\n gravity: 0,\n premultiplied: false\n };\n if (is.defined(image.blend)) {\n if (is.string(blend[image.blend])) {\n composite.blend = blend[image.blend];\n } else {\n throw is.invalidParameterError('blend', 'valid blend name', image.blend);\n }\n }\n if (is.defined(image.tile)) {\n if (is.bool(image.tile)) {\n composite.tile = image.tile;\n } else {\n throw is.invalidParameterError('tile', 'boolean', image.tile);\n }\n }\n if (is.defined(image.left)) {\n if (is.integer(image.left)) {\n composite.left = image.left;\n } else {\n throw is.invalidParameterError('left', 'integer', image.left);\n }\n }\n if (is.defined(image.top)) {\n if (is.integer(image.top)) {\n composite.top = image.top;\n } else {\n throw is.invalidParameterError('top', 'integer', image.top);\n }\n }\n if (is.defined(image.top) !== is.defined(image.left)) {\n throw new Error('Expected both left and top to be set');\n } else {\n composite.hasOffset = is.integer(image.top) && is.integer(image.left);\n }\n if (is.defined(image.gravity)) {\n if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) {\n composite.gravity = image.gravity;\n } else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) {\n composite.gravity = this.constructor.gravity[image.gravity];\n } else {\n throw is.invalidParameterError('gravity', 'valid gravity', image.gravity);\n }\n }\n if (is.defined(image.premultiplied)) {\n if (is.bool(image.premultiplied)) {\n composite.premultiplied = image.premultiplied;\n } else {\n throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied);\n }\n }\n return composite;\n });\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with composite-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Sharp.prototype.composite = composite;\n Sharp.blend = blend;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst color = require('color');\nconst is = require('./is');\n\n/**\n * How accurate an operation should be.\n * @member\n * @private\n */\nconst vipsPrecision = {\n integer: 'integer',\n float: 'float',\n approximate: 'approximate'\n};\n\n/**\n * Rotate the output image by either an explicit angle\n * or auto-orient based on the EXIF `Orientation` tag.\n *\n * If an angle is provided, it is converted to a valid positive degree rotation.\n * For example, `-450` will produce a 270 degree rotation.\n *\n * When rotating by an angle other than a multiple of 90,\n * the background colour can be provided with the `background` option.\n *\n * If no angle is provided, it is determined from the EXIF data.\n * Mirroring is supported and may infer the use of a flip operation.\n *\n * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.\n *\n * Only one rotation can occur per pipeline.\n * Previous calls to `rotate` in the same pipeline will be ignored.\n *\n * Multi-page images can only be rotated by 180 degrees.\n *\n * Method order is important when rotating, resizing and/or extracting regions,\n * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.\n *\n * @example\n * const pipeline = sharp()\n * .rotate()\n * .resize(null, 200)\n * .toBuffer(function (err, outputBuffer, info) {\n * // outputBuffer contains 200px high JPEG image data,\n * // auto-rotated using EXIF Orientation tag\n * // info.width and info.height contain the dimensions of the resized image\n * });\n * readableStream.pipe(pipeline);\n *\n * @example\n * const rotateThenResize = await sharp(input)\n * .rotate(90)\n * .resize({ width: 16, height: 8, fit: 'fill' })\n * .toBuffer();\n * const resizeThenRotate = await sharp(input)\n * .resize({ width: 16, height: 8, fit: 'fill' })\n * .rotate(90)\n * .toBuffer();\n *\n * @param {number} [angle=auto] angle of rotation.\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {string|Object} [options.background=\"#000000\"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction rotate (angle, options) {\n if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) {\n this.options.debuglog('ignoring previous rotate options');\n }\n if (!is.defined(angle)) {\n this.options.useExifOrientation = true;\n } else if (is.integer(angle) && !(angle % 90)) {\n this.options.angle = angle;\n } else if (is.number(angle)) {\n this.options.rotationAngle = angle;\n if (is.object(options) && options.background) {\n const backgroundColour = color(options.background);\n this.options.rotationBackground = [\n backgroundColour.red(),\n backgroundColour.green(),\n backgroundColour.blue(),\n Math.round(backgroundColour.alpha() * 255)\n ];\n }\n } else {\n throw is.invalidParameterError('angle', 'numeric', angle);\n }\n return this;\n}\n\n/**\n * Mirror the image vertically (up-down) about the x-axis.\n * This always occurs before rotation, if any.\n *\n * This operation does not work correctly with multi-page images.\n *\n * @example\n * const output = await sharp(input).flip().toBuffer();\n *\n * @param {Boolean} [flip=true]\n * @returns {Sharp}\n */\nfunction flip (flip) {\n this.options.flip = is.bool(flip) ? flip : true;\n return this;\n}\n\n/**\n * Mirror the image horizontally (left-right) about the y-axis.\n * This always occurs before rotation, if any.\n *\n * @example\n * const output = await sharp(input).flop().toBuffer();\n *\n * @param {Boolean} [flop=true]\n * @returns {Sharp}\n */\nfunction flop (flop) {\n this.options.flop = is.bool(flop) ? flop : true;\n return this;\n}\n\n/**\n * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.\n *\n * You must provide an array of length 4 or a 2x2 affine transformation matrix.\n * By default, new pixels are filled with a black background. You can provide a background color with the `background` option.\n * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.\n *\n * In the case of a 2x2 matrix, the transform is:\n * - X = `matrix[0, 0]` \\* (x + `idx`) + `matrix[0, 1]` \\* (y + `idy`) + `odx`\n * - Y = `matrix[1, 0]` \\* (x + `idx`) + `matrix[1, 1]` \\* (y + `idy`) + `ody`\n *\n * where:\n * - x and y are the coordinates in input image.\n * - X and Y are the coordinates in output image.\n * - (0,0) is the upper left corner.\n *\n * @since 0.27.0\n *\n * @example\n * const pipeline = sharp()\n * .affine([[1, 0.3], [0.1, 0.7]], {\n * background: 'white',\n * interpolator: sharp.interpolators.nohalo\n * })\n * .toBuffer((err, outputBuffer, info) => {\n * // outputBuffer contains the transformed image\n * // info.width and info.height contain the new dimensions\n * });\n *\n * inputStream\n * .pipe(pipeline);\n *\n * @param {Array<Array<number>>|Array<number>} matrix - affine transformation matrix\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {String|Object} [options.background=\"#000000\"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Number} [options.idx=0] - input horizontal offset\n * @param {Number} [options.idy=0] - input vertical offset\n * @param {Number} [options.odx=0] - output horizontal offset\n * @param {Number} [options.ody=0] - output vertical offset\n * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction affine (matrix, options) {\n const flatMatrix = [].concat(...matrix);\n if (flatMatrix.length === 4 && flatMatrix.every(is.number)) {\n this.options.affineMatrix = flatMatrix;\n } else {\n throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix);\n }\n\n if (is.defined(options)) {\n if (is.object(options)) {\n this._setBackgroundColourOption('affineBackground', options.background);\n if (is.defined(options.idx)) {\n if (is.number(options.idx)) {\n this.options.affineIdx = options.idx;\n } else {\n throw is.invalidParameterError('options.idx', 'number', options.idx);\n }\n }\n if (is.defined(options.idy)) {\n if (is.number(options.idy)) {\n this.options.affineIdy = options.idy;\n } else {\n throw is.invalidParameterError('options.idy', 'number', options.idy);\n }\n }\n if (is.defined(options.odx)) {\n if (is.number(options.odx)) {\n this.options.affineOdx = options.odx;\n } else {\n throw is.invalidParameterError('options.odx', 'number', options.odx);\n }\n }\n if (is.defined(options.ody)) {\n if (is.number(options.ody)) {\n this.options.affineOdy = options.ody;\n } else {\n throw is.invalidParameterError('options.ody', 'number', options.ody);\n }\n }\n if (is.defined(options.interpolator)) {\n if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) {\n this.options.affineInterpolator = options.interpolator;\n } else {\n throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator);\n }\n }\n } else {\n throw is.invalidParameterError('options', 'object', options);\n }\n }\n\n return this;\n}\n\n/**\n * Sharpen the image.\n *\n * When used without parameters, performs a fast, mild sharpen of the output image.\n *\n * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.\n * Fine-grained control over the level of sharpening in \"flat\" (m1) and \"jagged\" (m2) areas is available.\n *\n * See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.\n *\n * @example\n * const data = await sharp(input).sharpen().toBuffer();\n *\n * @example\n * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();\n *\n * @example\n * const data = await sharp(input)\n * .sharpen({\n * sigma: 2,\n * m1: 0,\n * m2: 3,\n * x1: 3,\n * y2: 15,\n * y3: 15,\n * })\n * .toBuffer();\n *\n * @param {Object|number} [options] - if present, is an Object with attributes\n * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10\n * @param {number} [options.m1=1.0] - the level of sharpening to apply to \"flat\" areas, between 0 and 1000000\n * @param {number} [options.m2=2.0] - the level of sharpening to apply to \"jagged\" areas, between 0 and 1000000\n * @param {number} [options.x1=2.0] - threshold between \"flat\" and \"jagged\", between 0 and 1000000\n * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000\n * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000\n * @param {number} [flat] - (deprecated) see `options.m1`.\n * @param {number} [jagged] - (deprecated) see `options.m2`.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction sharpen (options, flat, jagged) {\n if (!is.defined(options)) {\n // No arguments: default to mild sharpen\n this.options.sharpenSigma = -1;\n } else if (is.bool(options)) {\n // Deprecated boolean argument: apply mild sharpen?\n this.options.sharpenSigma = options ? -1 : 0;\n } else if (is.number(options) && is.inRange(options, 0.01, 10000)) {\n // Deprecated numeric argument: specific sigma\n this.options.sharpenSigma = options;\n // Deprecated control over flat areas\n if (is.defined(flat)) {\n if (is.number(flat) && is.inRange(flat, 0, 10000)) {\n this.options.sharpenM1 = flat;\n } else {\n throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);\n }\n }\n // Deprecated control over jagged areas\n if (is.defined(jagged)) {\n if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {\n this.options.sharpenM2 = jagged;\n } else {\n throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);\n }\n }\n } else if (is.plainObject(options)) {\n if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) {\n this.options.sharpenSigma = options.sigma;\n } else {\n throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma);\n }\n if (is.defined(options.m1)) {\n if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {\n this.options.sharpenM1 = options.m1;\n } else {\n throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);\n }\n }\n if (is.defined(options.m2)) {\n if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {\n this.options.sharpenM2 = options.m2;\n } else {\n throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);\n }\n }\n if (is.defined(options.x1)) {\n if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {\n this.options.sharpenX1 = options.x1;\n } else {\n throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);\n }\n }\n if (is.defined(options.y2)) {\n if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {\n this.options.sharpenY2 = options.y2;\n } else {\n throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);\n }\n }\n if (is.defined(options.y3)) {\n if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {\n this.options.sharpenY3 = options.y3;\n } else {\n throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);\n }\n }\n } else {\n throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options);\n }\n return this;\n}\n\n/**\n * Apply median filter.\n * When used without parameters the default window is 3x3.\n *\n * @example\n * const output = await sharp(input).median().toBuffer();\n *\n * @example\n * const output = await sharp(input).median(5).toBuffer();\n *\n * @param {number} [size=3] square mask size: size x size\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction median (size) {\n if (!is.defined(size)) {\n // No arguments: default to 3x3\n this.options.medianSize = 3;\n } else if (is.integer(size) && is.inRange(size, 1, 1000)) {\n // Numeric argument: specific sigma\n this.options.medianSize = size;\n } else {\n throw is.invalidParameterError('size', 'integer between 1 and 1000', size);\n }\n return this;\n}\n\n/**\n * Blur the image.\n *\n * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).\n *\n * When a `sigma` is provided, performs a slower, more accurate Gaussian blur.\n *\n * @example\n * const boxBlurred = await sharp(input)\n * .blur()\n * .toBuffer();\n *\n * @example\n * const gaussianBlurred = await sharp(input)\n * .blur(5)\n * .toBuffer();\n *\n * @param {Object|number|Boolean} [options]\n * @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.\n * @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate.\n * @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction blur (options) {\n let sigma;\n if (is.number(options)) {\n sigma = options;\n } else if (is.plainObject(options)) {\n if (!is.number(options.sigma)) {\n throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma);\n }\n sigma = options.sigma;\n if ('precision' in options) {\n if (is.string(vipsPrecision[options.precision])) {\n this.options.precision = vipsPrecision[options.precision];\n } else {\n throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision);\n }\n }\n if ('minAmplitude' in options) {\n if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) {\n this.options.minAmpl = options.minAmplitude;\n } else {\n throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude);\n }\n }\n }\n\n if (!is.defined(options)) {\n // No arguments: default to mild blur\n this.options.blurSigma = -1;\n } else if (is.bool(options)) {\n // Boolean argument: apply mild blur?\n this.options.blurSigma = options ? -1 : 0;\n } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {\n // Numeric argument: specific sigma\n this.options.blurSigma = sigma;\n } else {\n throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);\n }\n\n return this;\n}\n\n/**\n * Merge alpha transparency channel, if any, with a background, then remove the alpha channel.\n *\n * See also {@link /api-channel#removealpha|removeAlpha}.\n *\n * @example\n * await sharp(rgbaInput)\n * .flatten({ background: '#F0A703' })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black.\n * @returns {Sharp}\n */\nfunction flatten (options) {\n this.options.flatten = is.bool(options) ? options : true;\n if (is.object(options)) {\n this._setBackgroundColourOption('flattenBackground', options.background);\n }\n return this;\n}\n\n/**\n * Ensure the image has an alpha channel\n * with all white pixel values made fully transparent.\n *\n * Existing alpha channel values for non-white pixels remain unchanged.\n *\n * This feature is experimental and the API may change.\n *\n * @since 0.32.1\n *\n * @example\n * await sharp(rgbInput)\n * .unflatten()\n * .toBuffer();\n *\n * @example\n * await sharp(rgbInput)\n * .threshold(128, { grayscale: false }) // converter bright pixels to white\n * .unflatten()\n * .toBuffer();\n */\nfunction unflatten () {\n this.options.unflatten = true;\n return this;\n}\n\n/**\n * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`\n * then increasing the encoding (brighten) post-resize at a factor of `gamma`.\n * This can improve the perceived brightness of a resized image in non-linear colour spaces.\n * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation\n * when applying a gamma correction.\n *\n * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.\n *\n * @param {number} [gamma=2.2] value between 1.0 and 3.0.\n * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction gamma (gamma, gammaOut) {\n if (!is.defined(gamma)) {\n // Default gamma correction of 2.2 (sRGB)\n this.options.gamma = 2.2;\n } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) {\n this.options.gamma = gamma;\n } else {\n throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma);\n }\n if (!is.defined(gammaOut)) {\n // Default gamma correction for output is same as input\n this.options.gammaOut = this.options.gamma;\n } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) {\n this.options.gammaOut = gammaOut;\n } else {\n throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut);\n }\n return this;\n}\n\n/**\n * Produce the \"negative\" of the image.\n *\n * @example\n * const output = await sharp(input)\n * .negate()\n * .toBuffer();\n *\n * @example\n * const output = await sharp(input)\n * .negate({ alpha: false })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel\n * @returns {Sharp}\n */\nfunction negate (options) {\n this.options.negate = is.bool(options) ? options : true;\n if (is.plainObject(options) && 'alpha' in options) {\n if (!is.bool(options.alpha)) {\n throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha);\n } else {\n this.options.negateAlpha = options.alpha;\n }\n }\n return this;\n}\n\n/**\n * Enhance output image contrast by stretching its luminance to cover a full dynamic range.\n *\n * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.\n *\n * Luminance values below the `lower` percentile will be underexposed by clipping to zero.\n * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.\n *\n * @example\n * const output = await sharp(input)\n * .normalise()\n * .toBuffer();\n *\n * @example\n * const output = await sharp(input)\n * .normalise({ lower: 0, upper: 100 })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.\n * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.\n * @returns {Sharp}\n */\nfunction normalise (options) {\n if (is.plainObject(options)) {\n if (is.defined(options.lower)) {\n if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) {\n this.options.normaliseLower = options.lower;\n } else {\n throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower);\n }\n }\n if (is.defined(options.upper)) {\n if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) {\n this.options.normaliseUpper = options.upper;\n } else {\n throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper);\n }\n }\n }\n if (this.options.normaliseLower >= this.options.normaliseUpper) {\n throw is.invalidParameterError('range', 'lower to be less than upper',\n `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);\n }\n this.options.normalise = true;\n return this;\n}\n\n/**\n * Alternative spelling of normalise.\n *\n * @example\n * const output = await sharp(input)\n * .normalize()\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.\n * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.\n * @returns {Sharp}\n */\nfunction normalize (options) {\n return this.normalise(options);\n}\n\n/**\n * Perform contrast limiting adaptive histogram equalization\n * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}.\n *\n * This will, in general, enhance the clarity of the image by bringing out darker details.\n *\n * @since 0.28.3\n *\n * @example\n * const output = await sharp(input)\n * .clahe({\n * width: 3,\n * height: 3,\n * })\n * .toBuffer();\n *\n * @param {Object} options\n * @param {number} options.width - Integral width of the search window, in pixels.\n * @param {number} options.height - Integral height of the search window, in pixels.\n * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction clahe (options) {\n if (is.plainObject(options)) {\n if (is.integer(options.width) && options.width > 0) {\n this.options.claheWidth = options.width;\n } else {\n throw is.invalidParameterError('width', 'integer greater than zero', options.width);\n }\n if (is.integer(options.height) && options.height > 0) {\n this.options.claheHeight = options.height;\n } else {\n throw is.invalidParameterError('height', 'integer greater than zero', options.height);\n }\n if (is.defined(options.maxSlope)) {\n if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) {\n this.options.claheMaxSlope = options.maxSlope;\n } else {\n throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope);\n }\n }\n } else {\n throw is.invalidParameterError('options', 'plain object', options);\n }\n return this;\n}\n\n/**\n * Convolve the image with the specified kernel.\n *\n * @example\n * sharp(input)\n * .convolve({\n * width: 3,\n * height: 3,\n * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]\n * })\n * .raw()\n * .toBuffer(function(err, data, info) {\n * // data contains the raw pixel data representing the convolution\n * // of the input image with the horizontal Sobel operator\n * });\n *\n * @param {Object} kernel\n * @param {number} kernel.width - width of the kernel in pixels.\n * @param {number} kernel.height - height of the kernel in pixels.\n * @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values.\n * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels.\n * @param {number} [kernel.offset=0] - the offset of the kernel in pixels.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction convolve (kernel) {\n if (!is.object(kernel) || !Array.isArray(kernel.kernel) ||\n !is.integer(kernel.width) || !is.integer(kernel.height) ||\n !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) ||\n kernel.height * kernel.width !== kernel.kernel.length\n ) {\n // must pass in a kernel\n throw new Error('Invalid convolution kernel');\n }\n // Default scale is sum of kernel values\n if (!is.integer(kernel.scale)) {\n kernel.scale = kernel.kernel.reduce(function (a, b) {\n return a + b;\n }, 0);\n }\n // Clip scale to a minimum value of 1\n if (kernel.scale < 1) {\n kernel.scale = 1;\n }\n if (!is.integer(kernel.offset)) {\n kernel.offset = 0;\n }\n this.options.convKernel = kernel;\n return this;\n}\n\n/**\n * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.\n * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied.\n * @param {Object} [options]\n * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale.\n * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction threshold (threshold, options) {\n if (!is.defined(threshold)) {\n this.options.threshold = 128;\n } else if (is.bool(threshold)) {\n this.options.threshold = threshold ? 128 : 0;\n } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) {\n this.options.threshold = threshold;\n } else {\n throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold);\n }\n if (!is.object(options) || options.greyscale === true || options.grayscale === true) {\n this.options.thresholdGrayscale = true;\n } else {\n this.options.thresholdGrayscale = false;\n }\n return this;\n}\n\n/**\n * Perform a bitwise boolean operation with operand image.\n *\n * This operation creates an output image where each pixel is the result of\n * the selected bitwise boolean `operation` between the corresponding pixels of the input images.\n *\n * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file.\n * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.\n * @param {Object} [options]\n * @param {Object} [options.raw] - describes operand when using raw pixel data.\n * @param {number} [options.raw.width]\n * @param {number} [options.raw.height]\n * @param {number} [options.raw.channels]\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction boolean (operand, operator, options) {\n this.options.boolean = this._createInputDescriptor(operand, options);\n if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) {\n this.options.booleanOp = operator;\n } else {\n throw is.invalidParameterError('operator', 'one of: and, or, eor', operator);\n }\n return this;\n}\n\n/**\n * Apply the linear formula `a` * input + `b` to the image to adjust image levels.\n *\n * When a single number is provided, it will be used for all image channels.\n * When an array of numbers is provided, the array length must match the number of channels.\n *\n * @example\n * await sharp(input)\n * .linear(0.5, 2)\n * .toBuffer();\n *\n * @example\n * await sharp(rgbInput)\n * .linear(\n * [0.25, 0.5, 0.75],\n * [150, 100, 50]\n * )\n * .toBuffer();\n *\n * @param {(number|number[])} [a=[]] multiplier\n * @param {(number|number[])} [b=[]] offset\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction linear (a, b) {\n if (!is.defined(a) && is.number(b)) {\n a = 1.0;\n } else if (is.number(a) && !is.defined(b)) {\n b = 0.0;\n }\n if (!is.defined(a)) {\n this.options.linearA = [];\n } else if (is.number(a)) {\n this.options.linearA = [a];\n } else if (Array.isArray(a) && a.length && a.every(is.number)) {\n this.options.linearA = a;\n } else {\n throw is.invalidParameterError('a', 'number or array of numbers', a);\n }\n if (!is.defined(b)) {\n this.options.linearB = [];\n } else if (is.number(b)) {\n this.options.linearB = [b];\n } else if (Array.isArray(b) && b.length && b.every(is.number)) {\n this.options.linearB = b;\n } else {\n throw is.invalidParameterError('b', 'number or array of numbers', b);\n }\n if (this.options.linearA.length !== this.options.linearB.length) {\n throw new Error('Expected a and b to be arrays of the same length');\n }\n return this;\n}\n\n/**\n * Recombine the image with the specified matrix.\n *\n * @since 0.21.1\n *\n * @example\n * sharp(input)\n * .recomb([\n * [0.3588, 0.7044, 0.1368],\n * [0.2990, 0.5870, 0.1140],\n * [0.2392, 0.4696, 0.0912],\n * ])\n * .raw()\n * .toBuffer(function(err, data, info) {\n * // data contains the raw pixel data after applying the matrix\n * // With this example input, a sepia filter has been applied\n * });\n *\n * @param {Array<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction recomb (inputMatrix) {\n if (!Array.isArray(inputMatrix)) {\n throw is.invalidParameterError('inputMatrix', 'array', inputMatrix);\n }\n if (inputMatrix.length !== 3 && inputMatrix.length !== 4) {\n throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length);\n }\n const recombMatrix = inputMatrix.flat().map(Number);\n if (recombMatrix.length !== 9 && recombMatrix.length !== 16) {\n throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length);\n }\n this.options.recombMatrix = recombMatrix;\n return this;\n}\n\n/**\n * Transforms the image using brightness, saturation, hue rotation, and lightness.\n * Brightness and lightness both operate on luminance, with the difference being that\n * brightness is multiplicative whereas lightness is additive.\n *\n * @since 0.22.1\n *\n * @example\n * // increase brightness by a factor of 2\n * const output = await sharp(input)\n * .modulate({\n * brightness: 2\n * })\n * .toBuffer();\n *\n * @example\n * // hue-rotate by 180 degrees\n * const output = await sharp(input)\n * .modulate({\n * hue: 180\n * })\n * .toBuffer();\n *\n * @example\n * // increase lightness by +50\n * const output = await sharp(input)\n * .modulate({\n * lightness: 50\n * })\n * .toBuffer();\n *\n * @example\n * // decrease brightness and saturation while also hue-rotating by 90 degrees\n * const output = await sharp(input)\n * .modulate({\n * brightness: 0.5,\n * saturation: 0.5,\n * hue: 90,\n * })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.brightness] Brightness multiplier\n * @param {number} [options.saturation] Saturation multiplier\n * @param {number} [options.hue] Degrees for hue rotation\n * @param {number} [options.lightness] Lightness addend\n * @returns {Sharp}\n */\nfunction modulate (options) {\n if (!is.plainObject(options)) {\n throw is.invalidParameterError('options', 'plain object', options);\n }\n if ('brightness' in options) {\n if (is.number(options.brightness) && options.brightness >= 0) {\n this.options.brightness = options.brightness;\n } else {\n throw is.invalidParameterError('brightness', 'number above zero', options.brightness);\n }\n }\n if ('saturation' in options) {\n if (is.number(options.saturation) && options.saturation >= 0) {\n this.options.saturation = options.saturation;\n } else {\n throw is.invalidParameterError('saturation', 'number above zero', options.saturation);\n }\n }\n if ('hue' in options) {\n if (is.integer(options.hue)) {\n this.options.hue = options.hue % 360;\n } else {\n throw is.invalidParameterError('hue', 'number', options.hue);\n }\n }\n if ('lightness' in options) {\n if (is.number(options.lightness)) {\n this.options.lightness = options.lightness;\n } else {\n throw is.invalidParameterError('lightness', 'number', options.lightness);\n }\n }\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with operation-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n rotate,\n flip,\n flop,\n affine,\n sharpen,\n median,\n blur,\n flatten,\n unflatten,\n gamma,\n negate,\n normalise,\n normalize,\n clahe,\n convolve,\n threshold,\n boolean,\n linear,\n recomb,\n modulate\n });\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst color = require('color');\nconst is = require('./is');\n\n/**\n * Colourspaces.\n * @private\n */\nconst colourspace = {\n multiband: 'multiband',\n 'b-w': 'b-w',\n bw: 'b-w',\n cmyk: 'cmyk',\n srgb: 'srgb'\n};\n\n/**\n * Tint the image using the provided colour.\n * An alpha channel may be present and will be unchanged by the operation.\n *\n * @example\n * const output = await sharp(input)\n * .tint({ r: 255, g: 240, b: 16 })\n * .toBuffer();\n *\n * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.\n * @returns {Sharp}\n * @throws {Error} Invalid parameter\n */\nfunction tint (tint) {\n this._setBackgroundColourOption('tint', tint);\n return this;\n}\n\n/**\n * Convert to 8-bit greyscale; 256 shades of grey.\n * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.\n * By default the output image will be web-friendly sRGB and contain three (identical) color channels.\n * This may be overridden by other sharp operations such as `toColourspace('b-w')`,\n * which will produce an output image containing one color channel.\n * An alpha channel may be present, and will be unchanged by the operation.\n *\n * @example\n * const output = await sharp(input).greyscale().toBuffer();\n *\n * @param {Boolean} [greyscale=true]\n * @returns {Sharp}\n */\nfunction greyscale (greyscale) {\n this.options.greyscale = is.bool(greyscale) ? greyscale : true;\n return this;\n}\n\n/**\n * Alternative spelling of `greyscale`.\n * @param {Boolean} [grayscale=true]\n * @returns {Sharp}\n */\nfunction grayscale (grayscale) {\n return this.greyscale(grayscale);\n}\n\n/**\n * Set the pipeline colourspace.\n *\n * The input image will be converted to the provided colourspace at the start of the pipeline.\n * All operations will use this colourspace before converting to the output colourspace,\n * as defined by {@link #tocolourspace|toColourspace}.\n *\n * @since 0.29.0\n *\n * @example\n * // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.\n * await sharp(input)\n * .pipelineColourspace('rgb16')\n * .toColourspace('srgb')\n * .toFile('16bpc-pipeline-to-8bpc-output.png')\n *\n * @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction pipelineColourspace (colourspace) {\n if (!is.string(colourspace)) {\n throw is.invalidParameterError('colourspace', 'string', colourspace);\n }\n this.options.colourspacePipeline = colourspace;\n return this;\n}\n\n/**\n * Alternative spelling of `pipelineColourspace`.\n * @param {string} [colorspace] - pipeline colorspace.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction pipelineColorspace (colorspace) {\n return this.pipelineColourspace(colorspace);\n}\n\n/**\n * Set the output colourspace.\n * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n *\n * @example\n * // Output 16 bits per pixel RGB\n * await sharp(input)\n * .toColourspace('rgb16')\n * .toFile('16-bpp.png')\n *\n * @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction toColourspace (colourspace) {\n if (!is.string(colourspace)) {\n throw is.invalidParameterError('colourspace', 'string', colourspace);\n }\n this.options.colourspace = colourspace;\n return this;\n}\n\n/**\n * Alternative spelling of `toColourspace`.\n * @param {string} [colorspace] - output colorspace.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction toColorspace (colorspace) {\n return this.toColourspace(colorspace);\n}\n\n/**\n * Update a colour attribute of the this.options Object.\n * @private\n * @param {string} key\n * @param {string|Object} value\n * @throws {Error} Invalid value\n */\nfunction _setBackgroundColourOption (key, value) {\n if (is.defined(value)) {\n if (is.object(value) || is.string(value)) {\n const colour = color(value);\n this.options[key] = [\n colour.red(),\n colour.green(),\n colour.blue(),\n Math.round(colour.alpha() * 255)\n ];\n } else {\n throw is.invalidParameterError('background', 'object or string', value);\n }\n }\n}\n\n/**\n * Decorate the Sharp prototype with colour-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Public\n tint,\n greyscale,\n grayscale,\n pipelineColourspace,\n pipelineColorspace,\n toColourspace,\n toColorspace,\n // Private\n _setBackgroundColourOption\n });\n // Class attributes\n Sharp.colourspace = colourspace;\n Sharp.colorspace = colourspace;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst is = require('./is');\n\n/**\n * Boolean operations for bandbool.\n * @private\n */\nconst bool = {\n and: 'and',\n or: 'or',\n eor: 'eor'\n};\n\n/**\n * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.\n *\n * See also {@link /api-operation#flatten|flatten}.\n *\n * @example\n * sharp('rgba.png')\n * .removeAlpha()\n * .toFile('rgb.png', function(err, info) {\n * // rgb.png is a 3 channel image without an alpha channel\n * });\n *\n * @returns {Sharp}\n */\nfunction removeAlpha () {\n this.options.removeAlpha = true;\n return this;\n}\n\n/**\n * Ensure the output image has an alpha transparency channel.\n * If missing, the added alpha channel will have the specified\n * transparency level, defaulting to fully-opaque (1).\n * This is a no-op if the image already has an alpha channel.\n *\n * @since 0.21.2\n *\n * @example\n * // rgba.png will be a 4 channel image with a fully-opaque alpha channel\n * await sharp('rgb.jpg')\n * .ensureAlpha()\n * .toFile('rgba.png')\n *\n * @example\n * // rgba is a 4 channel image with a fully-transparent alpha channel\n * const rgba = await sharp(rgb)\n * .ensureAlpha(0)\n * .toBuffer();\n *\n * @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)\n * @returns {Sharp}\n * @throws {Error} Invalid alpha transparency level\n */\nfunction ensureAlpha (alpha) {\n if (is.defined(alpha)) {\n if (is.number(alpha) && is.inRange(alpha, 0, 1)) {\n this.options.ensureAlpha = alpha;\n } else {\n throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);\n }\n } else {\n this.options.ensureAlpha = 1;\n }\n return this;\n}\n\n/**\n * Extract a single channel from a multi-channel image.\n *\n * @example\n * // green.jpg is a greyscale image containing the green channel of the input\n * await sharp(input)\n * .extractChannel('green')\n * .toFile('green.jpg');\n *\n * @example\n * // red1 is the red value of the first pixel, red2 the second pixel etc.\n * const [red1, red2, ...] = await sharp(input)\n * .extractChannel(0)\n * .raw()\n * .toBuffer();\n *\n * @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.\n * @returns {Sharp}\n * @throws {Error} Invalid channel\n */\nfunction extractChannel (channel) {\n const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 };\n if (Object.keys(channelMap).includes(channel)) {\n channel = channelMap[channel];\n }\n if (is.integer(channel) && is.inRange(channel, 0, 4)) {\n this.options.extractChannel = channel;\n } else {\n throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);\n }\n return this;\n}\n\n/**\n * Join one or more channels to the image.\n * The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.\n * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n * Channel ordering follows vips convention:\n * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.\n * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.\n *\n * Buffers may be any of the image formats supported by sharp.\n * For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.\n *\n * @param {Array<string|Buffer>|string|Buffer} images - one or more images (file paths, Buffers).\n * @param {Object} options - image options, see `sharp()` constructor.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction joinChannel (images, options) {\n if (Array.isArray(images)) {\n images.forEach(function (image) {\n this.options.joinChannelIn.push(this._createInputDescriptor(image, options));\n }, this);\n } else {\n this.options.joinChannelIn.push(this._createInputDescriptor(images, options));\n }\n return this;\n}\n\n/**\n * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.\n *\n * @example\n * sharp('3-channel-rgb-input.png')\n * .bandbool(sharp.bool.and)\n * .toFile('1-channel-output.png', function (err, info) {\n * // The output will be a single channel image where each pixel `P = R & G & B`.\n * // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`\n * // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.\n * });\n *\n * @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction bandbool (boolOp) {\n if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) {\n this.options.bandBoolOp = boolOp;\n } else {\n throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp);\n }\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with channel-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Public instance functions\n removeAlpha,\n ensureAlpha,\n extractChannel,\n joinChannel,\n bandbool\n });\n // Class attributes\n Sharp.bool = bool;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst path = require('node:path');\nconst is = require('./is');\nconst sharp = require('./sharp');\n\nconst formats = new Map([\n ['heic', 'heif'],\n ['heif', 'heif'],\n ['avif', 'avif'],\n ['jpeg', 'jpeg'],\n ['jpg', 'jpeg'],\n ['jpe', 'jpeg'],\n ['tile', 'tile'],\n ['dz', 'tile'],\n ['png', 'png'],\n ['raw', 'raw'],\n ['tiff', 'tiff'],\n ['tif', 'tiff'],\n ['webp', 'webp'],\n ['gif', 'gif'],\n ['jp2', 'jp2'],\n ['jpx', 'jp2'],\n ['j2k', 'jp2'],\n ['j2c', 'jp2'],\n ['jxl', 'jxl']\n]);\n\nconst jp2Regex = /\\.(jp[2x]|j2[kc])$/i;\n\nconst errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');\n\nconst bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));\n\n/**\n * Write output image data to a file.\n *\n * If an explicit output format is not selected, it will be inferred from the extension,\n * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.\n * Note that raw pixel data is only supported for buffer output.\n *\n * By default all metadata will be removed, which includes EXIF-based orientation.\n * See {@link #withmetadata|withMetadata} for control over this.\n *\n * The caller is responsible for ensuring directory structures and permissions exist.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * @example\n * sharp(input)\n * .toFile('output.png', (err, info) => { ... });\n *\n * @example\n * sharp(input)\n * .toFile('output.png')\n * .then(info => { ... })\n * .catch(err => { ... });\n *\n * @param {string} fileOut - the path to write the image data to.\n * @param {Function} [callback] - called on completion with two arguments `(err, info)`.\n * `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n * `channels` and `premultiplied` (indicating if premultiplication was used).\n * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\n * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.\n * Animated output will also contain `pageHeight` and `pages`.\n * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n * @returns {Promise<Object>} - when no callback is provided\n * @throws {Error} Invalid parameters\n */\nfunction toFile (fileOut, callback) {\n let err;\n if (!is.string(fileOut)) {\n err = new Error('Missing output file path');\n } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {\n err = new Error('Cannot use same file for input and output');\n } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {\n err = errJp2Save();\n }\n if (err) {\n if (is.fn(callback)) {\n callback(err);\n } else {\n return Promise.reject(err);\n }\n } else {\n this.options.fileOut = fileOut;\n const stack = Error();\n return this._pipeline(callback, stack);\n }\n return this;\n}\n\n/**\n * Write output to a Buffer.\n * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.\n *\n * Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.\n *\n * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.\n *\n * By default all metadata will be removed, which includes EXIF-based orientation.\n * See {@link #withmetadata|withMetadata} for control over this.\n *\n * `callback`, if present, gets three arguments `(err, data, info)` where:\n * - `err` is an error, if any.\n * - `data` is the output image data.\n * - `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n * `channels` and `premultiplied` (indicating if premultiplication was used).\n * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\n * Animated output will also contain `pageHeight` and `pages`.\n * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * @example\n * sharp(input)\n * .toBuffer((err, data, info) => { ... });\n *\n * @example\n * sharp(input)\n * .toBuffer()\n * .then(data => { ... })\n * .catch(err => { ... });\n *\n * @example\n * sharp(input)\n * .png()\n * .toBuffer({ resolveWithObject: true })\n * .then(({ data, info }) => { ... })\n * .catch(err => { ... });\n *\n * @example\n * const { data, info } = await sharp('my-image.jpg')\n * // output the raw pixels\n * .raw()\n * .toBuffer({ resolveWithObject: true });\n *\n * // create a more type safe way to work with the raw pixel data\n * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer\n * // so `data` and `pixelArray` point to the same memory location\n * const pixelArray = new Uint8ClampedArray(data.buffer);\n *\n * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input\n * const { width, height, channels } = info;\n * await sharp(pixelArray, { raw: { width, height, channels } })\n * .toFile('my-changed-image.jpg');\n *\n * @param {Object} [options]\n * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.\n * @param {Function} [callback]\n * @returns {Promise<Buffer>} - when no callback is provided\n */\nfunction toBuffer (options, callback) {\n if (is.object(options)) {\n this._setBooleanOption('resolveWithObject', options.resolveWithObject);\n } else if (this.options.resolveWithObject) {\n this.options.resolveWithObject = false;\n }\n this.options.fileOut = '';\n const stack = Error();\n return this._pipeline(is.fn(options) ? options : callback, stack);\n}\n\n/**\n * Keep all EXIF metadata from the input image in the output image.\n *\n * EXIF metadata is unsupported for TIFF output.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithExif = await sharp(inputWithExif)\n * .keepExif()\n * .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepExif () {\n this.options.keepMetadata |= 0b00001;\n return this;\n}\n\n/**\n * Set EXIF metadata in the output image, ignoring any EXIF in the input image.\n *\n * @since 0.33.0\n *\n * @example\n * const dataWithExif = await sharp(input)\n * .withExif({\n * IFD0: {\n * Copyright: 'The National Gallery'\n * },\n * IFD3: {\n * GPSLatitudeRef: 'N',\n * GPSLatitude: '51/1 30/1 3230/100',\n * GPSLongitudeRef: 'W',\n * GPSLongitude: '0/1 7/1 4366/100'\n * }\n * })\n * .toBuffer();\n *\n * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withExif (exif) {\n if (is.object(exif)) {\n for (const [ifd, entries] of Object.entries(exif)) {\n if (is.object(entries)) {\n for (const [k, v] of Object.entries(entries)) {\n if (is.string(v)) {\n this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;\n } else {\n throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);\n }\n }\n } else {\n throw is.invalidParameterError(ifd, 'object', entries);\n }\n }\n } else {\n throw is.invalidParameterError('exif', 'object', exif);\n }\n this.options.withExifMerge = false;\n return this.keepExif();\n}\n\n/**\n * Update EXIF metadata from the input image in the output image.\n *\n * @since 0.33.0\n *\n * @example\n * const dataWithMergedExif = await sharp(inputWithExif)\n * .withExifMerge({\n * IFD0: {\n * Copyright: 'The National Gallery'\n * }\n * })\n * .toBuffer();\n *\n * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withExifMerge (exif) {\n this.withExif(exif);\n this.options.withExifMerge = true;\n return this;\n}\n\n/**\n * Keep ICC profile from the input image in the output image.\n *\n * Where necessary, will attempt to convert the output colour space to match the profile.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithIccProfile = await sharp(inputWithIccProfile)\n * .keepIccProfile()\n * .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepIccProfile () {\n this.options.keepMetadata |= 0b01000;\n return this;\n}\n\n/**\n * Transform using an ICC profile and attach to the output image.\n *\n * This can either be an absolute filesystem path or\n * built-in profile name (`srgb`, `p3`, `cmyk`).\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithP3 = await sharp(input)\n * .withIccProfile('p3')\n * .toBuffer();\n *\n * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).\n * @param {Object} [options]\n * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withIccProfile (icc, options) {\n if (is.string(icc)) {\n this.options.withIccProfile = icc;\n } else {\n throw is.invalidParameterError('icc', 'string', icc);\n }\n this.keepIccProfile();\n if (is.object(options)) {\n if (is.defined(options.attach)) {\n if (is.bool(options.attach)) {\n if (!options.attach) {\n this.options.keepMetadata &= ~0b01000;\n }\n } else {\n throw is.invalidParameterError('attach', 'boolean', options.attach);\n }\n }\n }\n return this;\n}\n\n/**\n * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.\n *\n * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent\n * sRGB colour space and strip all metadata, including the removal of any ICC profile.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithMetadata = await sharp(inputWithMetadata)\n * .keepMetadata()\n * .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepMetadata () {\n this.options.keepMetadata = 0b11111;\n return this;\n}\n\n/**\n * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.\n *\n * This will also convert to and add a web-friendly sRGB ICC profile if appropriate.\n *\n * Allows orientation and density to be set or updated.\n *\n * @example\n * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)\n * .withMetadata()\n * .toBuffer();\n *\n * @example\n * // Set output metadata to 96 DPI\n * const data = await sharp(input)\n * .withMetadata({ density: 96 })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.\n * @param {number} [options.density] Number of pixels per inch (DPI).\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withMetadata (options) {\n this.keepMetadata();\n this.withIccProfile('srgb');\n if (is.object(options)) {\n if (is.defined(options.orientation)) {\n if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {\n this.options.withMetadataOrientation = options.orientation;\n } else {\n throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation);\n }\n }\n if (is.defined(options.density)) {\n if (is.number(options.density) && options.density > 0) {\n this.options.withMetadataDensity = options.density;\n } else {\n throw is.invalidParameterError('density', 'positive number', options.density);\n }\n }\n if (is.defined(options.icc)) {\n this.withIccProfile(options.icc);\n }\n if (is.defined(options.exif)) {\n this.withExifMerge(options.exif);\n }\n }\n return this;\n}\n\n/**\n * Force output to a given format.\n *\n * @example\n * // Convert any input to PNG output\n * const data = await sharp(input)\n * .toFormat('png')\n * .toBuffer();\n *\n * @param {(string|Object)} format - as a string or an Object with an 'id' attribute\n * @param {Object} options - output options\n * @returns {Sharp}\n * @throws {Error} unsupported format or options\n */\nfunction toFormat (format, options) {\n const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase());\n if (!actualFormat) {\n throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format);\n }\n return this[actualFormat](options);\n}\n\n/**\n * Use these JPEG options for output image.\n *\n * @example\n * // Convert any input to very high quality JPEG output\n * const data = await sharp(input)\n * .jpeg({\n * quality: 100,\n * chromaSubsampling: '4:4:4'\n * })\n * .toBuffer();\n *\n * @example\n * // Use mozjpeg to reduce output JPEG file size (slower)\n * const data = await sharp(input)\n * .jpeg({ mozjpeg: true })\n * .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling\n * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables\n * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding\n * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }`\n * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation\n * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing\n * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive\n * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans\n * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8\n * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable\n * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jpeg (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.jpegQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.progressive)) {\n this._setBooleanOption('jpegProgressive', options.progressive);\n }\n if (is.defined(options.chromaSubsampling)) {\n if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n this.options.jpegChromaSubsampling = options.chromaSubsampling;\n } else {\n throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n }\n }\n const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding;\n if (is.defined(optimiseCoding)) {\n this._setBooleanOption('jpegOptimiseCoding', optimiseCoding);\n }\n if (is.defined(options.mozjpeg)) {\n if (is.bool(options.mozjpeg)) {\n if (options.mozjpeg) {\n this.options.jpegTrellisQuantisation = true;\n this.options.jpegOvershootDeringing = true;\n this.options.jpegOptimiseScans = true;\n this.options.jpegProgressive = true;\n this.options.jpegQuantisationTable = 3;\n }\n } else {\n throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg);\n }\n }\n const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation;\n if (is.defined(trellisQuantisation)) {\n this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation);\n }\n if (is.defined(options.overshootDeringing)) {\n this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing);\n }\n const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans;\n if (is.defined(optimiseScans)) {\n this._setBooleanOption('jpegOptimiseScans', optimiseScans);\n if (optimiseScans) {\n this.options.jpegProgressive = true;\n }\n }\n const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable;\n if (is.defined(quantisationTable)) {\n if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) {\n this.options.jpegQuantisationTable = quantisationTable;\n } else {\n throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable);\n }\n }\n }\n return this._updateFormatOut('jpeg', options);\n}\n\n/**\n * Use these PNG options for output image.\n *\n * By default, PNG output is full colour at 8 bits per pixel.\n *\n * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.\n * Set `palette` to `true` for slower, indexed PNG output.\n *\n * For 16 bits per pixel output, convert to `rgb16` via\n * {@link /api-colour#tocolourspace|toColourspace}.\n *\n * @example\n * // Convert any input to full colour PNG output\n * const data = await sharp(input)\n * .png()\n * .toBuffer();\n *\n * @example\n * // Convert any input to indexed PNG output (slower)\n * const data = await sharp(input)\n * .png({ palette: true })\n * .toBuffer();\n *\n * @example\n * // Output 16 bits per pixel RGB(A)\n * const data = await sharp(input)\n * .toColourspace('rgb16')\n * .png()\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)\n * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering\n * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support\n * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true`\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true`\n * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true`\n * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true`\n * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true`\n * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction png (options) {\n if (is.object(options)) {\n if (is.defined(options.progressive)) {\n this._setBooleanOption('pngProgressive', options.progressive);\n }\n if (is.defined(options.compressionLevel)) {\n if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) {\n this.options.pngCompressionLevel = options.compressionLevel;\n } else {\n throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel);\n }\n }\n if (is.defined(options.adaptiveFiltering)) {\n this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering);\n }\n const colours = options.colours || options.colors;\n if (is.defined(colours)) {\n if (is.integer(colours) && is.inRange(colours, 2, 256)) {\n this.options.pngBitdepth = bitdepthFromColourCount(colours);\n } else {\n throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);\n }\n }\n if (is.defined(options.palette)) {\n this._setBooleanOption('pngPalette', options.palette);\n } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) {\n this._setBooleanOption('pngPalette', true);\n }\n if (this.options.pngPalette) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) {\n this.options.pngQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) {\n this.options.pngEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);\n }\n }\n if (is.defined(options.dither)) {\n if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {\n this.options.pngDither = options.dither;\n } else {\n throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);\n }\n }\n }\n }\n return this._updateFormatOut('png', options);\n}\n\n/**\n * Use these WebP options for output image.\n *\n * @example\n * // Convert any input to lossless WebP output\n * const data = await sharp(input)\n * .webp({ lossless: true })\n * .toBuffer();\n *\n * @example\n * // Optimise the file size of an animated WebP\n * const outputWebp = await sharp(inputWebp, { animated: true })\n * .webp({ effort: 6 })\n * .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100\n * @param {boolean} [options.lossless=false] - use lossless compression mode\n * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode\n * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling\n * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow)\n * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow)\n * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction webp (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.webpQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.alphaQuality)) {\n if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) {\n this.options.webpAlphaQuality = options.alphaQuality;\n } else {\n throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality);\n }\n }\n if (is.defined(options.lossless)) {\n this._setBooleanOption('webpLossless', options.lossless);\n }\n if (is.defined(options.nearLossless)) {\n this._setBooleanOption('webpNearLossless', options.nearLossless);\n }\n if (is.defined(options.smartSubsample)) {\n this._setBooleanOption('webpSmartSubsample', options.smartSubsample);\n }\n if (is.defined(options.preset)) {\n if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {\n this.options.webpPreset = options.preset;\n } else {\n throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {\n this.options.webpEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort);\n }\n }\n if (is.defined(options.minSize)) {\n this._setBooleanOption('webpMinSize', options.minSize);\n }\n if (is.defined(options.mixed)) {\n this._setBooleanOption('webpMixed', options.mixed);\n }\n }\n trySetAnimationOptions(options, this.options);\n return this._updateFormatOut('webp', options);\n}\n\n/**\n * Use these GIF options for the output image.\n *\n * The first entry in the palette is reserved for transparency.\n *\n * The palette of the input image will be re-used if possible.\n *\n * @since 0.30.0\n *\n * @example\n * // Convert PNG to GIF\n * await sharp(pngBuffer)\n * .gif()\n * .toBuffer();\n *\n * @example\n * // Convert animated WebP to animated GIF\n * await sharp('animated.webp', { animated: true })\n * .toFile('animated.gif');\n *\n * @example\n * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF\n * const out = await sharp('in.gif', { animated: true })\n * .resize({ width: 128, height: 128 })\n * .gif({ dither: 0 })\n * .toBuffer();\n *\n * @example\n * // Lossy file size reduction of animated GIF\n * await sharp('in.gif', { animated: true })\n * .gif({ interFrameMaxError: 8 })\n * .toFile('optim.gif');\n *\n * @param {Object} [options] - output options\n * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow)\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256\n * @param {number} [options.colors=256] - alternative spelling of `options.colours`\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)\n * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)\n * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32\n * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction gif (options) {\n if (is.object(options)) {\n if (is.defined(options.reuse)) {\n this._setBooleanOption('gifReuse', options.reuse);\n }\n if (is.defined(options.progressive)) {\n this._setBooleanOption('gifProgressive', options.progressive);\n }\n const colours = options.colours || options.colors;\n if (is.defined(colours)) {\n if (is.integer(colours) && is.inRange(colours, 2, 256)) {\n this.options.gifBitdepth = bitdepthFromColourCount(colours);\n } else {\n throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);\n }\n }\n if (is.defined(options.effort)) {\n if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) {\n this.options.gifEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);\n }\n }\n if (is.defined(options.dither)) {\n if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {\n this.options.gifDither = options.dither;\n } else {\n throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);\n }\n }\n if (is.defined(options.interFrameMaxError)) {\n if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {\n this.options.gifInterFrameMaxError = options.interFrameMaxError;\n } else {\n throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);\n }\n }\n if (is.defined(options.interPaletteMaxError)) {\n if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {\n this.options.gifInterPaletteMaxError = options.interPaletteMaxError;\n } else {\n throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);\n }\n }\n }\n trySetAnimationOptions(options, this.options);\n return this._updateFormatOut('gif', options);\n}\n\n/* istanbul ignore next */\n/**\n * Use these JP2 options for output image.\n *\n * Requires libvips compiled with support for OpenJPEG.\n * The prebuilt binaries do not include this - see\n * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.\n *\n * @example\n * // Convert any input to lossless JP2 output\n * const data = await sharp(input)\n * .jp2({ lossless: true })\n * .toBuffer();\n *\n * @example\n * // Convert any input to very high quality JP2 output\n * const data = await sharp(input)\n * .jp2({\n * quality: 100,\n * chromaSubsampling: '4:4:4'\n * })\n * .toBuffer();\n *\n * @since 0.29.1\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression mode\n * @param {number} [options.tileWidth=512] - horizontal tile size\n * @param {number} [options.tileHeight=512] - vertical tile size\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jp2 (options) {\n if (!this.constructor.format.jp2k.output.buffer) {\n throw errJp2Save();\n }\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.jp2Quality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.lossless)) {\n if (is.bool(options.lossless)) {\n this.options.jp2Lossless = options.lossless;\n } else {\n throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n }\n }\n if (is.defined(options.tileWidth)) {\n if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) {\n this.options.jp2TileWidth = options.tileWidth;\n } else {\n throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth);\n }\n }\n if (is.defined(options.tileHeight)) {\n if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) {\n this.options.jp2TileHeight = options.tileHeight;\n } else {\n throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight);\n }\n }\n if (is.defined(options.chromaSubsampling)) {\n if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n this.options.jp2ChromaSubsampling = options.chromaSubsampling;\n } else {\n throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n }\n }\n }\n return this._updateFormatOut('jp2', options);\n}\n\n/**\n * Set animation options if available.\n * @private\n *\n * @param {Object} [source] - output options\n * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds)\n * @param {Object} [target] - target object for valid options\n * @throws {Error} Invalid options\n */\nfunction trySetAnimationOptions (source, target) {\n if (is.object(source) && is.defined(source.loop)) {\n if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) {\n target.loop = source.loop;\n } else {\n throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop);\n }\n }\n if (is.object(source) && is.defined(source.delay)) {\n // We allow singular values as well\n if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) {\n target.delay = [source.delay];\n } else if (\n Array.isArray(source.delay) &&\n source.delay.every(is.integer) &&\n source.delay.every(v => is.inRange(v, 0, 65535))) {\n target.delay = source.delay;\n } else {\n throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay);\n }\n }\n}\n\n/**\n * Use these TIFF options for output image.\n *\n * The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata}\n * instead of providing `xres` and `yres` in pixels/mm.\n *\n * @example\n * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output\n * sharp('input.svg')\n * .tiff({\n * compression: 'lzw',\n * bitdepth: 1\n * })\n * .toFile('1-bpp-output.tiff')\n * .then(info => { ... });\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format\n * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k\n * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float\n * @param {boolean} [options.pyramid=false] - write an image pyramid\n * @param {boolean} [options.tile=false] - write a tiled tiff\n * @param {number} [options.tileWidth=256] - horizontal tile size\n * @param {number} [options.tileHeight=256] - vertical tile size\n * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm\n * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm\n * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm\n * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit\n * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction tiff (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.tiffQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.bitdepth)) {\n if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) {\n this.options.tiffBitdepth = options.bitdepth;\n } else {\n throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth);\n }\n }\n // tiling\n if (is.defined(options.tile)) {\n this._setBooleanOption('tiffTile', options.tile);\n }\n if (is.defined(options.tileWidth)) {\n if (is.integer(options.tileWidth) && options.tileWidth > 0) {\n this.options.tiffTileWidth = options.tileWidth;\n } else {\n throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth);\n }\n }\n if (is.defined(options.tileHeight)) {\n if (is.integer(options.tileHeight) && options.tileHeight > 0) {\n this.options.tiffTileHeight = options.tileHeight;\n } else {\n throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);\n }\n }\n // miniswhite\n if (is.defined(options.miniswhite)) {\n this._setBooleanOption('tiffMiniswhite', options.miniswhite);\n }\n // pyramid\n if (is.defined(options.pyramid)) {\n this._setBooleanOption('tiffPyramid', options.pyramid);\n }\n // resolution\n if (is.defined(options.xres)) {\n if (is.number(options.xres) && options.xres > 0) {\n this.options.tiffXres = options.xres;\n } else {\n throw is.invalidParameterError('xres', 'number greater than zero', options.xres);\n }\n }\n if (is.defined(options.yres)) {\n if (is.number(options.yres) && options.yres > 0) {\n this.options.tiffYres = options.yres;\n } else {\n throw is.invalidParameterError('yres', 'number greater than zero', options.yres);\n }\n }\n // compression\n if (is.defined(options.compression)) {\n if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) {\n this.options.tiffCompression = options.compression;\n } else {\n throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression);\n }\n }\n // predictor\n if (is.defined(options.predictor)) {\n if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) {\n this.options.tiffPredictor = options.predictor;\n } else {\n throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor);\n }\n }\n // resolutionUnit\n if (is.defined(options.resolutionUnit)) {\n if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) {\n this.options.tiffResolutionUnit = options.resolutionUnit;\n } else {\n throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit);\n }\n }\n }\n return this._updateFormatOut('tiff', options);\n}\n\n/**\n * Use these AVIF options for output image.\n *\n * AVIF image sequences are not supported.\n * Prebuilt binaries support a bitdepth of 8 only.\n *\n * @example\n * const data = await sharp(input)\n * .avif({ effort: 2 })\n * .toBuffer();\n *\n * @example\n * const data = await sharp(input)\n * .avif({ lossless: true })\n * .toBuffer();\n *\n * @since 0.27.0\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=50] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction avif (options) {\n return this.heif({ ...options, compression: 'av1' });\n}\n\n/**\n * Use these HEIF options for output image.\n *\n * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a\n * globally-installed libvips compiled with support for libheif, libde265 and x265.\n *\n * @example\n * const data = await sharp(input)\n * .heif({ compression: 'hevc' })\n * .toBuffer();\n *\n * @since 0.23.0\n *\n * @param {Object} options - output options\n * @param {string} options.compression - compression format: av1, hevc\n * @param {number} [options.quality=50] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction heif (options) {\n if (is.object(options)) {\n if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {\n this.options.heifCompression = options.compression;\n } else {\n throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);\n }\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.heifQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.lossless)) {\n if (is.bool(options.lossless)) {\n this.options.heifLossless = options.lossless;\n } else {\n throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {\n this.options.heifEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort);\n }\n }\n if (is.defined(options.chromaSubsampling)) {\n if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n this.options.heifChromaSubsampling = options.chromaSubsampling;\n } else {\n throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n }\n }\n if (is.defined(options.bitdepth)) {\n if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {\n if (options.bitdepth !== 8 && this.constructor.versions.heif) {\n throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);\n }\n this.options.heifBitdepth = options.bitdepth;\n } else {\n throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);\n }\n }\n } else {\n throw is.invalidParameterError('options', 'Object', options);\n }\n return this._updateFormatOut('heif', options);\n}\n\n/**\n * Use these JPEG-XL (JXL) options for output image.\n *\n * This feature is experimental, please do not use in production systems.\n *\n * Requires libvips compiled with support for libjxl.\n * The prebuilt binaries do not include this - see\n * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.\n *\n * Image metadata (EXIF, XMP) is unsupported.\n *\n * @since 0.31.3\n *\n * @param {Object} [options] - output options\n * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality)\n * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified\n * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest)\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jxl (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644\n this.options.jxlDistance = options.quality >= 30\n ? 0.1 + (100 - options.quality) * 0.09\n : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n } else if (is.defined(options.distance)) {\n if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) {\n this.options.jxlDistance = options.distance;\n } else {\n throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance);\n }\n }\n if (is.defined(options.decodingTier)) {\n if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) {\n this.options.jxlDecodingTier = options.decodingTier;\n } else {\n throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier);\n }\n }\n if (is.defined(options.lossless)) {\n if (is.bool(options.lossless)) {\n this.options.jxlLossless = options.lossless;\n } else {\n throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) {\n this.options.jxlEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort);\n }\n }\n }\n return this._updateFormatOut('jxl', options);\n}\n\n/**\n * Force output to be raw, uncompressed pixel data.\n * Pixel ordering is left-to-right, top-to-bottom, without padding.\n * Channel ordering will be RGB or RGBA for non-greyscale colourspaces.\n *\n * @example\n * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input\n * const { data, info } = await sharp('input.jpg')\n * .raw()\n * .toBuffer({ resolveWithObject: true });\n *\n * @example\n * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input\n * const data = await sharp('input.png')\n * .ensureAlpha()\n * .extractChannel(3)\n * .toColourspace('b-w')\n * .raw({ depth: 'ushort' })\n * .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction raw (options) {\n if (is.object(options)) {\n if (is.defined(options.depth)) {\n if (is.string(options.depth) && is.inArray(options.depth,\n ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex']\n )) {\n this.options.rawDepth = options.depth;\n } else {\n throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth);\n }\n }\n }\n return this._updateFormatOut('raw');\n}\n\n/**\n * Use tile-based deep zoom (image pyramid) output.\n *\n * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions.\n * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format.\n *\n * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.\n *\n * Requires libvips compiled with support for libgsf.\n * The prebuilt binaries do not include this - see\n * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.\n *\n * @example\n * sharp('input.tiff')\n * .png()\n * .tile({\n * size: 512\n * })\n * .toFile('output.dz', function(err, info) {\n * // output.dzi is the Deep Zoom XML definition\n * // output_files contains 512x512 tiles grouped by zoom level\n * });\n *\n * @example\n * const zipFileWithTiles = await sharp(input)\n * .tile({ basename: \"tiles\" })\n * .toBuffer();\n *\n * @example\n * const iiififier = sharp().tile({ layout: \"iiif\" });\n * readableStream\n * .pipe(iiififier)\n * .pipe(writeableStream);\n *\n * @param {Object} [options]\n * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192.\n * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192.\n * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.\n * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.\n * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.\n * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise.\n * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).\n * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.\n * @param {boolean} [options.centre=false] centre image in tile.\n * @param {boolean} [options.center=false] alternative spelling of centre.\n * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json`\n * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction tile (options) {\n if (is.object(options)) {\n // Size of square tiles, in pixels\n if (is.defined(options.size)) {\n if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) {\n this.options.tileSize = options.size;\n } else {\n throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size);\n }\n }\n // Overlap of tiles, in pixels\n if (is.defined(options.overlap)) {\n if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) {\n if (options.overlap > this.options.tileSize) {\n throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap);\n }\n this.options.tileOverlap = options.overlap;\n } else {\n throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap);\n }\n }\n // Container\n if (is.defined(options.container)) {\n if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) {\n this.options.tileContainer = options.container;\n } else {\n throw is.invalidParameterError('container', 'one of: fs, zip', options.container);\n }\n }\n // Layout\n if (is.defined(options.layout)) {\n if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) {\n this.options.tileLayout = options.layout;\n } else {\n throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout);\n }\n }\n // Angle of rotation,\n if (is.defined(options.angle)) {\n if (is.integer(options.angle) && !(options.angle % 90)) {\n this.options.tileAngle = options.angle;\n } else {\n throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle);\n }\n }\n // Background colour\n this._setBackgroundColourOption('tileBackground', options.background);\n // Depth of tiles\n if (is.defined(options.depth)) {\n if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) {\n this.options.tileDepth = options.depth;\n } else {\n throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth);\n }\n }\n // Threshold to skip blank tiles\n if (is.defined(options.skipBlanks)) {\n if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) {\n this.options.tileSkipBlanks = options.skipBlanks;\n } else {\n throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks);\n }\n } else if (is.defined(options.layout) && options.layout === 'google') {\n this.options.tileSkipBlanks = 5;\n }\n // Center image in tile\n const centre = is.bool(options.center) ? options.center : options.centre;\n if (is.defined(centre)) {\n this._setBooleanOption('tileCentre', centre);\n }\n // @id attribute for IIIF layout\n if (is.defined(options.id)) {\n if (is.string(options.id)) {\n this.options.tileId = options.id;\n } else {\n throw is.invalidParameterError('id', 'string', options.id);\n }\n }\n // Basename for zip container\n if (is.defined(options.basename)) {\n if (is.string(options.basename)) {\n this.options.tileBasename = options.basename;\n } else {\n throw is.invalidParameterError('basename', 'string', options.basename);\n }\n }\n }\n // Format\n if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) {\n this.options.tileFormat = this.options.formatOut;\n } else if (this.options.formatOut !== 'input') {\n throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut);\n }\n return this._updateFormatOut('dz');\n}\n\n/**\n * Set a timeout for processing, in seconds.\n * Use a value of zero to continue processing indefinitely, the default behaviour.\n *\n * The clock starts when libvips opens an input image for processing.\n * Time spent waiting for a libuv thread to become available is not included.\n *\n * @example\n * // Ensure processing takes no longer than 3 seconds\n * try {\n * const data = await sharp(input)\n * .blur(1000)\n * .timeout({ seconds: 3 })\n * .toBuffer();\n * } catch (err) {\n * if (err.message.includes('timeout')) { ... }\n * }\n *\n * @since 0.29.2\n *\n * @param {Object} options\n * @param {number} options.seconds - Number of seconds after which processing will be stopped\n * @returns {Sharp}\n */\nfunction timeout (options) {\n if (!is.plainObject(options)) {\n throw is.invalidParameterError('options', 'object', options);\n }\n if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) {\n this.options.timeoutSeconds = options.seconds;\n } else {\n throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds);\n }\n return this;\n}\n\n/**\n * Update the output format unless options.force is false,\n * in which case revert to input format.\n * @private\n * @param {string} formatOut\n * @param {Object} [options]\n * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format\n * @returns {Sharp}\n */\nfunction _updateFormatOut (formatOut, options) {\n if (!(is.object(options) && options.force === false)) {\n this.options.formatOut = formatOut;\n }\n return this;\n}\n\n/**\n * Update a boolean attribute of the this.options Object.\n * @private\n * @param {string} key\n * @param {boolean} val\n * @throws {Error} Invalid key\n */\nfunction _setBooleanOption (key, val) {\n if (is.bool(val)) {\n this.options[key] = val;\n } else {\n throw is.invalidParameterError(key, 'boolean', val);\n }\n}\n\n/**\n * Called by a WriteableStream to notify us it is ready for data.\n * @private\n */\nfunction _read () {\n /* istanbul ignore else */\n if (!this.options.streamOut) {\n this.options.streamOut = true;\n const stack = Error();\n this._pipeline(undefined, stack);\n }\n}\n\n/**\n * Invoke the C++ image processing pipeline\n * Supports callback, stream and promise variants\n * @private\n */\nfunction _pipeline (callback, stack) {\n if (typeof callback === 'function') {\n // output=file/buffer\n if (this._isStreamInput()) {\n // output=file/buffer, input=stream\n this.on('finish', () => {\n this._flattenBufferIn();\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, data, info);\n }\n });\n });\n } else {\n // output=file/buffer, input=file/buffer\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, data, info);\n }\n });\n }\n return this;\n } else if (this.options.streamOut) {\n // output=stream\n if (this._isStreamInput()) {\n // output=stream, input=stream\n this.once('finish', () => {\n this._flattenBufferIn();\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n this.emit('error', is.nativeError(err, stack));\n } else {\n this.emit('info', info);\n this.push(data);\n }\n this.push(null);\n this.on('end', () => this.emit('close'));\n });\n });\n if (this.streamInFinished) {\n this.emit('finish');\n }\n } else {\n // output=stream, input=file/buffer\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n this.emit('error', is.nativeError(err, stack));\n } else {\n this.emit('info', info);\n this.push(data);\n }\n this.push(null);\n this.on('end', () => this.emit('close'));\n });\n }\n return this;\n } else {\n // output=promise\n if (this._isStreamInput()) {\n // output=promise, input=stream\n return new Promise((resolve, reject) => {\n this.once('finish', () => {\n this._flattenBufferIn();\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n if (this.options.resolveWithObject) {\n resolve({ data, info });\n } else {\n resolve(data);\n }\n }\n });\n });\n });\n } else {\n // output=promise, input=file/buffer\n return new Promise((resolve, reject) => {\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n if (this.options.resolveWithObject) {\n resolve({ data, info });\n } else {\n resolve(data);\n }\n }\n });\n });\n }\n }\n}\n\n/**\n * Decorate the Sharp prototype with output-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Public\n toFile,\n toBuffer,\n keepExif,\n withExif,\n withExifMerge,\n keepIccProfile,\n withIccProfile,\n keepMetadata,\n withMetadata,\n toFormat,\n jpeg,\n jp2,\n png,\n webp,\n tiff,\n avif,\n heif,\n jxl,\n gif,\n raw,\n tile,\n timeout,\n // Private\n _updateFormatOut,\n _setBooleanOption,\n _read,\n _pipeline\n });\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst events = require('node:events');\nconst detectLibc = require('detect-libc');\n\nconst is = require('./is');\nconst { runtimePlatformArch } = require('./libvips');\nconst sharp = require('./sharp');\n\nconst runtimePlatform = runtimePlatformArch();\nconst libvipsVersion = sharp.libvipsVersion();\n\n/**\n * An Object containing nested boolean values representing the available input and output formats/methods.\n * @member\n * @example\n * console.log(sharp.format);\n * @returns {Object}\n */\nconst format = sharp.format();\nformat.heif.output.alias = ['avif', 'heic'];\nformat.jpeg.output.alias = ['jpe', 'jpg'];\nformat.tiff.output.alias = ['tif'];\nformat.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx'];\n\n/**\n * An Object containing the available interpolators and their proper values\n * @readonly\n * @enum {string}\n */\nconst interpolators = {\n /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */\n nearest: 'nearest',\n /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */\n bilinear: 'bilinear',\n /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */\n bicubic: 'bicubic',\n /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some \"[acutance](http://en.wikipedia.org/wiki/Acutance)\" but typically reduces performance by a factor of 2. */\n locallyBoundedBicubic: 'lbb',\n /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */\n nohalo: 'nohalo',\n /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents \"staircasing\" when enlarging. */\n vertexSplitQuadraticBasisSpline: 'vsqbs'\n};\n\n/**\n * An Object containing the version numbers of sharp, libvips\n * and (when using prebuilt binaries) its dependencies.\n *\n * @member\n * @example\n * console.log(sharp.versions);\n */\nlet versions = {\n vips: libvipsVersion.semver\n};\n/* istanbul ignore next */\nif (!libvipsVersion.isGlobal) {\n if (!libvipsVersion.isWasm) {\n try {\n versions = require(`@img/sharp-${runtimePlatform}/versions`);\n } catch (_) {\n try {\n versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);\n } catch (_) {}\n }\n } else {\n try {\n versions = require('@img/sharp-wasm32/versions');\n } catch (_) {}\n }\n}\nversions.sharp = require('../package.json').version;\n\n/* istanbul ignore next */\nif (versions.heif && format.heif) {\n // Prebuilt binaries provide AV1\n format.heif.input.fileSuffix = ['.avif'];\n format.heif.output.alias = ['avif'];\n}\n\n/**\n * Gets or, when options are provided, sets the limits of _libvips'_ operation cache.\n * Existing entries in the cache will be trimmed after any change in limits.\n * This method always returns cache statistics,\n * useful for determining how much working memory is required for a particular task.\n *\n * @example\n * const stats = sharp.cache();\n * @example\n * sharp.cache( { items: 200 } );\n * sharp.cache( { files: 0 } );\n * sharp.cache(false);\n *\n * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching\n * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache\n * @param {number} [options.files=20] - is the maximum number of files to hold open\n * @param {number} [options.items=100] - is the maximum number of operations to cache\n * @returns {Object}\n */\nfunction cache (options) {\n if (is.bool(options)) {\n if (options) {\n // Default cache settings of 50MB, 20 files, 100 items\n return sharp.cache(50, 20, 100);\n } else {\n return sharp.cache(0, 0, 0);\n }\n } else if (is.object(options)) {\n return sharp.cache(options.memory, options.files, options.items);\n } else {\n return sharp.cache();\n }\n}\ncache(true);\n\n/**\n * Gets or, when a concurrency is provided, sets\n * the maximum number of threads _libvips_ should use to process _each image_.\n * These are from a thread pool managed by glib,\n * which helps avoid the overhead of creating new threads.\n *\n * This method always returns the current concurrency.\n *\n * The default value is the number of CPU cores,\n * except when using glibc-based Linux without jemalloc,\n * where the default is `1` to help reduce memory fragmentation.\n *\n * A value of `0` will reset this to the number of CPU cores.\n *\n * Some image format libraries spawn additional threads,\n * e.g. libaom manages its own 4 threads when encoding AVIF images,\n * and these are independent of the value set here.\n *\n * The maximum number of images that sharp can process in parallel\n * is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,\n * which defaults to 4.\n *\n * https://nodejs.org/api/cli.html#uv_threadpool_sizesize\n *\n * For example, by default, a machine with 8 CPU cores will process\n * 4 images in parallel and use up to 8 threads per image,\n * so there will be up to 32 concurrent threads.\n *\n * @example\n * const threads = sharp.concurrency(); // 4\n * sharp.concurrency(2); // 2\n * sharp.concurrency(0); // 4\n *\n * @param {number} [concurrency]\n * @returns {number} concurrency\n */\nfunction concurrency (concurrency) {\n return sharp.concurrency(is.integer(concurrency) ? concurrency : null);\n}\n/* istanbul ignore next */\nif (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {\n // Reduce default concurrency to 1 when using glibc memory allocator\n sharp.concurrency(1);\n} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {\n // Reduce default concurrency when musl thread over-subscription detected\n sharp.concurrency(require('node:os').availableParallelism());\n}\n\n/**\n * An EventEmitter that emits a `change` event when a task is either:\n * - queued, waiting for _libuv_ to provide a worker thread\n * - complete\n * @member\n * @example\n * sharp.queue.on('change', function(queueLength) {\n * console.log('Queue contains ' + queueLength + ' task(s)');\n * });\n */\nconst queue = new events.EventEmitter();\n\n/**\n * Provides access to internal task counters.\n * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.\n * - process is the number of resize tasks currently being processed.\n *\n * @example\n * const counters = sharp.counters(); // { queue: 2, process: 4 }\n *\n * @returns {Object}\n */\nfunction counters () {\n return sharp.counters();\n}\n\n/**\n * Get and set use of SIMD vector unit instructions.\n * Requires libvips to have been compiled with highway support.\n *\n * Improves the performance of `resize`, `blur` and `sharpen` operations\n * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.\n *\n * @example\n * const simd = sharp.simd();\n * // simd is `true` if the runtime use of highway is currently enabled\n * @example\n * const simd = sharp.simd(false);\n * // prevent libvips from using highway at runtime\n *\n * @param {boolean} [simd=true]\n * @returns {boolean}\n */\nfunction simd (simd) {\n return sharp.simd(is.bool(simd) ? simd : null);\n}\n\n/**\n * Block libvips operations at runtime.\n *\n * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,\n * which when set will block all \"untrusted\" operations.\n *\n * @since 0.32.4\n *\n * @example <caption>Block all TIFF input.</caption>\n * sharp.block({\n * operation: ['VipsForeignLoadTiff']\n * });\n *\n * @param {Object} options\n * @param {Array<string>} options.operation - List of libvips low-level operation names to block.\n */\nfunction block (options) {\n if (is.object(options)) {\n if (Array.isArray(options.operation) && options.operation.every(is.string)) {\n sharp.block(options.operation, true);\n } else {\n throw is.invalidParameterError('operation', 'Array<string>', options.operation);\n }\n } else {\n throw is.invalidParameterError('options', 'object', options);\n }\n}\n\n/**\n * Unblock libvips operations at runtime.\n *\n * This is useful for defining a list of allowed operations.\n *\n * @since 0.32.4\n *\n * @example <caption>Block all input except WebP from the filesystem.</caption>\n * sharp.block({\n * operation: ['VipsForeignLoad']\n * });\n * sharp.unblock({\n * operation: ['VipsForeignLoadWebpFile']\n * });\n *\n * @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>\n * sharp.block({\n * operation: ['VipsForeignLoad']\n * });\n * sharp.unblock({\n * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']\n * });\n *\n * @param {Object} options\n * @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.\n */\nfunction unblock (options) {\n if (is.object(options)) {\n if (Array.isArray(options.operation) && options.operation.every(is.string)) {\n sharp.block(options.operation, false);\n } else {\n throw is.invalidParameterError('operation', 'Array<string>', options.operation);\n }\n } else {\n throw is.invalidParameterError('options', 'object', options);\n }\n}\n\n/**\n * Decorate the Sharp class with utility-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Sharp.cache = cache;\n Sharp.concurrency = concurrency;\n Sharp.counters = counters;\n Sharp.simd = simd;\n Sharp.format = format;\n Sharp.interpolators = interpolators;\n Sharp.versions = versions;\n Sharp.queue = queue;\n Sharp.block = block;\n Sharp.unblock = unblock;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst Sharp = require('./constructor');\nrequire('./input')(Sharp);\nrequire('./resize')(Sharp);\nrequire('./composite')(Sharp);\nrequire('./operation')(Sharp);\nrequire('./colour')(Sharp);\nrequire('./channel')(Sharp);\nrequire('./output')(Sharp);\nrequire('./utility')(Sharp);\n\nmodule.exports = Sharp;\n","/**\n * Image Format Detection\n *\n * Detect image format from magic bytes.\n */\n\n/**\n * Supported image formats\n */\nexport type ImageFormat = 'png' | 'jpeg' | 'webp' | 'gif' | 'avif';\n\n/**\n * Magic bytes for each format\n */\nconst MAGIC_BYTES: Record<ImageFormat, { bytes: number[]; offset?: number; check?: number[] }> = {\n png: { bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] },\n jpeg: { bytes: [0xff, 0xd8, 0xff] },\n gif: { bytes: [0x47, 0x49, 0x46, 0x38] }, // GIF8\n webp: { bytes: [0x52, 0x49, 0x46, 0x46], offset: 8, check: [0x57, 0x45, 0x42, 0x50] }, // RIFF....WEBP\n avif: { bytes: [0x00, 0x00, 0x00], offset: 4, check: [0x66, 0x74, 0x79, 0x70] }, // ....ftyp (then check for avif/avis)\n};\n\n/**\n * Detect image format from magic bytes.\n *\n * @param buffer - Image data\n * @returns Detected format, or null if not recognized\n */\nexport function detectImageFormat(buffer: Uint8Array): ImageFormat | null {\n if (buffer.length < 12) return null;\n\n // Check PNG\n if (matchesBytes(buffer, MAGIC_BYTES.png.bytes)) {\n return 'png';\n }\n\n // Check JPEG\n if (matchesBytes(buffer, MAGIC_BYTES.jpeg.bytes)) {\n return 'jpeg';\n }\n\n // Check GIF\n if (matchesBytes(buffer, MAGIC_BYTES.gif.bytes)) {\n return 'gif';\n }\n\n // Check WebP (RIFF....WEBP)\n if (\n matchesBytes(buffer, MAGIC_BYTES.webp.bytes) &&\n matchesBytes(buffer, MAGIC_BYTES.webp.check!, MAGIC_BYTES.webp.offset!)\n ) {\n return 'webp';\n }\n\n // Check AVIF (....ftyp then avif or avis brand)\n if (matchesBytes(buffer, MAGIC_BYTES.avif.check!, MAGIC_BYTES.avif.offset!)) {\n // AVIF uses ftyp box with 'avif' or 'avis' brand\n const brand = String.fromCharCode(...buffer.slice(8, 12));\n if (brand === 'avif' || brand === 'avis' || brand === 'mif1' || brand === 'miaf') {\n return 'avif';\n }\n }\n\n return null;\n}\n\n/**\n * Check if buffer starts with given bytes at offset\n */\nfunction matchesBytes(buffer: Uint8Array, bytes: number[], offset = 0): boolean {\n if (buffer.length < offset + bytes.length) return false;\n for (let i = 0; i < bytes.length; i++) {\n if (buffer[offset + i] !== bytes[i]) return false;\n }\n return true;\n}\n\n/**\n * Get MIME type for image format\n */\nexport function getMimeType(format: ImageFormat): string {\n const mimeTypes: Record<ImageFormat, string> = {\n png: 'image/png',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n avif: 'image/avif',\n };\n return mimeTypes[format];\n}\n\n/**\n * Get file extension for image format\n */\nexport function getExtension(format: ImageFormat): string {\n const extensions: Record<ImageFormat, string> = {\n png: 'png',\n jpeg: 'jpg',\n webp: 'webp',\n gif: 'gif',\n avif: 'avif',\n };\n return extensions[format];\n}\n","/**\n * Image Dimensions Detection\n *\n * Get image dimensions without fully decoding the image.\n * Reads only the header bytes needed to determine dimensions.\n */\n\nimport { detectImageFormat, type ImageFormat } from './format.js';\n\n/**\n * Image dimensions result\n */\nexport interface ImageDimensions {\n width: number;\n height: number;\n format: ImageFormat;\n}\n\n/**\n * Get image dimensions without fully decoding the image.\n *\n * Reads only the header bytes needed to determine dimensions.\n *\n * @param buffer - Image data\n * @returns Dimensions and format, or null if not recognized\n */\nexport function getImageDimensions(buffer: Uint8Array): ImageDimensions | null {\n const format = detectImageFormat(buffer);\n if (!format) return null;\n\n switch (format) {\n case 'png':\n return getPngDimensions(buffer);\n case 'jpeg':\n return getJpegDimensions(buffer);\n case 'gif':\n return getGifDimensions(buffer);\n case 'webp':\n return getWebpDimensions(buffer);\n case 'avif':\n return getAvifDimensions(buffer);\n default:\n return null;\n }\n}\n\n/**\n * Get PNG dimensions from IHDR chunk\n */\nfunction getPngDimensions(buffer: Uint8Array): ImageDimensions | null {\n // PNG structure: signature (8 bytes) + IHDR chunk\n // IHDR: length (4) + type (4) + width (4) + height (4) + ...\n if (buffer.length < 24) return null;\n\n // Verify IHDR chunk type at offset 12\n const ihdr = String.fromCharCode(buffer[12]!, buffer[13]!, buffer[14]!, buffer[15]!);\n if (ihdr !== 'IHDR') return null;\n\n // Width and height are big-endian at offset 16 and 20\n const width = readUint32BE(buffer, 16);\n const height = readUint32BE(buffer, 20);\n\n if (width <= 0 || height <= 0) return null;\n\n return { width, height, format: 'png' };\n}\n\n/**\n * Get JPEG dimensions by parsing SOF markers\n */\nfunction getJpegDimensions(buffer: Uint8Array): ImageDimensions | null {\n if (buffer.length < 4) return null;\n\n let offset = 2; // Skip SOI marker\n\n while (offset < buffer.length - 8) {\n // Look for marker\n if (buffer[offset] !== 0xff) {\n offset++;\n continue;\n }\n\n const marker = buffer[offset + 1]!;\n\n // SOF markers (except SOF4 which is DHT)\n // SOF0-SOF3, SOF5-SOF7, SOF9-SOF11, SOF13-SOF15\n const isSOF =\n (marker >= 0xc0 && marker <= 0xc3) ||\n (marker >= 0xc5 && marker <= 0xc7) ||\n (marker >= 0xc9 && marker <= 0xcb) ||\n (marker >= 0xcd && marker <= 0xcf);\n\n if (isSOF) {\n // SOF: FF Cx LL LL P HH HH WW WW\n // Length at offset+2 (2 bytes), precision at offset+4\n // Height at offset+5 (2 bytes), Width at offset+7 (2 bytes)\n if (offset + 9 >= buffer.length) return null;\n\n const height = readUint16BE(buffer, offset + 5);\n const width = readUint16BE(buffer, offset + 7);\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'jpeg' };\n }\n }\n\n // Skip to next marker\n if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) {\n // Standalone markers\n offset += 2;\n } else if (marker === 0xff) {\n // Padding\n offset++;\n } else {\n // Skip segment\n const segmentLength = readUint16BE(buffer, offset + 2);\n offset += 2 + segmentLength;\n }\n }\n\n return null;\n}\n\n/**\n * Get GIF dimensions from logical screen descriptor\n */\nfunction getGifDimensions(buffer: Uint8Array): ImageDimensions | null {\n // GIF: signature (6) + logical screen descriptor (7)\n // Width at offset 6 (2 bytes LE), Height at offset 8 (2 bytes LE)\n if (buffer.length < 10) return null;\n\n const width = readUint16LE(buffer, 6);\n const height = readUint16LE(buffer, 8);\n\n if (width <= 0 || height <= 0) return null;\n\n return { width, height, format: 'gif' };\n}\n\n/**\n * Get WebP dimensions\n */\nfunction getWebpDimensions(buffer: Uint8Array): ImageDimensions | null {\n if (buffer.length < 30) return null;\n\n // Check for VP8 chunk at offset 12\n const chunk = String.fromCharCode(buffer[12]!, buffer[13]!, buffer[14]!, buffer[15]!);\n\n if (chunk === 'VP8 ') {\n // Lossy WebP: VP8 bitstream\n // Frame tag at offset 20, then 3-byte frame tag, then dimensions\n if (buffer.length < 30) return null;\n\n // Skip to frame dimensions (after signature)\n const width = (buffer[26]! | (buffer[27]! << 8)) & 0x3fff;\n const height = (buffer[28]! | (buffer[29]! << 8)) & 0x3fff;\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'webp' };\n }\n } else if (chunk === 'VP8L') {\n // Lossless WebP\n if (buffer.length < 25) return null;\n\n // Signature byte at offset 20, then dimensions packed in 4 bytes\n const bits = readUint32LE(buffer, 21);\n const width = (bits & 0x3fff) + 1;\n const height = ((bits >> 14) & 0x3fff) + 1;\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'webp' };\n }\n } else if (chunk === 'VP8X') {\n // Extended WebP with VP8X chunk\n if (buffer.length < 30) return null;\n\n // Canvas dimensions at offset 24 (3 bytes each, LE, +1)\n const width =\n (buffer[24]! | (buffer[25]! << 8) | (buffer[26]! << 16)) + 1;\n const height =\n (buffer[27]! | (buffer[28]! << 8) | (buffer[29]! << 16)) + 1;\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'webp' };\n }\n }\n\n return null;\n}\n\n/**\n * Get AVIF dimensions from ISPE box\n * AVIF uses HEIF container format with ISOBMFF boxes\n */\nfunction getAvifDimensions(buffer: Uint8Array): ImageDimensions | null {\n // This is a simplified parser - AVIF uses complex ISOBMFF structure\n // For a complete implementation, we'd need to parse the full box structure\n // Here we search for the ispe (image spatial extents) box\n\n if (buffer.length < 32) return null;\n\n // Search for 'ispe' box marker\n for (let i = 0; i < buffer.length - 16; i++) {\n if (\n buffer[i] === 0x69 && // 'i'\n buffer[i + 1] === 0x73 && // 's'\n buffer[i + 2] === 0x70 && // 'p'\n buffer[i + 3] === 0x65 // 'e'\n ) {\n // Found ispe box, dimensions are at offset +4 (version/flags) +4 (width) +4 (height)\n // ispe structure: type (4) + version (1) + flags (3) + width (4) + height (4)\n const offset = i + 4; // Skip 'ispe'\n if (offset + 12 > buffer.length) continue;\n\n const width = readUint32BE(buffer, offset + 4);\n const height = readUint32BE(buffer, offset + 8);\n\n if (width > 0 && height > 0 && width < 65536 && height < 65536) {\n return { width, height, format: 'avif' };\n }\n }\n }\n\n return null;\n}\n\n/**\n * Read big-endian uint32\n */\nfunction readUint32BE(buffer: Uint8Array, offset: number): number {\n return (\n ((buffer[offset]! << 24) |\n (buffer[offset + 1]! << 16) |\n (buffer[offset + 2]! << 8) |\n buffer[offset + 3]!) >>>\n 0\n );\n}\n\n/**\n * Read big-endian uint16\n */\nfunction readUint16BE(buffer: Uint8Array, offset: number): number {\n return (buffer[offset]! << 8) | buffer[offset + 1]!;\n}\n\n/**\n * Read little-endian uint16\n */\nfunction readUint16LE(buffer: Uint8Array, offset: number): number {\n return buffer[offset]! | (buffer[offset + 1]! << 8);\n}\n\n/**\n * Read little-endian uint32\n */\nfunction readUint32LE(buffer: Uint8Array, offset: number): number {\n return (\n (buffer[offset]! |\n (buffer[offset + 1]! << 8) |\n (buffer[offset + 2]! << 16) |\n (buffer[offset + 3]! << 24)) >>>\n 0\n );\n}\n","/**\n * Thumbnail Generation\n *\n * Create thumbnails from image data.\n * Works in both Node.js (sharp) and browser (canvas) environments.\n */\n\nimport { detectImageFormat, getMimeType, type ImageFormat } from './format.js';\nimport { getImageDimensions } from './dimensions.js';\nimport { ValidationError, ParseError } from '@character-foundry/core';\n\n/**\n * Thumbnail generation options\n */\nexport interface ThumbnailOptions {\n /** Maximum dimension (width or height). Default: 400 */\n maxSize?: number;\n /** Output format. Default: 'webp' */\n format?: 'webp' | 'jpeg' | 'png';\n /** Quality (0-1). Default: 0.8 */\n quality?: number;\n /** Fallback format if primary unsupported. Default: 'jpeg' */\n fallbackFormat?: 'jpeg' | 'png';\n /** Timeout in ms. Default: 10000 */\n timeout?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<ThumbnailOptions> = {\n maxSize: 400,\n format: 'webp',\n quality: 0.8,\n fallbackFormat: 'jpeg',\n timeout: 10000,\n};\n\n/**\n * Check if we're in Node.js environment\n */\nconst isNode = typeof window === 'undefined' && typeof process !== 'undefined';\n\n/**\n * Create a thumbnail from image data.\n *\n * Works in both Node.js (sharp) and browser (canvas) environments.\n *\n * @param imageData - Source image data\n * @param options - Thumbnail options\n * @returns Thumbnail image data\n */\nexport async function createThumbnail(\n imageData: Uint8Array,\n options: ThumbnailOptions = {}\n): Promise<Uint8Array> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n // Verify input is a valid image\n const format = detectImageFormat(imageData);\n if (!format) {\n throw new ValidationError('Input is not a recognized image format', 'imageData');\n }\n\n // Get dimensions to check if resize is needed\n const dims = getImageDimensions(imageData);\n if (!dims) {\n throw new ParseError('Could not determine image dimensions');\n }\n\n // Check if resize is needed\n const needsResize = dims.width > opts.maxSize || dims.height > opts.maxSize;\n\n if (isNode) {\n return createThumbnailNode(imageData, opts, needsResize);\n } else {\n return createThumbnailBrowser(imageData, opts, needsResize, format);\n }\n}\n\n/**\n * Create thumbnail using sharp (Node.js)\n */\nasync function createThumbnailNode(\n imageData: Uint8Array,\n options: Required<ThumbnailOptions>,\n needsResize: boolean\n): Promise<Uint8Array> {\n // Dynamically import sharp\n let sharp: typeof import('sharp');\n try {\n sharp = (await import('sharp')).default;\n } catch {\n throw new ValidationError(\n 'sharp is required for thumbnail generation in Node.js. Install with: npm install sharp',\n 'dependency'\n );\n }\n\n let pipeline = sharp(Buffer.from(imageData));\n\n if (needsResize) {\n pipeline = pipeline.resize(options.maxSize, options.maxSize, {\n fit: 'inside',\n withoutEnlargement: true,\n });\n }\n\n // Apply format conversion\n const quality = Math.round(options.quality * 100);\n\n switch (options.format) {\n case 'webp':\n pipeline = pipeline.webp({ quality });\n break;\n case 'jpeg':\n pipeline = pipeline.jpeg({ quality });\n break;\n case 'png':\n pipeline = pipeline.png({ compressionLevel: 9 });\n break;\n }\n\n const result = await pipeline.toBuffer();\n return new Uint8Array(result);\n}\n\n/**\n * Create thumbnail using Canvas API (Browser)\n */\nasync function createThumbnailBrowser(\n imageData: Uint8Array,\n options: Required<ThumbnailOptions>,\n needsResize: boolean,\n inputFormat: ImageFormat\n): Promise<Uint8Array> {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(`Thumbnail generation timed out after ${options.timeout}ms`));\n }, options.timeout);\n\n try {\n // Create blob from image data\n const mimeType = getMimeType(inputFormat);\n // Need to slice to handle potential SharedArrayBuffer\n const blob = new Blob([new Uint8Array(imageData)], { type: mimeType });\n const url = URL.createObjectURL(blob);\n\n const img = new Image();\n\n img.onload = () => {\n clearTimeout(timeoutId);\n URL.revokeObjectURL(url);\n\n try {\n // Calculate target dimensions\n let targetWidth = img.width;\n let targetHeight = img.height;\n\n if (needsResize) {\n const scale = Math.min(\n options.maxSize / img.width,\n options.maxSize / img.height\n );\n targetWidth = Math.round(img.width * scale);\n targetHeight = Math.round(img.height * scale);\n }\n\n // Create canvas and draw\n const canvas = document.createElement('canvas');\n canvas.width = targetWidth;\n canvas.height = targetHeight;\n\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n reject(new Error('Could not get canvas context'));\n return;\n }\n\n ctx.drawImage(img, 0, 0, targetWidth, targetHeight);\n\n // Try to export in requested format\n let outputMimeType = `image/${options.format}`;\n let dataUrl = canvas.toDataURL(outputMimeType, options.quality);\n\n // Check if format was supported (canvas falls back to PNG if unsupported)\n if (!dataUrl.startsWith(`data:${outputMimeType}`) && options.format === 'webp') {\n // WebP not supported, use fallback\n outputMimeType = `image/${options.fallbackFormat}`;\n dataUrl = canvas.toDataURL(outputMimeType, options.quality);\n }\n\n // Convert data URL to Uint8Array\n const base64 = dataUrl.split(',')[1]!;\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n\n resolve(bytes);\n } catch (err) {\n reject(err);\n }\n };\n\n img.onerror = () => {\n clearTimeout(timeoutId);\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n };\n\n img.src = url;\n } catch (err) {\n clearTimeout(timeoutId);\n reject(err);\n }\n });\n}\n\n/**\n * Calculate target dimensions while preserving aspect ratio\n */\nexport function calculateThumbnailDimensions(\n width: number,\n height: number,\n maxSize: number\n): { width: number; height: number } {\n if (width <= maxSize && height <= maxSize) {\n return { width, height };\n }\n\n const scale = Math.min(maxSize / width, maxSize / height);\n return {\n width: Math.round(width * scale),\n height: Math.round(height * scale),\n };\n}\n","/**\n * Common Types\n *\n * Shared types used across all card formats.\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * ISO 8601 date string schema\n */\nexport const ISO8601Schema = z.string().datetime();\n\n/**\n * UUID string schema\n */\nexport const UUIDSchema = z.string().uuid();\n\n/**\n * Card specification version schema\n */\nexport const SpecSchema = z.enum(['v2', 'v3']);\n\n/**\n * Source format identifier schema\n */\nexport const SourceFormatSchema = z.enum([\n 'png_v2', // PNG with 'chara' chunk (v2)\n 'png_v3', // PNG with 'ccv3' chunk (v3)\n 'json_v2', // Raw JSON v2\n 'json_v3', // Raw JSON v3\n 'charx', // ZIP with card.json (v3 spec)\n 'charx_risu', // ZIP with card.json + module.risum\n 'charx_jpeg', // JPEG with appended ZIP (read-only)\n 'voxta', // VoxPkg format\n]);\n\n/**\n * Original JSON shape schema\n */\nexport const OriginalShapeSchema = z.enum(['wrapped', 'unwrapped', 'legacy']);\n\n/**\n * Asset type identifier schema\n */\nexport const AssetTypeSchema = z.enum([\n 'icon',\n 'background',\n 'emotion',\n 'user_icon',\n 'sound',\n 'video',\n 'custom',\n 'x-risu-asset',\n]);\n\n/**\n * Asset descriptor schema (v3 spec)\n */\nexport const AssetDescriptorSchema = z.object({\n type: AssetTypeSchema,\n uri: z.string(),\n name: z.string(),\n ext: z.string(),\n});\n\n/**\n * Extracted asset with binary data schema\n */\nexport const ExtractedAssetSchema = z.object({\n descriptor: AssetDescriptorSchema,\n data: z.instanceof(Uint8Array),\n mimeType: z.string(),\n});\n\n// ============================================================================\n// TypeScript Types (inferred from Zod schemas)\n// ============================================================================\n\n/**\n * ISO 8601 date string\n */\nexport type ISO8601 = z.infer<typeof ISO8601Schema>;\n\n/**\n * UUID string\n */\nexport type UUID = z.infer<typeof UUIDSchema>;\n\n/**\n * Card specification version\n */\nexport type Spec = z.infer<typeof SpecSchema>;\n\n/**\n * Source format identifier\n */\nexport type SourceFormat = z.infer<typeof SourceFormatSchema>;\n\n/**\n * Original JSON shape\n */\nexport type OriginalShape = z.infer<typeof OriginalShapeSchema>;\n\n/**\n * Asset type identifier\n */\nexport type AssetType = z.infer<typeof AssetTypeSchema>;\n\n/**\n * Asset descriptor (v3 spec)\n */\nexport type AssetDescriptor = z.infer<typeof AssetDescriptorSchema>;\n\n/**\n * Extracted asset with binary data\n */\nexport type ExtractedAsset = z.infer<typeof ExtractedAssetSchema>;\n","/**\n * Character Card v2 Types\n *\n * Based on: https://github.com/malfoyslastname/character-card-spec-v2\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Lorebook entry schema for v2 cards\n */\nexport const CCv2LorebookEntrySchema = z.object({\n keys: z.array(z.string()).optional(), // Some tools use 'key' instead\n content: z.string(),\n enabled: z.boolean().default(true), // Default to enabled if missing\n insertion_order: z.preprocess((v) => v ?? 0, z.number().int()),\n // Optional fields - be lenient with nulls since wild data has them\n extensions: z.record(z.unknown()).optional(),\n case_sensitive: z.boolean().nullable().optional(),\n name: z.string().optional(),\n priority: z.number().int().nullable().optional(),\n id: z.number().int().nullable().optional(),\n comment: z.string().nullable().optional(),\n selective: z.boolean().nullable().optional(),\n secondary_keys: z.array(z.string()).nullable().optional(),\n constant: z.boolean().nullable().optional(),\n position: z.union([z.enum(['before_char', 'after_char', 'in_chat']), z.number().int(), z.literal('')]).nullable().optional(),\n}).passthrough(); // Allow SillyTavern extensions like depth, probability, etc.\n\n/**\n * Character book (lorebook) schema for v2 cards\n */\nexport const CCv2CharacterBookSchema = z.object({\n name: z.string().optional(),\n description: z.string().optional(),\n scan_depth: z.number().int().nonnegative().optional(),\n token_budget: z.number().int().nonnegative().optional(),\n recursive_scanning: z.boolean().optional(),\n extensions: z.record(z.unknown()).optional(),\n entries: z.array(CCv2LorebookEntrySchema),\n});\n\n/**\n * Character Card v2 data structure schema\n */\nexport const CCv2DataSchema = z.object({\n // Core fields - use .default('') to handle missing fields in malformed cards\n name: z.string().default(''),\n description: z.string().default(''),\n personality: z.string().nullable().default(''), // Can be null in wild (141 cards)\n scenario: z.string().default(''),\n first_mes: z.string().default(''),\n mes_example: z.string().nullable().default(''), // Can be null in wild (186 cards)\n // Optional fields\n creator_notes: z.string().optional(),\n system_prompt: z.string().optional(),\n post_history_instructions: z.string().optional(),\n alternate_greetings: z.array(z.string()).optional(),\n character_book: CCv2CharacterBookSchema.optional().nullable(),\n tags: z.array(z.string()).optional(),\n creator: z.string().optional(),\n character_version: z.string().optional(),\n extensions: z.record(z.unknown()).optional(),\n});\n\n/**\n * Wrapped v2 card format schema (modern tools)\n */\nexport const CCv2WrappedSchema = z.object({\n spec: z.literal('chara_card_v2'),\n spec_version: z.literal('2.0'),\n data: CCv2DataSchema,\n});\n\n// ============================================================================\n// TypeScript Types (inferred from Zod schemas)\n// ============================================================================\n\n/**\n * Lorebook entry for v2 cards\n */\nexport type CCv2LorebookEntry = z.infer<typeof CCv2LorebookEntrySchema>;\n\n/**\n * Character book (lorebook) for v2 cards\n */\nexport type CCv2CharacterBook = z.infer<typeof CCv2CharacterBookSchema>;\n\n/**\n * Character Card v2 data structure\n */\nexport type CCv2Data = z.infer<typeof CCv2DataSchema>;\n\n/**\n * Wrapped v2 card format (modern tools)\n */\nexport type CCv2Wrapped = z.infer<typeof CCv2WrappedSchema>;\n\n// ============================================================================\n// Type Guards & Parsers\n// ============================================================================\n\n/**\n * Check if data is a wrapped v2 card\n */\nexport function isWrappedV2(data: unknown): data is CCv2Wrapped {\n return CCv2WrappedSchema.safeParse(data).success;\n}\n\n/**\n * Check if data looks like v2 card data (wrapped or unwrapped)\n */\nexport function isV2CardData(data: unknown): data is CCv2Data | CCv2Wrapped {\n return (\n CCv2WrappedSchema.safeParse(data).success ||\n CCv2DataSchema.safeParse(data).success\n );\n}\n\n/**\n * Parse and validate a wrapped v2 card\n */\nexport function parseWrappedV2(data: unknown): CCv2Wrapped {\n return CCv2WrappedSchema.parse(data);\n}\n\n/**\n * Parse and validate v2 card data\n */\nexport function parseV2Data(data: unknown): CCv2Data {\n return CCv2DataSchema.parse(data);\n}\n\n/**\n * Check if data looks like a wrapped V2 card structurally (without strict validation).\n * This is more lenient than isWrappedV2 - it just checks structure, not full schema validity.\n */\nexport function looksLikeWrappedV2(data: unknown): data is { spec: string; data: Record<string, unknown> } {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return (\n obj.spec === 'chara_card_v2' &&\n obj.data !== null &&\n typeof obj.data === 'object'\n );\n}\n\n/**\n * Get v2 card data from wrapped or unwrapped format.\n *\n * Uses structural check instead of strict Zod validation to handle\n * malformed cards that have the right structure but missing/invalid fields.\n * The caller (e.g., ccv2ToCCv3) handles defaulting missing fields.\n */\nexport function getV2Data(card: CCv2Data | CCv2Wrapped): CCv2Data {\n // Use structural check - more lenient than isWrappedV2 schema validation\n if (looksLikeWrappedV2(card)) {\n return card.data as CCv2Data;\n }\n return card;\n}\n","/**\n * Character Card v3 Types\n *\n * Based on: https://github.com/kwaroran/character-card-spec-v3\n */\n\nimport { z } from 'zod';\nimport { AssetDescriptorSchema } from './common.js';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Lorebook entry schema for v3 cards\n */\nexport const CCv3LorebookEntrySchema = z.object({\n keys: z.array(z.string()).optional(), // Some tools use 'key' instead\n content: z.string(),\n enabled: z.boolean().default(true), // Default to enabled if missing\n insertion_order: z.preprocess((v) => v ?? 0, z.number().int()),\n // Optional fields - be lenient with nulls since wild data has them\n case_sensitive: z.boolean().nullable().optional(),\n name: z.string().optional(),\n priority: z.number().int().nullable().optional(),\n id: z.number().int().nullable().optional(),\n comment: z.string().nullable().optional(),\n selective: z.boolean().nullable().optional(),\n secondary_keys: z.array(z.string()).nullable().optional(),\n constant: z.boolean().nullable().optional(),\n position: z.union([z.enum(['before_char', 'after_char', 'in_chat']), z.number().int(), z.literal('')]).nullable().optional(),\n extensions: z.record(z.unknown()).optional(),\n // v3 specific - also lenient with types since SillyTavern uses numbers for enums\n automation_id: z.string().optional(),\n role: z.union([z.enum(['system', 'user', 'assistant']), z.number().int()]).nullable().optional(),\n group: z.string().optional(),\n scan_frequency: z.number().int().nonnegative().optional(),\n probability: z.number().min(0).max(100).optional(), // Some tools use 0-100 instead of 0-1\n use_regex: z.boolean().optional(),\n depth: z.number().int().nonnegative().optional(),\n selective_logic: z.union([z.enum(['AND', 'NOT']), z.number().int()]).optional(),\n}).passthrough(); // Allow tool-specific extensions\n\n/**\n * Character book (lorebook) schema for v3 cards\n */\nexport const CCv3CharacterBookSchema = z.object({\n name: z.string().optional(),\n description: z.string().optional(),\n scan_depth: z.number().int().nonnegative().optional(),\n token_budget: z.number().int().nonnegative().optional(),\n recursive_scanning: z.boolean().optional(),\n extensions: z.record(z.unknown()).optional(),\n entries: z.array(CCv3LorebookEntrySchema),\n});\n\n/**\n * Character Card v3 inner data structure schema.\n *\n * Note: Fields like group_only_greetings, creator, character_version, and tags\n * are technically \"required\" per V3 spec but rarely present in wild cards.\n * We use .default() to make parsing lenient while still producing valid output.\n */\nexport const CCv3DataInnerSchema = z.object({\n // Core fields - use .default('') to handle missing fields in malformed cards\n name: z.string().default(''),\n description: z.string().default(''),\n personality: z.string().nullable().default(''), // Can be null in wild (141 cards)\n scenario: z.string().default(''),\n first_mes: z.string().default(''),\n mes_example: z.string().nullable().default(''), // Can be null in wild (186 cards)\n // \"Required\" per spec but often missing in wild - use defaults for leniency\n creator: z.string().default(''),\n character_version: z.string().default(''),\n tags: z.array(z.string()).default([]),\n group_only_greetings: z.array(z.string()).default([]),\n // Optional fields\n creator_notes: z.string().optional(),\n system_prompt: z.string().optional(),\n post_history_instructions: z.string().optional(),\n alternate_greetings: z.array(z.string()).optional(),\n character_book: CCv3CharacterBookSchema.optional().nullable(),\n extensions: z.record(z.unknown()).optional(),\n // v3 specific\n assets: z.array(AssetDescriptorSchema).optional(),\n nickname: z.string().optional(),\n creator_notes_multilingual: z.record(z.string()).optional(),\n source: z.array(z.string()).optional(),\n creation_date: z.number().int().nonnegative().optional(), // Unix timestamp in seconds\n modification_date: z.number().int().nonnegative().optional(), // Unix timestamp in seconds\n});\n\n/**\n * Character Card v3 full structure schema\n */\nexport const CCv3DataSchema = z.object({\n spec: z.literal('chara_card_v3'),\n spec_version: z.literal('3.0'),\n data: CCv3DataInnerSchema,\n});\n\n// ============================================================================\n// TypeScript Types (inferred from Zod schemas)\n// ============================================================================\n\n/**\n * Lorebook entry for v3 cards\n */\nexport type CCv3LorebookEntry = z.infer<typeof CCv3LorebookEntrySchema>;\n\n/**\n * Character book (lorebook) for v3 cards\n */\nexport type CCv3CharacterBook = z.infer<typeof CCv3CharacterBookSchema>;\n\n/**\n * Character Card v3 inner data structure\n */\nexport type CCv3DataInner = z.infer<typeof CCv3DataInnerSchema>;\n\n/**\n * Character Card v3 full structure\n */\nexport type CCv3Data = z.infer<typeof CCv3DataSchema>;\n\n// ============================================================================\n// Type Guards & Parsers\n// ============================================================================\n\n/**\n * Check if data is a v3 card\n */\nexport function isV3Card(data: unknown): data is CCv3Data {\n return CCv3DataSchema.safeParse(data).success;\n}\n\n/**\n * Parse and validate a v3 card\n */\nexport function parseV3Card(data: unknown): CCv3Data {\n return CCv3DataSchema.parse(data);\n}\n\n/**\n * Parse and validate v3 card inner data\n */\nexport function parseV3DataInner(data: unknown): CCv3DataInner {\n return CCv3DataInnerSchema.parse(data);\n}\n\n/**\n * Get v3 card inner data\n */\nexport function getV3Data(card: CCv3Data): CCv3DataInner {\n return card.data;\n}\n\n/**\n * Check if data looks like a V3 card structurally (without strict validation).\n * More lenient than isV3Card - just checks structure, not full schema validity.\n */\nexport function looksLikeV3Card(data: unknown): data is { spec: string; data: Record<string, unknown> } {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return (\n obj.spec === 'chara_card_v3' &&\n obj.data !== null &&\n typeof obj.data === 'object'\n );\n}\n","/**\n * RisuAI Extension Types\n *\n * These extensions are preserved as opaque blobs.\n * We do NOT interpret or transform the script contents.\n */\n\n/**\n * Risu emotions mapping (v2 style)\n * Format: [name, uri][]\n */\nexport type RisuEmotions = [string, string][];\n\n/**\n * Risu additional assets (v3 style)\n * Format: [name, uri, type][]\n */\nexport type RisuAdditionalAssets = [string, string, string][];\n\n/**\n * Risu depth prompt configuration\n */\nexport interface RisuDepthPrompt {\n depth: number;\n prompt: string;\n}\n\n/**\n * Risu extensions in card.extensions.risuai\n * Preserved as opaque - we don't interpret script contents\n */\nexport interface RisuExtensions {\n // Emotion assets\n emotions?: RisuEmotions;\n additionalAssets?: RisuAdditionalAssets;\n\n // Script data - OPAQUE, do not parse\n triggerscript?: unknown;\n customScripts?: unknown;\n\n // Voice/TTS settings\n vits?: Record<string, string>;\n\n // Depth prompt\n depth_prompt?: RisuDepthPrompt;\n\n // Other Risu-specific fields\n [key: string]: unknown;\n}\n\n/**\n * CharX x_meta entry (PNG chunk metadata preservation)\n */\nexport interface CharxMetaEntry {\n type?: string; // e.g., 'WEBP', 'PNG', 'JPEG'\n [key: string]: unknown;\n}\n\n/**\n * Check if card has Risu extensions\n */\nexport function hasRisuExtensions(extensions?: Record<string, unknown>): boolean {\n if (!extensions) return false;\n return 'risuai' in extensions || 'risu' in extensions;\n}\n\n/**\n * Check if card has Risu scripts (triggerscript or customScripts)\n */\nexport function hasRisuScripts(extensions?: Record<string, unknown>): boolean {\n if (!extensions) return false;\n const risu = extensions.risuai as RisuExtensions | undefined;\n if (!risu) return false;\n return !!risu.triggerscript || !!risu.customScripts;\n}\n\n/**\n * Check if card has depth prompt\n * Checks both SillyTavern style (extensions.depth_prompt) and Risu style (extensions.risuai.depth_prompt)\n */\nexport function hasDepthPrompt(extensions?: Record<string, unknown>): boolean {\n if (!extensions) return false;\n // SillyTavern top-level depth_prompt\n if ('depth_prompt' in extensions && extensions.depth_prompt) return true;\n // Risu-style depth_prompt\n const risu = extensions.risuai as RisuExtensions | undefined;\n return !!risu?.depth_prompt;\n}\n","/**\n * Normalized Card Types\n *\n * Unified view of card data regardless of source format.\n * This is a computed/virtual representation, not stored.\n */\n\nimport type { CCv3CharacterBook } from './ccv3.js';\n\n/**\n * Normalized card representation\n * Provides unified access to card data from any format\n */\nexport interface NormalizedCard {\n // Core fields (always present)\n name: string;\n description: string;\n personality: string;\n scenario: string;\n firstMes: string;\n mesExample: string;\n\n // Optional prompts\n systemPrompt?: string;\n postHistoryInstructions?: string;\n\n // Arrays\n alternateGreetings: string[];\n groupOnlyGreetings: string[];\n tags: string[];\n\n // Metadata\n creator?: string;\n creatorNotes?: string;\n characterVersion?: string;\n\n // Character book (v3 format)\n characterBook?: CCv3CharacterBook;\n\n // Extensions (preserved as-is)\n extensions: Record<string, unknown>;\n}\n\n/**\n * Create empty normalized card with defaults\n */\nexport function createEmptyNormalizedCard(): NormalizedCard {\n return {\n name: '',\n description: '',\n personality: '',\n scenario: '',\n firstMes: '',\n mesExample: '',\n alternateGreetings: [],\n groupOnlyGreetings: [],\n tags: [],\n extensions: {},\n };\n}\n\n/**\n * Derived features extracted from card (not stored in card)\n */\nexport interface DerivedFeatures {\n // Content flags\n hasAlternateGreetings: boolean;\n alternateGreetingsCount: number;\n /** Total greetings = first_mes (1) + alternate_greetings */\n totalGreetingsCount: number;\n hasLorebook: boolean;\n lorebookEntriesCount: number;\n hasEmbeddedImages: boolean;\n embeddedImagesCount: number;\n hasGallery: boolean;\n\n // Format-specific\n hasRisuExtensions: boolean;\n hasRisuScripts: boolean;\n hasDepthPrompt: boolean;\n hasVoxtaAppearance: boolean;\n\n // Token counts (estimated)\n tokens: {\n description: number;\n personality: number;\n scenario: number;\n firstMes: number;\n mesExample: number;\n systemPrompt: number;\n total: number;\n };\n}\n\n/**\n * Create empty derived features\n */\nexport function createEmptyFeatures(): DerivedFeatures {\n return {\n hasAlternateGreetings: false,\n alternateGreetingsCount: 0,\n totalGreetingsCount: 1, // first_mes always counts as 1\n hasLorebook: false,\n lorebookEntriesCount: 0,\n hasEmbeddedImages: false,\n embeddedImagesCount: 0,\n hasGallery: false,\n hasRisuExtensions: false,\n hasRisuScripts: false,\n hasDepthPrompt: false,\n hasVoxtaAppearance: false,\n tokens: {\n description: 0,\n personality: 0,\n scenario: 0,\n firstMes: 0,\n mesExample: 0,\n systemPrompt: 0,\n total: 0,\n },\n };\n}\n","/**\n * Feature Derivation\n *\n * Canonical feature extraction from character cards.\n * Eliminates duplicate implementations across Archive, Federation, and Architect.\n */\n\nimport type { CCv2Data } from './ccv2.js';\nimport type { CCv3DataInner } from './ccv3.js';\nimport type { DerivedFeatures } from './normalized.js';\nimport { hasRisuExtensions, hasRisuScripts, hasDepthPrompt } from './risu.js';\n\n/**\n * Derive features from a character card (V2 or V3 format).\n *\n * This is the canonical implementation - all apps should use this\n * rather than implementing their own feature detection.\n *\n * @param card - Either CCv2Data or CCv3DataInner (unwrapped)\n * @returns DerivedFeatures with all feature flags populated\n *\n * @example\n * ```typescript\n * import { deriveFeatures, parseV3Card } from '@character-foundry/schemas';\n *\n * const card = parseV3Card(data);\n * const features = deriveFeatures(card.data);\n *\n * if (features.hasLorebook) {\n * console.log(`Found ${features.lorebookEntriesCount} lorebook entries`);\n * }\n * ```\n */\nexport function deriveFeatures(card: CCv2Data | CCv3DataInner): DerivedFeatures {\n // Detect format by checking for V3-specific field\n const isV3 = 'assets' in card;\n\n // Alternate greetings\n const altGreetings = card.alternate_greetings ?? [];\n const hasAlternateGreetings = altGreetings.length > 0;\n const alternateGreetingsCount = altGreetings.length;\n // Total = first_mes (1) + alternate_greetings\n const totalGreetingsCount = 1 + alternateGreetingsCount;\n\n // Lorebook\n const characterBook = card.character_book;\n const hasLorebook = !!characterBook && characterBook.entries.length > 0;\n const lorebookEntriesCount = characterBook?.entries.length ?? 0;\n\n // Assets (V3 only) - check for visual asset types\n const assets = isV3 ? (card as CCv3DataInner).assets ?? [] : [];\n const imageAssetTypes = ['icon', 'background', 'emotion', 'custom'];\n const imageAssets = assets.filter(\n (a) =>\n imageAssetTypes.includes(a.type) ||\n ['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(a.ext.toLowerCase()),\n );\n const hasGallery = imageAssets.length > 0;\n\n // Embedded images - check for data URLs in text fields\n const embeddedImageCount = countEmbeddedImages(card);\n const hasEmbeddedImages = embeddedImageCount > 0;\n\n // Extensions\n const extensions = card.extensions ?? {};\n const hasRisu = hasRisuExtensions(extensions);\n const hasScripts = hasRisuScripts(extensions);\n const hasDepth = hasDepthPrompt(extensions);\n const hasVoxta = checkVoxtaAppearance(extensions);\n\n // Token counts - initialize to zero (actual counting happens in tokenizers package)\n const tokens = {\n description: 0,\n personality: 0,\n scenario: 0,\n firstMes: 0,\n mesExample: 0,\n systemPrompt: 0,\n total: 0,\n };\n\n return {\n hasAlternateGreetings,\n alternateGreetingsCount,\n totalGreetingsCount,\n hasLorebook,\n lorebookEntriesCount,\n hasEmbeddedImages,\n embeddedImagesCount: embeddedImageCount,\n hasGallery,\n hasRisuExtensions: hasRisu,\n hasRisuScripts: hasScripts,\n hasDepthPrompt: hasDepth,\n hasVoxtaAppearance: hasVoxta,\n tokens,\n };\n}\n\n/**\n * Count embedded images (data URLs) in card text fields.\n * Looks for base64-encoded images in description, personality, scenario, etc.\n */\nfunction countEmbeddedImages(card: CCv2Data | CCv3DataInner): number {\n const textFields = [\n card.description,\n card.personality,\n card.scenario,\n card.first_mes,\n card.mes_example,\n card.creator_notes,\n card.system_prompt,\n card.post_history_instructions,\n ...(card.alternate_greetings ?? []),\n ].filter((field): field is string => typeof field === 'string');\n\n // Add group_only_greetings if V3\n if ('group_only_greetings' in card) {\n textFields.push(...(card.group_only_greetings ?? []));\n }\n\n let count = 0;\n const dataUrlPattern = /data:image\\/[^;]+;base64,/g;\n\n for (const text of textFields) {\n const matches = text.match(dataUrlPattern);\n if (matches) {\n count += matches.length;\n }\n }\n\n return count;\n}\n\n/**\n * Check if card has Voxta appearance data.\n * Voxta stores appearance in extensions.voxta.appearance\n */\nfunction checkVoxtaAppearance(extensions: Record<string, unknown>): boolean {\n if (!extensions.voxta) return false;\n const voxta = extensions.voxta as Record<string, unknown>;\n return !!voxta.appearance;\n}\n","/**\n * Format Detection\n *\n * Detect card specification version from JSON data.\n */\n\nimport type { Spec } from './common.js';\n\n/**\n * V3-only fields that indicate a V3 card\n */\nconst V3_ONLY_FIELDS = ['group_only_greetings', 'creation_date', 'modification_date', 'assets'] as const;\n\n/**\n * Result from detailed spec detection\n */\nexport interface SpecDetectionResult {\n /** Detected spec version */\n spec: Spec | null;\n /** Confidence level of detection */\n confidence: 'high' | 'medium' | 'low';\n /** What fields/values indicated this spec */\n indicators: string[];\n /** Anomalies or inconsistencies detected */\n warnings: string[];\n}\n\n/**\n * Detect card spec version from parsed JSON\n * Returns 'v2', 'v3', or null if not recognized\n */\nexport function detectSpec(data: unknown): Spec | null {\n return detectSpecDetailed(data).spec;\n}\n\n/**\n * Detailed spec detection with confidence and reasoning.\n * Useful for debugging and logging.\n */\nexport function detectSpecDetailed(data: unknown): SpecDetectionResult {\n const result: SpecDetectionResult = {\n spec: null,\n confidence: 'low',\n indicators: [],\n warnings: [],\n };\n\n if (!data || typeof data !== 'object') {\n result.indicators.push('Input is not an object');\n return result;\n }\n\n const obj = data as Record<string, unknown>;\n const dataObj = (obj.data && typeof obj.data === 'object' ? obj.data : null) as Record<\n string,\n unknown\n > | null;\n\n // Check for explicit spec markers (HIGH confidence)\n\n // Explicit v3 spec marker\n if (obj.spec === 'chara_card_v3') {\n result.spec = 'v3';\n result.confidence = 'high';\n result.indicators.push('spec field is \"chara_card_v3\"');\n\n // Check for inconsistencies\n if (obj.spec_version && obj.spec_version !== '3.0') {\n result.warnings.push(`spec_version \"${obj.spec_version}\" inconsistent with v3 spec`);\n }\n\n return result;\n }\n\n // Explicit v2 spec marker\n if (obj.spec === 'chara_card_v2') {\n result.spec = 'v2';\n result.confidence = 'high';\n result.indicators.push('spec field is \"chara_card_v2\"');\n\n // Check for inconsistencies - V3-only fields in V2 card\n if (dataObj) {\n for (const field of V3_ONLY_FIELDS) {\n if (field in dataObj) {\n result.warnings.push(`V3-only field \"${field}\" found in V2 card`);\n }\n }\n }\n\n if (obj.spec_version && obj.spec_version !== '2.0') {\n result.warnings.push(`spec_version \"${obj.spec_version}\" inconsistent with v2 spec`);\n }\n\n return result;\n }\n\n // Check spec_version field (HIGH confidence)\n if (typeof obj.spec_version === 'string') {\n if (obj.spec_version.startsWith('3')) {\n result.spec = 'v3';\n result.confidence = 'high';\n result.indicators.push(`spec_version \"${obj.spec_version}\" starts with \"3\"`);\n return result;\n }\n if (obj.spec_version.startsWith('2')) {\n result.spec = 'v2';\n result.confidence = 'high';\n result.indicators.push(`spec_version \"${obj.spec_version}\" starts with \"2\"`);\n return result;\n }\n }\n\n if (obj.spec_version === 2.0 || obj.spec_version === 2) {\n result.spec = 'v2';\n result.confidence = 'high';\n result.indicators.push(`spec_version is numeric ${obj.spec_version}`);\n return result;\n }\n\n // Check for V3-only fields (MEDIUM confidence)\n if (dataObj) {\n const v3Fields: string[] = [];\n for (const field of V3_ONLY_FIELDS) {\n if (field in dataObj) {\n v3Fields.push(field);\n }\n }\n\n if (v3Fields.length > 0) {\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push(`Has V3-only fields: ${v3Fields.join(', ')}`);\n return result;\n }\n }\n\n // Check root level for V3-only fields (also MEDIUM confidence)\n const rootV3Fields: string[] = [];\n for (const field of V3_ONLY_FIELDS) {\n if (field in obj) {\n rootV3Fields.push(field);\n }\n }\n if (rootV3Fields.length > 0) {\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push(`Has V3-only fields at root: ${rootV3Fields.join(', ')}`);\n result.warnings.push('V3 fields found at root level instead of data object');\n return result;\n }\n\n // Wrapped format with data object (MEDIUM confidence)\n if (obj.spec && dataObj) {\n const dataName = dataObj.name;\n if (dataName && typeof dataName === 'string') {\n // Infer from spec string\n if (typeof obj.spec === 'string') {\n if (obj.spec.includes('v3') || obj.spec.includes('3')) {\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push(`spec field \"${obj.spec}\" contains \"v3\" or \"3\"`);\n return result;\n }\n if (obj.spec.includes('v2') || obj.spec.includes('2')) {\n result.spec = 'v2';\n result.confidence = 'medium';\n result.indicators.push(`spec field \"${obj.spec}\" contains \"v2\" or \"2\"`);\n return result;\n }\n }\n // Default wrapped format to v3 (modern)\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push('Has wrapped format with spec and data.name');\n return result;\n }\n }\n\n // Unwrapped format - V1/V2 like structure (MEDIUM confidence)\n if (obj.name && typeof obj.name === 'string') {\n if ('description' in obj || 'personality' in obj || 'scenario' in obj) {\n result.spec = 'v2';\n result.confidence = 'medium';\n result.indicators.push('Unwrapped format with name, description/personality/scenario');\n return result;\n }\n }\n\n // Check if data object has card-like structure without spec (LOW confidence)\n if (dataObj && typeof dataObj.name === 'string') {\n if ('description' in dataObj || 'personality' in dataObj) {\n result.spec = 'v2';\n result.confidence = 'low';\n result.indicators.push('Has data object with name and card fields, but no spec');\n result.warnings.push('Missing spec field');\n return result;\n }\n }\n\n result.indicators.push('No card structure detected');\n return result;\n}\n\n/**\n * Check if card has a lorebook\n */\nexport function hasLorebook(data: unknown): boolean {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n\n // Check wrapped format\n const wrapped = obj.data as Record<string, unknown> | undefined;\n if (wrapped?.character_book) {\n const book = wrapped.character_book as Record<string, unknown>;\n if (Array.isArray(book.entries) && book.entries.length > 0) return true;\n }\n\n // Check unwrapped format\n if (obj.character_book) {\n const book = obj.character_book as Record<string, unknown>;\n if (Array.isArray(book.entries) && book.entries.length > 0) return true;\n }\n\n return false;\n}\n\n/**\n * Check if data looks like a valid card structure\n */\nexport function looksLikeCard(data: unknown): boolean {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n\n // Has explicit spec marker\n if (obj.spec === 'chara_card_v2' || obj.spec === 'chara_card_v3') {\n return true;\n }\n\n // Has wrapped data with name\n if (obj.data && typeof obj.data === 'object') {\n const dataObj = obj.data as Record<string, unknown>;\n if (typeof dataObj.name === 'string' && dataObj.name.length > 0) {\n return true;\n }\n }\n\n // Has unwrapped card-like structure\n if (typeof obj.name === 'string' && obj.name.length > 0) {\n if ('description' in obj || 'personality' in obj || 'first_mes' in obj) {\n return true;\n }\n }\n\n return false;\n}\n","/**\n * Card Normalizer\n *\n * Handles normalization of malformed card data from various sources.\n * Fixes common issues like wrong spec values, misplaced fields, missing required fields.\n */\n\nimport type { CCv2Data, CCv2Wrapped, CCv2CharacterBook, CCv2LorebookEntry } from './ccv2.js';\nimport type { CCv3Data, CCv3CharacterBook, CCv3LorebookEntry } from './ccv3.js';\nimport { detectSpec } from './detection.js';\n\n/**\n * Position values as numbers (non-standard) and their string equivalents\n */\nconst POSITION_MAP: Record<number, 'before_char' | 'after_char'> = {\n 0: 'before_char',\n 1: 'after_char',\n};\n\n/**\n * V3-only lorebook entry fields that should be moved to extensions for V2\n */\nconst V3_ONLY_ENTRY_FIELDS = [\n 'probability',\n 'depth',\n 'group',\n 'scan_frequency',\n 'use_regex',\n 'selective_logic',\n 'role',\n 'automation_id',\n] as const;\n\n/**\n * Required V2 card fields with their defaults\n */\nconst V2_REQUIRED_DEFAULTS: Partial<CCv2Data> = {\n name: '',\n description: '',\n personality: '',\n scenario: '',\n first_mes: '',\n mes_example: '',\n};\n\n/**\n * Required V3 card fields with their defaults\n */\nconst V3_REQUIRED_DEFAULTS: Partial<CCv3Data['data']> = {\n name: '',\n description: '',\n personality: '',\n scenario: '',\n first_mes: '',\n mes_example: '',\n creator: '',\n character_version: '1.0',\n tags: [],\n group_only_greetings: [],\n};\n\n/**\n * Fields that belong at root level for wrapped format\n */\nconst _ROOT_FIELDS = ['spec', 'spec_version', 'data'] as const;\n\n/**\n * Fields that belong in the data object\n */\nconst DATA_FIELDS = [\n 'name',\n 'description',\n 'personality',\n 'scenario',\n 'first_mes',\n 'mes_example',\n 'creator_notes',\n 'system_prompt',\n 'post_history_instructions',\n 'alternate_greetings',\n 'character_book',\n 'tags',\n 'creator',\n 'character_version',\n 'extensions',\n 'assets',\n 'nickname',\n 'creator_notes_multilingual',\n 'source',\n 'creation_date',\n 'modification_date',\n 'group_only_greetings',\n] as const;\n\n/**\n * Deep clone an object without mutating the original\n */\nfunction deepClone<T>(obj: T): T {\n if (obj === null || obj === undefined) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as T;\n }\n if (typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n result[key] = deepClone(value);\n }\n return result as T;\n }\n return obj;\n}\n\n/**\n * Check if a timestamp is in milliseconds (13+ digits)\n */\nfunction isMilliseconds(timestamp: number): boolean {\n // Timestamps before year 2001 in seconds: < 1000000000\n // Timestamps in milliseconds are typically 13 digits: 1000000000000+\n return timestamp > 10000000000;\n}\n\n/**\n * CardNormalizer - handles normalization of malformed card data\n */\nexport const CardNormalizer = {\n /**\n * Normalize card data to valid schema format.\n *\n * Handles:\n * - Fixing spec/spec_version values\n * - Moving misplaced fields to correct locations\n * - Adding missing required fields with defaults\n * - Handling hybrid formats (fields at root AND in data object)\n *\n * @param data - Raw card data (potentially malformed)\n * @param spec - Target spec version\n * @returns Normalized card data (does not mutate input)\n */\n normalize(data: unknown, spec: 'v2' | 'v3'): CCv2Wrapped | CCv3Data {\n if (!data || typeof data !== 'object') {\n // Return minimal valid card\n if (spec === 'v3') {\n return {\n spec: 'chara_card_v3',\n spec_version: '3.0',\n data: { ...V3_REQUIRED_DEFAULTS } as CCv3Data['data'],\n };\n }\n return {\n spec: 'chara_card_v2',\n spec_version: '2.0',\n data: { ...V2_REQUIRED_DEFAULTS } as CCv2Data,\n };\n }\n\n const obj = data as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n\n // Build merged data object from root fields + existing data object\n const existingData = (obj.data && typeof obj.data === 'object' ? obj.data : {}) as Record<\n string,\n unknown\n >;\n const mergedData: Record<string, unknown> = {};\n\n // Copy existing data first\n for (const [key, value] of Object.entries(existingData)) {\n mergedData[key] = deepClone(value);\n }\n\n // Move any misplaced root-level data fields into data object\n // (ChubAI hybrid format fix)\n for (const field of DATA_FIELDS) {\n if (field in obj && !(field in mergedData)) {\n mergedData[field] = deepClone(obj[field]);\n }\n }\n\n // Handle character_book: null -> remove entirely\n if (mergedData.character_book === null) {\n delete mergedData.character_book;\n }\n\n // Normalize character_book if present\n if (mergedData.character_book && typeof mergedData.character_book === 'object') {\n mergedData.character_book = this.normalizeCharacterBook(\n mergedData.character_book as Record<string, unknown>,\n spec\n );\n }\n\n // Apply defaults for required fields\n const defaults = spec === 'v3' ? V3_REQUIRED_DEFAULTS : V2_REQUIRED_DEFAULTS;\n for (const [key, defaultValue] of Object.entries(defaults)) {\n if (!(key in mergedData) || mergedData[key] === undefined) {\n mergedData[key] = Array.isArray(defaultValue) ? [...defaultValue] : defaultValue;\n }\n }\n\n // Ensure arrays are actually arrays\n if (mergedData.tags && !Array.isArray(mergedData.tags)) {\n mergedData.tags = [];\n }\n if (mergedData.alternate_greetings && !Array.isArray(mergedData.alternate_greetings)) {\n mergedData.alternate_greetings = [];\n }\n if (spec === 'v3') {\n if (\n mergedData.group_only_greetings &&\n !Array.isArray(mergedData.group_only_greetings)\n ) {\n mergedData.group_only_greetings = [];\n }\n }\n\n // Build result with correct spec\n if (spec === 'v3') {\n result.spec = 'chara_card_v3';\n result.spec_version = '3.0';\n result.data = this.fixTimestampsInner(mergedData);\n } else {\n result.spec = 'chara_card_v2';\n result.spec_version = '2.0';\n result.data = mergedData;\n }\n\n return result as unknown as CCv2Wrapped | CCv3Data;\n },\n\n /**\n * Normalize a character book (lorebook).\n *\n * Handles:\n * - Ensuring required fields exist\n * - Converting numeric position values to string enums\n * - Moving V3-only fields to extensions for V2 compatibility\n *\n * @param book - Raw character book data\n * @param spec - Target spec version\n * @returns Normalized character book\n */\n normalizeCharacterBook(\n book: Record<string, unknown>,\n spec: 'v2' | 'v3'\n ): CCv2CharacterBook | CCv3CharacterBook {\n const result: Record<string, unknown> = {};\n\n // Copy book-level fields\n if (book.name !== undefined) result.name = book.name;\n if (book.description !== undefined) result.description = book.description;\n if (book.scan_depth !== undefined) result.scan_depth = book.scan_depth;\n if (book.token_budget !== undefined) result.token_budget = book.token_budget;\n if (book.recursive_scanning !== undefined)\n result.recursive_scanning = book.recursive_scanning;\n if (book.extensions !== undefined) result.extensions = deepClone(book.extensions);\n\n // Normalize entries\n const entries = Array.isArray(book.entries) ? book.entries : [];\n result.entries = entries.map((entry) =>\n this.normalizeEntry(entry as Record<string, unknown>, spec)\n );\n\n return result as unknown as CCv2CharacterBook | CCv3CharacterBook;\n },\n\n /**\n * Normalize a single lorebook entry.\n *\n * Handles:\n * - Converting numeric position to string enum\n * - Moving V3-only fields to extensions for V2\n * - Ensuring required fields exist\n *\n * @param entry - Raw entry data\n * @param spec - Target spec version\n * @returns Normalized entry\n */\n normalizeEntry(\n entry: Record<string, unknown>,\n spec: 'v2' | 'v3'\n ): CCv2LorebookEntry | CCv3LorebookEntry {\n const result: Record<string, unknown> = {};\n\n // Required fields with defaults\n result.keys = Array.isArray(entry.keys) ? [...entry.keys] : [];\n result.content = typeof entry.content === 'string' ? entry.content : '';\n result.enabled = entry.enabled !== false; // default true\n result.insertion_order =\n typeof entry.insertion_order === 'number' ? entry.insertion_order : 0;\n\n // For V2, extensions is required\n if (spec === 'v2') {\n result.extensions =\n entry.extensions && typeof entry.extensions === 'object'\n ? deepClone(entry.extensions)\n : {};\n }\n\n // Optional fields\n if (entry.case_sensitive !== undefined) result.case_sensitive = entry.case_sensitive;\n if (entry.name !== undefined) result.name = entry.name;\n if (entry.priority !== undefined) result.priority = entry.priority;\n if (entry.id !== undefined) result.id = entry.id;\n if (entry.comment !== undefined) result.comment = entry.comment;\n if (entry.selective !== undefined) result.selective = entry.selective;\n if (entry.secondary_keys !== undefined) {\n result.secondary_keys = Array.isArray(entry.secondary_keys)\n ? [...entry.secondary_keys]\n : [];\n }\n if (entry.constant !== undefined) result.constant = entry.constant;\n\n // Position: convert numeric to string enum\n if (entry.position !== undefined) {\n if (typeof entry.position === 'number') {\n result.position = POSITION_MAP[entry.position] || 'before_char';\n } else if (entry.position === 'before_char' || entry.position === 'after_char') {\n result.position = entry.position;\n }\n }\n\n // Handle V3-only fields\n if (spec === 'v3') {\n // Copy V3 fields directly\n if (entry.extensions !== undefined) result.extensions = deepClone(entry.extensions);\n for (const field of V3_ONLY_ENTRY_FIELDS) {\n if (entry[field] !== undefined) {\n result[field] = entry[field];\n }\n }\n } else {\n // V2: Move V3-only fields to extensions\n const ext = (result.extensions || {}) as Record<string, unknown>;\n for (const field of V3_ONLY_ENTRY_FIELDS) {\n if (entry[field] !== undefined) {\n ext[field] = entry[field];\n }\n }\n result.extensions = ext;\n }\n\n return result as unknown as CCv2LorebookEntry | CCv3LorebookEntry;\n },\n\n /**\n * Fix CharacterTavern timestamp format (milliseconds -> seconds).\n *\n * CCv3 spec requires timestamps in seconds (Unix epoch).\n * CharacterTavern exports timestamps in milliseconds.\n *\n * @param data - V3 card data\n * @returns Card data with fixed timestamps (does not mutate input)\n */\n fixTimestamps(data: CCv3Data): CCv3Data {\n const result = deepClone(data);\n result.data = this.fixTimestampsInner(\n result.data as unknown as Record<string, unknown>\n ) as unknown as CCv3Data['data'];\n return result;\n },\n\n /**\n * Internal: fix timestamps in data object\n */\n fixTimestampsInner(data: Record<string, unknown>): Record<string, unknown> {\n const result = { ...data };\n\n if (typeof result.creation_date === 'number') {\n if (isMilliseconds(result.creation_date)) {\n result.creation_date = Math.floor(result.creation_date / 1000);\n }\n // Sanitize negative timestamps (.NET default dates like 0001-01-01)\n if ((result.creation_date as number) < 0) {\n delete result.creation_date;\n }\n }\n\n if (typeof result.modification_date === 'number') {\n if (isMilliseconds(result.modification_date)) {\n result.modification_date = Math.floor(result.modification_date / 1000);\n }\n // Sanitize negative timestamps (.NET default dates like 0001-01-01)\n if ((result.modification_date as number) < 0) {\n delete result.modification_date;\n }\n }\n\n return result;\n },\n\n /**\n * Auto-detect spec and normalize.\n *\n * @param data - Raw card data\n * @returns Normalized card data, or null if not a valid card\n */\n autoNormalize(data: unknown): CCv2Wrapped | CCv3Data | null {\n const spec = detectSpec(data);\n if (!spec) return null;\n\n // V1 cards get upgraded to V2\n const targetSpec = spec === 'v3' ? 'v3' : 'v2';\n return this.normalize(data, targetSpec);\n },\n};\n\nexport type { CCv2Wrapped, CCv3Data };\n","/**\n * Validation Utilities\n *\n * Helper functions for Zod validation with Foundry error integration.\n */\n\nimport { z } from 'zod';\n\n/**\n * Convert Zod error to human-readable message\n */\nexport function zodErrorToMessage(zodError: z.ZodError, context?: string): string {\n const messages = zodError.errors.map((err) => {\n const path = err.path.length > 0 ? `${err.path.join('.')}: ` : '';\n return `${path}${err.message}`;\n });\n\n const message = messages.join('; ');\n return context ? `${context} - ${message}` : message;\n}\n\n/**\n * Get the first error field from Zod error\n */\nexport function getFirstErrorField(zodError: z.ZodError): string | undefined {\n return zodError.errors[0]?.path[0]?.toString();\n}\n\n/**\n * Safe parse with detailed error information\n */\nexport function safeParse<T>(\n schema: z.ZodSchema<T>,\n data: unknown\n): { success: true; data: T } | { success: false; error: string; field?: string } {\n const result = schema.safeParse(data);\n\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n return {\n success: false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QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;MACF;MACA,SAAW;QACT,SAAW;QACX,OAAS;QACT,MAAQ;QACR,aAAa;QACb,aAAa;QACb,kBAAkB;QAClB,aAAa;QACb,cAAc;QACd,4BAA4B;QAC5B,+BAA+B;QAC/B,cAAc;QACd,cAAc;QACd,gBAAgB;MAClB;MACA,MAAQ;MACR,MAAQ;MACR,OAAS;MACT,OAAS;QACP;QACA;QACA;MACF;MACA,YAAc;QACZ,MAAQ;QACR,KAAO;MACT;MACA,UAAY;QACV;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;MACF;MACA,cAAgB;QACd,OAAS;QACT,eAAe;QACf,QAAU;MACZ;MACA,sBAAwB;QACtB,2BAA2B;QAC3B,yBAAyB;QACzB,mCAAmC;QACnC,iCAAiC;QACjC,gCAAgC;QAChC,kCAAkC;QAClC,kCAAkC;QAClC,gCAAgC;QAChC,sCAAsC;QACtC,oCAAoC;QACpC,wBAAwB;QACxB,0BAA0B;QAC1B,0BAA0B;QAC1B,wBAAwB;QACxB,8BAA8B;QAC9B,4BAA4B;QAC5B,qBAAqB;QACrB,yBAAyB;QACzB,wBAAwB;MAC1B;MACA,iBAAmB;QACjB,mBAAmB;QACnB,0BAA0B;QAC1B,iCAAiC;QACjC,iCAAiC;QACjC,gCAAgC;QAChC,eAAe;QACf,OAAS;QACT,IAAM;QACN,QAA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ACzB,YAAM,CAAC,SAAS,OAAO,OAAO,IAAI;AAClC,UAAI,QAAS,MAAK,KAAK,WAAW,QAAQ,YAAY,CAAC,EAAE;AACzD,UAAI,MAAO,MAAK,KAAK,SAAS,MAAM,YAAY,CAAC,EAAE;AACnD,UAAI,QAAS,MAAK,KAAK,WAAW,OAAO,EAAE;IAC7C,WAAW,UAAU,WAAW,GAAG;AACjC,YAAM,CAAC,SAAS,KAAK,IAAI;AACzB,UAAI,QAAS,MAAK,KAAK,WAAW,QAAQ,YAAY,CAAC,EAAE;AACzD,UAAI,MAAO,MAAK,KAAK,SAAS,MAAM,YAAY,CAAC,EAAE;IACrD,WAAW,UAAU,WAAW,GAAG;AACjC,UAAI,UAAU,CAAC,EAAG,MAAK,KAAK,WAAW,UAAU,CAAC,EAAE,YAAY,CAAC,EAAE;IACrE;EAEF,WAAW,MAAM,KAAK,SAAS,gBAAgB,GAAG;AAChD,WAAO;AACP,SAAK,KAAK,OAAO;EACnB;AAEA,SAAO,EAAE,MAAM,KAAK;AACtB;","names":["__require","family","version","z","globalLibvipsVersion","clone","debuglog","concat","swizzle","z2","metadata","stats","extend","composite","flip","flop","gamma","threshold","tint","greyscale","grayscale","colourspace","_","concurrency","simd","zipSync","z","z","VoxtaResourceKind","generateUUID","streamingUnzipSync","ZipPreflightError","SizeLimitError","ParseError","fromString","zipSync","detectImageFormat","getExtension"]}
1
+ {"version":3,"sources":["../../core/src/binary.ts","../../core/src/base64.ts","../../core/src/errors.ts","../../core/src/data-url.ts","../../core/src/uri.ts","../../core/src/image.ts","../../core/src/uuid.ts","../../core/src/binary.ts","../../core/src/zip.ts","../../voxta/src/types.ts","../../voxta/src/reader.ts","../../voxta/src/writer.ts","../../voxta/src/macros.ts","../../voxta/src/mapper.ts","../../voxta/src/merge.ts","../../voxta/src/loss.ts","../../voxta/src/enricher.ts","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/is.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/filesystem.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/elf.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/detect-libc.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/re.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/parse-options.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/identifiers.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/parse.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/coerce.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gte.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/lrucache.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/eq.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/neq.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gt.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lt.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lte.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/cmp.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/comparator.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/range.js","../../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/satisfies.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/package.json","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/libvips.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/sharp.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/constructor.js","../../../node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js","../../../node_modules/.pnpm/is-arrayish@0.3.4/node_modules/is-arrayish/index.js","../../../node_modules/.pnpm/simple-swizzle@0.2.4/node_modules/simple-swizzle/index.js","../../../node_modules/.pnpm/color-string@1.9.1/node_modules/color-string/index.js","../../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js","../../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js","../../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js","../../../node_modules/.pnpm/color@4.2.3/node_modules/color/index.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/input.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/resize.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/composite.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/operation.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/colour.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/channel.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/output.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/utility.js","../../../node_modules/.pnpm/sharp@0.33.5/node_modules/sharp/lib/index.js","../../media/src/format.ts","../../media/src/dimensions.ts","../../media/src/thumbnail.ts","../../schemas/src/common.ts","../../schemas/src/ccv2.ts","../../schemas/src/ccv3.ts","../../schemas/src/risu.ts","../../schemas/src/normalized.ts","../../schemas/src/feature-deriver.ts","../../schemas/src/detection.ts","../../schemas/src/normalizer.ts","../../schemas/src/validation.ts"],"sourcesContent":["/**\n * Binary Data Utilities\n *\n * Universal binary data operations using Uint8Array.\n * Works in both Node.js and browser environments.\n */\n\n/**\n * Universal binary data type (works in both environments)\n */\nexport type BinaryData = Uint8Array;\n\n/**\n * Read a 32-bit big-endian unsigned integer\n */\nexport function readUInt32BE(data: BinaryData, offset: number): number {\n return (\n (data[offset]! << 24) |\n (data[offset + 1]! << 16) |\n (data[offset + 2]! << 8) |\n data[offset + 3]!\n ) >>> 0;\n}\n\n/**\n * Write a 32-bit big-endian unsigned integer\n */\nexport function writeUInt32BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 24) & 0xff;\n data[offset + 1] = (value >>> 16) & 0xff;\n data[offset + 2] = (value >>> 8) & 0xff;\n data[offset + 3] = value & 0xff;\n}\n\n/**\n * Read a 16-bit big-endian unsigned integer\n */\nexport function readUInt16BE(data: BinaryData, offset: number): number {\n return ((data[offset]! << 8) | data[offset + 1]!) >>> 0;\n}\n\n/**\n * Write a 16-bit big-endian unsigned integer\n */\nexport function writeUInt16BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 8) & 0xff;\n data[offset + 1] = value & 0xff;\n}\n\n/**\n * Find a byte sequence in binary data\n */\nexport function indexOf(data: BinaryData, search: BinaryData, fromIndex = 0): number {\n outer: for (let i = fromIndex; i <= data.length - search.length; i++) {\n for (let j = 0; j < search.length; j++) {\n if (data[i + j] !== search[j]) continue outer;\n }\n return i;\n }\n return -1;\n}\n\n/**\n * Concatenate multiple binary arrays\n */\nexport function concat(...arrays: BinaryData[]): BinaryData {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Slice binary data (returns a view, not a copy)\n */\nexport function slice(data: BinaryData, start: number, end?: number): BinaryData {\n return data.subarray(start, end);\n}\n\n/**\n * Copy a portion of binary data (returns a new array)\n */\nexport function copy(data: BinaryData, start: number, end?: number): BinaryData {\n return data.slice(start, end);\n}\n\n/**\n * Convert string to binary (UTF-8)\n */\nexport function fromString(str: string): BinaryData {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Convert binary to string (UTF-8)\n */\nexport function toString(data: BinaryData): string {\n return new TextDecoder().decode(data);\n}\n\n/**\n * Convert string to binary (Latin1 - for PNG keywords and similar)\n */\nexport function fromLatin1(str: string): BinaryData {\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i) & 0xff;\n }\n return result;\n}\n\n/**\n * Convert binary to string (Latin1)\n */\nexport function toLatin1(data: BinaryData): string {\n let result = '';\n for (let i = 0; i < data.length; i++) {\n result += String.fromCharCode(data[i]!);\n }\n return result;\n}\n\n/**\n * Compare two binary arrays for equality\n */\nexport function equals(a: BinaryData, b: BinaryData): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Create a new Uint8Array filled with zeros\n */\nexport function alloc(size: number): BinaryData {\n return new Uint8Array(size);\n}\n\n/**\n * Create a Uint8Array from an array of numbers\n */\nexport function from(data: number[] | ArrayBuffer | BinaryData): BinaryData {\n if (data instanceof Uint8Array) {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n return new Uint8Array(data);\n}\n\n/**\n * Check if value is a Uint8Array\n */\nexport function isBinaryData(value: unknown): value is BinaryData {\n return value instanceof Uint8Array;\n}\n\n/**\n * Convert Node.js Buffer to Uint8Array (no-op if already Uint8Array)\n * This provides compatibility when interfacing with Node.js code\n */\nexport function toUint8Array(data: BinaryData | Buffer): BinaryData {\n if (data instanceof Uint8Array) {\n // Buffer extends Uint8Array, but we want a plain Uint8Array\n // This ensures we get a proper Uint8Array in all cases\n if (Object.getPrototypeOf(data).constructor.name === 'Buffer') {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n return data;\n }\n return new Uint8Array(data);\n}\n\n/**\n * Convert binary data to hex string\n */\nexport function toHex(data: BinaryData): string {\n return Array.from(data)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to binary data\n */\nexport function fromHex(hex: string): BinaryData {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n","/**\n * Universal Base64 Encoding/Decoding\n *\n * Works in both Node.js and browser environments.\n */\n\nimport type { BinaryData } from './binary.js';\n\n/**\n * Check if we're in a Node.js environment\n */\nconst isNode = typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null;\n\n/**\n * Threshold for switching to chunked encoding in browsers (1MB)\n * Below this, simple string concatenation is fast enough.\n * Above this, quadratic string growth becomes a problem.\n */\nconst LARGE_BUFFER_THRESHOLD = 1024 * 1024;\n\n/**\n * Encode binary data to base64 string\n *\n * PERFORMANCE: For large buffers (>1MB) in browsers, this automatically\n * uses the chunked implementation to avoid quadratic string concatenation.\n */\nexport function encode(data: BinaryData): string {\n if (isNode) {\n // Node.js: Buffer handles large data efficiently\n return Buffer.from(data).toString('base64');\n }\n\n // Browser: use chunked encoding for large buffers to avoid O(n²) string growth\n if (data.length > LARGE_BUFFER_THRESHOLD) {\n return encodeChunked(data);\n }\n\n // Small buffers: simple approach is fast enough\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]!);\n }\n return btoa(binary);\n}\n\n/**\n * Decode base64 string to binary data\n */\nexport function decode(base64: string): BinaryData {\n if (isNode) {\n // Node.js: use Buffer\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n\n // Browser: use atob\n const binary = atob(base64);\n const result = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n result[i] = binary.charCodeAt(i);\n }\n return result;\n}\n\n/**\n * Check if a string is valid base64\n */\nexport function isBase64(str: string): boolean {\n if (str.length === 0) return false;\n // Base64 regex: only valid base64 characters, length multiple of 4 (with padding)\n const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;\n return base64Regex.test(str) && str.length % 4 === 0;\n}\n\n/**\n * Encode binary data to URL-safe base64 string\n * Replaces + with -, / with _, and removes padding\n */\nexport function encodeUrlSafe(data: BinaryData): string {\n return encode(data)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decode URL-safe base64 string to binary data\n */\nexport function decodeUrlSafe(base64: string): BinaryData {\n // Add back padding if needed\n let padded = base64\n .replace(/-/g, '+')\n .replace(/_/g, '/');\n\n while (padded.length % 4 !== 0) {\n padded += '=';\n }\n\n return decode(padded);\n}\n\n/**\n * Chunk size for encoding large buffers (64KB)\n * Prevents stack overflow when using String.fromCharCode with spread operator\n */\nconst ENCODE_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Encode binary data to base64 string with chunking for large buffers.\n * Handles buffers >10MB without stack overflow.\n *\n * @param data - Binary data to encode\n * @returns Base64 encoded string\n *\n * @example\n * ```typescript\n * const largeBuffer = new Uint8Array(20 * 1024 * 1024); // 20MB\n * const base64 = encodeChunked(largeBuffer); // No stack overflow\n * ```\n */\nexport function encodeChunked(data: BinaryData): string {\n if (isNode) {\n // Node.js: Buffer handles large data efficiently\n return Buffer.from(data).toString('base64');\n }\n\n // Browser: process in chunks to avoid stack overflow\n const chunks: string[] = [];\n\n for (let i = 0; i < data.length; i += ENCODE_CHUNK_SIZE) {\n const chunk = data.subarray(i, Math.min(i + ENCODE_CHUNK_SIZE, data.length));\n let binary = '';\n for (let j = 0; j < chunk.length; j++) {\n binary += String.fromCharCode(chunk[j]!);\n }\n chunks.push(binary);\n }\n\n return btoa(chunks.join(''));\n}\n","/**\n * Error Classes\n *\n * Specific error types for character card operations.\n * All errors extend FoundryError for consistent handling.\n */\n\n/** Symbol to identify FoundryError instances across ESM/CJS boundaries */\nconst FOUNDRY_ERROR_MARKER = Symbol.for('@character-foundry/core:FoundryError');\n\n/**\n * Base error class for all Character Foundry errors\n */\nexport class FoundryError extends Error {\n /** @internal Marker for cross-module identification */\n readonly [FOUNDRY_ERROR_MARKER] = true;\n\n constructor(message: string, public readonly code: string) {\n super(message);\n this.name = 'FoundryError';\n // Maintains proper stack trace in V8 environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error during card parsing\n */\nexport class ParseError extends FoundryError {\n constructor(message: string, public readonly format?: string) {\n super(message, 'PARSE_ERROR');\n this.name = 'ParseError';\n }\n}\n\n/**\n * Error during card validation\n */\nexport class ValidationError extends FoundryError {\n constructor(message: string, public readonly field?: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Asset not found in card or archive\n */\nexport class AssetNotFoundError extends FoundryError {\n constructor(public readonly uri: string) {\n super(`Asset not found: ${uri}`, 'ASSET_NOT_FOUND');\n this.name = 'AssetNotFoundError';\n }\n}\n\n/**\n * Format not supported for operation\n */\nexport class FormatNotSupportedError extends FoundryError {\n constructor(public readonly format: string, operation?: string) {\n const msg = operation\n ? `Format '${format}' not supported for ${operation}`\n : `Format not supported: ${format}`;\n super(msg, 'FORMAT_NOT_SUPPORTED');\n this.name = 'FormatNotSupportedError';\n }\n}\n\n/**\n * File size exceeds limits\n */\nexport class SizeLimitError extends FoundryError {\n constructor(\n public readonly actualSize: number,\n public readonly maxSize: number,\n context?: string\n ) {\n const actualMB = (actualSize / 1024 / 1024).toFixed(2);\n const maxMB = (maxSize / 1024 / 1024).toFixed(2);\n const msg = context\n ? `${context}: Size ${actualMB}MB exceeds limit ${maxMB}MB`\n : `Size ${actualMB}MB exceeds limit ${maxMB}MB`;\n super(msg, 'SIZE_LIMIT_EXCEEDED');\n this.name = 'SizeLimitError';\n }\n}\n\n/**\n * Path traversal or unsafe path detected\n */\nexport class PathTraversalError extends FoundryError {\n constructor(public readonly path: string) {\n super(`Unsafe path detected: ${path}`, 'PATH_TRAVERSAL');\n this.name = 'PathTraversalError';\n }\n}\n\n/**\n * Export operation would lose data\n */\nexport class DataLossError extends FoundryError {\n constructor(\n public readonly lostFields: string[],\n public readonly targetFormat: string\n ) {\n const fields = lostFields.slice(0, 3).join(', ');\n const more = lostFields.length > 3 ? ` and ${lostFields.length - 3} more` : '';\n super(\n `Export to ${targetFormat} would lose: ${fields}${more}`,\n 'DATA_LOSS'\n );\n this.name = 'DataLossError';\n }\n}\n\n/**\n * Check if an error is a FoundryError\n *\n * Uses Symbol.for() marker instead of instanceof to handle dual ESM/CJS package loading.\n * In dual-package environments, instanceof can fail if the error comes from a different\n * module instance (e.g., ESM vs CJS version of the same package). Symbol.for() creates\n * a global symbol shared across all module instances.\n */\nexport function isFoundryError(error: unknown): error is FoundryError {\n return (\n error instanceof Error &&\n FOUNDRY_ERROR_MARKER in error &&\n (error as Record<symbol, unknown>)[FOUNDRY_ERROR_MARKER] === true\n );\n}\n\n/**\n * Wrap unknown errors in a FoundryError\n */\nexport function wrapError(error: unknown, context?: string): FoundryError {\n if (isFoundryError(error)) {\n return error;\n }\n\n const message = error instanceof Error\n ? error.message\n : String(error);\n\n return new FoundryError(\n context ? `${context}: ${message}` : message,\n 'UNKNOWN_ERROR'\n );\n}\n","/**\n * Data URL Utilities\n *\n * Convert between Uint8Array buffers and data URLs.\n * Handles large buffers (>10MB) without stack overflow by processing in chunks.\n */\n\nimport type { BinaryData } from './binary.js';\nimport { encodeChunked as base64Encode, decode as base64Decode } from './base64.js';\nimport { ValidationError } from './errors.js';\n\n/**\n * Convert Uint8Array to data URL.\n * Handles large buffers (>10MB) without stack overflow by processing in chunks.\n *\n * @param buffer - Binary data to encode\n * @param mimeType - MIME type for the data URL (e.g., 'image/png', 'application/octet-stream')\n * @returns Data URL string\n *\n * @example\n * ```typescript\n * const png = new Uint8Array([...]);\n * const dataUrl = toDataURL(png, 'image/png');\n * // => \"data:image/png;base64,iVBORw0KGgo...\"\n * ```\n */\nexport function toDataURL(buffer: BinaryData, mimeType: string): string {\n // Use chunked encoding to handle large buffers without stack overflow\n const base64 = base64Encode(buffer);\n return `data:${mimeType};base64,${base64}`;\n}\n\n/**\n * Parse a data URL back to buffer and MIME type.\n * Validates the data URL format before parsing.\n *\n * @param dataUrl - Data URL string to parse\n * @returns Object containing the decoded buffer and MIME type\n * @throws Error if the data URL format is invalid\n *\n * @example\n * ```typescript\n * const { buffer, mimeType } = fromDataURL('data:image/png;base64,iVBORw0KGgo...');\n * // buffer: Uint8Array\n * // mimeType: 'image/png'\n * ```\n */\nexport function fromDataURL(dataUrl: string): { buffer: Uint8Array; mimeType: string } {\n // Validate data URL format\n if (!dataUrl.startsWith('data:')) {\n throw new ValidationError('Invalid data URL: must start with \"data:\"', 'dataUrl');\n }\n\n const commaIndex = dataUrl.indexOf(',');\n if (commaIndex === -1) {\n throw new ValidationError('Invalid data URL: missing comma separator', 'dataUrl');\n }\n\n const header = dataUrl.slice(5, commaIndex); // Skip 'data:'\n const data = dataUrl.slice(commaIndex + 1);\n\n // Parse header: [<mediatype>][;base64]\n let mimeType = 'text/plain';\n let isBase64 = false;\n\n const parts = header.split(';');\n for (const part of parts) {\n if (part === 'base64') {\n isBase64 = true;\n } else if (part && !part.includes('=')) {\n // MIME type (not a parameter like charset=utf-8)\n mimeType = part;\n }\n }\n\n if (!isBase64) {\n // URL-encoded text data\n throw new ValidationError('Non-base64 data URLs are not supported', 'dataUrl');\n }\n\n const buffer = base64Decode(data);\n return { buffer, mimeType };\n}\n\n/**\n * Check if a string is a valid data URL\n *\n * @param str - String to check\n * @returns true if the string is a valid data URL format\n */\nexport function isDataURL(str: string): boolean {\n if (!str.startsWith('data:')) return false;\n const commaIndex = str.indexOf(',');\n if (commaIndex === -1) return false;\n const header = str.slice(5, commaIndex);\n return header.includes('base64');\n}\n","/**\n * URI Utilities\n *\n * Handles different asset URI schemes used in character cards.\n * Supports: embeded://, embedded://, ccdefault:, https://, http://,\n * data:, file://, __asset:, asset:, chara-ext-asset_\n */\n\nexport type URIScheme =\n | 'embeded' // embeded:// (CharX standard, note intentional typo)\n | 'ccdefault' // ccdefault:\n | 'https' // https://\n | 'http' // http://\n | 'data' // data:mime;base64,...\n | 'file' // file://\n | 'internal' // Internal asset ID (UUID/string)\n | 'pngchunk' // PNG chunk reference (__asset:, asset:, chara-ext-asset_)\n | 'unknown';\n\nexport interface ParsedURI {\n scheme: URIScheme;\n originalUri: string;\n normalizedUri: string; // Normalized form of the URI\n path?: string; // For embeded://, file://\n url?: string; // For http://, https://\n data?: string; // For data: URIs\n mimeType?: string; // For data: URIs\n encoding?: string; // For data: URIs (e.g., base64)\n chunkKey?: string; // For pngchunk - the key/index to look up\n chunkCandidates?: string[]; // For pngchunk - all possible chunk keys to search\n}\n\n/**\n * Normalize a URI to its canonical form\n * Handles common typos and variant formats\n */\nexport function normalizeURI(uri: string): string {\n const trimmed = uri.trim();\n\n // Fix embedded:// -> embeded:// (common typo, CharX spec uses single 'd')\n if (trimmed.startsWith('embedded://')) {\n return 'embeded://' + trimmed.substring('embedded://'.length);\n }\n\n // Normalize PNG chunk references to pngchunk: scheme\n if (trimmed.startsWith('__asset:')) {\n const id = trimmed.substring('__asset:'.length);\n return `pngchunk:${id}`;\n }\n if (trimmed.startsWith('asset:')) {\n const id = trimmed.substring('asset:'.length);\n return `pngchunk:${id}`;\n }\n if (trimmed.startsWith('chara-ext-asset_:')) {\n const id = trimmed.substring('chara-ext-asset_:'.length);\n return `pngchunk:${id}`;\n }\n if (trimmed.startsWith('chara-ext-asset_')) {\n const id = trimmed.substring('chara-ext-asset_'.length);\n return `pngchunk:${id}`;\n }\n\n return trimmed;\n}\n\n/**\n * Parse a URI and determine its scheme and components\n */\nexport function parseURI(uri: string): ParsedURI {\n const trimmed = uri.trim();\n const normalized = normalizeURI(trimmed);\n\n // PNG chunk references (__asset:, asset:, chara-ext-asset_, pngchunk:)\n if (\n trimmed.startsWith('__asset:') ||\n trimmed.startsWith('asset:') ||\n trimmed.startsWith('chara-ext-asset_') ||\n trimmed.startsWith('pngchunk:')\n ) {\n let assetId: string;\n if (trimmed.startsWith('__asset:')) {\n assetId = trimmed.substring('__asset:'.length);\n } else if (trimmed.startsWith('asset:')) {\n assetId = trimmed.substring('asset:'.length);\n } else if (trimmed.startsWith('chara-ext-asset_:')) {\n assetId = trimmed.substring('chara-ext-asset_:'.length);\n } else if (trimmed.startsWith('pngchunk:')) {\n assetId = trimmed.substring('pngchunk:'.length);\n } else {\n assetId = trimmed.substring('chara-ext-asset_'.length);\n }\n\n // Generate all possible chunk key variations for lookup\n const candidates = [\n assetId, // \"0\" or \"filename.png\"\n trimmed, // Original URI\n `asset:${assetId}`, // \"asset:0\"\n `__asset:${assetId}`, // \"__asset:0\"\n `__asset_${assetId}`, // \"__asset_0\"\n `chara-ext-asset_${assetId}`, // \"chara-ext-asset_0\"\n `chara-ext-asset_:${assetId}`, // \"chara-ext-asset_:0\"\n `pngchunk:${assetId}`, // \"pngchunk:0\"\n ];\n\n return {\n scheme: 'pngchunk',\n originalUri: uri,\n normalizedUri: normalized,\n chunkKey: assetId,\n chunkCandidates: candidates,\n };\n }\n\n // ccdefault: - use default asset\n if (trimmed === 'ccdefault:' || trimmed.startsWith('ccdefault:')) {\n return {\n scheme: 'ccdefault',\n originalUri: uri,\n normalizedUri: normalized,\n };\n }\n\n // embeded:// or embedded:// (normalize typo)\n if (trimmed.startsWith('embeded://') || trimmed.startsWith('embedded://')) {\n const path = trimmed.startsWith('embeded://')\n ? trimmed.substring('embeded://'.length)\n : trimmed.substring('embedded://'.length);\n return {\n scheme: 'embeded',\n originalUri: uri,\n normalizedUri: normalized,\n path,\n };\n }\n\n // https://\n if (trimmed.startsWith('https://')) {\n return {\n scheme: 'https',\n originalUri: uri,\n normalizedUri: normalized,\n url: trimmed,\n };\n }\n\n // http://\n if (trimmed.startsWith('http://')) {\n return {\n scheme: 'http',\n originalUri: uri,\n normalizedUri: normalized,\n url: trimmed,\n };\n }\n\n // data: URIs\n if (trimmed.startsWith('data:')) {\n const parsed = parseDataURI(trimmed);\n return {\n scheme: 'data',\n originalUri: uri,\n normalizedUri: normalized,\n ...parsed,\n };\n }\n\n // file://\n if (trimmed.startsWith('file://')) {\n const path = trimmed.substring('file://'.length);\n return {\n scheme: 'file',\n originalUri: uri,\n normalizedUri: normalized,\n path,\n };\n }\n\n // Internal asset ID (alphanumeric/UUID format)\n if (/^[a-zA-Z0-9_-]+$/.test(trimmed)) {\n return {\n scheme: 'internal',\n originalUri: uri,\n normalizedUri: normalized,\n path: trimmed,\n };\n }\n\n // Unknown scheme\n return {\n scheme: 'unknown',\n originalUri: uri,\n normalizedUri: normalized,\n };\n}\n\n/**\n * Parse a data URI into its components\n * Format: data:[<mediatype>][;base64],<data>\n */\nfunction parseDataURI(uri: string): { mimeType?: string; encoding?: string; data?: string } {\n const match = uri.match(/^data:([^;,]+)?(;base64)?,(.*)$/);\n\n if (!match) {\n return {};\n }\n\n return {\n mimeType: match[1] || 'text/plain',\n encoding: match[2] ? 'base64' : undefined,\n data: match[3],\n };\n}\n\n/**\n * Check if extension is an image format\n */\nexport function isImageExt(ext: string): boolean {\n const imageExts = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'];\n return imageExts.includes(ext.toLowerCase());\n}\n\n/**\n * Check if extension is an audio format\n */\nexport function isAudioExt(ext: string): boolean {\n const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac'];\n return audioExts.includes(ext.toLowerCase());\n}\n\n/**\n * Check if extension is a video format\n */\nexport function isVideoExt(ext: string): boolean {\n const videoExts = ['mp4', 'webm', 'avi', 'mov', 'mkv'];\n return videoExts.includes(ext.toLowerCase());\n}\n\n/** Safe MIME types for data: URIs that can be used in href/src */\nconst SAFE_DATA_URI_MIME_TYPES = new Set([\n // Images (safe for img src)\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n // Audio (safe for audio src)\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n 'audio/flac',\n 'audio/mp4',\n 'audio/aac',\n // Video (safe for video src)\n 'video/mp4',\n 'video/webm',\n // Text/data (generally safe)\n 'text/plain',\n 'application/json',\n 'application/octet-stream',\n]);\n\n/** Potentially dangerous MIME types that should NOT be used in href/src */\nconst DANGEROUS_DATA_URI_MIME_TYPES = new Set([\n // Executable/script content\n 'text/html',\n 'text/javascript',\n 'application/javascript',\n 'application/x-javascript',\n 'text/css',\n 'image/svg+xml', // SVG can contain scripts\n 'application/xhtml+xml',\n 'application/xml',\n]);\n\n/**\n * Options for URI safety validation\n */\nexport interface URISafetyOptions {\n /** Allow http:// URIs (default: false) */\n allowHttp?: boolean;\n /** Allow file:// URIs (default: false) */\n allowFile?: boolean;\n /**\n * Allowed MIME types for data: URIs (default: all safe types).\n * Set to empty array to reject all data: URIs.\n * Set to undefined to use default safe list.\n */\n allowedDataMimes?: string[];\n}\n\n/**\n * Result of URI safety check with detailed information\n */\nexport interface URISafetyResult {\n /** Whether the URI is safe to use */\n safe: boolean;\n /** Reason if unsafe */\n reason?: string;\n /** Detected scheme */\n scheme: URIScheme;\n /** MIME type for data: URIs */\n mimeType?: string;\n}\n\n/**\n * Validate if a URI is safe to use (detailed version)\n *\n * @param uri - URI to validate\n * @param options - Safety options\n * @returns Detailed safety result\n */\nexport function checkURISafety(uri: string, options: URISafetyOptions = {}): URISafetyResult {\n const parsed = parseURI(uri);\n\n switch (parsed.scheme) {\n case 'embeded':\n case 'ccdefault':\n case 'internal':\n case 'https':\n case 'pngchunk':\n return { safe: true, scheme: parsed.scheme };\n\n case 'data': {\n const mimeType = parsed.mimeType || 'text/plain';\n\n // Check for explicitly dangerous MIME types\n if (DANGEROUS_DATA_URI_MIME_TYPES.has(mimeType)) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: `Data URI with potentially dangerous MIME type: ${mimeType}`,\n };\n }\n\n // If custom allowed list is provided, check against it\n if (options.allowedDataMimes !== undefined) {\n if (options.allowedDataMimes.length === 0) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: 'Data URIs are not allowed',\n };\n }\n if (!options.allowedDataMimes.includes(mimeType)) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: `Data URI MIME type not in allowed list: ${mimeType}`,\n };\n }\n }\n\n // Otherwise use default safe list\n if (!SAFE_DATA_URI_MIME_TYPES.has(mimeType)) {\n return {\n safe: false,\n scheme: parsed.scheme,\n mimeType,\n reason: `Unknown data URI MIME type: ${mimeType}`,\n };\n }\n\n return { safe: true, scheme: parsed.scheme, mimeType };\n }\n\n case 'http':\n if (options.allowHttp === true) {\n return { safe: true, scheme: parsed.scheme };\n }\n return { safe: false, scheme: parsed.scheme, reason: 'HTTP URIs are not allowed' };\n\n case 'file':\n if (options.allowFile === true) {\n return { safe: true, scheme: parsed.scheme };\n }\n return { safe: false, scheme: parsed.scheme, reason: 'File URIs are not allowed' };\n\n case 'unknown':\n default:\n return { safe: false, scheme: parsed.scheme, reason: 'Unknown URI scheme' };\n }\n}\n\n/**\n * Validate if a URI is safe to use (simple boolean version for backwards compatibility)\n *\n * @deprecated Use checkURISafety() for detailed safety information\n */\nexport function isURISafe(uri: string, options: { allowHttp?: boolean; allowFile?: boolean } = {}): boolean {\n return checkURISafety(uri, options).safe;\n}\n\n/**\n * Extract file extension from URI\n */\nexport function getExtensionFromURI(uri: string): string {\n const parsed = parseURI(uri);\n\n if (parsed.path) {\n const parts = parsed.path.split('.');\n if (parts.length > 1) {\n return parts[parts.length - 1]!.toLowerCase();\n }\n }\n\n if (parsed.url) {\n const urlParts = parsed.url.split('?')[0]!.split('.');\n if (urlParts.length > 1) {\n return urlParts[urlParts.length - 1]!.toLowerCase();\n }\n }\n\n if (parsed.mimeType) {\n return getExtFromMimeType(parsed.mimeType);\n }\n\n return 'unknown';\n}\n\n/**\n * Get MIME type from file extension\n */\nexport function getMimeTypeFromExt(ext: string): string {\n const extToMime: Record<string, string> = {\n // Images\n 'png': 'image/png',\n 'jpg': 'image/jpeg',\n 'jpeg': 'image/jpeg',\n 'webp': 'image/webp',\n 'gif': 'image/gif',\n 'avif': 'image/avif',\n 'svg': 'image/svg+xml',\n 'bmp': 'image/bmp',\n 'ico': 'image/x-icon',\n\n // Audio\n 'mp3': 'audio/mpeg',\n 'wav': 'audio/wav',\n 'ogg': 'audio/ogg',\n 'flac': 'audio/flac',\n 'm4a': 'audio/mp4',\n 'aac': 'audio/aac',\n\n // Video\n 'mp4': 'video/mp4',\n 'webm': 'video/webm',\n 'avi': 'video/x-msvideo',\n 'mov': 'video/quicktime',\n 'mkv': 'video/x-matroska',\n\n // Text/Data\n 'json': 'application/json',\n 'txt': 'text/plain',\n 'html': 'text/html',\n 'css': 'text/css',\n 'js': 'application/javascript',\n };\n\n return extToMime[ext.toLowerCase()] || 'application/octet-stream';\n}\n\n/**\n * Get file extension from MIME type\n */\nexport function getExtFromMimeType(mimeType: string): string {\n const mimeToExt: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/avif': 'avif',\n 'image/svg+xml': 'svg',\n 'image/bmp': 'bmp',\n 'image/x-icon': 'ico',\n 'audio/mpeg': 'mp3',\n 'audio/wav': 'wav',\n 'audio/ogg': 'ogg',\n 'audio/flac': 'flac',\n 'audio/mp4': 'm4a',\n 'audio/aac': 'aac',\n 'video/mp4': 'mp4',\n 'video/webm': 'webm',\n 'video/x-msvideo': 'avi',\n 'video/quicktime': 'mov',\n 'video/x-matroska': 'mkv',\n 'application/json': 'json',\n 'text/plain': 'txt',\n 'text/html': 'html',\n 'text/css': 'css',\n 'application/javascript': 'js',\n };\n\n return mimeToExt[mimeType] || 'bin';\n}\n\n/**\n * Build a data URI from binary data and MIME type\n */\nexport function buildDataURI(data: string, mimeType: string, isBase64 = true): string {\n if (isBase64) {\n return `data:${mimeType};base64,${data}`;\n }\n return `data:${mimeType},${encodeURIComponent(data)}`;\n}\n","/**\n * Image Analysis Utilities\n *\n * Detect properties of image files from binary data.\n */\n\nimport {\n type BinaryData,\n indexOf,\n fromLatin1,\n} from './binary.js';\n\n/**\n * Check if an image buffer contains animation data.\n * Supports: APNG, WebP (Animated), GIF\n */\nexport function isAnimatedImage(data: BinaryData, _mimeType?: string): boolean {\n // 1. WebP Detection\n // RIFF .... WEBP\n if (\n data.length > 12 &&\n data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 && // RIFF\n data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50 // WEBP\n ) {\n // Check for VP8X chunk\n // VP8X chunk header: 'VP8X' (bytes 12-15)\n if (\n data[12] === 0x56 && data[13] === 0x50 && data[14] === 0x38 && data[15] === 0x58\n ) {\n // Flags byte is at offset 20 (16 + 4 bytes chunk size)\n // Animation bit is bit 1 (0x02)\n const flags = data[20];\n return (flags! & 0x02) !== 0;\n }\n return false;\n }\n\n // 2. PNG/APNG Detection\n // Signature: 89 50 4E 47 0D 0A 1A 0A\n if (\n data.length > 8 &&\n data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4E && data[3] === 0x47\n ) {\n // Search for 'acTL' chunk (Animation Control)\n // It must appear before IDAT.\n // Simple search: indexOf('acTL')\n // Note: theoretically 'acTL' string could appear in other data, but highly unlikely in valid PNG structure before IDAT\n // We can iterate chunks to be safe, but indexOf is faster for a quick check\n const actlSig = fromLatin1('acTL');\n const idatSig = fromLatin1('IDAT');\n \n const actlIndex = indexOf(data, actlSig);\n if (actlIndex === -1) return false;\n\n const idatIndex = indexOf(data, idatSig);\n // If acTL exists and is before the first IDAT (or IDAT not found yet), it's APNG\n return idatIndex === -1 || actlIndex < idatIndex;\n }\n\n // 3. GIF Detection\n // Signature: GIF87a or GIF89a\n if (\n data.length > 6 &&\n data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 // GIF\n ) {\n // Check for NETSCAPE2.0 extension (looping animation)\n // This is a heuristic. Static GIFs are rare in this domain but possible.\n // Full frame counting is expensive. Presence of NETSCAPE block is a strong indicator.\n const netscape = fromLatin1('NETSCAPE2.0');\n return indexOf(data, netscape) !== -1;\n }\n\n return false;\n}\n","/**\n * UUID Generation Utilities\n *\n * Provides crypto-grade UUID v4 generation that works in Node.js,\n * browsers (secure contexts), and falls back gracefully.\n */\n\n/**\n * Format 16 random bytes as a UUID v4 string\n */\nfunction formatUUID(bytes: Uint8Array): string {\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Fallback UUID generation using Math.random()\n * Only used when crypto APIs are unavailable (rare)\n */\nfunction mathRandomUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generate a cryptographically secure UUID v4.\n *\n * Uses crypto.randomUUID() when available (Node.js 19+, modern browsers).\n * Falls back to crypto.getRandomValues() if randomUUID is unavailable.\n * Last resort uses Math.random() (non-secure, emits warning in dev).\n *\n * @returns A valid RFC 4122 UUID v4 string\n *\n * @example\n * ```typescript\n * const id = generateUUID();\n * // => \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateUUID(): string {\n // Node.js 19+ or browser with secure context\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n\n // Fallback using crypto.getRandomValues (older Node/browsers)\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n // Set version (4) and variant (RFC 4122)\n bytes[6] = (bytes[6]! & 0x0f) | 0x40; // Version 4\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // Variant 1\n return formatUUID(bytes);\n }\n\n // Last resort - non-secure fallback\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'development') {\n console.warn('[character-foundry/core] generateUUID: Using insecure Math.random() fallback');\n }\n return mathRandomUUID();\n}\n\n/**\n * Validate if a string is a valid UUID v4\n *\n * @param uuid - String to validate\n * @returns true if valid UUID v4 format\n */\nexport function isValidUUID(uuid: string): boolean {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid);\n}\n","/**\n * Binary Data Utilities\n *\n * Universal binary data operations using Uint8Array.\n * Works in both Node.js and browser environments.\n */\n\n/**\n * Universal binary data type (works in both environments)\n */\nexport type BinaryData = Uint8Array;\n\n/**\n * Read a 32-bit big-endian unsigned integer\n */\nexport function readUInt32BE(data: BinaryData, offset: number): number {\n return (\n (data[offset]! << 24) |\n (data[offset + 1]! << 16) |\n (data[offset + 2]! << 8) |\n data[offset + 3]!\n ) >>> 0;\n}\n\n/**\n * Write a 32-bit big-endian unsigned integer\n */\nexport function writeUInt32BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 24) & 0xff;\n data[offset + 1] = (value >>> 16) & 0xff;\n data[offset + 2] = (value >>> 8) & 0xff;\n data[offset + 3] = value & 0xff;\n}\n\n/**\n * Read a 16-bit big-endian unsigned integer\n */\nexport function readUInt16BE(data: BinaryData, offset: number): number {\n return ((data[offset]! << 8) | data[offset + 1]!) >>> 0;\n}\n\n/**\n * Write a 16-bit big-endian unsigned integer\n */\nexport function writeUInt16BE(data: BinaryData, value: number, offset: number): void {\n data[offset] = (value >>> 8) & 0xff;\n data[offset + 1] = value & 0xff;\n}\n\n/**\n * Find a byte sequence in binary data\n */\nexport function indexOf(data: BinaryData, search: BinaryData, fromIndex = 0): number {\n outer: for (let i = fromIndex; i <= data.length - search.length; i++) {\n for (let j = 0; j < search.length; j++) {\n if (data[i + j] !== search[j]) continue outer;\n }\n return i;\n }\n return -1;\n}\n\n/**\n * Concatenate multiple binary arrays\n */\nexport function concat(...arrays: BinaryData[]): BinaryData {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Slice binary data (returns a view, not a copy)\n */\nexport function slice(data: BinaryData, start: number, end?: number): BinaryData {\n return data.subarray(start, end);\n}\n\n/**\n * Copy a portion of binary data (returns a new array)\n */\nexport function copy(data: BinaryData, start: number, end?: number): BinaryData {\n return data.slice(start, end);\n}\n\n/**\n * Convert string to binary (UTF-8)\n */\nexport function fromString(str: string): BinaryData {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Convert binary to string (UTF-8)\n */\nexport function toString(data: BinaryData): string {\n return new TextDecoder().decode(data);\n}\n\n/**\n * Convert string to binary (Latin1 - for PNG keywords and similar)\n */\nexport function fromLatin1(str: string): BinaryData {\n const result = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n result[i] = str.charCodeAt(i) & 0xff;\n }\n return result;\n}\n\n/**\n * Convert binary to string (Latin1)\n */\nexport function toLatin1(data: BinaryData): string {\n let result = '';\n for (let i = 0; i < data.length; i++) {\n result += String.fromCharCode(data[i]!);\n }\n return result;\n}\n\n/**\n * Compare two binary arrays for equality\n */\nexport function equals(a: BinaryData, b: BinaryData): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Create a new Uint8Array filled with zeros\n */\nexport function alloc(size: number): BinaryData {\n return new Uint8Array(size);\n}\n\n/**\n * Create a Uint8Array from an array of numbers\n */\nexport function from(data: number[] | ArrayBuffer | BinaryData): BinaryData {\n if (data instanceof Uint8Array) {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n return new Uint8Array(data);\n}\n\n/**\n * Check if value is a Uint8Array\n */\nexport function isBinaryData(value: unknown): value is BinaryData {\n return value instanceof Uint8Array;\n}\n\n/**\n * Convert Node.js Buffer to Uint8Array (no-op if already Uint8Array)\n * This provides compatibility when interfacing with Node.js code\n */\nexport function toUint8Array(data: BinaryData | Buffer): BinaryData {\n if (data instanceof Uint8Array) {\n // Buffer extends Uint8Array, but we want a plain Uint8Array\n // This ensures we get a proper Uint8Array in all cases\n if (Object.getPrototypeOf(data).constructor.name === 'Buffer') {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n return data;\n }\n return new Uint8Array(data);\n}\n\n/**\n * Convert binary data to hex string\n */\nexport function toHex(data: BinaryData): string {\n return Array.from(data)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to binary data\n */\nexport function fromHex(hex: string): BinaryData {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n","/**\n * ZIP Utility Functions\n *\n * Handles ZIP format detection and SFX (self-extracting) archive support.\n * Uses Uint8Array for universal browser/Node.js compatibility.\n */\n\nimport { indexOf, concat, type BinaryData } from './binary.js';\nimport { Unzip, UnzipInflate, UnzipPassThrough, type Unzipped, type UnzipFile } from 'fflate';\n\n// ZIP local file header signature: PK\\x03\\x04\nexport const ZIP_SIGNATURE = new Uint8Array([0x50, 0x4b, 0x03, 0x04]);\n\n// JPEG signatures\nexport const JPEG_SIGNATURE = new Uint8Array([0xff, 0xd8, 0xff]);\n\n/**\n * How to handle unsafe paths (with .. or absolute paths) during extraction.\n *\n * - 'skip': Silently skip unsafe files (default, backwards compatible)\n * - 'warn': Skip and call onUnsafePath callback for logging/monitoring\n * - 'reject': Throw ZipPreflightError immediately (strictest, recommended for untrusted input)\n */\nexport type UnsafePathHandling = 'skip' | 'warn' | 'reject';\n\n/**\n * Size limits for ZIP operations\n */\nexport interface ZipSizeLimits {\n /** Max size per file (default 50MB) */\n maxFileSize: number;\n /** Max total size (default 200MB) */\n maxTotalSize: number;\n /** Max number of files (default 1000) */\n maxFiles: number;\n /**\n * How to handle files with unsafe paths (path traversal attempts).\n *\n * Default: 'skip' (backwards compatible - silently ignores unsafe paths)\n * Recommended: 'reject' for untrusted input (throws on path traversal)\n *\n * @security Path traversal (../) in ZIP entries can lead to arbitrary file\n * overwrites when extracted to disk. While this library returns files in\n * memory, consumers may write to disk using the paths.\n */\n unsafePathHandling?: UnsafePathHandling;\n /**\n * Callback invoked when unsafe path is detected (only with 'warn' handling).\n * Use for logging/monitoring path traversal attempts.\n */\n onUnsafePath?: (path: string, reason: string) => void;\n}\n\nexport const DEFAULT_ZIP_LIMITS: ZipSizeLimits = {\n maxFileSize: 50 * 1024 * 1024, // 50MB per file (Risu standard)\n maxTotalSize: 500 * 1024 * 1024, // 500MB total (CharX can have many expression assets)\n maxFiles: 10000, // CharX cards can have 2k+ expression assets\n unsafePathHandling: 'skip', // Backwards compatible default\n};\n\n/**\n * Check if a buffer contains ZIP data (anywhere in the buffer).\n * This handles both regular ZIPs and SFX (self-extracting) archives.\n * @param data - Binary data to check\n * @returns true if ZIP signature found\n */\nexport function isZipBuffer(data: BinaryData): boolean {\n return indexOf(data, ZIP_SIGNATURE) >= 0;\n}\n\n/**\n * Check if a buffer starts with ZIP signature (standard ZIP detection).\n * @param data - Binary data to check\n * @returns true if data starts with PK\\x03\\x04\n */\nexport function startsWithZipSignature(data: BinaryData): boolean {\n return (\n data.length >= 4 &&\n data[0] === 0x50 &&\n data[1] === 0x4b &&\n data[2] === 0x03 &&\n data[3] === 0x04\n );\n}\n\n/**\n * Check if data starts with JPEG signature\n */\nexport function isJPEG(data: BinaryData): boolean {\n return (\n data.length >= 3 &&\n data[0] === 0xff &&\n data[1] === 0xd8 &&\n data[2] === 0xff\n );\n}\n\n/**\n * Check if data is a JPEG with appended ZIP (JPEG+CharX hybrid)\n */\nexport function isJpegCharX(data: BinaryData): boolean {\n if (!isJPEG(data)) return false;\n // Look for ZIP signature after JPEG data\n return indexOf(data, ZIP_SIGNATURE) > 0;\n}\n\n/**\n * Find ZIP data start in buffer (handles SFX/self-extracting archives).\n * SFX archives have an executable stub prepended to the ZIP data.\n *\n * @param data - Binary data that may contain ZIP data (possibly with SFX prefix)\n * @returns Binary data starting at ZIP signature, or original data if not found/already at start\n */\nexport function findZipStart(data: BinaryData): BinaryData {\n const index = indexOf(data, ZIP_SIGNATURE);\n\n if (index > 0) {\n // SFX archive detected - return data starting at ZIP signature\n return data.subarray(index);\n }\n\n // Either ZIP starts at 0, or no ZIP signature found - return original\n return data;\n}\n\n/**\n * Get the offset of ZIP data within a buffer.\n * @param data - Binary data to search\n * @returns Offset of ZIP signature, or -1 if not found\n */\nexport function getZipOffset(data: BinaryData): number {\n return indexOf(data, ZIP_SIGNATURE);\n}\n\n/**\n * Check if data is a valid ZIP archive (has signature at start or is SFX)\n * @param data - Binary data to check\n * @returns true if data contains valid ZIP structure\n */\nexport function isValidZip(data: BinaryData): boolean {\n const offset = getZipOffset(data);\n if (offset < 0) return false;\n\n // Check if there's enough data after the signature for a minimal ZIP\n // Minimum ZIP: local file header (30 bytes) + central directory (46 bytes) + end of central dir (22 bytes)\n return data.length - offset >= 98;\n}\n\n/**\n * Validate a path for directory traversal attacks\n * @param path - File path to validate\n * @returns true if path is safe\n */\nexport function isPathSafe(path: string): boolean {\n // Reject absolute paths\n if (path.startsWith('/') || /^[a-zA-Z]:/.test(path)) {\n return false;\n }\n\n // Reject path traversal\n if (path.includes('..')) {\n return false;\n }\n\n // Reject backslashes (Windows-style paths that might be used for traversal)\n if (path.includes('\\\\')) {\n return false;\n }\n\n return true;\n}\n\n/**\n * ZIP Central Directory File Header structure\n */\nexport interface ZipCentralDirEntry {\n fileName: string;\n compressedSize: number;\n uncompressedSize: number;\n}\n\n/**\n * Result of preflight ZIP size check\n */\nexport interface ZipPreflightResult {\n entries: ZipCentralDirEntry[];\n totalUncompressedSize: number;\n fileCount: number;\n}\n\n/**\n * Error thrown when ZIP preflight fails due to size limits\n */\nexport class ZipPreflightError extends Error {\n constructor(\n message: string,\n public readonly totalSize?: number,\n public readonly maxSize?: number,\n public readonly oversizedEntry?: string,\n public readonly entrySize?: number,\n public readonly maxEntrySize?: number\n ) {\n super(message);\n this.name = 'ZipPreflightError';\n }\n}\n\n/**\n * Preflight check ZIP central directory to get uncompressed sizes BEFORE extraction.\n * This prevents zip bomb attacks by rejecting archives with dangerous compression ratios\n * or oversized entries without fully decompressing them.\n *\n * The ZIP format stores uncompressed sizes in the central directory at the end of the file.\n * This function reads that metadata without decompressing any actual data.\n *\n * @param data - ZIP file data (can be SFX/self-extracting, will find ZIP start)\n * @param limits - Size limits to enforce\n * @returns Preflight result with entry info and totals\n * @throws ZipPreflightError if limits would be exceeded\n */\nexport function preflightZipSizes(\n data: BinaryData,\n limits: ZipSizeLimits = DEFAULT_ZIP_LIMITS\n): ZipPreflightResult {\n // Find ZIP start (handles SFX/hybrid archives)\n const zipData = findZipStart(data);\n\n // Find End of Central Directory (EOCD) signature: PK\\x05\\x06\n // EOCD is at the end of the file, max comment size is 65535 bytes\n const eocdSignature = new Uint8Array([0x50, 0x4b, 0x05, 0x06]);\n const searchStart = Math.max(0, zipData.length - 65535 - 22);\n\n let eocdOffset = -1;\n for (let i = zipData.length - 22; i >= searchStart; i--) {\n if (\n zipData[i] === eocdSignature[0] &&\n zipData[i + 1] === eocdSignature[1] &&\n zipData[i + 2] === eocdSignature[2] &&\n zipData[i + 3] === eocdSignature[3]\n ) {\n // SECURITY: Validate comment length to avoid false positives\n // If the ZIP comment contains the EOCD signature bytes, we could\n // find the wrong location. Verify by checking comment length.\n // Comment length is at offset +20 (2 bytes, little-endian)\n if (i + 21 < zipData.length) {\n const commentLength = zipData[i + 20]! | (zipData[i + 21]! << 8);\n // True EOCD should be at: file_size - 22 - comment_length\n const expectedOffset = zipData.length - 22 - commentLength;\n if (i === expectedOffset) {\n eocdOffset = i;\n break;\n }\n // Otherwise, this is a false positive (signature in comment), continue searching\n }\n }\n }\n\n if (eocdOffset < 0) {\n throw new ZipPreflightError('Invalid ZIP: End of Central Directory not found');\n }\n\n // Parse EOCD\n // Offset 8: Total number of central directory records\n // Offset 12: Size of central directory\n // Offset 16: Offset of start of central directory\n const totalEntries = zipData[eocdOffset + 8]! | (zipData[eocdOffset + 9]! << 8);\n const _cdSize = readUInt32LEFromBytes(zipData, eocdOffset + 12);\n const cdOffset = readUInt32LEFromBytes(zipData, eocdOffset + 16);\n\n // Check file count limit\n if (totalEntries > limits.maxFiles) {\n throw new ZipPreflightError(\n `ZIP contains ${totalEntries} files, exceeds limit of ${limits.maxFiles}`,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined\n );\n }\n\n // Parse Central Directory entries\n const entries: ZipCentralDirEntry[] = [];\n let totalUncompressedSize = 0;\n let offset = cdOffset;\n\n for (let i = 0; i < totalEntries && offset < eocdOffset; i++) {\n // Central Directory File Header signature: PK\\x01\\x02\n if (\n zipData[offset] !== 0x50 ||\n zipData[offset + 1] !== 0x4b ||\n zipData[offset + 2] !== 0x01 ||\n zipData[offset + 3] !== 0x02\n ) {\n throw new ZipPreflightError('Invalid ZIP: Central Directory header corrupted');\n }\n\n // Offset 20: Compressed size (4 bytes)\n const compressedSize = readUInt32LEFromBytes(zipData, offset + 20);\n // Offset 24: Uncompressed size (4 bytes)\n const uncompressedSize = readUInt32LEFromBytes(zipData, offset + 24);\n // Offset 28: File name length (2 bytes)\n const fileNameLength = zipData[offset + 28]! | (zipData[offset + 29]! << 8);\n // Offset 30: Extra field length (2 bytes)\n const extraLength = zipData[offset + 30]! | (zipData[offset + 31]! << 8);\n // Offset 32: File comment length (2 bytes)\n const commentLength = zipData[offset + 32]! | (zipData[offset + 33]! << 8);\n\n // Read file name\n const fileName = new TextDecoder().decode(\n zipData.subarray(offset + 46, offset + 46 + fileNameLength)\n );\n\n // Skip directories (names ending with /)\n if (!fileName.endsWith('/')) {\n // Check per-entry size limit\n if (uncompressedSize > limits.maxFileSize) {\n throw new ZipPreflightError(\n `File \"${fileName}\" uncompressed size ${uncompressedSize} exceeds limit ${limits.maxFileSize}`,\n undefined,\n undefined,\n fileName,\n uncompressedSize,\n limits.maxFileSize\n );\n }\n\n totalUncompressedSize += uncompressedSize;\n\n // Check total size limit early to fail fast\n if (totalUncompressedSize > limits.maxTotalSize) {\n throw new ZipPreflightError(\n `Total uncompressed size ${totalUncompressedSize} exceeds limit ${limits.maxTotalSize}`,\n totalUncompressedSize,\n limits.maxTotalSize\n );\n }\n\n entries.push({\n fileName,\n compressedSize,\n uncompressedSize,\n });\n }\n\n // Move to next entry\n offset += 46 + fileNameLength + extraLength + commentLength;\n }\n\n return {\n entries,\n totalUncompressedSize,\n fileCount: entries.length,\n };\n}\n\n/**\n * Read a 32-bit little-endian unsigned integer from bytes\n */\nfunction readUInt32LEFromBytes(data: BinaryData, offset: number): number {\n return (\n data[offset]! |\n (data[offset + 1]! << 8) |\n (data[offset + 2]! << 16) |\n (data[offset + 3]! << 24)\n ) >>> 0; // Convert to unsigned\n}\n\n/**\n * Streaming ZIP extraction with real-time byte limit enforcement.\n *\n * Unlike preflightZipSizes which only checks central directory metadata,\n * this function tracks ACTUAL decompressed bytes during extraction and\n * aborts immediately if limits are exceeded. This protects against\n * malicious archives that lie about sizes in their central directory.\n *\n * @security Path safety is enforced based on `limits.unsafePathHandling`:\n * - 'skip' (default): Silently ignores files with unsafe paths\n * - 'warn': Skips unsafe files and calls onUnsafePath callback\n * - 'reject': Throws ZipPreflightError on unsafe paths\n *\n * @performance SYNCHRONOUS BLOCKING OPERATION\n * This function runs synchronously and will block the event loop during\n * decompression. For large archives (>50MB), this can cause UI freezes\n * in browser environments or block the Node.js event loop.\n *\n * Recommendations:\n * - Browser: Use Web Workers for archives >10MB to avoid freezing the UI\n * - Node.js: Consider worker threads for archives >50MB\n * - All environments: Call preflightZipSizes() first to validate before extraction\n *\n * @param data - ZIP file data (can be SFX/self-extracting)\n * @param limits - Size limits to enforce\n * @returns Extracted files (synchronously)\n * @throws ZipPreflightError if limits are exceeded during extraction\n */\nexport function streamingUnzipSync(\n data: BinaryData,\n limits: ZipSizeLimits = DEFAULT_ZIP_LIMITS\n): Unzipped {\n // Find ZIP start (handles SFX/hybrid archives)\n const zipData = findZipStart(data);\n\n const result: Unzipped = {};\n let totalBytes = 0;\n let fileCount = 0;\n let error: Error | null = null;\n\n // Get path handling mode (default to 'skip' for backwards compatibility)\n const unsafePathHandling = limits.unsafePathHandling ?? 'skip';\n\n // Track chunks per file for concatenation\n const fileChunks = new Map<string, Uint8Array[]>();\n\n const unzipper = new Unzip((file: UnzipFile) => {\n if (error) return;\n\n // Skip directories\n if (file.name.endsWith('/')) {\n file.start();\n return;\n }\n\n // SECURITY: Check for path traversal attacks\n if (!isPathSafe(file.name)) {\n const reason = file.name.includes('..')\n ? 'path traversal (..)'\n : file.name.startsWith('/') || /^[a-zA-Z]:/.test(file.name)\n ? 'absolute path'\n : 'backslash in path';\n\n if (unsafePathHandling === 'reject') {\n error = new ZipPreflightError(\n `Unsafe path detected: \"${file.name}\" - ${reason}. ` +\n `This may be a path traversal attack.`\n );\n file.terminate();\n return;\n }\n\n if (unsafePathHandling === 'warn' && limits.onUnsafePath) {\n limits.onUnsafePath(file.name, reason);\n }\n\n // Skip this file (consume but don't store) for 'skip' and 'warn' modes\n // SECURITY: Still count bytes to prevent zip bombs hidden behind unsafe paths\n file.ondata = (err, chunk, _final) => {\n if (error) return;\n if (err) {\n error = err;\n return;\n }\n if (chunk && chunk.length > 0) {\n totalBytes += chunk.length;\n if (totalBytes > limits.maxTotalSize) {\n error = new ZipPreflightError(\n `Total actual size ${totalBytes} exceeds limit ${limits.maxTotalSize}`,\n totalBytes,\n limits.maxTotalSize\n );\n file.terminate();\n }\n }\n };\n file.start();\n return;\n }\n\n fileCount++;\n if (fileCount > limits.maxFiles) {\n error = new ZipPreflightError(\n `File count ${fileCount} exceeds limit ${limits.maxFiles}`\n );\n file.terminate();\n return;\n }\n\n const chunks: Uint8Array[] = [];\n fileChunks.set(file.name, chunks);\n let fileBytes = 0;\n\n file.ondata = (err, chunk, final) => {\n if (error) return;\n\n if (err) {\n error = err;\n return;\n }\n\n if (chunk && chunk.length > 0) {\n fileBytes += chunk.length;\n totalBytes += chunk.length;\n\n // Check per-file size limit (actual decompressed bytes)\n if (fileBytes > limits.maxFileSize) {\n error = new ZipPreflightError(\n `File \"${file.name}\" actual size ${fileBytes} exceeds limit ${limits.maxFileSize}`,\n undefined,\n undefined,\n file.name,\n fileBytes,\n limits.maxFileSize\n );\n file.terminate();\n return;\n }\n\n // Check total size limit (actual decompressed bytes)\n if (totalBytes > limits.maxTotalSize) {\n error = new ZipPreflightError(\n `Total actual size ${totalBytes} exceeds limit ${limits.maxTotalSize}`,\n totalBytes,\n limits.maxTotalSize\n );\n file.terminate();\n return;\n }\n\n chunks.push(chunk);\n }\n\n if (final && !error) {\n // Concatenate all chunks for this file\n result[file.name] = concat(...chunks);\n }\n };\n\n file.start();\n });\n\n // Register decompression handlers\n unzipper.register(UnzipInflate); // DEFLATE (compression method 8)\n unzipper.register(UnzipPassThrough); // Stored (compression method 0)\n\n // Push all data - fflate processes synchronously when given full buffer\n unzipper.push(zipData, true);\n\n // If an error occurred during processing, throw it\n if (error) {\n throw error;\n }\n\n return result;\n}\n\n/**\n * Re-export Unzipped type for convenience\n */\nexport type { Unzipped };\n","/**\n * Voxta Types\n *\n * Type definitions for Voxta package format.\n */\n\nimport type { BinaryData } from '@character-foundry/core';\n\n/**\n * Valid compression levels\n */\nexport type CompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\n\n/**\n * Voxta resource kind enumeration\n * Used in EntryResource, ThumbnailResource, and Collection references\n */\nexport enum VoxtaResourceKind {\n Character = 1,\n Book = 2,\n Scenario = 3,\n}\n\n/**\n * Voxta resource reference\n */\nexport interface VoxtaResourceRef {\n Kind: VoxtaResourceKind | number;\n Id: string;\n}\n\n/**\n * Voxta package metadata\n */\nexport interface VoxtaPackage {\n $type: 'package';\n Id: string;\n Name: string;\n Version: string;\n Description?: string;\n Creator?: string;\n ExplicitContent?: boolean;\n EntryResource?: VoxtaResourceRef;\n ThumbnailResource?: VoxtaResourceRef;\n DateCreated?: string;\n DateModified?: string;\n}\n\n/**\n * Voxta TTS configuration\n */\nexport interface VoxtaTtsConfig {\n Voice: {\n parameters: {\n VoiceBackend?: string;\n VoiceId?: string;\n Gender?: string;\n Filename?: string;\n FinetuneVoice?: string;\n [key: string]: unknown;\n };\n label: string;\n };\n Service: {\n ServiceName: string;\n ServiceId: string;\n };\n}\n\n/**\n * Voxta script\n */\nexport interface VoxtaScript {\n Name: string;\n Content: string;\n}\n\n/**\n * Voxta character\n */\nexport interface VoxtaCharacter {\n $type: 'character';\n Id: string;\n Name: string;\n Label?: string; // Optional nickname/display name\n Version?: string;\n PackageId?: string;\n\n // Core Info\n Description?: string; // Physical/visual appearance\n Personality?: string;\n Profile?: string; // Profile/Backstory\n Scenario?: string;\n FirstMessage?: string;\n AlternativeFirstMessages?: string[]; // Alternate greetings (maps to CCv3 alternate_greetings)\n MessageExamples?: string;\n\n // System prompts\n SystemPrompt?: string; // System prompt (additive)\n PostHistoryInstructions?: string; // UJB - added at end of messages\n Context?: string; // Context field\n Instructions?: string; // User instructions (not read by LLM)\n\n // Persona overrides\n UserNameOverride?: string;\n UserDescriptionOverride?: string;\n\n // Metadata\n Creator?: string;\n CreatorNotes?: string;\n Tags?: string[];\n ExplicitContent?: boolean;\n Culture?: string;\n ImportedFrom?: string; // Source tracking\n\n // References\n MemoryBooks?: string[];\n DefaultScenarios?: string[];\n\n // TTS\n TextToSpeech?: VoxtaTtsConfig[];\n\n // AI Settings\n ChatStyle?: number;\n EnableThinkingSpeech?: boolean;\n NotifyUserAwayReturn?: boolean;\n TimeAware?: boolean;\n UseMemory?: boolean;\n MaxTokens?: number;\n MaxSentences?: number;\n SystemPromptOverrideType?: number;\n\n // Simulation Settings\n ClimaxSensitivity?: number;\n PleasureDecay?: number;\n\n // Advanced\n Scripts?: VoxtaScript[];\n Augmentations?: unknown[];\n\n Thumbnail?: {\n RandomizedETag?: string;\n ContentType?: string;\n };\n\n DateCreated?: string; // ISO timestamp\n DateModified?: string; // ISO timestamp\n}\n\n/**\n * Voxta book item\n */\nexport interface VoxtaBookItem {\n Id: string;\n Keywords: string[];\n Text: string;\n Weight?: number;\n Deleted?: boolean;\n CreatedAt?: string;\n LastUpdated?: string;\n DeletedAt?: string;\n}\n\n/**\n * Voxta book (lorebook)\n */\nexport interface VoxtaBook {\n $type: 'book';\n Id: string;\n Name: string;\n Version?: string;\n PackageId?: string;\n Description?: string;\n ExplicitContent?: boolean;\n Creator?: string;\n Items: VoxtaBookItem[];\n DateCreated?: string;\n DateModified?: string;\n}\n\n/**\n * Voxta collection item (reference to a resource)\n */\nexport interface VoxtaCollectionItem {\n Resource: VoxtaResourceRef;\n}\n\n/**\n * Voxta collection folder (organizational grouping)\n */\nexport interface VoxtaCollectionFolder {\n Name: string;\n Description?: string;\n /** Kind of resources in this folder (1=Character, 2=Book, 3=Scenario) */\n Kind: VoxtaResourceKind | number;\n Items: VoxtaCollectionItem[];\n /** Nested folders (if any) */\n Folders?: VoxtaCollectionFolder[];\n}\n\n/**\n * Voxta collection root structure\n */\nexport interface VoxtaCollectionRoot {\n Folders: VoxtaCollectionFolder[];\n}\n\n/**\n * Voxta collection - organizes resources into themed groups\n */\nexport interface VoxtaCollection {\n $type: 'collection';\n Id: string;\n Name: string;\n Version?: string;\n PackageId?: string;\n ExplicitContent?: boolean;\n Root: VoxtaCollectionRoot;\n Thumbnail?: {\n RandomizedETag?: string;\n ContentType?: string;\n };\n DateCreated?: string;\n DateModified?: string;\n}\n\n/**\n * Voxta scenario action\n */\nexport interface VoxtaAction {\n Name: string;\n Layer?: string;\n Arguments?: unknown[];\n FinalLayer?: boolean;\n Timing?: number;\n Description?: string;\n Disabled?: boolean;\n Once?: boolean;\n FlagsFilter?: string;\n EvaluateNextEvent?: boolean;\n Effect?: {\n SetFlags?: string[];\n Script?: string;\n Event?: string;\n Story?: string;\n Secret?: string;\n Instructions?: string;\n MaxSentences?: number;\n MaxTokens?: number;\n [key: string]: unknown;\n };\n}\n\n/**\n * Voxta scenario event (similar to action but for event triggers)\n */\nexport interface VoxtaEvent {\n Id?: string;\n Name: string;\n Layer?: string;\n Timing?: number;\n Description?: string;\n Arguments?: unknown[];\n Disabled?: boolean;\n FinalLayer?: boolean;\n Once?: boolean;\n FlagsFilter?: string;\n EvaluateNextEvent?: boolean;\n Effect?: {\n SetFlags?: string[];\n Script?: string;\n Event?: string;\n Story?: string;\n Secret?: string;\n Instructions?: string;\n MaxSentences?: number;\n MaxTokens?: number;\n [key: string]: unknown;\n };\n}\n\n/**\n * Voxta scenario context (conditional context blocks)\n */\nexport interface VoxtaContext {\n Name: string;\n Text: string;\n FlagsFilter?: string;\n Disabled?: boolean;\n}\n\n/**\n * Voxta scenario role - maps characters to scenario slots\n */\nexport interface VoxtaRole {\n Name: string;\n Description?: string;\n DefaultCharacterId: string;\n EnabledOnStart?: boolean;\n}\n\n/**\n * Voxta impersonation (user persona override)\n */\nexport interface VoxtaImpersonation {\n Name: string;\n Description?: string;\n}\n\n/**\n * Voxta scenario\n */\nexport interface VoxtaScenario {\n $type: 'scenario';\n Id: string;\n Name: string;\n Version?: string;\n ParentId?: string;\n PackageId?: string;\n Client?: string;\n Creator?: string;\n Description?: string;\n\n // Core content\n Template?: string;\n Messages?: string;\n SystemPrompt?: string;\n SystemPromptOverrideType?: number;\n\n // Character mappings\n Roles?: VoxtaRole[];\n NarratorCharacterId?: string;\n Impersonation?: VoxtaImpersonation;\n\n // Scripting/automation\n SharedScripts?: VoxtaScript[];\n Actions?: VoxtaAction[];\n Events?: VoxtaEvent[];\n Contexts?: VoxtaContext[];\n\n // Settings\n ExplicitContent?: boolean;\n ChatFlow?: number;\n ChatStyle?: number;\n MemoryBooks?: string[];\n\n // Metadata\n Thumbnail?: {\n ETag?: number;\n RandomizedETag?: string;\n ContentType?: string;\n };\n DateCreated?: string;\n DateModified?: string;\n\n // App control (optional)\n UserId?: string;\n AppControlled?: boolean;\n Locked?: boolean;\n}\n\n/**\n * Extracted Voxta asset\n */\nexport interface ExtractedVoxtaAsset {\n path: string;\n buffer: BinaryData;\n characterId?: string;\n}\n\n/**\n * Extracted Voxta character with assets\n */\nexport interface ExtractedVoxtaCharacter {\n id: string;\n data: VoxtaCharacter;\n thumbnail?: BinaryData;\n assets: ExtractedVoxtaAsset[];\n}\n\n/**\n * Extracted Voxta scenario\n */\nexport interface ExtractedVoxtaScenario {\n id: string;\n data: VoxtaScenario;\n thumbnail?: BinaryData;\n}\n\n/**\n * Extracted Voxta book\n */\nexport interface ExtractedVoxtaBook {\n id: string;\n data: VoxtaBook;\n}\n\n/**\n * Extracted Voxta collection with assets\n */\nexport interface ExtractedVoxtaCollection {\n id: string;\n data: VoxtaCollection;\n thumbnail?: BinaryData;\n}\n\n/**\n * Voxta export type\n * - 'package': Has package.json with full metadata\n * - 'scenario': Has Scenarios/ folder but no package.json (scenario export)\n * - 'character': Only has Characters/ folder (single/multi character export)\n * - 'collection': Has Collections/ folder (bundled content with organization)\n */\nexport type VoxtaExportType = 'package' | 'scenario' | 'character' | 'collection';\n\n/**\n * Complete extracted Voxta data\n */\nexport interface VoxtaData {\n package?: VoxtaPackage;\n characters: ExtractedVoxtaCharacter[];\n scenarios: ExtractedVoxtaScenario[];\n books: ExtractedVoxtaBook[];\n collections: ExtractedVoxtaCollection[];\n\n /**\n * Type of export detected:\n * - 'package': Has package.json\n * - 'scenario': Has Scenarios/ but no package.json\n * - 'character': Only Characters/ (no package.json or Scenarios/)\n * - 'collection': Has Collections/ folder\n */\n exportType: VoxtaExportType;\n}\n\n/**\n * Options for Voxta extraction\n */\nexport interface VoxtaReadOptions {\n maxFileSize?: number;\n maxAssetSize?: number;\n maxTotalSize?: number;\n}\n\n/**\n * Asset to include in Voxta export\n */\nexport interface VoxtaWriteAsset {\n type: string;\n name: string;\n ext: string;\n data: BinaryData;\n tags?: string[];\n isMain?: boolean;\n}\n\n/**\n * Options for building Voxta package\n */\nexport interface VoxtaWriteOptions {\n compressionLevel?: CompressionLevel;\n includePackageJson?: boolean;\n characterId?: string;\n packageId?: string;\n /** Scenario to include - uses scenario.Id as the key */\n scenario?: VoxtaScenario;\n /** Scenario thumbnail */\n scenarioThumbnail?: BinaryData;\n}\n\n/**\n * Result of building a Voxta package\n */\nexport interface VoxtaBuildResult {\n buffer: BinaryData;\n assetCount: number;\n totalSize: number;\n characterId: string;\n /** Scenario ID if a scenario was included */\n scenarioId?: string;\n}\n\n/**\n * Voxta extension data stored in CCv3 extensions\n */\nexport interface VoxtaExtensionData {\n id: string;\n version?: string;\n packageId?: string;\n label?: string;\n textToSpeech?: VoxtaTtsConfig[];\n appearance?: string;\n context?: string;\n instructions?: string;\n userNameOverride?: string;\n userDescriptionOverride?: string;\n culture?: string;\n importedFrom?: string;\n chatSettings?: {\n chatStyle?: number;\n enableThinkingSpeech?: boolean;\n notifyUserAwayReturn?: boolean;\n timeAware?: boolean;\n useMemory?: boolean;\n maxTokens?: number;\n maxSentences?: number;\n systemPromptOverrideType?: number;\n };\n simulationSettings?: {\n climaxSensitivity?: number;\n pleasureDecay?: number;\n };\n scripts?: VoxtaScript[];\n augmentations?: unknown[];\n scenario?: {\n actions?: VoxtaAction[];\n sharedScripts?: VoxtaScript[];\n };\n original?: Partial<VoxtaCharacter>;\n}\n\n/**\n * Loss report for Voxta export\n */\nexport interface VoxtaLossReport {\n lostFields: string[];\n lostAssets: string[];\n warnings: string[];\n reason: string;\n}\n","/**\n * Voxta Reader\n *\n * Extracts and parses .voxpkg files.\n */\n\nimport {\n type BinaryData,\n toString,\n ParseError,\n SizeLimitError,\n} from '@character-foundry/core';\nimport {\n type Unzipped,\n getZipOffset,\n streamingUnzipSync,\n ZipPreflightError,\n} from '@character-foundry/core/zip';\nimport type {\n VoxtaData,\n VoxtaReadOptions,\n ExtractedVoxtaCharacter,\n ExtractedVoxtaScenario,\n ExtractedVoxtaBook,\n ExtractedVoxtaCollection,\n VoxtaPackage,\n VoxtaCharacter,\n VoxtaScenario,\n VoxtaBook,\n VoxtaCollection,\n} from './types.js';\n\nconst DEFAULT_OPTIONS: Required<VoxtaReadOptions> = {\n maxFileSize: 50 * 1024 * 1024, // 50MB\n maxAssetSize: 50 * 1024 * 1024, // 50MB\n maxTotalSize: 500 * 1024 * 1024, // 500MB - Voxta packages can be large\n};\n\n// ZIP End of Central Directory signature\nconst EOCD_SIGNATURE = new Uint8Array([0x50, 0x4b, 0x05, 0x06]);\n// ZIP Central Directory File Header signature\nconst CDFH_SIGNATURE = new Uint8Array([0x50, 0x4b, 0x01, 0x02]);\n\n/**\n * Scan ZIP central directory for filenames matching Voxta markers.\n * The central directory is at the END of the ZIP file, so we must parse\n * the EOCD record to find it.\n */\nfunction scanZipCentralDirectory(zipData: BinaryData, markers: string[]): boolean {\n // Find EOCD (End of Central Directory) - scan from end\n // EOCD is at least 22 bytes, search within last 64KB (comment can be up to 64KB)\n const searchSize = Math.min(zipData.length, 65536 + 22);\n let eocdOffset = -1;\n\n for (let i = zipData.length - 22; i >= zipData.length - searchSize; i--) {\n if (\n zipData[i] === EOCD_SIGNATURE[0] &&\n zipData[i + 1] === EOCD_SIGNATURE[1] &&\n zipData[i + 2] === EOCD_SIGNATURE[2] &&\n zipData[i + 3] === EOCD_SIGNATURE[3]\n ) {\n eocdOffset = i;\n break;\n }\n }\n\n if (eocdOffset < 0) return false;\n\n // EOCD structure (22 bytes minimum):\n // 0-3: signature (PK\\x05\\x06)\n // 4-5: disk number\n // 6-7: disk with central directory\n // 8-9: entries on this disk\n // 10-11: total entries\n // 12-15: central directory size\n // 16-19: central directory offset\n // 20-21: comment length\n\n // Read central directory offset (little-endian uint32 at offset 16)\n const cdOffset =\n zipData[eocdOffset + 16]! |\n (zipData[eocdOffset + 17]! << 8) |\n (zipData[eocdOffset + 18]! << 16) |\n (zipData[eocdOffset + 19]! << 24);\n\n // Read number of entries (little-endian uint16 at offset 10)\n const numEntries = zipData[eocdOffset + 10]! | (zipData[eocdOffset + 11]! << 8);\n\n if (cdOffset < 0 || cdOffset >= zipData.length) return false;\n\n // Iterate through central directory entries\n let pos = cdOffset;\n const decoder = new TextDecoder();\n\n for (let entry = 0; entry < numEntries && pos < eocdOffset; entry++) {\n // Verify CDFH signature\n if (\n zipData[pos] !== CDFH_SIGNATURE[0] ||\n zipData[pos + 1] !== CDFH_SIGNATURE[1] ||\n zipData[pos + 2] !== CDFH_SIGNATURE[2] ||\n zipData[pos + 3] !== CDFH_SIGNATURE[3]\n ) {\n break; // Invalid entry, stop parsing\n }\n\n // Central Directory File Header structure:\n // 0-3: signature\n // 4-5: version made by\n // 6-7: version needed\n // 8-9: flags\n // 10-11: compression method\n // 12-13: last mod time\n // 14-15: last mod date\n // 16-19: CRC-32\n // 20-23: compressed size\n // 24-27: uncompressed size\n // 28-29: filename length\n // 30-31: extra field length\n // 32-33: comment length\n // 34-35: disk number start\n // 36-37: internal attributes\n // 38-41: external attributes\n // 42-45: local header offset\n // 46+: filename, extra field, comment\n\n const fileNameLen = zipData[pos + 28]! | (zipData[pos + 29]! << 8);\n const extraLen = zipData[pos + 30]! | (zipData[pos + 31]! << 8);\n const commentLen = zipData[pos + 32]! | (zipData[pos + 33]! << 8);\n\n if (pos + 46 + fileNameLen > zipData.length) break;\n\n // Extract filename\n const fileName = decoder.decode(zipData.subarray(pos + 46, pos + 46 + fileNameLen));\n\n // Check against markers\n for (const marker of markers) {\n if (fileName === marker || fileName.startsWith(marker)) {\n return true;\n }\n }\n\n // Move to next entry\n pos += 46 + fileNameLen + extraLen + commentLen;\n }\n\n return false;\n}\n\n/**\n * Check if data is a Voxta package\n */\nexport function isVoxta(data: BinaryData): boolean {\n const zipOffset = getZipOffset(data);\n if (zipOffset < 0) return false;\n\n const zipData = data.subarray(zipOffset);\n\n // Voxta markers - package.json is the primary indicator\n const markers = [\n 'package.json',\n 'character.json',\n 'Characters/',\n 'MemoryBooks/',\n 'Scenarios/',\n 'Collections/',\n ];\n\n return scanZipCentralDirectory(zipData, markers);\n}\n\n/**\n * Extract and parse a Voxta package\n */\nexport function readVoxta(\n data: BinaryData,\n options: VoxtaReadOptions = {}\n): VoxtaData {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n // SECURITY: Streaming unzip with real-time byte limit enforcement\n // This tracks ACTUAL decompressed bytes and aborts if limits exceeded,\n // protecting against malicious archives that lie about sizes in central directory\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(data, {\n maxFileSize: opts.maxAssetSize,\n maxTotalSize: opts.maxTotalSize,\n maxFiles: 10000, // Voxta packages can have many files\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || opts.maxTotalSize,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n const result: VoxtaData = {\n characters: [],\n scenarios: [],\n books: [],\n collections: [],\n exportType: 'character', // Default, will be updated based on contents\n };\n\n // Temporary maps to aggregate data parts\n const charMap = new Map<string, Partial<ExtractedVoxtaCharacter>>();\n const scenarioMap = new Map<string, Partial<ExtractedVoxtaScenario>>();\n const bookMap = new Map<string, Partial<ExtractedVoxtaBook>>();\n const collectionMap = new Map<string, Partial<ExtractedVoxtaCollection>>();\n\n // Process entries (size limits already enforced by streamingUnzipSync)\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n // Skip directories\n if (fileName.endsWith('/') || fileData.length === 0) continue;\n\n // 1. Package Metadata\n if (fileName === 'package.json') {\n if (fileData.length > opts.maxFileSize) {\n throw new SizeLimitError(fileData.length, opts.maxFileSize, 'package.json');\n }\n try {\n result.package = JSON.parse(toString(fileData)) as VoxtaPackage;\n } catch (err) {\n throw new ParseError(\n `Failed to parse package.json: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n continue;\n }\n\n // 2. Characters - Path: Characters/{uuid}/...\n const charMatch = fileName.match(/^Characters\\/([^/]+)\\/(.+)$/);\n if (charMatch) {\n const [, charId, subPath] = charMatch;\n\n if (!charMap.has(charId!)) {\n charMap.set(charId!, { id: charId, assets: [] });\n }\n const charEntry = charMap.get(charId!)!;\n\n if (subPath === 'character.json') {\n try {\n charEntry.data = JSON.parse(toString(fileData)) as VoxtaCharacter;\n } catch (err) {\n throw new ParseError(\n `Failed to parse character.json for ${charId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n } else if (subPath!.startsWith('thumbnail.')) {\n charEntry.thumbnail = fileData;\n } else if (subPath!.startsWith('Assets/')) {\n charEntry.assets!.push({\n path: subPath!,\n buffer: fileData,\n characterId: charId,\n });\n }\n continue;\n }\n\n // 3. Scenarios - Path: Scenarios/{uuid}/...\n const scenarioMatch = fileName.match(/^Scenarios\\/([^/]+)\\/(.+)$/);\n if (scenarioMatch) {\n const [, scenarioId, subPath] = scenarioMatch;\n\n if (!scenarioMap.has(scenarioId!)) {\n scenarioMap.set(scenarioId!, { id: scenarioId });\n }\n const scenarioEntry = scenarioMap.get(scenarioId!)!;\n\n if (subPath === 'scenario.json') {\n try {\n scenarioEntry.data = JSON.parse(toString(fileData)) as VoxtaScenario;\n } catch (err) {\n throw new ParseError(\n `Failed to parse scenario.json for ${scenarioId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n } else if (subPath!.startsWith('thumbnail.')) {\n scenarioEntry.thumbnail = fileData;\n }\n continue;\n }\n\n // 4. Books - Path: Books/{uuid}/...\n const bookMatch = fileName.match(/^Books\\/([^/]+)\\/(.+)$/);\n if (bookMatch) {\n const [, bookId, subPath] = bookMatch;\n\n if (!bookMap.has(bookId!)) {\n bookMap.set(bookId!, { id: bookId });\n }\n const bookEntry = bookMap.get(bookId!)!;\n\n if (subPath === 'book.json') {\n try {\n bookEntry.data = JSON.parse(toString(fileData)) as VoxtaBook;\n } catch (err) {\n throw new ParseError(\n `Failed to parse book.json for ${bookId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n }\n continue;\n }\n\n // 5. Collections - Path: Collections/{uuid}/...\n const collectionMatch = fileName.match(/^Collections\\/([^/]+)\\/(.+)$/);\n if (collectionMatch) {\n const [, collectionId, subPath] = collectionMatch;\n\n if (!collectionMap.has(collectionId!)) {\n collectionMap.set(collectionId!, { id: collectionId });\n }\n const collectionEntry = collectionMap.get(collectionId!)!;\n\n if (subPath === 'collection.json') {\n try {\n collectionEntry.data = JSON.parse(toString(fileData)) as VoxtaCollection;\n } catch (err) {\n throw new ParseError(\n `Failed to parse collection.json for ${collectionId}: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n } else if (subPath!.startsWith('thumbnail.')) {\n collectionEntry.thumbnail = fileData;\n }\n continue;\n }\n }\n\n // Assemble final results - filter incomplete entries\n for (const [, char] of charMap) {\n if (char.data) {\n result.characters.push(char as ExtractedVoxtaCharacter);\n }\n }\n\n for (const [, scenario] of scenarioMap) {\n if (scenario.data) {\n result.scenarios.push(scenario as ExtractedVoxtaScenario);\n }\n }\n\n for (const [, book] of bookMap) {\n if (book.data) {\n result.books.push(book as ExtractedVoxtaBook);\n }\n }\n\n for (const [, collection] of collectionMap) {\n if (collection.data) {\n result.collections.push(collection as ExtractedVoxtaCollection);\n }\n }\n\n // Determine export type based on contents\n if (result.package) {\n result.exportType = 'package';\n } else if (result.collections.length > 0) {\n // Collections without package.json = collection export\n result.exportType = 'collection';\n } else if (result.scenarios.length > 0) {\n result.exportType = 'scenario';\n }\n // else stays 'character' (default)\n\n return result;\n}\n\n/**\n * Async version of readVoxta\n */\nexport async function readVoxtaAsync(\n data: BinaryData,\n options: VoxtaReadOptions = {}\n): Promise<VoxtaData> {\n return readVoxta(data, options);\n}\n","/**\n * Voxta Writer\n *\n * Creates .voxpkg files from CCv3 card data.\n */\n\nimport { zipSync, type Zippable } from 'fflate';\nimport { fromString, generateUUID } from '@character-foundry/core';\nimport { detectImageFormat, getExtension } from '@character-foundry/media';\nimport type { CCv3Data } from '@character-foundry/schemas';\nimport type {\n VoxtaWriteAsset,\n VoxtaWriteOptions,\n VoxtaBuildResult,\n VoxtaCharacter,\n VoxtaScenario,\n VoxtaExtensionData,\n CompressionLevel,\n} from './types.js';\nimport { standardToVoxta } from './macros.js';\nimport { ccv3LorebookToVoxtaBook } from './mapper.js';\n\n/**\n * Sanitize a name for use in file paths\n */\nfunction sanitizeName(name: string, ext: string): string {\n let safeName = name;\n\n if (safeName.toLowerCase().endsWith(`.${ext.toLowerCase()}`)) {\n safeName = safeName.substring(0, safeName.length - (ext.length + 1));\n }\n\n safeName = safeName\n .replace(/[._]/g, '-')\n .replace(/[^a-zA-Z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '');\n\n if (!safeName) safeName = 'asset';\n\n return safeName;\n}\n\n/**\n * Build a Voxta package from CCv3 card data\n */\nexport function writeVoxta(\n card: CCv3Data,\n assets: VoxtaWriteAsset[],\n options: VoxtaWriteOptions = {}\n): VoxtaBuildResult {\n const { compressionLevel = 6, includePackageJson = false } = options;\n const cardData = card.data;\n\n // Get Voxta extension data if present\n const extensions = cardData.extensions as Record<string, unknown> | undefined;\n const voxtaExt = extensions?.voxta as VoxtaExtensionData | undefined;\n\n // Generate IDs\n const characterId = options.characterId || voxtaExt?.id || generateUUID();\n const packageId = options.packageId || voxtaExt?.packageId || generateUUID();\n const dateNow = new Date().toISOString();\n\n // Get appearance from voxta extension or visual_description\n const appearance = voxtaExt?.appearance || (extensions?.visual_description as string) || '';\n\n // Create ZIP entries\n const zipEntries: Zippable = {};\n\n // Handle Lorebook (MemoryBook)\n const book = ccv3LorebookToVoxtaBook(card);\n const memoryBooks: string[] = voxtaExt?.original?.MemoryBooks || [];\n\n if (book) {\n // Ensure we have a unique ID for the book\n if (!book.Id) book.Id = generateUUID();\n\n // Add to memory books list if not already present\n if (!memoryBooks.includes(book.Id)) {\n memoryBooks.push(book.Id);\n }\n\n // Write book to ZIP - character will reference it via MemoryBooks\n zipEntries[`Books/${book.Id}/book.json`] = [\n fromString(JSON.stringify(book, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n\n // Note: We no longer force includePackageJson = true here.\n // The Books/ folder is valid alongside Characters/ without package.json.\n // This allows single-character exports with lorebooks.\n }\n\n // 1. Package.json (optional)\n if (includePackageJson) {\n const packageMeta = {\n $type: 'package',\n Id: packageId,\n Name: cardData.name,\n Version: cardData.character_version || '1.0.0',\n Description: cardData.description,\n Creator: cardData.creator,\n ExplicitContent: true,\n EntryResource: { Kind: 1, Id: characterId },\n ThumbnailResource: { Kind: 1, Id: characterId },\n DateCreated: voxtaExt?.original?.DateCreated || dateNow,\n DateModified: dateNow,\n };\n zipEntries['package.json'] = [\n fromString(JSON.stringify(packageMeta, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n }\n\n // 2. Character.json\n const character: VoxtaCharacter = {\n $type: 'character',\n Id: characterId,\n PackageId: packageId,\n Name: cardData.name,\n Version: cardData.character_version,\n\n // Core Info - apply macro conversion (handle nullable personality/mes_example)\n Description: appearance,\n Personality: standardToVoxta(cardData.personality ?? ''),\n Profile: standardToVoxta(cardData.description),\n Scenario: standardToVoxta(cardData.scenario),\n FirstMessage: standardToVoxta(cardData.first_mes),\n AlternativeFirstMessages: (cardData.alternate_greetings || []).map(standardToVoxta),\n MessageExamples: standardToVoxta(cardData.mes_example ?? ''),\n\n // System prompts - Voxta supports these\n SystemPrompt: cardData.system_prompt ? standardToVoxta(cardData.system_prompt) : undefined,\n PostHistoryInstructions: cardData.post_history_instructions ? standardToVoxta(cardData.post_history_instructions) : undefined,\n\n // Metadata\n Creator: cardData.creator,\n CreatorNotes: cardData.creator_notes,\n Tags: cardData.tags,\n\n // References\n MemoryBooks: memoryBooks.length > 0 ? memoryBooks : undefined,\n\n // Voxta-specific from extension\n TextToSpeech: voxtaExt?.textToSpeech,\n ChatStyle: voxtaExt?.chatSettings?.chatStyle,\n EnableThinkingSpeech: voxtaExt?.chatSettings?.enableThinkingSpeech,\n NotifyUserAwayReturn: voxtaExt?.chatSettings?.notifyUserAwayReturn,\n TimeAware: voxtaExt?.chatSettings?.timeAware,\n UseMemory: voxtaExt?.chatSettings?.useMemory,\n MaxTokens: voxtaExt?.chatSettings?.maxTokens,\n MaxSentences: voxtaExt?.chatSettings?.maxSentences,\n SystemPromptOverrideType: voxtaExt?.chatSettings?.systemPromptOverrideType,\n \n // Simulation Settings\n ClimaxSensitivity: voxtaExt?.simulationSettings?.climaxSensitivity,\n PleasureDecay: voxtaExt?.simulationSettings?.pleasureDecay,\n\n Scripts: voxtaExt?.scripts,\n\n DateCreated: voxtaExt?.original?.DateCreated || dateNow,\n DateModified: dateNow,\n };\n\n zipEntries[`Characters/${characterId}/character.json`] = [\n fromString(JSON.stringify(character, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n\n // 3. Add assets\n let assetCount = 0;\n let mainThumbnail: VoxtaWriteAsset | undefined;\n\n for (const asset of assets) {\n const safeName = sanitizeName(asset.name, asset.ext);\n const finalFilename = `${safeName}.${asset.ext}`;\n let voxtaPath = '';\n\n const tags = asset.tags || [];\n\n // Check if this is the main icon (used as thumbnail only, not in Assets folder)\n const isMainIcon = asset.type === 'icon' && (\n tags.includes('portrait-override') ||\n asset.name === 'main' ||\n asset.isMain\n );\n\n if (asset.type === 'sound' || tags.includes('voice')) {\n voxtaPath = `Characters/${characterId}/Assets/VoiceSamples/${finalFilename}`;\n } else if (asset.type === 'icon' || asset.type === 'emotion') {\n // Track main icon for thumbnail (but don't add to Assets folder)\n if (asset.type === 'icon') {\n if (tags.includes('portrait-override')) {\n mainThumbnail = asset;\n } else if (!mainThumbnail && (asset.name === 'main' || asset.isMain)) {\n mainThumbnail = asset;\n }\n }\n\n // Skip adding main icon to Assets folder - it will only be the thumbnail\n if (isMainIcon) {\n continue;\n }\n\n voxtaPath = `Characters/${characterId}/Assets/Avatars/Default/${finalFilename}`;\n } else {\n voxtaPath = `Characters/${characterId}/Assets/Misc/${finalFilename}`;\n }\n\n zipEntries[voxtaPath] = [asset.data, { level: compressionLevel as CompressionLevel }];\n assetCount++;\n }\n\n // 4. Add thumbnail (detect format - supports PNG, WebP, JPEG)\n if (!mainThumbnail && assets.length > 0) {\n mainThumbnail = assets.find((a) => a.type === 'icon');\n }\n\n if (mainThumbnail) {\n const thumbData =\n mainThumbnail.data instanceof Uint8Array\n ? mainThumbnail.data\n : new Uint8Array(mainThumbnail.data);\n const thumbFormat = detectImageFormat(thumbData);\n const thumbExt = thumbFormat ? getExtension(thumbFormat) : 'png';\n\n zipEntries[`Characters/${characterId}/thumbnail.${thumbExt}`] = [\n mainThumbnail.data,\n { level: compressionLevel as CompressionLevel },\n ];\n }\n\n // 5. Add scenario if provided (uses scenario.Id as key)\n let scenarioId: string | undefined;\n if (options.scenario) {\n const scenario = options.scenario;\n scenarioId = scenario.Id;\n\n // Ensure scenario has required fields\n const scenarioData: VoxtaScenario = {\n ...scenario,\n $type: 'scenario',\n PackageId: packageId,\n DateModified: dateNow,\n };\n\n // Write scenario.json\n zipEntries[`Scenarios/${scenarioId}/scenario.json`] = [\n fromString(JSON.stringify(scenarioData, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n\n // Add scenario thumbnail if provided (detect format)\n if (options.scenarioThumbnail) {\n const scenarioThumbData =\n options.scenarioThumbnail instanceof Uint8Array\n ? options.scenarioThumbnail\n : new Uint8Array(options.scenarioThumbnail);\n const scenarioThumbFormat = detectImageFormat(scenarioThumbData);\n const scenarioThumbExt = scenarioThumbFormat ? getExtension(scenarioThumbFormat) : 'png';\n\n zipEntries[`Scenarios/${scenarioId}/thumbnail.${scenarioThumbExt}`] = [\n options.scenarioThumbnail,\n { level: compressionLevel as CompressionLevel },\n ];\n }\n\n // Update package.json EntryResource to point to scenario (Kind: 3)\n if (includePackageJson) {\n const packageMeta = {\n $type: 'package',\n Id: packageId,\n Name: scenario.Name || cardData.name,\n Version: scenario.Version || cardData.character_version || '1.0.0',\n Description: scenario.Description || cardData.description,\n Creator: scenario.Creator || cardData.creator,\n ExplicitContent: scenario.ExplicitContent ?? true,\n EntryResource: { Kind: 3, Id: scenarioId }, // Kind 3 = Scenario\n ThumbnailResource: { Kind: 3, Id: scenarioId },\n DateCreated: scenario.DateCreated || voxtaExt?.original?.DateCreated || dateNow,\n DateModified: dateNow,\n };\n zipEntries['package.json'] = [\n fromString(JSON.stringify(packageMeta, null, 2)),\n { level: compressionLevel as CompressionLevel },\n ];\n }\n }\n\n // Create ZIP\n const buffer = zipSync(zipEntries);\n\n return {\n buffer,\n assetCount,\n totalSize: buffer.length,\n characterId,\n scenarioId,\n };\n}\n\n/**\n * Async version of writeVoxta\n */\nexport async function writeVoxtaAsync(\n card: CCv3Data,\n assets: VoxtaWriteAsset[],\n options: VoxtaWriteOptions = {}\n): Promise<VoxtaBuildResult> {\n return writeVoxta(card, assets, options);\n}\n","/**\n * Macro Conversion\n *\n * Converts between Voxta-style macros (with spaces) and standard macros.\n *\n * Voxta uses: {{ user }}, {{ char }}\n * Standard uses: {{user}}, {{char}}\n */\n\n/**\n * Convert Voxta-style macros to standard format (no spaces)\n */\nexport function voxtaToStandard(text: string): string {\n if (!text) return text;\n\n let result = text;\n\n // Replace {{ user }} variants with {{user}}\n result = result.replace(/\\{\\{\\s*user\\s*\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('User') || match.includes('USER');\n return isUpperCase ? '{{User}}' : '{{user}}';\n });\n\n // Replace {{ char }} variants with {{char}}\n result = result.replace(/\\{\\{\\s*char\\s*\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('Char') || match.includes('CHAR');\n return isUpperCase ? '{{Char}}' : '{{char}}';\n });\n\n return result;\n}\n\n/**\n * Convert standard macros to Voxta-style format (with spaces)\n */\nexport function standardToVoxta(text: string): string {\n if (!text) return text;\n\n let result = text;\n\n // Replace {{user}} variants with {{ user }}\n result = result.replace(/\\{\\{user\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('User') || match.includes('USER');\n return isUpperCase ? '{{ User }}' : '{{ user }}';\n });\n\n // Replace {{char}} variants with {{ char }}\n result = result.replace(/\\{\\{char\\}\\}/gi, (match) => {\n const isUpperCase = match.includes('Char') || match.includes('CHAR');\n return isUpperCase ? '{{ Char }}' : '{{ char }}';\n });\n\n return result;\n}\n","/**\n * Voxta <-> CCv3 Mapping\n *\n * Conversion utilities between Voxta format and CCv3 format.\n */\n\nimport type {\n CCv3Data,\n CCv3CharacterBook,\n CCv3LorebookEntry,\n} from '@character-foundry/schemas';\nimport { generateUUID } from '@character-foundry/core';\nimport type {\n VoxtaCharacter,\n VoxtaBook,\n VoxtaExtensionData,\n} from './types.js';\nimport { voxtaToStandard, standardToVoxta } from './macros.js';\n\n/**\n * Convert a Voxta character to CCv3 format\n */\nexport function voxtaToCCv3(character: VoxtaCharacter, books?: VoxtaBook[]): CCv3Data {\n // Build voxta extension data to preserve Voxta-specific fields\n const voxtaExt: VoxtaExtensionData = {\n id: character.Id,\n packageId: character.PackageId,\n label: character.Label,\n appearance: character.Description,\n context: character.Context,\n instructions: character.Instructions,\n userNameOverride: character.UserNameOverride,\n userDescriptionOverride: character.UserDescriptionOverride,\n culture: character.Culture,\n importedFrom: character.ImportedFrom,\n textToSpeech: character.TextToSpeech,\n chatSettings: {\n chatStyle: character.ChatStyle,\n enableThinkingSpeech: character.EnableThinkingSpeech,\n notifyUserAwayReturn: character.NotifyUserAwayReturn,\n timeAware: character.TimeAware,\n useMemory: character.UseMemory,\n maxTokens: character.MaxTokens,\n maxSentences: character.MaxSentences,\n systemPromptOverrideType: character.SystemPromptOverrideType,\n },\n simulationSettings: {\n climaxSensitivity: character.ClimaxSensitivity,\n pleasureDecay: character.PleasureDecay,\n },\n scripts: character.Scripts,\n augmentations: character.Augmentations,\n original: {\n DateCreated: character.DateCreated,\n DateModified: character.DateModified,\n },\n };\n\n // Convert lorebook from VoxtaBooks\n let characterBook: CCv3CharacterBook | undefined;\n\n if (books && books.length > 0) {\n const entries: CCv3LorebookEntry[] = [];\n const linkedBookIds = new Set(character.MemoryBooks || []);\n\n for (const book of books) {\n // Only include if linked or if no links defined (legacy/implicit)\n if (linkedBookIds.size === 0 || linkedBookIds.has(book.Id)) {\n if (book.Items) {\n for (let i = 0; i < book.Items.length; i++) {\n const item = book.Items[i]!;\n entries.push({\n keys: item.Keywords || [],\n content: voxtaToStandard(item.Text || ''),\n enabled: item.Deleted !== true,\n insertion_order: i,\n name: item.Id || '',\n priority: item.Weight || 10,\n id: i,\n comment: '',\n selective: false,\n secondary_keys: [],\n constant: false,\n position: 'before_char',\n });\n }\n }\n }\n }\n\n if (entries.length > 0) {\n characterBook = {\n entries,\n name: books[0]!.Name || 'Imported Lorebook',\n };\n }\n }\n\n // Convert timestamps (ISO string -> Unix seconds)\n // Sanitize .NET default dates (0001-01-01) which produce negative timestamps\n const rawCreationDate = character.DateCreated\n ? Math.floor(new Date(character.DateCreated).getTime() / 1000)\n : undefined;\n const rawModificationDate = character.DateModified\n ? Math.floor(new Date(character.DateModified).getTime() / 1000)\n : undefined;\n const creationDate = rawCreationDate !== undefined && rawCreationDate >= 0 ? rawCreationDate : undefined;\n const modificationDate = rawModificationDate !== undefined && rawModificationDate >= 0 ? rawModificationDate : undefined;\n\n // SPEC-COMPLIANT MAPPING (per CHARX_vs_VOXPKG_COMPARISON.md):\n // - Voxta Description (physical appearance) → CCv3 visual_description extension\n // - Voxta Personality → CCv3 personality\n // - Voxta Profile (backstory/details) → CCv3 description\n // Pure 1:1 mapping - no extraction, no magic\n\n // Build CCv3 card\n const card: CCv3Data = {\n spec: 'chara_card_v3',\n spec_version: '3.0',\n data: {\n name: character.Name || 'Unknown',\n nickname: character.Label,\n description: voxtaToStandard(character.Profile || ''),\n personality: voxtaToStandard(character.Personality || ''),\n scenario: voxtaToStandard(character.Scenario || ''),\n first_mes: voxtaToStandard(character.FirstMessage || ''),\n mes_example: voxtaToStandard(character.MessageExamples || ''),\n creator_notes: character.CreatorNotes || '',\n system_prompt: voxtaToStandard(character.SystemPrompt || ''),\n post_history_instructions: voxtaToStandard(character.PostHistoryInstructions || ''),\n alternate_greetings: (character.AlternativeFirstMessages || []).map(voxtaToStandard),\n group_only_greetings: [],\n tags: character.Tags || [],\n creator: character.Creator || '',\n character_version: character.Version || '1.0',\n creation_date: creationDate,\n modification_date: modificationDate,\n character_book: characterBook,\n extensions: {\n voxta: voxtaExt,\n visual_description: character.Description || undefined,\n },\n },\n };\n\n return card;\n}\n\n/**\n * Convert CCv3 card to Voxta character format\n */\nexport function ccv3ToVoxta(card: CCv3Data): VoxtaCharacter {\n const cardData = card.data;\n const extensions = cardData.extensions as Record<string, unknown> | undefined;\n const voxtaExt = extensions?.voxta as VoxtaExtensionData | undefined;\n const dateNow = new Date().toISOString();\n\n const appearance = voxtaExt?.appearance || (extensions?.visual_description as string) || '';\n\n // Convert timestamps (Unix seconds -> ISO string)\n const dateCreated = cardData.creation_date\n ? new Date(cardData.creation_date * 1000).toISOString()\n : voxtaExt?.original?.DateCreated || dateNow;\n const dateModified = cardData.modification_date\n ? new Date(cardData.modification_date * 1000).toISOString()\n : dateNow;\n\n const character: VoxtaCharacter = {\n $type: 'character',\n Id: voxtaExt?.id || generateUUID(),\n PackageId: voxtaExt?.packageId || generateUUID(),\n Name: cardData.name,\n Label: cardData.nickname || voxtaExt?.label,\n Version: cardData.character_version,\n\n // Core content (handle nullable personality/mes_example)\n Description: appearance,\n Personality: standardToVoxta(cardData.personality ?? ''),\n Profile: standardToVoxta(cardData.description),\n Scenario: standardToVoxta(cardData.scenario),\n FirstMessage: standardToVoxta(cardData.first_mes),\n AlternativeFirstMessages: (cardData.alternate_greetings || []).map(standardToVoxta),\n MessageExamples: standardToVoxta(cardData.mes_example ?? ''),\n\n // System prompts\n SystemPrompt: standardToVoxta(cardData.system_prompt || ''),\n PostHistoryInstructions: standardToVoxta(cardData.post_history_instructions || ''),\n Context: voxtaExt?.context,\n Instructions: voxtaExt?.instructions,\n\n // Persona overrides\n UserNameOverride: voxtaExt?.userNameOverride,\n UserDescriptionOverride: voxtaExt?.userDescriptionOverride,\n\n // Metadata\n Creator: cardData.creator,\n CreatorNotes: cardData.creator_notes,\n Tags: cardData.tags,\n Culture: voxtaExt?.culture,\n ImportedFrom: voxtaExt?.importedFrom,\n\n // TTS & AI settings\n TextToSpeech: voxtaExt?.textToSpeech,\n ChatStyle: voxtaExt?.chatSettings?.chatStyle,\n EnableThinkingSpeech: voxtaExt?.chatSettings?.enableThinkingSpeech,\n NotifyUserAwayReturn: voxtaExt?.chatSettings?.notifyUserAwayReturn,\n TimeAware: voxtaExt?.chatSettings?.timeAware,\n UseMemory: voxtaExt?.chatSettings?.useMemory,\n MaxTokens: voxtaExt?.chatSettings?.maxTokens,\n MaxSentences: voxtaExt?.chatSettings?.maxSentences,\n SystemPromptOverrideType: voxtaExt?.chatSettings?.systemPromptOverrideType,\n\n // Simulation settings\n ClimaxSensitivity: voxtaExt?.simulationSettings?.climaxSensitivity,\n PleasureDecay: voxtaExt?.simulationSettings?.pleasureDecay,\n\n // Advanced\n Scripts: voxtaExt?.scripts,\n Augmentations: voxtaExt?.augmentations,\n\n DateCreated: dateCreated,\n DateModified: dateModified,\n };\n\n return character;\n}\n\n/**\n * Convert CCv3 lorebook to Voxta book format\n */\nexport function ccv3LorebookToVoxtaBook(card: CCv3Data): VoxtaBook | null {\n const characterBook = card.data.character_book;\n if (!characterBook?.entries || characterBook.entries.length === 0) {\n return null;\n }\n\n const book: VoxtaBook = {\n $type: 'book',\n Id: generateUUID(),\n Name: characterBook.name || `${card.data.name}'s Lorebook`,\n Items: characterBook.entries.map((entry) => ({\n Id: generateUUID(),\n Keywords: entry.keys || [],\n Text: standardToVoxta(entry.content || ''),\n Weight: entry.priority || 10,\n Deleted: entry.enabled === false,\n })),\n };\n\n return book;\n}\n","/**\n * Voxta Merge Utilities\n *\n * Functions for merging CCv3 edits into Voxta structures.\n */\n\nimport { zipSync, type Zippable } from 'fflate';\nimport {\n type BinaryData,\n fromString,\n ParseError,\n SizeLimitError,\n generateUUID,\n} from '@character-foundry/core';\nimport {\n findZipStart,\n streamingUnzipSync,\n ZipPreflightError,\n type Unzipped,\n} from '@character-foundry/core/zip';\nimport { detectImageFormat, getExtension } from '@character-foundry/media';\nimport type { CCv3Data, CCv3CharacterBook } from '@character-foundry/schemas';\nimport type {\n VoxtaCharacter,\n VoxtaBook,\n VoxtaBookItem,\n VoxtaPackage,\n ExtractedVoxtaCharacter,\n ExtractedVoxtaBook,\n CompressionLevel,\n} from './types.js';\nimport { standardToVoxta } from './macros.js';\n\n/**\n * Editable CCv3 fields (subset that can be changed in editors)\n */\nexport type CCv3Edits = Partial<CCv3Data['data']>;\n\n/**\n * Merge partial CCv3 edits into an existing Voxta character.\n *\n * This function applies only the fields present in `edits` to the original\n * character, preserving Voxta-specific fields like Scripts, TTS, and\n * Augmentations that CCv3 cannot represent.\n *\n * @param original - The original extracted Voxta character\n * @param edits - Partial CCv3 data fields to apply\n * @returns Updated VoxtaCharacter with edits merged\n */\nexport function mergeCharacterEdits(\n original: ExtractedVoxtaCharacter | VoxtaCharacter,\n edits: CCv3Edits\n): VoxtaCharacter {\n // Get the base character data\n const char: VoxtaCharacter =\n 'data' in original ? { ...original.data } : { ...original };\n\n const dateNow = new Date().toISOString();\n\n // Core text fields - only update if present in edits\n if (edits.name !== undefined) {\n char.Name = edits.name;\n }\n\n if (edits.nickname !== undefined) {\n char.Label = edits.nickname || undefined;\n }\n\n if (edits.description !== undefined) {\n char.Profile = standardToVoxta(edits.description);\n }\n\n if (edits.personality !== undefined) {\n char.Personality = standardToVoxta(edits.personality ?? '');\n }\n\n if (edits.scenario !== undefined) {\n char.Scenario = standardToVoxta(edits.scenario);\n }\n\n if (edits.first_mes !== undefined) {\n char.FirstMessage = standardToVoxta(edits.first_mes);\n }\n\n if (edits.alternate_greetings !== undefined) {\n char.AlternativeFirstMessages = edits.alternate_greetings.map(standardToVoxta);\n }\n\n if (edits.mes_example !== undefined) {\n char.MessageExamples = standardToVoxta(edits.mes_example ?? '');\n }\n\n // System prompts\n if (edits.system_prompt !== undefined) {\n char.SystemPrompt = standardToVoxta(edits.system_prompt);\n }\n\n if (edits.post_history_instructions !== undefined) {\n char.PostHistoryInstructions = standardToVoxta(edits.post_history_instructions);\n }\n\n // Metadata\n if (edits.creator !== undefined) {\n char.Creator = edits.creator || undefined;\n }\n\n if (edits.creator_notes !== undefined) {\n char.CreatorNotes = edits.creator_notes || undefined;\n }\n\n if (edits.tags !== undefined) {\n char.Tags = edits.tags;\n }\n\n if (edits.character_version !== undefined) {\n char.Version = edits.character_version || undefined;\n }\n\n // Handle visual_description from extensions\n if (edits.extensions !== undefined) {\n const ext = edits.extensions as Record<string, unknown> | undefined;\n if (ext?.visual_description !== undefined) {\n char.Description = (ext.visual_description as string) || undefined;\n }\n }\n\n // Update modification timestamp\n char.DateModified = dateNow;\n\n return char;\n}\n\n/**\n * Merge partial CCv3 lorebook edits into an existing Voxta book.\n *\n * @param original - The original extracted Voxta book\n * @param edits - CCv3 character_book to merge\n * @returns Updated VoxtaBook with edits merged\n */\nexport function mergeBookEdits(\n original: ExtractedVoxtaBook | VoxtaBook,\n edits: CCv3CharacterBook\n): VoxtaBook {\n const book: VoxtaBook = 'data' in original ? { ...original.data } : { ...original };\n const dateNow = new Date().toISOString();\n\n // Update book name if provided\n if (edits.name !== undefined) {\n book.Name = edits.name;\n }\n\n // Merge entries - match by name (stored as entry ID) or create new\n if (edits.entries !== undefined) {\n const existingById = new Map<string, VoxtaBookItem>();\n for (const item of book.Items || []) {\n existingById.set(item.Id, item);\n }\n\n const newItems: VoxtaBookItem[] = [];\n\n for (const entry of edits.entries) {\n // Try to match existing entry by name (which stores the original ID)\n const existingId = entry.name || '';\n const existing = existingById.get(existingId);\n\n if (existing) {\n // Update existing entry\n newItems.push({\n ...existing,\n Keywords: entry.keys || [],\n Text: standardToVoxta(entry.content || ''),\n Weight: entry.priority ?? existing.Weight ?? 10,\n Deleted: entry.enabled === false,\n LastUpdated: dateNow,\n });\n existingById.delete(existingId);\n } else {\n // Create new entry\n newItems.push({\n Id: generateUUID(),\n Keywords: entry.keys || [],\n Text: standardToVoxta(entry.content || ''),\n Weight: entry.priority ?? 10,\n Deleted: entry.enabled === false,\n CreatedAt: dateNow,\n LastUpdated: dateNow,\n });\n }\n }\n\n // Mark remaining entries as deleted (soft delete)\n for (const remaining of existingById.values()) {\n newItems.push({\n ...remaining,\n Deleted: true,\n DeletedAt: dateNow,\n });\n }\n\n book.Items = newItems;\n }\n\n book.DateModified = dateNow;\n\n return book;\n}\n\n/**\n * Delta changes to apply to a Voxta package\n */\nexport interface VoxtaDeltas {\n /** Updated characters by ID */\n characters?: Map<string, VoxtaCharacter>;\n /** Updated books by ID */\n books?: Map<string, VoxtaBook>;\n /** Updated package metadata (optional) */\n package?: Partial<VoxtaPackage>;\n}\n\n/**\n * Options for applying deltas\n */\nexport interface ApplyDeltaOptions {\n compressionLevel?: CompressionLevel;\n}\n\n/** Max total size for delta operations (500MB) */\nconst DELTA_MAX_TOTAL_SIZE = 500 * 1024 * 1024;\n/** Max file size for delta operations (50MB) */\nconst DELTA_MAX_FILE_SIZE = 50 * 1024 * 1024;\n\n/**\n * Apply delta changes to an existing Voxta package.\n *\n * This performs a minimal update - only files that have changed are rewritten.\n * All other files (assets, scenarios, unchanged characters/books) are preserved\n * exactly as they were in the original package.\n *\n * @param originalBuffer - The original .voxpkg file buffer\n * @param deltas - Changes to apply\n * @param options - Compression options\n * @returns New package buffer with changes applied\n */\nexport function applyVoxtaDeltas(\n originalBuffer: BinaryData,\n deltas: VoxtaDeltas,\n options: ApplyDeltaOptions = {}\n): Uint8Array {\n const { compressionLevel = 6 } = options;\n\n // Handle SFX archives\n const zipData = findZipStart(originalBuffer);\n\n // SECURITY: Use streaming unzip with actual byte tracking and path validation\n // This protects against:\n // 1. Zip bombs (archives that lie about sizes in central directory)\n // 2. Path traversal attacks (Zip Slip)\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(zipData, {\n maxFileSize: DELTA_MAX_FILE_SIZE,\n maxTotalSize: DELTA_MAX_TOTAL_SIZE,\n maxFiles: 10000,\n unsafePathHandling: 'reject', // Fail on path traversal attempts\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || DELTA_MAX_TOTAL_SIZE,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n // Build new ZIP entries, starting with all originals\n const zipEntries: Zippable = {};\n\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n // Check if this file should be replaced\n let replaced = false;\n\n // Check for character.json updates\n const charMatch = fileName.match(/^Characters\\/([^/]+)\\/character\\.json$/);\n if (charMatch && deltas.characters?.has(charMatch[1]!)) {\n const updatedChar = deltas.characters.get(charMatch[1]!)!;\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedChar, null, 2)),\n { level: compressionLevel },\n ];\n replaced = true;\n }\n\n // Check for book.json updates\n const bookMatch = fileName.match(/^Books\\/([^/]+)\\/book\\.json$/);\n if (bookMatch && deltas.books?.has(bookMatch[1]!)) {\n const updatedBook = deltas.books.get(bookMatch[1]!)!;\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedBook, null, 2)),\n { level: compressionLevel },\n ];\n replaced = true;\n }\n\n // Check for package.json update\n if (fileName === 'package.json' && deltas.package) {\n // Merge with existing package metadata\n const existing = JSON.parse(new TextDecoder().decode(fileData)) as VoxtaPackage;\n const updated: VoxtaPackage = {\n ...existing,\n ...deltas.package,\n DateModified: new Date().toISOString(),\n };\n zipEntries[fileName] = [\n fromString(JSON.stringify(updated, null, 2)),\n { level: compressionLevel },\n ];\n replaced = true;\n }\n\n // Keep original if not replaced\n if (!replaced) {\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n }\n\n // Create new ZIP\n return zipSync(zipEntries);\n}\n\n/**\n * Async version of applyVoxtaDeltas\n */\nexport async function applyVoxtaDeltasAsync(\n originalBuffer: BinaryData,\n deltas: VoxtaDeltas,\n options: ApplyDeltaOptions = {}\n): Promise<Uint8Array> {\n return applyVoxtaDeltas(originalBuffer, deltas, options);\n}\n\n/**\n * Character info in package manifest\n */\nexport interface ManifestCharacter {\n id: string;\n name: string;\n}\n\n/**\n * Book info in package manifest\n */\nexport interface ManifestBook {\n id: string;\n name: string;\n /** Character IDs that reference this book */\n usedBy: string[];\n}\n\n/**\n * Scenario info in package manifest\n */\nexport interface ManifestScenario {\n id: string;\n name: string;\n}\n\n/**\n * Package manifest for UI display\n */\nexport interface PackageManifest {\n packageId?: string;\n packageName?: string;\n characters: ManifestCharacter[];\n books: ManifestBook[];\n scenarios: ManifestScenario[];\n}\n\n/**\n * Get a manifest summary of a Voxta package for UI display.\n *\n * This provides a quick overview of package contents with relationship\n * information (which characters use which books).\n *\n * @param data - Extracted Voxta data from readVoxta()\n * @returns Package manifest for UI display\n */\nexport function getPackageManifest(data: import('./types.js').VoxtaData): PackageManifest {\n const characters: ManifestCharacter[] = data.characters.map((c) => ({\n id: c.id,\n name: c.data.Name,\n }));\n\n // Build a map of book ID -> character IDs that use it\n const bookUsers = new Map<string, string[]>();\n for (const char of data.characters) {\n const memoryBooks = char.data.MemoryBooks || [];\n for (const bookId of memoryBooks) {\n if (!bookUsers.has(bookId)) {\n bookUsers.set(bookId, []);\n }\n bookUsers.get(bookId)!.push(char.id);\n }\n }\n\n const books: ManifestBook[] = data.books.map((b) => ({\n id: b.id,\n name: b.data.Name,\n usedBy: bookUsers.get(b.id) || [],\n }));\n\n const scenarios: ManifestScenario[] = data.scenarios.map((s) => ({\n id: s.id,\n name: s.data.Name,\n }));\n\n return {\n packageId: data.package?.Id,\n packageName: data.package?.Name,\n characters,\n books,\n scenarios,\n };\n}\n\n/**\n * Options for extracting a character package\n */\nexport interface ExtractCharacterOptions {\n compressionLevel?: CompressionLevel;\n /** Include books referenced by the character */\n includeBooks?: boolean;\n /** New package name (defaults to character name) */\n packageName?: string;\n}\n\n/**\n * Extract a single character from a multi-character package.\n *\n * Creates a new standalone .voxpkg containing just the specified character,\n * their assets, and optionally their referenced books.\n *\n * NOTE: Scenarios are NOT extracted since they may contain scripts that\n * reference other characters in the package.\n *\n * @param originalBuffer - The original .voxpkg file buffer\n * @param characterId - ID of the character to extract\n * @param options - Extraction options\n * @returns New package buffer with just the specified character\n */\nexport function extractCharacterPackage(\n originalBuffer: BinaryData,\n characterId: string,\n options: ExtractCharacterOptions = {}\n): Uint8Array {\n const { compressionLevel = 6, includeBooks = true, packageName } = options;\n\n // Handle SFX archives\n const zipData = findZipStart(originalBuffer);\n\n // SECURITY: Use streaming unzip with actual byte tracking and path validation\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(zipData, {\n maxFileSize: DELTA_MAX_FILE_SIZE,\n maxTotalSize: DELTA_MAX_TOTAL_SIZE,\n maxFiles: 10000,\n unsafePathHandling: 'reject',\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || DELTA_MAX_TOTAL_SIZE,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n // Find the character's data to get their name and book refs\n const charJsonPath = `Characters/${characterId}/character.json`;\n const charJsonData = unzipped[charJsonPath];\n if (!charJsonData) {\n throw new ParseError(`Character ${characterId} not found in package`, 'voxta');\n }\n\n const charData = JSON.parse(new TextDecoder().decode(charJsonData)) as VoxtaCharacter;\n const memoryBooks = new Set(charData.MemoryBooks || []);\n\n // Generate new package ID\n const newPackageId = generateUUID();\n const dateNow = new Date().toISOString();\n\n // Build new ZIP with only this character's files\n const zipEntries: Zippable = {};\n\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n // Skip empty directories\n if (fileName.endsWith('/') || fileData.length === 0) continue;\n\n // Include all files under this character's directory\n if (fileName.startsWith(`Characters/${characterId}/`)) {\n // Update character.json with new package ID\n if (fileName === charJsonPath) {\n const updatedChar: VoxtaCharacter = {\n ...charData,\n PackageId: newPackageId,\n DateModified: dateNow,\n };\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedChar, null, 2)),\n { level: compressionLevel },\n ];\n } else {\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n continue;\n }\n\n // Include books if requested and referenced by this character\n if (includeBooks) {\n const bookMatch = fileName.match(/^Books\\/([^/]+)\\//);\n if (bookMatch && memoryBooks.has(bookMatch[1]!)) {\n // Update book.json with new package ID\n if (fileName.endsWith('/book.json')) {\n const bookData = JSON.parse(new TextDecoder().decode(fileData)) as VoxtaBook;\n const updatedBook: VoxtaBook = {\n ...bookData,\n PackageId: newPackageId,\n DateModified: dateNow,\n };\n zipEntries[fileName] = [\n fromString(JSON.stringify(updatedBook, null, 2)),\n { level: compressionLevel },\n ];\n } else {\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n continue;\n }\n }\n }\n\n // Create new package.json\n const newPackage: VoxtaPackage = {\n $type: 'package',\n Id: newPackageId,\n Name: packageName || charData.Name,\n Version: charData.Version || '1.0.0',\n Description: charData.Profile || undefined,\n Creator: charData.Creator,\n ExplicitContent: charData.ExplicitContent,\n EntryResource: { Kind: 1, Id: characterId },\n ThumbnailResource: { Kind: 1, Id: characterId },\n DateCreated: charData.DateCreated || dateNow,\n DateModified: dateNow,\n };\n\n zipEntries['package.json'] = [\n fromString(JSON.stringify(newPackage, null, 2)),\n { level: compressionLevel },\n ];\n\n return zipSync(zipEntries);\n}\n\n/**\n * Options for adding a character to a package\n */\nexport interface AddCharacterOptions {\n compressionLevel?: CompressionLevel;\n /** Books to include with the character */\n books?: VoxtaBook[];\n /** Assets to include (path relative to character dir -> data) */\n assets?: Map<string, BinaryData>;\n /** Thumbnail image */\n thumbnail?: BinaryData;\n}\n\n/**\n * Add a character to an existing Voxta package.\n *\n * @param originalBuffer - The original .voxpkg file buffer\n * @param character - The character to add\n * @param options - Options including books and assets\n * @returns New package buffer with the character added\n */\nexport function addCharacterToPackage(\n originalBuffer: BinaryData,\n character: VoxtaCharacter,\n options: AddCharacterOptions = {}\n): Uint8Array {\n const { compressionLevel = 6, books = [], assets, thumbnail } = options;\n\n // Handle SFX archives\n const zipData = findZipStart(originalBuffer);\n\n // SECURITY: Use streaming unzip with actual byte tracking and path validation\n let unzipped: Unzipped;\n try {\n unzipped = streamingUnzipSync(zipData, {\n maxFileSize: DELTA_MAX_FILE_SIZE,\n maxTotalSize: DELTA_MAX_TOTAL_SIZE,\n maxFiles: 10000,\n unsafePathHandling: 'reject',\n });\n } catch (err) {\n if (err instanceof ZipPreflightError) {\n throw new SizeLimitError(\n err.totalSize || err.entrySize || 0,\n err.maxSize || err.maxEntrySize || DELTA_MAX_TOTAL_SIZE,\n err.oversizedEntry || 'Voxta package'\n );\n }\n throw new ParseError(\n `Failed to unzip Voxta package: ${err instanceof Error ? err.message : String(err)}`,\n 'voxta'\n );\n }\n\n // Get existing package metadata\n const packageJsonData = unzipped['package.json'];\n let packageMeta: VoxtaPackage | undefined;\n if (packageJsonData) {\n packageMeta = JSON.parse(new TextDecoder().decode(packageJsonData)) as VoxtaPackage;\n }\n\n const packageId = packageMeta?.Id || generateUUID();\n const dateNow = new Date().toISOString();\n\n // Build new ZIP with all original files plus new character\n const zipEntries: Zippable = {};\n\n // Copy all original files\n for (const [fileName, fileData] of Object.entries(unzipped)) {\n if (fileName === 'package.json') continue; // Will update separately\n zipEntries[fileName] = [fileData, { level: compressionLevel }];\n }\n\n // Ensure character has the right package ID\n const charToAdd: VoxtaCharacter = {\n ...character,\n PackageId: packageId,\n DateModified: dateNow,\n };\n\n // Add character.json\n const charId = charToAdd.Id;\n zipEntries[`Characters/${charId}/character.json`] = [\n fromString(JSON.stringify(charToAdd, null, 2)),\n { level: compressionLevel },\n ];\n\n // Add thumbnail if provided (detect format)\n if (thumbnail) {\n const thumbData = thumbnail instanceof Uint8Array ? thumbnail : new Uint8Array(thumbnail);\n const thumbFormat = detectImageFormat(thumbData);\n const thumbExt = thumbFormat ? getExtension(thumbFormat) : 'png';\n zipEntries[`Characters/${charId}/thumbnail.${thumbExt}`] = [thumbnail, { level: compressionLevel }];\n }\n\n // Add assets if provided\n if (assets) {\n for (const [assetPath, assetData] of assets) {\n zipEntries[`Characters/${charId}/${assetPath}`] = [assetData, { level: compressionLevel }];\n }\n }\n\n // Add books\n for (const book of books) {\n const bookToAdd: VoxtaBook = {\n ...book,\n PackageId: packageId,\n DateModified: dateNow,\n };\n zipEntries[`Books/${book.Id}/book.json`] = [\n fromString(JSON.stringify(bookToAdd, null, 2)),\n { level: compressionLevel },\n ];\n }\n\n // Update package.json\n const updatedPackage: VoxtaPackage = packageMeta\n ? { ...packageMeta, DateModified: dateNow }\n : {\n $type: 'package',\n Id: packageId,\n Name: charToAdd.Name,\n Version: '1.0.0',\n EntryResource: { Kind: 1, Id: charId },\n ThumbnailResource: { Kind: 1, Id: charId },\n DateCreated: dateNow,\n DateModified: dateNow,\n };\n\n zipEntries['package.json'] = [\n fromString(JSON.stringify(updatedPackage, null, 2)),\n { level: compressionLevel },\n ];\n\n return zipSync(zipEntries);\n}\n","/**\n * Voxta Loss Reporting\n *\n * Documents what data is lost when exporting to Voxta format.\n */\n\nimport type { NormalizedCard } from '@character-foundry/schemas';\nimport { hasRisuExtensions, hasRisuScripts, hasDepthPrompt } from '@character-foundry/schemas';\nimport type { VoxtaLossReport } from './types.js';\n\n/**\n * Fields that cannot be represented in Voxta format\n */\nconst _ALWAYS_LOST_FIELDS = [\n 'group_only_greetings', // Voxta doesn't support groups\n];\n\n/**\n * Extension namespaces that are always lost\n */\nconst LOST_EXTENSION_NAMESPACES = [\n 'risuai', // All Risu extensions\n 'chub', // Chub metadata\n 'depth_prompt', // SillyTavern depth prompts\n];\n\n/**\n * Check what would be lost when exporting a card to Voxta format\n */\nexport function checkVoxtaLoss(card: NormalizedCard): VoxtaLossReport {\n const lostFields: string[] = [];\n const lostAssets: string[] = [];\n const warnings: string[] = [];\n\n // Check always-lost fields that have content\n // Note: system_prompt, post_history_instructions, and alternate_greetings ARE supported by Voxta\n if (card.groupOnlyGreetings.length > 0) {\n lostFields.push(`group_only_greetings (${card.groupOnlyGreetings.length} entries)`);\n }\n\n // Check extensions\n const extensions = card.extensions;\n\n if (hasRisuExtensions(extensions)) {\n lostFields.push('extensions.risuai.*');\n\n if (hasRisuScripts(extensions)) {\n warnings.push('Risu scripts (triggerscript, customScripts) will be lost');\n }\n }\n\n if (hasDepthPrompt(extensions)) {\n lostFields.push('extensions.depth_prompt');\n warnings.push('SillyTavern depth prompt will be lost');\n }\n\n if (extensions?.chub) {\n lostFields.push('extensions.chub.*');\n }\n\n // Check for any other unknown extensions\n for (const key of Object.keys(extensions)) {\n if (key !== 'voxta' && key !== 'visual_description' && !LOST_EXTENSION_NAMESPACES.includes(key)) {\n lostFields.push(`extensions.${key}`);\n }\n }\n\n // Check character book extensions\n if (card.characterBook?.extensions) {\n lostFields.push('character_book.extensions');\n }\n\n // Check lorebook entry extensions\n if (card.characterBook?.entries) {\n const entriesWithExtensions = card.characterBook.entries.filter(e => e.extensions && Object.keys(e.extensions).length > 0);\n if (entriesWithExtensions.length > 0) {\n lostFields.push(`lorebook entries extensions (${entriesWithExtensions.length} entries)`);\n }\n }\n\n return {\n lostFields,\n lostAssets,\n warnings,\n reason: 'Voxta format does not support extensions field',\n };\n}\n\n/**\n * Check if export would be lossless\n */\nexport function isVoxtaExportLossless(card: NormalizedCard): boolean {\n const report = checkVoxtaLoss(card);\n return report.lostFields.length === 0 && report.lostAssets.length === 0;\n}\n\n/**\n * Format loss report as human-readable string\n */\nexport function formatVoxtaLossReport(report: VoxtaLossReport): string {\n const lines: string[] = [];\n\n if (report.lostFields.length === 0 && report.lostAssets.length === 0 && report.warnings.length === 0) {\n return 'No data will be lost in this export.';\n }\n\n lines.push('Voxta Export Loss Report');\n lines.push('========================');\n lines.push('');\n lines.push(`Reason: ${report.reason}`);\n lines.push('');\n\n if (report.lostFields.length > 0) {\n lines.push('Lost Fields:');\n for (const field of report.lostFields) {\n lines.push(` - ${field}`);\n }\n lines.push('');\n }\n\n if (report.lostAssets.length > 0) {\n lines.push('Lost Assets:');\n for (const asset of report.lostAssets) {\n lines.push(` - ${asset}`);\n }\n lines.push('');\n }\n\n if (report.warnings.length > 0) {\n lines.push('Warnings:');\n for (const warning of report.warnings) {\n lines.push(` ! ${warning}`);\n }\n }\n\n return lines.join('\\n');\n}\n","/**\n * Voxta Asset Enricher\n *\n * Analyzes Voxta asset paths to extract semantic tags and types.\n * e.g. \"Avatars/Default/happy_idle_01.webp\" -> tags: [emotion:happy, state:idle, variant:01]\n */\n\nimport type { ExtractedVoxtaAsset } from './types.js';\n\nexport interface EnrichedAssetMetadata {\n type: 'icon' | 'sound' | 'custom';\n tags: string[];\n}\n\n/**\n * Extract metadata from a Voxta asset path/filename\n */\nexport function enrichVoxtaAsset(asset: ExtractedVoxtaAsset): EnrichedAssetMetadata {\n const tags: string[] = [];\n let type: EnrichedAssetMetadata['type'] = 'custom';\n\n const parts = asset.path.split('/');\n const filename = parts[parts.length - 1] || '';\n \n // 1. Determine Type\n if (asset.path.includes('/Avatars/')) {\n type = 'icon';\n \n // 2. Extract Semantic Tags from Filename\n // Format: {Emotion}_{State}_{Variant}.ext\n const nameNoExt = filename.substring(0, filename.lastIndexOf('.'));\n const nameParts = nameNoExt.split('_');\n \n if (nameParts.length >= 3) {\n const [emotion, state, variant] = nameParts;\n if (emotion) tags.push(`emotion:${emotion.toLowerCase()}`);\n if (state) tags.push(`state:${state.toLowerCase()}`);\n if (variant) tags.push(`variant:${variant}`);\n } else if (nameParts.length === 2) {\n const [emotion, state] = nameParts;\n if (emotion) tags.push(`emotion:${emotion.toLowerCase()}`);\n if (state) tags.push(`state:${state.toLowerCase()}`);\n } else if (nameParts.length === 1) {\n if (nameParts[0]) tags.push(`emotion:${nameParts[0].toLowerCase()}`);\n }\n \n } else if (asset.path.includes('/VoiceSamples/')) {\n type = 'sound';\n tags.push('voice');\n }\n\n return { type, tags };\n}\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\n/**\n * Is this value defined and not null?\n * @private\n */\nconst defined = function (val) {\n return typeof val !== 'undefined' && val !== null;\n};\n\n/**\n * Is this value an object?\n * @private\n */\nconst object = function (val) {\n return typeof val === 'object';\n};\n\n/**\n * Is this value a plain object?\n * @private\n */\nconst plainObject = function (val) {\n return Object.prototype.toString.call(val) === '[object Object]';\n};\n\n/**\n * Is this value a function?\n * @private\n */\nconst fn = function (val) {\n return typeof val === 'function';\n};\n\n/**\n * Is this value a boolean?\n * @private\n */\nconst bool = function (val) {\n return typeof val === 'boolean';\n};\n\n/**\n * Is this value a Buffer object?\n * @private\n */\nconst buffer = function (val) {\n return val instanceof Buffer;\n};\n\n/**\n * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray?\n * @private\n */\nconst typedArray = function (val) {\n if (defined(val)) {\n switch (val.constructor) {\n case Uint8Array:\n case Uint8ClampedArray:\n case Int8Array:\n case Uint16Array:\n case Int16Array:\n case Uint32Array:\n case Int32Array:\n case Float32Array:\n case Float64Array:\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * Is this value an ArrayBuffer object?\n * @private\n */\nconst arrayBuffer = function (val) {\n return val instanceof ArrayBuffer;\n};\n\n/**\n * Is this value a non-empty string?\n * @private\n */\nconst string = function (val) {\n return typeof val === 'string' && val.length > 0;\n};\n\n/**\n * Is this value a real number?\n * @private\n */\nconst number = function (val) {\n return typeof val === 'number' && !Number.isNaN(val);\n};\n\n/**\n * Is this value an integer?\n * @private\n */\nconst integer = function (val) {\n return Number.isInteger(val);\n};\n\n/**\n * Is this value within an inclusive given range?\n * @private\n */\nconst inRange = function (val, min, max) {\n return val >= min && val <= max;\n};\n\n/**\n * Is this value within the elements of an array?\n * @private\n */\nconst inArray = function (val, list) {\n return list.includes(val);\n};\n\n/**\n * Create an Error with a message relating to an invalid parameter.\n *\n * @param {string} name - parameter name.\n * @param {string} expected - description of the type/value/range expected.\n * @param {*} actual - the value received.\n * @returns {Error} Containing the formatted message.\n * @private\n */\nconst invalidParameterError = function (name, expected, actual) {\n return new Error(\n `Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}`\n );\n};\n\n/**\n * Ensures an Error from C++ contains a JS stack.\n *\n * @param {Error} native - Error with message from C++.\n * @param {Error} context - Error with stack from JS.\n * @returns {Error} Error with message and stack.\n * @private\n */\nconst nativeError = function (native, context) {\n context.message = native.message;\n return context;\n};\n\nmodule.exports = {\n defined,\n object,\n plainObject,\n fn,\n bool,\n buffer,\n typedArray,\n arrayBuffer,\n string,\n number,\n integer,\n inRange,\n inArray,\n invalidParameterError,\n nativeError\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst isLinux = () => process.platform === 'linux';\n\nlet report = null;\nconst getReport = () => {\n if (!report) {\n /* istanbul ignore next */\n if (isLinux() && process.report) {\n const orig = process.report.excludeNetwork;\n process.report.excludeNetwork = true;\n report = process.report.getReport();\n process.report.excludeNetwork = orig;\n } else {\n report = {};\n }\n }\n return report;\n};\n\nmodule.exports = { isLinux, getReport };\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst fs = require('fs');\n\nconst LDD_PATH = '/usr/bin/ldd';\nconst SELF_PATH = '/proc/self/exe';\nconst MAX_LENGTH = 2048;\n\n/**\n * Read the content of a file synchronous\n *\n * @param {string} path\n * @returns {Buffer}\n */\nconst readFileSync = (path) => {\n const fd = fs.openSync(path, 'r');\n const buffer = Buffer.alloc(MAX_LENGTH);\n const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0);\n fs.close(fd, () => {});\n return buffer.subarray(0, bytesRead);\n};\n\n/**\n * Read the content of a file\n *\n * @param {string} path\n * @returns {Promise<Buffer>}\n */\nconst readFile = (path) => new Promise((resolve, reject) => {\n fs.open(path, 'r', (err, fd) => {\n if (err) {\n reject(err);\n } else {\n const buffer = Buffer.alloc(MAX_LENGTH);\n fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {\n resolve(buffer.subarray(0, bytesRead));\n fs.close(fd, () => {});\n });\n }\n });\n});\n\nmodule.exports = {\n LDD_PATH,\n SELF_PATH,\n readFileSync,\n readFile\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst interpreterPath = (elf) => {\n if (elf.length < 64) {\n return null;\n }\n if (elf.readUInt32BE(0) !== 0x7F454C46) {\n // Unexpected magic bytes\n return null;\n }\n if (elf.readUInt8(4) !== 2) {\n // Not a 64-bit ELF\n return null;\n }\n if (elf.readUInt8(5) !== 1) {\n // Not little-endian\n return null;\n }\n const offset = elf.readUInt32LE(32);\n const size = elf.readUInt16LE(54);\n const count = elf.readUInt16LE(56);\n for (let i = 0; i < count; i++) {\n const headerOffset = offset + (i * size);\n const type = elf.readUInt32LE(headerOffset);\n if (type === 3) {\n const fileOffset = elf.readUInt32LE(headerOffset + 8);\n const fileSize = elf.readUInt32LE(headerOffset + 32);\n return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\\0.*$/g, '');\n }\n }\n return null;\n};\n\nmodule.exports = {\n interpreterPath\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst childProcess = require('child_process');\nconst { isLinux, getReport } = require('./process');\nconst { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem');\nconst { interpreterPath } = require('./elf');\n\nlet cachedFamilyInterpreter;\nlet cachedFamilyFilesystem;\nlet cachedVersionFilesystem;\n\nconst command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true';\nlet commandOut = '';\n\nconst safeCommand = () => {\n if (!commandOut) {\n return new Promise((resolve) => {\n childProcess.exec(command, (err, out) => {\n commandOut = err ? ' ' : out;\n resolve(commandOut);\n });\n });\n }\n return commandOut;\n};\n\nconst safeCommandSync = () => {\n if (!commandOut) {\n try {\n commandOut = childProcess.execSync(command, { encoding: 'utf8' });\n } catch (_err) {\n commandOut = ' ';\n }\n }\n return commandOut;\n};\n\n/**\n * A String constant containing the value `glibc`.\n * @type {string}\n * @public\n */\nconst GLIBC = 'glibc';\n\n/**\n * A Regexp constant to get the GLIBC Version.\n * @type {string}\n */\nconst RE_GLIBC_VERSION = /LIBC[a-z0-9 \\-).]*?(\\d+\\.\\d+)/i;\n\n/**\n * A String constant containing the value `musl`.\n * @type {string}\n * @public\n */\nconst MUSL = 'musl';\n\nconst isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-');\n\nconst familyFromReport = () => {\n const report = getReport();\n if (report.header && report.header.glibcVersionRuntime) {\n return GLIBC;\n }\n if (Array.isArray(report.sharedObjects)) {\n if (report.sharedObjects.some(isFileMusl)) {\n return MUSL;\n }\n }\n return null;\n};\n\nconst familyFromCommand = (out) => {\n const [getconf, ldd1] = out.split(/[\\r\\n]+/);\n if (getconf && getconf.includes(GLIBC)) {\n return GLIBC;\n }\n if (ldd1 && ldd1.includes(MUSL)) {\n return MUSL;\n }\n return null;\n};\n\nconst familyFromInterpreterPath = (path) => {\n if (path) {\n if (path.includes('/ld-musl-')) {\n return MUSL;\n } else if (path.includes('/ld-linux-')) {\n return GLIBC;\n }\n }\n return null;\n};\n\nconst getFamilyFromLddContent = (content) => {\n content = content.toString();\n if (content.includes('musl')) {\n return MUSL;\n }\n if (content.includes('GNU C Library')) {\n return GLIBC;\n }\n return null;\n};\n\nconst familyFromFilesystem = async () => {\n if (cachedFamilyFilesystem !== undefined) {\n return cachedFamilyFilesystem;\n }\n cachedFamilyFilesystem = null;\n try {\n const lddContent = await readFile(LDD_PATH);\n cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n } catch (e) {}\n return cachedFamilyFilesystem;\n};\n\nconst familyFromFilesystemSync = () => {\n if (cachedFamilyFilesystem !== undefined) {\n return cachedFamilyFilesystem;\n }\n cachedFamilyFilesystem = null;\n try {\n const lddContent = readFileSync(LDD_PATH);\n cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n } catch (e) {}\n return cachedFamilyFilesystem;\n};\n\nconst familyFromInterpreter = async () => {\n if (cachedFamilyInterpreter !== undefined) {\n return cachedFamilyInterpreter;\n }\n cachedFamilyInterpreter = null;\n try {\n const selfContent = await readFile(SELF_PATH);\n const path = interpreterPath(selfContent);\n cachedFamilyInterpreter = familyFromInterpreterPath(path);\n } catch (e) {}\n return cachedFamilyInterpreter;\n};\n\nconst familyFromInterpreterSync = () => {\n if (cachedFamilyInterpreter !== undefined) {\n return cachedFamilyInterpreter;\n }\n cachedFamilyInterpreter = null;\n try {\n const selfContent = readFileSync(SELF_PATH);\n const path = interpreterPath(selfContent);\n cachedFamilyInterpreter = familyFromInterpreterPath(path);\n } catch (e) {}\n return cachedFamilyInterpreter;\n};\n\n/**\n * Resolves with the libc family when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst family = async () => {\n let family = null;\n if (isLinux()) {\n family = await familyFromInterpreter();\n if (!family) {\n family = await familyFromFilesystem();\n if (!family) {\n family = familyFromReport();\n }\n if (!family) {\n const out = await safeCommand();\n family = familyFromCommand(out);\n }\n }\n }\n return family;\n};\n\n/**\n * Returns the libc family when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst familySync = () => {\n let family = null;\n if (isLinux()) {\n family = familyFromInterpreterSync();\n if (!family) {\n family = familyFromFilesystemSync();\n if (!family) {\n family = familyFromReport();\n }\n if (!family) {\n const out = safeCommandSync();\n family = familyFromCommand(out);\n }\n }\n }\n return family;\n};\n\n/**\n * Resolves `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {Promise<boolean>}\n */\nconst isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC;\n\n/**\n * Returns `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {boolean}\n */\nconst isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC;\n\nconst versionFromFilesystem = async () => {\n if (cachedVersionFilesystem !== undefined) {\n return cachedVersionFilesystem;\n }\n cachedVersionFilesystem = null;\n try {\n const lddContent = await readFile(LDD_PATH);\n const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n if (versionMatch) {\n cachedVersionFilesystem = versionMatch[1];\n }\n } catch (e) {}\n return cachedVersionFilesystem;\n};\n\nconst versionFromFilesystemSync = () => {\n if (cachedVersionFilesystem !== undefined) {\n return cachedVersionFilesystem;\n }\n cachedVersionFilesystem = null;\n try {\n const lddContent = readFileSync(LDD_PATH);\n const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n if (versionMatch) {\n cachedVersionFilesystem = versionMatch[1];\n }\n } catch (e) {}\n return cachedVersionFilesystem;\n};\n\nconst versionFromReport = () => {\n const report = getReport();\n if (report.header && report.header.glibcVersionRuntime) {\n return report.header.glibcVersionRuntime;\n }\n return null;\n};\n\nconst versionSuffix = (s) => s.trim().split(/\\s+/)[1];\n\nconst versionFromCommand = (out) => {\n const [getconf, ldd1, ldd2] = out.split(/[\\r\\n]+/);\n if (getconf && getconf.includes(GLIBC)) {\n return versionSuffix(getconf);\n }\n if (ldd1 && ldd2 && ldd1.includes(MUSL)) {\n return versionSuffix(ldd2);\n }\n return null;\n};\n\n/**\n * Resolves with the libc version when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst version = async () => {\n let version = null;\n if (isLinux()) {\n version = await versionFromFilesystem();\n if (!version) {\n version = versionFromReport();\n }\n if (!version) {\n const out = await safeCommand();\n version = versionFromCommand(out);\n }\n }\n return version;\n};\n\n/**\n * Returns the libc version when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst versionSync = () => {\n let version = null;\n if (isLinux()) {\n version = versionFromFilesystemSync();\n if (!version) {\n version = versionFromReport();\n }\n if (!version) {\n const out = safeCommandSync();\n version = versionFromCommand(out);\n }\n }\n return version;\n};\n\nmodule.exports = {\n GLIBC,\n MUSL,\n family,\n familySync,\n isNonGlibcLinux,\n isNonGlibcLinuxSync,\n version,\n versionSync\n};\n","'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n","'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n","'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numberic identifiers include numberic identifiers but can be longer.\n// Therefore non-numberic identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n","'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n","'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n","'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n","'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n","'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n","'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n","'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n","'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n","'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n","'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n","'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n","{\n \"name\": \"sharp\",\n \"description\": \"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images\",\n \"version\": \"0.33.5\",\n \"author\": \"Lovell Fuller <npm@lovell.info>\",\n \"homepage\": \"https://sharp.pixelplumbing.com\",\n \"contributors\": [\n \"Pierre Inglebert <pierre.inglebert@gmail.com>\",\n \"Jonathan Ong <jonathanrichardong@gmail.com>\",\n \"Chanon Sajjamanochai <chanon.s@gmail.com>\",\n \"Juliano Julio <julianojulio@gmail.com>\",\n \"Daniel Gasienica <daniel@gasienica.ch>\",\n \"Julian Walker <julian@fiftythree.com>\",\n \"Amit Pitaru <pitaru.amit@gmail.com>\",\n \"Brandon Aaron <hello.brandon@aaron.sh>\",\n \"Andreas Lind <andreas@one.com>\",\n \"Maurus Cuelenaere <mcuelenaere@gmail.com>\",\n \"Linus Unnebäck <linus@folkdatorn.se>\",\n \"Victor Mateevitsi <mvictoras@gmail.com>\",\n \"Alaric Holloway <alaric.holloway@gmail.com>\",\n \"Bernhard K. Weisshuhn <bkw@codingforce.com>\",\n \"Chris Riley <criley@primedia.com>\",\n \"David Carley <dacarley@gmail.com>\",\n \"John Tobin <john@limelightmobileinc.com>\",\n \"Kenton Gray <kentongray@gmail.com>\",\n \"Felix Bünemann <Felix.Buenemann@gmail.com>\",\n \"Samy Al Zahrani <samyalzahrany@gmail.com>\",\n \"Chintan Thakkar <lemnisk8@gmail.com>\",\n \"F. Orlando Galashan <frulo@gmx.de>\",\n \"Kleis Auke Wolthuizen <info@kleisauke.nl>\",\n \"Matt Hirsch <mhirsch@media.mit.edu>\",\n \"Matthias Thoemmes <thoemmes@gmail.com>\",\n \"Patrick Paskaris <patrick@paskaris.gr>\",\n \"Jérémy Lal <kapouer@melix.org>\",\n \"Rahul Nanwani <r.nanwani@gmail.com>\",\n \"Alice Monday <alice0meta@gmail.com>\",\n \"Kristo Jorgenson <kristo.jorgenson@gmail.com>\",\n \"YvesBos <yves_bos@outlook.com>\",\n \"Guy Maliar <guy@tailorbrands.com>\",\n \"Nicolas Coden <nicolas@ncoden.fr>\",\n \"Matt Parrish <matt.r.parrish@gmail.com>\",\n \"Marcel Bretschneider <marcel.bretschneider@gmail.com>\",\n \"Matthew McEachen <matthew+github@mceachen.org>\",\n \"Jarda Kotěšovec <jarda.kotesovec@gmail.com>\",\n \"Kenric D'Souza <kenric.dsouza@gmail.com>\",\n \"Oleh Aleinyk <oleg.aleynik@gmail.com>\",\n \"Marcel Bretschneider <marcel.bretschneider@gmail.com>\",\n \"Andrea Bianco <andrea.bianco@unibas.ch>\",\n \"Rik Heywood <rik@rik.org>\",\n \"Thomas Parisot <hi@oncletom.io>\",\n \"Nathan Graves <nathanrgraves+github@gmail.com>\",\n \"Tom Lokhorst <tom@lokhorst.eu>\",\n \"Espen Hovlandsdal <espen@hovlandsdal.com>\",\n \"Sylvain Dumont <sylvain.dumont35@gmail.com>\",\n \"Alun Davies <alun.owain.davies@googlemail.com>\",\n \"Aidan Hoolachan <ajhoolachan21@gmail.com>\",\n \"Axel Eirola <axel.eirola@iki.fi>\",\n \"Freezy <freezy@xbmc.org>\",\n \"Daiz <taneli.vatanen@gmail.com>\",\n \"Julian Aubourg <j@ubourg.net>\",\n \"Keith Belovay <keith@picthrive.com>\",\n \"Michael B. Klein <mbklein@gmail.com>\",\n \"Jordan Prudhomme <jordan@raboland.fr>\",\n \"Ilya Ovdin <iovdin@gmail.com>\",\n \"Andargor <andargor@yahoo.com>\",\n \"Paul Neave <paul.neave@gmail.com>\",\n \"Brendan Kennedy <brenwken@gmail.com>\",\n \"Brychan Bennett-Odlum <git@brychan.io>\",\n \"Edward Silverton <e.silverton@gmail.com>\",\n \"Roman Malieiev <aromaleev@gmail.com>\",\n \"Tomas Szabo <tomas.szabo@deftomat.com>\",\n \"Robert O'Rourke <robert@o-rourke.org>\",\n \"Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>\",\n \"Christian Flintrup <chr@gigahost.dk>\",\n \"Manan Jadhav <manan@motionden.com>\",\n \"Leon Radley <leon@radley.se>\",\n \"alza54 <alza54@thiocod.in>\",\n \"Jacob Smith <jacob@frende.me>\",\n \"Michael Nutt <michael@nutt.im>\",\n \"Brad Parham <baparham@gmail.com>\",\n \"Taneli Vatanen <taneli.vatanen@gmail.com>\",\n \"Joris Dugué <zaruike10@gmail.com>\",\n \"Chris Banks <christopher.bradley.banks@gmail.com>\",\n \"Ompal Singh <ompal.hitm09@gmail.com>\",\n \"Brodan <christopher.hranj@gmail.com>\",\n \"Ankur Parihar <ankur.github@gmail.com>\",\n \"Brahim Ait elhaj <brahima@gmail.com>\",\n \"Mart Jansink <m.jansink@gmail.com>\",\n \"Lachlan Newman <lachnewman007@gmail.com>\",\n \"Dennis Beatty <dennis@dcbeatty.com>\",\n \"Ingvar Stepanyan <me@rreverser.com>\",\n \"Don Denton <don@happycollision.com>\"\n ],\n \"scripts\": {\n \"install\": \"node install/check\",\n \"clean\": \"rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*\",\n \"test\": \"npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types\",\n \"test-lint\": \"semistandard && cpplint\",\n \"test-unit\": \"nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha\",\n \"test-licensing\": \"license-checker --production --summary --onlyAllow=\\\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\\\"\",\n \"test-leak\": \"./test/leak/leak.sh\",\n \"test-types\": \"tsd\",\n \"package-from-local-build\": \"node npm/from-local-build\",\n \"package-from-github-release\": \"node npm/from-github-release\",\n \"docs-build\": \"node docs/build && node docs/search-index/build\",\n \"docs-serve\": \"cd docs && npx serve\",\n \"docs-publish\": \"cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp\"\n },\n \"type\": \"commonjs\",\n \"main\": \"lib/index.js\",\n \"types\": \"lib/index.d.ts\",\n \"files\": [\n \"install\",\n \"lib\",\n \"src/*.{cc,h,gyp}\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/lovell/sharp.git\"\n },\n \"keywords\": [\n \"jpeg\",\n \"png\",\n \"webp\",\n \"avif\",\n \"tiff\",\n \"gif\",\n \"svg\",\n \"jp2\",\n \"dzi\",\n \"image\",\n \"resize\",\n \"thumbnail\",\n \"crop\",\n \"embed\",\n \"libvips\",\n \"vips\"\n ],\n \"dependencies\": {\n \"color\": \"^4.2.3\",\n \"detect-libc\": \"^2.0.3\",\n \"semver\": \"^7.6.3\"\n },\n \"optionalDependencies\": {\n \"@img/sharp-darwin-arm64\": \"0.33.5\",\n \"@img/sharp-darwin-x64\": \"0.33.5\",\n \"@img/sharp-libvips-darwin-arm64\": \"1.0.4\",\n \"@img/sharp-libvips-darwin-x64\": \"1.0.4\",\n \"@img/sharp-libvips-linux-arm\": \"1.0.5\",\n \"@img/sharp-libvips-linux-arm64\": \"1.0.4\",\n \"@img/sharp-libvips-linux-s390x\": \"1.0.4\",\n \"@img/sharp-libvips-linux-x64\": \"1.0.4\",\n \"@img/sharp-libvips-linuxmusl-arm64\": \"1.0.4\",\n \"@img/sharp-libvips-linuxmusl-x64\": \"1.0.4\",\n \"@img/sharp-linux-arm\": \"0.33.5\",\n \"@img/sharp-linux-arm64\": \"0.33.5\",\n \"@img/sharp-linux-s390x\": \"0.33.5\",\n \"@img/sharp-linux-x64\": \"0.33.5\",\n \"@img/sharp-linuxmusl-arm64\": \"0.33.5\",\n \"@img/sharp-linuxmusl-x64\": \"0.33.5\",\n \"@img/sharp-wasm32\": \"0.33.5\",\n \"@img/sharp-win32-ia32\": \"0.33.5\",\n \"@img/sharp-win32-x64\": \"0.33.5\"\n },\n \"devDependencies\": {\n \"@emnapi/runtime\": \"^1.2.0\",\n \"@img/sharp-libvips-dev\": \"1.0.4\",\n \"@img/sharp-libvips-dev-wasm32\": \"1.0.5\",\n \"@img/sharp-libvips-win32-ia32\": \"1.0.4\",\n \"@img/sharp-libvips-win32-x64\": \"1.0.4\",\n \"@types/node\": \"*\",\n \"async\": \"^3.2.5\",\n \"cc\": \"^3.0.1\",\n \"emnapi\": \"^1.2.0\",\n \"exif-reader\": \"^2.0.1\",\n \"extract-zip\": \"^2.0.1\",\n \"icc\": \"^3.0.0\",\n \"jsdoc-to-markdown\": \"^8.0.3\",\n \"license-checker\": \"^25.0.1\",\n \"mocha\": \"^10.7.3\",\n \"node-addon-api\": \"^8.1.0\",\n \"nyc\": \"^17.0.0\",\n \"prebuild\": \"^13.0.1\",\n \"semistandard\": \"^17.0.0\",\n \"tar-fs\": \"^3.0.6\",\n \"tsd\": \"^0.31.1\"\n },\n \"license\": \"Apache-2.0\",\n \"engines\": {\n \"node\": \"^18.17.0 || ^20.3.0 || >=21.0.0\"\n },\n \"config\": {\n \"libvips\": \">=8.15.3\"\n },\n \"funding\": {\n \"url\": \"https://opencollective.com/libvips\"\n },\n \"binary\": {\n \"napi_versions\": [\n 9\n ]\n },\n \"semistandard\": {\n \"env\": [\n \"mocha\"\n ]\n },\n \"cc\": {\n \"linelength\": \"120\",\n \"filter\": [\n \"build/include\"\n ]\n },\n \"nyc\": {\n \"include\": [\n \"lib\"\n ]\n },\n \"tsd\": {\n \"directory\": \"test/types/\"\n }\n}\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst { spawnSync } = require('node:child_process');\nconst { createHash } = require('node:crypto');\nconst semverCoerce = require('semver/functions/coerce');\nconst semverGreaterThanOrEqualTo = require('semver/functions/gte');\nconst semverSatisfies = require('semver/functions/satisfies');\nconst detectLibc = require('detect-libc');\n\nconst { config, engines, optionalDependencies } = require('../package.json');\n\nconst minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */\n config.libvips;\nconst minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version;\n\nconst prebuiltPlatforms = [\n 'darwin-arm64', 'darwin-x64',\n 'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64',\n 'linuxmusl-arm64', 'linuxmusl-x64',\n 'win32-ia32', 'win32-x64'\n];\n\nconst spawnSyncOptions = {\n encoding: 'utf8',\n shell: true\n};\n\nconst log = (item) => {\n if (item instanceof Error) {\n console.error(`sharp: Installation error: ${item.message}`);\n } else {\n console.log(`sharp: ${item}`);\n }\n};\n\n/* istanbul ignore next */\nconst runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : '';\n\nconst runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`;\n\n/* istanbul ignore next */\nconst buildPlatformArch = () => {\n if (isEmscripten()) {\n return 'wasm32';\n }\n /* eslint camelcase: [\"error\", { allow: [\"^npm_config_\"] }] */\n const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env;\n const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc();\n return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`;\n};\n\nconst buildSharpLibvipsIncludeDir = () => {\n try {\n return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`);\n } catch {\n try {\n return require('@img/sharp-libvips-dev/include');\n } catch {}\n }\n /* istanbul ignore next */\n return '';\n};\n\nconst buildSharpLibvipsCPlusPlusDir = () => {\n try {\n return require('@img/sharp-libvips-dev/cplusplus');\n } catch {}\n /* istanbul ignore next */\n return '';\n};\n\nconst buildSharpLibvipsLibDir = () => {\n try {\n return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`);\n } catch {\n try {\n return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`);\n } catch {}\n }\n /* istanbul ignore next */\n return '';\n};\n\nconst isUnsupportedNodeRuntime = () => {\n /* istanbul ignore next */\n if (process.release?.name === 'node' && process.versions) {\n if (!semverSatisfies(process.versions.node, engines.node)) {\n return { found: process.versions.node, expected: engines.node };\n }\n }\n};\n\n/* istanbul ignore next */\nconst isEmscripten = () => {\n const { CC } = process.env;\n return Boolean(CC && CC.endsWith('/emcc'));\n};\n\nconst isRosetta = () => {\n /* istanbul ignore next */\n if (process.platform === 'darwin' && process.arch === 'x64') {\n const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout;\n return (translated || '').trim() === 'sysctl.proc_translated: 1';\n }\n return false;\n};\n\nconst sha512 = (s) => createHash('sha512').update(s).digest('hex');\n\nconst yarnLocator = () => {\n try {\n const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`);\n const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`]).version;\n return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10);\n } catch {}\n return '';\n};\n\n/* istanbul ignore next */\nconst spawnRebuild = () =>\n spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, {\n ...spawnSyncOptions,\n stdio: 'inherit'\n }).status;\n\nconst globalLibvipsVersion = () => {\n if (process.platform !== 'win32') {\n const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', {\n ...spawnSyncOptions,\n env: {\n ...process.env,\n PKG_CONFIG_PATH: pkgConfigPath()\n }\n }).stdout;\n /* istanbul ignore next */\n return (globalLibvipsVersion || '').trim();\n } else {\n return '';\n }\n};\n\n/* istanbul ignore next */\nconst pkgConfigPath = () => {\n if (process.platform !== 'win32') {\n const brewPkgConfigPath = spawnSync(\n 'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d\" \" -f2',\n spawnSyncOptions\n ).stdout || '';\n return [\n brewPkgConfigPath.trim(),\n process.env.PKG_CONFIG_PATH,\n '/usr/local/lib/pkgconfig',\n '/usr/lib/pkgconfig',\n '/usr/local/libdata/pkgconfig',\n '/usr/libdata/pkgconfig'\n ].filter(Boolean).join(':');\n } else {\n return '';\n }\n};\n\nconst skipSearch = (status, reason, logger) => {\n if (logger) {\n logger(`Detected ${reason}, skipping search for globally-installed libvips`);\n }\n return status;\n};\n\nconst useGlobalLibvips = (logger) => {\n if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) {\n return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger);\n }\n if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) {\n return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger);\n }\n /* istanbul ignore next */\n if (isRosetta()) {\n return skipSearch(false, 'Rosetta', logger);\n }\n const globalVipsVersion = globalLibvipsVersion();\n return !!globalVipsVersion && /* istanbul ignore next */\n semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion);\n};\n\nmodule.exports = {\n minimumLibvipsVersion,\n prebuiltPlatforms,\n buildPlatformArch,\n buildSharpLibvipsIncludeDir,\n buildSharpLibvipsCPlusPlusDir,\n buildSharpLibvipsLibDir,\n isUnsupportedNodeRuntime,\n runtimePlatformArch,\n log,\n yarnLocator,\n spawnRebuild,\n globalLibvipsVersion,\n pkgConfigPath,\n useGlobalLibvips\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\n// Inspects the runtime environment and exports the relevant sharp.node binary\n\nconst { familySync, versionSync } = require('detect-libc');\n\nconst { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips');\nconst runtimePlatform = runtimePlatformArch();\n\nconst paths = [\n `../src/build/Release/sharp-${runtimePlatform}.node`,\n '../src/build/Release/sharp-wasm32.node',\n `@img/sharp-${runtimePlatform}/sharp.node`,\n '@img/sharp-wasm32/sharp.node'\n];\n\nlet sharp;\nconst errors = [];\nfor (const path of paths) {\n try {\n sharp = require(path);\n break;\n } catch (err) {\n /* istanbul ignore next */\n errors.push(err);\n }\n}\n\n/* istanbul ignore next */\nif (sharp) {\n module.exports = sharp;\n} else {\n const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os));\n\n const help = [`Could not load the \"sharp\" module using the ${runtimePlatform} runtime`];\n errors.forEach(err => {\n if (err.code !== 'MODULE_NOT_FOUND') {\n help.push(`${err.code}: ${err.message}`);\n }\n });\n const messages = errors.map(err => err.message).join(' ');\n help.push('Possible solutions:');\n // Common error messages\n if (isUnsupportedNodeRuntime()) {\n const { found, expected } = isUnsupportedNodeRuntime();\n help.push(\n '- Please upgrade Node.js:',\n ` Found ${found}`,\n ` Requires ${expected}`\n );\n } else if (prebuiltPlatforms.includes(runtimePlatform)) {\n const [os, cpu] = runtimePlatform.split('-');\n const libc = os.endsWith('musl') ? ' --libc=musl' : '';\n help.push(\n '- Ensure optional dependencies can be installed:',\n ' npm install --include=optional sharp',\n '- Ensure your package manager supports multi-platform installation:',\n ' See https://sharp.pixelplumbing.com/install#cross-platform',\n '- Add platform-specific dependencies:',\n ` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp`\n );\n } else {\n help.push(\n `- Manually install libvips >= ${minimumLibvipsVersion}`,\n '- Add experimental WebAssembly-based dependencies:',\n ' npm install --cpu=wasm32 sharp',\n ' npm install @img/sharp-wasm32'\n );\n }\n if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) {\n try {\n const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);\n const libcFound = `${familySync()} ${versionSync()}`;\n const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`;\n help.push(\n '- Update your OS:',\n ` Found ${libcFound}`,\n ` Requires ${libcRequires}`\n );\n } catch (errEngines) {}\n }\n if (isLinux && /\\/snap\\/core[0-9]{2}/.test(messages)) {\n help.push(\n '- Remove the Node.js Snap, which does not support native modules',\n ' snap remove node'\n );\n }\n if (isMacOs && /Incompatible library version/.test(messages)) {\n help.push(\n '- Update Homebrew:',\n ' brew update && brew upgrade vips'\n );\n }\n if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) {\n help.push('- Run Node.js without using the --no-addons flag');\n }\n // Link to installation docs\n if (isWindows && /The specified procedure could not be found/.test(messages)) {\n help.push(\n '- Using the canvas package on Windows?',\n ' See https://sharp.pixelplumbing.com/install#canvas-and-windows',\n '- Check for outdated versions of sharp in the dependency tree:',\n ' npm ls sharp'\n );\n }\n help.push(\n '- Consult the installation documentation:',\n ' See https://sharp.pixelplumbing.com/install'\n );\n throw new Error(help.join('\\n'));\n}\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst util = require('node:util');\nconst stream = require('node:stream');\nconst is = require('./is');\n\nrequire('./sharp');\n\n// Use NODE_DEBUG=sharp to enable libvips warnings\nconst debuglog = util.debuglog('sharp');\n\n/**\n * Constructor factory to create an instance of `sharp`, to which further methods are chained.\n *\n * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object.\n * When using Stream based output, derived attributes are available from the `info` event.\n *\n * Non-critical problems encountered during processing are emitted as `warning` events.\n *\n * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class.\n *\n * When loading more than one page/frame of an animated image,\n * these are combined as a vertically-stacked \"toilet roll\" image\n * where the overall height is the `pageHeight` multiplied by the number of `pages`.\n *\n * @constructs Sharp\n *\n * @emits Sharp#info\n * @emits Sharp#warning\n *\n * @example\n * sharp('input.jpg')\n * .resize(300, 200)\n * .toFile('output.jpg', function(err) {\n * // output.jpg is a 300 pixels wide and 200 pixels high image\n * // containing a scaled and cropped version of input.jpg\n * });\n *\n * @example\n * // Read image data from remote URL,\n * // resize to 300 pixels wide,\n * // emit an 'info' event with calculated dimensions\n * // and finally write image data to writableStream\n * const { body } = fetch('https://...');\n * const readableStream = Readable.fromWeb(body);\n * const transformer = sharp()\n * .resize(300)\n * .on('info', ({ height }) => {\n * console.log(`Image height is ${height}`);\n * });\n * readableStream.pipe(transformer).pipe(writableStream);\n *\n * @example\n * // Create a blank 300x200 PNG image of semi-translucent red pixels\n * sharp({\n * create: {\n * width: 300,\n * height: 200,\n * channels: 4,\n * background: { r: 255, g: 0, b: 0, alpha: 0.5 }\n * }\n * })\n * .png()\n * .toBuffer()\n * .then( ... );\n *\n * @example\n * // Convert an animated GIF to an animated WebP\n * await sharp('in.gif', { animated: true }).toFile('out.webp');\n *\n * @example\n * // Read a raw array of pixels and save it to a png\n * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray\n * const image = sharp(input, {\n * // because the input does not contain its dimensions or how many channels it has\n * // we need to specify it in the constructor options\n * raw: {\n * width: 2,\n * height: 1,\n * channels: 3\n * }\n * });\n * await image.toFile('my-two-pixels.png');\n *\n * @example\n * // Generate RGB Gaussian noise\n * await sharp({\n * create: {\n * width: 300,\n * height: 200,\n * channels: 3,\n * noise: {\n * type: 'gaussian',\n * mean: 128,\n * sigma: 30\n * }\n * }\n * }).toFile('noise.png');\n *\n * @example\n * // Generate an image from text\n * await sharp({\n * text: {\n * text: 'Hello, world!',\n * width: 400, // max width\n * height: 300 // max height\n * }\n * }).toFile('text_bw.png');\n *\n * @example\n * // Generate an rgba image from text using pango markup and font\n * await sharp({\n * text: {\n * text: '<span foreground=\"red\">Red!</span><span background=\"cyan\">blue</span>',\n * font: 'sans',\n * rgba: true,\n * dpi: 300\n * }\n * }).toFile('text_rgba.png');\n *\n * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be\n * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or\n * a TypedArray containing raw pixel image data, or\n * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file.\n * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present.\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort.\n * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels\n * (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted.\n * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF).\n * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF).\n * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically.\n * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000.\n * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored.\n * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages.\n * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based.\n * @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image.\n * @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based.\n * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`.\n * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering.\n * @param {number} [options.raw.width] - integral number of pixels wide.\n * @param {number} [options.raw.height] - integral number of pixels high.\n * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4.\n * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true`\n * to avoid sharp premultiplying the image. (optional, default `false`)\n * @param {Object} [options.create] - describes a new image to be created.\n * @param {number} [options.create.width] - integral number of pixels wide.\n * @param {number} [options.create.height] - integral number of pixels high.\n * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA).\n * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Object} [options.create.noise] - describes a noise to be created.\n * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported.\n * @param {number} [options.create.noise.mean] - mean of pixels in generated noise.\n * @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise.\n * @param {Object} [options.text] - describes a new text image to be created.\n * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.\n * @param {string} [options.text.font] - font name to render with.\n * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.\n * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.\n * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.\n * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text.\n * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.\n * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `<span foreground=\"red\">Red!</span>`.\n * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified.\n * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nconst Sharp = function (input, options) {\n if (arguments.length === 1 && !is.defined(input)) {\n throw new Error('Invalid input');\n }\n if (!(this instanceof Sharp)) {\n return new Sharp(input, options);\n }\n stream.Duplex.call(this);\n this.options = {\n // resize options\n topOffsetPre: -1,\n leftOffsetPre: -1,\n widthPre: -1,\n heightPre: -1,\n topOffsetPost: -1,\n leftOffsetPost: -1,\n widthPost: -1,\n heightPost: -1,\n width: -1,\n height: -1,\n canvas: 'crop',\n position: 0,\n resizeBackground: [0, 0, 0, 255],\n useExifOrientation: false,\n angle: 0,\n rotationAngle: 0,\n rotationBackground: [0, 0, 0, 255],\n rotateBeforePreExtract: false,\n flip: false,\n flop: false,\n extendTop: 0,\n extendBottom: 0,\n extendLeft: 0,\n extendRight: 0,\n extendBackground: [0, 0, 0, 255],\n extendWith: 'background',\n withoutEnlargement: false,\n withoutReduction: false,\n affineMatrix: [],\n affineBackground: [0, 0, 0, 255],\n affineIdx: 0,\n affineIdy: 0,\n affineOdx: 0,\n affineOdy: 0,\n affineInterpolator: this.constructor.interpolators.bilinear,\n kernel: 'lanczos3',\n fastShrinkOnLoad: true,\n // operations\n tint: [-1, 0, 0, 0],\n flatten: false,\n flattenBackground: [0, 0, 0],\n unflatten: false,\n negate: false,\n negateAlpha: true,\n medianSize: 0,\n blurSigma: 0,\n precision: 'integer',\n minAmpl: 0.2,\n sharpenSigma: 0,\n sharpenM1: 1,\n sharpenM2: 2,\n sharpenX1: 2,\n sharpenY2: 10,\n sharpenY3: 20,\n threshold: 0,\n thresholdGrayscale: true,\n trimBackground: [],\n trimThreshold: -1,\n trimLineArt: false,\n gamma: 0,\n gammaOut: 0,\n greyscale: false,\n normalise: false,\n normaliseLower: 1,\n normaliseUpper: 99,\n claheWidth: 0,\n claheHeight: 0,\n claheMaxSlope: 3,\n brightness: 1,\n saturation: 1,\n hue: 0,\n lightness: 0,\n booleanBufferIn: null,\n booleanFileIn: '',\n joinChannelIn: [],\n extractChannel: -1,\n removeAlpha: false,\n ensureAlpha: -1,\n colourspace: 'srgb',\n colourspacePipeline: 'last',\n composite: [],\n // output\n fileOut: '',\n formatOut: 'input',\n streamOut: false,\n keepMetadata: 0,\n withMetadataOrientation: -1,\n withMetadataDensity: 0,\n withIccProfile: '',\n withExif: {},\n withExifMerge: true,\n resolveWithObject: false,\n // output format\n jpegQuality: 80,\n jpegProgressive: false,\n jpegChromaSubsampling: '4:2:0',\n jpegTrellisQuantisation: false,\n jpegOvershootDeringing: false,\n jpegOptimiseScans: false,\n jpegOptimiseCoding: true,\n jpegQuantisationTable: 0,\n pngProgressive: false,\n pngCompressionLevel: 6,\n pngAdaptiveFiltering: false,\n pngPalette: false,\n pngQuality: 100,\n pngEffort: 7,\n pngBitdepth: 8,\n pngDither: 1,\n jp2Quality: 80,\n jp2TileHeight: 512,\n jp2TileWidth: 512,\n jp2Lossless: false,\n jp2ChromaSubsampling: '4:4:4',\n webpQuality: 80,\n webpAlphaQuality: 100,\n webpLossless: false,\n webpNearLossless: false,\n webpSmartSubsample: false,\n webpPreset: 'default',\n webpEffort: 4,\n webpMinSize: false,\n webpMixed: false,\n gifBitdepth: 8,\n gifEffort: 7,\n gifDither: 1,\n gifInterFrameMaxError: 0,\n gifInterPaletteMaxError: 3,\n gifReuse: true,\n gifProgressive: false,\n tiffQuality: 80,\n tiffCompression: 'jpeg',\n tiffPredictor: 'horizontal',\n tiffPyramid: false,\n tiffMiniswhite: false,\n tiffBitdepth: 8,\n tiffTile: false,\n tiffTileHeight: 256,\n tiffTileWidth: 256,\n tiffXres: 1.0,\n tiffYres: 1.0,\n tiffResolutionUnit: 'inch',\n heifQuality: 50,\n heifLossless: false,\n heifCompression: 'av1',\n heifEffort: 4,\n heifChromaSubsampling: '4:4:4',\n heifBitdepth: 8,\n jxlDistance: 1,\n jxlDecodingTier: 0,\n jxlEffort: 7,\n jxlLossless: false,\n rawDepth: 'uchar',\n tileSize: 256,\n tileOverlap: 0,\n tileContainer: 'fs',\n tileLayout: 'dz',\n tileFormat: 'last',\n tileDepth: 'last',\n tileAngle: 0,\n tileSkipBlanks: -1,\n tileBackground: [255, 255, 255, 255],\n tileCentre: false,\n tileId: 'https://example.com/iiif',\n tileBasename: '',\n timeoutSeconds: 0,\n linearA: [],\n linearB: [],\n // Function to notify of libvips warnings\n debuglog: warning => {\n this.emit('warning', warning);\n debuglog(warning);\n },\n // Function to notify of queue length changes\n queueListener: function (queueLength) {\n Sharp.queue.emit('change', queueLength);\n }\n };\n this.options.input = this._createInputDescriptor(input, options, { allowStream: true });\n return this;\n};\nObject.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype);\nObject.setPrototypeOf(Sharp, stream.Duplex);\n\n/**\n * Take a \"snapshot\" of the Sharp instance, returning a new instance.\n * Cloned instances inherit the input of their parent instance.\n * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream.\n *\n * @example\n * const pipeline = sharp().rotate();\n * pipeline.clone().resize(800, 600).pipe(firstWritableStream);\n * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream);\n * readableStream.pipe(pipeline);\n * // firstWritableStream receives auto-rotated, resized readableStream\n * // secondWritableStream receives auto-rotated, extracted region of readableStream\n *\n * @example\n * // Create a pipeline that will download an image, resize it and format it to different files\n * // Using Promises to know when the pipeline is complete\n * const fs = require(\"fs\");\n * const got = require(\"got\");\n * const sharpStream = sharp({ failOn: 'none' });\n *\n * const promises = [];\n *\n * promises.push(\n * sharpStream\n * .clone()\n * .jpeg({ quality: 100 })\n * .toFile(\"originalFile.jpg\")\n * );\n *\n * promises.push(\n * sharpStream\n * .clone()\n * .resize({ width: 500 })\n * .jpeg({ quality: 80 })\n * .toFile(\"optimized-500.jpg\")\n * );\n *\n * promises.push(\n * sharpStream\n * .clone()\n * .resize({ width: 500 })\n * .webp({ quality: 80 })\n * .toFile(\"optimized-500.webp\")\n * );\n *\n * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md\n * got.stream(\"https://www.example.com/some-file.jpg\").pipe(sharpStream);\n *\n * Promise.all(promises)\n * .then(res => { console.log(\"Done!\", res); })\n * .catch(err => {\n * console.error(\"Error processing files, let's clean it up\", err);\n * try {\n * fs.unlinkSync(\"originalFile.jpg\");\n * fs.unlinkSync(\"optimized-500.jpg\");\n * fs.unlinkSync(\"optimized-500.webp\");\n * } catch (e) {}\n * });\n *\n * @returns {Sharp}\n */\nfunction clone () {\n // Clone existing options\n const clone = this.constructor.call();\n const { debuglog, queueListener, ...options } = this.options;\n clone.options = structuredClone(options);\n clone.options.debuglog = debuglog;\n clone.options.queueListener = queueListener;\n // Pass 'finish' event to clone for Stream-based input\n if (this._isStreamInput()) {\n this.on('finish', () => {\n // Clone inherits input data\n this._flattenBufferIn();\n clone.options.input.buffer = this.options.input.buffer;\n clone.emit('finish');\n });\n }\n return clone;\n}\nObject.assign(Sharp.prototype, { clone });\n\n/**\n * Export constructor.\n * @private\n */\nmodule.exports = Sharp;\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","module.exports = function isArrayish(obj) {\n\tif (!obj || typeof obj === 'string') {\n\t\treturn false;\n\t}\n\n\treturn obj instanceof Array || Array.isArray(obj) ||\n\t\t(obj.length >= 0 && (obj.splice instanceof Function ||\n\t\t\t(Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String')));\n};\n","'use strict';\n\nvar isArrayish = require('is-arrayish');\n\nvar concat = Array.prototype.concat;\nvar slice = Array.prototype.slice;\n\nvar swizzle = module.exports = function swizzle(args) {\n\tvar results = [];\n\n\tfor (var i = 0, len = args.length; i < len; i++) {\n\t\tvar arg = args[i];\n\n\t\tif (isArrayish(arg)) {\n\t\t\t// http://jsperf.com/javascript-array-concat-vs-push/98\n\t\t\tresults = concat.call(results, slice.call(arg));\n\t\t} else {\n\t\t\tresults.push(arg);\n\t\t}\n\t}\n\n\treturn results;\n};\n\nswizzle.wrap = function (fn) {\n\treturn function () {\n\t\treturn fn(swizzle(arguments));\n\t};\n};\n","/* MIT license */\nvar colorNames = require('color-name');\nvar swizzle = require('simple-swizzle');\nvar hasOwnProperty = Object.hasOwnProperty;\n\nvar reverseNames = Object.create(null);\n\n// create a list of reverse color names\nfor (var name in colorNames) {\n\tif (hasOwnProperty.call(colorNames, name)) {\n\t\treverseNames[colorNames[name]] = name;\n\t}\n}\n\nvar cs = module.exports = {\n\tto: {},\n\tget: {}\n};\n\ncs.get = function (string) {\n\tvar prefix = string.substring(0, 3).toLowerCase();\n\tvar val;\n\tvar model;\n\tswitch (prefix) {\n\t\tcase 'hsl':\n\t\t\tval = cs.get.hsl(string);\n\t\t\tmodel = 'hsl';\n\t\t\tbreak;\n\t\tcase 'hwb':\n\t\t\tval = cs.get.hwb(string);\n\t\t\tmodel = 'hwb';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tval = cs.get.rgb(string);\n\t\t\tmodel = 'rgb';\n\t\t\tbreak;\n\t}\n\n\tif (!val) {\n\t\treturn null;\n\t}\n\n\treturn {model: model, value: val};\n};\n\ncs.get.rgb = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar abbr = /^#([a-f0-9]{3,4})$/i;\n\tvar hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;\n\tvar rgba = /^rgba?\\(\\s*([+-]?\\d+)(?=[\\s,])\\s*(?:,\\s*)?([+-]?\\d+)(?=[\\s,])\\s*(?:,\\s*)?([+-]?\\d+)\\s*(?:[,|\\/]\\s*([+-]?[\\d\\.]+)(%?)\\s*)?\\)$/;\n\tvar per = /^rgba?\\(\\s*([+-]?[\\d\\.]+)\\%\\s*,?\\s*([+-]?[\\d\\.]+)\\%\\s*,?\\s*([+-]?[\\d\\.]+)\\%\\s*(?:[,|\\/]\\s*([+-]?[\\d\\.]+)(%?)\\s*)?\\)$/;\n\tvar keyword = /^(\\w+)$/;\n\n\tvar rgb = [0, 0, 0, 1];\n\tvar match;\n\tvar i;\n\tvar hexAlpha;\n\n\tif (match = string.match(hex)) {\n\t\thexAlpha = match[2];\n\t\tmatch = match[1];\n\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\t// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19\n\t\t\tvar i2 = i * 2;\n\t\t\trgb[i] = parseInt(match.slice(i2, i2 + 2), 16);\n\t\t}\n\n\t\tif (hexAlpha) {\n\t\t\trgb[3] = parseInt(hexAlpha, 16) / 255;\n\t\t}\n\t} else if (match = string.match(abbr)) {\n\t\tmatch = match[1];\n\t\thexAlpha = match[3];\n\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = parseInt(match[i] + match[i], 16);\n\t\t}\n\n\t\tif (hexAlpha) {\n\t\t\trgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;\n\t\t}\n\t} else if (match = string.match(rgba)) {\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = parseInt(match[i + 1], 0);\n\t\t}\n\n\t\tif (match[4]) {\n\t\t\tif (match[5]) {\n\t\t\t\trgb[3] = parseFloat(match[4]) * 0.01;\n\t\t\t} else {\n\t\t\t\trgb[3] = parseFloat(match[4]);\n\t\t\t}\n\t\t}\n\t} else if (match = string.match(per)) {\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);\n\t\t}\n\n\t\tif (match[4]) {\n\t\t\tif (match[5]) {\n\t\t\t\trgb[3] = parseFloat(match[4]) * 0.01;\n\t\t\t} else {\n\t\t\t\trgb[3] = parseFloat(match[4]);\n\t\t\t}\n\t\t}\n\t} else if (match = string.match(keyword)) {\n\t\tif (match[1] === 'transparent') {\n\t\t\treturn [0, 0, 0, 0];\n\t\t}\n\n\t\tif (!hasOwnProperty.call(colorNames, match[1])) {\n\t\t\treturn null;\n\t\t}\n\n\t\trgb = colorNames[match[1]];\n\t\trgb[3] = 1;\n\n\t\treturn rgb;\n\t} else {\n\t\treturn null;\n\t}\n\n\tfor (i = 0; i < 3; i++) {\n\t\trgb[i] = clamp(rgb[i], 0, 255);\n\t}\n\trgb[3] = clamp(rgb[3], 0, 1);\n\n\treturn rgb;\n};\n\ncs.get.hsl = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar hsl = /^hsla?\\(\\s*([+-]?(?:\\d{0,3}\\.)?\\d+)(?:deg)?\\s*,?\\s*([+-]?[\\d\\.]+)%\\s*,?\\s*([+-]?[\\d\\.]+)%\\s*(?:[,|\\/]\\s*([+-]?(?=\\.\\d|\\d)(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)\\s*)?\\)$/;\n\tvar match = string.match(hsl);\n\n\tif (match) {\n\t\tvar alpha = parseFloat(match[4]);\n\t\tvar h = ((parseFloat(match[1]) % 360) + 360) % 360;\n\t\tvar s = clamp(parseFloat(match[2]), 0, 100);\n\t\tvar l = clamp(parseFloat(match[3]), 0, 100);\n\t\tvar a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);\n\n\t\treturn [h, s, l, a];\n\t}\n\n\treturn null;\n};\n\ncs.get.hwb = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar hwb = /^hwb\\(\\s*([+-]?\\d{0,3}(?:\\.\\d+)?)(?:deg)?\\s*,\\s*([+-]?[\\d\\.]+)%\\s*,\\s*([+-]?[\\d\\.]+)%\\s*(?:,\\s*([+-]?(?=\\.\\d|\\d)(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)\\s*)?\\)$/;\n\tvar match = string.match(hwb);\n\n\tif (match) {\n\t\tvar alpha = parseFloat(match[4]);\n\t\tvar h = ((parseFloat(match[1]) % 360) + 360) % 360;\n\t\tvar w = clamp(parseFloat(match[2]), 0, 100);\n\t\tvar b = clamp(parseFloat(match[3]), 0, 100);\n\t\tvar a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);\n\t\treturn [h, w, b, a];\n\t}\n\n\treturn null;\n};\n\ncs.to.hex = function () {\n\tvar rgba = swizzle(arguments);\n\n\treturn (\n\t\t'#' +\n\t\thexDouble(rgba[0]) +\n\t\thexDouble(rgba[1]) +\n\t\thexDouble(rgba[2]) +\n\t\t(rgba[3] < 1\n\t\t\t? (hexDouble(Math.round(rgba[3] * 255)))\n\t\t\t: '')\n\t);\n};\n\ncs.to.rgb = function () {\n\tvar rgba = swizzle(arguments);\n\n\treturn rgba.length < 4 || rgba[3] === 1\n\t\t? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'\n\t\t: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';\n};\n\ncs.to.rgb.percent = function () {\n\tvar rgba = swizzle(arguments);\n\n\tvar r = Math.round(rgba[0] / 255 * 100);\n\tvar g = Math.round(rgba[1] / 255 * 100);\n\tvar b = Math.round(rgba[2] / 255 * 100);\n\n\treturn rgba.length < 4 || rgba[3] === 1\n\t\t? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'\n\t\t: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';\n};\n\ncs.to.hsl = function () {\n\tvar hsla = swizzle(arguments);\n\treturn hsla.length < 4 || hsla[3] === 1\n\t\t? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'\n\t\t: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';\n};\n\n// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax\n// (hwb have alpha optional & 1 is default value)\ncs.to.hwb = function () {\n\tvar hwba = swizzle(arguments);\n\n\tvar a = '';\n\tif (hwba.length >= 4 && hwba[3] !== 1) {\n\t\ta = ', ' + hwba[3];\n\t}\n\n\treturn 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';\n};\n\ncs.to.keyword = function (rgb) {\n\treturn reverseNames[rgb.slice(0, 3)];\n};\n\n// helpers\nfunction clamp(num, min, max) {\n\treturn Math.min(Math.max(min, num), max);\n}\n\nfunction hexDouble(num) {\n\tvar str = Math.round(num).toString(16).toUpperCase();\n\treturn (str.length < 2) ? '0' + str : str;\n}\n","/* MIT license */\n/* eslint-disable no-mixed-operators */\nconst cssKeywords = require('color-name');\n\n// NOTE: conversions should only return primitive values (i.e. arrays, or\n// values that give correct `typeof` results).\n// do not use box values types (i.e. Number(), String(), etc.)\n\nconst reverseKeywords = {};\nfor (const key of Object.keys(cssKeywords)) {\n\treverseKeywords[cssKeywords[key]] = key;\n}\n\nconst convert = {\n\trgb: {channels: 3, labels: 'rgb'},\n\thsl: {channels: 3, labels: 'hsl'},\n\thsv: {channels: 3, labels: 'hsv'},\n\thwb: {channels: 3, labels: 'hwb'},\n\tcmyk: {channels: 4, labels: 'cmyk'},\n\txyz: {channels: 3, labels: 'xyz'},\n\tlab: {channels: 3, labels: 'lab'},\n\tlch: {channels: 3, labels: 'lch'},\n\thex: {channels: 1, labels: ['hex']},\n\tkeyword: {channels: 1, labels: ['keyword']},\n\tansi16: {channels: 1, labels: ['ansi16']},\n\tansi256: {channels: 1, labels: ['ansi256']},\n\thcg: {channels: 3, labels: ['h', 'c', 'g']},\n\tapple: {channels: 3, labels: ['r16', 'g16', 'b16']},\n\tgray: {channels: 1, labels: ['gray']}\n};\n\nmodule.exports = convert;\n\n// Hide .channels and .labels properties\nfor (const model of Object.keys(convert)) {\n\tif (!('channels' in convert[model])) {\n\t\tthrow new Error('missing channels property: ' + model);\n\t}\n\n\tif (!('labels' in convert[model])) {\n\t\tthrow new Error('missing channel labels property: ' + model);\n\t}\n\n\tif (convert[model].labels.length !== convert[model].channels) {\n\t\tthrow new Error('channel and label counts mismatch: ' + model);\n\t}\n\n\tconst {channels, labels} = convert[model];\n\tdelete convert[model].channels;\n\tdelete convert[model].labels;\n\tObject.defineProperty(convert[model], 'channels', {value: channels});\n\tObject.defineProperty(convert[model], 'labels', {value: labels});\n}\n\nconvert.rgb.hsl = function (rgb) {\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\tconst min = Math.min(r, g, b);\n\tconst max = Math.max(r, g, b);\n\tconst delta = max - min;\n\tlet h;\n\tlet s;\n\n\tif (max === min) {\n\t\th = 0;\n\t} else if (r === max) {\n\t\th = (g - b) / delta;\n\t} else if (g === max) {\n\t\th = 2 + (b - r) / delta;\n\t} else if (b === max) {\n\t\th = 4 + (r - g) / delta;\n\t}\n\n\th = Math.min(h * 60, 360);\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tconst l = (min + max) / 2;\n\n\tif (max === min) {\n\t\ts = 0;\n\t} else if (l <= 0.5) {\n\t\ts = delta / (max + min);\n\t} else {\n\t\ts = delta / (2 - max - min);\n\t}\n\n\treturn [h, s * 100, l * 100];\n};\n\nconvert.rgb.hsv = function (rgb) {\n\tlet rdif;\n\tlet gdif;\n\tlet bdif;\n\tlet h;\n\tlet s;\n\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\tconst v = Math.max(r, g, b);\n\tconst diff = v - Math.min(r, g, b);\n\tconst diffc = function (c) {\n\t\treturn (v - c) / 6 / diff + 1 / 2;\n\t};\n\n\tif (diff === 0) {\n\t\th = 0;\n\t\ts = 0;\n\t} else {\n\t\ts = diff / v;\n\t\trdif = diffc(r);\n\t\tgdif = diffc(g);\n\t\tbdif = diffc(b);\n\n\t\tif (r === v) {\n\t\t\th = bdif - gdif;\n\t\t} else if (g === v) {\n\t\t\th = (1 / 3) + rdif - bdif;\n\t\t} else if (b === v) {\n\t\t\th = (2 / 3) + gdif - rdif;\n\t\t}\n\n\t\tif (h < 0) {\n\t\t\th += 1;\n\t\t} else if (h > 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tconst r = rgb[0];\n\tconst g = rgb[1];\n\tlet b = rgb[2];\n\tconst h = convert.rgb.hsl(rgb)[0];\n\tconst w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\n\tconst k = Math.min(1 - r, 1 - g, 1 - b);\n\tconst c = (1 - r - k) / (1 - k) || 0;\n\tconst m = (1 - g - k) / (1 - k) || 0;\n\tconst y = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\nfunction comparativeDistance(x, y) {\n\t/*\n\t\tSee https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n\t*/\n\treturn (\n\t\t((x[0] - y[0]) ** 2) +\n\t\t((x[1] - y[1]) ** 2) +\n\t\t((x[2] - y[2]) ** 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tconst reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tlet currentClosestDistance = Infinity;\n\tlet currentClosestKeyword;\n\n\tfor (const keyword of Object.keys(cssKeywords)) {\n\t\tconst value = cssKeywords[keyword];\n\n\t\t// Compute comparative distance\n\t\tconst distance = comparativeDistance(rgb, value);\n\n\t\t// Check if its less, if so set as closest\n\t\tif (distance < currentClosestDistance) {\n\t\t\tcurrentClosestDistance = distance;\n\t\t\tcurrentClosestKeyword = keyword;\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tlet r = rgb[0] / 255;\n\tlet g = rgb[1] / 255;\n\tlet b = rgb[2] / 255;\n\n\t// Assume sRGB\n\tr = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);\n\n\tconst x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tconst y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tconst z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tconst xyz = convert.rgb.xyz(rgb);\n\tlet x = xyz[0];\n\tlet y = xyz[1];\n\tlet z = xyz[2];\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);\n\n\tconst l = (116 * y) - 16;\n\tconst a = 500 * (x - y);\n\tconst b = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tconst h = hsl[0] / 360;\n\tconst s = hsl[1] / 100;\n\tconst l = hsl[2] / 100;\n\tlet t2;\n\tlet t3;\n\tlet val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tconst t1 = 2 * l - t2;\n\n\tconst rgb = [0, 0, 0];\n\tfor (let i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tconst h = hsl[0];\n\tlet s = hsl[1] / 100;\n\tlet l = hsl[2] / 100;\n\tlet smin = s;\n\tconst lmin = Math.max(l, 0.01);\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tconst v = (l + s) / 2;\n\tconst sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tconst h = hsv[0] / 60;\n\tconst s = hsv[1] / 100;\n\tlet v = hsv[2] / 100;\n\tconst hi = Math.floor(h) % 6;\n\n\tconst f = h - Math.floor(h);\n\tconst p = 255 * v * (1 - s);\n\tconst q = 255 * v * (1 - (s * f));\n\tconst t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tconst h = hsv[0];\n\tconst s = hsv[1] / 100;\n\tconst v = hsv[2] / 100;\n\tconst vmin = Math.max(v, 0.01);\n\tlet sl;\n\tlet l;\n\n\tl = (2 - s) * v;\n\tconst lmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tconst h = hwb[0] / 360;\n\tlet wh = hwb[1] / 100;\n\tlet bl = hwb[2] / 100;\n\tconst ratio = wh + bl;\n\tlet f;\n\n\t// Wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\tconst i = Math.floor(6 * h);\n\tconst v = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tconst n = wh + f * (v - wh); // Linear interpolation\n\n\tlet r;\n\tlet g;\n\tlet b;\n\t/* eslint-disable max-statements-per-line,no-multi-spaces */\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\t/* eslint-enable max-statements-per-line,no-multi-spaces */\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tconst c = cmyk[0] / 100;\n\tconst m = cmyk[1] / 100;\n\tconst y = cmyk[2] / 100;\n\tconst k = cmyk[3] / 100;\n\n\tconst r = 1 - Math.min(1, c * (1 - k) + k);\n\tconst g = 1 - Math.min(1, m * (1 - k) + k);\n\tconst b = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tconst x = xyz[0] / 100;\n\tconst y = xyz[1] / 100;\n\tconst z = xyz[2] / 100;\n\tlet r;\n\tlet g;\n\tlet b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// Assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tlet x = xyz[0];\n\tlet y = xyz[1];\n\tlet z = xyz[2];\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);\n\n\tconst l = (116 * y) - 16;\n\tconst a = 500 * (x - y);\n\tconst b = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tconst l = lab[0];\n\tconst a = lab[1];\n\tconst b = lab[2];\n\tlet x;\n\tlet y;\n\tlet z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tconst y2 = y ** 3;\n\tconst x2 = x ** 3;\n\tconst z2 = z ** 3;\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tconst l = lab[0];\n\tconst a = lab[1];\n\tconst b = lab[2];\n\tlet h;\n\n\tconst hr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tconst c = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tconst l = lch[0];\n\tconst c = lch[1];\n\tconst h = lch[2];\n\n\tconst hr = h / 360 * 2 * Math.PI;\n\tconst a = c * Math.cos(hr);\n\tconst b = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args, saturation = null) {\n\tconst [r, g, b] = args;\n\tlet value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tlet ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// Optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tconst r = args[0];\n\tconst g = args[1];\n\tconst b = args[2];\n\n\t// We use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tconst ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tlet color = args % 10;\n\n\t// Handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tconst mult = (~~(args > 50) + 1) * 0.5;\n\tconst r = ((color & 1) * mult) * 255;\n\tconst g = (((color >> 1) & 1) * mult) * 255;\n\tconst b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// Handle greyscale\n\tif (args >= 232) {\n\t\tconst c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tlet rem;\n\tconst r = Math.floor(args / 36) / 5 * 255;\n\tconst g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tconst b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tconst integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tconst string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tconst match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tlet colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(char => {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tconst integer = parseInt(colorString, 16);\n\tconst r = (integer >> 16) & 0xFF;\n\tconst g = (integer >> 8) & 0xFF;\n\tconst b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tconst r = rgb[0] / 255;\n\tconst g = rgb[1] / 255;\n\tconst b = rgb[2] / 255;\n\tconst max = Math.max(Math.max(r, g), b);\n\tconst min = Math.min(Math.min(r, g), b);\n\tconst chroma = (max - min);\n\tlet grayscale;\n\tlet hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tconst s = hsl[1] / 100;\n\tconst l = hsl[2] / 100;\n\n\tconst c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));\n\n\tlet f = 0;\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tconst s = hsv[1] / 100;\n\tconst v = hsv[2] / 100;\n\n\tconst c = s * v;\n\tlet f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tconst h = hcg[0] / 360;\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tconst pure = [0, 0, 0];\n\tconst hi = (h % 1) * 6;\n\tconst v = hi % 1;\n\tconst w = 1 - v;\n\tlet mg = 0;\n\n\t/* eslint-disable max-statements-per-line */\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\t/* eslint-enable max-statements-per-line */\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\n\tconst v = c + g * (1.0 - c);\n\tlet f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\n\tconst l = g * (1.0 - c) + 0.5 * c;\n\tlet s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tconst c = hcg[1] / 100;\n\tconst g = hcg[2] / 100;\n\tconst v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tconst w = hwb[1] / 100;\n\tconst b = hwb[2] / 100;\n\tconst v = 1 - b;\n\tconst c = v - w;\n\tlet g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hsv = convert.gray.hsl;\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tconst val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tconst integer = (val << 16) + (val << 8) + val;\n\n\tconst string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tconst val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","const conversions = require('./conversions');\n\n/*\n\tThis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tconst graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tconst models = Object.keys(conversions);\n\n\tfor (let len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tconst graph = buildGraph();\n\tconst queue = [fromModel]; // Unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tconst current = queue.pop();\n\t\tconst adjacents = Object.keys(conversions[current]);\n\n\t\tfor (let len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tconst adjacent = adjacents[i];\n\t\t\tconst node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tconst path = [graph[toModel].parent, toModel];\n\tlet fn = conversions[graph[toModel].parent][toModel];\n\n\tlet cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tconst graph = deriveBFS(fromModel);\n\tconst conversion = {};\n\n\tconst models = Object.keys(graph);\n\tfor (let len = models.length, i = 0; i < len; i++) {\n\t\tconst toModel = models[i];\n\t\tconst node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// No possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","const conversions = require('./conversions');\nconst route = require('./route');\n\nconst convert = {};\n\nconst models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tconst wrappedFn = function (...args) {\n\t\tconst arg0 = args[0];\n\t\tif (arg0 === undefined || arg0 === null) {\n\t\t\treturn arg0;\n\t\t}\n\n\t\tif (arg0.length > 1) {\n\t\t\targs = arg0;\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// Preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tconst wrappedFn = function (...args) {\n\t\tconst arg0 = args[0];\n\n\t\tif (arg0 === undefined || arg0 === null) {\n\t\t\treturn arg0;\n\t\t}\n\n\t\tif (arg0.length > 1) {\n\t\t\targs = arg0;\n\t\t}\n\n\t\tconst result = fn(args);\n\n\t\t// We're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (let len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// Preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(fromModel => {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tconst routes = route(fromModel);\n\tconst routeModels = Object.keys(routes);\n\n\trouteModels.forEach(toModel => {\n\t\tconst fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","const colorString = require('color-string');\nconst convert = require('color-convert');\n\nconst skippedModels = [\n\t// To be honest, I don't really feel like keyword belongs in color convert, but eh.\n\t'keyword',\n\n\t// Gray conflicts with some method names, and has its own method defined.\n\t'gray',\n\n\t// Shouldn't really be in color-convert either...\n\t'hex',\n];\n\nconst hashedModelKeys = {};\nfor (const model of Object.keys(convert)) {\n\thashedModelKeys[[...convert[model].labels].sort().join('')] = model;\n}\n\nconst limiters = {};\n\nfunction Color(object, model) {\n\tif (!(this instanceof Color)) {\n\t\treturn new Color(object, model);\n\t}\n\n\tif (model && model in skippedModels) {\n\t\tmodel = null;\n\t}\n\n\tif (model && !(model in convert)) {\n\t\tthrow new Error('Unknown model: ' + model);\n\t}\n\n\tlet i;\n\tlet channels;\n\n\tif (object == null) { // eslint-disable-line no-eq-null,eqeqeq\n\t\tthis.model = 'rgb';\n\t\tthis.color = [0, 0, 0];\n\t\tthis.valpha = 1;\n\t} else if (object instanceof Color) {\n\t\tthis.model = object.model;\n\t\tthis.color = [...object.color];\n\t\tthis.valpha = object.valpha;\n\t} else if (typeof object === 'string') {\n\t\tconst result = colorString.get(object);\n\t\tif (result === null) {\n\t\t\tthrow new Error('Unable to parse color from string: ' + object);\n\t\t}\n\n\t\tthis.model = result.model;\n\t\tchannels = convert[this.model].channels;\n\t\tthis.color = result.value.slice(0, channels);\n\t\tthis.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;\n\t} else if (object.length > 0) {\n\t\tthis.model = model || 'rgb';\n\t\tchannels = convert[this.model].channels;\n\t\tconst newArray = Array.prototype.slice.call(object, 0, channels);\n\t\tthis.color = zeroArray(newArray, channels);\n\t\tthis.valpha = typeof object[channels] === 'number' ? object[channels] : 1;\n\t} else if (typeof object === 'number') {\n\t\t// This is always RGB - can be converted later on.\n\t\tthis.model = 'rgb';\n\t\tthis.color = [\n\t\t\t(object >> 16) & 0xFF,\n\t\t\t(object >> 8) & 0xFF,\n\t\t\tobject & 0xFF,\n\t\t];\n\t\tthis.valpha = 1;\n\t} else {\n\t\tthis.valpha = 1;\n\n\t\tconst keys = Object.keys(object);\n\t\tif ('alpha' in object) {\n\t\t\tkeys.splice(keys.indexOf('alpha'), 1);\n\t\t\tthis.valpha = typeof object.alpha === 'number' ? object.alpha : 0;\n\t\t}\n\n\t\tconst hashedKeys = keys.sort().join('');\n\t\tif (!(hashedKeys in hashedModelKeys)) {\n\t\t\tthrow new Error('Unable to parse color from object: ' + JSON.stringify(object));\n\t\t}\n\n\t\tthis.model = hashedModelKeys[hashedKeys];\n\n\t\tconst {labels} = convert[this.model];\n\t\tconst color = [];\n\t\tfor (i = 0; i < labels.length; i++) {\n\t\t\tcolor.push(object[labels[i]]);\n\t\t}\n\n\t\tthis.color = zeroArray(color);\n\t}\n\n\t// Perform limitations (clamping, etc.)\n\tif (limiters[this.model]) {\n\t\tchannels = convert[this.model].channels;\n\t\tfor (i = 0; i < channels; i++) {\n\t\t\tconst limit = limiters[this.model][i];\n\t\t\tif (limit) {\n\t\t\t\tthis.color[i] = limit(this.color[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\tthis.valpha = Math.max(0, Math.min(1, this.valpha));\n\n\tif (Object.freeze) {\n\t\tObject.freeze(this);\n\t}\n}\n\nColor.prototype = {\n\ttoString() {\n\t\treturn this.string();\n\t},\n\n\ttoJSON() {\n\t\treturn this[this.model]();\n\t},\n\n\tstring(places) {\n\t\tlet self = this.model in colorString.to ? this : this.rgb();\n\t\tself = self.round(typeof places === 'number' ? places : 1);\n\t\tconst args = self.valpha === 1 ? self.color : [...self.color, this.valpha];\n\t\treturn colorString.to[self.model](args);\n\t},\n\n\tpercentString(places) {\n\t\tconst self = this.rgb().round(typeof places === 'number' ? places : 1);\n\t\tconst args = self.valpha === 1 ? self.color : [...self.color, this.valpha];\n\t\treturn colorString.to.rgb.percent(args);\n\t},\n\n\tarray() {\n\t\treturn this.valpha === 1 ? [...this.color] : [...this.color, this.valpha];\n\t},\n\n\tobject() {\n\t\tconst result = {};\n\t\tconst {channels} = convert[this.model];\n\t\tconst {labels} = convert[this.model];\n\n\t\tfor (let i = 0; i < channels; i++) {\n\t\t\tresult[labels[i]] = this.color[i];\n\t\t}\n\n\t\tif (this.valpha !== 1) {\n\t\t\tresult.alpha = this.valpha;\n\t\t}\n\n\t\treturn result;\n\t},\n\n\tunitArray() {\n\t\tconst rgb = this.rgb().color;\n\t\trgb[0] /= 255;\n\t\trgb[1] /= 255;\n\t\trgb[2] /= 255;\n\n\t\tif (this.valpha !== 1) {\n\t\t\trgb.push(this.valpha);\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tunitObject() {\n\t\tconst rgb = this.rgb().object();\n\t\trgb.r /= 255;\n\t\trgb.g /= 255;\n\t\trgb.b /= 255;\n\n\t\tif (this.valpha !== 1) {\n\t\t\trgb.alpha = this.valpha;\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tround(places) {\n\t\tplaces = Math.max(places || 0, 0);\n\t\treturn new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model);\n\t},\n\n\talpha(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color([...this.color, Math.max(0, Math.min(1, value))], this.model);\n\t\t}\n\n\t\treturn this.valpha;\n\t},\n\n\t// Rgb\n\tred: getset('rgb', 0, maxfn(255)),\n\tgreen: getset('rgb', 1, maxfn(255)),\n\tblue: getset('rgb', 2, maxfn(255)),\n\n\thue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360),\n\n\tsaturationl: getset('hsl', 1, maxfn(100)),\n\tlightness: getset('hsl', 2, maxfn(100)),\n\n\tsaturationv: getset('hsv', 1, maxfn(100)),\n\tvalue: getset('hsv', 2, maxfn(100)),\n\n\tchroma: getset('hcg', 1, maxfn(100)),\n\tgray: getset('hcg', 2, maxfn(100)),\n\n\twhite: getset('hwb', 1, maxfn(100)),\n\twblack: getset('hwb', 2, maxfn(100)),\n\n\tcyan: getset('cmyk', 0, maxfn(100)),\n\tmagenta: getset('cmyk', 1, maxfn(100)),\n\tyellow: getset('cmyk', 2, maxfn(100)),\n\tblack: getset('cmyk', 3, maxfn(100)),\n\n\tx: getset('xyz', 0, maxfn(95.047)),\n\ty: getset('xyz', 1, maxfn(100)),\n\tz: getset('xyz', 2, maxfn(108.833)),\n\n\tl: getset('lab', 0, maxfn(100)),\n\ta: getset('lab', 1),\n\tb: getset('lab', 2),\n\n\tkeyword(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color(value);\n\t\t}\n\n\t\treturn convert[this.model].keyword(this.color);\n\t},\n\n\thex(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color(value);\n\t\t}\n\n\t\treturn colorString.to.hex(this.rgb().round().color);\n\t},\n\n\thexa(value) {\n\t\tif (value !== undefined) {\n\t\t\treturn new Color(value);\n\t\t}\n\n\t\tconst rgbArray = this.rgb().round().color;\n\n\t\tlet alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();\n\t\tif (alphaHex.length === 1) {\n\t\t\talphaHex = '0' + alphaHex;\n\t\t}\n\n\t\treturn colorString.to.hex(rgbArray) + alphaHex;\n\t},\n\n\trgbNumber() {\n\t\tconst rgb = this.rgb().color;\n\t\treturn ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);\n\t},\n\n\tluminosity() {\n\t\t// http://www.w3.org/TR/WCAG20/#relativeluminancedef\n\t\tconst rgb = this.rgb().color;\n\n\t\tconst lum = [];\n\t\tfor (const [i, element] of rgb.entries()) {\n\t\t\tconst chan = element / 255;\n\t\t\tlum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;\n\t\t}\n\n\t\treturn 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];\n\t},\n\n\tcontrast(color2) {\n\t\t// http://www.w3.org/TR/WCAG20/#contrast-ratiodef\n\t\tconst lum1 = this.luminosity();\n\t\tconst lum2 = color2.luminosity();\n\n\t\tif (lum1 > lum2) {\n\t\t\treturn (lum1 + 0.05) / (lum2 + 0.05);\n\t\t}\n\n\t\treturn (lum2 + 0.05) / (lum1 + 0.05);\n\t},\n\n\tlevel(color2) {\n\t\t// https://www.w3.org/TR/WCAG/#contrast-enhanced\n\t\tconst contrastRatio = this.contrast(color2);\n\t\tif (contrastRatio >= 7) {\n\t\t\treturn 'AAA';\n\t\t}\n\n\t\treturn (contrastRatio >= 4.5) ? 'AA' : '';\n\t},\n\n\tisDark() {\n\t\t// YIQ equation from http://24ways.org/2010/calculating-color-contrast\n\t\tconst rgb = this.rgb().color;\n\t\tconst yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000;\n\t\treturn yiq < 128;\n\t},\n\n\tisLight() {\n\t\treturn !this.isDark();\n\t},\n\n\tnegate() {\n\t\tconst rgb = this.rgb();\n\t\tfor (let i = 0; i < 3; i++) {\n\t\t\trgb.color[i] = 255 - rgb.color[i];\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tlighten(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[2] += hsl.color[2] * ratio;\n\t\treturn hsl;\n\t},\n\n\tdarken(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[2] -= hsl.color[2] * ratio;\n\t\treturn hsl;\n\t},\n\n\tsaturate(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[1] += hsl.color[1] * ratio;\n\t\treturn hsl;\n\t},\n\n\tdesaturate(ratio) {\n\t\tconst hsl = this.hsl();\n\t\thsl.color[1] -= hsl.color[1] * ratio;\n\t\treturn hsl;\n\t},\n\n\twhiten(ratio) {\n\t\tconst hwb = this.hwb();\n\t\thwb.color[1] += hwb.color[1] * ratio;\n\t\treturn hwb;\n\t},\n\n\tblacken(ratio) {\n\t\tconst hwb = this.hwb();\n\t\thwb.color[2] += hwb.color[2] * ratio;\n\t\treturn hwb;\n\t},\n\n\tgrayscale() {\n\t\t// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale\n\t\tconst rgb = this.rgb().color;\n\t\tconst value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;\n\t\treturn Color.rgb(value, value, value);\n\t},\n\n\tfade(ratio) {\n\t\treturn this.alpha(this.valpha - (this.valpha * ratio));\n\t},\n\n\topaquer(ratio) {\n\t\treturn this.alpha(this.valpha + (this.valpha * ratio));\n\t},\n\n\trotate(degrees) {\n\t\tconst hsl = this.hsl();\n\t\tlet hue = hsl.color[0];\n\t\thue = (hue + degrees) % 360;\n\t\thue = hue < 0 ? 360 + hue : hue;\n\t\thsl.color[0] = hue;\n\t\treturn hsl;\n\t},\n\n\tmix(mixinColor, weight) {\n\t\t// Ported from sass implementation in C\n\t\t// https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209\n\t\tif (!mixinColor || !mixinColor.rgb) {\n\t\t\tthrow new Error('Argument to \"mix\" was not a Color instance, but rather an instance of ' + typeof mixinColor);\n\t\t}\n\n\t\tconst color1 = mixinColor.rgb();\n\t\tconst color2 = this.rgb();\n\t\tconst p = weight === undefined ? 0.5 : weight;\n\n\t\tconst w = 2 * p - 1;\n\t\tconst a = color1.alpha() - color2.alpha();\n\n\t\tconst w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2;\n\t\tconst w2 = 1 - w1;\n\n\t\treturn Color.rgb(\n\t\t\tw1 * color1.red() + w2 * color2.red(),\n\t\t\tw1 * color1.green() + w2 * color2.green(),\n\t\t\tw1 * color1.blue() + w2 * color2.blue(),\n\t\t\tcolor1.alpha() * p + color2.alpha() * (1 - p));\n\t},\n};\n\n// Model conversion methods and static constructors\nfor (const model of Object.keys(convert)) {\n\tif (skippedModels.includes(model)) {\n\t\tcontinue;\n\t}\n\n\tconst {channels} = convert[model];\n\n\t// Conversion methods\n\tColor.prototype[model] = function (...args) {\n\t\tif (this.model === model) {\n\t\t\treturn new Color(this);\n\t\t}\n\n\t\tif (args.length > 0) {\n\t\t\treturn new Color(args, model);\n\t\t}\n\n\t\treturn new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model);\n\t};\n\n\t// 'static' construction methods\n\tColor[model] = function (...args) {\n\t\tlet color = args[0];\n\t\tif (typeof color === 'number') {\n\t\t\tcolor = zeroArray(args, channels);\n\t\t}\n\n\t\treturn new Color(color, model);\n\t};\n}\n\nfunction roundTo(number, places) {\n\treturn Number(number.toFixed(places));\n}\n\nfunction roundToPlace(places) {\n\treturn function (number) {\n\t\treturn roundTo(number, places);\n\t};\n}\n\nfunction getset(model, channel, modifier) {\n\tmodel = Array.isArray(model) ? model : [model];\n\n\tfor (const m of model) {\n\t\t(limiters[m] || (limiters[m] = []))[channel] = modifier;\n\t}\n\n\tmodel = model[0];\n\n\treturn function (value) {\n\t\tlet result;\n\n\t\tif (value !== undefined) {\n\t\t\tif (modifier) {\n\t\t\t\tvalue = modifier(value);\n\t\t\t}\n\n\t\t\tresult = this[model]();\n\t\t\tresult.color[channel] = value;\n\t\t\treturn result;\n\t\t}\n\n\t\tresult = this[model]().color[channel];\n\t\tif (modifier) {\n\t\t\tresult = modifier(result);\n\t\t}\n\n\t\treturn result;\n\t};\n}\n\nfunction maxfn(max) {\n\treturn function (v) {\n\t\treturn Math.max(0, Math.min(max, v));\n\t};\n}\n\nfunction assertArray(value) {\n\treturn Array.isArray(value) ? value : [value];\n}\n\nfunction zeroArray(array, length) {\n\tfor (let i = 0; i < length; i++) {\n\t\tif (typeof array[i] !== 'number') {\n\t\t\tarray[i] = 0;\n\t\t}\n\t}\n\n\treturn array;\n}\n\nmodule.exports = Color;\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst color = require('color');\nconst is = require('./is');\nconst sharp = require('./sharp');\n\n/**\n * Justication alignment\n * @member\n * @private\n */\nconst align = {\n left: 'low',\n center: 'centre',\n centre: 'centre',\n right: 'high'\n};\n\n/**\n * Extract input options, if any, from an object.\n * @private\n */\nfunction _inputOptionsFromObject (obj) {\n const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj;\n return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined)\n ? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd }\n : undefined;\n}\n\n/**\n * Create Object containing input and input-related options.\n * @private\n */\nfunction _createInputDescriptor (input, inputOptions, containerOptions) {\n const inputDescriptor = {\n failOn: 'warning',\n limitInputPixels: Math.pow(0x3FFF, 2),\n ignoreIcc: false,\n unlimited: false,\n sequentialRead: true\n };\n if (is.string(input)) {\n // filesystem\n inputDescriptor.file = input;\n } else if (is.buffer(input)) {\n // Buffer\n if (input.length === 0) {\n throw Error('Input Buffer is empty');\n }\n inputDescriptor.buffer = input;\n } else if (is.arrayBuffer(input)) {\n if (input.byteLength === 0) {\n throw Error('Input bit Array is empty');\n }\n inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength);\n } else if (is.typedArray(input)) {\n if (input.length === 0) {\n throw Error('Input Bit Array is empty');\n }\n inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);\n } else if (is.plainObject(input) && !is.defined(inputOptions)) {\n // Plain Object descriptor, e.g. create\n inputOptions = input;\n if (_inputOptionsFromObject(inputOptions)) {\n // Stream with options\n inputDescriptor.buffer = [];\n }\n } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) {\n // Stream without options\n inputDescriptor.buffer = [];\n } else {\n throw new Error(`Unsupported input '${input}' of type ${typeof input}${\n is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : ''\n }`);\n }\n if (is.object(inputOptions)) {\n // Deprecated: failOnError\n if (is.defined(inputOptions.failOnError)) {\n if (is.bool(inputOptions.failOnError)) {\n inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none';\n } else {\n throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError);\n }\n }\n // failOn\n if (is.defined(inputOptions.failOn)) {\n if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) {\n inputDescriptor.failOn = inputOptions.failOn;\n } else {\n throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn);\n }\n }\n // Density\n if (is.defined(inputOptions.density)) {\n if (is.inRange(inputOptions.density, 1, 100000)) {\n inputDescriptor.density = inputOptions.density;\n } else {\n throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density);\n }\n }\n // Ignore embeddded ICC profile\n if (is.defined(inputOptions.ignoreIcc)) {\n if (is.bool(inputOptions.ignoreIcc)) {\n inputDescriptor.ignoreIcc = inputOptions.ignoreIcc;\n } else {\n throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc);\n }\n }\n // limitInputPixels\n if (is.defined(inputOptions.limitInputPixels)) {\n if (is.bool(inputOptions.limitInputPixels)) {\n inputDescriptor.limitInputPixels = inputOptions.limitInputPixels\n ? Math.pow(0x3FFF, 2)\n : 0;\n } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) {\n inputDescriptor.limitInputPixels = inputOptions.limitInputPixels;\n } else {\n throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels);\n }\n }\n // unlimited\n if (is.defined(inputOptions.unlimited)) {\n if (is.bool(inputOptions.unlimited)) {\n inputDescriptor.unlimited = inputOptions.unlimited;\n } else {\n throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited);\n }\n }\n // sequentialRead\n if (is.defined(inputOptions.sequentialRead)) {\n if (is.bool(inputOptions.sequentialRead)) {\n inputDescriptor.sequentialRead = inputOptions.sequentialRead;\n } else {\n throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead);\n }\n }\n // Raw pixel input\n if (is.defined(inputOptions.raw)) {\n if (\n is.object(inputOptions.raw) &&\n is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 &&\n is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 &&\n is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4)\n ) {\n inputDescriptor.rawWidth = inputOptions.raw.width;\n inputDescriptor.rawHeight = inputOptions.raw.height;\n inputDescriptor.rawChannels = inputOptions.raw.channels;\n inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied;\n\n switch (input.constructor) {\n case Uint8Array:\n case Uint8ClampedArray:\n inputDescriptor.rawDepth = 'uchar';\n break;\n case Int8Array:\n inputDescriptor.rawDepth = 'char';\n break;\n case Uint16Array:\n inputDescriptor.rawDepth = 'ushort';\n break;\n case Int16Array:\n inputDescriptor.rawDepth = 'short';\n break;\n case Uint32Array:\n inputDescriptor.rawDepth = 'uint';\n break;\n case Int32Array:\n inputDescriptor.rawDepth = 'int';\n break;\n case Float32Array:\n inputDescriptor.rawDepth = 'float';\n break;\n case Float64Array:\n inputDescriptor.rawDepth = 'double';\n break;\n default:\n inputDescriptor.rawDepth = 'uchar';\n break;\n }\n } else {\n throw new Error('Expected width, height and channels for raw pixel input');\n }\n }\n // Multi-page input (GIF, TIFF, PDF)\n if (is.defined(inputOptions.animated)) {\n if (is.bool(inputOptions.animated)) {\n inputDescriptor.pages = inputOptions.animated ? -1 : 1;\n } else {\n throw is.invalidParameterError('animated', 'boolean', inputOptions.animated);\n }\n }\n if (is.defined(inputOptions.pages)) {\n if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) {\n inputDescriptor.pages = inputOptions.pages;\n } else {\n throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages);\n }\n }\n if (is.defined(inputOptions.page)) {\n if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) {\n inputDescriptor.page = inputOptions.page;\n } else {\n throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page);\n }\n }\n // Multi-level input (OpenSlide)\n if (is.defined(inputOptions.level)) {\n if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) {\n inputDescriptor.level = inputOptions.level;\n } else {\n throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level);\n }\n }\n // Sub Image File Directory (TIFF)\n if (is.defined(inputOptions.subifd)) {\n if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) {\n inputDescriptor.subifd = inputOptions.subifd;\n } else {\n throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd);\n }\n }\n // Create new image\n if (is.defined(inputOptions.create)) {\n if (\n is.object(inputOptions.create) &&\n is.integer(inputOptions.create.width) && inputOptions.create.width > 0 &&\n is.integer(inputOptions.create.height) && inputOptions.create.height > 0 &&\n is.integer(inputOptions.create.channels)\n ) {\n inputDescriptor.createWidth = inputOptions.create.width;\n inputDescriptor.createHeight = inputOptions.create.height;\n inputDescriptor.createChannels = inputOptions.create.channels;\n // Noise\n if (is.defined(inputOptions.create.noise)) {\n if (!is.object(inputOptions.create.noise)) {\n throw new Error('Expected noise to be an object');\n }\n if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) {\n throw new Error('Only gaussian noise is supported at the moment');\n }\n if (!is.inRange(inputOptions.create.channels, 1, 4)) {\n throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels);\n }\n inputDescriptor.createNoiseType = inputOptions.create.noise.type;\n if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) {\n inputDescriptor.createNoiseMean = inputOptions.create.noise.mean;\n } else {\n throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean);\n }\n if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) {\n inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma;\n } else {\n throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma);\n }\n } else if (is.defined(inputOptions.create.background)) {\n if (!is.inRange(inputOptions.create.channels, 3, 4)) {\n throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels);\n }\n const background = color(inputOptions.create.background);\n inputDescriptor.createBackground = [\n background.red(),\n background.green(),\n background.blue(),\n Math.round(background.alpha() * 255)\n ];\n } else {\n throw new Error('Expected valid noise or background to create a new input image');\n }\n delete inputDescriptor.buffer;\n } else {\n throw new Error('Expected valid width, height and channels to create a new input image');\n }\n }\n // Create a new image with text\n if (is.defined(inputOptions.text)) {\n if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) {\n inputDescriptor.textValue = inputOptions.text.text;\n if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) {\n throw new Error('Expected only one of dpi or height');\n }\n if (is.defined(inputOptions.text.font)) {\n if (is.string(inputOptions.text.font)) {\n inputDescriptor.textFont = inputOptions.text.font;\n } else {\n throw is.invalidParameterError('text.font', 'string', inputOptions.text.font);\n }\n }\n if (is.defined(inputOptions.text.fontfile)) {\n if (is.string(inputOptions.text.fontfile)) {\n inputDescriptor.textFontfile = inputOptions.text.fontfile;\n } else {\n throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile);\n }\n }\n if (is.defined(inputOptions.text.width)) {\n if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) {\n inputDescriptor.textWidth = inputOptions.text.width;\n } else {\n throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width);\n }\n }\n if (is.defined(inputOptions.text.height)) {\n if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) {\n inputDescriptor.textHeight = inputOptions.text.height;\n } else {\n throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height);\n }\n }\n if (is.defined(inputOptions.text.align)) {\n if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) {\n inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align];\n } else {\n throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align);\n }\n }\n if (is.defined(inputOptions.text.justify)) {\n if (is.bool(inputOptions.text.justify)) {\n inputDescriptor.textJustify = inputOptions.text.justify;\n } else {\n throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify);\n }\n }\n if (is.defined(inputOptions.text.dpi)) {\n if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) {\n inputDescriptor.textDpi = inputOptions.text.dpi;\n } else {\n throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi);\n }\n }\n if (is.defined(inputOptions.text.rgba)) {\n if (is.bool(inputOptions.text.rgba)) {\n inputDescriptor.textRgba = inputOptions.text.rgba;\n } else {\n throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba);\n }\n }\n if (is.defined(inputOptions.text.spacing)) {\n if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) {\n inputDescriptor.textSpacing = inputOptions.text.spacing;\n } else {\n throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing);\n }\n }\n if (is.defined(inputOptions.text.wrap)) {\n if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) {\n inputDescriptor.textWrap = inputOptions.text.wrap;\n } else {\n throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap);\n }\n }\n delete inputDescriptor.buffer;\n } else {\n throw new Error('Expected a valid string to create an image with text.');\n }\n }\n } else if (is.defined(inputOptions)) {\n throw new Error('Invalid input options ' + inputOptions);\n }\n return inputDescriptor;\n}\n\n/**\n * Handle incoming Buffer chunk on Writable Stream.\n * @private\n * @param {Buffer} chunk\n * @param {string} encoding - unused\n * @param {Function} callback\n */\nfunction _write (chunk, encoding, callback) {\n /* istanbul ignore else */\n if (Array.isArray(this.options.input.buffer)) {\n /* istanbul ignore else */\n if (is.buffer(chunk)) {\n if (this.options.input.buffer.length === 0) {\n this.on('finish', () => {\n this.streamInFinished = true;\n });\n }\n this.options.input.buffer.push(chunk);\n callback();\n } else {\n callback(new Error('Non-Buffer data on Writable Stream'));\n }\n } else {\n callback(new Error('Unexpected data on Writable Stream'));\n }\n}\n\n/**\n * Flattens the array of chunks accumulated in input.buffer.\n * @private\n */\nfunction _flattenBufferIn () {\n if (this._isStreamInput()) {\n this.options.input.buffer = Buffer.concat(this.options.input.buffer);\n }\n}\n\n/**\n * Are we expecting Stream-based input?\n * @private\n * @returns {boolean}\n */\nfunction _isStreamInput () {\n return Array.isArray(this.options.input.buffer);\n}\n\n/**\n * Fast access to (uncached) image metadata without decoding any compressed pixel data.\n *\n * This is read from the header of the input image.\n * It does not take into consideration any operations to be applied to the output image,\n * such as resize or rotate.\n *\n * Dimensions in the response will respect the `page` and `pages` properties of the\n * {@link /api-constructor#parameters|constructor parameters}.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg`\n * - `size`: Total size of image in bytes, for Stream and Buffer input only\n * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below)\n * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below)\n * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation)\n * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK\n * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat)\n * - `density`: Number of pixels per inch (DPI), if present\n * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK\n * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan\n * - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP\n * - `pageHeight`: Number of pixels high each page in a multi-page image will be.\n * - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG).\n * - `loop`: Number of times to loop an animated image, zero refers to a continuous loop.\n * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers.\n * - `pagePrimary`: Number of the primary page in a HEIF image\n * - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide\n * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image\n * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value\n * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC)\n * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present\n * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile\n * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel\n * - `orientation`: Number value of the EXIF Orientation header, if present\n * - `exif`: Buffer containing raw EXIF data, if present\n * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present\n * - `iptc`: Buffer containing raw IPTC data, if present\n * - `xmp`: Buffer containing raw XMP data, if present\n * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present\n * - `formatMagick`: String containing format for images loaded via *magick\n * - `comments`: Array of keyword/text pairs representing PNG text blocks, if present.\n *\n * @example\n * const metadata = await sharp(input).metadata();\n *\n * @example\n * const image = sharp(inputJpg);\n * image\n * .metadata()\n * .then(function(metadata) {\n * return image\n * .resize(Math.round(metadata.width / 2))\n * .webp()\n * .toBuffer();\n * })\n * .then(function(data) {\n * // data contains a WebP image half the width and height of the original JPEG\n * });\n *\n * @example\n * // Based on EXIF rotation metadata, get the right-side-up width and height:\n *\n * const size = getNormalSize(await sharp(input).metadata());\n *\n * function getNormalSize({ width, height, orientation }) {\n * return (orientation || 0) >= 5\n * ? { width: height, height: width }\n * : { width, height };\n * }\n *\n * @param {Function} [callback] - called with the arguments `(err, metadata)`\n * @returns {Promise<Object>|Sharp}\n */\nfunction metadata (callback) {\n const stack = Error();\n if (is.fn(callback)) {\n if (this._isStreamInput()) {\n this.on('finish', () => {\n this._flattenBufferIn();\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, metadata);\n }\n });\n });\n } else {\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, metadata);\n }\n });\n }\n return this;\n } else {\n if (this._isStreamInput()) {\n return new Promise((resolve, reject) => {\n const finished = () => {\n this._flattenBufferIn();\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(metadata);\n }\n });\n };\n if (this.writableFinished) {\n finished();\n } else {\n this.once('finish', finished);\n }\n });\n } else {\n return new Promise((resolve, reject) => {\n sharp.metadata(this.options, (err, metadata) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(metadata);\n }\n });\n });\n }\n }\n}\n\n/**\n * Access to pixel-derived image statistics for every channel in the image.\n * A `Promise` is returned when `callback` is not provided.\n *\n * - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains\n * - `min` (minimum value in the channel)\n * - `max` (maximum value in the channel)\n * - `sum` (sum of all values in a channel)\n * - `squaresSum` (sum of squared values in a channel)\n * - `mean` (mean of the values in a channel)\n * - `stdev` (standard deviation for the values in a channel)\n * - `minX` (x-coordinate of one of the pixel where the minimum lies)\n * - `minY` (y-coordinate of one of the pixel where the minimum lies)\n * - `maxX` (x-coordinate of one of the pixel where the maximum lies)\n * - `maxY` (y-coordinate of one of the pixel where the maximum lies)\n * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque.\n * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any.\n * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any.\n * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram.\n *\n * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be\n * written to a buffer in order to run `stats` on the result (see third example).\n *\n * @example\n * const image = sharp(inputJpg);\n * image\n * .stats()\n * .then(function(stats) {\n * // stats contains the channel-wise statistics array and the isOpaque value\n * });\n *\n * @example\n * const { entropy, sharpness, dominant } = await sharp(input).stats();\n * const { r, g, b } = dominant;\n *\n * @example\n * const image = sharp(input);\n * // store intermediate result\n * const part = await image.extract(region).toBuffer();\n * // create new instance to obtain statistics of extracted region\n * const stats = await sharp(part).stats();\n *\n * @param {Function} [callback] - called with the arguments `(err, stats)`\n * @returns {Promise<Object>}\n */\nfunction stats (callback) {\n const stack = Error();\n if (is.fn(callback)) {\n if (this._isStreamInput()) {\n this.on('finish', () => {\n this._flattenBufferIn();\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, stats);\n }\n });\n });\n } else {\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, stats);\n }\n });\n }\n return this;\n } else {\n if (this._isStreamInput()) {\n return new Promise((resolve, reject) => {\n this.on('finish', function () {\n this._flattenBufferIn();\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(stats);\n }\n });\n });\n });\n } else {\n return new Promise((resolve, reject) => {\n sharp.stats(this.options, (err, stats) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n resolve(stats);\n }\n });\n });\n }\n }\n}\n\n/**\n * Decorate the Sharp prototype with input-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Private\n _inputOptionsFromObject,\n _createInputDescriptor,\n _write,\n _flattenBufferIn,\n _isStreamInput,\n // Public\n metadata,\n stats\n });\n // Class attributes\n Sharp.align = align;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst is = require('./is');\n\n/**\n * Weighting to apply when using contain/cover fit.\n * @member\n * @private\n */\nconst gravity = {\n center: 0,\n centre: 0,\n north: 1,\n east: 2,\n south: 3,\n west: 4,\n northeast: 5,\n southeast: 6,\n southwest: 7,\n northwest: 8\n};\n\n/**\n * Position to apply when using contain/cover fit.\n * @member\n * @private\n */\nconst position = {\n top: 1,\n right: 2,\n bottom: 3,\n left: 4,\n 'right top': 5,\n 'right bottom': 6,\n 'left bottom': 7,\n 'left top': 8\n};\n\n/**\n * How to extend the image.\n * @member\n * @private\n */\nconst extendWith = {\n background: 'background',\n copy: 'copy',\n repeat: 'repeat',\n mirror: 'mirror'\n};\n\n/**\n * Strategies for automagic cover behaviour.\n * @member\n * @private\n */\nconst strategy = {\n entropy: 16,\n attention: 17\n};\n\n/**\n * Reduction kernels.\n * @member\n * @private\n */\nconst kernel = {\n nearest: 'nearest',\n linear: 'linear',\n cubic: 'cubic',\n mitchell: 'mitchell',\n lanczos2: 'lanczos2',\n lanczos3: 'lanczos3'\n};\n\n/**\n * Methods by which an image can be resized to fit the provided dimensions.\n * @member\n * @private\n */\nconst fit = {\n contain: 'contain',\n cover: 'cover',\n fill: 'fill',\n inside: 'inside',\n outside: 'outside'\n};\n\n/**\n * Map external fit property to internal canvas property.\n * @member\n * @private\n */\nconst mapFitToCanvas = {\n contain: 'embed',\n cover: 'crop',\n fill: 'ignore_aspect',\n inside: 'max',\n outside: 'min'\n};\n\n/**\n * @private\n */\nfunction isRotationExpected (options) {\n return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0;\n}\n\n/**\n * @private\n */\nfunction isResizeExpected (options) {\n return options.width !== -1 || options.height !== -1;\n}\n\n/**\n * Resize image to `width`, `height` or `width x height`.\n *\n * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are:\n * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit.\n * - `contain`: Preserving aspect ratio, contain within both provided dimensions using \"letterboxing\" where necessary.\n * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions.\n * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.\n * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.\n *\n * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property.\n *\n * <img alt=\"Examples of various values for the fit property when resizing\" width=\"100%\" style=\"aspect-ratio: 998/243\" src=\"https://cdn.jsdelivr.net/gh/lovell/sharp@main/docs/image/api-resize-fit.svg\">\n *\n * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are:\n * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`.\n * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`.\n * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy.\n *\n * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property.\n *\n * The strategy-based approach initially resizes so one dimension is at its target length\n * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy.\n * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29).\n * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.\n *\n * Possible downsizing kernels are:\n * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation).\n * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function).\n * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).\n * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf).\n * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`.\n * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default).\n *\n * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators.\n * Downsampling kernels without a matching upsampling interpolator map to `cubic`.\n *\n * Only one resize can occur per pipeline.\n * Previous calls to `resize` in the same pipeline will be ignored.\n *\n * @example\n * sharp(input)\n * .resize({ width: 100 })\n * .toBuffer()\n * .then(data => {\n * // 100 pixels wide, auto-scaled height\n * });\n *\n * @example\n * sharp(input)\n * .resize({ height: 100 })\n * .toBuffer()\n * .then(data => {\n * // 100 pixels high, auto-scaled width\n * });\n *\n * @example\n * sharp(input)\n * .resize(200, 300, {\n * kernel: sharp.kernel.nearest,\n * fit: 'contain',\n * position: 'right top',\n * background: { r: 255, g: 255, b: 255, alpha: 0.5 }\n * })\n * .toFile('output.png')\n * .then(() => {\n * // output.png is a 200 pixels wide and 300 pixels high image\n * // containing a nearest-neighbour scaled version\n * // contained within the north-east corner of a semi-transparent white canvas\n * });\n *\n * @example\n * const transformer = sharp()\n * .resize({\n * width: 200,\n * height: 200,\n * fit: sharp.fit.cover,\n * position: sharp.strategy.entropy\n * });\n * // Read image data from readableStream\n * // Write 200px square auto-cropped image data to writableStream\n * readableStream\n * .pipe(transformer)\n * .pipe(writableStream);\n *\n * @example\n * sharp(input)\n * .resize(200, 200, {\n * fit: sharp.fit.inside,\n * withoutEnlargement: true\n * })\n * .toFormat('jpeg')\n * .toBuffer()\n * .then(function(outputBuffer) {\n * // outputBuffer contains JPEG image data\n * // no wider and no higher than 200 pixels\n * // and no larger than the input image\n * });\n *\n * @example\n * sharp(input)\n * .resize(200, 200, {\n * fit: sharp.fit.outside,\n * withoutReduction: true\n * })\n * .toFormat('jpeg')\n * .toBuffer()\n * .then(function(outputBuffer) {\n * // outputBuffer contains JPEG image data\n * // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio\n * // and no smaller than the input image\n * });\n *\n * @example\n * const scaleByHalf = await sharp(input)\n * .metadata()\n * .then(({ width }) => sharp(input)\n * .resize(Math.round(width * 0.5))\n * .toBuffer()\n * );\n *\n * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height.\n * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width.\n * @param {Object} [options]\n * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority.\n * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority.\n * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`.\n * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`.\n * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.\n * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load.\n * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions.\n * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions.\n * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction resize (widthOrOptions, height, options) {\n if (isResizeExpected(this.options)) {\n this.options.debuglog('ignoring previous resize options');\n }\n if (this.options.widthPost !== -1) {\n this.options.debuglog('operation order will be: extract, resize, extract');\n }\n if (is.defined(widthOrOptions)) {\n if (is.object(widthOrOptions) && !is.defined(options)) {\n options = widthOrOptions;\n } else if (is.integer(widthOrOptions) && widthOrOptions > 0) {\n this.options.width = widthOrOptions;\n } else {\n throw is.invalidParameterError('width', 'positive integer', widthOrOptions);\n }\n } else {\n this.options.width = -1;\n }\n if (is.defined(height)) {\n if (is.integer(height) && height > 0) {\n this.options.height = height;\n } else {\n throw is.invalidParameterError('height', 'positive integer', height);\n }\n } else {\n this.options.height = -1;\n }\n if (is.object(options)) {\n // Width\n if (is.defined(options.width)) {\n if (is.integer(options.width) && options.width > 0) {\n this.options.width = options.width;\n } else {\n throw is.invalidParameterError('width', 'positive integer', options.width);\n }\n }\n // Height\n if (is.defined(options.height)) {\n if (is.integer(options.height) && options.height > 0) {\n this.options.height = options.height;\n } else {\n throw is.invalidParameterError('height', 'positive integer', options.height);\n }\n }\n // Fit\n if (is.defined(options.fit)) {\n const canvas = mapFitToCanvas[options.fit];\n if (is.string(canvas)) {\n this.options.canvas = canvas;\n } else {\n throw is.invalidParameterError('fit', 'valid fit', options.fit);\n }\n }\n // Position\n if (is.defined(options.position)) {\n const pos = is.integer(options.position)\n ? options.position\n : strategy[options.position] || position[options.position] || gravity[options.position];\n if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) {\n this.options.position = pos;\n } else {\n throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position);\n }\n }\n // Background\n this._setBackgroundColourOption('resizeBackground', options.background);\n // Kernel\n if (is.defined(options.kernel)) {\n if (is.string(kernel[options.kernel])) {\n this.options.kernel = kernel[options.kernel];\n } else {\n throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel);\n }\n }\n // Without enlargement\n if (is.defined(options.withoutEnlargement)) {\n this._setBooleanOption('withoutEnlargement', options.withoutEnlargement);\n }\n // Without reduction\n if (is.defined(options.withoutReduction)) {\n this._setBooleanOption('withoutReduction', options.withoutReduction);\n }\n // Shrink on load\n if (is.defined(options.fastShrinkOnLoad)) {\n this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad);\n }\n }\n if (isRotationExpected(this.options) && isResizeExpected(this.options)) {\n this.options.rotateBeforePreExtract = true;\n }\n return this;\n}\n\n/**\n * Extend / pad / extrude one or more edges of the image with either\n * the provided background colour or pixels derived from the image.\n * This operation will always occur after resizing and extraction, if any.\n *\n * @example\n * // Resize to 140 pixels wide, then add 10 transparent pixels\n * // to the top, left and right edges and 20 to the bottom edge\n * sharp(input)\n * .resize(140)\n * .extend({\n * top: 10,\n * bottom: 20,\n * left: 10,\n * right: 10,\n * background: { r: 0, g: 0, b: 0, alpha: 0 }\n * })\n * ...\n *\n* @example\n * // Add a row of 10 red pixels to the bottom\n * sharp(input)\n * .extend({\n * bottom: 10,\n * background: 'red'\n * })\n * ...\n *\n * @example\n * // Extrude image by 8 pixels to the right, mirroring existing right hand edge\n * sharp(input)\n * .extend({\n * right: 8,\n * background: 'mirror'\n * })\n * ...\n *\n * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts\n * @param {number} [extend.top=0]\n * @param {number} [extend.left=0]\n * @param {number} [extend.bottom=0]\n * @param {number} [extend.right=0]\n * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror.\n * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n*/\nfunction extend (extend) {\n if (is.integer(extend) && extend > 0) {\n this.options.extendTop = extend;\n this.options.extendBottom = extend;\n this.options.extendLeft = extend;\n this.options.extendRight = extend;\n } else if (is.object(extend)) {\n if (is.defined(extend.top)) {\n if (is.integer(extend.top) && extend.top >= 0) {\n this.options.extendTop = extend.top;\n } else {\n throw is.invalidParameterError('top', 'positive integer', extend.top);\n }\n }\n if (is.defined(extend.bottom)) {\n if (is.integer(extend.bottom) && extend.bottom >= 0) {\n this.options.extendBottom = extend.bottom;\n } else {\n throw is.invalidParameterError('bottom', 'positive integer', extend.bottom);\n }\n }\n if (is.defined(extend.left)) {\n if (is.integer(extend.left) && extend.left >= 0) {\n this.options.extendLeft = extend.left;\n } else {\n throw is.invalidParameterError('left', 'positive integer', extend.left);\n }\n }\n if (is.defined(extend.right)) {\n if (is.integer(extend.right) && extend.right >= 0) {\n this.options.extendRight = extend.right;\n } else {\n throw is.invalidParameterError('right', 'positive integer', extend.right);\n }\n }\n this._setBackgroundColourOption('extendBackground', extend.background);\n if (is.defined(extend.extendWith)) {\n if (is.string(extendWith[extend.extendWith])) {\n this.options.extendWith = extendWith[extend.extendWith];\n } else {\n throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith);\n }\n }\n } else {\n throw is.invalidParameterError('extend', 'integer or object', extend);\n }\n return this;\n}\n\n/**\n * Extract/crop a region of the image.\n *\n * - Use `extract` before `resize` for pre-resize extraction.\n * - Use `extract` after `resize` for post-resize extraction.\n * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order.\n *\n * @example\n * sharp(input)\n * .extract({ left: left, top: top, width: width, height: height })\n * .toFile(output, function(err) {\n * // Extract a region of the input image, saving in the same format.\n * });\n * @example\n * sharp(input)\n * .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre })\n * .resize(width, height)\n * .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost })\n * .toFile(output, function(err) {\n * // Extract a region, resize, then extract from the resized image\n * });\n *\n * @param {Object} options - describes the region to extract using integral pixel values\n * @param {number} options.left - zero-indexed offset from left edge\n * @param {number} options.top - zero-indexed offset from top edge\n * @param {number} options.width - width of region to extract\n * @param {number} options.height - height of region to extract\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction extract (options) {\n const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre';\n if (this.options[`width${suffix}`] !== -1) {\n this.options.debuglog('ignoring previous extract options');\n }\n ['left', 'top', 'width', 'height'].forEach(function (name) {\n const value = options[name];\n if (is.integer(value) && value >= 0) {\n this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value;\n } else {\n throw is.invalidParameterError(name, 'integer', value);\n }\n }, this);\n // Ensure existing rotation occurs before pre-resize extraction\n if (isRotationExpected(this.options) && !isResizeExpected(this.options)) {\n if (this.options.widthPre === -1 || this.options.widthPost === -1) {\n this.options.rotateBeforePreExtract = true;\n }\n }\n return this;\n}\n\n/**\n * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel.\n *\n * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels.\n *\n * If the result of this operation would trim an image to nothing then no change is made.\n *\n * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties.\n *\n * @example\n * // Trim pixels with a colour similar to that of the top-left pixel.\n * await sharp(input)\n * .trim()\n * .toFile(output);\n *\n * @example\n * // Trim pixels with the exact same colour as that of the top-left pixel.\n * await sharp(input)\n * .trim({\n * threshold: 0\n * })\n * .toFile(output);\n *\n * @example\n * // Assume input is line art and trim only pixels with a similar colour to red.\n * const output = await sharp(input)\n * .trim({\n * background: \"#FF0000\",\n * lineArt: true\n * })\n * .toBuffer();\n *\n * @example\n * // Trim all \"yellow-ish\" pixels, being more lenient with the higher threshold.\n * const output = await sharp(input)\n * .trim({\n * background: \"yellow\",\n * threshold: 42,\n * })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel.\n * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number.\n * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic?\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction trim (options) {\n this.options.trimThreshold = 10;\n if (is.defined(options)) {\n if (is.object(options)) {\n if (is.defined(options.background)) {\n this._setBackgroundColourOption('trimBackground', options.background);\n }\n if (is.defined(options.threshold)) {\n if (is.number(options.threshold) && options.threshold >= 0) {\n this.options.trimThreshold = options.threshold;\n } else {\n throw is.invalidParameterError('threshold', 'positive number', options.threshold);\n }\n }\n if (is.defined(options.lineArt)) {\n this._setBooleanOption('trimLineArt', options.lineArt);\n }\n } else {\n throw is.invalidParameterError('trim', 'object', options);\n }\n }\n if (isRotationExpected(this.options)) {\n this.options.rotateBeforePreExtract = true;\n }\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with resize-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n resize,\n extend,\n extract,\n trim\n });\n // Class attributes\n Sharp.gravity = gravity;\n Sharp.strategy = strategy;\n Sharp.kernel = kernel;\n Sharp.fit = fit;\n Sharp.position = position;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst is = require('./is');\n\n/**\n * Blend modes.\n * @member\n * @private\n */\nconst blend = {\n clear: 'clear',\n source: 'source',\n over: 'over',\n in: 'in',\n out: 'out',\n atop: 'atop',\n dest: 'dest',\n 'dest-over': 'dest-over',\n 'dest-in': 'dest-in',\n 'dest-out': 'dest-out',\n 'dest-atop': 'dest-atop',\n xor: 'xor',\n add: 'add',\n saturate: 'saturate',\n multiply: 'multiply',\n screen: 'screen',\n overlay: 'overlay',\n darken: 'darken',\n lighten: 'lighten',\n 'colour-dodge': 'colour-dodge',\n 'color-dodge': 'colour-dodge',\n 'colour-burn': 'colour-burn',\n 'color-burn': 'colour-burn',\n 'hard-light': 'hard-light',\n 'soft-light': 'soft-light',\n difference: 'difference',\n exclusion: 'exclusion'\n};\n\n/**\n * Composite image(s) over the processed (resized, extracted etc.) image.\n *\n * The images to composite must be the same size or smaller than the processed image.\n * If both `top` and `left` options are provided, they take precedence over `gravity`.\n *\n * Any resize, rotate or extract operations in the same processing pipeline\n * will always be applied to the input image before composition.\n *\n * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`,\n * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`,\n * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`,\n * `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`,\n * `hard-light`, `soft-light`, `difference`, `exclusion`.\n *\n * More information about blend modes can be found at\n * https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode\n * and https://www.cairographics.org/operators/\n *\n * @since 0.22.0\n *\n * @example\n * await sharp(background)\n * .composite([\n * { input: layer1, gravity: 'northwest' },\n * { input: layer2, gravity: 'southeast' },\n * ])\n * .toFile('combined.png');\n *\n * @example\n * const output = await sharp('input.gif', { animated: true })\n * .composite([\n * { input: 'overlay.png', tile: true, blend: 'saturate' }\n * ])\n * .toBuffer();\n *\n * @example\n * sharp('input.png')\n * .rotate(180)\n * .resize(300)\n * .flatten( { background: '#ff6600' } )\n * .composite([{ input: 'overlay.png', gravity: 'southeast' }])\n * .sharpen()\n * .withMetadata()\n * .webp( { quality: 90 } )\n * .toBuffer()\n * .then(function(outputBuffer) {\n * // outputBuffer contains upside down, 300px wide, alpha channel flattened\n * // onto orange background, composited with overlay.png with SE gravity,\n * // sharpened, with metadata, 90% quality WebP image data. Phew!\n * });\n *\n * @param {Object[]} images - Ordered list of images to composite\n * @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below)\n * @param {Object} [images[].input.create] - describes a blank overlay to be created.\n * @param {Number} [images[].input.create.width]\n * @param {Number} [images[].input.create.height]\n * @param {Number} [images[].input.create.channels] - 3-4\n * @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Object} [images[].input.text] - describes a new text image to be created.\n * @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `<i>Le</i>Monde`.\n * @param {string} [images[].input.text.font] - font name to render with.\n * @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`.\n * @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries.\n * @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0.\n * @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`).\n * @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text.\n * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified.\n * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `<span foreground=\"red\">Red!</span>`.\n * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified.\n * @param {String} [images[].blend='over'] - how to blend this image with the image below.\n * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay.\n * @param {Number} [images[].top] - the pixel offset from the top edge.\n * @param {Number} [images[].left] - the pixel offset from the left edge.\n * @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`.\n * @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option.\n * @param {Number} [images[].density=72] - number representing the DPI for vector overlay image.\n * @param {Object} [images[].raw] - describes overlay when using raw pixel data.\n * @param {Number} [images[].raw.width]\n * @param {Number} [images[].raw.height]\n * @param {Number} [images[].raw.channels]\n * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image.\n * @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters}\n * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters}\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction composite (images) {\n if (!Array.isArray(images)) {\n throw is.invalidParameterError('images to composite', 'array', images);\n }\n this.options.composite = images.map(image => {\n if (!is.object(image)) {\n throw is.invalidParameterError('image to composite', 'object', image);\n }\n const inputOptions = this._inputOptionsFromObject(image);\n const composite = {\n input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }),\n blend: 'over',\n tile: false,\n left: 0,\n top: 0,\n hasOffset: false,\n gravity: 0,\n premultiplied: false\n };\n if (is.defined(image.blend)) {\n if (is.string(blend[image.blend])) {\n composite.blend = blend[image.blend];\n } else {\n throw is.invalidParameterError('blend', 'valid blend name', image.blend);\n }\n }\n if (is.defined(image.tile)) {\n if (is.bool(image.tile)) {\n composite.tile = image.tile;\n } else {\n throw is.invalidParameterError('tile', 'boolean', image.tile);\n }\n }\n if (is.defined(image.left)) {\n if (is.integer(image.left)) {\n composite.left = image.left;\n } else {\n throw is.invalidParameterError('left', 'integer', image.left);\n }\n }\n if (is.defined(image.top)) {\n if (is.integer(image.top)) {\n composite.top = image.top;\n } else {\n throw is.invalidParameterError('top', 'integer', image.top);\n }\n }\n if (is.defined(image.top) !== is.defined(image.left)) {\n throw new Error('Expected both left and top to be set');\n } else {\n composite.hasOffset = is.integer(image.top) && is.integer(image.left);\n }\n if (is.defined(image.gravity)) {\n if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) {\n composite.gravity = image.gravity;\n } else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) {\n composite.gravity = this.constructor.gravity[image.gravity];\n } else {\n throw is.invalidParameterError('gravity', 'valid gravity', image.gravity);\n }\n }\n if (is.defined(image.premultiplied)) {\n if (is.bool(image.premultiplied)) {\n composite.premultiplied = image.premultiplied;\n } else {\n throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied);\n }\n }\n return composite;\n });\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with composite-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Sharp.prototype.composite = composite;\n Sharp.blend = blend;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst color = require('color');\nconst is = require('./is');\n\n/**\n * How accurate an operation should be.\n * @member\n * @private\n */\nconst vipsPrecision = {\n integer: 'integer',\n float: 'float',\n approximate: 'approximate'\n};\n\n/**\n * Rotate the output image by either an explicit angle\n * or auto-orient based on the EXIF `Orientation` tag.\n *\n * If an angle is provided, it is converted to a valid positive degree rotation.\n * For example, `-450` will produce a 270 degree rotation.\n *\n * When rotating by an angle other than a multiple of 90,\n * the background colour can be provided with the `background` option.\n *\n * If no angle is provided, it is determined from the EXIF data.\n * Mirroring is supported and may infer the use of a flip operation.\n *\n * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any.\n *\n * Only one rotation can occur per pipeline.\n * Previous calls to `rotate` in the same pipeline will be ignored.\n *\n * Multi-page images can only be rotated by 180 degrees.\n *\n * Method order is important when rotating, resizing and/or extracting regions,\n * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`.\n *\n * @example\n * const pipeline = sharp()\n * .rotate()\n * .resize(null, 200)\n * .toBuffer(function (err, outputBuffer, info) {\n * // outputBuffer contains 200px high JPEG image data,\n * // auto-rotated using EXIF Orientation tag\n * // info.width and info.height contain the dimensions of the resized image\n * });\n * readableStream.pipe(pipeline);\n *\n * @example\n * const rotateThenResize = await sharp(input)\n * .rotate(90)\n * .resize({ width: 16, height: 8, fit: 'fill' })\n * .toBuffer();\n * const resizeThenRotate = await sharp(input)\n * .resize({ width: 16, height: 8, fit: 'fill' })\n * .rotate(90)\n * .toBuffer();\n *\n * @param {number} [angle=auto] angle of rotation.\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {string|Object} [options.background=\"#000000\"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction rotate (angle, options) {\n if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) {\n this.options.debuglog('ignoring previous rotate options');\n }\n if (!is.defined(angle)) {\n this.options.useExifOrientation = true;\n } else if (is.integer(angle) && !(angle % 90)) {\n this.options.angle = angle;\n } else if (is.number(angle)) {\n this.options.rotationAngle = angle;\n if (is.object(options) && options.background) {\n const backgroundColour = color(options.background);\n this.options.rotationBackground = [\n backgroundColour.red(),\n backgroundColour.green(),\n backgroundColour.blue(),\n Math.round(backgroundColour.alpha() * 255)\n ];\n }\n } else {\n throw is.invalidParameterError('angle', 'numeric', angle);\n }\n return this;\n}\n\n/**\n * Mirror the image vertically (up-down) about the x-axis.\n * This always occurs before rotation, if any.\n *\n * This operation does not work correctly with multi-page images.\n *\n * @example\n * const output = await sharp(input).flip().toBuffer();\n *\n * @param {Boolean} [flip=true]\n * @returns {Sharp}\n */\nfunction flip (flip) {\n this.options.flip = is.bool(flip) ? flip : true;\n return this;\n}\n\n/**\n * Mirror the image horizontally (left-right) about the y-axis.\n * This always occurs before rotation, if any.\n *\n * @example\n * const output = await sharp(input).flop().toBuffer();\n *\n * @param {Boolean} [flop=true]\n * @returns {Sharp}\n */\nfunction flop (flop) {\n this.options.flop = is.bool(flop) ? flop : true;\n return this;\n}\n\n/**\n * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any.\n *\n * You must provide an array of length 4 or a 2x2 affine transformation matrix.\n * By default, new pixels are filled with a black background. You can provide a background color with the `background` option.\n * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`.\n *\n * In the case of a 2x2 matrix, the transform is:\n * - X = `matrix[0, 0]` \\* (x + `idx`) + `matrix[0, 1]` \\* (y + `idy`) + `odx`\n * - Y = `matrix[1, 0]` \\* (x + `idx`) + `matrix[1, 1]` \\* (y + `idy`) + `ody`\n *\n * where:\n * - x and y are the coordinates in input image.\n * - X and Y are the coordinates in output image.\n * - (0,0) is the upper left corner.\n *\n * @since 0.27.0\n *\n * @example\n * const pipeline = sharp()\n * .affine([[1, 0.3], [0.1, 0.7]], {\n * background: 'white',\n * interpolator: sharp.interpolators.nohalo\n * })\n * .toBuffer((err, outputBuffer, info) => {\n * // outputBuffer contains the transformed image\n * // info.width and info.height contain the new dimensions\n * });\n *\n * inputStream\n * .pipe(pipeline);\n *\n * @param {Array<Array<number>>|Array<number>} matrix - affine transformation matrix\n * @param {Object} [options] - if present, is an Object with optional attributes.\n * @param {String|Object} [options.background=\"#000000\"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha.\n * @param {Number} [options.idx=0] - input horizontal offset\n * @param {Number} [options.idy=0] - input vertical offset\n * @param {Number} [options.odx=0] - output horizontal offset\n * @param {Number} [options.ody=0] - output vertical offset\n * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction affine (matrix, options) {\n const flatMatrix = [].concat(...matrix);\n if (flatMatrix.length === 4 && flatMatrix.every(is.number)) {\n this.options.affineMatrix = flatMatrix;\n } else {\n throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix);\n }\n\n if (is.defined(options)) {\n if (is.object(options)) {\n this._setBackgroundColourOption('affineBackground', options.background);\n if (is.defined(options.idx)) {\n if (is.number(options.idx)) {\n this.options.affineIdx = options.idx;\n } else {\n throw is.invalidParameterError('options.idx', 'number', options.idx);\n }\n }\n if (is.defined(options.idy)) {\n if (is.number(options.idy)) {\n this.options.affineIdy = options.idy;\n } else {\n throw is.invalidParameterError('options.idy', 'number', options.idy);\n }\n }\n if (is.defined(options.odx)) {\n if (is.number(options.odx)) {\n this.options.affineOdx = options.odx;\n } else {\n throw is.invalidParameterError('options.odx', 'number', options.odx);\n }\n }\n if (is.defined(options.ody)) {\n if (is.number(options.ody)) {\n this.options.affineOdy = options.ody;\n } else {\n throw is.invalidParameterError('options.ody', 'number', options.ody);\n }\n }\n if (is.defined(options.interpolator)) {\n if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) {\n this.options.affineInterpolator = options.interpolator;\n } else {\n throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator);\n }\n }\n } else {\n throw is.invalidParameterError('options', 'object', options);\n }\n }\n\n return this;\n}\n\n/**\n * Sharpen the image.\n *\n * When used without parameters, performs a fast, mild sharpen of the output image.\n *\n * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space.\n * Fine-grained control over the level of sharpening in \"flat\" (m1) and \"jagged\" (m2) areas is available.\n *\n * See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation.\n *\n * @example\n * const data = await sharp(input).sharpen().toBuffer();\n *\n * @example\n * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer();\n *\n * @example\n * const data = await sharp(input)\n * .sharpen({\n * sigma: 2,\n * m1: 0,\n * m2: 3,\n * x1: 3,\n * y2: 15,\n * y3: 15,\n * })\n * .toBuffer();\n *\n * @param {Object|number} [options] - if present, is an Object with attributes\n * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10\n * @param {number} [options.m1=1.0] - the level of sharpening to apply to \"flat\" areas, between 0 and 1000000\n * @param {number} [options.m2=2.0] - the level of sharpening to apply to \"jagged\" areas, between 0 and 1000000\n * @param {number} [options.x1=2.0] - threshold between \"flat\" and \"jagged\", between 0 and 1000000\n * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000\n * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000\n * @param {number} [flat] - (deprecated) see `options.m1`.\n * @param {number} [jagged] - (deprecated) see `options.m2`.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction sharpen (options, flat, jagged) {\n if (!is.defined(options)) {\n // No arguments: default to mild sharpen\n this.options.sharpenSigma = -1;\n } else if (is.bool(options)) {\n // Deprecated boolean argument: apply mild sharpen?\n this.options.sharpenSigma = options ? -1 : 0;\n } else if (is.number(options) && is.inRange(options, 0.01, 10000)) {\n // Deprecated numeric argument: specific sigma\n this.options.sharpenSigma = options;\n // Deprecated control over flat areas\n if (is.defined(flat)) {\n if (is.number(flat) && is.inRange(flat, 0, 10000)) {\n this.options.sharpenM1 = flat;\n } else {\n throw is.invalidParameterError('flat', 'number between 0 and 10000', flat);\n }\n }\n // Deprecated control over jagged areas\n if (is.defined(jagged)) {\n if (is.number(jagged) && is.inRange(jagged, 0, 10000)) {\n this.options.sharpenM2 = jagged;\n } else {\n throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged);\n }\n }\n } else if (is.plainObject(options)) {\n if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) {\n this.options.sharpenSigma = options.sigma;\n } else {\n throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma);\n }\n if (is.defined(options.m1)) {\n if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) {\n this.options.sharpenM1 = options.m1;\n } else {\n throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1);\n }\n }\n if (is.defined(options.m2)) {\n if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) {\n this.options.sharpenM2 = options.m2;\n } else {\n throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2);\n }\n }\n if (is.defined(options.x1)) {\n if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) {\n this.options.sharpenX1 = options.x1;\n } else {\n throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1);\n }\n }\n if (is.defined(options.y2)) {\n if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) {\n this.options.sharpenY2 = options.y2;\n } else {\n throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2);\n }\n }\n if (is.defined(options.y3)) {\n if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) {\n this.options.sharpenY3 = options.y3;\n } else {\n throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3);\n }\n }\n } else {\n throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options);\n }\n return this;\n}\n\n/**\n * Apply median filter.\n * When used without parameters the default window is 3x3.\n *\n * @example\n * const output = await sharp(input).median().toBuffer();\n *\n * @example\n * const output = await sharp(input).median(5).toBuffer();\n *\n * @param {number} [size=3] square mask size: size x size\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction median (size) {\n if (!is.defined(size)) {\n // No arguments: default to 3x3\n this.options.medianSize = 3;\n } else if (is.integer(size) && is.inRange(size, 1, 1000)) {\n // Numeric argument: specific sigma\n this.options.medianSize = size;\n } else {\n throw is.invalidParameterError('size', 'integer between 1 and 1000', size);\n }\n return this;\n}\n\n/**\n * Blur the image.\n *\n * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter).\n *\n * When a `sigma` is provided, performs a slower, more accurate Gaussian blur.\n *\n * @example\n * const boxBlurred = await sharp(input)\n * .blur()\n * .toBuffer();\n *\n * @example\n * const gaussianBlurred = await sharp(input)\n * .blur(5)\n * .toBuffer();\n *\n * @param {Object|number|Boolean} [options]\n * @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`.\n * @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate.\n * @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction blur (options) {\n let sigma;\n if (is.number(options)) {\n sigma = options;\n } else if (is.plainObject(options)) {\n if (!is.number(options.sigma)) {\n throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma);\n }\n sigma = options.sigma;\n if ('precision' in options) {\n if (is.string(vipsPrecision[options.precision])) {\n this.options.precision = vipsPrecision[options.precision];\n } else {\n throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision);\n }\n }\n if ('minAmplitude' in options) {\n if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) {\n this.options.minAmpl = options.minAmplitude;\n } else {\n throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude);\n }\n }\n }\n\n if (!is.defined(options)) {\n // No arguments: default to mild blur\n this.options.blurSigma = -1;\n } else if (is.bool(options)) {\n // Boolean argument: apply mild blur?\n this.options.blurSigma = options ? -1 : 0;\n } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) {\n // Numeric argument: specific sigma\n this.options.blurSigma = sigma;\n } else {\n throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma);\n }\n\n return this;\n}\n\n/**\n * Merge alpha transparency channel, if any, with a background, then remove the alpha channel.\n *\n * See also {@link /api-channel#removealpha|removeAlpha}.\n *\n * @example\n * await sharp(rgbaInput)\n * .flatten({ background: '#F0A703' })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black.\n * @returns {Sharp}\n */\nfunction flatten (options) {\n this.options.flatten = is.bool(options) ? options : true;\n if (is.object(options)) {\n this._setBackgroundColourOption('flattenBackground', options.background);\n }\n return this;\n}\n\n/**\n * Ensure the image has an alpha channel\n * with all white pixel values made fully transparent.\n *\n * Existing alpha channel values for non-white pixels remain unchanged.\n *\n * This feature is experimental and the API may change.\n *\n * @since 0.32.1\n *\n * @example\n * await sharp(rgbInput)\n * .unflatten()\n * .toBuffer();\n *\n * @example\n * await sharp(rgbInput)\n * .threshold(128, { grayscale: false }) // converter bright pixels to white\n * .unflatten()\n * .toBuffer();\n */\nfunction unflatten () {\n this.options.unflatten = true;\n return this;\n}\n\n/**\n * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma`\n * then increasing the encoding (brighten) post-resize at a factor of `gamma`.\n * This can improve the perceived brightness of a resized image in non-linear colour spaces.\n * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation\n * when applying a gamma correction.\n *\n * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases.\n *\n * @param {number} [gamma=2.2] value between 1.0 and 3.0.\n * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction gamma (gamma, gammaOut) {\n if (!is.defined(gamma)) {\n // Default gamma correction of 2.2 (sRGB)\n this.options.gamma = 2.2;\n } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) {\n this.options.gamma = gamma;\n } else {\n throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma);\n }\n if (!is.defined(gammaOut)) {\n // Default gamma correction for output is same as input\n this.options.gammaOut = this.options.gamma;\n } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) {\n this.options.gammaOut = gammaOut;\n } else {\n throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut);\n }\n return this;\n}\n\n/**\n * Produce the \"negative\" of the image.\n *\n * @example\n * const output = await sharp(input)\n * .negate()\n * .toBuffer();\n *\n * @example\n * const output = await sharp(input)\n * .negate({ alpha: false })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel\n * @returns {Sharp}\n */\nfunction negate (options) {\n this.options.negate = is.bool(options) ? options : true;\n if (is.plainObject(options) && 'alpha' in options) {\n if (!is.bool(options.alpha)) {\n throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha);\n } else {\n this.options.negateAlpha = options.alpha;\n }\n }\n return this;\n}\n\n/**\n * Enhance output image contrast by stretching its luminance to cover a full dynamic range.\n *\n * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes.\n *\n * Luminance values below the `lower` percentile will be underexposed by clipping to zero.\n * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value.\n *\n * @example\n * const output = await sharp(input)\n * .normalise()\n * .toBuffer();\n *\n * @example\n * const output = await sharp(input)\n * .normalise({ lower: 0, upper: 100 })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.\n * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.\n * @returns {Sharp}\n */\nfunction normalise (options) {\n if (is.plainObject(options)) {\n if (is.defined(options.lower)) {\n if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) {\n this.options.normaliseLower = options.lower;\n } else {\n throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower);\n }\n }\n if (is.defined(options.upper)) {\n if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) {\n this.options.normaliseUpper = options.upper;\n } else {\n throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper);\n }\n }\n }\n if (this.options.normaliseLower >= this.options.normaliseUpper) {\n throw is.invalidParameterError('range', 'lower to be less than upper',\n `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);\n }\n this.options.normalise = true;\n return this;\n}\n\n/**\n * Alternative spelling of normalise.\n *\n * @example\n * const output = await sharp(input)\n * .normalize()\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed.\n * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed.\n * @returns {Sharp}\n */\nfunction normalize (options) {\n return this.normalise(options);\n}\n\n/**\n * Perform contrast limiting adaptive histogram equalization\n * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}.\n *\n * This will, in general, enhance the clarity of the image by bringing out darker details.\n *\n * @since 0.28.3\n *\n * @example\n * const output = await sharp(input)\n * .clahe({\n * width: 3,\n * height: 3,\n * })\n * .toBuffer();\n *\n * @param {Object} options\n * @param {number} options.width - Integral width of the search window, in pixels.\n * @param {number} options.height - Integral height of the search window, in pixels.\n * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction clahe (options) {\n if (is.plainObject(options)) {\n if (is.integer(options.width) && options.width > 0) {\n this.options.claheWidth = options.width;\n } else {\n throw is.invalidParameterError('width', 'integer greater than zero', options.width);\n }\n if (is.integer(options.height) && options.height > 0) {\n this.options.claheHeight = options.height;\n } else {\n throw is.invalidParameterError('height', 'integer greater than zero', options.height);\n }\n if (is.defined(options.maxSlope)) {\n if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) {\n this.options.claheMaxSlope = options.maxSlope;\n } else {\n throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope);\n }\n }\n } else {\n throw is.invalidParameterError('options', 'plain object', options);\n }\n return this;\n}\n\n/**\n * Convolve the image with the specified kernel.\n *\n * @example\n * sharp(input)\n * .convolve({\n * width: 3,\n * height: 3,\n * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1]\n * })\n * .raw()\n * .toBuffer(function(err, data, info) {\n * // data contains the raw pixel data representing the convolution\n * // of the input image with the horizontal Sobel operator\n * });\n *\n * @param {Object} kernel\n * @param {number} kernel.width - width of the kernel in pixels.\n * @param {number} kernel.height - height of the kernel in pixels.\n * @param {Array<number>} kernel.kernel - Array of length `width*height` containing the kernel values.\n * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels.\n * @param {number} [kernel.offset=0] - the offset of the kernel in pixels.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction convolve (kernel) {\n if (!is.object(kernel) || !Array.isArray(kernel.kernel) ||\n !is.integer(kernel.width) || !is.integer(kernel.height) ||\n !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) ||\n kernel.height * kernel.width !== kernel.kernel.length\n ) {\n // must pass in a kernel\n throw new Error('Invalid convolution kernel');\n }\n // Default scale is sum of kernel values\n if (!is.integer(kernel.scale)) {\n kernel.scale = kernel.kernel.reduce(function (a, b) {\n return a + b;\n }, 0);\n }\n // Clip scale to a minimum value of 1\n if (kernel.scale < 1) {\n kernel.scale = 1;\n }\n if (!is.integer(kernel.offset)) {\n kernel.offset = 0;\n }\n this.options.convKernel = kernel;\n return this;\n}\n\n/**\n * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0.\n * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied.\n * @param {Object} [options]\n * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale.\n * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction threshold (threshold, options) {\n if (!is.defined(threshold)) {\n this.options.threshold = 128;\n } else if (is.bool(threshold)) {\n this.options.threshold = threshold ? 128 : 0;\n } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) {\n this.options.threshold = threshold;\n } else {\n throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold);\n }\n if (!is.object(options) || options.greyscale === true || options.grayscale === true) {\n this.options.thresholdGrayscale = true;\n } else {\n this.options.thresholdGrayscale = false;\n }\n return this;\n}\n\n/**\n * Perform a bitwise boolean operation with operand image.\n *\n * This operation creates an output image where each pixel is the result of\n * the selected bitwise boolean `operation` between the corresponding pixels of the input images.\n *\n * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file.\n * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.\n * @param {Object} [options]\n * @param {Object} [options.raw] - describes operand when using raw pixel data.\n * @param {number} [options.raw.width]\n * @param {number} [options.raw.height]\n * @param {number} [options.raw.channels]\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction boolean (operand, operator, options) {\n this.options.boolean = this._createInputDescriptor(operand, options);\n if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) {\n this.options.booleanOp = operator;\n } else {\n throw is.invalidParameterError('operator', 'one of: and, or, eor', operator);\n }\n return this;\n}\n\n/**\n * Apply the linear formula `a` * input + `b` to the image to adjust image levels.\n *\n * When a single number is provided, it will be used for all image channels.\n * When an array of numbers is provided, the array length must match the number of channels.\n *\n * @example\n * await sharp(input)\n * .linear(0.5, 2)\n * .toBuffer();\n *\n * @example\n * await sharp(rgbInput)\n * .linear(\n * [0.25, 0.5, 0.75],\n * [150, 100, 50]\n * )\n * .toBuffer();\n *\n * @param {(number|number[])} [a=[]] multiplier\n * @param {(number|number[])} [b=[]] offset\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction linear (a, b) {\n if (!is.defined(a) && is.number(b)) {\n a = 1.0;\n } else if (is.number(a) && !is.defined(b)) {\n b = 0.0;\n }\n if (!is.defined(a)) {\n this.options.linearA = [];\n } else if (is.number(a)) {\n this.options.linearA = [a];\n } else if (Array.isArray(a) && a.length && a.every(is.number)) {\n this.options.linearA = a;\n } else {\n throw is.invalidParameterError('a', 'number or array of numbers', a);\n }\n if (!is.defined(b)) {\n this.options.linearB = [];\n } else if (is.number(b)) {\n this.options.linearB = [b];\n } else if (Array.isArray(b) && b.length && b.every(is.number)) {\n this.options.linearB = b;\n } else {\n throw is.invalidParameterError('b', 'number or array of numbers', b);\n }\n if (this.options.linearA.length !== this.options.linearB.length) {\n throw new Error('Expected a and b to be arrays of the same length');\n }\n return this;\n}\n\n/**\n * Recombine the image with the specified matrix.\n *\n * @since 0.21.1\n *\n * @example\n * sharp(input)\n * .recomb([\n * [0.3588, 0.7044, 0.1368],\n * [0.2990, 0.5870, 0.1140],\n * [0.2392, 0.4696, 0.0912],\n * ])\n * .raw()\n * .toBuffer(function(err, data, info) {\n * // data contains the raw pixel data after applying the matrix\n * // With this example input, a sepia filter has been applied\n * });\n *\n * @param {Array<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction recomb (inputMatrix) {\n if (!Array.isArray(inputMatrix)) {\n throw is.invalidParameterError('inputMatrix', 'array', inputMatrix);\n }\n if (inputMatrix.length !== 3 && inputMatrix.length !== 4) {\n throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length);\n }\n const recombMatrix = inputMatrix.flat().map(Number);\n if (recombMatrix.length !== 9 && recombMatrix.length !== 16) {\n throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length);\n }\n this.options.recombMatrix = recombMatrix;\n return this;\n}\n\n/**\n * Transforms the image using brightness, saturation, hue rotation, and lightness.\n * Brightness and lightness both operate on luminance, with the difference being that\n * brightness is multiplicative whereas lightness is additive.\n *\n * @since 0.22.1\n *\n * @example\n * // increase brightness by a factor of 2\n * const output = await sharp(input)\n * .modulate({\n * brightness: 2\n * })\n * .toBuffer();\n *\n * @example\n * // hue-rotate by 180 degrees\n * const output = await sharp(input)\n * .modulate({\n * hue: 180\n * })\n * .toBuffer();\n *\n * @example\n * // increase lightness by +50\n * const output = await sharp(input)\n * .modulate({\n * lightness: 50\n * })\n * .toBuffer();\n *\n * @example\n * // decrease brightness and saturation while also hue-rotating by 90 degrees\n * const output = await sharp(input)\n * .modulate({\n * brightness: 0.5,\n * saturation: 0.5,\n * hue: 90,\n * })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.brightness] Brightness multiplier\n * @param {number} [options.saturation] Saturation multiplier\n * @param {number} [options.hue] Degrees for hue rotation\n * @param {number} [options.lightness] Lightness addend\n * @returns {Sharp}\n */\nfunction modulate (options) {\n if (!is.plainObject(options)) {\n throw is.invalidParameterError('options', 'plain object', options);\n }\n if ('brightness' in options) {\n if (is.number(options.brightness) && options.brightness >= 0) {\n this.options.brightness = options.brightness;\n } else {\n throw is.invalidParameterError('brightness', 'number above zero', options.brightness);\n }\n }\n if ('saturation' in options) {\n if (is.number(options.saturation) && options.saturation >= 0) {\n this.options.saturation = options.saturation;\n } else {\n throw is.invalidParameterError('saturation', 'number above zero', options.saturation);\n }\n }\n if ('hue' in options) {\n if (is.integer(options.hue)) {\n this.options.hue = options.hue % 360;\n } else {\n throw is.invalidParameterError('hue', 'number', options.hue);\n }\n }\n if ('lightness' in options) {\n if (is.number(options.lightness)) {\n this.options.lightness = options.lightness;\n } else {\n throw is.invalidParameterError('lightness', 'number', options.lightness);\n }\n }\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with operation-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n rotate,\n flip,\n flop,\n affine,\n sharpen,\n median,\n blur,\n flatten,\n unflatten,\n gamma,\n negate,\n normalise,\n normalize,\n clahe,\n convolve,\n threshold,\n boolean,\n linear,\n recomb,\n modulate\n });\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst color = require('color');\nconst is = require('./is');\n\n/**\n * Colourspaces.\n * @private\n */\nconst colourspace = {\n multiband: 'multiband',\n 'b-w': 'b-w',\n bw: 'b-w',\n cmyk: 'cmyk',\n srgb: 'srgb'\n};\n\n/**\n * Tint the image using the provided colour.\n * An alpha channel may be present and will be unchanged by the operation.\n *\n * @example\n * const output = await sharp(input)\n * .tint({ r: 255, g: 240, b: 16 })\n * .toBuffer();\n *\n * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module.\n * @returns {Sharp}\n * @throws {Error} Invalid parameter\n */\nfunction tint (tint) {\n this._setBackgroundColourOption('tint', tint);\n return this;\n}\n\n/**\n * Convert to 8-bit greyscale; 256 shades of grey.\n * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results.\n * By default the output image will be web-friendly sRGB and contain three (identical) color channels.\n * This may be overridden by other sharp operations such as `toColourspace('b-w')`,\n * which will produce an output image containing one color channel.\n * An alpha channel may be present, and will be unchanged by the operation.\n *\n * @example\n * const output = await sharp(input).greyscale().toBuffer();\n *\n * @param {Boolean} [greyscale=true]\n * @returns {Sharp}\n */\nfunction greyscale (greyscale) {\n this.options.greyscale = is.bool(greyscale) ? greyscale : true;\n return this;\n}\n\n/**\n * Alternative spelling of `greyscale`.\n * @param {Boolean} [grayscale=true]\n * @returns {Sharp}\n */\nfunction grayscale (grayscale) {\n return this.greyscale(grayscale);\n}\n\n/**\n * Set the pipeline colourspace.\n *\n * The input image will be converted to the provided colourspace at the start of the pipeline.\n * All operations will use this colourspace before converting to the output colourspace,\n * as defined by {@link #tocolourspace|toColourspace}.\n *\n * @since 0.29.0\n *\n * @example\n * // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB.\n * await sharp(input)\n * .pipelineColourspace('rgb16')\n * .toColourspace('srgb')\n * .toFile('16bpc-pipeline-to-8bpc-output.png')\n *\n * @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction pipelineColourspace (colourspace) {\n if (!is.string(colourspace)) {\n throw is.invalidParameterError('colourspace', 'string', colourspace);\n }\n this.options.colourspacePipeline = colourspace;\n return this;\n}\n\n/**\n * Alternative spelling of `pipelineColourspace`.\n * @param {string} [colorspace] - pipeline colorspace.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction pipelineColorspace (colorspace) {\n return this.pipelineColourspace(colorspace);\n}\n\n/**\n * Set the output colourspace.\n * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n *\n * @example\n * // Output 16 bits per pixel RGB\n * await sharp(input)\n * .toColourspace('rgb16')\n * .toFile('16-bpp.png')\n *\n * @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794)\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction toColourspace (colourspace) {\n if (!is.string(colourspace)) {\n throw is.invalidParameterError('colourspace', 'string', colourspace);\n }\n this.options.colourspace = colourspace;\n return this;\n}\n\n/**\n * Alternative spelling of `toColourspace`.\n * @param {string} [colorspace] - output colorspace.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction toColorspace (colorspace) {\n return this.toColourspace(colorspace);\n}\n\n/**\n * Update a colour attribute of the this.options Object.\n * @private\n * @param {string} key\n * @param {string|Object} value\n * @throws {Error} Invalid value\n */\nfunction _setBackgroundColourOption (key, value) {\n if (is.defined(value)) {\n if (is.object(value) || is.string(value)) {\n const colour = color(value);\n this.options[key] = [\n colour.red(),\n colour.green(),\n colour.blue(),\n Math.round(colour.alpha() * 255)\n ];\n } else {\n throw is.invalidParameterError('background', 'object or string', value);\n }\n }\n}\n\n/**\n * Decorate the Sharp prototype with colour-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Public\n tint,\n greyscale,\n grayscale,\n pipelineColourspace,\n pipelineColorspace,\n toColourspace,\n toColorspace,\n // Private\n _setBackgroundColourOption\n });\n // Class attributes\n Sharp.colourspace = colourspace;\n Sharp.colorspace = colourspace;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst is = require('./is');\n\n/**\n * Boolean operations for bandbool.\n * @private\n */\nconst bool = {\n and: 'and',\n or: 'or',\n eor: 'eor'\n};\n\n/**\n * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel.\n *\n * See also {@link /api-operation#flatten|flatten}.\n *\n * @example\n * sharp('rgba.png')\n * .removeAlpha()\n * .toFile('rgb.png', function(err, info) {\n * // rgb.png is a 3 channel image without an alpha channel\n * });\n *\n * @returns {Sharp}\n */\nfunction removeAlpha () {\n this.options.removeAlpha = true;\n return this;\n}\n\n/**\n * Ensure the output image has an alpha transparency channel.\n * If missing, the added alpha channel will have the specified\n * transparency level, defaulting to fully-opaque (1).\n * This is a no-op if the image already has an alpha channel.\n *\n * @since 0.21.2\n *\n * @example\n * // rgba.png will be a 4 channel image with a fully-opaque alpha channel\n * await sharp('rgb.jpg')\n * .ensureAlpha()\n * .toFile('rgba.png')\n *\n * @example\n * // rgba is a 4 channel image with a fully-transparent alpha channel\n * const rgba = await sharp(rgb)\n * .ensureAlpha(0)\n * .toBuffer();\n *\n * @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque)\n * @returns {Sharp}\n * @throws {Error} Invalid alpha transparency level\n */\nfunction ensureAlpha (alpha) {\n if (is.defined(alpha)) {\n if (is.number(alpha) && is.inRange(alpha, 0, 1)) {\n this.options.ensureAlpha = alpha;\n } else {\n throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha);\n }\n } else {\n this.options.ensureAlpha = 1;\n }\n return this;\n}\n\n/**\n * Extract a single channel from a multi-channel image.\n *\n * @example\n * // green.jpg is a greyscale image containing the green channel of the input\n * await sharp(input)\n * .extractChannel('green')\n * .toFile('green.jpg');\n *\n * @example\n * // red1 is the red value of the first pixel, red2 the second pixel etc.\n * const [red1, red2, ...] = await sharp(input)\n * .extractChannel(0)\n * .raw()\n * .toBuffer();\n *\n * @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`.\n * @returns {Sharp}\n * @throws {Error} Invalid channel\n */\nfunction extractChannel (channel) {\n const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 };\n if (Object.keys(channelMap).includes(channel)) {\n channel = channelMap[channel];\n }\n if (is.integer(channel) && is.inRange(channel, 0, 4)) {\n this.options.extractChannel = channel;\n } else {\n throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel);\n }\n return this;\n}\n\n/**\n * Join one or more channels to the image.\n * The meaning of the added channels depends on the output colourspace, set with `toColourspace()`.\n * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels.\n * Channel ordering follows vips convention:\n * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha.\n * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha.\n *\n * Buffers may be any of the image formats supported by sharp.\n * For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor.\n *\n * @param {Array<string|Buffer>|string|Buffer} images - one or more images (file paths, Buffers).\n * @param {Object} options - image options, see `sharp()` constructor.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction joinChannel (images, options) {\n if (Array.isArray(images)) {\n images.forEach(function (image) {\n this.options.joinChannelIn.push(this._createInputDescriptor(image, options));\n }, this);\n } else {\n this.options.joinChannelIn.push(this._createInputDescriptor(images, options));\n }\n return this;\n}\n\n/**\n * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image.\n *\n * @example\n * sharp('3-channel-rgb-input.png')\n * .bandbool(sharp.bool.and)\n * .toFile('1-channel-output.png', function (err, info) {\n * // The output will be a single channel image where each pixel `P = R & G & B`.\n * // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`\n * // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.\n * });\n *\n * @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction bandbool (boolOp) {\n if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) {\n this.options.bandBoolOp = boolOp;\n } else {\n throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp);\n }\n return this;\n}\n\n/**\n * Decorate the Sharp prototype with channel-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Public instance functions\n removeAlpha,\n ensureAlpha,\n extractChannel,\n joinChannel,\n bandbool\n });\n // Class attributes\n Sharp.bool = bool;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst path = require('node:path');\nconst is = require('./is');\nconst sharp = require('./sharp');\n\nconst formats = new Map([\n ['heic', 'heif'],\n ['heif', 'heif'],\n ['avif', 'avif'],\n ['jpeg', 'jpeg'],\n ['jpg', 'jpeg'],\n ['jpe', 'jpeg'],\n ['tile', 'tile'],\n ['dz', 'tile'],\n ['png', 'png'],\n ['raw', 'raw'],\n ['tiff', 'tiff'],\n ['tif', 'tiff'],\n ['webp', 'webp'],\n ['gif', 'gif'],\n ['jp2', 'jp2'],\n ['jpx', 'jp2'],\n ['j2k', 'jp2'],\n ['j2c', 'jp2'],\n ['jxl', 'jxl']\n]);\n\nconst jp2Regex = /\\.(jp[2x]|j2[kc])$/i;\n\nconst errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');\n\nconst bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));\n\n/**\n * Write output image data to a file.\n *\n * If an explicit output format is not selected, it will be inferred from the extension,\n * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.\n * Note that raw pixel data is only supported for buffer output.\n *\n * By default all metadata will be removed, which includes EXIF-based orientation.\n * See {@link #withmetadata|withMetadata} for control over this.\n *\n * The caller is responsible for ensuring directory structures and permissions exist.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * @example\n * sharp(input)\n * .toFile('output.png', (err, info) => { ... });\n *\n * @example\n * sharp(input)\n * .toFile('output.png')\n * .then(info => { ... })\n * .catch(err => { ... });\n *\n * @param {string} fileOut - the path to write the image data to.\n * @param {Function} [callback] - called on completion with two arguments `(err, info)`.\n * `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n * `channels` and `premultiplied` (indicating if premultiplication was used).\n * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\n * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.\n * Animated output will also contain `pageHeight` and `pages`.\n * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n * @returns {Promise<Object>} - when no callback is provided\n * @throws {Error} Invalid parameters\n */\nfunction toFile (fileOut, callback) {\n let err;\n if (!is.string(fileOut)) {\n err = new Error('Missing output file path');\n } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {\n err = new Error('Cannot use same file for input and output');\n } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {\n err = errJp2Save();\n }\n if (err) {\n if (is.fn(callback)) {\n callback(err);\n } else {\n return Promise.reject(err);\n }\n } else {\n this.options.fileOut = fileOut;\n const stack = Error();\n return this._pipeline(callback, stack);\n }\n return this;\n}\n\n/**\n * Write output to a Buffer.\n * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.\n *\n * Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format.\n *\n * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.\n *\n * By default all metadata will be removed, which includes EXIF-based orientation.\n * See {@link #withmetadata|withMetadata} for control over this.\n *\n * `callback`, if present, gets three arguments `(err, data, info)` where:\n * - `err` is an error, if any.\n * - `data` is the output image data.\n * - `info` contains the output image `format`, `size` (bytes), `width`, `height`,\n * `channels` and `premultiplied` (indicating if premultiplication was used).\n * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.\n * Animated output will also contain `pageHeight` and `pages`.\n * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.\n *\n * A `Promise` is returned when `callback` is not provided.\n *\n * @example\n * sharp(input)\n * .toBuffer((err, data, info) => { ... });\n *\n * @example\n * sharp(input)\n * .toBuffer()\n * .then(data => { ... })\n * .catch(err => { ... });\n *\n * @example\n * sharp(input)\n * .png()\n * .toBuffer({ resolveWithObject: true })\n * .then(({ data, info }) => { ... })\n * .catch(err => { ... });\n *\n * @example\n * const { data, info } = await sharp('my-image.jpg')\n * // output the raw pixels\n * .raw()\n * .toBuffer({ resolveWithObject: true });\n *\n * // create a more type safe way to work with the raw pixel data\n * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer\n * // so `data` and `pixelArray` point to the same memory location\n * const pixelArray = new Uint8ClampedArray(data.buffer);\n *\n * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input\n * const { width, height, channels } = info;\n * await sharp(pixelArray, { raw: { width, height, channels } })\n * .toFile('my-changed-image.jpg');\n *\n * @param {Object} [options]\n * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.\n * @param {Function} [callback]\n * @returns {Promise<Buffer>} - when no callback is provided\n */\nfunction toBuffer (options, callback) {\n if (is.object(options)) {\n this._setBooleanOption('resolveWithObject', options.resolveWithObject);\n } else if (this.options.resolveWithObject) {\n this.options.resolveWithObject = false;\n }\n this.options.fileOut = '';\n const stack = Error();\n return this._pipeline(is.fn(options) ? options : callback, stack);\n}\n\n/**\n * Keep all EXIF metadata from the input image in the output image.\n *\n * EXIF metadata is unsupported for TIFF output.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithExif = await sharp(inputWithExif)\n * .keepExif()\n * .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepExif () {\n this.options.keepMetadata |= 0b00001;\n return this;\n}\n\n/**\n * Set EXIF metadata in the output image, ignoring any EXIF in the input image.\n *\n * @since 0.33.0\n *\n * @example\n * const dataWithExif = await sharp(input)\n * .withExif({\n * IFD0: {\n * Copyright: 'The National Gallery'\n * },\n * IFD3: {\n * GPSLatitudeRef: 'N',\n * GPSLatitude: '51/1 30/1 3230/100',\n * GPSLongitudeRef: 'W',\n * GPSLongitude: '0/1 7/1 4366/100'\n * }\n * })\n * .toBuffer();\n *\n * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withExif (exif) {\n if (is.object(exif)) {\n for (const [ifd, entries] of Object.entries(exif)) {\n if (is.object(entries)) {\n for (const [k, v] of Object.entries(entries)) {\n if (is.string(v)) {\n this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;\n } else {\n throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);\n }\n }\n } else {\n throw is.invalidParameterError(ifd, 'object', entries);\n }\n }\n } else {\n throw is.invalidParameterError('exif', 'object', exif);\n }\n this.options.withExifMerge = false;\n return this.keepExif();\n}\n\n/**\n * Update EXIF metadata from the input image in the output image.\n *\n * @since 0.33.0\n *\n * @example\n * const dataWithMergedExif = await sharp(inputWithExif)\n * .withExifMerge({\n * IFD0: {\n * Copyright: 'The National Gallery'\n * }\n * })\n * .toBuffer();\n *\n * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withExifMerge (exif) {\n this.withExif(exif);\n this.options.withExifMerge = true;\n return this;\n}\n\n/**\n * Keep ICC profile from the input image in the output image.\n *\n * Where necessary, will attempt to convert the output colour space to match the profile.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithIccProfile = await sharp(inputWithIccProfile)\n * .keepIccProfile()\n * .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepIccProfile () {\n this.options.keepMetadata |= 0b01000;\n return this;\n}\n\n/**\n * Transform using an ICC profile and attach to the output image.\n *\n * This can either be an absolute filesystem path or\n * built-in profile name (`srgb`, `p3`, `cmyk`).\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithP3 = await sharp(input)\n * .withIccProfile('p3')\n * .toBuffer();\n *\n * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).\n * @param {Object} [options]\n * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withIccProfile (icc, options) {\n if (is.string(icc)) {\n this.options.withIccProfile = icc;\n } else {\n throw is.invalidParameterError('icc', 'string', icc);\n }\n this.keepIccProfile();\n if (is.object(options)) {\n if (is.defined(options.attach)) {\n if (is.bool(options.attach)) {\n if (!options.attach) {\n this.options.keepMetadata &= ~0b01000;\n }\n } else {\n throw is.invalidParameterError('attach', 'boolean', options.attach);\n }\n }\n }\n return this;\n}\n\n/**\n * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.\n *\n * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent\n * sRGB colour space and strip all metadata, including the removal of any ICC profile.\n *\n * @since 0.33.0\n *\n * @example\n * const outputWithMetadata = await sharp(inputWithMetadata)\n * .keepMetadata()\n * .toBuffer();\n *\n * @returns {Sharp}\n */\nfunction keepMetadata () {\n this.options.keepMetadata = 0b11111;\n return this;\n}\n\n/**\n * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.\n *\n * This will also convert to and add a web-friendly sRGB ICC profile if appropriate.\n *\n * Allows orientation and density to be set or updated.\n *\n * @example\n * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)\n * .withMetadata()\n * .toBuffer();\n *\n * @example\n * // Set output metadata to 96 DPI\n * const data = await sharp(input)\n * .withMetadata({ density: 96 })\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.\n * @param {number} [options.density] Number of pixels per inch (DPI).\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction withMetadata (options) {\n this.keepMetadata();\n this.withIccProfile('srgb');\n if (is.object(options)) {\n if (is.defined(options.orientation)) {\n if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {\n this.options.withMetadataOrientation = options.orientation;\n } else {\n throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation);\n }\n }\n if (is.defined(options.density)) {\n if (is.number(options.density) && options.density > 0) {\n this.options.withMetadataDensity = options.density;\n } else {\n throw is.invalidParameterError('density', 'positive number', options.density);\n }\n }\n if (is.defined(options.icc)) {\n this.withIccProfile(options.icc);\n }\n if (is.defined(options.exif)) {\n this.withExifMerge(options.exif);\n }\n }\n return this;\n}\n\n/**\n * Force output to a given format.\n *\n * @example\n * // Convert any input to PNG output\n * const data = await sharp(input)\n * .toFormat('png')\n * .toBuffer();\n *\n * @param {(string|Object)} format - as a string or an Object with an 'id' attribute\n * @param {Object} options - output options\n * @returns {Sharp}\n * @throws {Error} unsupported format or options\n */\nfunction toFormat (format, options) {\n const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase());\n if (!actualFormat) {\n throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format);\n }\n return this[actualFormat](options);\n}\n\n/**\n * Use these JPEG options for output image.\n *\n * @example\n * // Convert any input to very high quality JPEG output\n * const data = await sharp(input)\n * .jpeg({\n * quality: 100,\n * chromaSubsampling: '4:4:4'\n * })\n * .toBuffer();\n *\n * @example\n * // Use mozjpeg to reduce output JPEG file size (slower)\n * const data = await sharp(input)\n * .jpeg({ mozjpeg: true })\n * .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling\n * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables\n * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding\n * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }`\n * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation\n * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing\n * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive\n * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans\n * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8\n * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable\n * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jpeg (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.jpegQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.progressive)) {\n this._setBooleanOption('jpegProgressive', options.progressive);\n }\n if (is.defined(options.chromaSubsampling)) {\n if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n this.options.jpegChromaSubsampling = options.chromaSubsampling;\n } else {\n throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n }\n }\n const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding;\n if (is.defined(optimiseCoding)) {\n this._setBooleanOption('jpegOptimiseCoding', optimiseCoding);\n }\n if (is.defined(options.mozjpeg)) {\n if (is.bool(options.mozjpeg)) {\n if (options.mozjpeg) {\n this.options.jpegTrellisQuantisation = true;\n this.options.jpegOvershootDeringing = true;\n this.options.jpegOptimiseScans = true;\n this.options.jpegProgressive = true;\n this.options.jpegQuantisationTable = 3;\n }\n } else {\n throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg);\n }\n }\n const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation;\n if (is.defined(trellisQuantisation)) {\n this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation);\n }\n if (is.defined(options.overshootDeringing)) {\n this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing);\n }\n const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans;\n if (is.defined(optimiseScans)) {\n this._setBooleanOption('jpegOptimiseScans', optimiseScans);\n if (optimiseScans) {\n this.options.jpegProgressive = true;\n }\n }\n const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable;\n if (is.defined(quantisationTable)) {\n if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) {\n this.options.jpegQuantisationTable = quantisationTable;\n } else {\n throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable);\n }\n }\n }\n return this._updateFormatOut('jpeg', options);\n}\n\n/**\n * Use these PNG options for output image.\n *\n * By default, PNG output is full colour at 8 bits per pixel.\n *\n * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.\n * Set `palette` to `true` for slower, indexed PNG output.\n *\n * For 16 bits per pixel output, convert to `rgb16` via\n * {@link /api-colour#tocolourspace|toColourspace}.\n *\n * @example\n * // Convert any input to full colour PNG output\n * const data = await sharp(input)\n * .png()\n * .toBuffer();\n *\n * @example\n * // Convert any input to indexed PNG output (slower)\n * const data = await sharp(input)\n * .png({ palette: true })\n * .toBuffer();\n *\n * @example\n * // Output 16 bits per pixel RGB(A)\n * const data = await sharp(input)\n * .toColourspace('rgb16')\n * .png()\n * .toBuffer();\n *\n * @param {Object} [options]\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)\n * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering\n * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support\n * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true`\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true`\n * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true`\n * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true`\n * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true`\n * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction png (options) {\n if (is.object(options)) {\n if (is.defined(options.progressive)) {\n this._setBooleanOption('pngProgressive', options.progressive);\n }\n if (is.defined(options.compressionLevel)) {\n if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) {\n this.options.pngCompressionLevel = options.compressionLevel;\n } else {\n throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel);\n }\n }\n if (is.defined(options.adaptiveFiltering)) {\n this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering);\n }\n const colours = options.colours || options.colors;\n if (is.defined(colours)) {\n if (is.integer(colours) && is.inRange(colours, 2, 256)) {\n this.options.pngBitdepth = bitdepthFromColourCount(colours);\n } else {\n throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);\n }\n }\n if (is.defined(options.palette)) {\n this._setBooleanOption('pngPalette', options.palette);\n } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) {\n this._setBooleanOption('pngPalette', true);\n }\n if (this.options.pngPalette) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) {\n this.options.pngQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) {\n this.options.pngEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);\n }\n }\n if (is.defined(options.dither)) {\n if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {\n this.options.pngDither = options.dither;\n } else {\n throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);\n }\n }\n }\n }\n return this._updateFormatOut('png', options);\n}\n\n/**\n * Use these WebP options for output image.\n *\n * @example\n * // Convert any input to lossless WebP output\n * const data = await sharp(input)\n * .webp({ lossless: true })\n * .toBuffer();\n *\n * @example\n * // Optimise the file size of an animated WebP\n * const outputWebp = await sharp(inputWebp, { animated: true })\n * .webp({ effort: 6 })\n * .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100\n * @param {boolean} [options.lossless=false] - use lossless compression mode\n * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode\n * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling\n * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow)\n * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow)\n * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction webp (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.webpQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.alphaQuality)) {\n if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) {\n this.options.webpAlphaQuality = options.alphaQuality;\n } else {\n throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality);\n }\n }\n if (is.defined(options.lossless)) {\n this._setBooleanOption('webpLossless', options.lossless);\n }\n if (is.defined(options.nearLossless)) {\n this._setBooleanOption('webpNearLossless', options.nearLossless);\n }\n if (is.defined(options.smartSubsample)) {\n this._setBooleanOption('webpSmartSubsample', options.smartSubsample);\n }\n if (is.defined(options.preset)) {\n if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {\n this.options.webpPreset = options.preset;\n } else {\n throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {\n this.options.webpEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort);\n }\n }\n if (is.defined(options.minSize)) {\n this._setBooleanOption('webpMinSize', options.minSize);\n }\n if (is.defined(options.mixed)) {\n this._setBooleanOption('webpMixed', options.mixed);\n }\n }\n trySetAnimationOptions(options, this.options);\n return this._updateFormatOut('webp', options);\n}\n\n/**\n * Use these GIF options for the output image.\n *\n * The first entry in the palette is reserved for transparency.\n *\n * The palette of the input image will be re-used if possible.\n *\n * @since 0.30.0\n *\n * @example\n * // Convert PNG to GIF\n * await sharp(pngBuffer)\n * .gif()\n * .toBuffer();\n *\n * @example\n * // Convert animated WebP to animated GIF\n * await sharp('animated.webp', { animated: true })\n * .toFile('animated.gif');\n *\n * @example\n * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF\n * const out = await sharp('in.gif', { animated: true })\n * .resize({ width: 128, height: 128 })\n * .gif({ dither: 0 })\n * .toBuffer();\n *\n * @example\n * // Lossy file size reduction of animated GIF\n * await sharp('in.gif', { animated: true })\n * .gif({ interFrameMaxError: 8 })\n * .toFile('optim.gif');\n *\n * @param {Object} [options] - output options\n * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow)\n * @param {boolean} [options.progressive=false] - use progressive (interlace) scan\n * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256\n * @param {number} [options.colors=256] - alternative spelling of `options.colours`\n * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)\n * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)\n * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32\n * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256\n * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)\n * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction gif (options) {\n if (is.object(options)) {\n if (is.defined(options.reuse)) {\n this._setBooleanOption('gifReuse', options.reuse);\n }\n if (is.defined(options.progressive)) {\n this._setBooleanOption('gifProgressive', options.progressive);\n }\n const colours = options.colours || options.colors;\n if (is.defined(colours)) {\n if (is.integer(colours) && is.inRange(colours, 2, 256)) {\n this.options.gifBitdepth = bitdepthFromColourCount(colours);\n } else {\n throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);\n }\n }\n if (is.defined(options.effort)) {\n if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) {\n this.options.gifEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);\n }\n }\n if (is.defined(options.dither)) {\n if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {\n this.options.gifDither = options.dither;\n } else {\n throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);\n }\n }\n if (is.defined(options.interFrameMaxError)) {\n if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {\n this.options.gifInterFrameMaxError = options.interFrameMaxError;\n } else {\n throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);\n }\n }\n if (is.defined(options.interPaletteMaxError)) {\n if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {\n this.options.gifInterPaletteMaxError = options.interPaletteMaxError;\n } else {\n throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);\n }\n }\n }\n trySetAnimationOptions(options, this.options);\n return this._updateFormatOut('gif', options);\n}\n\n/* istanbul ignore next */\n/**\n * Use these JP2 options for output image.\n *\n * Requires libvips compiled with support for OpenJPEG.\n * The prebuilt binaries do not include this - see\n * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.\n *\n * @example\n * // Convert any input to lossless JP2 output\n * const data = await sharp(input)\n * .jp2({ lossless: true })\n * .toBuffer();\n *\n * @example\n * // Convert any input to very high quality JP2 output\n * const data = await sharp(input)\n * .jp2({\n * quality: 100,\n * chromaSubsampling: '4:4:4'\n * })\n * .toBuffer();\n *\n * @since 0.29.1\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression mode\n * @param {number} [options.tileWidth=512] - horizontal tile size\n * @param {number} [options.tileHeight=512] - vertical tile size\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jp2 (options) {\n if (!this.constructor.format.jp2k.output.buffer) {\n throw errJp2Save();\n }\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.jp2Quality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.lossless)) {\n if (is.bool(options.lossless)) {\n this.options.jp2Lossless = options.lossless;\n } else {\n throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n }\n }\n if (is.defined(options.tileWidth)) {\n if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) {\n this.options.jp2TileWidth = options.tileWidth;\n } else {\n throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth);\n }\n }\n if (is.defined(options.tileHeight)) {\n if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) {\n this.options.jp2TileHeight = options.tileHeight;\n } else {\n throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight);\n }\n }\n if (is.defined(options.chromaSubsampling)) {\n if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n this.options.jp2ChromaSubsampling = options.chromaSubsampling;\n } else {\n throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n }\n }\n }\n return this._updateFormatOut('jp2', options);\n}\n\n/**\n * Set animation options if available.\n * @private\n *\n * @param {Object} [source] - output options\n * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation\n * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds)\n * @param {Object} [target] - target object for valid options\n * @throws {Error} Invalid options\n */\nfunction trySetAnimationOptions (source, target) {\n if (is.object(source) && is.defined(source.loop)) {\n if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) {\n target.loop = source.loop;\n } else {\n throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop);\n }\n }\n if (is.object(source) && is.defined(source.delay)) {\n // We allow singular values as well\n if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) {\n target.delay = [source.delay];\n } else if (\n Array.isArray(source.delay) &&\n source.delay.every(is.integer) &&\n source.delay.every(v => is.inRange(v, 0, 65535))) {\n target.delay = source.delay;\n } else {\n throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay);\n }\n }\n}\n\n/**\n * Use these TIFF options for output image.\n *\n * The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata}\n * instead of providing `xres` and `yres` in pixels/mm.\n *\n * @example\n * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output\n * sharp('input.svg')\n * .tiff({\n * compression: 'lzw',\n * bitdepth: 1\n * })\n * .toFile('1-bpp-output.tiff')\n * .then(info => { ... });\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=80] - quality, integer 1-100\n * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format\n * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k\n * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float\n * @param {boolean} [options.pyramid=false] - write an image pyramid\n * @param {boolean} [options.tile=false] - write a tiled tiff\n * @param {number} [options.tileWidth=256] - horizontal tile size\n * @param {number} [options.tileHeight=256] - vertical tile size\n * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm\n * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm\n * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm\n * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit\n * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction tiff (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.tiffQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.bitdepth)) {\n if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) {\n this.options.tiffBitdepth = options.bitdepth;\n } else {\n throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth);\n }\n }\n // tiling\n if (is.defined(options.tile)) {\n this._setBooleanOption('tiffTile', options.tile);\n }\n if (is.defined(options.tileWidth)) {\n if (is.integer(options.tileWidth) && options.tileWidth > 0) {\n this.options.tiffTileWidth = options.tileWidth;\n } else {\n throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth);\n }\n }\n if (is.defined(options.tileHeight)) {\n if (is.integer(options.tileHeight) && options.tileHeight > 0) {\n this.options.tiffTileHeight = options.tileHeight;\n } else {\n throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight);\n }\n }\n // miniswhite\n if (is.defined(options.miniswhite)) {\n this._setBooleanOption('tiffMiniswhite', options.miniswhite);\n }\n // pyramid\n if (is.defined(options.pyramid)) {\n this._setBooleanOption('tiffPyramid', options.pyramid);\n }\n // resolution\n if (is.defined(options.xres)) {\n if (is.number(options.xres) && options.xres > 0) {\n this.options.tiffXres = options.xres;\n } else {\n throw is.invalidParameterError('xres', 'number greater than zero', options.xres);\n }\n }\n if (is.defined(options.yres)) {\n if (is.number(options.yres) && options.yres > 0) {\n this.options.tiffYres = options.yres;\n } else {\n throw is.invalidParameterError('yres', 'number greater than zero', options.yres);\n }\n }\n // compression\n if (is.defined(options.compression)) {\n if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) {\n this.options.tiffCompression = options.compression;\n } else {\n throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression);\n }\n }\n // predictor\n if (is.defined(options.predictor)) {\n if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) {\n this.options.tiffPredictor = options.predictor;\n } else {\n throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor);\n }\n }\n // resolutionUnit\n if (is.defined(options.resolutionUnit)) {\n if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) {\n this.options.tiffResolutionUnit = options.resolutionUnit;\n } else {\n throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit);\n }\n }\n }\n return this._updateFormatOut('tiff', options);\n}\n\n/**\n * Use these AVIF options for output image.\n *\n * AVIF image sequences are not supported.\n * Prebuilt binaries support a bitdepth of 8 only.\n *\n * @example\n * const data = await sharp(input)\n * .avif({ effort: 2 })\n * .toBuffer();\n *\n * @example\n * const data = await sharp(input)\n * .avif({ lossless: true })\n * .toBuffer();\n *\n * @since 0.27.0\n *\n * @param {Object} [options] - output options\n * @param {number} [options.quality=50] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction avif (options) {\n return this.heif({ ...options, compression: 'av1' });\n}\n\n/**\n * Use these HEIF options for output image.\n *\n * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a\n * globally-installed libvips compiled with support for libheif, libde265 and x265.\n *\n * @example\n * const data = await sharp(input)\n * .heif({ compression: 'hevc' })\n * .toBuffer();\n *\n * @since 0.23.0\n *\n * @param {Object} options - output options\n * @param {string} options.compression - compression format: av1, hevc\n * @param {number} [options.quality=50] - quality, integer 1-100\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest)\n * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling\n * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction heif (options) {\n if (is.object(options)) {\n if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) {\n this.options.heifCompression = options.compression;\n } else {\n throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression);\n }\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n this.options.heifQuality = options.quality;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n }\n if (is.defined(options.lossless)) {\n if (is.bool(options.lossless)) {\n this.options.heifLossless = options.lossless;\n } else {\n throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) {\n this.options.heifEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort);\n }\n }\n if (is.defined(options.chromaSubsampling)) {\n if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {\n this.options.heifChromaSubsampling = options.chromaSubsampling;\n } else {\n throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);\n }\n }\n if (is.defined(options.bitdepth)) {\n if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) {\n if (options.bitdepth !== 8 && this.constructor.versions.heif) {\n throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth);\n }\n this.options.heifBitdepth = options.bitdepth;\n } else {\n throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth);\n }\n }\n } else {\n throw is.invalidParameterError('options', 'Object', options);\n }\n return this._updateFormatOut('heif', options);\n}\n\n/**\n * Use these JPEG-XL (JXL) options for output image.\n *\n * This feature is experimental, please do not use in production systems.\n *\n * Requires libvips compiled with support for libjxl.\n * The prebuilt binaries do not include this - see\n * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.\n *\n * Image metadata (EXIF, XMP) is unsupported.\n *\n * @since 0.31.3\n *\n * @param {Object} [options] - output options\n * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality)\n * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified\n * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality)\n * @param {boolean} [options.lossless=false] - use lossless compression\n * @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest)\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction jxl (options) {\n if (is.object(options)) {\n if (is.defined(options.quality)) {\n if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {\n // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644\n this.options.jxlDistance = options.quality >= 30\n ? 0.1 + (100 - options.quality) * 0.09\n : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25;\n } else {\n throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);\n }\n } else if (is.defined(options.distance)) {\n if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) {\n this.options.jxlDistance = options.distance;\n } else {\n throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance);\n }\n }\n if (is.defined(options.decodingTier)) {\n if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) {\n this.options.jxlDecodingTier = options.decodingTier;\n } else {\n throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier);\n }\n }\n if (is.defined(options.lossless)) {\n if (is.bool(options.lossless)) {\n this.options.jxlLossless = options.lossless;\n } else {\n throw is.invalidParameterError('lossless', 'boolean', options.lossless);\n }\n }\n if (is.defined(options.effort)) {\n if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) {\n this.options.jxlEffort = options.effort;\n } else {\n throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort);\n }\n }\n }\n return this._updateFormatOut('jxl', options);\n}\n\n/**\n * Force output to be raw, uncompressed pixel data.\n * Pixel ordering is left-to-right, top-to-bottom, without padding.\n * Channel ordering will be RGB or RGBA for non-greyscale colourspaces.\n *\n * @example\n * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input\n * const { data, info } = await sharp('input.jpg')\n * .raw()\n * .toBuffer({ resolveWithObject: true });\n *\n * @example\n * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input\n * const data = await sharp('input.png')\n * .ensureAlpha()\n * .extractChannel(3)\n * .toColourspace('b-w')\n * .raw({ depth: 'ushort' })\n * .toBuffer();\n *\n * @param {Object} [options] - output options\n * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex\n * @returns {Sharp}\n * @throws {Error} Invalid options\n */\nfunction raw (options) {\n if (is.object(options)) {\n if (is.defined(options.depth)) {\n if (is.string(options.depth) && is.inArray(options.depth,\n ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex']\n )) {\n this.options.rawDepth = options.depth;\n } else {\n throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth);\n }\n }\n }\n return this._updateFormatOut('raw');\n}\n\n/**\n * Use tile-based deep zoom (image pyramid) output.\n *\n * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions.\n * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format.\n *\n * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`.\n *\n * Requires libvips compiled with support for libgsf.\n * The prebuilt binaries do not include this - see\n * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}.\n *\n * @example\n * sharp('input.tiff')\n * .png()\n * .tile({\n * size: 512\n * })\n * .toFile('output.dz', function(err, info) {\n * // output.dzi is the Deep Zoom XML definition\n * // output_files contains 512x512 tiles grouped by zoom level\n * });\n *\n * @example\n * const zipFileWithTiles = await sharp(input)\n * .tile({ basename: \"tiles\" })\n * .toBuffer();\n *\n * @example\n * const iiififier = sharp().tile({ layout: \"iiif\" });\n * readableStream\n * .pipe(iiififier)\n * .pipe(writeableStream);\n *\n * @param {Object} [options]\n * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192.\n * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192.\n * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90.\n * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency.\n * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout.\n * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise.\n * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file).\n * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`.\n * @param {boolean} [options.centre=false] centre image in tile.\n * @param {boolean} [options.center=false] alternative spelling of centre.\n * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json`\n * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`.\n * @returns {Sharp}\n * @throws {Error} Invalid parameters\n */\nfunction tile (options) {\n if (is.object(options)) {\n // Size of square tiles, in pixels\n if (is.defined(options.size)) {\n if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) {\n this.options.tileSize = options.size;\n } else {\n throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size);\n }\n }\n // Overlap of tiles, in pixels\n if (is.defined(options.overlap)) {\n if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) {\n if (options.overlap > this.options.tileSize) {\n throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap);\n }\n this.options.tileOverlap = options.overlap;\n } else {\n throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap);\n }\n }\n // Container\n if (is.defined(options.container)) {\n if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) {\n this.options.tileContainer = options.container;\n } else {\n throw is.invalidParameterError('container', 'one of: fs, zip', options.container);\n }\n }\n // Layout\n if (is.defined(options.layout)) {\n if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) {\n this.options.tileLayout = options.layout;\n } else {\n throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout);\n }\n }\n // Angle of rotation,\n if (is.defined(options.angle)) {\n if (is.integer(options.angle) && !(options.angle % 90)) {\n this.options.tileAngle = options.angle;\n } else {\n throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle);\n }\n }\n // Background colour\n this._setBackgroundColourOption('tileBackground', options.background);\n // Depth of tiles\n if (is.defined(options.depth)) {\n if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) {\n this.options.tileDepth = options.depth;\n } else {\n throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth);\n }\n }\n // Threshold to skip blank tiles\n if (is.defined(options.skipBlanks)) {\n if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) {\n this.options.tileSkipBlanks = options.skipBlanks;\n } else {\n throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks);\n }\n } else if (is.defined(options.layout) && options.layout === 'google') {\n this.options.tileSkipBlanks = 5;\n }\n // Center image in tile\n const centre = is.bool(options.center) ? options.center : options.centre;\n if (is.defined(centre)) {\n this._setBooleanOption('tileCentre', centre);\n }\n // @id attribute for IIIF layout\n if (is.defined(options.id)) {\n if (is.string(options.id)) {\n this.options.tileId = options.id;\n } else {\n throw is.invalidParameterError('id', 'string', options.id);\n }\n }\n // Basename for zip container\n if (is.defined(options.basename)) {\n if (is.string(options.basename)) {\n this.options.tileBasename = options.basename;\n } else {\n throw is.invalidParameterError('basename', 'string', options.basename);\n }\n }\n }\n // Format\n if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) {\n this.options.tileFormat = this.options.formatOut;\n } else if (this.options.formatOut !== 'input') {\n throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut);\n }\n return this._updateFormatOut('dz');\n}\n\n/**\n * Set a timeout for processing, in seconds.\n * Use a value of zero to continue processing indefinitely, the default behaviour.\n *\n * The clock starts when libvips opens an input image for processing.\n * Time spent waiting for a libuv thread to become available is not included.\n *\n * @example\n * // Ensure processing takes no longer than 3 seconds\n * try {\n * const data = await sharp(input)\n * .blur(1000)\n * .timeout({ seconds: 3 })\n * .toBuffer();\n * } catch (err) {\n * if (err.message.includes('timeout')) { ... }\n * }\n *\n * @since 0.29.2\n *\n * @param {Object} options\n * @param {number} options.seconds - Number of seconds after which processing will be stopped\n * @returns {Sharp}\n */\nfunction timeout (options) {\n if (!is.plainObject(options)) {\n throw is.invalidParameterError('options', 'object', options);\n }\n if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) {\n this.options.timeoutSeconds = options.seconds;\n } else {\n throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds);\n }\n return this;\n}\n\n/**\n * Update the output format unless options.force is false,\n * in which case revert to input format.\n * @private\n * @param {string} formatOut\n * @param {Object} [options]\n * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format\n * @returns {Sharp}\n */\nfunction _updateFormatOut (formatOut, options) {\n if (!(is.object(options) && options.force === false)) {\n this.options.formatOut = formatOut;\n }\n return this;\n}\n\n/**\n * Update a boolean attribute of the this.options Object.\n * @private\n * @param {string} key\n * @param {boolean} val\n * @throws {Error} Invalid key\n */\nfunction _setBooleanOption (key, val) {\n if (is.bool(val)) {\n this.options[key] = val;\n } else {\n throw is.invalidParameterError(key, 'boolean', val);\n }\n}\n\n/**\n * Called by a WriteableStream to notify us it is ready for data.\n * @private\n */\nfunction _read () {\n /* istanbul ignore else */\n if (!this.options.streamOut) {\n this.options.streamOut = true;\n const stack = Error();\n this._pipeline(undefined, stack);\n }\n}\n\n/**\n * Invoke the C++ image processing pipeline\n * Supports callback, stream and promise variants\n * @private\n */\nfunction _pipeline (callback, stack) {\n if (typeof callback === 'function') {\n // output=file/buffer\n if (this._isStreamInput()) {\n // output=file/buffer, input=stream\n this.on('finish', () => {\n this._flattenBufferIn();\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, data, info);\n }\n });\n });\n } else {\n // output=file/buffer, input=file/buffer\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n callback(is.nativeError(err, stack));\n } else {\n callback(null, data, info);\n }\n });\n }\n return this;\n } else if (this.options.streamOut) {\n // output=stream\n if (this._isStreamInput()) {\n // output=stream, input=stream\n this.once('finish', () => {\n this._flattenBufferIn();\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n this.emit('error', is.nativeError(err, stack));\n } else {\n this.emit('info', info);\n this.push(data);\n }\n this.push(null);\n this.on('end', () => this.emit('close'));\n });\n });\n if (this.streamInFinished) {\n this.emit('finish');\n }\n } else {\n // output=stream, input=file/buffer\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n this.emit('error', is.nativeError(err, stack));\n } else {\n this.emit('info', info);\n this.push(data);\n }\n this.push(null);\n this.on('end', () => this.emit('close'));\n });\n }\n return this;\n } else {\n // output=promise\n if (this._isStreamInput()) {\n // output=promise, input=stream\n return new Promise((resolve, reject) => {\n this.once('finish', () => {\n this._flattenBufferIn();\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n if (this.options.resolveWithObject) {\n resolve({ data, info });\n } else {\n resolve(data);\n }\n }\n });\n });\n });\n } else {\n // output=promise, input=file/buffer\n return new Promise((resolve, reject) => {\n sharp.pipeline(this.options, (err, data, info) => {\n if (err) {\n reject(is.nativeError(err, stack));\n } else {\n if (this.options.resolveWithObject) {\n resolve({ data, info });\n } else {\n resolve(data);\n }\n }\n });\n });\n }\n }\n}\n\n/**\n * Decorate the Sharp prototype with output-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Object.assign(Sharp.prototype, {\n // Public\n toFile,\n toBuffer,\n keepExif,\n withExif,\n withExifMerge,\n keepIccProfile,\n withIccProfile,\n keepMetadata,\n withMetadata,\n toFormat,\n jpeg,\n jp2,\n png,\n webp,\n tiff,\n avif,\n heif,\n jxl,\n gif,\n raw,\n tile,\n timeout,\n // Private\n _updateFormatOut,\n _setBooleanOption,\n _read,\n _pipeline\n });\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst events = require('node:events');\nconst detectLibc = require('detect-libc');\n\nconst is = require('./is');\nconst { runtimePlatformArch } = require('./libvips');\nconst sharp = require('./sharp');\n\nconst runtimePlatform = runtimePlatformArch();\nconst libvipsVersion = sharp.libvipsVersion();\n\n/**\n * An Object containing nested boolean values representing the available input and output formats/methods.\n * @member\n * @example\n * console.log(sharp.format);\n * @returns {Object}\n */\nconst format = sharp.format();\nformat.heif.output.alias = ['avif', 'heic'];\nformat.jpeg.output.alias = ['jpe', 'jpg'];\nformat.tiff.output.alias = ['tif'];\nformat.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx'];\n\n/**\n * An Object containing the available interpolators and their proper values\n * @readonly\n * @enum {string}\n */\nconst interpolators = {\n /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */\n nearest: 'nearest',\n /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */\n bilinear: 'bilinear',\n /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */\n bicubic: 'bicubic',\n /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some \"[acutance](http://en.wikipedia.org/wiki/Acutance)\" but typically reduces performance by a factor of 2. */\n locallyBoundedBicubic: 'lbb',\n /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */\n nohalo: 'nohalo',\n /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents \"staircasing\" when enlarging. */\n vertexSplitQuadraticBasisSpline: 'vsqbs'\n};\n\n/**\n * An Object containing the version numbers of sharp, libvips\n * and (when using prebuilt binaries) its dependencies.\n *\n * @member\n * @example\n * console.log(sharp.versions);\n */\nlet versions = {\n vips: libvipsVersion.semver\n};\n/* istanbul ignore next */\nif (!libvipsVersion.isGlobal) {\n if (!libvipsVersion.isWasm) {\n try {\n versions = require(`@img/sharp-${runtimePlatform}/versions`);\n } catch (_) {\n try {\n versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);\n } catch (_) {}\n }\n } else {\n try {\n versions = require('@img/sharp-wasm32/versions');\n } catch (_) {}\n }\n}\nversions.sharp = require('../package.json').version;\n\n/* istanbul ignore next */\nif (versions.heif && format.heif) {\n // Prebuilt binaries provide AV1\n format.heif.input.fileSuffix = ['.avif'];\n format.heif.output.alias = ['avif'];\n}\n\n/**\n * Gets or, when options are provided, sets the limits of _libvips'_ operation cache.\n * Existing entries in the cache will be trimmed after any change in limits.\n * This method always returns cache statistics,\n * useful for determining how much working memory is required for a particular task.\n *\n * @example\n * const stats = sharp.cache();\n * @example\n * sharp.cache( { items: 200 } );\n * sharp.cache( { files: 0 } );\n * sharp.cache(false);\n *\n * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching\n * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache\n * @param {number} [options.files=20] - is the maximum number of files to hold open\n * @param {number} [options.items=100] - is the maximum number of operations to cache\n * @returns {Object}\n */\nfunction cache (options) {\n if (is.bool(options)) {\n if (options) {\n // Default cache settings of 50MB, 20 files, 100 items\n return sharp.cache(50, 20, 100);\n } else {\n return sharp.cache(0, 0, 0);\n }\n } else if (is.object(options)) {\n return sharp.cache(options.memory, options.files, options.items);\n } else {\n return sharp.cache();\n }\n}\ncache(true);\n\n/**\n * Gets or, when a concurrency is provided, sets\n * the maximum number of threads _libvips_ should use to process _each image_.\n * These are from a thread pool managed by glib,\n * which helps avoid the overhead of creating new threads.\n *\n * This method always returns the current concurrency.\n *\n * The default value is the number of CPU cores,\n * except when using glibc-based Linux without jemalloc,\n * where the default is `1` to help reduce memory fragmentation.\n *\n * A value of `0` will reset this to the number of CPU cores.\n *\n * Some image format libraries spawn additional threads,\n * e.g. libaom manages its own 4 threads when encoding AVIF images,\n * and these are independent of the value set here.\n *\n * The maximum number of images that sharp can process in parallel\n * is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,\n * which defaults to 4.\n *\n * https://nodejs.org/api/cli.html#uv_threadpool_sizesize\n *\n * For example, by default, a machine with 8 CPU cores will process\n * 4 images in parallel and use up to 8 threads per image,\n * so there will be up to 32 concurrent threads.\n *\n * @example\n * const threads = sharp.concurrency(); // 4\n * sharp.concurrency(2); // 2\n * sharp.concurrency(0); // 4\n *\n * @param {number} [concurrency]\n * @returns {number} concurrency\n */\nfunction concurrency (concurrency) {\n return sharp.concurrency(is.integer(concurrency) ? concurrency : null);\n}\n/* istanbul ignore next */\nif (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {\n // Reduce default concurrency to 1 when using glibc memory allocator\n sharp.concurrency(1);\n} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {\n // Reduce default concurrency when musl thread over-subscription detected\n sharp.concurrency(require('node:os').availableParallelism());\n}\n\n/**\n * An EventEmitter that emits a `change` event when a task is either:\n * - queued, waiting for _libuv_ to provide a worker thread\n * - complete\n * @member\n * @example\n * sharp.queue.on('change', function(queueLength) {\n * console.log('Queue contains ' + queueLength + ' task(s)');\n * });\n */\nconst queue = new events.EventEmitter();\n\n/**\n * Provides access to internal task counters.\n * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.\n * - process is the number of resize tasks currently being processed.\n *\n * @example\n * const counters = sharp.counters(); // { queue: 2, process: 4 }\n *\n * @returns {Object}\n */\nfunction counters () {\n return sharp.counters();\n}\n\n/**\n * Get and set use of SIMD vector unit instructions.\n * Requires libvips to have been compiled with highway support.\n *\n * Improves the performance of `resize`, `blur` and `sharpen` operations\n * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.\n *\n * @example\n * const simd = sharp.simd();\n * // simd is `true` if the runtime use of highway is currently enabled\n * @example\n * const simd = sharp.simd(false);\n * // prevent libvips from using highway at runtime\n *\n * @param {boolean} [simd=true]\n * @returns {boolean}\n */\nfunction simd (simd) {\n return sharp.simd(is.bool(simd) ? simd : null);\n}\n\n/**\n * Block libvips operations at runtime.\n *\n * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,\n * which when set will block all \"untrusted\" operations.\n *\n * @since 0.32.4\n *\n * @example <caption>Block all TIFF input.</caption>\n * sharp.block({\n * operation: ['VipsForeignLoadTiff']\n * });\n *\n * @param {Object} options\n * @param {Array<string>} options.operation - List of libvips low-level operation names to block.\n */\nfunction block (options) {\n if (is.object(options)) {\n if (Array.isArray(options.operation) && options.operation.every(is.string)) {\n sharp.block(options.operation, true);\n } else {\n throw is.invalidParameterError('operation', 'Array<string>', options.operation);\n }\n } else {\n throw is.invalidParameterError('options', 'object', options);\n }\n}\n\n/**\n * Unblock libvips operations at runtime.\n *\n * This is useful for defining a list of allowed operations.\n *\n * @since 0.32.4\n *\n * @example <caption>Block all input except WebP from the filesystem.</caption>\n * sharp.block({\n * operation: ['VipsForeignLoad']\n * });\n * sharp.unblock({\n * operation: ['VipsForeignLoadWebpFile']\n * });\n *\n * @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>\n * sharp.block({\n * operation: ['VipsForeignLoad']\n * });\n * sharp.unblock({\n * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']\n * });\n *\n * @param {Object} options\n * @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.\n */\nfunction unblock (options) {\n if (is.object(options)) {\n if (Array.isArray(options.operation) && options.operation.every(is.string)) {\n sharp.block(options.operation, false);\n } else {\n throw is.invalidParameterError('operation', 'Array<string>', options.operation);\n }\n } else {\n throw is.invalidParameterError('options', 'object', options);\n }\n}\n\n/**\n * Decorate the Sharp class with utility-related functions.\n * @private\n */\nmodule.exports = function (Sharp) {\n Sharp.cache = cache;\n Sharp.concurrency = concurrency;\n Sharp.counters = counters;\n Sharp.simd = simd;\n Sharp.format = format;\n Sharp.interpolators = interpolators;\n Sharp.versions = versions;\n Sharp.queue = queue;\n Sharp.block = block;\n Sharp.unblock = unblock;\n};\n","// Copyright 2013 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst Sharp = require('./constructor');\nrequire('./input')(Sharp);\nrequire('./resize')(Sharp);\nrequire('./composite')(Sharp);\nrequire('./operation')(Sharp);\nrequire('./colour')(Sharp);\nrequire('./channel')(Sharp);\nrequire('./output')(Sharp);\nrequire('./utility')(Sharp);\n\nmodule.exports = Sharp;\n","/**\n * Image Format Detection\n *\n * Detect image format from magic bytes.\n */\n\n/**\n * Supported image formats\n */\nexport type ImageFormat = 'png' | 'jpeg' | 'webp' | 'gif' | 'avif';\n\n/**\n * Magic bytes for each format\n */\nconst MAGIC_BYTES: Record<ImageFormat, { bytes: number[]; offset?: number; check?: number[] }> = {\n png: { bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] },\n jpeg: { bytes: [0xff, 0xd8, 0xff] },\n gif: { bytes: [0x47, 0x49, 0x46, 0x38] }, // GIF8\n webp: { bytes: [0x52, 0x49, 0x46, 0x46], offset: 8, check: [0x57, 0x45, 0x42, 0x50] }, // RIFF....WEBP\n avif: { bytes: [0x00, 0x00, 0x00], offset: 4, check: [0x66, 0x74, 0x79, 0x70] }, // ....ftyp (then check for avif/avis)\n};\n\n/**\n * Detect image format from magic bytes.\n *\n * @param buffer - Image data\n * @returns Detected format, or null if not recognized\n */\nexport function detectImageFormat(buffer: Uint8Array): ImageFormat | null {\n if (buffer.length < 12) return null;\n\n // Check PNG\n if (matchesBytes(buffer, MAGIC_BYTES.png.bytes)) {\n return 'png';\n }\n\n // Check JPEG\n if (matchesBytes(buffer, MAGIC_BYTES.jpeg.bytes)) {\n return 'jpeg';\n }\n\n // Check GIF\n if (matchesBytes(buffer, MAGIC_BYTES.gif.bytes)) {\n return 'gif';\n }\n\n // Check WebP (RIFF....WEBP)\n if (\n matchesBytes(buffer, MAGIC_BYTES.webp.bytes) &&\n matchesBytes(buffer, MAGIC_BYTES.webp.check!, MAGIC_BYTES.webp.offset!)\n ) {\n return 'webp';\n }\n\n // Check AVIF (....ftyp then avif or avis brand)\n if (matchesBytes(buffer, MAGIC_BYTES.avif.check!, MAGIC_BYTES.avif.offset!)) {\n // AVIF uses ftyp box with 'avif' or 'avis' brand\n const brand = String.fromCharCode(...buffer.slice(8, 12));\n if (brand === 'avif' || brand === 'avis' || brand === 'mif1' || brand === 'miaf') {\n return 'avif';\n }\n }\n\n return null;\n}\n\n/**\n * Check if buffer starts with given bytes at offset\n */\nfunction matchesBytes(buffer: Uint8Array, bytes: number[], offset = 0): boolean {\n if (buffer.length < offset + bytes.length) return false;\n for (let i = 0; i < bytes.length; i++) {\n if (buffer[offset + i] !== bytes[i]) return false;\n }\n return true;\n}\n\n/**\n * Get MIME type for image format\n */\nexport function getMimeType(format: ImageFormat): string {\n const mimeTypes: Record<ImageFormat, string> = {\n png: 'image/png',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n avif: 'image/avif',\n };\n return mimeTypes[format];\n}\n\n/**\n * Get file extension for image format\n */\nexport function getExtension(format: ImageFormat): string {\n const extensions: Record<ImageFormat, string> = {\n png: 'png',\n jpeg: 'jpg',\n webp: 'webp',\n gif: 'gif',\n avif: 'avif',\n };\n return extensions[format];\n}\n","/**\n * Image Dimensions Detection\n *\n * Get image dimensions without fully decoding the image.\n * Reads only the header bytes needed to determine dimensions.\n */\n\nimport { detectImageFormat, type ImageFormat } from './format.js';\n\n/**\n * Image dimensions result\n */\nexport interface ImageDimensions {\n width: number;\n height: number;\n format: ImageFormat;\n}\n\n/**\n * Get image dimensions without fully decoding the image.\n *\n * Reads only the header bytes needed to determine dimensions.\n *\n * @param buffer - Image data\n * @returns Dimensions and format, or null if not recognized\n */\nexport function getImageDimensions(buffer: Uint8Array): ImageDimensions | null {\n const format = detectImageFormat(buffer);\n if (!format) return null;\n\n switch (format) {\n case 'png':\n return getPngDimensions(buffer);\n case 'jpeg':\n return getJpegDimensions(buffer);\n case 'gif':\n return getGifDimensions(buffer);\n case 'webp':\n return getWebpDimensions(buffer);\n case 'avif':\n return getAvifDimensions(buffer);\n default:\n return null;\n }\n}\n\n/**\n * Get PNG dimensions from IHDR chunk\n */\nfunction getPngDimensions(buffer: Uint8Array): ImageDimensions | null {\n // PNG structure: signature (8 bytes) + IHDR chunk\n // IHDR: length (4) + type (4) + width (4) + height (4) + ...\n if (buffer.length < 24) return null;\n\n // Verify IHDR chunk type at offset 12\n const ihdr = String.fromCharCode(buffer[12]!, buffer[13]!, buffer[14]!, buffer[15]!);\n if (ihdr !== 'IHDR') return null;\n\n // Width and height are big-endian at offset 16 and 20\n const width = readUint32BE(buffer, 16);\n const height = readUint32BE(buffer, 20);\n\n if (width <= 0 || height <= 0) return null;\n\n return { width, height, format: 'png' };\n}\n\n/**\n * Get JPEG dimensions by parsing SOF markers\n */\nfunction getJpegDimensions(buffer: Uint8Array): ImageDimensions | null {\n if (buffer.length < 4) return null;\n\n let offset = 2; // Skip SOI marker\n\n while (offset < buffer.length - 8) {\n // Look for marker\n if (buffer[offset] !== 0xff) {\n offset++;\n continue;\n }\n\n const marker = buffer[offset + 1]!;\n\n // SOF markers (except SOF4 which is DHT)\n // SOF0-SOF3, SOF5-SOF7, SOF9-SOF11, SOF13-SOF15\n const isSOF =\n (marker >= 0xc0 && marker <= 0xc3) ||\n (marker >= 0xc5 && marker <= 0xc7) ||\n (marker >= 0xc9 && marker <= 0xcb) ||\n (marker >= 0xcd && marker <= 0xcf);\n\n if (isSOF) {\n // SOF: FF Cx LL LL P HH HH WW WW\n // Length at offset+2 (2 bytes), precision at offset+4\n // Height at offset+5 (2 bytes), Width at offset+7 (2 bytes)\n if (offset + 9 >= buffer.length) return null;\n\n const height = readUint16BE(buffer, offset + 5);\n const width = readUint16BE(buffer, offset + 7);\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'jpeg' };\n }\n }\n\n // Skip to next marker\n if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) {\n // Standalone markers\n offset += 2;\n } else if (marker === 0xff) {\n // Padding\n offset++;\n } else {\n // Skip segment\n const segmentLength = readUint16BE(buffer, offset + 2);\n offset += 2 + segmentLength;\n }\n }\n\n return null;\n}\n\n/**\n * Get GIF dimensions from logical screen descriptor\n */\nfunction getGifDimensions(buffer: Uint8Array): ImageDimensions | null {\n // GIF: signature (6) + logical screen descriptor (7)\n // Width at offset 6 (2 bytes LE), Height at offset 8 (2 bytes LE)\n if (buffer.length < 10) return null;\n\n const width = readUint16LE(buffer, 6);\n const height = readUint16LE(buffer, 8);\n\n if (width <= 0 || height <= 0) return null;\n\n return { width, height, format: 'gif' };\n}\n\n/**\n * Get WebP dimensions\n */\nfunction getWebpDimensions(buffer: Uint8Array): ImageDimensions | null {\n if (buffer.length < 30) return null;\n\n // Check for VP8 chunk at offset 12\n const chunk = String.fromCharCode(buffer[12]!, buffer[13]!, buffer[14]!, buffer[15]!);\n\n if (chunk === 'VP8 ') {\n // Lossy WebP: VP8 bitstream\n // Frame tag at offset 20, then 3-byte frame tag, then dimensions\n if (buffer.length < 30) return null;\n\n // Skip to frame dimensions (after signature)\n const width = (buffer[26]! | (buffer[27]! << 8)) & 0x3fff;\n const height = (buffer[28]! | (buffer[29]! << 8)) & 0x3fff;\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'webp' };\n }\n } else if (chunk === 'VP8L') {\n // Lossless WebP\n if (buffer.length < 25) return null;\n\n // Signature byte at offset 20, then dimensions packed in 4 bytes\n const bits = readUint32LE(buffer, 21);\n const width = (bits & 0x3fff) + 1;\n const height = ((bits >> 14) & 0x3fff) + 1;\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'webp' };\n }\n } else if (chunk === 'VP8X') {\n // Extended WebP with VP8X chunk\n if (buffer.length < 30) return null;\n\n // Canvas dimensions at offset 24 (3 bytes each, LE, +1)\n const width =\n (buffer[24]! | (buffer[25]! << 8) | (buffer[26]! << 16)) + 1;\n const height =\n (buffer[27]! | (buffer[28]! << 8) | (buffer[29]! << 16)) + 1;\n\n if (width > 0 && height > 0) {\n return { width, height, format: 'webp' };\n }\n }\n\n return null;\n}\n\n/**\n * Get AVIF dimensions from ISPE box\n * AVIF uses HEIF container format with ISOBMFF boxes\n */\nfunction getAvifDimensions(buffer: Uint8Array): ImageDimensions | null {\n // This is a simplified parser - AVIF uses complex ISOBMFF structure\n // For a complete implementation, we'd need to parse the full box structure\n // Here we search for the ispe (image spatial extents) box\n\n if (buffer.length < 32) return null;\n\n // Search for 'ispe' box marker\n for (let i = 0; i < buffer.length - 16; i++) {\n if (\n buffer[i] === 0x69 && // 'i'\n buffer[i + 1] === 0x73 && // 's'\n buffer[i + 2] === 0x70 && // 'p'\n buffer[i + 3] === 0x65 // 'e'\n ) {\n // Found ispe box, dimensions are at offset +4 (version/flags) +4 (width) +4 (height)\n // ispe structure: type (4) + version (1) + flags (3) + width (4) + height (4)\n const offset = i + 4; // Skip 'ispe'\n if (offset + 12 > buffer.length) continue;\n\n const width = readUint32BE(buffer, offset + 4);\n const height = readUint32BE(buffer, offset + 8);\n\n if (width > 0 && height > 0 && width < 65536 && height < 65536) {\n return { width, height, format: 'avif' };\n }\n }\n }\n\n return null;\n}\n\n/**\n * Read big-endian uint32\n */\nfunction readUint32BE(buffer: Uint8Array, offset: number): number {\n return (\n ((buffer[offset]! << 24) |\n (buffer[offset + 1]! << 16) |\n (buffer[offset + 2]! << 8) |\n buffer[offset + 3]!) >>>\n 0\n );\n}\n\n/**\n * Read big-endian uint16\n */\nfunction readUint16BE(buffer: Uint8Array, offset: number): number {\n return (buffer[offset]! << 8) | buffer[offset + 1]!;\n}\n\n/**\n * Read little-endian uint16\n */\nfunction readUint16LE(buffer: Uint8Array, offset: number): number {\n return buffer[offset]! | (buffer[offset + 1]! << 8);\n}\n\n/**\n * Read little-endian uint32\n */\nfunction readUint32LE(buffer: Uint8Array, offset: number): number {\n return (\n (buffer[offset]! |\n (buffer[offset + 1]! << 8) |\n (buffer[offset + 2]! << 16) |\n (buffer[offset + 3]! << 24)) >>>\n 0\n );\n}\n","/**\n * Thumbnail Generation\n *\n * Create thumbnails from image data.\n * Works in both Node.js (sharp) and browser (canvas) environments.\n */\n\nimport { detectImageFormat, getMimeType, type ImageFormat } from './format.js';\nimport { getImageDimensions } from './dimensions.js';\nimport { ValidationError, ParseError } from '@character-foundry/core';\n\n/**\n * Thumbnail generation options\n */\nexport interface ThumbnailOptions {\n /** Maximum dimension (width or height). Default: 400 */\n maxSize?: number;\n /** Output format. Default: 'webp' */\n format?: 'webp' | 'jpeg' | 'png';\n /** Quality (0-1). Default: 0.8 */\n quality?: number;\n /** Fallback format if primary unsupported. Default: 'jpeg' */\n fallbackFormat?: 'jpeg' | 'png';\n /** Timeout in ms. Default: 10000 */\n timeout?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<ThumbnailOptions> = {\n maxSize: 400,\n format: 'webp',\n quality: 0.8,\n fallbackFormat: 'jpeg',\n timeout: 10000,\n};\n\n/**\n * Check if we're in Node.js environment\n */\nconst isNode = typeof window === 'undefined' && typeof process !== 'undefined';\n\n/**\n * Create a thumbnail from image data.\n *\n * Works in both Node.js (sharp) and browser (canvas) environments.\n *\n * @param imageData - Source image data\n * @param options - Thumbnail options\n * @returns Thumbnail image data\n */\nexport async function createThumbnail(\n imageData: Uint8Array,\n options: ThumbnailOptions = {}\n): Promise<Uint8Array> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n // Verify input is a valid image\n const format = detectImageFormat(imageData);\n if (!format) {\n throw new ValidationError('Input is not a recognized image format', 'imageData');\n }\n\n // Get dimensions to check if resize is needed\n const dims = getImageDimensions(imageData);\n if (!dims) {\n throw new ParseError('Could not determine image dimensions');\n }\n\n // Check if resize is needed\n const needsResize = dims.width > opts.maxSize || dims.height > opts.maxSize;\n\n if (isNode) {\n return createThumbnailNode(imageData, opts, needsResize);\n } else {\n return createThumbnailBrowser(imageData, opts, needsResize, format);\n }\n}\n\n/**\n * Create thumbnail using sharp (Node.js)\n */\nasync function createThumbnailNode(\n imageData: Uint8Array,\n options: Required<ThumbnailOptions>,\n needsResize: boolean\n): Promise<Uint8Array> {\n // Dynamically import sharp\n let sharp: typeof import('sharp');\n try {\n sharp = (await import('sharp')).default;\n } catch {\n throw new ValidationError(\n 'sharp is required for thumbnail generation in Node.js. Install with: npm install sharp',\n 'dependency'\n );\n }\n\n let pipeline = sharp(Buffer.from(imageData));\n\n if (needsResize) {\n pipeline = pipeline.resize(options.maxSize, options.maxSize, {\n fit: 'inside',\n withoutEnlargement: true,\n });\n }\n\n // Apply format conversion\n const quality = Math.round(options.quality * 100);\n\n switch (options.format) {\n case 'webp':\n pipeline = pipeline.webp({ quality });\n break;\n case 'jpeg':\n pipeline = pipeline.jpeg({ quality });\n break;\n case 'png':\n pipeline = pipeline.png({ compressionLevel: 9 });\n break;\n }\n\n const result = await pipeline.toBuffer();\n return new Uint8Array(result);\n}\n\n/**\n * Create thumbnail using Canvas API (Browser)\n */\nasync function createThumbnailBrowser(\n imageData: Uint8Array,\n options: Required<ThumbnailOptions>,\n needsResize: boolean,\n inputFormat: ImageFormat\n): Promise<Uint8Array> {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(`Thumbnail generation timed out after ${options.timeout}ms`));\n }, options.timeout);\n\n try {\n // Create blob from image data\n const mimeType = getMimeType(inputFormat);\n // Need to slice to handle potential SharedArrayBuffer\n const blob = new Blob([new Uint8Array(imageData)], { type: mimeType });\n const url = URL.createObjectURL(blob);\n\n const img = new Image();\n\n img.onload = () => {\n clearTimeout(timeoutId);\n URL.revokeObjectURL(url);\n\n try {\n // Calculate target dimensions\n let targetWidth = img.width;\n let targetHeight = img.height;\n\n if (needsResize) {\n const scale = Math.min(\n options.maxSize / img.width,\n options.maxSize / img.height\n );\n targetWidth = Math.round(img.width * scale);\n targetHeight = Math.round(img.height * scale);\n }\n\n // Create canvas and draw\n const canvas = document.createElement('canvas');\n canvas.width = targetWidth;\n canvas.height = targetHeight;\n\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n reject(new Error('Could not get canvas context'));\n return;\n }\n\n ctx.drawImage(img, 0, 0, targetWidth, targetHeight);\n\n // Try to export in requested format\n let outputMimeType = `image/${options.format}`;\n let dataUrl = canvas.toDataURL(outputMimeType, options.quality);\n\n // Check if format was supported (canvas falls back to PNG if unsupported)\n if (!dataUrl.startsWith(`data:${outputMimeType}`) && options.format === 'webp') {\n // WebP not supported, use fallback\n outputMimeType = `image/${options.fallbackFormat}`;\n dataUrl = canvas.toDataURL(outputMimeType, options.quality);\n }\n\n // Convert data URL to Uint8Array\n const base64 = dataUrl.split(',')[1]!;\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n\n resolve(bytes);\n } catch (err) {\n reject(err);\n }\n };\n\n img.onerror = () => {\n clearTimeout(timeoutId);\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n };\n\n img.src = url;\n } catch (err) {\n clearTimeout(timeoutId);\n reject(err);\n }\n });\n}\n\n/**\n * Calculate target dimensions while preserving aspect ratio\n */\nexport function calculateThumbnailDimensions(\n width: number,\n height: number,\n maxSize: number\n): { width: number; height: number } {\n if (width <= maxSize && height <= maxSize) {\n return { width, height };\n }\n\n const scale = Math.min(maxSize / width, maxSize / height);\n return {\n width: Math.round(width * scale),\n height: Math.round(height * scale),\n };\n}\n","/**\n * Common Types\n *\n * Shared types used across all card formats.\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * ISO 8601 date string schema\n */\nexport const ISO8601Schema = z.string().datetime();\n\n/**\n * UUID string schema\n */\nexport const UUIDSchema = z.string().uuid();\n\n/**\n * Card specification version schema\n */\nexport const SpecSchema = z.enum(['v2', 'v3']);\n\n/**\n * Source format identifier schema\n */\nexport const SourceFormatSchema = z.enum([\n 'png_v2', // PNG with 'chara' chunk (v2)\n 'png_v3', // PNG with 'ccv3' chunk (v3)\n 'json_v2', // Raw JSON v2\n 'json_v3', // Raw JSON v3\n 'charx', // ZIP with card.json (v3 spec)\n 'charx_risu', // ZIP with card.json + module.risum\n 'charx_jpeg', // JPEG with appended ZIP (read-only)\n 'voxta', // VoxPkg format\n]);\n\n/**\n * Original JSON shape schema\n */\nexport const OriginalShapeSchema = z.enum(['wrapped', 'unwrapped', 'legacy']);\n\n/**\n * Asset type identifier schema\n */\nexport const AssetTypeSchema = z.enum([\n 'icon',\n 'background',\n 'emotion',\n 'user_icon',\n 'sound',\n 'video',\n 'custom',\n 'x-risu-asset',\n]);\n\n/**\n * Asset descriptor schema (v3 spec)\n */\nexport const AssetDescriptorSchema = z.object({\n type: AssetTypeSchema,\n uri: z.string(),\n name: z.string(),\n ext: z.string(),\n});\n\n/**\n * Extracted asset with binary data schema\n */\nexport const ExtractedAssetSchema = z.object({\n descriptor: AssetDescriptorSchema,\n data: z.instanceof(Uint8Array),\n mimeType: z.string(),\n});\n\n// ============================================================================\n// TypeScript Types (inferred from Zod schemas)\n// ============================================================================\n\n/**\n * ISO 8601 date string\n */\nexport type ISO8601 = z.infer<typeof ISO8601Schema>;\n\n/**\n * UUID string\n */\nexport type UUID = z.infer<typeof UUIDSchema>;\n\n/**\n * Card specification version\n */\nexport type Spec = z.infer<typeof SpecSchema>;\n\n/**\n * Source format identifier\n */\nexport type SourceFormat = z.infer<typeof SourceFormatSchema>;\n\n/**\n * Original JSON shape\n */\nexport type OriginalShape = z.infer<typeof OriginalShapeSchema>;\n\n/**\n * Asset type identifier\n */\nexport type AssetType = z.infer<typeof AssetTypeSchema>;\n\n/**\n * Asset descriptor (v3 spec)\n */\nexport type AssetDescriptor = z.infer<typeof AssetDescriptorSchema>;\n\n/**\n * Extracted asset with binary data\n */\nexport type ExtractedAsset = z.infer<typeof ExtractedAssetSchema>;\n","/**\n * Character Card v2 Types\n *\n * Based on: https://github.com/malfoyslastname/character-card-spec-v2\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Lorebook entry schema for v2 cards\n */\nexport const CCv2LorebookEntrySchema = z.object({\n keys: z.array(z.string()).optional(), // Some tools use 'key' instead\n content: z.string(),\n enabled: z.boolean().default(true), // Default to enabled if missing\n insertion_order: z.preprocess((v) => v ?? 0, z.number().int()),\n // Optional fields - be lenient with nulls since wild data has them\n extensions: z.record(z.unknown()).optional(),\n case_sensitive: z.boolean().nullable().optional(),\n name: z.string().optional(),\n priority: z.number().int().nullable().optional(),\n id: z.number().int().nullable().optional(),\n comment: z.string().nullable().optional(),\n selective: z.boolean().nullable().optional(),\n secondary_keys: z.array(z.string()).nullable().optional(),\n constant: z.boolean().nullable().optional(),\n position: z.union([z.enum(['before_char', 'after_char']), z.number().int(), z.literal('')]).nullable().optional(),\n}).passthrough(); // Allow SillyTavern extensions like depth, probability, etc.\n\n/**\n * Character book (lorebook) schema for v2 cards\n */\nexport const CCv2CharacterBookSchema = z.object({\n name: z.string().optional(),\n description: z.string().optional(),\n scan_depth: z.number().int().nonnegative().optional(),\n token_budget: z.number().int().nonnegative().optional(),\n recursive_scanning: z.boolean().optional(),\n extensions: z.record(z.unknown()).optional(),\n entries: z.array(CCv2LorebookEntrySchema),\n});\n\n/**\n * Character Card v2 data structure schema\n */\nexport const CCv2DataSchema = z.object({\n // Core fields - use .default('') to handle missing fields in malformed cards\n name: z.string().default(''),\n description: z.string().default(''),\n personality: z.string().nullable().default(''), // Can be null in wild (141 cards)\n scenario: z.string().default(''),\n first_mes: z.string().default(''),\n mes_example: z.string().nullable().default(''), // Can be null in wild (186 cards)\n // Optional fields\n creator_notes: z.string().optional(),\n system_prompt: z.string().optional(),\n post_history_instructions: z.string().optional(),\n alternate_greetings: z.array(z.string()).optional(),\n character_book: CCv2CharacterBookSchema.optional().nullable(),\n tags: z.array(z.string()).optional(),\n creator: z.string().optional(),\n character_version: z.string().optional(),\n extensions: z.record(z.unknown()).optional(),\n});\n\n/**\n * Wrapped v2 card format schema (modern tools)\n */\nexport const CCv2WrappedSchema = z.object({\n spec: z.literal('chara_card_v2'),\n spec_version: z.literal('2.0'),\n data: CCv2DataSchema,\n});\n\n// ============================================================================\n// TypeScript Types (inferred from Zod schemas)\n// ============================================================================\n\n/**\n * Lorebook entry for v2 cards\n */\nexport type CCv2LorebookEntry = z.infer<typeof CCv2LorebookEntrySchema>;\n\n/**\n * Character book (lorebook) for v2 cards\n */\nexport type CCv2CharacterBook = z.infer<typeof CCv2CharacterBookSchema>;\n\n/**\n * Character Card v2 data structure\n */\nexport type CCv2Data = z.infer<typeof CCv2DataSchema>;\n\n/**\n * Wrapped v2 card format (modern tools)\n */\nexport type CCv2Wrapped = z.infer<typeof CCv2WrappedSchema>;\n\n// ============================================================================\n// Type Guards & Parsers\n// ============================================================================\n\n/**\n * Check if data is a wrapped v2 card\n */\nexport function isWrappedV2(data: unknown): data is CCv2Wrapped {\n return CCv2WrappedSchema.safeParse(data).success;\n}\n\n/**\n * Check if data looks like v2 card data (wrapped or unwrapped)\n */\nexport function isV2CardData(data: unknown): data is CCv2Data | CCv2Wrapped {\n return (\n CCv2WrappedSchema.safeParse(data).success ||\n CCv2DataSchema.safeParse(data).success\n );\n}\n\n/**\n * Parse and validate a wrapped v2 card\n */\nexport function parseWrappedV2(data: unknown): CCv2Wrapped {\n return CCv2WrappedSchema.parse(data);\n}\n\n/**\n * Parse and validate v2 card data\n */\nexport function parseV2Data(data: unknown): CCv2Data {\n return CCv2DataSchema.parse(data);\n}\n\n/**\n * Check if data looks like a wrapped V2 card structurally (without strict validation).\n * This is more lenient than isWrappedV2 - it just checks structure, not full schema validity.\n */\nexport function looksLikeWrappedV2(data: unknown): data is { spec: string; data: Record<string, unknown> } {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return (\n obj.spec === 'chara_card_v2' &&\n obj.data !== null &&\n typeof obj.data === 'object'\n );\n}\n\n/**\n * Get v2 card data from wrapped or unwrapped format.\n *\n * Uses structural check instead of strict Zod validation to handle\n * malformed cards that have the right structure but missing/invalid fields.\n * The caller (e.g., ccv2ToCCv3) handles defaulting missing fields.\n */\nexport function getV2Data(card: CCv2Data | CCv2Wrapped): CCv2Data {\n // Use structural check - more lenient than isWrappedV2 schema validation\n if (looksLikeWrappedV2(card)) {\n return card.data as CCv2Data;\n }\n return card;\n}\n","/**\n * Character Card v3 Types\n *\n * Based on: https://github.com/kwaroran/character-card-spec-v3\n */\n\nimport { z } from 'zod';\nimport { AssetDescriptorSchema } from './common.js';\n\n// ============================================================================\n// Zod Schemas\n// ============================================================================\n\n/**\n * Lorebook entry schema for v3 cards\n */\nexport const CCv3LorebookEntrySchema = z.object({\n keys: z.array(z.string()).optional(), // Some tools use 'key' instead\n content: z.string(),\n enabled: z.boolean().default(true), // Default to enabled if missing\n insertion_order: z.preprocess((v) => v ?? 0, z.number().int()),\n // Optional fields - be lenient with nulls since wild data has them\n case_sensitive: z.boolean().nullable().optional(),\n name: z.string().optional(),\n priority: z.number().int().nullable().optional(),\n id: z.number().int().nullable().optional(),\n comment: z.string().nullable().optional(),\n selective: z.boolean().nullable().optional(),\n secondary_keys: z.array(z.string()).nullable().optional(),\n constant: z.boolean().nullable().optional(),\n position: z.union([z.enum(['before_char', 'after_char']), z.number().int(), z.literal('')]).nullable().optional(),\n extensions: z.record(z.unknown()).optional(),\n // v3 specific - also lenient with types since SillyTavern uses numbers for enums\n automation_id: z.string().optional(),\n role: z.union([z.enum(['system', 'user', 'assistant']), z.number().int()]).nullable().optional(),\n group: z.string().optional(),\n scan_frequency: z.number().int().nonnegative().optional(),\n probability: z.number().min(0).max(100).optional(), // Some tools use 0-100 instead of 0-1\n use_regex: z.boolean().optional(),\n depth: z.number().int().nonnegative().optional(),\n selective_logic: z.union([z.enum(['AND', 'NOT']), z.number().int()]).optional(),\n}).passthrough(); // Allow tool-specific extensions\n\n/**\n * Character book (lorebook) schema for v3 cards\n */\nexport const CCv3CharacterBookSchema = z.object({\n name: z.string().optional(),\n description: z.string().optional(),\n scan_depth: z.number().int().nonnegative().optional(),\n token_budget: z.number().int().nonnegative().optional(),\n recursive_scanning: z.boolean().optional(),\n extensions: z.record(z.unknown()).optional(),\n entries: z.array(CCv3LorebookEntrySchema),\n});\n\n/**\n * Character Card v3 inner data structure schema.\n *\n * Note: Fields like group_only_greetings, creator, character_version, and tags\n * are technically \"required\" per V3 spec but rarely present in wild cards.\n * We use .default() to make parsing lenient while still producing valid output.\n */\nexport const CCv3DataInnerSchema = z.object({\n // Core fields - use .default('') to handle missing fields in malformed cards\n name: z.string().default(''),\n description: z.string().default(''),\n personality: z.string().nullable().default(''), // Can be null in wild (141 cards)\n scenario: z.string().default(''),\n first_mes: z.string().default(''),\n mes_example: z.string().nullable().default(''), // Can be null in wild (186 cards)\n // \"Required\" per spec but often missing in wild - use defaults for leniency\n creator: z.string().default(''),\n character_version: z.string().default(''),\n tags: z.array(z.string()).default([]),\n group_only_greetings: z.array(z.string()).default([]),\n // Optional fields\n creator_notes: z.string().optional(),\n system_prompt: z.string().optional(),\n post_history_instructions: z.string().optional(),\n alternate_greetings: z.array(z.string()).optional(),\n character_book: CCv3CharacterBookSchema.optional().nullable(),\n extensions: z.record(z.unknown()).optional(),\n // v3 specific\n assets: z.array(AssetDescriptorSchema).optional(),\n nickname: z.string().optional(),\n creator_notes_multilingual: z.record(z.string()).optional(),\n source: z.array(z.string()).optional(),\n creation_date: z.number().int().nonnegative().optional(), // Unix timestamp in seconds\n modification_date: z.number().int().nonnegative().optional(), // Unix timestamp in seconds\n});\n\n/**\n * Character Card v3 full structure schema\n */\nexport const CCv3DataSchema = z.object({\n spec: z.literal('chara_card_v3'),\n spec_version: z.literal('3.0'),\n data: CCv3DataInnerSchema,\n});\n\n// ============================================================================\n// TypeScript Types (inferred from Zod schemas)\n// ============================================================================\n\n/**\n * Lorebook entry for v3 cards\n */\nexport type CCv3LorebookEntry = z.infer<typeof CCv3LorebookEntrySchema>;\n\n/**\n * Character book (lorebook) for v3 cards\n */\nexport type CCv3CharacterBook = z.infer<typeof CCv3CharacterBookSchema>;\n\n/**\n * Character Card v3 inner data structure\n */\nexport type CCv3DataInner = z.infer<typeof CCv3DataInnerSchema>;\n\n/**\n * Character Card v3 full structure\n */\nexport type CCv3Data = z.infer<typeof CCv3DataSchema>;\n\n// ============================================================================\n// Type Guards & Parsers\n// ============================================================================\n\n/**\n * Check if data is a v3 card\n */\nexport function isV3Card(data: unknown): data is CCv3Data {\n return CCv3DataSchema.safeParse(data).success;\n}\n\n/**\n * Parse and validate a v3 card\n */\nexport function parseV3Card(data: unknown): CCv3Data {\n return CCv3DataSchema.parse(data);\n}\n\n/**\n * Parse and validate v3 card inner data\n */\nexport function parseV3DataInner(data: unknown): CCv3DataInner {\n return CCv3DataInnerSchema.parse(data);\n}\n\n/**\n * Get v3 card inner data\n */\nexport function getV3Data(card: CCv3Data): CCv3DataInner {\n return card.data;\n}\n\n/**\n * Check if data looks like a V3 card structurally (without strict validation).\n * More lenient than isV3Card - just checks structure, not full schema validity.\n */\nexport function looksLikeV3Card(data: unknown): data is { spec: string; data: Record<string, unknown> } {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n return (\n obj.spec === 'chara_card_v3' &&\n obj.data !== null &&\n typeof obj.data === 'object'\n );\n}\n","/**\n * RisuAI Extension Types\n *\n * These extensions are preserved as opaque blobs.\n * We do NOT interpret or transform the script contents.\n */\n\n/**\n * Risu emotions mapping (v2 style)\n * Format: [name, uri][]\n */\nexport type RisuEmotions = [string, string][];\n\n/**\n * Risu additional assets (v3 style)\n * Format: [name, uri, type][]\n */\nexport type RisuAdditionalAssets = [string, string, string][];\n\n/**\n * Risu depth prompt configuration\n */\nexport interface RisuDepthPrompt {\n depth: number;\n prompt: string;\n}\n\n/**\n * Risu extensions in card.extensions.risuai\n * Preserved as opaque - we don't interpret script contents\n */\nexport interface RisuExtensions {\n // Emotion assets\n emotions?: RisuEmotions;\n additionalAssets?: RisuAdditionalAssets;\n\n // Script data - OPAQUE, do not parse\n triggerscript?: unknown;\n customScripts?: unknown;\n\n // Voice/TTS settings\n vits?: Record<string, string>;\n\n // Depth prompt\n depth_prompt?: RisuDepthPrompt;\n\n // Other Risu-specific fields\n [key: string]: unknown;\n}\n\n/**\n * CharX x_meta entry (PNG chunk metadata preservation)\n */\nexport interface CharxMetaEntry {\n type?: string; // e.g., 'WEBP', 'PNG', 'JPEG'\n [key: string]: unknown;\n}\n\n/**\n * Check if card has Risu extensions\n */\nexport function hasRisuExtensions(extensions?: Record<string, unknown>): boolean {\n if (!extensions) return false;\n return 'risuai' in extensions || 'risu' in extensions;\n}\n\n/**\n * Check if card has Risu scripts (triggerscript or customScripts)\n */\nexport function hasRisuScripts(extensions?: Record<string, unknown>): boolean {\n if (!extensions) return false;\n const risu = extensions.risuai as RisuExtensions | undefined;\n if (!risu) return false;\n return !!risu.triggerscript || !!risu.customScripts;\n}\n\n/**\n * Check if card has depth prompt\n * Checks both SillyTavern style (extensions.depth_prompt) and Risu style (extensions.risuai.depth_prompt)\n */\nexport function hasDepthPrompt(extensions?: Record<string, unknown>): boolean {\n if (!extensions) return false;\n // SillyTavern top-level depth_prompt\n if ('depth_prompt' in extensions && extensions.depth_prompt) return true;\n // Risu-style depth_prompt\n const risu = extensions.risuai as RisuExtensions | undefined;\n return !!risu?.depth_prompt;\n}\n","/**\n * Normalized Card Types\n *\n * Unified view of card data regardless of source format.\n * This is a computed/virtual representation, not stored.\n */\n\nimport type { CCv3CharacterBook } from './ccv3.js';\n\n/**\n * Normalized card representation\n * Provides unified access to card data from any format\n */\nexport interface NormalizedCard {\n // Core fields (always present)\n name: string;\n description: string;\n personality: string;\n scenario: string;\n firstMes: string;\n mesExample: string;\n\n // Optional prompts\n systemPrompt?: string;\n postHistoryInstructions?: string;\n\n // Arrays\n alternateGreetings: string[];\n groupOnlyGreetings: string[];\n tags: string[];\n\n // Metadata\n creator?: string;\n creatorNotes?: string;\n characterVersion?: string;\n\n // Character book (v3 format)\n characterBook?: CCv3CharacterBook;\n\n // Extensions (preserved as-is)\n extensions: Record<string, unknown>;\n}\n\n/**\n * Create empty normalized card with defaults\n */\nexport function createEmptyNormalizedCard(): NormalizedCard {\n return {\n name: '',\n description: '',\n personality: '',\n scenario: '',\n firstMes: '',\n mesExample: '',\n alternateGreetings: [],\n groupOnlyGreetings: [],\n tags: [],\n extensions: {},\n };\n}\n\n/**\n * Derived features extracted from card (not stored in card)\n */\nexport interface DerivedFeatures {\n // Content flags\n hasAlternateGreetings: boolean;\n alternateGreetingsCount: number;\n /** Total greetings = first_mes (1) + alternate_greetings */\n totalGreetingsCount: number;\n hasLorebook: boolean;\n lorebookEntriesCount: number;\n hasEmbeddedImages: boolean;\n embeddedImagesCount: number;\n hasGallery: boolean;\n\n // Format-specific\n hasRisuExtensions: boolean;\n hasRisuScripts: boolean;\n hasDepthPrompt: boolean;\n hasVoxtaAppearance: boolean;\n\n // Token counts (estimated)\n tokens: {\n description: number;\n personality: number;\n scenario: number;\n firstMes: number;\n mesExample: number;\n systemPrompt: number;\n total: number;\n };\n}\n\n/**\n * Create empty derived features\n */\nexport function createEmptyFeatures(): DerivedFeatures {\n return {\n hasAlternateGreetings: false,\n alternateGreetingsCount: 0,\n totalGreetingsCount: 1, // first_mes always counts as 1\n hasLorebook: false,\n lorebookEntriesCount: 0,\n hasEmbeddedImages: false,\n embeddedImagesCount: 0,\n hasGallery: false,\n hasRisuExtensions: false,\n hasRisuScripts: false,\n hasDepthPrompt: false,\n hasVoxtaAppearance: false,\n tokens: {\n description: 0,\n personality: 0,\n scenario: 0,\n firstMes: 0,\n mesExample: 0,\n systemPrompt: 0,\n total: 0,\n },\n };\n}\n","/**\n * Feature Derivation\n *\n * Canonical feature extraction from character cards.\n * Eliminates duplicate implementations across Archive, Federation, and Architect.\n */\n\nimport type { CCv2Data } from './ccv2.js';\nimport type { CCv3DataInner } from './ccv3.js';\nimport type { DerivedFeatures } from './normalized.js';\nimport { hasRisuExtensions, hasRisuScripts, hasDepthPrompt } from './risu.js';\n\n/**\n * Derive features from a character card (V2 or V3 format).\n *\n * This is the canonical implementation - all apps should use this\n * rather than implementing their own feature detection.\n *\n * @param card - Either CCv2Data or CCv3DataInner (unwrapped)\n * @returns DerivedFeatures with all feature flags populated\n *\n * @example\n * ```typescript\n * import { deriveFeatures, parseV3Card } from '@character-foundry/schemas';\n *\n * const card = parseV3Card(data);\n * const features = deriveFeatures(card.data);\n *\n * if (features.hasLorebook) {\n * console.log(`Found ${features.lorebookEntriesCount} lorebook entries`);\n * }\n * ```\n */\nexport function deriveFeatures(card: CCv2Data | CCv3DataInner): DerivedFeatures {\n // Detect format by checking for V3-specific field\n const isV3 = 'assets' in card;\n\n // Alternate greetings\n const altGreetings = card.alternate_greetings ?? [];\n const hasAlternateGreetings = altGreetings.length > 0;\n const alternateGreetingsCount = altGreetings.length;\n // Total = first_mes (1) + alternate_greetings\n const totalGreetingsCount = 1 + alternateGreetingsCount;\n\n // Lorebook\n const characterBook = card.character_book;\n const hasLorebook = !!characterBook && characterBook.entries.length > 0;\n const lorebookEntriesCount = characterBook?.entries.length ?? 0;\n\n // Assets (V3 only) - check for visual asset types\n const assets = isV3 ? (card as CCv3DataInner).assets ?? [] : [];\n const imageAssetTypes = ['icon', 'background', 'emotion', 'custom'];\n const imageAssets = assets.filter(\n (a) =>\n imageAssetTypes.includes(a.type) ||\n ['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(a.ext.toLowerCase()),\n );\n const hasGallery = imageAssets.length > 0;\n\n // Embedded images - check for data URLs in text fields\n const embeddedImageCount = countEmbeddedImages(card);\n const hasEmbeddedImages = embeddedImageCount > 0;\n\n // Extensions\n const extensions = card.extensions ?? {};\n const hasRisu = hasRisuExtensions(extensions);\n const hasScripts = hasRisuScripts(extensions);\n const hasDepth = hasDepthPrompt(extensions);\n const hasVoxta = checkVoxtaAppearance(extensions);\n\n // Token counts - initialize to zero (actual counting happens in tokenizers package)\n const tokens = {\n description: 0,\n personality: 0,\n scenario: 0,\n firstMes: 0,\n mesExample: 0,\n systemPrompt: 0,\n total: 0,\n };\n\n return {\n hasAlternateGreetings,\n alternateGreetingsCount,\n totalGreetingsCount,\n hasLorebook,\n lorebookEntriesCount,\n hasEmbeddedImages,\n embeddedImagesCount: embeddedImageCount,\n hasGallery,\n hasRisuExtensions: hasRisu,\n hasRisuScripts: hasScripts,\n hasDepthPrompt: hasDepth,\n hasVoxtaAppearance: hasVoxta,\n tokens,\n };\n}\n\n/**\n * Count embedded images (data URLs) in card text fields.\n * Looks for base64-encoded images in description, personality, scenario, etc.\n */\nfunction countEmbeddedImages(card: CCv2Data | CCv3DataInner): number {\n const textFields = [\n card.description,\n card.personality,\n card.scenario,\n card.first_mes,\n card.mes_example,\n card.creator_notes,\n card.system_prompt,\n card.post_history_instructions,\n ...(card.alternate_greetings ?? []),\n ].filter((field): field is string => typeof field === 'string');\n\n // Add group_only_greetings if V3\n if ('group_only_greetings' in card) {\n textFields.push(...(card.group_only_greetings ?? []));\n }\n\n let count = 0;\n const dataUrlPattern = /data:image\\/[^;]+;base64,/g;\n\n for (const text of textFields) {\n const matches = text.match(dataUrlPattern);\n if (matches) {\n count += matches.length;\n }\n }\n\n return count;\n}\n\n/**\n * Check if card has Voxta appearance data.\n * Voxta stores appearance in extensions.voxta.appearance\n */\nfunction checkVoxtaAppearance(extensions: Record<string, unknown>): boolean {\n if (!extensions.voxta) return false;\n const voxta = extensions.voxta as Record<string, unknown>;\n return !!voxta.appearance;\n}\n","/**\n * Format Detection\n *\n * Detect card specification version from JSON data.\n */\n\nimport type { Spec } from './common.js';\n\n/**\n * V3-only fields that indicate a V3 card\n */\nconst V3_ONLY_FIELDS = ['group_only_greetings', 'creation_date', 'modification_date', 'assets'] as const;\n\n/**\n * Result from detailed spec detection\n */\nexport interface SpecDetectionResult {\n /** Detected spec version */\n spec: Spec | null;\n /** Confidence level of detection */\n confidence: 'high' | 'medium' | 'low';\n /** What fields/values indicated this spec */\n indicators: string[];\n /** Anomalies or inconsistencies detected */\n warnings: string[];\n}\n\n/**\n * Detect card spec version from parsed JSON\n * Returns 'v2', 'v3', or null if not recognized\n */\nexport function detectSpec(data: unknown): Spec | null {\n return detectSpecDetailed(data).spec;\n}\n\n/**\n * Detailed spec detection with confidence and reasoning.\n * Useful for debugging and logging.\n */\nexport function detectSpecDetailed(data: unknown): SpecDetectionResult {\n const result: SpecDetectionResult = {\n spec: null,\n confidence: 'low',\n indicators: [],\n warnings: [],\n };\n\n if (!data || typeof data !== 'object') {\n result.indicators.push('Input is not an object');\n return result;\n }\n\n const obj = data as Record<string, unknown>;\n const dataObj = (obj.data && typeof obj.data === 'object' ? obj.data : null) as Record<\n string,\n unknown\n > | null;\n\n // Check for explicit spec markers (HIGH confidence)\n\n // Explicit v3 spec marker\n if (obj.spec === 'chara_card_v3') {\n result.spec = 'v3';\n result.confidence = 'high';\n result.indicators.push('spec field is \"chara_card_v3\"');\n\n // Check for inconsistencies\n if (obj.spec_version && obj.spec_version !== '3.0') {\n result.warnings.push(`spec_version \"${obj.spec_version}\" inconsistent with v3 spec`);\n }\n\n return result;\n }\n\n // Explicit v2 spec marker\n if (obj.spec === 'chara_card_v2') {\n result.spec = 'v2';\n result.confidence = 'high';\n result.indicators.push('spec field is \"chara_card_v2\"');\n\n // Check for inconsistencies - V3-only fields in V2 card\n if (dataObj) {\n for (const field of V3_ONLY_FIELDS) {\n if (field in dataObj) {\n result.warnings.push(`V3-only field \"${field}\" found in V2 card`);\n }\n }\n }\n\n if (obj.spec_version && obj.spec_version !== '2.0') {\n result.warnings.push(`spec_version \"${obj.spec_version}\" inconsistent with v2 spec`);\n }\n\n return result;\n }\n\n // Check spec_version field (HIGH confidence)\n if (typeof obj.spec_version === 'string') {\n if (obj.spec_version.startsWith('3')) {\n result.spec = 'v3';\n result.confidence = 'high';\n result.indicators.push(`spec_version \"${obj.spec_version}\" starts with \"3\"`);\n return result;\n }\n if (obj.spec_version.startsWith('2')) {\n result.spec = 'v2';\n result.confidence = 'high';\n result.indicators.push(`spec_version \"${obj.spec_version}\" starts with \"2\"`);\n return result;\n }\n }\n\n if (obj.spec_version === 2.0 || obj.spec_version === 2) {\n result.spec = 'v2';\n result.confidence = 'high';\n result.indicators.push(`spec_version is numeric ${obj.spec_version}`);\n return result;\n }\n\n // Check for V3-only fields (MEDIUM confidence)\n if (dataObj) {\n const v3Fields: string[] = [];\n for (const field of V3_ONLY_FIELDS) {\n if (field in dataObj) {\n v3Fields.push(field);\n }\n }\n\n if (v3Fields.length > 0) {\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push(`Has V3-only fields: ${v3Fields.join(', ')}`);\n return result;\n }\n }\n\n // Check root level for V3-only fields (also MEDIUM confidence)\n const rootV3Fields: string[] = [];\n for (const field of V3_ONLY_FIELDS) {\n if (field in obj) {\n rootV3Fields.push(field);\n }\n }\n if (rootV3Fields.length > 0) {\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push(`Has V3-only fields at root: ${rootV3Fields.join(', ')}`);\n result.warnings.push('V3 fields found at root level instead of data object');\n return result;\n }\n\n // Wrapped format with data object (MEDIUM confidence)\n if (obj.spec && dataObj) {\n const dataName = dataObj.name;\n if (dataName && typeof dataName === 'string') {\n // Infer from spec string\n if (typeof obj.spec === 'string') {\n if (obj.spec.includes('v3') || obj.spec.includes('3')) {\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push(`spec field \"${obj.spec}\" contains \"v3\" or \"3\"`);\n return result;\n }\n if (obj.spec.includes('v2') || obj.spec.includes('2')) {\n result.spec = 'v2';\n result.confidence = 'medium';\n result.indicators.push(`spec field \"${obj.spec}\" contains \"v2\" or \"2\"`);\n return result;\n }\n }\n // Default wrapped format to v3 (modern)\n result.spec = 'v3';\n result.confidence = 'medium';\n result.indicators.push('Has wrapped format with spec and data.name');\n return result;\n }\n }\n\n // Unwrapped format - V1/V2 like structure (MEDIUM confidence)\n if (obj.name && typeof obj.name === 'string') {\n if ('description' in obj || 'personality' in obj || 'scenario' in obj) {\n result.spec = 'v2';\n result.confidence = 'medium';\n result.indicators.push('Unwrapped format with name, description/personality/scenario');\n return result;\n }\n }\n\n // Check if data object has card-like structure without spec (LOW confidence)\n if (dataObj && typeof dataObj.name === 'string') {\n if ('description' in dataObj || 'personality' in dataObj) {\n result.spec = 'v2';\n result.confidence = 'low';\n result.indicators.push('Has data object with name and card fields, but no spec');\n result.warnings.push('Missing spec field');\n return result;\n }\n }\n\n result.indicators.push('No card structure detected');\n return result;\n}\n\n/**\n * Check if card has a lorebook\n */\nexport function hasLorebook(data: unknown): boolean {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n\n // Check wrapped format\n const wrapped = obj.data as Record<string, unknown> | undefined;\n if (wrapped?.character_book) {\n const book = wrapped.character_book as Record<string, unknown>;\n if (Array.isArray(book.entries) && book.entries.length > 0) return true;\n }\n\n // Check unwrapped format\n if (obj.character_book) {\n const book = obj.character_book as Record<string, unknown>;\n if (Array.isArray(book.entries) && book.entries.length > 0) return true;\n }\n\n return false;\n}\n\n/**\n * Check if data looks like a valid card structure\n */\nexport function looksLikeCard(data: unknown): boolean {\n if (!data || typeof data !== 'object') return false;\n const obj = data as Record<string, unknown>;\n\n // Has explicit spec marker\n if (obj.spec === 'chara_card_v2' || obj.spec === 'chara_card_v3') {\n return true;\n }\n\n // Has wrapped data with name\n if (obj.data && typeof obj.data === 'object') {\n const dataObj = obj.data as Record<string, unknown>;\n if (typeof dataObj.name === 'string' && dataObj.name.length > 0) {\n return true;\n }\n }\n\n // Has unwrapped card-like structure\n if (typeof obj.name === 'string' && obj.name.length > 0) {\n if ('description' in obj || 'personality' in obj || 'first_mes' in obj) {\n return true;\n }\n }\n\n return false;\n}\n","/**\n * Card Normalizer\n *\n * Handles normalization of malformed card data from various sources.\n * Fixes common issues like wrong spec values, misplaced fields, missing required fields.\n */\n\nimport type { CCv2Data, CCv2Wrapped, CCv2CharacterBook, CCv2LorebookEntry } from './ccv2.js';\nimport type { CCv3Data, CCv3CharacterBook, CCv3LorebookEntry } from './ccv3.js';\nimport { detectSpec } from './detection.js';\n\n/**\n * Position values as numbers (non-standard) and their string equivalents\n */\nconst POSITION_MAP: Record<number, 'before_char' | 'after_char'> = {\n 0: 'before_char',\n 1: 'after_char',\n};\n\n/**\n * V3-only lorebook entry fields that should be moved to extensions for V2\n */\nconst V3_ONLY_ENTRY_FIELDS = [\n 'probability',\n 'depth',\n 'group',\n 'scan_frequency',\n 'use_regex',\n 'selective_logic',\n 'role',\n 'automation_id',\n] as const;\n\n/**\n * Required V2 card fields with their defaults\n */\nconst V2_REQUIRED_DEFAULTS: Partial<CCv2Data> = {\n name: '',\n description: '',\n personality: '',\n scenario: '',\n first_mes: '',\n mes_example: '',\n};\n\n/**\n * Required V3 card fields with their defaults\n */\nconst V3_REQUIRED_DEFAULTS: Partial<CCv3Data['data']> = {\n name: '',\n description: '',\n personality: '',\n scenario: '',\n first_mes: '',\n mes_example: '',\n creator: '',\n character_version: '1.0',\n tags: [],\n group_only_greetings: [],\n};\n\n/**\n * Fields that belong at root level for wrapped format\n */\nconst _ROOT_FIELDS = ['spec', 'spec_version', 'data'] as const;\n\n/**\n * Fields that belong in the data object\n */\nconst DATA_FIELDS = [\n 'name',\n 'description',\n 'personality',\n 'scenario',\n 'first_mes',\n 'mes_example',\n 'creator_notes',\n 'system_prompt',\n 'post_history_instructions',\n 'alternate_greetings',\n 'character_book',\n 'tags',\n 'creator',\n 'character_version',\n 'extensions',\n 'assets',\n 'nickname',\n 'creator_notes_multilingual',\n 'source',\n 'creation_date',\n 'modification_date',\n 'group_only_greetings',\n] as const;\n\n/**\n * Deep clone an object without mutating the original\n */\nfunction deepClone<T>(obj: T): T {\n if (obj === null || obj === undefined) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as T;\n }\n if (typeof obj === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n result[key] = deepClone(value);\n }\n return result as T;\n }\n return obj;\n}\n\n/**\n * Check if a timestamp is in milliseconds (13+ digits)\n */\nfunction isMilliseconds(timestamp: number): boolean {\n // Timestamps before year 2001 in seconds: < 1000000000\n // Timestamps in milliseconds are typically 13 digits: 1000000000000+\n return timestamp > 10000000000;\n}\n\n/**\n * CardNormalizer - handles normalization of malformed card data\n */\nexport const CardNormalizer = {\n /**\n * Normalize card data to valid schema format.\n *\n * Handles:\n * - Fixing spec/spec_version values\n * - Moving misplaced fields to correct locations\n * - Adding missing required fields with defaults\n * - Handling hybrid formats (fields at root AND in data object)\n *\n * @param data - Raw card data (potentially malformed)\n * @param spec - Target spec version\n * @returns Normalized card data (does not mutate input)\n */\n normalize(data: unknown, spec: 'v2' | 'v3'): CCv2Wrapped | CCv3Data {\n if (!data || typeof data !== 'object') {\n // Return minimal valid card\n if (spec === 'v3') {\n return {\n spec: 'chara_card_v3',\n spec_version: '3.0',\n data: { ...V3_REQUIRED_DEFAULTS } as CCv3Data['data'],\n };\n }\n return {\n spec: 'chara_card_v2',\n spec_version: '2.0',\n data: { ...V2_REQUIRED_DEFAULTS } as CCv2Data,\n };\n }\n\n const obj = data as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n\n // Build merged data object from root fields + existing data object\n const existingData = (obj.data && typeof obj.data === 'object' ? obj.data : {}) as Record<\n string,\n unknown\n >;\n const mergedData: Record<string, unknown> = {};\n\n // Copy existing data first\n for (const [key, value] of Object.entries(existingData)) {\n mergedData[key] = deepClone(value);\n }\n\n // Move any misplaced root-level data fields into data object\n // (ChubAI hybrid format fix)\n for (const field of DATA_FIELDS) {\n if (field in obj && !(field in mergedData)) {\n mergedData[field] = deepClone(obj[field]);\n }\n }\n\n // Handle character_book: null -> remove entirely\n if (mergedData.character_book === null) {\n delete mergedData.character_book;\n }\n\n // Normalize character_book if present\n if (mergedData.character_book && typeof mergedData.character_book === 'object') {\n mergedData.character_book = this.normalizeCharacterBook(\n mergedData.character_book as Record<string, unknown>,\n spec\n );\n }\n\n // Apply defaults for required fields\n const defaults = spec === 'v3' ? V3_REQUIRED_DEFAULTS : V2_REQUIRED_DEFAULTS;\n for (const [key, defaultValue] of Object.entries(defaults)) {\n if (!(key in mergedData) || mergedData[key] === undefined) {\n mergedData[key] = Array.isArray(defaultValue) ? [...defaultValue] : defaultValue;\n }\n }\n\n // Ensure arrays are actually arrays\n if (mergedData.tags && !Array.isArray(mergedData.tags)) {\n mergedData.tags = [];\n }\n if (mergedData.alternate_greetings && !Array.isArray(mergedData.alternate_greetings)) {\n mergedData.alternate_greetings = [];\n }\n if (spec === 'v3') {\n if (\n mergedData.group_only_greetings &&\n !Array.isArray(mergedData.group_only_greetings)\n ) {\n mergedData.group_only_greetings = [];\n }\n }\n\n // Build result with correct spec\n if (spec === 'v3') {\n result.spec = 'chara_card_v3';\n result.spec_version = '3.0';\n result.data = this.fixTimestampsInner(mergedData);\n } else {\n result.spec = 'chara_card_v2';\n result.spec_version = '2.0';\n result.data = mergedData;\n }\n\n return result as unknown as CCv2Wrapped | CCv3Data;\n },\n\n /**\n * Normalize a character book (lorebook).\n *\n * Handles:\n * - Ensuring required fields exist\n * - Converting numeric position values to string enums\n * - Moving V3-only fields to extensions for V2 compatibility\n *\n * @param book - Raw character book data\n * @param spec - Target spec version\n * @returns Normalized character book\n */\n normalizeCharacterBook(\n book: Record<string, unknown>,\n spec: 'v2' | 'v3'\n ): CCv2CharacterBook | CCv3CharacterBook {\n const result: Record<string, unknown> = {};\n\n // Copy book-level fields\n if (book.name !== undefined) result.name = book.name;\n if (book.description !== undefined) result.description = book.description;\n if (book.scan_depth !== undefined) result.scan_depth = book.scan_depth;\n if (book.token_budget !== undefined) result.token_budget = book.token_budget;\n if (book.recursive_scanning !== undefined)\n result.recursive_scanning = book.recursive_scanning;\n if (book.extensions !== undefined) result.extensions = deepClone(book.extensions);\n\n // Normalize entries\n const entries = Array.isArray(book.entries) ? book.entries : [];\n result.entries = entries.map((entry) =>\n this.normalizeEntry(entry as Record<string, unknown>, spec)\n );\n\n return result as unknown as CCv2CharacterBook | CCv3CharacterBook;\n },\n\n /**\n * Normalize a single lorebook entry.\n *\n * Handles:\n * - Converting numeric position to string enum\n * - Moving V3-only fields to extensions for V2\n * - Ensuring required fields exist\n *\n * @param entry - Raw entry data\n * @param spec - Target spec version\n * @returns Normalized entry\n */\n normalizeEntry(\n entry: Record<string, unknown>,\n spec: 'v2' | 'v3'\n ): CCv2LorebookEntry | CCv3LorebookEntry {\n const result: Record<string, unknown> = {};\n\n // Required fields with defaults\n result.keys = Array.isArray(entry.keys) ? [...entry.keys] : [];\n result.content = typeof entry.content === 'string' ? entry.content : '';\n result.enabled = entry.enabled !== false; // default true\n result.insertion_order =\n typeof entry.insertion_order === 'number' ? entry.insertion_order : 0;\n\n // For V2, extensions is required\n if (spec === 'v2') {\n result.extensions =\n entry.extensions && typeof entry.extensions === 'object'\n ? deepClone(entry.extensions)\n : {};\n }\n\n // Optional fields\n if (entry.case_sensitive !== undefined) result.case_sensitive = entry.case_sensitive;\n if (entry.name !== undefined) result.name = entry.name;\n if (entry.priority !== undefined) result.priority = entry.priority;\n if (entry.id !== undefined) result.id = entry.id;\n if (entry.comment !== undefined) result.comment = entry.comment;\n if (entry.selective !== undefined) result.selective = entry.selective;\n if (entry.secondary_keys !== undefined) {\n result.secondary_keys = Array.isArray(entry.secondary_keys)\n ? [...entry.secondary_keys]\n : [];\n }\n if (entry.constant !== undefined) result.constant = entry.constant;\n\n // Position: convert numeric to string enum\n if (entry.position !== undefined) {\n if (typeof entry.position === 'number') {\n result.position = POSITION_MAP[entry.position] || 'before_char';\n } else if (entry.position === 'before_char' || entry.position === 'after_char') {\n result.position = entry.position;\n }\n }\n\n // Handle V3-only fields\n if (spec === 'v3') {\n // Copy V3 fields directly\n if (entry.extensions !== undefined) result.extensions = deepClone(entry.extensions);\n for (const field of V3_ONLY_ENTRY_FIELDS) {\n if (entry[field] !== undefined) {\n result[field] = entry[field];\n }\n }\n } else {\n // V2: Move V3-only fields to extensions\n const ext = (result.extensions || {}) as Record<string, unknown>;\n for (const field of V3_ONLY_ENTRY_FIELDS) {\n if (entry[field] !== undefined) {\n ext[field] = entry[field];\n }\n }\n result.extensions = ext;\n }\n\n return result as unknown as CCv2LorebookEntry | CCv3LorebookEntry;\n },\n\n /**\n * Fix CharacterTavern timestamp format (milliseconds -> seconds).\n *\n * CCv3 spec requires timestamps in seconds (Unix epoch).\n * CharacterTavern exports timestamps in milliseconds.\n *\n * @param data - V3 card data\n * @returns Card data with fixed timestamps (does not mutate input)\n */\n fixTimestamps(data: CCv3Data): CCv3Data {\n const result = deepClone(data);\n result.data = this.fixTimestampsInner(\n result.data as unknown as Record<string, unknown>\n ) as unknown as CCv3Data['data'];\n return result;\n },\n\n /**\n * Internal: fix timestamps in data object\n */\n fixTimestampsInner(data: Record<string, unknown>): Record<string, unknown> {\n const result = { ...data };\n\n if (typeof result.creation_date === 'number') {\n if (isMilliseconds(result.creation_date)) {\n result.creation_date = Math.floor(result.creation_date / 1000);\n }\n // Sanitize negative timestamps (.NET default dates like 0001-01-01)\n if ((result.creation_date as number) < 0) {\n delete result.creation_date;\n }\n }\n\n if (typeof result.modification_date === 'number') {\n if (isMilliseconds(result.modification_date)) {\n result.modification_date = Math.floor(result.modification_date / 1000);\n }\n // Sanitize negative timestamps (.NET default dates like 0001-01-01)\n if ((result.modification_date as number) < 0) {\n delete result.modification_date;\n }\n }\n\n return result;\n },\n\n /**\n * Auto-detect spec and normalize.\n *\n * @param data - Raw card data\n * @returns Normalized card data, or null if not a valid card\n */\n autoNormalize(data: unknown): CCv2Wrapped | CCv3Data | null {\n const spec = detectSpec(data);\n if (!spec) return null;\n\n // V1 cards get upgraded to V2\n const targetSpec = spec === 'v3' ? 'v3' : 'v2';\n return this.normalize(data, targetSpec);\n },\n};\n\nexport type { CCv2Wrapped, CCv3Data };\n","/**\n * Validation Utilities\n *\n * Helper functions for Zod validation with Foundry error integration.\n */\n\nimport { z } from 'zod';\n\n/**\n * Convert Zod error to human-readable message\n */\nexport function zodErrorToMessage(zodError: z.ZodError, context?: string): string {\n const messages = zodError.errors.map((err) => {\n const path = err.path.length > 0 ? `${err.path.join('.')}: ` : '';\n return `${path}${err.message}`;\n });\n\n const message = messages.join('; ');\n return context ? `${context} - ${message}` : message;\n}\n\n/**\n * Get the first error field from Zod error\n */\nexport function getFirstErrorField(zodError: z.ZodError): string | undefined {\n return zodError.errors[0]?.path[0]?.toString();\n}\n\n/**\n * Safe parse with detailed error information\n */\nexport function safeParse<T>(\n schema: z.ZodSchema<T>,\n data: unknown\n): { success: true; data: T } | { success: false; error: string; field?: string } {\n const result = schema.safeParse(data);\n\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n return {\n success: false,\n error: zodErrorToMessage(result.error),\n field: getFirstErrorField(result.error),\n };\n}\n"],"mappings":";;;;;;;;AA6FO,SAAS,WAAW,KAAyB;AAClD,SAAO,IAAI,YAAY,EAAE,OAAO,GAAG;AACrC;AAKO,SAAS,SAAS,MAA0B;AACjD,SAAO,IAAI,YAAY,EAAE,OAAO,IAAI;AACtC;AC3FA,IAAM,SAAS,OAAO,YAAY,eAChC,QAAQ,YAAY,QACpB,QAAQ,SAAS,QAAQ;AAO3B,IAAM,yBAAyB,OAAO;AAsFtC,IAAM,oBAAoB,KAAK;AClG/B,IAAM,uBAAuB,uBAAO,IAAI,sCAAsC;AAKvE,IAAM,eAAN,cAA2B,MAAM;EAItC,YAAY,SAAiC,MAAc;AACzD,UAAM,OAAO;AAD8B,SAAA,OAAA;AAE3C,SAAK,OAAO;AAEZ,QAAI,MAAM,mBAAmB;AAC3B,YAAM,kBAAkB,MAAM,KAAK,WAAW;IAChD;EACF;;EATA,CAAU,oBAAoB,IAAI;AAUpC;AAKO,IAAM,aAAN,cAAyB,aA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Q,UAAU,QAAQ,SAC1B,QAAQ,UAAU,QAAQ,OAAO;AACnC,qBAAO;YACT;UACF;QACF;AAGA,eAAO;MACT;AAEA,aAAO;IACT;EAAA;AAAA,CAAA;AC5iBA,IAAA,oBAAA,WAAA;EAAA,mFAAA,SAAA,QAAA;AAAA;AAEA,QAAM,QAAQ,cAAA;AACd,QAAM,YAAY,CAAC,SAAS,OAAO,YAAY;AAC7C,UAAI;AACF,gBAAQ,IAAI,MAAM,OAAO,OAAO;MAClC,SAAS,IAAI;AACX,eAAO;MACT;AACA,aAAO,MAAM,KAAK,OAAO;IAC3B;AACA,WAAO,UAAU;EAAA;AAAA,CAAA;ACXjB,IAAA,kBAAA,WAAA;EAAA,wEAAA,SAAA,QAAA;AAAA,WAAA,UAAA;MACE,MAAQ;MACR,aAAe;MACf,SAAW;MACX,QAAU;MACV,UAAY;MACZ,cAAgB;QACd;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;MACF;MACA,SAAW;QACT,SAAW;QACX,OAAS;QACT,MAAQ;QACR,aAAa;QACb,aAAa;QACb,kBAAkB;QAClB,aAAa;QACb,cAAc;QACd,4BAA4B;QAC5B,+BAA+B;QAC/B,cAAc;QACd,cAAc;QACd,gBAAgB;MAClB;MACA,MAAQ;MACR,MAAQ;MACR,OAAS;MACT,OAAS;QACP;QACA;QACA;MACF;MACA,YAAc;QACZ,MAAQ;QACR,K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sVersion","clone","debuglog","concat","swizzle","z2","metadata","stats","extend","composite","flip","flop","gamma","threshold","tint","greyscale","grayscale","colourspace","_","concurrency","simd","zipSync","z","z","VoxtaResourceKind","generateUUID","streamingUnzipSync","ZipPreflightError","SizeLimitError","ParseError","fromString","zipSync","detectImageFormat","getExtension"]}