Commit 2a6e4a19 authored by Luke Sandberg's avatar Luke Sandberg Committed by Luke Sandberg

rework communication protocol

rust -> bootstraps worker
worker ->registers with rust

rust <-> work chat at will
parent f3ee8bfa
...@@ -378,16 +378,6 @@ dependencies = [ ...@@ -378,16 +378,6 @@ dependencies = [
"critical-section", "critical-section",
] ]
[[package]]
name = "atomic-wait"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a55b94919229f2c42292fd71ffa4b75e83193bffdd77b1e858cd55fd2d0b0ea8"
dependencies = [
"libc",
"windows-sys 0.42.0",
]
[[package]] [[package]]
name = "atomic-waker" name = "atomic-waker"
version = "1.1.2" version = "1.1.2"
...@@ -8440,10 +8430,8 @@ name = "swc_plugin_backend_napi" ...@@ -8440,10 +8430,8 @@ name = "swc_plugin_backend_napi"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"atomic-wait",
"napi", "napi",
"napi-derive", "napi-derive",
"once_cell",
"swc_plugin_runner 25.0.0", "swc_plugin_runner 25.0.0",
] ]
...@@ -11710,21 +11698,6 @@ dependencies = [ ...@@ -11710,21 +11698,6 @@ dependencies = [
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
[[package]]
name = "windows-sys"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.45.0" version = "0.45.0"
......
...@@ -9,8 +9,6 @@ workspace = true ...@@ -9,8 +9,6 @@ workspace = true
[dependencies] [dependencies]
anyhow = { workspace = true } anyhow = { workspace = true }
atomic-wait = "1.1.0"
once_cell = { workspace = true }
napi = { workspace = true } napi = { workspace = true }
napi-derive = { workspace = true } napi-derive = { workspace = true }
swc_plugin_runner = { version = "25.0.0", default-features = false } swc_plugin_runner = { version = "25.0.0", default-features = false }
This diff is collapsed.
...@@ -155,6 +155,7 @@ ...@@ -155,6 +155,7 @@
"@swc/cli": "0.1.55", "@swc/cli": "0.1.55",
"@swc/core": "1.11.24", "@swc/core": "1.11.24",
"@swc/helpers": "0.5.15", "@swc/helpers": "0.5.15",
"@swc/plugin-react-remove-properties": "11.1.0",
"@swc/types": "0.1.7", "@swc/types": "0.1.7",
"@taskr/esnext": "1.1.0", "@taskr/esnext": "1.1.0",
"@testing-library/jest-dom": "6.1.2", "@testing-library/jest-dom": "6.1.2",
......
...@@ -1164,5 +1164,7 @@ ...@@ -1164,5 +1164,7 @@
"1163": "No active instance for memory operation", "1163": "No active instance for memory operation",
"1164": "Unknown request type: %s", "1164": "Unknown request type: %s",
"1165": "Instance %s not found", "1165": "Instance %s not found",
"1166": "wasm-worker must be run as a worker thread" "1166": "wasm-worker must be run as a worker thread",
"1167": "wasm-manager: nativeBindingsPath not set",
"1168": "Instance %s not found for host fn"
} }
...@@ -62,6 +62,41 @@ export declare function recvTaskMessageInWorker( ...@@ -62,6 +62,41 @@ export declare function recvTaskMessageInWorker(
workerId: number workerId: number
): Promise<NapiTaskMessage> ): Promise<NapiTaskMessage>
export declare function sendTaskMessage(message: NapiTaskMessage): Promise<void> export declare function sendTaskMessage(message: NapiTaskMessage): Promise<void>
/**
* Called by worker after WASM instantiation to register a dispatch callback.
*
* The `ops` object must have these methods:
* - transform(programPtr, programLen, unresolvedMark, commentsProxy) → number
* - getDiag() → number
* - readMemory(ptr, len) → Buffer
* - writeMemory(ptr, data: Buffer) → void
* - alloc(size) → number
* - free(ptr, size) → number
*
* A TSFN is created targeting this worker's event loop. When Rust needs to
* call a WASM export, it posts to this TSFN, which runs the appropriate
* method on `ops` and sends the result back via a sync channel.
*/
export declare function wasmWorkerRegisterCallback(
instanceId: number,
ops: object
): void
/**
* Called by worker when WASM hits a host function import.
* Runs the Func closure synchronously on the worker thread and returns the result.
*
* The worker provides a `memoryAccessor` object with methods to read/write WASM memory:
* - readBuf(ptr, len) → Buffer
* - writeBuf(ptr, data: Buffer) → void
* - alloc(size) → number
* - free(ptr, size) → number
*/
export declare function wasmWorkerDispatchHostFn(
instanceId: number,
fnIndex: number,
args: Array<number>,
memoryAccessor: object
): unknown
export interface NapiLocation { export interface NapiLocation {
line: number line: number
column?: number column?: number
......
...@@ -1736,8 +1736,13 @@ function loadNative(importPath?: string): Binding { ...@@ -1736,8 +1736,13 @@ function loadNative(importPath?: string): Binding {
// Register the NAPI-based WASM plugin runtime so SWC plugins run via // Register the NAPI-based WASM plugin runtime so SWC plugins run via
// Node's V8 WebAssembly engine instead of wasmtime. // Node's V8 WebAssembly engine instead of wasmtime.
if (typeof bindings.registerWasmPluginRuntime === 'function') { if (
const { wasmManager } = (require('./wasm-manager') as typeof import('./wasm-manager')) typeof bindings.registerWasmPluginRuntime === 'function' &&
bindingsPath
) {
const { wasmManager } =
require('./wasm-manager') as typeof import('./wasm-manager')
wasmManager.setBindingsPath(bindingsPath)
bindings.registerWasmPluginRuntime(wasmManager) bindings.registerWasmPluginRuntime(wasmManager)
} }
......
...@@ -4,41 +4,29 @@ ...@@ -4,41 +4,29 @@
* Architecture: * Architecture:
* - Module compilation: cached on main thread (WebAssembly.Module is ref-counted) * - Module compilation: cached on main thread (WebAssembly.Module is ref-counted)
* - Instance lifecycle: delegated to worker threads via postMessage * - Instance lifecycle: delegated to worker threads via postMessage
* - Transform hot path: Rust thread talks directly to worker via SharedArrayBuffer * - Transform/getDiag/memory ops: Rust dispatches to worker threads via
* - Host function callbacks during transform: Rust ↔ worker via Atomics * per-instance ThreadsafeFunctions (TSFNs) — no blocking loops or Condvars
* - Host function callbacks: synchronous NAPI calls on the worker thread
* *
* The main thread's role is minimal: compile modules, route setup requests to * The main thread's role: compile modules and route setup requests to workers.
* workers, and provide the shared memory pointers to Rust for direct access.
*/ */
import { Worker, type TransferListItem } from 'worker_threads' import { Worker } from 'worker_threads'
import path from 'path' import path from 'path'
// ---------------------------------------------------------------------------
// Shared memory layout constants (must match wasm-worker.ts and lib.rs)
// ---------------------------------------------------------------------------
const CTRL_BUFFER_INTS = 32 // Int32 slots in control buffer
const CTRL_BUFFER_SIZE = CTRL_BUFFER_INTS * 4
const DATA_BUFFER_SIZE = 8 * 1024 * 1024 // 8MB for memory read/write ops
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Worker pool // Worker pool
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
interface WorkerEntry { interface WorkerEntry {
worker: Worker worker: Worker
ctrlBuffer: SharedArrayBuffer /** Instance IDs owned by this worker (one per worker in current design) */
dataBuffer: SharedArrayBuffer
/** Instance IDs owned by this worker */
instances: Set<number> instances: Set<number>
/** Pending postMessage responses */ /** Pending postMessage responses */
pending: Map< pending: Map<
number, number,
{ resolve: (v: any) => void; reject: (e: Error) => void } { resolve: (v: any) => void; reject: (e: Error) => void }
> >
/** True while a transform is in progress (Atomics-based) */
busy: boolean
} }
const workers: WorkerEntry[] = [] const workers: WorkerEntry[] = []
...@@ -48,6 +36,9 @@ let nextInstanceId = 1 ...@@ -48,6 +36,9 @@ let nextInstanceId = 1
// Map from instance ID → worker index for routing // Map from instance ID → worker index for routing
const instanceWorkerMap = new Map<number, number>() const instanceWorkerMap = new Map<number, number>()
// Path to the native .node binding, set during init
let nativeBindingsPath: string | null = null
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Module cache: compile once, clone to workers for free // Module cache: compile once, clone to workers for free
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -60,24 +51,21 @@ const compiledModules = new Map<number, WebAssembly.Module>() ...@@ -60,24 +51,21 @@ const compiledModules = new Map<number, WebAssembly.Module>()
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function createWorker(): WorkerEntry { function createWorker(): WorkerEntry {
const ctrlBuffer = new SharedArrayBuffer(CTRL_BUFFER_SIZE) if (!nativeBindingsPath) {
const dataBuffer = new SharedArrayBuffer(DATA_BUFFER_SIZE) throw new Error('wasm-manager: nativeBindingsPath not set')
}
// Initialize control flag to IDLE (0)
new Int32Array(ctrlBuffer)[0] = 0
const workerPath = path.join(__dirname, 'wasm-worker.js') const workerPath = path.join(__dirname, 'wasm-worker.js')
const worker = new Worker(workerPath, { const worker = new Worker(workerPath, {
workerData: { ctrlBuffer, dataBuffer }, workerData: { nativeBindingsPath },
// Suppress the WASI warnings, this isn't a great solution
execArgv: ['--no-warnings'],
}) })
const entry: WorkerEntry = { const entry: WorkerEntry = {
worker, worker,
ctrlBuffer,
dataBuffer,
instances: new Set(), instances: new Set(),
pending: new Map(), pending: new Map(),
busy: false,
} }
worker.on('message', (msg: { id: number; result?: any; error?: string }) => { worker.on('message', (msg: { id: number; result?: any; error?: string }) => {
...@@ -93,31 +81,29 @@ function createWorker(): WorkerEntry { ...@@ -93,31 +81,29 @@ function createWorker(): WorkerEntry {
}) })
worker.on('error', (err) => { worker.on('error', (err) => {
// Reject all pending operations console.error(`[wasm-manager] worker error:`, err)
for (const [, p] of entry.pending) { for (const [, p] of entry.pending) {
p.reject(err) p.reject(err)
} }
entry.pending.clear() entry.pending.clear()
}) })
worker.on('exit', (code) => {
if (code !== 0) {
console.error(`[wasm-manager] worker exited with code ${code}`)
}
})
workers.push(entry) workers.push(entry)
return entry return entry
} }
function sendToWorker( function sendToWorker(entry: WorkerEntry, msg: any): Promise<any> {
entry: WorkerEntry,
msg: any,
transfer?: TransferListItem[]
): Promise<any> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const id = nextMessageId++ const id = nextMessageId++
msg.id = id msg.id = id
entry.pending.set(id, { resolve, reject }) entry.pending.set(id, { resolve, reject })
if (transfer) { entry.worker.postMessage(msg)
entry.worker.postMessage(msg, transfer)
} else {
entry.worker.postMessage(msg)
}
}) })
} }
...@@ -143,26 +129,24 @@ function pickWorker(): WorkerEntry { ...@@ -143,26 +129,24 @@ function pickWorker(): WorkerEntry {
export const wasmManager = { export const wasmManager = {
/** /**
* Initialize the worker pool. Called once during registration. * Initialize the worker pool. Called once during registration.
* Returns an array of { ctrlBuffer, dataBuffer } for each worker, * Workers load the native addon directly for NAPI-based communication.
* which Rust stores for direct Atomics access.
*/ */
initWorkerPool(workerCount: number): Array<{ initWorkerPool(workerCount: number): void {
ctrlBuffer: SharedArrayBuffer
dataBuffer: SharedArrayBuffer
}> {
for (let i = 0; i < workerCount; i++) { for (let i = 0; i < workerCount; i++) {
createWorker() createWorker()
} }
return workers.map((w) => ({ },
ctrlBuffer: w.ctrlBuffer,
dataBuffer: w.dataBuffer, /**
})) * Set the path to the native .node binding file.
* Must be called before initWorkerPool.
*/
setBindingsPath(bindingsPath: string): void {
nativeBindingsPath = bindingsPath
}, },
/** /**
* Compile a WASM module and cache it. Returns a module ID. * Compile a WASM module and cache it. Returns a module ID.
* The WebAssembly.Module is stored on the main thread; workers receive
* it via postMessage structured clone (V8 shares the compiled code).
*/ */
compileModule(wasmBytes: Buffer): number { compileModule(wasmBytes: Buffer): number {
const id = nextModuleId++ const id = nextModuleId++
...@@ -186,8 +170,9 @@ export const wasmManager = { ...@@ -186,8 +170,9 @@ export const wasmManager = {
* Instantiate a WASM module on a worker. The module is transferred via * Instantiate a WASM module on a worker. The module is transferred via
* structured clone (zero-cost for WebAssembly.Module). * structured clone (zero-cost for WebAssembly.Module).
* *
* Returns { instanceId, workerIndex } so Rust knows which worker's * Returns { instanceId, promise } — Rust waits on the promise for completion.
* SharedArrayBuffer to use for transforms. * After instantiation, the worker registers ops with Rust via NAPI and
* its event loop remains free to receive TSFN callbacks.
*/ */
instantiateOnWorker( instantiateOnWorker(
moduleId: number, moduleId: number,
...@@ -197,7 +182,7 @@ export const wasmManager = { ...@@ -197,7 +182,7 @@ export const wasmManager = {
resultCount: number resultCount: number
index: number index: number
}> }>
): { instanceId: number; workerIndex: number; promise: Promise<number> } { ): { instanceId: number; promise: Promise<number> } {
const module = compiledModules.get(moduleId) const module = compiledModules.get(moduleId)
if (!module) throw new Error(`Module ${moduleId} not found`) if (!module) throw new Error(`Module ${moduleId} not found`)
...@@ -215,100 +200,7 @@ export const wasmManager = { ...@@ -215,100 +200,7 @@ export const wasmManager = {
hostFnDescriptors, hostFnDescriptors,
}) })
return { instanceId, workerIndex, promise } return { instanceId, promise }
},
/**
* Get the worker index for a given instance (for routing).
*/
getWorkerIndex(instanceId: number): number {
const idx = instanceWorkerMap.get(instanceId)
if (idx === undefined) throw new Error(`Instance ${instanceId} not found`)
return idx
},
/**
* Read memory from a worker's WASM instance via postMessage.
* Used for non-hot-path operations (setup, teardown).
*/
readMemoryAsync(
instanceId: number,
ptr: number,
len: number
): Promise<Buffer> {
const workerIndex = instanceWorkerMap.get(instanceId)
if (workerIndex === undefined)
throw new Error(`Instance ${instanceId} not found`)
return sendToWorker(workers[workerIndex], {
type: 'readMemory',
instanceId,
ptr,
len,
}).then((ab: ArrayBuffer) => Buffer.from(ab))
},
/**
* Write memory to a worker's WASM instance via postMessage.
*/
writeMemoryAsync(
instanceId: number,
ptr: number,
data: Buffer
): Promise<void> {
const workerIndex = instanceWorkerMap.get(instanceId)
if (workerIndex === undefined)
throw new Error(`Instance ${instanceId} not found`)
const ab = data.buffer.slice(
data.byteOffset,
data.byteOffset + data.byteLength
) as ArrayBuffer
return sendToWorker(
workers[workerIndex],
{ type: 'writeMemory', instanceId, ptr, data: ab },
[ab]
)
},
/**
* Allocate memory in a worker's WASM instance via postMessage.
*/
allocAsync(instanceId: number, size: number): Promise<number> {
const workerIndex = instanceWorkerMap.get(instanceId)
if (workerIndex === undefined)
throw new Error(`Instance ${instanceId} not found`)
return sendToWorker(workers[workerIndex], {
type: 'alloc',
instanceId,
size,
})
},
/**
* Free memory in a worker's WASM instance via postMessage.
*/
freeAsync(instanceId: number, ptr: number, size: number): Promise<number> {
const workerIndex = instanceWorkerMap.get(instanceId)
if (workerIndex === undefined)
throw new Error(`Instance ${instanceId} not found`)
return sendToWorker(workers[workerIndex], {
type: 'free',
instanceId,
ptr,
size,
})
},
/**
* Get diagnostics from a worker's WASM instance via postMessage.
*/
getDiagAsync(instanceId: number): Promise<number> {
const workerIndex = instanceWorkerMap.get(instanceId)
if (workerIndex === undefined)
throw new Error(`Instance ${instanceId} not found`)
return sendToWorker(workers[workerIndex], {
type: 'getDiag',
instanceId,
})
}, },
dropModule(moduleId: number): void { dropModule(moduleId: number): void {
......
This diff is collapsed.
...@@ -159,6 +159,9 @@ importers: ...@@ -159,6 +159,9 @@ importers:
'@swc/helpers': '@swc/helpers':
specifier: 0.5.15 specifier: 0.5.15
version: 0.5.15 version: 0.5.15
'@swc/plugin-react-remove-properties':
specifier: 11.1.0
version: 11.1.0
'@swc/types': '@swc/types':
specifier: 0.1.7 specifier: 0.1.7
version: 0.1.7 version: 0.1.7
...@@ -6436,6 +6439,9 @@ packages: ...@@ -6436,6 +6439,9 @@ packages:
peerDependencies: peerDependencies:
'@swc/core': '*' '@swc/core': '*'
'@swc/plugin-react-remove-properties@11.1.0':
resolution: {integrity: sha512-+L+wq63DMWi4dbcYUmNNEWYZdJjCFqnOTglsTh3/ZHPbB3DWOd2qQtb/CyxfqC6liih4/RoNff2yogm6JBf4aQ==}
'@swc/types@0.1.21': '@swc/types@0.1.21':
resolution: {integrity: sha512-2YEtj5HJVbKivud9N4bpPBAyZhj4S2Ipe5LkUG94alTpr7in/GU/EARgPAd3BwU+YOmFVJC2+kjqhGRi3r0ZpQ==} resolution: {integrity: sha512-2YEtj5HJVbKivud9N4bpPBAyZhj4S2Ipe5LkUG94alTpr7in/GU/EARgPAd3BwU+YOmFVJC2+kjqhGRi3r0ZpQ==}
...@@ -24120,6 +24126,10 @@ snapshots: ...@@ -24120,6 +24126,10 @@ snapshots:
'@swc/counter': 0.1.3 '@swc/counter': 0.1.3
jsonc-parser: 3.3.1 jsonc-parser: 3.3.1
'@swc/plugin-react-remove-properties@11.1.0':
dependencies:
'@swc/counter': 0.1.3
'@swc/types@0.1.21': '@swc/types@0.1.21':
dependencies: dependencies:
'@swc/counter': 0.1.3 '@swc/counter': 0.1.3
/* eslint-env jest */
/**
* Tests for the NAPI-based WASM plugin runtime.
*
* Level 1: wasm-manager worker pool lifecycle (compile, instantiate, drop)
* Level 2: Full transform through the SWC bindings with a real plugin binary
*/
import path from 'path'
// ---------------------------------------------------------------------------
// Level 1: wasm-manager worker pool and module lifecycle
// ---------------------------------------------------------------------------
describe('wasm-manager', () => {
let wasmManager: typeof import('next/dist/build/swc/wasm-manager').wasmManager
beforeAll(() => {
// Import wasm-manager directly to test its API without loading native bindings
wasmManager = require('next/dist/build/swc/wasm-manager').wasmManager
})
afterAll(() => {
// Workers are daemon threads; they'll be cleaned up on process exit.
// No explicit shutdown API yet.
})
it('initWorkerPool creates workers', () => {
// Set a dummy bindings path for testing (workers won't actually load it
// in these lifecycle tests since we don't instantiate WASM modules)
wasmManager.setBindingsPath(
path.join(
__dirname,
'..',
'..',
'node_modules',
'@next',
'swc',
'native',
'next-swc.darwin-arm64.node'
)
)
// initWorkerPool now returns void (no SABs)
wasmManager.initWorkerPool(2)
})
it('compileModule returns a module ID', () => {
// Minimal valid WASM module: magic + version + empty
const minimalWasm = new Uint8Array([
0x00,
0x61,
0x73,
0x6d, // magic: \0asm
0x01,
0x00,
0x00,
0x00, // version: 1
])
const moduleId = wasmManager.compileModule(Buffer.from(minimalWasm))
expect(typeof moduleId).toBe('number')
expect(moduleId).toBeGreaterThan(0)
// Clean up
wasmManager.dropModule(moduleId)
})
it('cloneModule returns a new ID for the same module', () => {
const minimalWasm = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
])
const moduleId = wasmManager.compileModule(Buffer.from(minimalWasm))
const cloneId = wasmManager.cloneModule(moduleId)
expect(cloneId).not.toBe(moduleId)
expect(typeof cloneId).toBe('number')
// Both should be droppable independently
wasmManager.dropModule(moduleId)
wasmManager.dropModule(cloneId)
})
it('cloneModule throws for unknown module', () => {
expect(() => wasmManager.cloneModule(999999)).toThrow(/not found/)
})
// Note: instantiateOnWorker is not tested here because it requires
// the native addon to be loaded in the worker thread (the worker enters
// a blocking NAPI work loop after instantiation). Full instantiation
// is tested in the Level 2 tests via the SWC transform path.
})
// ---------------------------------------------------------------------------
// Level 2: Full SWC transform with a real plugin
// ---------------------------------------------------------------------------
describe('swc plugin transform via NAPI runtime', () => {
let transform: typeof import('next/dist/build/swc').transform
let pluginPath: string
beforeAll(async () => {
// installBindings() sets loadedBindings so transform() (which uses
// getBindingsSync()) works. The Rust side is idempotent — if the
// jest-transformer already registered workers, this is a no-op.
const { installBindings } = require('next/dist/build/swc/install-bindings')
await installBindings()
transform = require('next/dist/build/swc').transform
pluginPath = require.resolve('@swc/plugin-react-remove-properties')
})
it('transforms code without plugins (sanity check)', async () => {
const result = await transform('const x = 1', {
filename: 'test.ts',
jsc: { parser: { syntax: 'typescript', tsx: false } },
})
expect(result.code).toContain('x')
}, 10000)
it('transforms code with swc plugin (removes data-* attributes)', async () => {
const source = `
export default function Page() {
return <div data-testid="hello" data-custom="remove-me">Hello World</div>
}
`
let result: any
try {
result = await transform(source, {
filename: 'test.tsx',
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
experimental: {
plugins: [[pluginPath, { properties: ['data-custom'] }]],
},
},
})
} catch (e: any) {
console.error('Transform error:', e.message)
console.error('Full error:', JSON.stringify(e, null, 2))
throw e
}
expect(result.code).toContain('Hello World')
// data-testid should remain (not in the removal list)
expect(result.code).toContain('data-testid')
// data-custom should be removed by the plugin
expect(result.code).not.toContain('data-custom')
})
it('transforms code with plugin removing all data-testid', async () => {
const source = `
export default function Page() {
return (
<div data-testid="a">
<span data-testid="b">text</span>
</div>
)
}
`
const result = await transform(source, {
filename: 'test.tsx',
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
experimental: {
plugins: [[pluginPath, { properties: ['^data-testid$'] }]],
},
},
})
expect(result.code).toContain('text')
expect(result.code).not.toContain('data-testid')
})
it('handles multiple sequential transforms', async () => {
for (let i = 0; i < 5; i++) {
const source = `
export function Comp${i}() {
return <div data-remove="yes">item ${i}</div>
}
`
const result = await transform(source, {
filename: `test${i}.tsx`,
jsc: {
parser: { syntax: 'typescript', tsx: true },
experimental: {
plugins: [[pluginPath, { properties: ['data-remove'] }]],
},
},
})
expect(result.code).toContain(`item ${i}`)
expect(result.code).not.toContain('data-remove')
}
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment