import type { InputOptions, NormalizedOutputOptions, OutputBundle, OutputChunk, Plugin, PluginContext, } from "rollup"; import type { IsomorphicRollupFs } from "../../src/fs-iface"; import htmlScriptEntrypoints from "../../src/ui-page"; // Mock glob to return the input path directly for testing jest.mock("glob", () => ({ glob: jest.fn((pattern: string) => Promise.resolve([pattern])), })); describe("HTML Script Entrypoints plugin", () => { const createMockFs = (files: Record): IsomorphicRollupFs => ({ access: async (path: string) => files[path] !== undefined, readFile: async (path: string) => { const content = files[path]; if (content === undefined) { throw new Error(`ENOENT: no such file or directory, open '${path}'`); } return content; }, stat: async (path: string) => { if (files[path] === undefined) { throw new Error(`ENOENT: no such file or directory, stat '${path}'`); } return { isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false, type: "file" as const, mode: 0o644, size: files[path]?.length || 0, ino: 1, mtimeMs: Date.now(), ctimeMs: Date.now(), uid: 1, gid: 1, dev: 1, }; }, lstatSync: (path: string) => { if (files[path] === undefined) { throw new Error(`ENOENT: no such file or directory, lstat '${path}'`); } return { isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false, } as ReturnType>; }, readdir: async (path: string, options?: { withFileTypes?: boolean }) => { // For glob to work, return matching files as dirents const matchingFiles = Object.keys(files) .filter((f) => f.startsWith(path + "/") || f === path) .map((f) => ({ name: f.split("/").pop() || f, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false, })); return options?.withFileTypes ? matchingFiles : matchingFiles.map((f) => f.name); }, realpath: async (path: string) => path, realpathSync: (path: string) => path, mkdir: async () => {}, writeFile: async () => {}, }); const createMockContext = (): PluginContext => ({ error: (msg: string) => { throw new Error(msg); }, emitFile: jest.fn(), warn: jest.fn(), }) as unknown as PluginContext; const createMockChunk = (name: string, fileName: string): OutputChunk => ({ type: "chunk", name, fileName, code: "console.log('bundled');", isEntry: true, facadeModuleId: `/project/${name}.js`, isDynamicEntry: false, moduleIds: [`/project/${name}.js`], exports: [], imports: [], dynamicImports: [], implicitlyLoadedBefore: [], modules: {}, map: null, sourcemapFileName: null, preliminaryFileName: fileName, importedBindings: {}, referencedFiles: [], }) as unknown as OutputChunk; const callOptionsHook = async ( plugin: Plugin, context: PluginContext, options: InputOptions, ) => { const hook = plugin.options; if (typeof hook === "function") { return await hook.call(context, options); } else if (hook && typeof hook === "object" && "handler" in hook) { const optionsHook = hook as { handler: (options: InputOptions) => Promise; }; return await optionsHook.handler.call(context, options); } return undefined; }; const callGenerateBundleHook = ( plugin: Plugin, context: PluginContext, outputOptions: NormalizedOutputOptions, bundle: OutputBundle, ) => { const hook = plugin.generateBundle; if (typeof hook === "function") { return hook.call(context, outputOptions, bundle, false); } else if (hook && typeof hook === "object" && "handler" in hook) { const bundleHook = hook as { handler: ( options: NormalizedOutputOptions, bundle: OutputBundle, isWrite: boolean, ) => void | Promise; }; return bundleHook.handler.call(context, outputOptions, bundle, false); } }; describe("buildStart hook", () => { test("should add HTML files to watch list", async () => { const fs = createMockFs({ "/project/index.html": ``, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); // First call options to populate the registry await callOptionsHook(plugin, context, { input: "/project/index.html", }); // Now call buildStart const watchedFiles: string[] = []; const buildStartContext = { ...context, addWatchFile: (file: string) => { watchedFiles.push(file); }, } as unknown as PluginContext; const buildStartHook = plugin.buildStart; if (typeof buildStartHook === "function") { buildStartHook.call(buildStartContext, { input: { app: "/project/app.js" }, } as any); } expect(watchedFiles).toContain("/project/index.html"); }); test("should add multiple HTML files to watch list", async () => { const glob = require("glob").glob; const originalMock = glob.getMockImplementation(); try { // Set up glob mock to return multiple files glob.mockImplementation(() => Promise.resolve(["/project/page1.html", "/project/page2.html"]), ); const fs = createMockFs({ "/project/page1.html": ``, "/project/page2.html": ``, "/project/app.js": "console.log('app');", "/project/vendor.js": "console.log('vendor');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); await callOptionsHook(plugin, context, { input: "/project/*.html", }); const watchedFiles: string[] = []; const buildStartContext = { ...context, addWatchFile: (file: string) => { watchedFiles.push(file); }, } as unknown as PluginContext; const buildStartHook = plugin.buildStart; if (typeof buildStartHook === "function") { buildStartHook.call(buildStartContext, { input: { app: "/project/app.js", vendor: "/project/vendor.js" }, } as any); } expect(watchedFiles).toContain("/project/page1.html"); expect(watchedFiles).toContain("/project/page2.html"); expect(watchedFiles).toHaveLength(2); } finally { glob.mockImplementation(originalMock); } }); }); describe("options hook", () => { test("should extract script entrypoints from HTML", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); expect(result).toMatchObject({ input: { app: "/project/app.js", }, }); }); test("should extract multiple script entrypoints", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.js": "console.log('app');", "/project/vendor.js": "console.log('vendor');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); expect(result).toMatchObject({ input: { app: "/project/app.js", vendor: "/project/vendor.js", }, }); }); test("should handle g:import elements", async () => { const fs = createMockFs({ "/project/index.xml": ` `, "/project/component.js": "export default {};", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.xml", }); expect(result).toMatchObject({ input: { component: "/project/component.js", }, }); }); test("should use custom entryPath function", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.tsx": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", entryPath: (entry, { fullPath }) => ({ [`custom-${entry.replace(/\.\w+$/, "")}`]: fullPath, }), }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); expect(result).toMatchObject({ input: { "custom-app": "/project/app.tsx", }, }); }); test("should skip non-existent script files", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); expect(result).toMatchObject({ input: { app: "/project/app.js", }, }); }); test("should handle query parameters in src", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); expect(result).toMatchObject({ input: { app: "/project/app.js?raw", }, }); }); test("should throw error for non-string input", async () => { const plugin: Plugin = htmlScriptEntrypoints({ rootDir: "/project", }); const context = createMockContext(); await expect( callOptionsHook(plugin, context, { input: ["multiple.html", "inputs.html"], }), ).rejects.toThrow( "htmlScriptEntrypoints plugin only supports a single HTML file as input", ); }); test("should ignore inline scripts without src attribute", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); // Should only extract the script with src, ignoring inline scripts expect(result).toMatchObject({ input: { app: "/project/app.js", }, }); }); test("should throw error when no script entrypoints found", async () => { const fs = createMockFs({ "/project/index.html": ` No scripts here `, }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); await expect( callOptionsHook(plugin, context, { input: "/project/index.html", }), ).rejects.toThrow( "No script entry points were found in /project/index.html", ); }); test("should throw error when only inline scripts exist", async () => { const fs = createMockFs({ "/project/index.html": ` `, }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); await expect( callOptionsHook(plugin, context, { input: "/project/index.html", }), ).rejects.toThrow( "No script entry points were found in /project/index.html", ); }); test("should skip processing for non-HTML/XML input", async () => { const plugin: Plugin = htmlScriptEntrypoints({ rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/app.js", }); expect(result).toBeUndefined(); }); test("should skip entryPath that returns multiple keys", async () => { const fs = createMockFs({ "/project/index.html": ` `, "/project/app.js": "console.log('app');", "/project/other.js": "console.log('other');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", entryPath: (entry, { fullPath }) => { if (entry.includes("app")) { return { multiple: fullPath, keys: fullPath }; } return { [entry.replace(/\.js$/, "")]: fullPath }; }, }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/index.html", }); expect(result).toMatchObject({ input: { other: "/project/other.js", }, }); }); test("should sort multiple glob results alphabetically", async () => { const glob = require("glob").glob; const originalMock = glob.getMockImplementation(); // Mock glob to return multiple files in unsorted order glob.mockImplementation((pattern: string) => Promise.resolve([ "/project/z-page.html", "/project/a-page.html", "/project/m-page.html", ]), ); const fs = createMockFs({ "/project/z-page.html": ``, "/project/a-page.html": ``, "/project/m-page.html": ``, "/project/z.js": "console.log('z');", "/project/a.js": "console.log('a');", "/project/m.js": "console.log('m');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); const result = await callOptionsHook(plugin, context, { input: "/project/*.html", }); // Restore original mock glob.mockImplementation(originalMock); // Should process files in alphabetical order expect(result).toMatchObject({ input: { a: "/project/a.js", m: "/project/m.js", z: "/project/z.js", }, }); }); test("should throw error when no filesystem is available", async () => { // Save originals const originalRollupFs = (globalThis as any).__rollupFs; const originalNodeFsAdapter = jest.requireActual( "../../src/node-fs-adapter", ).default; // Clear __rollupFs delete (globalThis as any).__rollupFs; // Mock node-fs-adapter to return null jest.doMock("../../src/node-fs-adapter", () => ({ __esModule: true, default: null, })); // Clear the module cache and reimport jest.resetModules(); const htmlScriptEntrypoints = require("../../src/ui-page").default; const plugin: Plugin = htmlScriptEntrypoints({ rootDir: "/project", // No fs provided }); const context = createMockContext(); await expect( callOptionsHook(plugin, context, { input: "/project/index.html", }), ).rejects.toThrow("No filesystem was passed to plugin. Cannot continue"); // Restore if (originalRollupFs !== undefined) { (globalThis as any).__rollupFs = originalRollupFs; } jest.resetModules(); jest.unmock("../../src/node-fs-adapter"); }); }); describe("generateBundle hook", () => { test("should update script src with bundle file names", async () => { const fs = createMockFs({ "/project/index.html": ``, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); // First call options to set up the registry await callOptionsHook(plugin, context, { input: "/project/index.html", }); const bundle: OutputBundle = { "app-abc123.js": createMockChunk("app", "app-abc123.js"), }; callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, bundle, ); expect(context.emitFile).toHaveBeenCalledWith({ type: "asset", fileName: "index.html", // note self-closing tags by default source: ``, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", updateSrcPath: (original, emitted) => `/static/${emitted}`, }); const context = createMockContext(); await callOptionsHook(plugin, context, { input: "/project/index.html", }); const bundle: OutputBundle = { "app-abc123.js": createMockChunk("app", "app-abc123.js"), }; callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, bundle, ); expect(context.emitFile).toHaveBeenCalledWith({ type: "asset", fileName: "index.html", source: expect.stringContaining('src="/static/app-abc123.js"'), }); }); test("should preserve attributes and structure", async () => { const fs = createMockFs({ "/project/index.html": ``, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); await callOptionsHook(plugin, context, { input: "/project/index.html", }); const bundle: OutputBundle = { "app.js": createMockChunk("app", "app.js"), }; callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, bundle, ); const emittedContent = (context.emitFile as jest.Mock).mock.calls[0][0] .source as string; expect(emittedContent).toContain('type="module"'); expect(emittedContent).toContain('async=""'); }); test("should handle multiple HTML files", async () => { const fs = createMockFs({ "/project/page1.html": ``, "/project/page2.html": ``, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", }); const context = createMockContext(); // Note: This test is limited because the plugin expects glob results // but for this test we'll just verify it doesn't crash with the single file await callOptionsHook(plugin, context, { input: "/project/page1.html", }); const bundle: OutputBundle = { "app.js": createMockChunk("app", "app.js"), }; callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, bundle, ); expect(context.emitFile).toHaveBeenCalledTimes(1); }); test("should use custom serializer options", async () => { const fs = createMockFs({ "/project/index.html": ``, "/project/app.js": "console.log('app');", }); const plugin: Plugin = htmlScriptEntrypoints({ fs, rootDir: "/project", serializerOptions: { selfClosingTags: false, }, }); const context = createMockContext(); await callOptionsHook(plugin, context, { input: "/project/index.html", }); const bundle: OutputBundle = { "app.js": createMockChunk("app", "app.js"), }; callGenerateBundleHook( plugin, context, {} as NormalizedOutputOptions, bundle, ); const emittedContent = (context.emitFile as jest.Mock).mock.calls[0][0] .source as string; // With selfClosingTags: false, should not have self-closing tags expect(emittedContent).toBeDefined(); expect(emittedContent).toBe( ``, ); }); }); });