function patchESBuildOptimizerPlugin(plugin, options) {
	const components = plugin.name === optimizeSveltePluginName;
	const compileFn = components ? compileSvelte : compileSvelteModule;
	const statsName = components ? 'prebundle library components' : 'prebundle library modules';
	const filter = components ? /\.svelte(?:\?.*)?$/ : /\.svelte\.[jt]s(?:\?.*)?$/;
	plugin.setup = (build) => {
		if (build.initialOptions.plugins?.some((v) => v.name === 'vite:dep-scan')) return;

		/** @type {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection | undefined} */
		let statsCollection;
		build.onStart(() => {
			statsCollection = options.stats?.startCollection(statsName, {
				logResult: (c) => c.stats.length > 1
			});
		});
		build.onLoad({ filter }, async ({ path: filename }) => {
			const code = readFileSync(filename, 'utf8');
			try {
				const result = await compileFn(options, { filename, code }, statsCollection);
				const contents = result.map
					? result.code + '//# sourceMappingURL=' + result.map.toUrl()
					: result.code;
				return { contents };
			} catch (e) {
				return { errors: [toESBuildError(e, options)] };
			}
		});
		build.onEnd(() => {
			statsCollection?.finish();
		});
	};
}
@param {EsbuildPlugin} plugin
@param {import('../types/options.d.ts').ResolvedOptions} options