@warlock.js/core 4.11.0 → 4.12.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../core/src/image/image.ts"],"sourcesContent":["import { http } from \"@mongez/http\";\r\nimport type sharp from \"sharp\";\r\nimport type { FormatEnum } from \"sharp\";\r\n\r\n// ============================================================\r\n// Eager-loaded Sharp Module\r\n// ============================================================\r\n\r\n/**\r\n * Installation instructions for sharp\r\n */\r\nconst SHARP_INSTALL_INSTRUCTIONS = `\r\nImage processing requires the sharp package.\r\nInstall it with:\r\n\r\n warlock add image\r\n\r\nOr manually:\r\n\r\n npm install sharp\r\n pnpm add sharp\r\n yarn add sharp\r\n`.trim();\r\n\r\n/**\r\n * Module availability flag\r\n */\r\nlet moduleExists: boolean | null = null;\r\n\r\n/**\r\n * Cached sharp function (loaded at import time)\r\n */\r\nlet sharpFn: typeof sharp;\r\n\r\n/**\r\n * Eagerly load sharp module at import time\r\n */\r\nasync function loadSharpModule() {\r\n try {\r\n const module = await import(\"sharp\");\r\n sharpFn = module.default;\r\n moduleExists = true;\r\n } catch {\r\n moduleExists = false;\r\n }\r\n}\r\n\r\n// Kick off eager loading immediately\r\nloadSharpModule();\r\n\r\n// ============================================================\r\n// Types\r\n// ============================================================\r\n\r\nexport type ImageFormat = keyof FormatEnum;\r\n\r\nexport type ImageInput = string | Buffer | Uint8Array | ArrayBuffer;\r\n\r\n/**\r\n * Watermark configuration for deferred execution\r\n */\r\nexport type WatermarkConfig = {\r\n image: ImageInput | Image;\r\n options: sharp.OverlayOptions;\r\n};\r\n\r\n/**\r\n * Operation descriptor for deferred pipeline execution.\r\n * All operations are stored and executed at save/toBuffer time.\r\n */\r\ntype ImageOperation =\r\n | { type: \"resize\"; options: sharp.ResizeOptions }\r\n | { type: \"crop\"; options: sharp.Region }\r\n | { type: \"rotate\"; angle: number }\r\n | { type: \"flip\" }\r\n | { type: \"flop\" }\r\n | { type: \"blur\"; sigma: number }\r\n | { type: \"sharpen\"; options?: sharp.SharpenOptions }\r\n | { type: \"blackAndWhite\" }\r\n | { type: \"opacity\"; value: number }\r\n | { type: \"negate\"; options?: sharp.NegateOptions }\r\n | { type: \"tint\"; color: sharp.Color }\r\n | { type: \"trim\"; options?: sharp.TrimOptions }\r\n | { type: \"watermark\"; config: WatermarkConfig }\r\n | { type: \"watermarks\"; configs: WatermarkConfig[] };\r\n\r\n/**\r\n * Transformation options that can be applied in batch via `apply()` method.\r\n *\r\n * **Execution Order (when using apply()):**\r\n * 1. resize - Resize first to work with correct dimensions\r\n * 2. crop - Crop after resize to extract the desired region\r\n * 3. rotate - Rotation after sizing\r\n * 4. flip/flop - Mirror operations\r\n * 5. blackAndWhite/grayscale - Color space conversion\r\n * 6. blur - Blur effect\r\n * 7. sharpen - Sharpen effect\r\n * 8. tint - Color overlay\r\n * 9. negate - Invert colors\r\n * 10. opacity - Transparency (applied via composite)\r\n * 11. format/quality - Applied on save/export\r\n */\r\nexport type ImageTransformOptions = {\r\n /**\r\n * Output quality (1-100), applied based on final format\r\n */\r\n quality?: number;\r\n /**\r\n * Output format (jpeg, png, webp, avif, etc.)\r\n */\r\n format?: ImageFormat;\r\n /**\r\n * Resize options\r\n */\r\n resize?: sharp.ResizeOptions;\r\n /**\r\n * Crop/extract region\r\n */\r\n crop?: sharp.Region;\r\n /**\r\n * Rotation angle in degrees\r\n */\r\n rotate?: number;\r\n /**\r\n * Flip vertically (top to bottom)\r\n */\r\n flip?: boolean;\r\n /**\r\n * Flop horizontally (left to right)\r\n */\r\n flop?: boolean;\r\n /**\r\n * Convert to black and white\r\n */\r\n blackAndWhite?: boolean;\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n grayscale?: boolean;\r\n /**\r\n * Blur sigma (must be >= 0.3)\r\n */\r\n blur?: number;\r\n /**\r\n * Sharpen options\r\n */\r\n sharpen?: sharp.SharpenOptions | boolean;\r\n /**\r\n * Tint color\r\n */\r\n tint?: sharp.Color;\r\n /**\r\n * Negate/invert colors\r\n */\r\n negate?: sharp.NegateOptions | boolean;\r\n /**\r\n * Opacity (0-100)\r\n */\r\n opacity?: number;\r\n /**\r\n * Trim options\r\n */\r\n trim?: sharp.TrimOptions | boolean;\r\n /**\r\n * Single watermark\r\n */\r\n watermark?: WatermarkConfig;\r\n /**\r\n * Multiple watermarks\r\n */\r\n watermarks?: WatermarkConfig[];\r\n};\r\n\r\n/**\r\n * Internal options stored for deferred application\r\n */\r\ntype InternalOptions = {\r\n quality?: number;\r\n format?: ImageFormat;\r\n};\r\n\r\n/**\r\n * Image manipulation class with deferred pipeline execution.\r\n *\r\n * **Important:** This class requires the `sharp` package to be installed.\r\n * Install it with: `warlock add image` or `npm install sharp`\r\n *\r\n * Sharp is lazy-loaded on the first async operation (save, toBuffer, etc.),\r\n * so the constructor and all chainable methods remain synchronous.\r\n *\r\n * All operations are synchronous and stored as descriptors.\r\n * The pipeline is executed only when calling output methods:\r\n * - `save()` - Save to file\r\n * - `toBuffer()` - Get as buffer\r\n * - `toBase64()` - Get as base64 string\r\n * - `toDataUrl()` - Get as data URL\r\n *\r\n * @example\r\n * ```typescript\r\n * // All chaining is synchronous - single await at the end\r\n * await new Image(\"photo.jpg\")\r\n * .resize({ width: 800 })\r\n * .watermark(\"logo.png\", { gravity: \"southeast\" })\r\n * .quality(85)\r\n * .save(\"output.jpg\");\r\n * ```\r\n */\r\nexport class Image {\r\n /**\r\n * Image options that will be applied on save/export\r\n */\r\n protected options: InternalOptions = {};\r\n\r\n /**\r\n * Deferred operations pipeline\r\n */\r\n protected operations: ImageOperation[] = [];\r\n\r\n /**\r\n * Cached metadata to avoid repeated async calls\r\n */\r\n protected cachedMetadata: sharp.Metadata | null = null;\r\n\r\n /**\r\n * Whether the pipeline has been executed\r\n */\r\n protected pipelineExecuted = false;\r\n\r\n /**\r\n * Sharp image object\r\n */\r\n public readonly image: sharp.Sharp;\r\n\r\n /**\r\n * Formats that support quality option\r\n */\r\n protected static readonly QUALITY_FORMATS = [\"jpeg\", \"jpg\", \"webp\", \"avif\", \"tiff\", \"heif\"];\r\n\r\n /**\r\n * Constructor\r\n */\r\n public constructor(image: ImageInput | sharp.Sharp) {\r\n if (moduleExists === false) {\r\n throw new Error(`sharp is not installed.\\n\\n${SHARP_INSTALL_INSTRUCTIONS}`);\r\n }\r\n\r\n // Check if it's already a sharp instance\r\n if (image instanceof Object && \"clone\" in image && typeof image.clone === \"function\") {\r\n this.image = image as sharp.Sharp;\r\n } else {\r\n this.image = sharpFn(image as ImageInput);\r\n }\r\n }\r\n\r\n /**\r\n * Create image instance from file path\r\n */\r\n public static fromFile(path: string): Image {\r\n return new Image(path);\r\n }\r\n\r\n /**\r\n * Create image instance from buffer\r\n */\r\n public static fromBuffer(buffer: Buffer): Image {\r\n return new Image(buffer);\r\n }\r\n\r\n /**\r\n * Create image instance from url\r\n */\r\n public static async fromUrl(url: string): Promise<Image> {\r\n const { data, error } = await http.get<ArrayBuffer>(url, {\r\n responseType: \"arrayBuffer\",\r\n });\r\n\r\n if (error || !data) {\r\n throw new Error(\r\n `Failed to load image from URL \"${url}\": ${error?.message ?? \"Empty response received\"}`,\r\n );\r\n }\r\n\r\n return new Image(Buffer.from(data));\r\n }\r\n\r\n /**\r\n * Add an operation to the deferred pipeline\r\n */\r\n protected addOperation(operation: ImageOperation): this {\r\n this.operations.push(operation);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Apply multiple transformations at once with a predefined execution order.\r\n *\r\n * This method ensures transformations are applied in a logical order:\r\n * resize → crop → rotate → flip/flop → colorspace → effects → opacity → format\r\n *\r\n * For custom ordering, use individual chained methods instead.\r\n */\r\n public apply(options: ImageTransformOptions): this {\r\n // 1. Resize first to work with correct dimensions\r\n if (options.resize) {\r\n this.resize(options.resize);\r\n }\r\n\r\n // 2. Crop after resize\r\n if (options.crop) {\r\n this.crop(options.crop);\r\n }\r\n\r\n // 3. Rotation\r\n if (options.rotate !== undefined) {\r\n this.rotate(options.rotate);\r\n }\r\n\r\n // 4. Mirror operations\r\n if (options.flip) {\r\n this.flip();\r\n }\r\n\r\n if (options.flop) {\r\n this.flop();\r\n }\r\n\r\n // 5. Color space conversion\r\n if (options.blackAndWhite || options.grayscale) {\r\n this.blackAndWhite();\r\n }\r\n\r\n // 6. Blur effect\r\n if (options.blur !== undefined) {\r\n this.blur(options.blur);\r\n }\r\n\r\n // 7. Sharpen effect\r\n if (options.sharpen) {\r\n const sharpenOptions = typeof options.sharpen === \"boolean\" ? undefined : options.sharpen;\r\n this.sharpen(sharpenOptions);\r\n }\r\n\r\n // 8. Tint color\r\n if (options.tint) {\r\n this.tint(options.tint);\r\n }\r\n\r\n // 9. Negate/invert\r\n if (options.negate) {\r\n const negateOptions = typeof options.negate === \"boolean\" ? undefined : options.negate;\r\n this.negate(negateOptions);\r\n }\r\n\r\n // 10. Trim edges\r\n if (options.trim) {\r\n const trimOptions = typeof options.trim === \"boolean\" ? undefined : options.trim;\r\n this.trim(trimOptions);\r\n }\r\n\r\n // 11. Watermarks\r\n if (options.watermark) {\r\n this.watermark(options.watermark.image, options.watermark.options);\r\n }\r\n\r\n if (options.watermarks) {\r\n this.watermarks(options.watermarks);\r\n }\r\n\r\n // 12. Opacity (applied via composite)\r\n if (options.opacity !== undefined) {\r\n this.opacity(options.opacity);\r\n }\r\n\r\n // 13. Store format/quality for deferred application\r\n if (options.format) {\r\n this.format(options.format);\r\n }\r\n\r\n if (options.quality !== undefined) {\r\n this.quality(options.quality);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set image opacity (0-100)\r\n */\r\n public opacity(value: number): this {\r\n if (value < 0 || value > 100) {\r\n throw new Error(\"Opacity must be between 0 and 100\");\r\n }\r\n\r\n return this.addOperation({ type: \"opacity\", value });\r\n }\r\n\r\n /**\r\n * Convert image to black and white\r\n */\r\n public blackAndWhite(): this {\r\n return this.addOperation({ type: \"blackAndWhite\" });\r\n }\r\n\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n public grayscale(): this {\r\n return this.blackAndWhite();\r\n }\r\n\r\n /**\r\n * Get image dimensions (cached after first call)\r\n */\r\n public async dimensions(): Promise<{\r\n width: number | undefined;\r\n height: number | undefined;\r\n }> {\r\n const metadata = await this.metadata();\r\n\r\n return { width: metadata.width, height: metadata.height };\r\n }\r\n\r\n /**\r\n * Get image metadata (cached after first call)\r\n *\r\n * The metadata is cached to avoid repeated async operations.\r\n * Use `refreshMetadata()` to force a fresh fetch.\r\n */\r\n public async metadata(): Promise<sharp.Metadata> {\r\n if (!this.cachedMetadata) {\r\n this.cachedMetadata = await this.image.metadata();\r\n }\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Force refresh of cached metadata\r\n *\r\n * Call this after transformations if you need updated metadata.\r\n */\r\n public async refreshMetadata(): Promise<sharp.Metadata> {\r\n this.cachedMetadata = await this.image.metadata();\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Clear cached metadata\r\n */\r\n public clearMetadataCache(): this {\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Resize image\r\n */\r\n public resize(options: sharp.ResizeOptions): this {\r\n if (typeof options.width !== \"undefined\" && !options.width) {\r\n delete options.width;\r\n }\r\n\r\n if (typeof options.height !== \"undefined\" && !options.height) {\r\n delete options.height;\r\n }\r\n\r\n return this.addOperation({ type: \"resize\", options });\r\n }\r\n\r\n /**\r\n * Crop/extract a region from the image\r\n */\r\n public crop(options: sharp.Region): this {\r\n return this.addOperation({ type: \"crop\", options });\r\n }\r\n\r\n /**\r\n * Set image quality (1-100)\r\n * Quality is stored and applied when saving/exporting\r\n * based on the final format.\r\n */\r\n public quality(quality: number): this {\r\n if (quality < 1 || quality > 100) {\r\n throw new Error(\"Quality must be between 1 and 100\");\r\n }\r\n\r\n this.options.quality = quality;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Execute the deferred pipeline - apply all stored operations\r\n */\r\n protected async executePipeline(): Promise<sharp.Sharp> {\r\n if (this.pipelineExecuted) {\r\n return this.image;\r\n }\r\n\r\n for (const operation of this.operations) {\r\n await this.executeOperation(this.image, operation);\r\n }\r\n\r\n await this.applyFormatAndQuality(this.image);\r\n\r\n this.pipelineExecuted = true;\r\n\r\n return this.image;\r\n }\r\n\r\n /**\r\n * Execute a single operation\r\n */\r\n protected async executeOperation(image: sharp.Sharp, operation: ImageOperation): Promise<void> {\r\n switch (operation.type) {\r\n case \"resize\":\r\n image.resize(operation.options);\r\n break;\r\n\r\n case \"crop\":\r\n image.extract(operation.options);\r\n break;\r\n\r\n case \"rotate\":\r\n image.rotate(operation.angle);\r\n break;\r\n\r\n case \"flip\":\r\n image.flip();\r\n break;\r\n\r\n case \"flop\":\r\n image.flop();\r\n break;\r\n\r\n case \"blur\":\r\n image.blur(operation.sigma);\r\n break;\r\n\r\n case \"sharpen\":\r\n image.sharpen(operation.options);\r\n break;\r\n\r\n case \"blackAndWhite\":\r\n image.toColourspace(\"b-w\");\r\n break;\r\n\r\n case \"opacity\": {\r\n const alpha = Math.round((operation.value / 100) * 255);\r\n const alphaPixel = Buffer.from([255, 255, 255, alpha]);\r\n image.composite([\r\n {\r\n blend: \"dest-in\",\r\n input: alphaPixel,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"negate\":\r\n image.negate(operation.options);\r\n break;\r\n\r\n case \"tint\":\r\n image.tint(operation.color);\r\n break;\r\n\r\n case \"trim\":\r\n image.trim(operation.options);\r\n break;\r\n\r\n case \"watermark\": {\r\n const buffer = await this.resolveImageBuffer(operation.config.image);\r\n image.composite([\r\n {\r\n input: buffer,\r\n ...operation.config.options,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"watermarks\": {\r\n const buffers = await Promise.all(\r\n operation.configs.map((config) => this.resolveImageBuffer(config.image)),\r\n );\r\n image.composite(\r\n operation.configs.map((config, index) => ({\r\n input: buffers[index],\r\n ...config.options,\r\n })),\r\n );\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Resolve an image input to a buffer\r\n */\r\n protected async resolveImageBuffer(input: ImageInput | Image): Promise<Buffer> {\r\n if (input instanceof Image) {\r\n // For Image instances, get buffer without applying options (raw buffer)\r\n return input.image.toBuffer();\r\n }\r\n\r\n // For other inputs (path, buffer, etc.), create temp sharp instance\r\n const tempImage = sharpFn(input);\r\n\r\n return tempImage.toBuffer();\r\n }\r\n\r\n /**\r\n * Apply format and quality options.\r\n * If no format is explicitly set, preserves the original format and applies\r\n * quality appropriately based on the format type.\r\n */\r\n protected async applyFormatAndQuality(image: sharp.Sharp): Promise<void> {\r\n const { quality, format } = this.options;\r\n\r\n if (format) {\r\n // Explicit format specified\r\n const formatOptions = quality ? { quality } : undefined;\r\n image.toFormat(format, formatOptions);\r\n return;\r\n }\r\n\r\n if (quality === undefined) {\r\n // No quality or format set, nothing to apply\r\n return;\r\n }\r\n\r\n // Quality is set but no format specified - detect original format\r\n const metadata = await this.metadata();\r\n const originalFormat = metadata.format;\r\n\r\n if (!originalFormat) {\r\n // Cannot detect format, default to webp with quality\r\n image.webp({ quality });\r\n return;\r\n }\r\n\r\n // Apply quality based on original format\r\n if (Image.QUALITY_FORMATS.includes(originalFormat)) {\r\n // Format supports quality option\r\n image.toFormat(originalFormat as ImageFormat, { quality });\r\n } else if (originalFormat === \"png\") {\r\n // PNG uses compressionLevel (0-9) instead of quality\r\n // Map quality 1-100 to compressionLevel 9-0 (higher quality = lower compression)\r\n const compressionLevel = Math.round(9 - (quality / 100) * 9);\r\n image.png({ compressionLevel });\r\n } else if (originalFormat === \"gif\") {\r\n // GIF doesn't support quality, just preserve format\r\n image.gif();\r\n }\r\n // Unknown format: preserve as-is (no quality applied)\r\n }\r\n\r\n /**\r\n * Save to file\r\n */\r\n public async save(path: string): Promise<sharp.OutputInfo> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Convert to webp and save to file\r\n */\r\n public async saveAsWebp(path: string): Promise<sharp.OutputInfo> {\r\n // Override format to webp\r\n this.options.format = \"webp\";\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Change the file format\r\n */\r\n public format(format: ImageFormat): this {\r\n this.options.format = format;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Add watermark (deferred - executed at save time)\r\n */\r\n public watermark(image: ImageInput | Image, options: sharp.OverlayOptions = {}): this {\r\n return this.addOperation({\r\n type: \"watermark\",\r\n config: { image, options },\r\n });\r\n }\r\n\r\n /**\r\n * Add multiple watermarks (deferred - executed at save time)\r\n */\r\n public watermarks(configs: WatermarkConfig[]): this {\r\n return this.addOperation({\r\n type: \"watermarks\",\r\n configs,\r\n });\r\n }\r\n\r\n /**\r\n * Rotate image\r\n */\r\n public rotate(angle: number): this {\r\n return this.addOperation({ type: \"rotate\", angle });\r\n }\r\n\r\n /**\r\n * Flip image vertically (top to bottom)\r\n */\r\n public flip(): this {\r\n return this.addOperation({ type: \"flip\" });\r\n }\r\n\r\n /**\r\n * Flop image horizontally (left to right)\r\n */\r\n public flop(): this {\r\n return this.addOperation({ type: \"flop\" });\r\n }\r\n\r\n /**\r\n * Blur image\r\n */\r\n public blur(sigma: number): this {\r\n if (sigma < 0.3) {\r\n throw new Error(\"Blur sigma must be at least 0.3\");\r\n }\r\n\r\n return this.addOperation({ type: \"blur\", sigma });\r\n }\r\n\r\n /**\r\n * Convert to base64\r\n */\r\n public async toBase64(): Promise<string> {\r\n const image = await this.executePipeline();\r\n const buffer = await image.toBuffer();\r\n\r\n return buffer.toString(\"base64\");\r\n }\r\n\r\n /**\r\n * Convert to data URL (base64 with mime type prefix)\r\n */\r\n public async toDataUrl(): Promise<string> {\r\n const metadata = await this.metadata();\r\n const format = this.options.format || metadata.format || \"png\";\r\n const mimeType = `image/${format === \"jpg\" ? \"jpeg\" : format}`;\r\n const base64 = await this.toBase64();\r\n\r\n return `data:${mimeType};base64,${base64}`;\r\n }\r\n\r\n /**\r\n * Sharpen image\r\n */\r\n public sharpen(options?: sharp.SharpenOptions): this {\r\n return this.addOperation({ type: \"sharpen\", options });\r\n }\r\n\r\n /**\r\n * Negate/invert image colors\r\n */\r\n public negate(options?: sharp.NegateOptions): this {\r\n return this.addOperation({ type: \"negate\", options });\r\n }\r\n\r\n /**\r\n * Tint image with a color\r\n */\r\n public tint(color: sharp.Color): this {\r\n return this.addOperation({ type: \"tint\", color });\r\n }\r\n\r\n /**\r\n * Trim edges from the image\r\n */\r\n public trim(options?: sharp.TrimOptions): this {\r\n return this.addOperation({ type: \"trim\", options });\r\n }\r\n\r\n /**\r\n * Convert to buffer\r\n */\r\n public async toBuffer(): Promise<Buffer> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toBuffer();\r\n }\r\n\r\n /**\r\n * Clone the image for separate transformations\r\n */\r\n public clone(): Image {\r\n const clonedImage = new Image(this.image.clone());\r\n clonedImage.options = { ...this.options };\r\n clonedImage.operations = [...this.operations];\r\n clonedImage.cachedMetadata = this.cachedMetadata ? { ...this.cachedMetadata } : null;\r\n\r\n return clonedImage;\r\n }\r\n\r\n /**\r\n * Get the current stored options\r\n */\r\n public getOptions(): Readonly<InternalOptions> {\r\n return { ...this.options };\r\n }\r\n\r\n /**\r\n * Get the pending operations count\r\n */\r\n public getPendingOperationsCount(): number {\r\n return this.operations.length;\r\n }\r\n\r\n /**\r\n * Reset all stored options\r\n */\r\n public resetOptions(): this {\r\n this.options = {};\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Clear all pending operations\r\n */\r\n public clearOperations(): this {\r\n this.operations = [];\r\n this.pipelineExecuted = false;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Reset the image to its initial state (clear operations and options)\r\n */\r\n public reset(): this {\r\n this.operations = [];\r\n this.options = {};\r\n this.pipelineExecuted = false;\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n}\r\n"],"mappings":";;;;;;AAWA,MAAM,6BAA6B;;;;;;;;;;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AK,WAAW;CACzB;;;;CAKA,AAAO,eAAqB;EAC1B,KAAK,UAAU,CAAC;EAEhB,OAAO;CACT;;;;CAKA,AAAO,kBAAwB;EAC7B,KAAK,aAAa,CAAC;EACnB,KAAK,mBAAmB;EAExB,OAAO;CACT;;;;CAKA,AAAO,QAAc;EACnB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAChB,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;EAEtB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../core/src/image/image.ts"],"sourcesContent":["import { http } from \"@mongez/http\";\r\nimport { createRequire } from \"node:module\";\r\nimport type sharp from \"sharp\";\r\nimport type { FormatEnum } from \"sharp\";\r\n\r\n// ============================================================\r\n// Lazily Resolved Sharp Module\r\n// ============================================================\r\n\r\n/**\r\n * Installation instructions for sharp\r\n */\r\nconst SHARP_INSTALL_INSTRUCTIONS = `\r\nImage processing requires the sharp package.\r\nInstall it with:\r\n\r\n warlock add image\r\n\r\nOr manually:\r\n\r\n npm install sharp\r\n pnpm add sharp\r\n yarn add sharp\r\n`.trim();\r\n\r\n/**\r\n * Cached sharp function, populated by the first `resolveSharp()` call\r\n */\r\nlet sharpFn: typeof sharp | null = null;\r\n\r\n/**\r\n * Whether the resolution attempt already ran (success or failure)\r\n */\r\nlet sharpResolved = false;\r\n\r\n/**\r\n * Why the resolution failed, when it failed for a reason other than absence.\r\n *\r\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\r\n * once, so without this the second construction would fall through to the\r\n * \"not installed\" branch and report a different, wrong cause.\r\n */\r\nlet sharpLoadError: Error | null = null;\r\n\r\n/**\r\n * `new Error(message, { cause })` is ES2022, and this package still compiles\r\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\r\n * only. Node has supported the option since v16, so this is the type layer\r\n * catching up with the runtime, not a change in what the code does.\r\n */\r\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\r\n\r\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\r\n\r\n/**\r\n * Whether `error` says sharp itself is absent, as opposed to present but broken.\r\n *\r\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\r\n * dependency missing *inside* sharp raises the very same code (`Cannot find\r\n * module 'color'`), and treating that as absence would tell the operator to\r\n * install a package they already have. So the message has to name the specifier\r\n * `'sharp'` exactly — quoted, which is also what keeps `'sharp-cli'` and friends\r\n * from matching.\r\n */\r\nfunction isSharpMissing(error: unknown): boolean {\r\n if (!(error instanceof Error)) return false;\r\n\r\n return (\r\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\r\n error.message.includes(\"Cannot find module 'sharp'\")\r\n );\r\n}\r\n\r\n/**\r\n * Resolve sharp synchronously, on first use.\r\n *\r\n * Resolution is deliberately *lazy* and *synchronous*:\r\n *\r\n * - Lazy, because a top-level require would drag sharp's native binary into\r\n * every `import \"@warlock.js/core\"`, including apps that never touch images.\r\n * - Synchronous, because the `Image` constructor is synchronous. An async\r\n * import kicked off at module load leaves a window in which the module is\r\n * neither loaded nor known to be missing, and a constructor running inside\r\n * that window has no correct answer to give.\r\n *\r\n * `createRequire` gives an ESM-safe `require`, and the outcome — module, absence\r\n * or load failure — is cached, so the resolution runs exactly once per process.\r\n * The failure *reason* is cached too, not just the fact of it: every call after\r\n * a failed load has to report the same cause as the first one.\r\n *\r\n * @throws when sharp is not installed, or is installed but cannot be loaded\r\n */\r\nfunction resolveSharp(): typeof sharp {\r\n if (!sharpResolved) {\r\n sharpResolved = true;\r\n\r\n try {\r\n const require = createRequire(import.meta.url);\r\n const module = require(\"sharp\");\r\n sharpFn = (module.default ?? module) as typeof sharp;\r\n } catch (error) {\r\n sharpFn = null;\r\n\r\n if (!isSharpMissing(error)) {\r\n // sharp is there, it just would not load — almost always a binary built\r\n // for another platform. Its own error names the runtime and the fix, so\r\n // it is inlined *and* chained: a terminal that never prints `cause`\r\n // must still show the text that actually helps.\r\n sharpLoadError = new ErrorWithCause(\r\n `Failed to load \"sharp\": ${(error as Error).message}`,\r\n { cause: error },\r\n );\r\n }\r\n }\r\n }\r\n\r\n if (sharpLoadError) {\r\n throw sharpLoadError;\r\n }\r\n\r\n if (!sharpFn) {\r\n throw new Error(`sharp is not installed.\\n\\n${SHARP_INSTALL_INSTRUCTIONS}`);\r\n }\r\n\r\n return sharpFn;\r\n}\r\n\r\n// ============================================================\r\n// Types\r\n// ============================================================\r\n\r\nexport type ImageFormat = keyof FormatEnum;\r\n\r\nexport type ImageInput = string | Buffer | Uint8Array | ArrayBuffer;\r\n\r\n/**\r\n * Watermark configuration for deferred execution\r\n */\r\nexport type WatermarkConfig = {\r\n image: ImageInput | Image;\r\n options: sharp.OverlayOptions;\r\n};\r\n\r\n/**\r\n * Operation descriptor for deferred pipeline execution.\r\n * All operations are stored and executed at save/toBuffer time.\r\n */\r\ntype ImageOperation =\r\n | { type: \"resize\"; options: sharp.ResizeOptions }\r\n | { type: \"crop\"; options: sharp.Region }\r\n | { type: \"rotate\"; angle: number }\r\n | { type: \"flip\" }\r\n | { type: \"flop\" }\r\n | { type: \"blur\"; sigma: number }\r\n | { type: \"sharpen\"; options?: sharp.SharpenOptions }\r\n | { type: \"blackAndWhite\" }\r\n | { type: \"opacity\"; value: number }\r\n | { type: \"negate\"; options?: sharp.NegateOptions }\r\n | { type: \"tint\"; color: sharp.Color }\r\n | { type: \"trim\"; options?: sharp.TrimOptions }\r\n | { type: \"watermark\"; config: WatermarkConfig }\r\n | { type: \"watermarks\"; configs: WatermarkConfig[] };\r\n\r\n/**\r\n * Transformation options that can be applied in batch via `apply()` method.\r\n *\r\n * **Execution Order (when using apply()):**\r\n * 1. resize - Resize first to work with correct dimensions\r\n * 2. crop - Crop after resize to extract the desired region\r\n * 3. rotate - Rotation after sizing\r\n * 4. flip/flop - Mirror operations\r\n * 5. blackAndWhite/grayscale - Color space conversion\r\n * 6. blur - Blur effect\r\n * 7. sharpen - Sharpen effect\r\n * 8. tint - Color overlay\r\n * 9. negate - Invert colors\r\n * 10. opacity - Transparency (applied via composite)\r\n * 11. format/quality - Applied on save/export\r\n */\r\nexport type ImageTransformOptions = {\r\n /**\r\n * Output quality (1-100), applied based on final format\r\n */\r\n quality?: number;\r\n /**\r\n * Output format (jpeg, png, webp, avif, etc.)\r\n */\r\n format?: ImageFormat;\r\n /**\r\n * Resize options\r\n */\r\n resize?: sharp.ResizeOptions;\r\n /**\r\n * Crop/extract region\r\n */\r\n crop?: sharp.Region;\r\n /**\r\n * Rotation angle in degrees\r\n */\r\n rotate?: number;\r\n /**\r\n * Flip vertically (top to bottom)\r\n */\r\n flip?: boolean;\r\n /**\r\n * Flop horizontally (left to right)\r\n */\r\n flop?: boolean;\r\n /**\r\n * Convert to black and white\r\n */\r\n blackAndWhite?: boolean;\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n grayscale?: boolean;\r\n /**\r\n * Blur sigma (must be >= 0.3)\r\n */\r\n blur?: number;\r\n /**\r\n * Sharpen options\r\n */\r\n sharpen?: sharp.SharpenOptions | boolean;\r\n /**\r\n * Tint color\r\n */\r\n tint?: sharp.Color;\r\n /**\r\n * Negate/invert colors\r\n */\r\n negate?: sharp.NegateOptions | boolean;\r\n /**\r\n * Opacity (0-100)\r\n */\r\n opacity?: number;\r\n /**\r\n * Trim options\r\n */\r\n trim?: sharp.TrimOptions | boolean;\r\n /**\r\n * Single watermark\r\n */\r\n watermark?: WatermarkConfig;\r\n /**\r\n * Multiple watermarks\r\n */\r\n watermarks?: WatermarkConfig[];\r\n};\r\n\r\n/**\r\n * Internal options stored for deferred application\r\n */\r\ntype InternalOptions = {\r\n quality?: number;\r\n format?: ImageFormat;\r\n};\r\n\r\n/**\r\n * Image manipulation class with deferred pipeline execution.\r\n *\r\n * **Important:** This class requires the `sharp` package to be installed.\r\n * Install it with: `warlock add image` or `npm install sharp`\r\n *\r\n * Sharp is resolved synchronously on the first construction that needs it, so\r\n * the constructor and all chainable methods remain synchronous, and a missing\r\n * sharp throws at construction rather than at some later await.\r\n *\r\n * All operations are synchronous and stored as descriptors.\r\n * The pipeline is executed only when calling output methods:\r\n * - `save()` - Save to file\r\n * - `toBuffer()` - Get as buffer\r\n * - `toBase64()` - Get as base64 string\r\n * - `toDataUrl()` - Get as data URL\r\n *\r\n * @example\r\n * ```typescript\r\n * // All chaining is synchronous - single await at the end\r\n * await new Image(\"photo.jpg\")\r\n * .resize({ width: 800 })\r\n * .watermark(\"logo.png\", { gravity: \"southeast\" })\r\n * .quality(85)\r\n * .save(\"output.jpg\");\r\n * ```\r\n */\r\nexport class Image {\r\n /**\r\n * Image options that will be applied on save/export\r\n */\r\n protected options: InternalOptions = {};\r\n\r\n /**\r\n * Deferred operations pipeline\r\n */\r\n protected operations: ImageOperation[] = [];\r\n\r\n /**\r\n * Cached metadata to avoid repeated async calls\r\n */\r\n protected cachedMetadata: sharp.Metadata | null = null;\r\n\r\n /**\r\n * Whether the pipeline has been executed\r\n */\r\n protected pipelineExecuted = false;\r\n\r\n /**\r\n * Sharp image object\r\n */\r\n public readonly image: sharp.Sharp;\r\n\r\n /**\r\n * Formats that support quality option\r\n */\r\n protected static readonly QUALITY_FORMATS = [\"jpeg\", \"jpg\", \"webp\", \"avif\", \"tiff\", \"heif\"];\r\n\r\n /**\r\n * Constructor\r\n */\r\n public constructor(image: ImageInput | sharp.Sharp) {\r\n // An existing sharp instance carries its own module — short-circuit before\r\n // resolving sharp, so cloning never pays for (or fails on) a module load.\r\n if (image instanceof Object && \"clone\" in image && typeof image.clone === \"function\") {\r\n this.image = image as sharp.Sharp;\r\n } else {\r\n this.image = resolveSharp()(image as ImageInput);\r\n }\r\n }\r\n\r\n /**\r\n * Create image instance from file path\r\n */\r\n public static fromFile(path: string): Image {\r\n return new Image(path);\r\n }\r\n\r\n /**\r\n * Create image instance from buffer\r\n */\r\n public static fromBuffer(buffer: Buffer): Image {\r\n return new Image(buffer);\r\n }\r\n\r\n /**\r\n * Create image instance from url\r\n */\r\n public static async fromUrl(url: string): Promise<Image> {\r\n const { data, error } = await http.get<ArrayBuffer>(url, {\r\n responseType: \"arrayBuffer\",\r\n });\r\n\r\n if (error || !data) {\r\n throw new Error(\r\n `Failed to load image from URL \"${url}\": ${error?.message ?? \"Empty response received\"}`,\r\n );\r\n }\r\n\r\n return new Image(Buffer.from(data));\r\n }\r\n\r\n /**\r\n * Add an operation to the deferred pipeline\r\n */\r\n protected addOperation(operation: ImageOperation): this {\r\n this.operations.push(operation);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Apply multiple transformations at once with a predefined execution order.\r\n *\r\n * This method ensures transformations are applied in a logical order:\r\n * resize → crop → rotate → flip/flop → colorspace → effects → opacity → format\r\n *\r\n * For custom ordering, use individual chained methods instead.\r\n */\r\n public apply(options: ImageTransformOptions): this {\r\n // 1. Resize first to work with correct dimensions\r\n if (options.resize) {\r\n this.resize(options.resize);\r\n }\r\n\r\n // 2. Crop after resize\r\n if (options.crop) {\r\n this.crop(options.crop);\r\n }\r\n\r\n // 3. Rotation\r\n if (options.rotate !== undefined) {\r\n this.rotate(options.rotate);\r\n }\r\n\r\n // 4. Mirror operations\r\n if (options.flip) {\r\n this.flip();\r\n }\r\n\r\n if (options.flop) {\r\n this.flop();\r\n }\r\n\r\n // 5. Color space conversion\r\n if (options.blackAndWhite || options.grayscale) {\r\n this.blackAndWhite();\r\n }\r\n\r\n // 6. Blur effect\r\n if (options.blur !== undefined) {\r\n this.blur(options.blur);\r\n }\r\n\r\n // 7. Sharpen effect\r\n if (options.sharpen) {\r\n const sharpenOptions = typeof options.sharpen === \"boolean\" ? undefined : options.sharpen;\r\n this.sharpen(sharpenOptions);\r\n }\r\n\r\n // 8. Tint color\r\n if (options.tint) {\r\n this.tint(options.tint);\r\n }\r\n\r\n // 9. Negate/invert\r\n if (options.negate) {\r\n const negateOptions = typeof options.negate === \"boolean\" ? undefined : options.negate;\r\n this.negate(negateOptions);\r\n }\r\n\r\n // 10. Trim edges\r\n if (options.trim) {\r\n const trimOptions = typeof options.trim === \"boolean\" ? undefined : options.trim;\r\n this.trim(trimOptions);\r\n }\r\n\r\n // 11. Watermarks\r\n if (options.watermark) {\r\n this.watermark(options.watermark.image, options.watermark.options);\r\n }\r\n\r\n if (options.watermarks) {\r\n this.watermarks(options.watermarks);\r\n }\r\n\r\n // 12. Opacity (applied via composite)\r\n if (options.opacity !== undefined) {\r\n this.opacity(options.opacity);\r\n }\r\n\r\n // 13. Store format/quality for deferred application\r\n if (options.format) {\r\n this.format(options.format);\r\n }\r\n\r\n if (options.quality !== undefined) {\r\n this.quality(options.quality);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set image opacity (0-100)\r\n */\r\n public opacity(value: number): this {\r\n if (value < 0 || value > 100) {\r\n throw new Error(\"Opacity must be between 0 and 100\");\r\n }\r\n\r\n return this.addOperation({ type: \"opacity\", value });\r\n }\r\n\r\n /**\r\n * Convert image to black and white\r\n */\r\n public blackAndWhite(): this {\r\n return this.addOperation({ type: \"blackAndWhite\" });\r\n }\r\n\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n public grayscale(): this {\r\n return this.blackAndWhite();\r\n }\r\n\r\n /**\r\n * Get image dimensions (cached after first call)\r\n */\r\n public async dimensions(): Promise<{\r\n width: number | undefined;\r\n height: number | undefined;\r\n }> {\r\n const metadata = await this.metadata();\r\n\r\n return { width: metadata.width, height: metadata.height };\r\n }\r\n\r\n /**\r\n * Get image metadata (cached after first call)\r\n *\r\n * The metadata is cached to avoid repeated async operations.\r\n * Use `refreshMetadata()` to force a fresh fetch.\r\n */\r\n public async metadata(): Promise<sharp.Metadata> {\r\n if (!this.cachedMetadata) {\r\n this.cachedMetadata = await this.image.metadata();\r\n }\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Force refresh of cached metadata\r\n *\r\n * Call this after transformations if you need updated metadata.\r\n */\r\n public async refreshMetadata(): Promise<sharp.Metadata> {\r\n this.cachedMetadata = await this.image.metadata();\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Clear cached metadata\r\n */\r\n public clearMetadataCache(): this {\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Resize image\r\n */\r\n public resize(options: sharp.ResizeOptions): this {\r\n if (typeof options.width !== \"undefined\" && !options.width) {\r\n delete options.width;\r\n }\r\n\r\n if (typeof options.height !== \"undefined\" && !options.height) {\r\n delete options.height;\r\n }\r\n\r\n return this.addOperation({ type: \"resize\", options });\r\n }\r\n\r\n /**\r\n * Crop/extract a region from the image\r\n */\r\n public crop(options: sharp.Region): this {\r\n return this.addOperation({ type: \"crop\", options });\r\n }\r\n\r\n /**\r\n * Set image quality (1-100)\r\n * Quality is stored and applied when saving/exporting\r\n * based on the final format.\r\n */\r\n public quality(quality: number): this {\r\n if (quality < 1 || quality > 100) {\r\n throw new Error(\"Quality must be between 1 and 100\");\r\n }\r\n\r\n this.options.quality = quality;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Execute the deferred pipeline - apply all stored operations\r\n */\r\n protected async executePipeline(): Promise<sharp.Sharp> {\r\n if (this.pipelineExecuted) {\r\n return this.image;\r\n }\r\n\r\n for (const operation of this.operations) {\r\n await this.executeOperation(this.image, operation);\r\n }\r\n\r\n await this.applyFormatAndQuality(this.image);\r\n\r\n this.pipelineExecuted = true;\r\n\r\n return this.image;\r\n }\r\n\r\n /**\r\n * Execute a single operation\r\n */\r\n protected async executeOperation(image: sharp.Sharp, operation: ImageOperation): Promise<void> {\r\n switch (operation.type) {\r\n case \"resize\":\r\n image.resize(operation.options);\r\n break;\r\n\r\n case \"crop\":\r\n image.extract(operation.options);\r\n break;\r\n\r\n case \"rotate\":\r\n image.rotate(operation.angle);\r\n break;\r\n\r\n case \"flip\":\r\n image.flip();\r\n break;\r\n\r\n case \"flop\":\r\n image.flop();\r\n break;\r\n\r\n case \"blur\":\r\n image.blur(operation.sigma);\r\n break;\r\n\r\n case \"sharpen\":\r\n image.sharpen(operation.options);\r\n break;\r\n\r\n case \"blackAndWhite\":\r\n image.toColourspace(\"b-w\");\r\n break;\r\n\r\n case \"opacity\": {\r\n const alpha = Math.round((operation.value / 100) * 255);\r\n const alphaPixel = Buffer.from([255, 255, 255, alpha]);\r\n image.composite([\r\n {\r\n blend: \"dest-in\",\r\n input: alphaPixel,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"negate\":\r\n image.negate(operation.options);\r\n break;\r\n\r\n case \"tint\":\r\n image.tint(operation.color);\r\n break;\r\n\r\n case \"trim\":\r\n image.trim(operation.options);\r\n break;\r\n\r\n case \"watermark\": {\r\n const buffer = await this.resolveImageBuffer(operation.config.image);\r\n image.composite([\r\n {\r\n input: buffer,\r\n ...operation.config.options,\r\n },\r\n ]);\r\n break;\r\n }\r\n\r\n case \"watermarks\": {\r\n const buffers = await Promise.all(\r\n operation.configs.map((config) => this.resolveImageBuffer(config.image)),\r\n );\r\n image.composite(\r\n operation.configs.map((config, index) => ({\r\n input: buffers[index],\r\n ...config.options,\r\n })),\r\n );\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Resolve an image input to a buffer\r\n */\r\n protected async resolveImageBuffer(input: ImageInput | Image): Promise<Buffer> {\r\n if (input instanceof Image) {\r\n // For Image instances, get buffer without applying options (raw buffer)\r\n return input.image.toBuffer();\r\n }\r\n\r\n // For other inputs (path, buffer, etc.), create temp sharp instance\r\n const tempImage = resolveSharp()(input);\r\n\r\n return tempImage.toBuffer();\r\n }\r\n\r\n /**\r\n * Apply format and quality options.\r\n * If no format is explicitly set, preserves the original format and applies\r\n * quality appropriately based on the format type.\r\n */\r\n protected async applyFormatAndQuality(image: sharp.Sharp): Promise<void> {\r\n const { quality, format } = this.options;\r\n\r\n if (format) {\r\n // Explicit format specified\r\n const formatOptions = quality ? { quality } : undefined;\r\n image.toFormat(format, formatOptions);\r\n return;\r\n }\r\n\r\n if (quality === undefined) {\r\n // No quality or format set, nothing to apply\r\n return;\r\n }\r\n\r\n // Quality is set but no format specified - detect original format\r\n const metadata = await this.metadata();\r\n const originalFormat = metadata.format;\r\n\r\n if (!originalFormat) {\r\n // Cannot detect format, default to webp with quality\r\n image.webp({ quality });\r\n return;\r\n }\r\n\r\n // Apply quality based on original format\r\n if (Image.QUALITY_FORMATS.includes(originalFormat)) {\r\n // Format supports quality option\r\n image.toFormat(originalFormat as ImageFormat, { quality });\r\n } else if (originalFormat === \"png\") {\r\n // PNG uses compressionLevel (0-9) instead of quality\r\n // Map quality 1-100 to compressionLevel 9-0 (higher quality = lower compression)\r\n const compressionLevel = Math.round(9 - (quality / 100) * 9);\r\n image.png({ compressionLevel });\r\n } else if (originalFormat === \"gif\") {\r\n // GIF doesn't support quality, just preserve format\r\n image.gif();\r\n }\r\n // Unknown format: preserve as-is (no quality applied)\r\n }\r\n\r\n /**\r\n * Save to file\r\n */\r\n public async save(path: string): Promise<sharp.OutputInfo> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Convert to webp and save to file\r\n */\r\n public async saveAsWebp(path: string): Promise<sharp.OutputInfo> {\r\n // Override format to webp\r\n this.options.format = \"webp\";\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Change the file format\r\n */\r\n public format(format: ImageFormat): this {\r\n this.options.format = format;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Add watermark (deferred - executed at save time)\r\n */\r\n public watermark(image: ImageInput | Image, options: sharp.OverlayOptions = {}): this {\r\n return this.addOperation({\r\n type: \"watermark\",\r\n config: { image, options },\r\n });\r\n }\r\n\r\n /**\r\n * Add multiple watermarks (deferred - executed at save time)\r\n */\r\n public watermarks(configs: WatermarkConfig[]): this {\r\n return this.addOperation({\r\n type: \"watermarks\",\r\n configs,\r\n });\r\n }\r\n\r\n /**\r\n * Rotate image\r\n */\r\n public rotate(angle: number): this {\r\n return this.addOperation({ type: \"rotate\", angle });\r\n }\r\n\r\n /**\r\n * Flip image vertically (top to bottom)\r\n */\r\n public flip(): this {\r\n return this.addOperation({ type: \"flip\" });\r\n }\r\n\r\n /**\r\n * Flop image horizontally (left to right)\r\n */\r\n public flop(): this {\r\n return this.addOperation({ type: \"flop\" });\r\n }\r\n\r\n /**\r\n * Blur image\r\n */\r\n public blur(sigma: number): this {\r\n if (sigma < 0.3) {\r\n throw new Error(\"Blur sigma must be at least 0.3\");\r\n }\r\n\r\n return this.addOperation({ type: \"blur\", sigma });\r\n }\r\n\r\n /**\r\n * Convert to base64\r\n */\r\n public async toBase64(): Promise<string> {\r\n const image = await this.executePipeline();\r\n const buffer = await image.toBuffer();\r\n\r\n return buffer.toString(\"base64\");\r\n }\r\n\r\n /**\r\n * Convert to data URL (base64 with mime type prefix)\r\n */\r\n public async toDataUrl(): Promise<string> {\r\n const metadata = await this.metadata();\r\n const format = this.options.format || metadata.format || \"png\";\r\n const mimeType = `image/${format === \"jpg\" ? \"jpeg\" : format}`;\r\n const base64 = await this.toBase64();\r\n\r\n return `data:${mimeType};base64,${base64}`;\r\n }\r\n\r\n /**\r\n * Sharpen image\r\n */\r\n public sharpen(options?: sharp.SharpenOptions): this {\r\n return this.addOperation({ type: \"sharpen\", options });\r\n }\r\n\r\n /**\r\n * Negate/invert image colors\r\n */\r\n public negate(options?: sharp.NegateOptions): this {\r\n return this.addOperation({ type: \"negate\", options });\r\n }\r\n\r\n /**\r\n * Tint image with a color\r\n */\r\n public tint(color: sharp.Color): this {\r\n return this.addOperation({ type: \"tint\", color });\r\n }\r\n\r\n /**\r\n * Trim edges from the image\r\n */\r\n public trim(options?: sharp.TrimOptions): this {\r\n return this.addOperation({ type: \"trim\", options });\r\n }\r\n\r\n /**\r\n * Convert to buffer\r\n */\r\n public async toBuffer(): Promise<Buffer> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toBuffer();\r\n }\r\n\r\n /**\r\n * Clone the image for separate transformations\r\n */\r\n public clone(): Image {\r\n const clonedImage = new Image(this.image.clone());\r\n clonedImage.options = { ...this.options };\r\n clonedImage.operations = [...this.operations];\r\n clonedImage.cachedMetadata = this.cachedMetadata ? { ...this.cachedMetadata } : null;\r\n\r\n return clonedImage;\r\n }\r\n\r\n /**\r\n * Get the current stored options\r\n */\r\n public getOptions(): Readonly<InternalOptions> {\r\n return { ...this.options };\r\n }\r\n\r\n /**\r\n * Get the pending operations count\r\n */\r\n public getPendingOperationsCount(): number {\r\n return this.operations.length;\r\n }\r\n\r\n /**\r\n * Reset all stored options\r\n */\r\n public resetOptions(): this {\r\n this.options = {};\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Clear all pending operations\r\n */\r\n public clearOperations(): this {\r\n this.operations = [];\r\n this.pipelineExecuted = false;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Reset the image to its initial state (clear operations and options)\r\n */\r\n public reset(): this {\r\n this.operations = [];\r\n this.options = {};\r\n this.pipelineExecuted = false;\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n}\r\n"],"mappings":";;;;;;;AAYA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,UAA+B;;;;AAKnC,IAAI,gBAAgB;;;;;;;;AASpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAS,eAAe,OAAyB;CAC/C,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,OACG,MAAgC,SAAS,sBAC1C,MAAM,QAAQ,SAAS,4BAA4B;AAEvD;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,eAA6B;CACpC,IAAI,CAAC,eAAe;EAClB,gBAAgB;EAEhB,IAAI;GAEF,MAAM,SADU,cAAc,OAAO,KAAK,GACrB,CAAC,CAAC,OAAO;GAC9B,UAAW,OAAO,WAAW;EAC/B,SAAS,OAAO;GACd,UAAU;GAEV,IAAI,CAAC,eAAe,KAAK,GAKvB,iBAAiB,IAAI,eACnB,2BAA4B,MAAgB,WAC5C,EAAE,OAAO,MAAM,CACjB;EAEJ;CACF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C;EACnB,KAAK,mBAAmB;EAExB,OAAO;CACT;;;;CAKA,AAAO,QAAc;EACnB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAChB,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;EAEtB,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"mailer-pool.d.mts","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"mappings":";;;;;;AA4KA;;iBAAsB,SAAA,CAAU,MAAA,EAAQ,kBAAA,GAAqB,OAAA,CAAQ,WAAA;;;;iBA6C/C,YAAA,CAAa,MAAA,EAAQ,kBAAA,GAAqB,OAAO;;;;iBAcvD,WAAA,CAAY,MAA0B,EAAlB,kBAAkB;;;AA3D0B;iBAyEhE,eAAA;;;;iBAYA,YAAA;EAAkB,IAAA;EAAc,MAAM;AAAA"}
1
+ {"version":3,"file":"mailer-pool.d.mts","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"mappings":";;;;;;AAiLA;;iBAAsB,SAAA,CAAU,MAAA,EAAQ,kBAAA,GAAqB,OAAA,CAAQ,WAAA;;;;iBA6C/C,YAAA,CAAa,MAAA,EAAQ,kBAAA,GAAqB,OAAO;;;;iBAcvD,WAAA,CAAY,MAA0B,EAAlB,kBAAkB;;;AA3D0B;iBAyEhE,eAAA;;;;iBAYA,YAAA;EAAkB,IAAA;EAAc,MAAM;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"mailer-pool.mjs","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type nodemailer from \"nodemailer\";\nimport type { Transporter } from \"nodemailer\";\nimport type { MailConfigurations, SESConfigurations, SMTPConfigurations } from \"./types\";\n\n// ============================================================\n// Eager-loaded Nodemailer Module\n// ============================================================\n\n/**\n * Installation instructions for nodemailer\n */\nconst NODEMAILER_INSTALL_INSTRUCTIONS = `\nEmail functionality requires the nodemailer package.\nInstall it with:\n\n warlock add mail\n\nOr manually:\n\n npm install nodemailer\n pnpm add nodemailer\n yarn add nodemailer\n`.trim();\n\n/**\n * Module availability flag\n */\nlet moduleExists: boolean | null = null;\n\n/**\n * Cached nodemailer module (loaded at import time)\n */\nlet nodemailerModule: typeof nodemailer;\n\nlet nodemailerLoadPromise: Promise<void> | null = null;\n\n/**\n * Eagerly load nodemailer module at import time\n */\nasync function loadNodemailerModule() {\n try {\n const module = await import(\"nodemailer\");\n nodemailerModule = module.default;\n moduleExists = true;\n } catch {\n moduleExists = false;\n }\n}\n\n// Kick off eager loading immediately\nnodemailerLoadPromise = loadNodemailerModule();\n\nconst SES_INSTALL_INSTRUCTIONS = `\nAWS SES functionality requires the @aws-sdk/client-sesv2 package.\nInstall it with:\n\n warlock add ses\n\nOr manually:\n\n npm install @aws-sdk/client-sesv2\n pnpm add @aws-sdk/client-sesv2\n yarn add @aws-sdk/client-sesv2\n`.trim();\n\nlet sesModuleExists: boolean | null = null;\n\nlet sesModule: typeof import(\"@aws-sdk/client-sesv2\");\n\nlet sesLoadPromise: Promise<void> | null = null;\n\nasync function loadSesModule() {\n try {\n const module = await import(\"@aws-sdk/client-sesv2\");\n sesModule = module.default;\n sesModuleExists = true;\n } catch {\n sesModuleExists = false;\n }\n}\n\nsesLoadPromise = loadSesModule();\n\nfunction isSesConfig(config: MailConfigurations): config is SESConfigurations {\n return \"driver\" in config && config.driver === \"ses\";\n}\n\nasync function getSesMailer(config: SESConfigurations): Promise<Transporter> {\n if (sesModuleExists === null && sesLoadPromise) {\n await sesLoadPromise;\n }\n\n if (sesModuleExists === false) {\n throw new Error(`@aws-sdk/client-sesv2 is not installed.\\n\\n${SES_INSTALL_INSTRUCTIONS}`);\n }\n\n const hash = `ses_${config.region}_${config.accessKeyId}`;\n\n const existingTransporter = mailerPool.get(hash);\n if (existingTransporter) {\n return existingTransporter;\n }\n\n log.info(\"mail\", \"pool\", `Creating new SES mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const ses = new sesModule!.SESv2Client({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n\n const transporter = nodemailerModule.createTransport({\n SES: { sesClient: ses, SendEmailCommand: sesModule.SendEmailCommand },\n });\n\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n// ============================================================\n// Mailer Pool\n// ============================================================\n\n/**\n * Mailer pool for connection reuse\n * Maps config hash to transporter instance\n */\nconst mailerPool = new Map<string, Transporter>();\n\n/**\n * Create a hash from mail configuration for pooling\n */\nfunction createConfigHash(config: SMTPConfigurations): string {\n const key = JSON.stringify({\n // SMTP specific fields\n host: config.host,\n port: config.port,\n secure: config.secure,\n auth: config.auth,\n username: config.username,\n password: config.password,\n });\n\n // Simple hash function\n let hash = 0;\n for (let i = 0; i < key.length; i++) {\n const char = key.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n return `mailer_${hash}`;\n}\n\n/**\n * Get hash for any mailer config\n */\nfunction getMailerHash(config: MailConfigurations): string {\n if (isSesConfig(config)) {\n return `ses_${config.region}_${config.accessKeyId}`;\n }\n return createConfigHash(config);\n}\n\n/**\n * Get or create a mailer transporter from the pool\n * Nodemailer is eagerly loaded at import time\n */\nexport async function getMailer(config: MailConfigurations): Promise<Transporter> {\n if (moduleExists === null && nodemailerLoadPromise) {\n await nodemailerLoadPromise;\n }\n\n if (moduleExists === false) {\n throw new Error(`nodemailer is not installed.\\n\\n${NODEMAILER_INSTALL_INSTRUCTIONS}`);\n }\n\n if (isSesConfig(config)) {\n return getSesMailer(config);\n }\n\n const hash = getMailerHash(config);\n\n // Return existing transporter if available\n const existingTransporter = mailerPool.get(hash);\n\n if (existingTransporter) {\n return existingTransporter;\n }\n\n // Create new transporter\n log.info(\"mail\", \"pool\", `Creating new mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const { auth, username, password, requireTLS, tls, ...transportConfig } = config;\n\n const transporter = nodemailerModule.createTransport({\n requireTLS: requireTLS ?? tls,\n auth: auth ?? {\n user: username,\n pass: password,\n },\n ...transportConfig,\n });\n\n // Store in pool\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n/**\n * Verify a mailer connection\n */\nexport async function verifyMailer(config: MailConfigurations): Promise<boolean> {\n const transporter = await getMailer(config);\n\n try {\n await transporter.verify();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Close a specific mailer connection\n */\nexport function closeMailer(config: MailConfigurations): void {\n const hash = getMailerHash(config);\n const transporter = mailerPool.get(hash);\n\n if (transporter) {\n transporter.close();\n mailerPool.delete(hash);\n log.info(\"mail\", \"pool\", `Closed mailer transport (pool size: ${mailerPool.size})`);\n }\n}\n\n/**\n * Close all mailer connections\n */\nexport function closeAllMailers(): void {\n for (const [hash, transporter] of mailerPool) {\n transporter.close();\n mailerPool.delete(hash);\n }\n\n log.info(\"mail\", \"pool\", \"Closed all mailer transports\");\n}\n\n/**\n * Get pool statistics\n */\nexport function getPoolStats(): { size: number; hashes: string[] } {\n return {\n size: mailerPool.size,\n hashes: Array.from(mailerPool.keys()),\n };\n}\n"],"mappings":";;;;;;AAYA,MAAM,kCAAkC;;;;;;;;;;;EAWtC,KAAK;;;;AAKP,IAAI,eAA+B;;;;AAKnC,IAAI;AAEJ,IAAI,wBAA8C;;;;AAKlD,eAAe,uBAAuB;CACpC,IAAI;EAEF,oBAAmB,MADE,OAAO,cACH,CAAC;EAC1B,eAAe;CACjB,QAAQ;EACN,eAAe;CACjB;AACF;AAGA,wBAAwB,qBAAqB;AAE7C,MAAM,2BAA2B;;;;;;;;;;;EAW/B,KAAK;AAEP,IAAI,kBAAkC;AAEtC,IAAI;AAEJ,IAAI,iBAAuC;AAE3C,eAAe,gBAAgB;CAC7B,IAAI;EAEF,aAAY,MADS,OAAO,yBACV,CAAC;EACnB,kBAAkB;CACpB,QAAQ;EACN,kBAAkB;CACpB;AACF;AAEA,iBAAiB,cAAc;AAE/B,SAAS,YAAY,QAAyD;CAC5E,OAAO,YAAY,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OACnB,MAAM,IAAI,MAAM,mCAAmC,iCAAiC;CAGtF,IAAI,YAAY,MAAM,GACpB,OAAO,aAAa,MAAM;CAG5B,MAAM,OAAO,cAAc,MAAM;CAGjC,MAAM,sBAAsB,WAAW,IAAI,IAAI;CAE/C,IAAI,qBACF,OAAO;CAIT,IAAI,KAAK,QAAQ,QAAQ,6CAA6C,WAAW,OAAO,EAAE,EAAE;CAE5F,MAAM,EAAE,MAAM,UAAU,UAAU,YAAY,KAAK,GAAG,oBAAoB;CAE1E,MAAM,cAAc,iBAAiB,gBAAgB;EACnD,YAAY,cAAc;EAC1B,MAAM,QAAQ;GACZ,MAAM;GACN,MAAM;EACR;EACA,GAAG;CACL,CAAC;CAGD,WAAW,IAAI,MAAM,WAAW;CAEhC,OAAO;AACT;;;;AAKA,eAAsB,aAAa,QAA8C;CAC/E,MAAM,cAAc,MAAM,UAAU,MAAM;CAE1C,IAAI;EACF,MAAM,YAAY,OAAO;EACzB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;AAKA,SAAgB,YAAY,QAAkC;CAC5D,MAAM,OAAO,cAAc,MAAM;CACjC,MAAM,cAAc,WAAW,IAAI,IAAI;CAEvC,IAAI,aAAa;EACf,YAAY,MAAM;EAClB,WAAW,OAAO,IAAI;EACtB,IAAI,KAAK,QAAQ,QAAQ,uCAAuC,WAAW,KAAK,EAAE;CACpF;AACF;;;;AAKA,SAAgB,kBAAwB;CACtC,KAAK,MAAM,CAAC,MAAM,gBAAgB,YAAY;EAC5C,YAAY,MAAM;EAClB,WAAW,OAAO,IAAI;CACxB;CAEA,IAAI,KAAK,QAAQ,QAAQ,8BAA8B;AACzD;;;;AAKA,SAAgB,eAAmD;CACjE,OAAO;EACL,MAAM,WAAW;EACjB,QAAQ,MAAM,KAAK,WAAW,KAAK,CAAC;CACtC;AACF"}
1
+ {"version":3,"file":"mailer-pool.mjs","names":[],"sources":["../../../../../../../core/src/mail/mailer-pool.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport type nodemailer from \"nodemailer\";\nimport type { Transporter } from \"nodemailer\";\nimport type { MailConfigurations, SESConfigurations, SMTPConfigurations } from \"./types\";\n\n// ============================================================\n// Eager-loaded Nodemailer Module\n// ============================================================\n\n/**\n * Installation instructions for nodemailer\n */\nconst NODEMAILER_INSTALL_INSTRUCTIONS = `\nEmail functionality requires the nodemailer package.\nInstall it with:\n\n warlock add mail\n\nOr manually:\n\n npm install nodemailer\n pnpm add nodemailer\n yarn add nodemailer\n`.trim();\n\n/**\n * Module availability flag\n */\nlet moduleExists: boolean | null = null;\n\n/**\n * Cached nodemailer module (loaded at import time)\n */\nlet nodemailerModule: typeof nodemailer;\n\nlet nodemailerLoadPromise: Promise<void> | null = null;\n\n/**\n * Eagerly load nodemailer module at import time\n */\nasync function loadNodemailerModule() {\n try {\n const module = await import(\"nodemailer\");\n nodemailerModule = module.default;\n moduleExists = true;\n } catch {\n moduleExists = false;\n }\n}\n\n// Kick off eager loading immediately\nnodemailerLoadPromise = loadNodemailerModule();\n\nconst SES_INSTALL_INSTRUCTIONS = `\nAWS SES functionality requires the @aws-sdk/client-sesv2 package.\nInstall it with:\n\n warlock add ses\n\nOr manually:\n\n npm install @aws-sdk/client-sesv2\n pnpm add @aws-sdk/client-sesv2\n yarn add @aws-sdk/client-sesv2\n`.trim();\n\nlet sesModuleExists: boolean | null = null;\n\nlet sesModule: typeof import(\"@aws-sdk/client-sesv2\");\n\nlet sesLoadPromise: Promise<void> | null = null;\n\nasync function loadSesModule() {\n try {\n const module = await import(\"@aws-sdk/client-sesv2\");\n sesModule = module.default;\n sesModuleExists = true;\n } catch {\n sesModuleExists = false;\n }\n}\n\nsesLoadPromise = loadSesModule();\n\nfunction isSesConfig(config: MailConfigurations): config is SESConfigurations {\n return \"driver\" in config && config.driver === \"ses\";\n}\n\nasync function getSesMailer(config: SESConfigurations): Promise<Transporter> {\n if (sesModuleExists === null && sesLoadPromise) {\n await sesLoadPromise;\n }\n\n if (sesModuleExists === false) {\n throw new Error(`@aws-sdk/client-sesv2 is not installed.\\n\\n${SES_INSTALL_INSTRUCTIONS}`);\n }\n\n const hash = `ses_${config.region}_${config.accessKeyId}`;\n\n const existingTransporter = mailerPool.get(hash);\n if (existingTransporter) {\n return existingTransporter;\n }\n\n log.info(\"mail\", \"pool\", `Creating new SES mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const ses = new sesModule!.SESv2Client({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n\n // PRECONDITION: callers must already have awaited `nodemailerLoadPromise` — `getMailer` does, at\n // its own guard above, before it dispatches here. This function reads `nodemailerModule` WITHOUT\n // resolving it, and is safe only because it is unexported with a single call site. Exporting it,\n // or adding a caller outside `getMailer`, reintroduces defect #20: a synchronous read of a module\n // whose load was started and never awaited. Tracked as #29.\n const transporter = nodemailerModule.createTransport({\n SES: { sesClient: ses, SendEmailCommand: sesModule.SendEmailCommand },\n });\n\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n// ============================================================\n// Mailer Pool\n// ============================================================\n\n/**\n * Mailer pool for connection reuse\n * Maps config hash to transporter instance\n */\nconst mailerPool = new Map<string, Transporter>();\n\n/**\n * Create a hash from mail configuration for pooling\n */\nfunction createConfigHash(config: SMTPConfigurations): string {\n const key = JSON.stringify({\n // SMTP specific fields\n host: config.host,\n port: config.port,\n secure: config.secure,\n auth: config.auth,\n username: config.username,\n password: config.password,\n });\n\n // Simple hash function\n let hash = 0;\n for (let i = 0; i < key.length; i++) {\n const char = key.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n return `mailer_${hash}`;\n}\n\n/**\n * Get hash for any mailer config\n */\nfunction getMailerHash(config: MailConfigurations): string {\n if (isSesConfig(config)) {\n return `ses_${config.region}_${config.accessKeyId}`;\n }\n return createConfigHash(config);\n}\n\n/**\n * Get or create a mailer transporter from the pool\n * Nodemailer is eagerly loaded at import time\n */\nexport async function getMailer(config: MailConfigurations): Promise<Transporter> {\n if (moduleExists === null && nodemailerLoadPromise) {\n await nodemailerLoadPromise;\n }\n\n if (moduleExists === false) {\n throw new Error(`nodemailer is not installed.\\n\\n${NODEMAILER_INSTALL_INSTRUCTIONS}`);\n }\n\n if (isSesConfig(config)) {\n return getSesMailer(config);\n }\n\n const hash = getMailerHash(config);\n\n // Return existing transporter if available\n const existingTransporter = mailerPool.get(hash);\n\n if (existingTransporter) {\n return existingTransporter;\n }\n\n // Create new transporter\n log.info(\"mail\", \"pool\", `Creating new mailer transport (pool size: ${mailerPool.size + 1})`);\n\n const { auth, username, password, requireTLS, tls, ...transportConfig } = config;\n\n const transporter = nodemailerModule.createTransport({\n requireTLS: requireTLS ?? tls,\n auth: auth ?? {\n user: username,\n pass: password,\n },\n ...transportConfig,\n });\n\n // Store in pool\n mailerPool.set(hash, transporter);\n\n return transporter;\n}\n\n/**\n * Verify a mailer connection\n */\nexport async function verifyMailer(config: MailConfigurations): Promise<boolean> {\n const transporter = await getMailer(config);\n\n try {\n await transporter.verify();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Close a specific mailer connection\n */\nexport function closeMailer(config: MailConfigurations): void {\n const hash = getMailerHash(config);\n const transporter = mailerPool.get(hash);\n\n if (transporter) {\n transporter.close();\n mailerPool.delete(hash);\n log.info(\"mail\", \"pool\", `Closed mailer transport (pool size: ${mailerPool.size})`);\n }\n}\n\n/**\n * Close all mailer connections\n */\nexport function closeAllMailers(): void {\n for (const [hash, transporter] of mailerPool) {\n transporter.close();\n mailerPool.delete(hash);\n }\n\n log.info(\"mail\", \"pool\", \"Closed all mailer transports\");\n}\n\n/**\n * Get pool statistics\n */\nexport function getPoolStats(): { size: number; hashes: string[] } {\n return {\n size: mailerPool.size,\n hashes: Array.from(mailerPool.keys()),\n };\n}\n"],"mappings":";;;;;;AAYA,MAAM,kCAAkC;;;;;;;;;;;EAWtC,KAAK;;;;AAKP,IAAI,eAA+B;;;;AAKnC,IAAI;AAEJ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OAAO,IAAI;EACtB,IAAI,KAAK,QAAQ,QAAQ,uCAAuC,WAAW,KAAK,EAAE;CACpF;AACF;;;;AAKA,SAAgB,kBAAwB;CACtC,KAAK,MAAM,CAAC,MAAM,gBAAgB,YAAY;EAC5C,YAAY,MAAM;EAClB,WAAW,OAAO,IAAI;CACxB;CAEA,IAAI,KAAK,QAAQ,QAAQ,8BAA8B;AACzD;;;;AAKA,SAAgB,eAAmD;CACjE,OAAO;EACL,MAAM,WAAW;EACjB,QAAQ,MAAM,KAAK,WAAW,KAAK,CAAC;CACtC;AACF"}
@@ -7,6 +7,10 @@ import { ComponentType, ReactElement, ReactNode } from "react";
7
7
  * **Important:** This function requires React packages to be installed.
