The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
fix(core): apply Medusa patches on import instead of in withMercur() (#1573)
Viktor Holik7c9d841f100d
diff --git a/packages/core/src/__tests__/with-mercur.unit.spec.ts b/packages/core/src/__tests__/with-mercur.unit.spec.tsindex 877d9456d..51cb67ae5 100644--- a/packages/core/src/__tests__/with-mercur.unit.spec.ts+++ b/packages/core/src/__tests__/with-mercur.unit.spec.ts@@ -1,4 +1,8 @@-jest.mock("../patches", () => ({ applyMercurPatches: jest.fn() }))+jest.mock("../patches", () => ({+ assertPatchesDisabled: jest.fn(),+ disabledPatchesFromEnv: jest.fn(() => []),+ ensureMercurPatches: jest.fn(),+}))jest.mock("../utils/disable-medusa-middlewares", () => ({disableMedusaMiddlewares: jest.fn(),}))diff --git a/packages/core/src/patches/README.md b/packages/core/src/patches/README.mdindex d5afa38b0..fc4b0a085 100644--- a/packages/core/src/patches/README.md+++ b/packages/core/src/patches/README.md@@ -8,9 +8,15 @@ incompatible (`patchedDependencies` / the `patch:` protocol / `patchedDependenci/ nothing native), and none of them reach a marketplace that installed`@mercurjs/core` into an existing Medusa app.-So the diffs live here and are applied from `withMercur()`, which every project-calls in `medusa-config.ts`. They travel with the package version and arrive on a-normal `@mercurjs/core` upgrade.+So the diffs live here and are applied as a side effect of importing+`@mercurjs/core` (or `@mercurjs/core/workflows`), via `register.ts`. They travel+with the package version and arrive on a normal `@mercurjs/core` upgrade.++It has to be the import, not the `withMercur()` call: a config's imports are all+evaluated before any call in it, so a block imported next to `@mercurjs/core` in+`medusa-config.ts` would load core-flows unpatched, and a workflow composed from+unpatched source never gains the hooks a patch adds. Import `@mercurjs/core`+before anything that pulls in core-flows.## How they are applied@@ -19,11 +25,15 @@ packages, and workers would race each other doing it. `loader.ts` installs a`.js` loader hook and compiles the patched source in place of the original onfirst require.-`withMercur()` is not always the first thing to pull in a target package —+`@mercurjs/core` is not always the first thing to pull in a target package —`@medusajs/test-utils` requires `@medusajs/core-flows` before it loads`medusa-config` — so a patched file may already sit in the require cache with itsunpatched source. Those files (only those files, never the whole package) are-evicted and required again through the hook. A workflow module re-registers+evicted and required again through the hook, and the fresh exports are copied+onto the evicted module's `exports` object: every index above the file+re-exports it through a getter over that object, so without the copy+`require("@medusajs/core-flows")` would keep returning the unpatched workflow.+Anything that already destructured the old value keeps it. A workflow module re-registersitself under the same id on that second load, and since the reload replays thesame source, replacing the previous definition is the correct outcome: Medusa'sduplicate guard is relaxed for the duration of the reload, because generated step@@ -94,14 +104,16 @@ upstream in Medusa, not here.## Escape hatch-```ts-withMercur({- projectConfig: {- mercur: { disabledPatches: ["@[email protected]"] },- },-})+```bash+MERCUR_DISABLED_PATCHES="@[email protected]" medusa develop```+Comma separated. It is read from the process environment when `@mercurjs/core`+is imported, so it must be set before `medusa-config.ts` is evaluated — a `.env`+loaded by `loadEnv()` inside the config is too late. The older+`projectConfig.mercur.disabledPatches` is read after the patches are applied, so+listing a patch only there fails the boot with a pointer to the variable.+Skipping a patch restores the upstream bug it corrects; the reason is logged.## Current patchesdiff --git a/packages/core/src/patches/__tests__/disabled-patches.unit.spec.ts b/packages/core/src/patches/__tests__/disabled-patches.unit.spec.tsnew file mode 100644index 000000000..392a61940--- /dev/null+++ b/packages/core/src/patches/__tests__/disabled-patches.unit.spec.ts@@ -0,0 +1,38 @@+import { assertPatchesDisabled, disabledPatchesFromEnv } from "../index"++const APPLIED = Symbol.for("@mercurjs/core/patches-applied")+const state = globalThis as typeof globalThis & {+ [APPLIED]?: { disabled: string[] }+}++describe("disabledPatchesFromEnv", () => {+ it("reads a comma separated list", () => {+ expect(+ disabledPatchesFromEnv({ MERCUR_DISABLED_PATCHES: " a.patch, ,b.patch " })+ ).toEqual(["a.patch", "b.patch"])+ })++ it("is empty when unset", () => {+ expect(disabledPatchesFromEnv({})).toEqual([])+ })+})++describe("assertPatchesDisabled", () => {+ afterEach(() => {+ delete state[APPLIED]+ })++ it("accepts a config opt-out that was already honoured on import", () => {+ state[APPLIED] = { disabled: ["a.patch"] }++ expect(() => assertPatchesDisabled(["a.patch"])).not.toThrow()+ })++ it("fails when the config opts out of a patch that was applied on import", () => {+ state[APPLIED] = { disabled: [] }++ expect(() => assertPatchesDisabled(["a.patch"])).toThrow(+ /MERCUR_DISABLED_PATCHES="a.patch"/+ )+ })+})diff --git a/packages/core/src/patches/__tests__/fixtures/core-flows-first.ts b/packages/core/src/patches/__tests__/fixtures/core-flows-first.tsnew file mode 100644index 000000000..0e9787a00--- /dev/null+++ b/packages/core/src/patches/__tests__/fixtures/core-flows-first.ts@@ -0,0 +1,14 @@+import { applyMercurPatches } from "../../index"++const hookTypes = () => {+ const coreFlows = require("@medusajs/core-flows")+ return [+ typeof coreFlows.capturePaymentWorkflow.hooks.paymentCaptured,+ typeof coreFlows.refundPaymentWorkflow.hooks.paymentRefunded,+ ]+}++const before = hookTypes()+applyMercurPatches({ logger: { info: () => {}, warn: () => {} } })++process.stdout.write(JSON.stringify({ before, after: hookTypes() }))diff --git a/packages/core/src/patches/__tests__/fixtures/core-imported-first.ts b/packages/core/src/patches/__tests__/fixtures/core-imported-first.tsnew file mode 100644index 000000000..9722925b9--- /dev/null+++ b/packages/core/src/patches/__tests__/fixtures/core-imported-first.ts@@ -0,0 +1,10 @@+import "../../../with-mercur"++const coreFlows = require("@medusajs/core-flows")++process.stdout.write(+ JSON.stringify([+ typeof coreFlows.capturePaymentWorkflow.hooks.paymentCaptured,+ typeof coreFlows.refundPaymentWorkflow.hooks.paymentRefunded,+ ])+)diff --git a/packages/core/src/patches/__tests__/load-order.unit.spec.ts b/packages/core/src/patches/__tests__/load-order.unit.spec.tsnew file mode 100644index 000000000..3b5d7cda2--- /dev/null+++ b/packages/core/src/patches/__tests__/load-order.unit.spec.ts@@ -0,0 +1,29 @@+import { execFileSync } from "child_process"+import { join } from "path"++// Jest resolves modules through its own registry and never reaches Node's+// loader, which is where the patches live, so each case runs in a real process.+const CORE_ROOT = join(__dirname, "..", "..", "..")++function run(fixture: string): unknown {+ const output = execFileSync(+ process.execPath,+ [require.resolve("tsx/cli"), join(__dirname, "fixtures", fixture)],+ { cwd: CORE_ROOT, encoding: "utf8", env: { ...process.env, NODE_ENV: "test" } }+ )+ // Importing `@mercurjs/core` logs each applied patch to stdout ahead of the result.+ return JSON.parse(output.trim().split("\n").pop()!)+}++describe("patch load order", () => {+ it("patches core-flows as a side effect of importing @mercurjs/core", () => {+ expect(run("core-imported-first.ts")).toEqual(["function", "function"])+ })++ it("reaches the package index when core-flows was loaded before patching", () => {+ expect(run("core-flows-first.ts")).toEqual({+ before: ["undefined", "undefined"],+ after: ["function", "function"],+ })+ })+})diff --git a/packages/core/src/patches/index.ts b/packages/core/src/patches/index.tsindex 001228296..798647942 100644--- a/packages/core/src/patches/index.ts+++ b/packages/core/src/patches/index.ts@@ -5,9 +5,8 @@ import { isPatchApplied, readPatchedFiles } from "./apply-patch"import {isAlreadyLoaded,isOverridden,- purgeFiles,registerOverrides,- reload,+ replaceLoaded,} from "./loader"import { PATCHES, type PatchEntry } from "./manifest"import { resolvePackageCopies, type PackageCopy } from "./resolve-package-dirs"@@ -19,9 +18,9 @@ import { isWithinRange } from "./version"// mutually incompatible, and none of them reach a marketplace that installed// `@mercurjs/core` into an existing Medusa app.//-// So the diffs live in `patches/` and are applied here, from `withMercur()`,-// which every project calls. They travel with the package version and arrive on-// a normal upgrade.+// So the diffs live in `patches/` and are applied as a side effect of importing+// `@mercurjs/core` (see `register.ts`). They travel with the package version and+// arrive on a normal upgrade.//// Patches are applied in memory, never written to `node_modules`: a boot has no// business mutating installed packages, workers would race doing it, and a file@@ -93,13 +92,12 @@ function applyToCopy(registerOverrides(copy.dir, patched, resolveFile)- // Something required these modules before `withMercur()` ran, so the cache- // holds their unpatched source. Evict them and compile the patched source in- // their place; a workflow module re-registers itself under the same id, which- // is what makes the patch take effect on an already-loaded package.+ // Something required these modules before `@mercurjs/core` was loaded, so the+ // cache holds their unpatched source. A workflow module re-registers itself+ // under the same id, which is what makes the patch take effect on an+ // already-loaded package.if (stale.length) {- purgeFiles(stale)- reload(copy.dir, stale)+ replaceLoaded(copy.dir, stale)}return true@@ -161,4 +159,53 @@ export function applyMercurPatches(options: ApplyPatchesOptions = {}): void {}}+// Keyed on the global symbol registry so that two installed copies of+// `@mercurjs/core` — common under bun and pnpm — patch the process only once.+const APPLIED = Symbol.for("@mercurjs/core/patches-applied")++type GlobalWithPatchState = typeof globalThis & {+ [APPLIED]?: { disabled: string[] }+}++export const DISABLED_PATCHES_ENV = "MERCUR_DISABLED_PATCHES"++export function disabledPatchesFromEnv(+ env: NodeJS.ProcessEnv = process.env+): string[] {+ return (env[DISABLED_PATCHES_ENV] ?? "")+ .split(",")+ .map((name) => name.trim())+ .filter(Boolean)+}++export function ensureMercurPatches(options: ApplyPatchesOptions = {}): void {+ const state = globalThis as GlobalWithPatchState+ if (state[APPLIED]) return++ applyMercurPatches(options)+ state[APPLIED] = { disabled: options.disabled ?? [] }+}++/**+ * Patches are applied when `@mercurjs/core` is imported, which is before+ * `withMercur()` can see its config. A patch listed only in the config was+ * therefore applied anyway; say so instead of letting the opt-out silently fail.+ */+export function assertPatchesDisabled(requested: string[] = []): void {+ const applied = (globalThis as GlobalWithPatchState)[APPLIED]+ if (!applied) return++ const missed = requested.filter((name) => !applied.disabled.includes(name))+ if (!missed.length) return++ throw new Error(+ `[mercur] projectConfig.mercur.disabledPatches lists ${missed+ .map((name) => `"${name}"`)+ .join(", ")}, but patches are applied when @mercurjs/core is imported, ` ++ `before the config is read. Set ${DISABLED_PATCHES_ENV}="${requested.join(+ ","+ )}" in the process environment instead.`+ )+}+export { PATCHES } from "./manifest"diff --git a/packages/core/src/patches/loader.ts b/packages/core/src/patches/loader.tsindex 2aa1b1825..6054b7e12 100644--- a/packages/core/src/patches/loader.ts+++ b/packages/core/src/patches/loader.ts@@ -70,9 +70,8 @@ export function registerOverrides(}}-// `withMercur()` runs from `medusa-config`, which is not always the first thing-// to pull in a target package — `@medusajs/test-utils` requires core-flows-// before it loads the config. A module already in the cache would keep its+// `@mercurjs/core` is not always the first thing to pull in a target package —+// `@medusajs/test-utils` requires core-flows before it loads the config. A module already in the cache would keep its// unpatched source forever, so the patched files are evicted and required again// through the override above.//@@ -130,6 +129,56 @@ export function reload(packageDir: string, absolutePaths: string[]): void {}}+/**+ * Evicts already-loaded files and compiles their patched source in place.+ *+ * Eviction alone does not reach code that required the package earlier: every+ * index above a patched file re-exports it through a getter over the evicted+ * module's `exports` object, so `require("@medusajs/core-flows")` keeps handing+ * out the unpatched workflow. Copying the fresh exports onto that stale object+ * is what makes the patch visible through the whole re-export chain.+ */+export function replaceLoaded(packageDir: string, absolutePaths: string[]): void {+ const previous = new Map<string, unknown>()+ for (const filename of absolutePaths) {+ previous.set(filename, require.cache[filename]?.exports)+ }++ purgeFiles(absolutePaths)+ reload(packageDir, absolutePaths)++ for (const [filename, stale] of previous) {+ const fresh: unknown = require.cache[filename]?.exports+ if (isObject(stale) && isObject(fresh) && stale !== fresh) {+ adoptExports(stale, fresh)+ }+ }+}++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null+}++function adoptExports(+ stale: Record<string, unknown>,+ fresh: Record<string, unknown>+): void {+ for (const key of Object.keys(fresh)) {+ const descriptor = Object.getOwnPropertyDescriptor(stale, key)++ if (!descriptor || descriptor.configurable) {+ Object.defineProperty(stale, key, {+ configurable: true,+ enumerable: true,+ writable: true,+ value: fresh[key],+ })+ } else if (descriptor.writable) {+ stale[key] = fresh[key]+ }+ }+}+// Resolved from the patched package, not from `@mercurjs/core`: bun and pnpm// give each dependent its own copy, and a `WorkflowManager` from a different// copy holds a different registry than the one `createWorkflow` writes to.diff --git a/packages/core/src/patches/register.ts b/packages/core/src/patches/register.tsnew file mode 100644index 000000000..de24c25d1--- /dev/null+++ b/packages/core/src/patches/register.ts@@ -0,0 +1,8 @@+import { disabledPatchesFromEnv, ensureMercurPatches } from "./index"++// A config's imports are evaluated before any call in it, so anything imported+// next to `@mercurjs/core` in `medusa-config.ts` loads before `withMercur()` runs.+// Patching has to happen here, on import: a workflow composed from unpatched+// source never gains the hooks a patch adds, so a block that registers a hook+// handler at import time would find it missing.+ensureMercurPatches({ disabled: disabledPatchesFromEnv() })diff --git a/packages/core/src/with-mercur.ts b/packages/core/src/with-mercur.tsindex 66017d440..dd5a76092 100644--- a/packages/core/src/with-mercur.ts+++ b/packages/core/src/with-mercur.ts@@ -1,6 +1,8 @@+import "./patches/register"+import type { InputConfigWithArrayModules } from "@medusajs/framework/types"import { defineConfig } from '@medusajs/framework/utils'-import { applyMercurPatches } from "./patches"+import { assertPatchesDisabled } from "./patches"import { disableMedusaMiddlewares } from "./utils/disable-medusa-middlewares"type HttpConfig = NonNullable<NonNullable<InputConfigWithArrayModules["projectConfig"]>["http"]>@@ -12,9 +14,10 @@ export type MercurInputConfig = Omit<InputConfigWithArrayModules, "projectConfig}mercur?: {/**- * Patch file names to skip, e.g. "@[email protected]".- * Each one restores an upstream bug, so only reach for this when a patch- * conflicts with your own override.+ * @deprecated Patches are applied when `@mercurjs/core` is imported,+ * before this config is read. Set `MERCUR_DISABLED_PATCHES` (comma+ * separated) in the process environment instead; listing a patch only+ * here fails the boot.*/disabledPatches?: string[]}@@ -22,14 +25,7 @@ export type MercurInputConfig = Omit<InputConfigWithArrayModules, "projectConfig}export function withMercur(config: MercurInputConfig = {}): InputConfigWithArrayModules {- // Before `disableMedusaMiddlewares`, which requires Medusa middleware modules- // that pull in `@medusajs/core-flows` transitively. Patches are compiled on- // first require, so anything that loads the targeted modules must run after- // this. Medusa itself imports core-flows lazily, well after `medusa-config`- // is evaluated, which is what leaves this window open at all.- applyMercurPatches({- disabled: config.projectConfig?.mercur?.disabledPatches,- })+ assertPatchesDisabled(config.projectConfig?.mercur?.disabledPatches)disableMedusaMiddlewares()const projectConfig = {diff --git a/packages/core/src/workflows/index.ts b/packages/core/src/workflows/index.tsindex 7630d8032..94e8d2724 100644--- a/packages/core/src/workflows/index.ts+++ b/packages/core/src/workflows/index.ts@@ -1,3 +1,5 @@+import "../patches/register"+export * from "./campaign"export * from "./customer-group"export * from "./commission"