From 5e7342f50e7d72f6426bd7b19b14d53129aafe49 Mon Sep 17 00:00:00 2001 From: Samuel Macleod Date: Tue, 16 Dec 2025 17:54:22 +0000 Subject: [PATCH] feat(msw): add workerd export --- package.json | 14 ++++++++++++++ src/workerd/index.ts | 17 +++++++++++++++++ tsup.config.ts | 16 ++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 src/workerd/index.ts diff --git a/package.json b/package.json index a624ea9b9..48ceb106d 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,20 @@ "default": "./lib/native/index.js" } }, + "./workerd": { + "workerd": { + "types": "./lib/workerd/index.d.mts", + "default": "./lib/workerd/index.mjs" + }, + "import": { + "types": "./lib/workerd/index.d.mts", + "default": "./lib/workerd/index.mjs" + }, + "default": { + "types": "./lib/workerd/index.d.ts", + "default": "./lib/workerd/index.js" + } + }, "./core/http": { "module-sync": { "types": "./lib/core/http.d.mts", diff --git a/src/workerd/index.ts b/src/workerd/index.ts new file mode 100644 index 000000000..587ee9c09 --- /dev/null +++ b/src/workerd/index.ts @@ -0,0 +1,17 @@ +import { FetchInterceptor } from '@mswjs/interceptors/fetch' +import type { RequestHandler } from '~/core/handlers/RequestHandler' +import { SetupServerCommonApi } from '../node/SetupServerCommonApi' + +/** + * Sets up a requests interception in workerd with the given request handlers. + * @param {RequestHandler[]} handlers List of request handlers. + * + * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference} + */ +export function setupServer( + ...handlers: Array +): SetupServerCommonApi { + // Provision request interception via patching `fetch` only + // in workerd. There is no `http`/`https` modules in that environment. + return new SetupServerCommonApi([new FetchInterceptor()], handlers) +} diff --git a/tsup.config.ts b/tsup.config.ts index 76fe8e8d6..50db22904 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -125,6 +125,21 @@ const reactNativeConfig: Options = { esbuildPlugins: [resolveCoreImportsPlugin(), forceEsmExtensionsPlugin()], } +const workerdConfig: Options = { + name: 'workerd', + platform: 'node', + entry: ['./src/workerd/index.ts'], + external: ['picocolors', 'util', 'events', mswCore, ecosystemDependencies], + format: ['esm', 'cjs'], + outDir: './lib/workerd', + bundle: true, + splitting: false, + sourcemap: true, + dts: true, + tsconfig: path.resolve(__dirname, 'src/tsconfig.node.build.json'), + esbuildPlugins: [resolveCoreImportsPlugin(), forceEsmExtensionsPlugin()], +} + const iifeConfig: Options = { name: 'iife', platform: 'browser', @@ -154,6 +169,7 @@ export default defineConfig([ coreConfig, nodeConfig, reactNativeConfig, + workerdConfig, browserConfig, iifeConfig, ])