8
8
  * Install them with: `warlock add react` or `yarn add react react-dom`
9
9
  *
10
+ * React is resolved synchronously on the first call that needs it, so this
11
+ * function stays synchronous and missing packages throw here rather than
12
+ * surfacing later as a read off an undefined module.
13
+ *
10
14
  * @example
11
15
  * ```typescript
12
16
  * const html = renderReact(<WelcomeEmail name="John" />);
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"mappings":";;;;;AAgEA;;;;;;;;;iBAAgB,WAAA,CAAY,YAAA,EAAc,YAAA,GAAe,aAAA,GAAgB,SAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"mappings":";;;;;AAqKA;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,YAAA,EAAc,YAAA,GAAe,aAAA,GAAgB,SAAA"}
@@ -1,3 +1,5 @@
1
+ import { createRequire } from "node:module";
2
+
1
3
  //#region ../core/src/react/index.ts
2
4
  /**
3
5
  * Installation instructions for React
@@ -15,40 +17,112 @@ Or manually:
15
17
  yarn add react react-dom
16
18
  `.trim();
17
19
  /**
18
- * Module availability flag
20
+ * Cached React modules, populated by the first `resolveReactModules()` call
19
21
  */
20
- let moduleExists = null;
22
+ let react = null;
23
+ let reactDomServer = null;
21
24
  /**
22
- * Cached React modules (loaded at import time)
25
+ * Whether the resolution attempt already ran (success or failure)
23
26
  */
