import { expect, test, describe } from "vitest"; import { transform } from "@swc/core"; import path from "node:path"; import url from "node:url"; import fs from "node:fs/promises"; import { runInNewContext } from "node:vm"; const pluginName = "swc_plugin_styled_components.wasm"; const transformCode = async (code: string, options = {}) => { return transform(code, { jsc: { parser: { syntax: "ecmascript", jsx: true, }, target: "es2018", experimental: { plugins: [ [ path.join( path.dirname(url.fileURLToPath(import.meta.url)), "..", pluginName, ), options, ], ], }, }, filename: "test.js", }); }; async function walkDir( dir: URL, callback: ( dir: string, input: string, config?: Record, ) => Promise, ) { const dirs = await fs.readdir(dir); const baseDir = url.fileURLToPath(dir); for (const dir of dirs) { const inputFilePath = path.join(baseDir, dir, "code.js"); const configPath = path.join(baseDir, dir, "config.json"); const config = await fs.readFile(configPath, "utf-8").then( (json) => { return JSON.parse(json); }, (_) => { // ignore return {}; }, ); try { const input = await fs.readFile(inputFilePath, "utf-8"); await callback(dir, input, config); } catch (e) { console.log(e); } } } describe("Should load styled-components wasm plugin correctly", async () => { await walkDir( new URL("../transform/tests/fixtures", import.meta.url), async (dir, input, config) => { await test(`Should transform ${dir} correctly`, async () => { const { code } = await transformCode(input, config); expect(code).toMatchSnapshot(); }); }, ); }); test("issue-659: evaluates nested css prop member chains at render time", async () => { const fixture = new URL( "../transform/tests/fixtures/issue-659/", import.meta.url, ); const input = await fs.readFile(new URL("code.js", fixture), "utf-8"); const config = JSON.parse( await fs.readFile(new URL("config.json", fixture), "utf-8"), ); const transformed = await transformCode(input, config); const { code } = await transform(transformed.code, { module: { type: "commonjs" }, jsc: { target: "es2018" }, }); const styled = Object.assign(() => () => ({}), { div: () => ({}) }); const exports = {} as { Avatar: (props: { size: string; property: string }) => unknown; }; runInNewContext(code, { exports, require: () => ({ __esModule: true, default: styled }), React: { createElement: (_type: unknown, props: unknown) => props }, }); expect(exports.Avatar({ size: "small", property: "bottom" })).toEqual({ $_css: "8px", $_css2: "4px", $_css3: "4px", $_css4: "8px", }); expect(exports.Avatar({ size: "large", property: "bottom" })).toEqual({ $_css: "16px", $_css2: "8px", $_css3: "8px", $_css4: "8px", }); });