import type { Plugin, PluginContext, NormalizedOutputOptions, EmittedAsset, LoadResult, ObjectHook, } from "rollup"; import url from "../../src/url"; import crypto from "crypto"; import path from "path"; // Polyfill for crypto.subtle in Node.js test environment if (!globalThis.crypto) { globalThis.crypto = crypto.webcrypto as Crypto; } interface MockFiles { [path: string]: Uint8Array; } interface EmittedFile { type: string; fileName: string; source: Uint8Array; } interface MockContext extends PluginContext { getEmittedFiles: () => EmittedFile[]; getWatchedFiles: () => string[]; } describe("URL plugin", () => { const createMockContext = (files: MockFiles = {}): MockContext => { const emittedFiles: EmittedFile[] = []; const watchedFiles: string[] = []; return { fs: { stat: async (filePath: string) => { const content = files[filePath]; if (content === undefined) { throw new Error( `ENOENT: no such file or directory, stat '${filePath}'`, ); } return Promise.resolve({ size: content.length, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false, }) as ReturnType; }, readFile: async (filePath: string) => { const content = files[filePath]; if (content === undefined) { throw new Error( `ENOENT: no such file or directory, open '${filePath}'`, ); } return content; }, }, addWatchFile: (file: string) => { watchedFiles.push(file); }, emitFile: (file: EmittedAsset) => { emittedFiles.push(file as EmittedFile); return file.fileName!; }, getEmittedFiles: () => emittedFiles, getWatchedFiles: () => watchedFiles, } as unknown as MockContext; }; const callLoadHook = async ( plugin: Plugin, context: MockContext, id: string, ): Promise => { if (typeof plugin.load === "function") { return (await plugin.load.call(context, id)) as string | null; } else if ( plugin.load && typeof plugin.load === "object" && "handler" in plugin.load ) { const loadHook = plugin.load as { handler: (id: string) => LoadResult }; return (await loadHook.handler.call(context, id)) as string | null; } return null; }; const callGenerateBundleHook = async ( plugin: Plugin, context: MockContext, outputOptions: NormalizedOutputOptions, ): Promise => { if (typeof plugin.generateBundle === "function") { return await plugin.generateBundle.call( context, outputOptions, {}, false, ); } else if ( plugin.generateBundle && typeof plugin.generateBundle === "object" && "handler" in plugin.generateBundle ) { const bundleHook = plugin.generateBundle as { handler: ( options: NormalizedOutputOptions, bundle: Record, isWrite: boolean, ) => void | Promise; }; return await bundleHook.handler.call(context, outputOptions, {}, false); } }; describe("basic functionality", () => { test("should inline small images as base64", async () => { const plugin = url() as Plugin; const smallImage = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); // PNG header const files = { "/project/assets/icon.png": smallImage, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/icon.png", ); expect(result).toContain('export default "data:image/png;base64,'); expect(result).toContain("iVBORw0KGgo="); expect(context.getWatchedFiles()).toContain("/project/assets/icon.png"); }); test("should emit large images as assets", async () => { const plugin = url() as Plugin; // Create a large file > 14KB const largeImage = new Uint8Array(15 * 1024); largeImage.fill(1); const files = { "/project/assets/large.png": largeImage, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/large.png", ); expect(result).toContain('export default "'); expect(result).not.toContain("data:"); expect(result).toMatch(/\.png"/); // Should have hash and extension // Verify file is emitted during generateBundle await callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, ); const emittedFiles = context.getEmittedFiles(); expect(emittedFiles).toHaveLength(1); expect(emittedFiles[0]).toMatchObject({ type: "asset", source: largeImage, }); expect(emittedFiles[0].fileName).toMatch(/\.png$/); }); test("should handle SVG files with URI encoding", async () => { const plugin = url() as Plugin; const svgContent = new Uint8Array( Buffer.from(''), ); const files = { "/project/assets/icon.svg": svgContent, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/icon.svg", ); expect(result).toContain('export default "data:image/svg+xml,'); expect(result).not.toContain("base64"); expect(result).toContain("%3Csvg"); // URL encoded { const plugin = url() as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/assets/icon.png": image, }; const context = createMockContext(files); await callLoadHook(plugin, context, "/project/assets/icon.png"); expect(context.getWatchedFiles()).toEqual(["/project/assets/icon.png"]); }); }); describe("file filtering", () => { test("should process default image extensions", async () => { const plugin = url() as Plugin; const image = new Uint8Array([1, 2, 3]); const files: MockFiles = { "/project/icon.svg": image, "/project/photo.png": image, "/project/pic.jpg": image, "/project/pic.jpeg": image, "/project/anim.gif": image, "/project/img.webp": image, }; const context = createMockContext(files); for (const file of Object.keys(files)) { const result = await callLoadHook(plugin, context, file); expect(result).not.toBeNull(); expect(result).toContain("export default"); } }); test("should not process non-image files by default", async () => { const plugin = url() as Plugin; const file = new Uint8Array([1, 2, 3]); const files = { "/project/document.pdf": file, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/document.pdf", ); expect(result).toBeNull(); }); test("should respect custom include option", async () => { const plugin = url({ include: "**/*.txt" }) as Plugin; const file = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" const files = { "/project/data.txt": file, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/data.txt"); expect(result).not.toBeNull(); }); test("should respect exclude option", async () => { const plugin = url({ exclude: "**/vendor/**" }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/vendor/icon.png": image, "/project/assets/icon.png": image, }; const context = createMockContext(files); const resultExcluded = await callLoadHook( plugin, context, "/project/vendor/icon.png", ); const resultIncluded = await callLoadHook( plugin, context, "/project/assets/icon.png", ); expect(resultExcluded).toBeNull(); expect(resultIncluded).not.toBeNull(); }); }); describe("size limit options", () => { test("should respect custom limit option", async () => { const plugin = url({ limit: 100 }) as Plugin; // 100 bytes const smallImage = new Uint8Array(50); const largeImage = new Uint8Array(150); const files = { "/project/small.png": smallImage, "/project/large.png": largeImage, }; const context = createMockContext(files); const resultSmall = await callLoadHook( plugin, context, "/project/small.png", ); const resultLarge = await callLoadHook( plugin, context, "/project/large.png", ); expect(resultSmall).toContain("data:image/png;base64,"); expect(resultLarge).not.toContain("data:"); }); test("should always emit files when limit is 0", async () => { const plugin = url({ limit: 0 }) as Plugin; const tinyImage = new Uint8Array([1, 2, 3]); const files = { "/project/tiny.png": tinyImage, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/tiny.png"); expect(result).not.toContain("data:"); expect(result).toMatch(/export default ".*\.png"/); }); }); describe("fileName patterns", () => { test("should use default [hash][extname] pattern", async () => { const plugin = url({ limit: 0 }) as Plugin; const image = new Uint8Array([1, 2, 3, 4, 5]); const files = { "/project/assets/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/icon.png", ); // Should have 16-char hash + extension expect(result).toMatch(/export default "[a-f0-9]{16}\.png"/); }); test("should support [name] placeholder", async () => { const plugin = url({ limit: 0, fileName: "[name][extname]" }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/assets/my-icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/my-icon.png", ); expect(result).toContain('export default "my-icon.png"'); }); test("should support [dirname] placeholder", async () => { const plugin = url({ limit: 0, fileName: "[dirname][name][extname]", }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/assets/icons/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/icons/icon.png", ); // dirname should be the last folder name expect(result).toMatch(/export default "icons.*icon\.png"/); }); test("should support [hash] placeholder", async () => { const plugin = url({ limit: 0, fileName: "img-[hash][extname]", }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.png"); expect(result).toMatch(/export default "img-[a-f0-9]{16}\.png"/); }); test("should support combination of placeholders", async () => { const plugin = url({ limit: 0, fileName: "assets/[dirname]/[name]-[hash][extname]", }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/images/icons/logo.png": image, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/images/icons/logo.png", ); // dirname includes extra separator on some platforms expect(result).toMatch( /export default "assets\/icons\/?\/logo-[a-f0-9]{16}\.png"/, ); }); test("should handle sourceDir option for dirname", async () => { const plugin = url({ limit: 0, fileName: "[dirname][name][extname]", sourceDir: "/project", }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/assets/images/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/assets/images/icon.png", ); // Should use relative path from sourceDir expect(result).toMatch(/export default "assets.*images.*icon\.png"/); }); test("should handle empty dirname when file is in sourceDir root", async () => { const plugin = url({ limit: 0, fileName: "[dirname][name][extname]", sourceDir: "/project/src", }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/src/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook( plugin, context, "/project/src/icon.png", ); // When file is in sourceDir root, relativeDir is empty, so [dirname] should produce nothing expect(result).toBe('export default "icon.png"'); }); }); describe("publicPath option", () => { test("should prepend publicPath to emitted file URLs", async () => { const plugin = url({ limit: 0, publicPath: "/static/" }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.png"); expect(result).toMatch(/export default "\/static\/[a-f0-9]{16}\.png"/); }); test("should work with custom fileName and publicPath", async () => { const plugin = url({ limit: 0, publicPath: "https://cdn.example.com/", fileName: "images/[name][extname]", }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/logo.png": image, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/logo.png"); expect(result).toContain( 'export default "https://cdn.example.com/images/logo.png"', ); }); }); describe("emitFiles option", () => { test("should emit files by default", async () => { const plugin = url({ limit: 0 }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); await callLoadHook(plugin, context, "/project/icon.png"); await callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, ); expect(context.getEmittedFiles()).toHaveLength(1); }); test("should skip emitting files when emitFiles is false", async () => { const plugin = url({ limit: 0, emitFiles: false }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); await callLoadHook(plugin, context, "/project/icon.png"); await callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, ); expect(context.getEmittedFiles()).toHaveLength(0); }); }); describe("updateExport option", () => { test("should transform export data with updateExport function", async () => { const plugin = url({ updateExport: (data: string) => data.toUpperCase(), }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.png"); expect(result).toContain("DATA:IMAGE/PNG;BASE64,"); expect(result).toMatch(/export default "[A-Z0-9:;,=+\/]+"/); // Include colon, semicolon, comma }); test("should apply updateExport to both inlined and emitted files", async () => { const plugin = url({ limit: 0, fileName: "[name][extname]", updateExport: (data: string) => `custom-prefix-${data}`, }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.png"); expect(result).toContain('export default "custom-prefix-icon.png"'); }); }); describe("SVG special handling", () => { test("should strip newlines and tabs from SVG", async () => { const plugin = url() as Plugin; const svgContent = new Uint8Array( Buffer.from("\n\t\n"), ); const files = { "/project/icon.svg": svgContent, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.svg"); expect(result).not.toContain("\\n"); expect(result).not.toContain("\\t"); }); test("should strip comments from SVG", async () => { const plugin = url() as Plugin; const svgContent = new Uint8Array( Buffer.from(""), ); const files = { "/project/icon.svg": svgContent, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.svg"); expect(result).not.toContain("comment"); }); test("should properly encode SVG special characters", async () => { const plugin = url() as Plugin; const svgContent = new Uint8Array( Buffer.from("Test (parens)"), ); const files = { "/project/icon.svg": svgContent, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.svg"); expect(result).toContain("%28"); // encoded ( expect(result).toContain("%29"); // encoded ) }); }); describe("MIME type handling", () => { test("should use correct MIME type for different image formats", async () => { const plugin = url() as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/photo.jpg": image, "/project/anim.gif": image, "/project/img.webp": image, }; const context = createMockContext(files); const jpgResult = await callLoadHook( plugin, context, "/project/photo.jpg", ); const gifResult = await callLoadHook( plugin, context, "/project/anim.gif", ); const webpResult = await callLoadHook( plugin, context, "/project/img.webp", ); expect(jpgResult).toContain("data:image/jpeg;base64,"); expect(gifResult).toContain("data:image/gif;base64,"); expect(webpResult).toContain("data:image/webp;base64,"); }); }); describe("multiple file handling", () => { test("should handle multiple files without conflicts", async () => { const plugin = url({ limit: 0 }) as Plugin; const image1 = new Uint8Array([1, 2, 3]); const image2 = new Uint8Array([4, 5, 6]); const files = { "/project/icon1.png": image1, "/project/icon2.png": image2, }; const context = createMockContext(files); await callLoadHook(plugin, context, "/project/icon1.png"); await callLoadHook(plugin, context, "/project/icon2.png"); await callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, ); const emittedFiles = context.getEmittedFiles(); expect(emittedFiles).toHaveLength(2); expect(emittedFiles[0].source).toEqual(image1); expect(emittedFiles[1].source).toEqual(image2); // Also verify hashes are different const result1 = await callLoadHook(plugin, context, "/project/icon1.png"); const result2 = await callLoadHook(plugin, context, "/project/icon2.png"); const hash1 = result1!.match(/[a-f0-9]{16}\.png/)![0]; const hash2 = result2!.match(/[a-f0-9]{16}\.png/)![0]; expect(hash1).not.toBe(hash2); }); }); describe("Windows path handling", () => { test("should convert Windows paths to POSIX in exports", async () => { const plugin = url({ limit: 0, fileName: "assets\\[name][extname]", // Windows-style path }) as Plugin; const image = new Uint8Array([1, 2, 3]); const files = { "/project/icon.png": image, }; const context = createMockContext(files); const result = await callLoadHook(plugin, context, "/project/icon.png"); // Should convert backslashes to forward slashes in export on Windows // On non-Windows systems, path.sep is already '/' so this may not apply if (path.sep === "\\") { expect(result).toContain('export default "assets/icon.png"'); } else { // On POSIX systems, just verify the export exists expect(result).toContain('export default "assets'); expect(result).toContain('icon.png"'); } }); }); });