24
- let react;
25
- let reactDomServer;
27
+ let reactResolved = false;
26
28
  /**
27
- * Eagerly load React modules at import time
29
+ * Why the resolution failed, when it failed.
30
+ *
31
+ * Cached and re-thrown on every later call: the resolution attempt runs exactly
32
+ * once, so without this the second `renderReact()` would skip the attempt and
33
+ * fall through to the "not installed" branch, reporting a different, wrong
34
+ * cause one call after the accurate one.
35
+ */
36
+ let reactLoadError = null;
37
+ const ErrorWithCause = Error;
38
+ /**
39
+ * Whether `error` says `specifier` itself is absent, as opposed to present but
40
+ * broken.
41
+ *
42
+ * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a
43
+ * dependency missing *inside* react raises the very same code (`Cannot find
44
+ * module 'scheduler'`), and treating that as absence would tell the operator to
45
+ * install a package they already have. So the message has to name the specifier
46
+ * exactly — quoted, which is also what stops `'react-dom'` from matching a
47
+ * check for `'react'`.
48
+ */
49
+ function isModuleMissing(error, specifier) {
50
+ if (!(error instanceof Error)) return false;
51
+ return error.code === "MODULE_NOT_FOUND" && error.message.includes(`Cannot find module '${specifier}'`);
52
+ }
53
+ /**
54
+ * Require one module, translating its failure into a message that names the
55
+ * specifier that actually failed.
56
+ *
57
+ * The two specifiers are resolved separately and reported separately: a broken
58
+ * `react-dom/server` must never be announced as "react is not installed", since
59
+ * that sends the operator to fix a package that is already fine.
28
60
  */
