import { vi, describe, expect, it, beforeEach } from "vite-plus/test";
import {
previewOptionsTransform,
applyTransform,
type ReactGrabOptions,
} from "../src/utils/transform.js";
vi.mock("node:fs", () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
accessSync: vi.fn(),
constants: { W_OK: 2 },
}));
import { existsSync, readFileSync, writeFileSync, accessSync } from "node:fs";
const mockExistsSync = vi.mocked(existsSync);
const mockReadFileSync = vi.mocked(readFileSync);
const mockWriteFileSync = vi.mocked(writeFileSync);
const mockAccessSync = vi.mocked(accessSync);
const toPosixPath = (path: unknown): string => String(path).replace(/\\/g, "/");
beforeEach(() => {
vi.clearAllMocks();
});
describe("previewOptionsTransform - Next.js App Router", () => {
const layoutWithReactGrab = `import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{process.env.NODE_ENV === "development" && (
)}
{children}
);
}`;
it("should add activationKey option to existing React Grab script", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("data-options");
expect(result.newContent).toContain("activationKey");
expect(result.newContent).toContain("Meta+K");
});
it("should preserve valid JSX format when adding data-options to self-closing Script", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithReactGrab);
const options: ReactGrabOptions = {
activationMode: "toggle",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).not.toMatch(/\/\s*\n\s*data-options/);
expect(result.newContent).toMatch(/data-options.*\n\s*\/>/s);
});
it("should not split self-closing tag when adding data-options", () => {
const layoutWithSelfClosingScript = `import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithSelfClosingScript);
const options: ReactGrabOptions = {
activationMode: "toggle",
allowActivationInsideInput: false,
maxContextLines: 3,
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("data-options={JSON.stringify(");
expect(result.newContent).toContain('activationMode: "toggle"');
expect(result.newContent).toContain("allowActivationInsideInput: false");
expect(result.newContent).toContain("maxContextLines: 3");
expect(result.newContent).toContain("/>");
expect(result.newContent).not.toMatch(/\}\)\s*\n\s*\n\s*\/>/);
expect(result.newContent).not.toMatch(/strategy="beforeInteractive"\s*\/\s*\n/);
});
it("should not add extra blank line before closing tag", () => {
const layoutWithScript = `import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{process.env.NODE_ENV === "development" && (
)}
{children}
);
}`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithScript);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("data-options");
expect(result.newContent).not.toMatch(/\}\)\n\s*\n\s*\/>/);
});
it("should add multiple options to React Grab script", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Ctrl+Shift+G",
activationMode: "toggle",
keyHoldDuration: 200,
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("activationKey");
expect(result.newContent).toContain("Ctrl+Shift+G");
expect(result.newContent).toContain("activationMode");
expect(result.newContent).toContain("toggle");
expect(result.newContent).toContain("keyHoldDuration");
expect(result.newContent).toContain("200");
});
it("should add allowActivationInsideInput option", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithReactGrab);
const options: ReactGrabOptions = {
allowActivationInsideInput: false,
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("allowActivationInsideInput");
expect(result.newContent).toContain("false");
});
it("should add maxContextLines option", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithReactGrab);
const options: ReactGrabOptions = {
maxContextLines: 5,
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("maxContextLines");
expect(result.newContent).toContain("5");
});
it("should update existing data-options attribute", () => {
const layoutWithOptions = `import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{process.env.NODE_ENV === "development" && (
)}
{children}
);
}`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithOptions);
const options: ReactGrabOptions = {
activationKey: "Meta+Space",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("Meta+Space");
expect(result.newContent).not.toContain('"Alt"');
});
it("should fail when React Grab is not found", () => {
const layoutWithoutReactGrab = `export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithoutReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(false);
expect(result.message).toContain("Could not find React Grab");
});
it("should fail when layout file not found", () => {
mockExistsSync.mockReturnValue(false);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(false);
expect(result.message).toContain("Could not find file");
});
it("should configure options in instrumentation-client when layout is not wired", () => {
const layoutWithoutReactGrab = `export default function RootLayout({ children }: { children: React.ReactNode }) {
return {children};
}`;
const instrumentationWithReactGrab = `if (process.env.NODE_ENV === "development") {
void import("react-grab");
}`;
mockExistsSync.mockImplementation((path) => {
const pathString = String(path);
return pathString.endsWith("layout.tsx") || pathString.endsWith("instrumentation-client.ts");
});
mockReadFileSync.mockImplementation((path) => {
if (String(path).endsWith("instrumentation-client.ts")) return instrumentationWithReactGrab;
return layoutWithoutReactGrab;
});
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.filePath).toContain("instrumentation-client.ts");
expect(result.newContent).toContain('void import("react-grab").then((m) => m.init(');
expect(result.newContent).toContain('"activationKey":"Meta+K"');
});
it("should configure options in the layout file that actually contains React Grab", () => {
const layoutWithoutReactGrab = `export default function RootLayout({ children }: { children: React.ReactNode }) {
return {children};
}`;
const layoutWithReactGrab = `import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}`;
mockExistsSync.mockImplementation((path) => {
const pathString = toPosixPath(path);
return pathString.endsWith("app/layout.tsx") || pathString.endsWith("src/app/layout.tsx");
});
mockReadFileSync.mockImplementation((path) => {
if (toPosixPath(path).includes("src/app/layout.tsx")) return layoutWithReactGrab;
return layoutWithoutReactGrab;
});
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(toPosixPath(result.filePath)).toContain("src/app/layout.tsx");
expect(result.newContent).toContain("data-options");
expect(result.newContent).toContain("Meta+K");
});
});
describe("previewOptionsTransform - Next.js Pages Router", () => {
const documentWithReactGrab = `import { Html, Head, Main, NextScript } from "next/document";
import Script from "next/script";
export default function Document() {
return (
);
}`;
it("should add options to Pages Router document", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("_document.tsx"));
mockReadFileSync.mockReturnValue(documentWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+G",
activationMode: "hold",
};
const result = previewOptionsTransform("/test", "next", "pages", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("data-options");
expect(result.newContent).toContain("Meta+G");
expect(result.newContent).toContain("hold");
});
});
describe("previewOptionsTransform - Vite", () => {
const entryWithReactGrab = `if (import.meta.env.DEV) {
import("react-grab");
}
import React from "react";
import ReactDOM from "react-dom/client";`;
it("should add options to Vite import", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("main.tsx"));
mockReadFileSync.mockReturnValue(entryWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Space",
};
const result = previewOptionsTransform("/test", "vite", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("init(");
expect(result.newContent).toContain('"activationKey":"Space"');
});
it("should update existing options in Vite import without duplicating", () => {
const entryWithExistingOptions = `if (import.meta.env.DEV) {
import("react-grab").then((m) => m.init({"activationKey":"g"}));
}
import React from "react";
import ReactDOM from "react-dom/client";`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("main.tsx"));
mockReadFileSync.mockReturnValue(entryWithExistingOptions);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "vite", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain('"activationKey":"Meta+K"');
expect(result.newContent).not.toContain('"activationKey":"g"');
const initCount = (result.newContent!.match(/\.then\(/g) || []).length;
expect(initCount).toBe(1);
});
it("should replace subpath import with existing callback without double-chaining", () => {
const entryWithSubpathInit = `if (import.meta.env.DEV) {
import("react-grab/dist/index.global.js").then(({ init }) => init({"activationKey":"g"}));
}
import React from "react";
import ReactDOM from "react-dom/client";`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("main.tsx"));
mockReadFileSync.mockReturnValue(entryWithSubpathInit);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "vite", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain(
'import("react-grab").then((m) => m.init({"activationKey":"Meta+K"}))',
);
const initCount = (result.newContent!.match(/\.then\(/g) || []).length;
expect(initCount).toBe(1);
});
it("should add multiple options to Vite import", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("main.tsx"));
mockReadFileSync.mockReturnValue(entryWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Alt+E",
activationMode: "toggle",
maxContextLines: 10,
};
const result = previewOptionsTransform("/test", "vite", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain(".then((m) => m.init(");
expect(result.newContent).toContain('"activationKey":"Alt+E"');
expect(result.newContent).toContain('"activationMode":"toggle"');
expect(result.newContent).toContain('"maxContextLines":10');
});
it("should add options to Vite subpath import", () => {
const entryWithSubpathReactGrab = `if (import.meta.env.DEV) {
import("react-grab/dist/index.global.js");
}
import React from "react";
import ReactDOM from "react-dom/client";`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("main.tsx"));
mockReadFileSync.mockReturnValue(entryWithSubpathReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "vite", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain(
'import("react-grab").then((m) => m.init({"activationKey":"Meta+K"}))',
);
});
it("should fail when React Grab import not found", () => {
const entryWithoutReactGrab = `import React from "react";
import ReactDOM from "react-dom/client";`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("main.tsx"));
mockReadFileSync.mockReturnValue(entryWithoutReactGrab);
const options: ReactGrabOptions = {
activationKey: "Space",
};
const result = previewOptionsTransform("/test", "vite", "unknown", options);
expect(result.success).toBe(false);
});
});
describe("previewOptionsTransform - Webpack", () => {
const entryWithReactGrab = `if (process.env.NODE_ENV === "development") {
import("react-grab");
}
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")!).render(
);`;
it("should add options to Webpack import", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("index.tsx"));
mockReadFileSync.mockReturnValue(entryWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Ctrl+K",
};
const result = previewOptionsTransform("/test", "webpack", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain(".then((m) => m.init(");
expect(result.newContent).toContain('"activationKey":"Ctrl+K"');
});
it("should update existing options in Webpack import without duplicating", () => {
const entryWithExistingOptions = `if (process.env.NODE_ENV === "development") {
import("react-grab").then((m) => m.init({"activationKey":"Ctrl+G"}));
}
import React from "react";
import ReactDOM from "react-dom/client";`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("index.tsx"));
mockReadFileSync.mockReturnValue(entryWithExistingOptions);
const options: ReactGrabOptions = {
activationKey: "Space",
};
const result = previewOptionsTransform("/test", "webpack", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain('"activationKey":"Space"');
expect(result.newContent).not.toContain('"activationKey":"Ctrl+G"');
const initCount = (result.newContent!.match(/\.then\(/g) || []).length;
expect(initCount).toBe(1);
});
it("should handle all configuration options", () => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("index.tsx"));
mockReadFileSync.mockReturnValue(entryWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+Shift+D",
activationMode: "hold",
keyHoldDuration: 300,
allowActivationInsideInput: true,
maxContextLines: 7,
};
const result = previewOptionsTransform("/test", "webpack", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain('"activationKey":"Meta+Shift+D"');
expect(result.newContent).toContain('"activationMode":"hold"');
expect(result.newContent).toContain('"keyHoldDuration":300');
expect(result.newContent).toContain('"allowActivationInsideInput":true');
expect(result.newContent).toContain('"maxContextLines":7');
});
});
describe("previewOptionsTransform - TanStack Start", () => {
it("should preserve void when adding options to React Grab import", () => {
const rootWithReactGrab = `import { useEffect } from "react";
import { Outlet, createRootRoute } from "@tanstack/react-router";
export const Route = createRootRoute({ component: RootComponent });
function RootComponent() {
useEffect(() => {
if (import.meta.env.DEV) {
void import("react-grab");
}
}, []);
return ;
}`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("__root.tsx"));
mockReadFileSync.mockReturnValue(rootWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "tanstack", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain(
'void import("react-grab/core").then(({ init }) => init({"activationKey":"Meta+K"}))',
);
});
it("should replace existing core init callback without double-chaining", () => {
const rootWithReactGrab = `import { useEffect } from "react";
import { Outlet, createRootRoute } from "@tanstack/react-router";
export const Route = createRootRoute({ component: RootComponent });
function RootComponent() {
useEffect(() => {
if (import.meta.env.DEV) {
import("react-grab/core").then((m) => m.init({"activationKey":"g"}));
}
}, []);
return ;
}`;
mockExistsSync.mockImplementation((path) => String(path).endsWith("__root.tsx"));
mockReadFileSync.mockReturnValue(rootWithReactGrab);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "tanstack", "unknown", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain(
'import("react-grab/core").then(({ init }) => init({"activationKey":"Meta+K"}))',
);
const initCount = (result.newContent!.match(/\.then\(/g) || []).length;
expect(initCount).toBe(1);
});
});
describe("previewOptionsTransform - Unknown framework", () => {
it("should fail for unknown framework (no file found)", () => {
mockExistsSync.mockReturnValue(false);
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "unknown", "unknown", options);
expect(result.success).toBe(false);
expect(result.message).toContain("Could not find file");
});
});
describe("applyTransform", () => {
it("should write file when result has newContent and file is writable", () => {
mockAccessSync.mockReturnValue(undefined);
mockWriteFileSync.mockReturnValue(undefined);
const result = {
success: true,
filePath: "/test/layout.tsx",
message: "Update React Grab options",
originalContent: "old content",
newContent: "new content with options",
};
const writeResult = applyTransform(result);
expect(writeResult.success).toBe(true);
expect(mockWriteFileSync).toHaveBeenCalledWith("/test/layout.tsx", "new content with options");
});
it("should return error when file is not writable", () => {
mockAccessSync.mockImplementation(() => {
throw new Error("EACCES");
});
const result = {
success: true,
filePath: "/test/layout.tsx",
message: "Update React Grab options",
originalContent: "old content",
newContent: "new content",
};
const writeResult = applyTransform(result);
expect(writeResult.success).toBe(false);
expect(writeResult.error).toContain("Cannot write to");
expect(mockWriteFileSync).not.toHaveBeenCalled();
});
it("should not write file when result has noChanges", () => {
const result = {
success: true,
filePath: "/test/layout.tsx",
message: "No changes needed",
noChanges: true,
};
const writeResult = applyTransform(result);
expect(writeResult.success).toBe(true);
expect(mockWriteFileSync).not.toHaveBeenCalled();
});
it("should not write file when result is not successful", () => {
const result = {
success: false,
filePath: "/test/layout.tsx",
message: "Error",
};
const writeResult = applyTransform(result);
expect(writeResult.success).toBe(true);
expect(mockWriteFileSync).not.toHaveBeenCalled();
});
});
describe("Activation key formats", () => {
const layoutWithReactGrab = `import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}`;
beforeEach(() => {
mockExistsSync.mockImplementation((path) => String(path).endsWith("layout.tsx"));
mockReadFileSync.mockReturnValue(layoutWithReactGrab);
});
it("should handle simple key like Space", () => {
const options: ReactGrabOptions = {
activationKey: "Space",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("Space");
});
it("should handle single letter key", () => {
const options: ReactGrabOptions = {
activationKey: "g",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain('"g"');
});
it("should handle modifier + key combo", () => {
const options: ReactGrabOptions = {
activationKey: "Meta+K",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("Meta+K");
});
it("should handle multiple modifiers + key", () => {
const options: ReactGrabOptions = {
activationKey: "Ctrl+Shift+Alt+G",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("Ctrl+Shift+Alt+G");
});
it("should handle function keys", () => {
const options: ReactGrabOptions = {
activationKey: "F1",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("F1");
});
it("should handle Escape key", () => {
const options: ReactGrabOptions = {
activationKey: "Escape",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("Escape");
});
it("should handle Meta+Escape combo", () => {
const options: ReactGrabOptions = {
activationKey: "Meta+Escape",
};
const result = previewOptionsTransform("/test", "next", "app", options);
expect(result.success).toBe(true);
expect(result.newContent).toContain("Meta+Escape");
});
});