|
| 1 | +import { rollup, type Plugin } from 'rollup'; |
| 2 | +import typescript from '@rollup/plugin-typescript'; |
| 3 | +import { format, resolveConfig } from 'prettier'; |
| 4 | +import { dirname, resolve } from 'path'; |
| 5 | + |
| 6 | +interface InlineWorkerOptions { |
| 7 | + /** File names (not paths) that trigger the plugin, e.g. `['worker.ts']`. */ |
| 8 | + include: string[]; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * Rollup plugin that bundles worker TypeScript files into inline functions. |
| 13 | + * |
| 14 | + * Only files whose path ends with one of the provided `include` patterns |
| 15 | + * are processed — all other modules are skipped with zero overhead. |
| 16 | + * |
| 17 | + * For each matched file, the plugin: |
| 18 | + * 1. Finds the corresponding `-impl.ts` entry (e.g. `worker.ts` → `worker/worker-impl.ts`) |
| 19 | + * 2. Bundles it with a nested Rollup + TypeScript build |
| 20 | + * 3. Wraps the result in an exported function and formats with prettier |
| 21 | + * |
| 22 | + * The consumer creates a Worker from the function via: |
| 23 | + * `new Worker(\`data:text/javascript,(\${fn.toString()})()\`)` |
| 24 | + * or via a Blob URL. |
| 25 | + */ |
| 26 | +export default function inlineWorker({ include }: InlineWorkerOptions): Plugin { |
| 27 | + const fileNames = new Set(include); |
| 28 | + |
| 29 | + return { |
| 30 | + name: 'inline-worker', |
| 31 | + |
| 32 | + async load(id: string) { |
| 33 | + const fileName = id.split('/').pop(); |
| 34 | + if (!fileNames.has(fileName!)) return null; |
| 35 | + |
| 36 | + // e2ee-worker.ts → e2ee-worker/e2ee-worker-impl.ts |
| 37 | + const dir = dirname(id); |
| 38 | + const name = fileName!.replace(/\.ts$/, ''); |
| 39 | + const implPath = resolve(dir, name, `${name}-impl.ts`); |
| 40 | + |
| 41 | + const bundle = await rollup({ |
| 42 | + input: implPath, |
| 43 | + plugins: [ |
| 44 | + typescript({ |
| 45 | + tsconfig: resolve(dir, name, 'tsconfig.json'), |
| 46 | + exclude: ['**/node_modules/**', '**/__tests__/**'], |
| 47 | + }), |
| 48 | + ], |
| 49 | + }); |
| 50 | + |
| 51 | + const { output } = await bundle.generate({ |
| 52 | + format: 'es', |
| 53 | + indent: false, |
| 54 | + sourcemap: false, |
| 55 | + }); |
| 56 | + await bundle.close(); |
| 57 | + |
| 58 | + // Wrap bundled code in an exported function, then format with prettier. |
| 59 | + return await format( |
| 60 | + `export function e2eeWorker() { ${output[0].code} }`, |
| 61 | + { |
| 62 | + parser: 'babel', |
| 63 | + ...(await resolveConfig(implPath)), |
| 64 | + }, |
| 65 | + ); |
| 66 | + }, |
| 67 | + }; |
| 68 | +} |
0 commit comments