29
- async function loadReactModules() {
61
+ function requireModule(require, specifier) {
30
62
  try {
31
- react = await import("react");
32
- reactDomServer = await import("react-dom/server");
33
- moduleExists = true;
34
- } catch {
35
- moduleExists = false;
63
+ const module = require(specifier);
64
+ return module.default ?? module;
65
+ } catch (error) {
66
+ if (isModuleMissing(error, specifier)) throw new Error(`${specifier} is not installed.\n\n${REACT_INSTALL_INSTRUCTIONS}`);
67
+ throw new ErrorWithCause(`Failed to load "${specifier}": ${error.message}`, { cause: error });
36
68
  }
37
69
  }
38
- loadReactModules();
70
+ /**
71
+ * Resolve the React modules synchronously, on first use.
72
+ *
73
+ * Resolution is deliberately *lazy* and *synchronous*:
74
+ *
75
+ * - Lazy, because a top-level require would drag react and react-dom into every
76
+ * `import "@warlock.js/core"`, including apps that never render a component.
77
+ * - Synchronous, because `renderReact()` is synchronous. An async import kicked
78
+ * off at module load leaves a window in which the modules are neither loaded
79
+ * nor known to be missing, and a render running inside that window has no
80
+ * correct answer to give — it used to read `createElement` off `undefined`.
81
+ *
82
+ * `createRequire` gives an ESM-safe `require`, and the outcome — modules,
83
+ * absence or load failure — is cached, so resolution runs exactly once per
84
+ * process. The failure *reason* is cached too, not just the fact of it: every
85
+ * call after a failed load has to report the same cause as the first one.
86
+ *
87
+ * @throws when react or react-dom is not installed, or cannot be loaded
88
+ */
89
+ function resolveReactModules() {
90
+ if (!reactResolved) {
91
+ reactResolved = true;
92
+ try {
93
+ const require = createRequire(import.meta.url);
94
+ react = requireModule(require, "react");
95
+ reactDomServer = requireModule(require, "react-dom/server");
96
+ } catch (error) {
97
+ react = null;
98
+ reactDomServer = null;
99
+ reactLoadError = error;
100
+ }
101
+ }
102
+ if (reactLoadError) throw reactLoadError;
103
+ if (!react || !reactDomServer) throw new Error(`react is not installed.\n\n${REACT_INSTALL_INSTRUCTIONS}`);
104
+ return {
105
+ react,
106
+ reactDomServer
107
+ };
108
+ }
39
109
  /**
40
110
  * Render a React element/component to HTML string
41
111
  *
42
112
  * **Important:** This function requires React packages to be installed.
43
113
  * Install them with: `warlock add react` or `yarn add react react-dom`
44
114
  *
115
+ * React is resolved synchronously on the first call that needs it, so this
116
+ * function stays synchronous and missing packages throw here rather than
117
+ * surfacing later as a read off an undefined module.
118
+ *
45
119
  * @example
46
120
  * ```typescript
47
121
  * const html = renderReact(<WelcomeEmail name="John" />);
48
122
  * ```
49
123
  */
50
124
  function renderReact(reactElement) {
51
- if (moduleExists === false) throw new Error(`react is not installed.\n\n${REACT_INSTALL_INSTRUCTIONS}`);
125
+ const { react, reactDomServer } = resolveReactModules();
52
126
  if (typeof reactElement === "function") reactElement = react.createElement(reactElement);
53
127
  return reactDomServer.renderToString(reactElement);
54
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"sourcesContent":["import type { ComponentType, ReactElement, ReactNode } from \"react\";\n\n// ============================================================\n// Eager-loaded React Modules\n// ============================================================\n\n/**\n * Installation instructions for React\n */\nconst REACT_INSTALL_INSTRUCTIONS = `\nReact SSR functionality requires React packages.\nInstall them with:\n\n warlock add react\n\nOr manually:\n\n npm install react react-dom\n pnpm add react react-dom\n yarn add react react-dom\n`.trim();\n\n/**\n * Module availability flag\n */\nlet moduleExists: boolean | null = null;\n\n/**\n * Cached React modules (loaded at import time)\n */\nlet react: typeof import(\"react\");\nlet reactDomServer: typeof import(\"react-dom/server\");\n\n/**\n * Eagerly load React modules at import time\n */\nasync function loadReactModules() {\n try {\n react = await import(\"react\");\n reactDomServer = await import(\"react-dom/server\");\n moduleExists = true;\n } catch {\n moduleExists = false;\n }\n}\n\n// Kick off eager loading immediately\nloadReactModules();\n\n// ============================================================\n// Render Function\n// ============================================================\n\n/**\n * Render a React element/component to HTML string\n *\n * **Important:** This function requires React packages to be installed.\n * Install them with: `warlock add react` or `yarn add react react-dom`\n *\n * @example\n * ```typescript\n * const html = renderReact(<WelcomeEmail name=\"John\" />);\n * ```\n */\nexport function renderReact(reactElement: ReactElement | ComponentType | ReactNode): string {\n if (moduleExists === false) {\n throw new Error(`react is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n if (typeof reactElement === \"function\") {\n reactElement = react.createElement(reactElement);\n }\n\n return reactDomServer.renderToString(reactElement);\n}\n"],"mappings":";;;;AASA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,eAA+B;;;;AAKnC,IAAI;AACJ,IAAI;;;;AAKJ,eAAe,mBAAmB;CAChC,IAAI;EACF,QAAQ,MAAM,OAAO;EACrB,iBAAiB,MAAM,OAAO;EAC9B,eAAe;CACjB,QAAQ;EACN,eAAe;CACjB;AACF;AAGA,iBAAiB;;;;;;;;;;;;AAiBjB,SAAgB,YAAY,cAAgE;CAC1F,IAAI,iBAAiB,OACnB,MAAM,IAAI,MAAM,8BAA8B,4BAA4B;CAG5E,IAAI,OAAO,iBAAiB,YAC1B,eAAe,MAAM,cAAc,YAAY;CAGjD,OAAO,eAAe,eAAe,YAAY;AACnD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport type { ComponentType, ReactElement, ReactNode } from \"react\";\n\n// ============================================================\n// Lazily Resolved React Modules\n// ============================================================\n\n/**\n * Installation instructions for React\n */\nconst REACT_INSTALL_INSTRUCTIONS = `\nReact SSR functionality requires React packages.\nInstall them with:\n\n warlock add react\n\nOr manually:\n\n npm install react react-dom\n pnpm add react react-dom\n yarn add react react-dom\n`.trim();\n\n/**\n * Cached React modules, populated by the first `resolveReactModules()` call\n */\nlet react: typeof import(\"react\") | null = null;\nlet reactDomServer: typeof import(\"react-dom/server\") | null = null;\n\n/**\n * Whether the resolution attempt already ran (success or failure)\n */\nlet reactResolved = false;\n\n/**\n * Why the resolution failed, when it failed.\n *\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\n * once, so without this the second `renderReact()` would skip the attempt and\n * fall through to the \"not installed\" branch, reporting a different, wrong\n * cause one call after the accurate one.\n */\nlet reactLoadError: Error | null = null;\n\n/**\n * `new Error(message, { cause })` is ES2022, and this package still compiles\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\n * only. Node has supported the option since v16, so this is the type layer\n * catching up with the runtime, not a change in what the code does.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * Whether `error` says `specifier` itself is absent, as opposed to present but\n * broken.\n *\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\n * dependency missing *inside* react raises the very same code (`Cannot find\n * module 'scheduler'`), and treating that as absence would tell the operator to\n * install a package they already have. So the message has to name the specifier\n * exactly — quoted, which is also what stops `'react-dom'` from matching a\n * check for `'react'`.\n */\nfunction isModuleMissing(error: unknown, specifier: string): boolean {\n if (!(error instanceof Error)) return false;\n\n return (\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\n error.message.includes(`Cannot find module '${specifier}'`)\n );\n}\n\n/**\n * Require one module, translating its failure into a message that names the\n * specifier that actually failed.\n *\n * The two specifiers are resolved separately and reported separately: a broken\n * `react-dom/server` must never be announced as \"react is not installed\", since\n * that sends the operator to fix a package that is already fine.\n */\nfunction requireModule<T>(require: NodeRequire, specifier: string): T {\n try {\n const module = require(specifier);\n\n return (module.default ?? module) as T;\n } catch (error) {\n if (isModuleMissing(error, specifier)) {\n throw new Error(`${specifier} is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n // The package is there, it just would not load. Its own error names the\n // real cause, so it is inlined *and* chained: a terminal that never prints\n // `cause` must still show the text that actually helps.\n throw new ErrorWithCause(`Failed to load \"${specifier}\": ${(error as Error).message}`, {\n cause: error,\n });\n }\n}\n\n/**\n * Resolve the React modules synchronously, on first use.\n *\n * Resolution is deliberately *lazy* and *synchronous*:\n *\n * - Lazy, because a top-level require would drag react and react-dom into every\n * `import \"@warlock.js/core\"`, including apps that never render a component.\n * - Synchronous, because `renderReact()` is synchronous. An async import kicked\n * off at module load leaves a window in which the modules are neither loaded\n * nor known to be missing, and a render running inside that window has no\n * correct answer to give — it used to read `createElement` off `undefined`.\n *\n * `createRequire` gives an ESM-safe `require`, and the outcome — modules,\n * absence or load failure — is cached, so resolution runs exactly once per\n * process. The failure *reason* is cached too, not just the fact of it: every\n * call after a failed load has to report the same cause as the first one.\n *\n * @throws when react or react-dom is not installed, or cannot be loaded\n */\nfunction resolveReactModules() {\n if (!reactResolved) {\n reactResolved = true;\n\n try {\n const require = createRequire(import.meta.url);\n react = requireModule<typeof import(\"react\")>(require, \"react\");\n reactDomServer = requireModule<typeof import(\"react-dom/server\")>(require, \"react-dom/server\");\n } catch (error) {\n react = null;\n reactDomServer = null;\n reactLoadError = error as Error;\n }\n }\n\n if (reactLoadError) {\n throw reactLoadError;\n }\n\n if (!react || !reactDomServer) {\n throw new Error(`react is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n return { react, reactDomServer };\n}\n\n// ============================================================\n// Render Function\n// ============================================================\n\n/**\n * Render a React element/component to HTML string\n *\n * **Important:** This function requires React packages to be installed.\n * Install them with: `warlock add react` or `yarn add react react-dom`\n *\n * React is resolved synchronously on the first call that needs it, so this\n * function stays synchronous and missing packages throw here rather than\n * surfacing later as a read off an undefined module.\n *\n * @example\n * ```typescript\n * const html = renderReact(<WelcomeEmail name=\"John\" />);\n * ```\n */\nexport function renderReact(reactElement: ReactElement | ComponentType | ReactNode): string {\n const { react, reactDomServer } = resolveReactModules();\n\n if (typeof reactElement === \"function\") {\n reactElement = react.createElement(reactElement);\n }\n\n return reactDomServer.renderToString(reactElement);\n}\n"],"mappings":";;;;;;AAUA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,QAAuC;AAC3C,IAAI,iBAA2D;;;;AAK/D,IAAI,gBAAgB;;;;;;;;;AAUpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;;AAavB,SAAS,gBAAgB,OAAgB,WAA4B;CACnE,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,OACG,MAAgC,SAAS,sBAC1C,MAAM,QAAQ,SAAS,uBAAuB,UAAU,EAAE;AAE9D;;;;;;;;;AAUA,SAAS,cAAiB,SAAsB,WAAsB;CACpE,IAAI;EACF,MAAM,SAAS,QAAQ,SAAS;EAEhC,OAAQ,OAAO,WAAW;CAC5B,SAAS,OAAO;EACd,IAAI,gBAAgB,OAAO,SAAS,GAClC,MAAM,IAAI,MAAM,GAAG,UAAU,wBAAwB,4BAA4B;EAMnF,MAAM,IAAI,eAAe,mBAAmB,UAAU,KAAM,MAAgB,WAAW,EACrF,OAAO,MACT,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,sBAAsB;CAC7B,IAAI,CAAC,eAAe;EAClB,gBAAgB;EAEhB,IAAI;GACF,MAAM,UAAU,cAAc,OAAO,KAAK,GAAG;GAC7C,QAAQ,cAAsC,SAAS,OAAO;GAC9D,iBAAiB,cAAiD,SAAS,kBAAkB;EAC/F,SAAS,OAAO;GACd,QAAQ;GACR,iBAAiB;GACjB,iBAAiB;EACnB;CACF;CAEA,IAAI,gBACF,MAAM;CAGR,IAAI,CAAC,SAAS,CAAC,gBACb,MAAM,IAAI,MAAM,8BAA8B,4BAA4B;CAG5E,OAAO;EAAE;EAAO;CAAe;AACjC;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,cAAgE;CAC1F,MAAM,EAAE,OAAO,mBAAmB,oBAAoB;CAEtD,IAAI,OAAO,iBAAiB,YAC1B,eAAe,MAAM,cAAc,YAAY;CAGjD,OAAO,eAAe,eAAe,YAAY;AACnD"}
package/package.json CHANGED
@@ -36,13 +36,13 @@
36
36
  "@mongez/slug": "^1.0.7",
37
37
  "@mongez/supportive-is": "^2.1.3",
38
38
  "@mongez/time-wizard": "^1.0.6",
39
- "@warlock.js/auth": "4.11.0",
40
- "@warlock.js/cache": "4.11.0",
41
- "@warlock.js/cascade": "4.11.0",
42
- "@warlock.js/context": "4.11.0",
43
- "@warlock.js/logger": "4.11.0",
44
- "@warlock.js/seal": "4.11.0",
45
- "@warlock.js/fs": "4.11.0",
39
+ "@warlock.js/auth": "4.12.0",
40
+ "@warlock.js/cache": "4.12.0",
41
+ "@warlock.js/cascade": "4.12.0",
42
+ "@warlock.js/context": "4.12.0",
43
+ "@warlock.js/logger": "4.12.0",
44
+ "@warlock.js/seal": "4.12.0",
45
+ "@warlock.js/fs": "4.12.0",
46
46
  "chokidar": "^5.0.0",
47
47
  "dayjs": "^1.11.19",
48
48
  "es-module-lexer": "^2.0.0",
@@ -68,15 +68,15 @@
68
68
  "react": "^19.2.3",
69
69
  "react-dom": "^19.2.3",
70
70
  "@react-email/render": "^2.0.5",
71
- "@warlock.js/herald": "4.11.0",
72
- "@warlock.js/ai": "4.11.0",
73
- "@warlock.js/access": "4.11.0",
74
- "@warlock.js/notifications": "4.11.0"
71
+ "@warlock.js/herald": "4.12.0",
72
+ "@warlock.js/ai": "4.12.0",
73
+ "@warlock.js/access": "4.12.0",
74
+ "@warlock.js/notifications": "4.12.0"
75
75
  },
76
76
  "bin": {
77
77
  "warlock": "bin/warlock.js"
78
78
  },
79
- "version": "4.11.0",
79
+ "version": "4.12.0",
80
80
  "type": "module",
81
81
  "main": "./esm/index.mjs",
82
82
  "module": "./esm/index.mjs",
@@ -22,7 +22,9 @@ await new Image("./photo.jpg")
22
22
  .save("./output.webp");
23
23
  ```
24
24
 
25
- That's the full contract. The chain doesn't touch sharp until the output method fires.
25
+ That's the full contract. The chain doesn't run sharp until the output method fires; the
26
+ constructor resolves the sharp module itself, so a missing sharp throws there rather than at the
27
+ final await.
26
28
 
27
29
  ## Installation
28
30
 
@@ -156,12 +156,30 @@ The framework ships a fixed set of commands you call but don't author. Knowing t
156
156
 
157
157
  | Command | Flags / args | Preloads |
158
158
  | -------- | ----------------------------------------------- | ------------------------------ |
159
- | `warlock migrate` | `--list` (just list pending), `--fresh` / `-f` (drop tables first) | database, logger |
159
+ | `warlock migrate` | `--list` / `-l` (executed **and** pending), `--pending` (pending only, sets an exit code), `--fresh` / `-f` (drop tables first) | database, logger |
160
160
  | `warlock seed` | `--name <pattern>` (run seeds matching the pattern) | full bootstrap (env, configs, app modules) |
161
161
  | `warlock create-database <name>` | bare positional `<name>` | database |
162
162
  | `warlock drop.tables` | `--force, -f` (skip confirmation prompt) | database, logger |
163
163
  | `warlock db.indexes` | builds DB indexes for every registered model | database |
164
164
 
165
+ **Asking what will run next.** `warlock migrate --list` prints executed migrations and then the pending ones **in execution order**. Do not derive the pending set by differencing `--all` against `--list`: `--all` globs `src/app` only, while `--list` reads the migrations table, which also holds migrations that packages register through `database.migrations` (`@warlock.js/auth` contributes two). The difference under-counts pending, in the direction that says "safe to proceed".
166
+
167
+ `--list` is a report and always exits `0`. `--pending` is a gate, and its exit code is its whole API:
168
+
169
+ | Exit | Meaning |
170
+ | ---- | ------- |
171
+ | `0` | computed, nothing pending |
172
+ | `1` | computed, N pending |
173
+ | `2` | **could not be computed** |
174
+
175
+ ```bash
176
+ warlock migrate --pending && ./deploy.sh
177
+ ```
178
+
179
+ `2` is separate from `1` on purpose — a script must be able to tell a backlog from an unknown, because one means *run them* and the other means *stop*. When the migration files cannot be loaded, both commands print `Pending: unavailable — <reason>` beneath a complete executed listing rather than reporting `0`.
180
+
181
+ **If you are writing a command that reports on pending migrations:** register migrations first. `listPendingMigrations()` filters the runner's registry, so a caller that has not loaded anything gets `[]` — which reads as "nothing pending" and is not the same claim.
182
+
165
183
  ### Scaffolding
166
184
 
167
185
  The `generate.*` family covers every module piece: