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): derive cart shipping-method cleanup from offers, not products (#1455)
Viktor Holik01f723412f92
diff --git a/integration-tests/http/offer/cart/multi-seller-shipping-methods.spec.ts b/integration-tests/http/offer/cart/multi-seller-shipping-methods.spec.tsnew file mode 100644index 000000000..fbf701c19--- /dev/null+++ b/integration-tests/http/offer/cart/multi-seller-shipping-methods.spec.ts@@ -0,0 +1,350 @@+import {+ IRegionModuleService,+ ISalesChannelModuleService,+ MedusaContainer,+} from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MercurModules, SellerStatus } from "@mercurjs/types"++import {+ generatePublishableKey,+ generateStoreHeaders,+} from "../../../helpers/create-admin-user"+import { createCustomerUser } from "../../../helpers/create-customer-user"+import { createVendorProduct } from "../../../helpers/create-product"+import { createSellerUser } from "../../../helpers/create-seller-user"++const approveSeller = async (container: MedusaContainer, sellerId: string) => {+ const sellerModule: any = container.resolve(MercurModules.SELLER)+ await sellerModule.updateSellers({ id: sellerId, status: SellerStatus.OPEN })+}++jest.setTimeout(120000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api }) => {+ describe("Cart - multi-seller shipping methods", () => {+ let appContainer: MedusaContainer+ let storeHeaders: any+ let region: any+ let salesChannel: any+ let counter = 0++ const seedSeller = async (opts: {+ email: string+ name: string+ offerPrice: number+ existingProduct?: any+ }) => {+ const result = await createSellerUser(appContainer, {+ email: opts.email,+ name: opts.name,+ })+ await approveSeller(appContainer, (result.seller as any).id)+ const headers = result.headers+ const suffix = `_${opts.name}_${Date.now()}_${++counter}`++ const stockLocation = (+ await api.post(+ `/vendor/stock-locations`,+ { name: `Warehouse${suffix}` },+ headers+ )+ ).data.stock_location++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-sets`,+ { name: `FS${suffix}`, type: "shipping" },+ headers+ )+ const fulfillmentSet = (+ await api.get(+ `/vendor/stock-locations/${stockLocation.id}?fields=*fulfillment_sets`,+ headers+ )+ ).data.stock_location.fulfillment_sets[0]+ const serviceZone = (+ await api.post(+ `/vendor/fulfillment-sets/${fulfillmentSet.id}/service-zones`,+ {+ name: `SZ${suffix}`,+ geo_zones: [{ type: "country", country_code: "us" }],+ },+ headers+ )+ ).data.fulfillment_set.service_zones.find(+ (z: any) => z.name === `SZ${suffix}`+ )+ const shippingProfile = (+ await api.post(+ `/vendor/shipping-profiles`,+ { name: `SP${suffix}`, type: "default" },+ headers+ )+ ).data.shipping_profile++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-providers`,+ { add: ["manual_manual"] },+ headers+ )+ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,+ { add: [salesChannel.id] },+ headers+ )++ const shippingOption = (+ await api.post(+ `/vendor/shipping-options`,+ {+ name: `Ship${suffix}`,+ service_zone_id: serviceZone.id,+ shipping_profile_id: shippingProfile.id,+ provider_id: "manual_manual",+ price_type: "flat",+ type: {+ label: "Standard",+ description: "Standard shipping",+ code: "standard",+ },+ prices: [{ currency_code: "usd", amount: 500 }],+ rules: [+ {+ attribute: "enabled_in_store",+ value: "true",+ operator: "eq",+ },+ ],+ },+ headers+ )+ ).data.shipping_option++ const product =+ opts.existingProduct ??+ (await createVendorProduct(api, headers, {+ title: `Prod${suffix}`,+ sku: `V${suffix}`,+ }))++ if (!opts.existingProduct) {+ await api.post(+ `/vendor/sales-channels/${salesChannel.id}/products`,+ { add: [product.id] },+ headers+ )+ }++ const offer = (+ await api.post(+ `/vendor/offers`,+ {+ sku: `OF${suffix}`,+ variant_id: product.variants[0].id,+ shipping_profile_id: shippingProfile.id,+ inventory_items: [+ {+ title: `Inv${suffix}`,+ required_quantity: 1,+ stock_levels: [+ {+ location_id: stockLocation.id,+ stocked_quantity: 20,+ },+ ],+ },+ ],+ prices: [+ { amount: opts.offerPrice, currency_code: "usd" },+ ],+ },+ headers+ )+ ).data.offer++ return {+ sellerId: result.seller.id,+ headers,+ product,+ variant: product.variants[0],+ offer,+ shippingProfile,+ shippingOptionId: shippingOption.id as string,+ }+ }++ const addShippingMethod = async (+ cartId: string,+ optionId: string+ ) => {+ const res = await api.post(+ `/store/carts/${cartId}/shipping-methods`,+ { option_id: optionId },+ storeHeaders+ )+ return res.data.cart.shipping_methods as any[]+ }++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ const customerResult = await createCustomerUser(appContainer, {+ email: "[email protected]",+ first_name: "Multi",+ last_name: "Buyer",+ })++ const apiKey = await generatePublishableKey(appContainer)+ const baseStoreHeaders = generateStoreHeaders({+ publishableKey: apiKey,+ })+ storeHeaders = {+ headers: {+ ...baseStoreHeaders.headers,+ ...customerResult.headers.headers,+ },+ }++ const salesChannelModule =+ appContainer.resolve<ISalesChannelModuleService>(+ Modules.SALES_CHANNEL+ )+ salesChannel = await salesChannelModule.createSalesChannels({+ name: "Default Store",+ })++ const regionModule = appContainer.resolve<IRegionModuleService>(+ Modules.REGION+ )+ region = await regionModule.createRegions({+ name: "Test Region",+ currency_code: "usd",+ countries: ["us"],+ })++ const link = appContainer.resolve(ContainerRegistrationKeys.LINK)+ await link.create({+ [Modules.REGION]: { region_id: region.id },+ [Modules.PAYMENT]: {+ payment_provider_id: "pp_system_default",+ },+ })+ })++ it("keeps both sellers' shipping methods when a line's product is profile-linked to another seller", async () => {+ // Seller A first-offers the shared product, so the one-to-one+ // product↔shipping-profile link points at A's profile.+ const sellerA = await seedSeller({+ email: "[email protected]",+ name: "SellerA",+ offerPrice: 3000,+ })++ // Seller B undercuts A on that same product.+ const sellerB = await seedSeller({+ email: "[email protected]",+ name: "SellerB",+ offerPrice: 1000,+ existingProduct: sellerA.product,+ })++ // A second product, sold only by A, so the cart spans two sellers.+ const sellerAOther = await seedSeller({+ email: "[email protected]",+ name: "SellerAOther",+ offerPrice: 2000,+ })++ const cart = (+ await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ email: "[email protected]",+ shipping_address: {+ first_name: "Multi",+ last_name: "Buyer",+ address_1: "123 Main St",+ city: "New York",+ country_code: "us",+ postal_code: "10001",+ },+ billing_address: {+ first_name: "Multi",+ last_name: "Buyer",+ address_1: "123 Main St",+ city: "New York",+ country_code: "us",+ postal_code: "10001",+ },+ },+ storeHeaders+ )+ ).data.cart++ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: sellerB.offer.id, quantity: 1 },+ storeHeaders+ )+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: sellerAOther.offer.id, quantity: 1 },+ storeHeaders+ )++ const afterFirst = await addShippingMethod(+ cart.id,+ sellerB.shippingOptionId+ )+ expect(afterFirst).toHaveLength(1)++ // Adding the second seller's method triggers the refresh whose+ // orphan-profile cleanup used to delete B's method, because the+ // shared product is profile-linked to seller A.+ const afterSecond = await addShippingMethod(+ cart.id,+ sellerAOther.shippingOptionId+ )++ expect(afterSecond).toHaveLength(2)+ expect(+ afterSecond.map((m) => m.shipping_option_id).sort()+ ).toEqual(+ [+ sellerB.shippingOptionId,+ sellerAOther.shippingOptionId,+ ].sort()+ )++ const paymentCollection = (+ await api.post(+ `/store/payment-collections`,+ { cart_id: cart.id },+ storeHeaders+ )+ ).data.payment_collection+ await api.post(+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,+ { provider_id: "pp_system_default" },+ storeHeaders+ )++ const completeResp = await api.post(+ `/store/carts/${cart.id}/complete`,+ {},+ storeHeaders+ )++ expect(completeResp.status).toEqual(200)+ expect(completeResp.data.type).toEqual("order_group")+ })+ })+ },+})diff --git a/integration-tests/jest.config.js b/integration-tests/jest.config.jsindex b084c632e..952ff7db5 100644--- a/integration-tests/jest.config.js+++ b/integration-tests/jest.config.js@@ -1,8 +1,15 @@+const path = require("path")+const { loadEnv } = require("@medusajs/framework/utils")loadEnv("test", process.cwd())module.exports = {transform: {+ // Mercur patches two shipped core-flows files. Jest never consults Node's+ // module hooks, so without this the patches are inert under test and the+ // suite silently exercises unpatched code.+ "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/]cart[\\\\/].*\\.js$":+ "@mercurjs/core/patches/jest-transformer","^.+\\.[jt]s$": ["@swc/jest",{@@ -14,12 +21,17 @@ module.exports = {],},testEnvironment: "node",+ // Everything in node_modules is left untransformed except the core-flows cart+ // files the patches target.+ transformIgnorePatterns: [+ "/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/]cart[\\\\/])",+ ],moduleFileExtensions: ["js", "ts", "json"],modulePathIgnorePatterns: ["dist/"],- setupFiles: ["./setup.js"],+ setupFiles: [path.join(__dirname, "setup.js")],// Balance `--shard` partitions by estimated duration instead of file count// so heavy specs don't cluster in one shard and blow the job timeout.- testSequencer: "./test-sequencer.js",+ testSequencer: path.join(__dirname, "test-sequencer.js"),}if (process.env.TEST_TYPE === "integration:http") {@@ -34,5 +46,10 @@ if (process.env.TEST_TYPE === "integration:http") {} else if (process.env.TEST_TYPE === "integration:modules") {module.exports.testMatch = ["**/src/modules/*/__tests__/**/*.[jt]s"]} else if (process.env.TEST_TYPE === "unit") {- module.exports.testMatch = ["**/src/**/__tests__/**/*.unit.spec.[jt]s"]+ // Unit specs live next to the source they cover, in the workspace packages+ // rather than here, so the run is rooted at the repo.+ module.exports.rootDir = path.join(__dirname, "..")+ module.exports.testMatch = [+ "**/packages/core/src/**/__tests__/**/*.unit.spec.[jt]s",+ ]}\ No newline at end of filediff --git a/integration-tests/package.json b/integration-tests/package.jsonindex fc7ff26e5..e6b9169cf 100644--- a/integration-tests/package.json+++ b/integration-tests/package.json@@ -3,6 +3,7 @@"version": "0.0.1","private": true,"scripts": {+ "test:unit": "TEST_TYPE=unit jest --rootDir .. --silent=false","test:integration:http": "TEST_TYPE=integration:http NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit","test:integration:meilisearch": "TEST_TYPE=integration:http MEILISEARCH_HOST=http://localhost:7700 MEILISEARCH_API_KEY=masterKey NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit --testPathPattern=meilisearch"},diff --git a/package.json b/package.jsonindex ddf5ba6f2..694c82825 100644--- a/package.json+++ b/package.json@@ -5,6 +5,7 @@"build": "turbo run build","dev": "turbo run dev","lint": "oxlint --quiet",+ "test:unit": "cd integration-tests && bun run test:unit","test:integration:http": "cd integration-tests && bun run test:integration:http"},"dependencies": {diff --git a/packages/core/package.json b/packages/core/package.jsonindex effa1bad3..35a6c899e 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -47,9 +47,10 @@"medusa-v2"],"scripts": {- "build": "bun ./node_modules/@mercurjs/cli/dist/index.js codegen && rm -rf .medusa && tsc --declaration --outDir .medusa/server",+ "build": "bun ./node_modules/@mercurjs/cli/dist/index.js codegen && rm -rf .medusa && tsc --declaration --outDir .medusa/server && bun run copy:patches",+ "copy:patches": "mkdir -p .medusa/server/src/patches/patches && cp src/patches/patches/*.patch .medusa/server/src/patches/patches/","dev": "medusa plugin:develop",- "prepublishOnly": "tsc --declaration --outDir .medusa/server"+ "prepublishOnly": "tsc --declaration --outDir .medusa/server && bun run copy:patches"},"devDependencies": {"cors": "^2.8.5",diff --git a/packages/core/src/patches/README.md b/packages/core/src/patches/README.mdnew file mode 100644index 000000000..2cb4d7034--- /dev/null+++ b/packages/core/src/patches/README.md@@ -0,0 +1,127 @@+# patches++Unified diffs against Medusa internals that expose no hook, applied at boot.++Shipping these through a package manager is not an option: `templates/basic`+supports bun, yarn, pnpm and npm, whose patch mechanisms are mutually+incompatible (`patchedDependencies` / the `patch:` protocol / `patchedDependencies`+/ 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.++## How they are applied++**In memory, never to disk.** A server boot has no business mutating installed+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 on+first require.++`withMercur()` 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 its+unpatched source. Those files (only those files, never the whole package) are+evicted and required again through the hook. A workflow module re-registers+itself under the same id on that second load, and since the reload replays the+same source, replacing the previous definition is the correct outcome: Medusa's+duplicate guard is relaxed for the duration of the reload, because generated step+ids make a second load of the same file compare unequal to the first.++That covers Node's module loader. Jest has its own: it loads modules through its+own registry and never consults `Module._extensions`, so neither the override nor+the eviction above can fire under test. Left at that, the patches are silently+inert in every suite while the runtime still reports them applied — tests would+exercise different code than production, which is worse than not patching at all.++`jest-transformer.ts` closes that gap by applying the same diff at transform+time. Register it ahead of the project transform and let the targeted files+through `transformIgnorePatterns` (see `integration-tests/jest.config.js`):++```js+transform: {+ "node_modules[\\/].*core-flows[\\/]dist[\\/]cart[\\/].*\\.js$":+ "@mercurjs/core/patches/jest-transformer",+ "^.+\\.[jt]s$": ["@swc/jest", { /* ... */ }],+},+transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\/]dist[\\/]cart[\\/])"],+```++Both paths funnel through `patchSourceForPath`, so a patch means the same thing+in either environment, and `jest-transformer.unit.spec.ts` fails if the test+environment ever stops seeing patched sources. **Any other runner with its own+module registry — vitest, some bundlers — needs the same treatment, or the+patches will not apply there.**++Because nothing is written, a patch that a user *also* applied through their own+package manager is detected and skipped rather than treated as a conflict.++## Lifecycle++- **already applied** — every hunk reverses cleanly, so the patch is skipped.+ Someone may have applied the same diff through their own package manager.+- **stale** — a hunk no longer matches its context: boot fails, naming the patch+ and the bug that skipping it would restore.+- **out of range** — the copy this project resolves is outside the patch's+ `compatible` range: boot fails with the installed version. Incidental copies in+ a shared package-manager store are skipped rather than fatal.+- **applied** — one log line per patch, with the number of copies touched.++The diff's own context is the real guard: if upstream moves the code, the hunk+stops matching and boot fails with the patch name and the bug it corrects. The+`compatible` range in `manifest.ts` only turns a known-incompatible bump into a+clearer message than a failed hunk.++## Adding a patch++1. Copy the target package's file out of `node_modules`, edit it, and+ `git diff --no-index` the pair. Paths in the patch are relative to the package+ root (`dist/...`).+2. Name the file `<package>@<version-generated-from>.patch`, with `/` in the+ package name written as `+`.+3. Add an entry to `PATCHES` in `manifest.ts`.+4. Mark each hunk with a `// MERCUR:` comment saying *why*. Someone reading the+ patched file in `node_modules` while debugging needs that.++`bun run test:unit` covers every patch in the manifest: that it still applies to+each in-range copy, that it reverses cleanly, and that a drifted context is+refused rather than relocated. That suite is the drift gate — run it on every+Medusa bump.++Keep patches small. A large one means the change belongs in a Mercur workflow or+upstream in Medusa, not here.++## Escape hatch++```ts+withMercur({+ projectConfig: {+ mercur: { disabledPatches: ["@[email protected]"] },+ },+})+```++Skipping a patch restores the upstream bug it corrects; the reason is logged.++## Current patches++- **`@[email protected]`** — disables the orphan-profile cleanup in+ `refreshCartShippingMethodsWorkflow`. Upstream deletes a shipping method whose+ profile is not required by any cart item, deriving that set from each item's+ master product; in Mercur the shipping profile belongs to the offer (the+ product link is one-to-one and the first offerer wins it), so in a+ multi-seller cart holding a co-sold product every other seller's method is+ judged orphaned and checkout fails. See+ https://github.com/mercurjs/mercur/issues/1442.++ The cleanup is disabled rather than re-derived from the offer because the+ offer is not present on the cart this workflow receives: `refreshCartItems`+ refetches with a field list it captured by reference at module-load time, so+ adding a field to that list no longer reaches the already-composed workflow.++ **Consequence:** a genuinely orphaned method now survives — remove a seller's+ last item and their shipping method stays on the cart. Dropping it belongs to+ Mercur's own cart flows.++Removable once the equivalent fix lands upstream in Medusa.diff --git a/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts b/packages/core/src/patches/__tests__/jest-transformer.unit.spec.tsnew file mode 100644index 000000000..b32fb9528--- /dev/null+++ b/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts@@ -0,0 +1,56 @@+import { readFileSync } from "fs"+import { join } from "path"++import { process as transform } from "../jest-transformer"+import { PATCHES } from "../manifest"+import { resolvePackageCopies } from "../resolve-package-dirs"+import { parseUnifiedDiff } from "../unified-diff"+import { isWithinRange } from "../version"++// Jest loads modules through its own registry and never consults Node's module+// hooks, so the runtime patch mechanism cannot fire here. Without the+// transformer every suite exercises unpatched Medusa code while the runtime+// reports the patch as applied.+describe("jest transformer", () => {+ const entry = PATCHES.find(+ (patch) => patch.package === "@medusajs/core-flows"+ )!++ const copy = () =>+ resolvePackageCopies(entry.package).find(+ (candidate) =>+ candidate.version &&+ isWithinRange(candidate.version, entry.compatible)+ )!++ it("serves patched source for every file the patch targets", () => {+ const patchFilePath = join(__dirname, "..", "patches", entry.file)+ const files = parseUnifiedDiff(readFileSync(patchFilePath, "utf8"))++ expect(files.length).toBeGreaterThan(0)++ for (const file of files) {+ const sourcePath = join(copy().dir, file.path)+ const original = readFileSync(sourcePath, "utf8")+ const { code } = transform(original, sourcePath)++ expect(code).not.toEqual(original)+ expect(code).toContain("MERCUR:")+ }+ })++ it("disables the orphan-profile cleanup that deletes co-sold sellers' methods", () => {+ const sourcePath = join(+ copy().dir,+ "dist/cart/workflows/refresh-cart-shipping-methods.js"+ )+ const { code } = transform(readFileSync(sourcePath, "utf8"), sourcePath)++ expect(code).toContain("const shouldCleanupOrphanProfiles = false")+ })++ it("leaves files it does not target untouched", () => {+ const source = "module.exports = 1\n"+ expect(transform(source, "/tmp/somewhere/else.js").code).toEqual(source)+ })+})diff --git a/packages/core/src/patches/__tests__/patches.unit.spec.ts b/packages/core/src/patches/__tests__/patches.unit.spec.tsnew file mode 100644index 000000000..484afc9a3--- /dev/null+++ b/packages/core/src/patches/__tests__/patches.unit.spec.ts@@ -0,0 +1,79 @@+import { existsSync, readFileSync } from "fs"+import { join } from "path"++import { isPatchApplied, readPatchedFiles } from "../apply-patch"+import { PATCHES } from "../manifest"+import { resolvePackageCopies } from "../resolve-package-dirs"+import { applyHunks, parseUnifiedDiff, reverse } from "../unified-diff"+import { isWithinRange } from "../version"++const PATCH_DIR = join(__dirname, "..", "patches")++describe("patches", () => {+ describe.each(PATCHES)("$file", (entry) => {+ const patchFilePath = join(PATCH_DIR, entry.file)++ it("ships the patch file the manifest points at", () => {+ expect(existsSync(patchFilePath)).toBe(true)+ })++ // The whole point of a patch is that it stops matching when upstream+ // moves. This is the gate that turns that into a CI failure rather than+ // a boot failure in someone's marketplace.+ // Package-manager stores are shared between checkouts, so a sweep also+ // turns up versions this project never loads. Only the copy the project+ // resolves has to accept the patch.+ const inRange = () =>+ resolvePackageCopies(entry.package).filter(+ (copy) =>+ copy.version && isWithinRange(copy.version, entry.compatible)+ )++ it("applies to every in-range copy of the target package", () => {+ const copies = inRange()+ expect(copies.length).toBeGreaterThan(0)++ for (const copy of copies) {+ expect(readPatchedFiles(copy.dir, patchFilePath)).not.toBeNull()+ }+ })++ it("is not reported as already applied against pristine sources", () => {+ for (const copy of inRange()) {+ expect(isPatchApplied(copy.dir, patchFilePath)).toBe(false)+ }+ })++ it("reverses cleanly once applied", () => {+ const files = parseUnifiedDiff(readFileSync(patchFilePath, "utf8"))++ for (const copy of inRange()) {+ for (const file of files) {+ const source = readFileSync(join(copy.dir, file.path), "utf8")+ const patched = applyHunks(source, file.hunks)++ expect(patched).not.toBeNull()+ expect(applyHunks(patched as string, reverse(file.hunks))).toEqual(+ source+ )+ }+ }+ })++ it("refuses to apply when the surrounding context has moved", () => {+ const files = parseUnifiedDiff(readFileSync(patchFilePath, "utf8"))+ const [copy] = inRange()++ for (const file of files) {+ const source = readFileSync(join(copy.dir, file.path), "utf8")+ const contextLine = file.hunks[0].before.find((line) => line.trim())!+ const drifted = source.replace(+ contextLine,+ `${contextLine} /* upstream moved */`+ )++ expect(applyHunks(drifted, file.hunks)).toBeNull()+ }+ })+ })+})diff --git a/packages/core/src/patches/apply-patch.ts b/packages/core/src/patches/apply-patch.tsnew file mode 100644index 000000000..bdcb52ac7--- /dev/null+++ b/packages/core/src/patches/apply-patch.ts@@ -0,0 +1,93 @@+import { existsSync, readFileSync } from "fs"+import { join, sep } from "path"++import { PATCHES } from "./manifest"+import { applyHunks, parseUnifiedDiff, reverse } from "./unified-diff"++export type PatchedFile = {+ /** Path of the patched file relative to the package root. */+ relativePath: string+ source: string+}++/**+ * Reads every file a patch touches and returns their patched source. Nothing is+ * written to disk — the results are handed to the module loader hook, which+ * compiles them in place of the originals.+ *+ * Returns `null` when a hunk does not apply, which is the signal that upstream+ * has moved and the patch must be regenerated.+ */+export function readPatchedFiles(+ packageDir: string,+ patchFilePath: string+): PatchedFile[] | null {+ const files = parseUnifiedDiff(readFileSync(patchFilePath, "utf8"))+ const patched: PatchedFile[] = []++ for (const file of files) {+ const filePath = join(packageDir, file.path)+ if (!existsSync(filePath)) return null++ const result = applyHunks(readFileSync(filePath, "utf8"), file.hunks)+ if (result === null) return null++ patched.push({ relativePath: file.path, source: result })+ }++ return patched.length ? patched : null+}++/**+ * True when every hunk reverses cleanly, meaning the patch is already present —+ * the equivalent of `git apply --reverse --check`. Someone may have applied the+ * same diff through their own package manager, which is a supported outcome+ * rather than a conflict.+ */+export function isPatchApplied(+ packageDir: string,+ patchFilePath: string+): boolean {+ const files = parseUnifiedDiff(readFileSync(patchFilePath, "utf8"))++ for (const file of files) {+ const filePath = join(packageDir, file.path)+ if (!existsSync(filePath)) return false++ const source = readFileSync(filePath, "utf8")+ if (applyHunks(source, reverse(file.hunks)) === null) return false+ }++ return true+}++/**+ * Applies whichever patch targets `absolutePath`, if any, returning the patched+ * source or `null` when the file is not a patch target.+ *+ * This is the loader-agnostic half of the system: Node's require hook and the+ * Jest transformer both funnel through it, so a patch means the same thing in+ * production and under test.+ */+export function patchSourceForPath(+ absolutePath: string,+ source: string+): string | null {+ const normalized = absolutePath.split(sep).join("/")++ for (const entry of PATCHES) {+ const patchFilePath = join(__dirname, "patches", entry.file)+ if (!existsSync(patchFilePath)) continue++ for (const file of parseUnifiedDiff(readFileSync(patchFilePath, "utf8"))) {+ const suffix = `${entry.package}/${file.path}`+ if (!normalized.endsWith(suffix)) continue++ // Already patched (a package-manager patch, or a second pass): the+ // forward hunks will not match, and that is not an error.+ return applyHunks(source, file.hunks)+ }+ }++ return null+}diff --git a/packages/core/src/patches/index.ts b/packages/core/src/patches/index.tsnew file mode 100644index 000000000..2220fcc45--- /dev/null+++ b/packages/core/src/patches/index.ts@@ -0,0 +1,156 @@+import { existsSync, realpathSync } from "fs"+import { join } from "path"++import { isPatchApplied, readPatchedFiles } from "./apply-patch"+import {+ isAlreadyLoaded,+ isOverridden,+ purgeFiles,+ registerOverrides,+ reload,+} from "./loader"+import { PATCHES, type PatchEntry } from "./manifest"+import { resolvePackageCopies, type PackageCopy } from "./resolve-package-dirs"+import { isWithinRange } from "./version"++// Mercur has to correct a handful of Medusa internals that expose no hook.+// Shipping those corrections through a package manager is not an option:+// `templates/basic` supports bun, yarn, pnpm and npm, whose patch mechanisms are+// 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.+//+// 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+// that has already been required cannot be un-required cleanly.++const PATCH_DIR = join(__dirname, "patches")++export type ApplyPatchesOptions = {+ /** Patch file names to skip, for adopters who need to opt out of one. */+ disabled?: string[]+ logger?: Pick<Console, "info" | "warn">+}++function fail(entry: PatchEntry, copy: PackageCopy, detail: string): never {+ throw new Error(+ `[mercur] Patch "${entry.file}" ${detail} ` ++ `(${entry.package}@${copy.version ?? "unknown"}, ${copy.dir}).\n` ++ `It corrects: ${entry.reason}\n` ++ `Regenerate the patch for the installed version, or skip it via ` ++ `projectConfig.mercur.disabledPatches — skipping restores the bug above.`+ )+}++function resolveFile(packageDir: string, relativePath: string): string {+ const filePath = join(packageDir, relativePath)+ try {+ return realpathSync(filePath)+ } catch {+ return filePath+ }+}++/**+ * Returns true when the copy was patched. A non-primary copy that does not+ * match is skipped rather than fatal: package-manager stores are shared between+ * checkouts, so a sweep turns up versions this project never loads.+ */+function applyToCopy(+ entry: PatchEntry,+ copy: PackageCopy,+ patchFilePath: string+): boolean {+ if (copy.version && !isWithinRange(copy.version, entry.compatible)) {+ if (!copy.primary) return false+ fail(+ entry,+ copy,+ `was generated against ${entry.package} >=${entry.compatible.from} ` ++ `<${entry.compatible.to}, but ${copy.version} is what this project resolves`+ )+ }++ // Someone may have applied the same diff through their package manager. That+ // is a supported outcome, not a conflict.+ if (isPatchApplied(copy.dir, patchFilePath)) {+ return true+ }++ const patched = readPatchedFiles(copy.dir, patchFilePath)+ if (!patched) {+ if (!copy.primary) return false+ fail(entry, copy, "no longer applies — its context has changed upstream")+ }++ const paths = patched.map((file) => resolveFile(copy.dir, file.relativePath))+ const stale = paths.filter(+ (path) => isAlreadyLoaded(path) && !isOverridden(path)+ )++ 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.+ if (stale.length) {+ purgeFiles(stale)+ reload(copy.dir, stale)+ }++ return true+}++export function applyMercurPatches(options: ApplyPatchesOptions = {}): void {+ const disabled = new Set(options.disabled ?? [])+ const logger = options.logger ?? console++ for (const entry of PATCHES) {+ if (disabled.has(entry.file)) {+ logger.warn(+ `[mercur] Skipping patch "${entry.file}" (disabled). This restores the ` ++ `upstream behaviour it corrects: ${entry.reason}`+ )+ continue+ }++ const patchFilePath = join(PATCH_DIR, entry.file)+ if (!existsSync(patchFilePath)) {+ throw new Error(`[mercur] Patch file is missing: ${patchFilePath}`)+ }++ const copies = resolvePackageCopies(entry.package)+ if (!copies.length) {+ throw new Error(+ `[mercur] Patch "${entry.file}" found no installed copy of ${entry.package}.`+ )+ }++ const patchedCount = copies.filter((copy) =>+ applyToCopy(entry, copy, patchFilePath)+ ).length++ if (!patchedCount) {+ throw new Error(+ `[mercur] Patch "${entry.file}" matched no installed copy of ` ++ `${entry.package}. It corrects: ${entry.reason}`+ )+ }++ logger.info(+ `[mercur] Applied patch "${entry.file}" to ${patchedCount} copy/copies of ` ++ `${entry.package}`+ )++ // Load the patched package now rather than leaving it to Medusa: the+ // override only bites on first require, so failing here keeps the failure+ // next to the patch that caused it.+ require(entry.package)+ }+}++export { PATCHES } from "./manifest"diff --git a/packages/core/src/patches/jest-transformer.ts b/packages/core/src/patches/jest-transformer.tsnew file mode 100644index 000000000..80bef310c--- /dev/null+++ b/packages/core/src/patches/jest-transformer.ts@@ -0,0 +1,59 @@+import { createHash } from "crypto"+import { existsSync, readFileSync } from "fs"+import { join } from "path"++import { patchSourceForPath } from "./apply-patch"+import { PATCHES } from "./manifest"++// Jest loads modules through its own registry and never consults Node's+// `Module._extensions`, so the require hook that applies these patches at+// runtime cannot fire under test. Without this transformer the patches would be+// silently inert in every test suite — production and tests would disagree+// about what the code does, which is worse than not patching at all.+//+// Register it ahead of the project's own transform, and let the two patched+// files through `transformIgnorePatterns`:+//+// transform: {+// "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/]cart[\\\\/].*\\.js$":+// "@mercurjs/core/patches/jest-transformer",+// "^.+\\.[jt]s$": ["@swc/jest", { ... }],+// },+// transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/]cart[\\\\/])"],++type TransformOutput = { code: string }++function patchesFingerprint(): string {+ const hash = createHash("sha1")++ for (const entry of PATCHES) {+ const patchFilePath = join(__dirname, "patches", entry.file)+ hash.update(entry.file)+ if (existsSync(patchFilePath)) {+ hash.update(readFileSync(patchFilePath))+ }+ }++ return hash.digest("hex")+}++export function process(+ sourceText: string,+ sourcePath: string+): TransformOutput {+ return { code: patchSourceForPath(sourcePath, sourceText) ?? sourceText }+}++/**+ * Editing a patch has to invalidate Jest's transform cache, or a stale entry+ * serves the unpatched source and the suite quietly tests the wrong code.+ */+export function getCacheKey(sourceText: string, sourcePath: string): string {+ return createHash("sha1")+ .update(sourceText)+ .update(sourcePath)+ .update(patchesFingerprint())+ .digest("hex")+}++export default { process, getCacheKey }diff --git a/packages/core/src/patches/loader.ts b/packages/core/src/patches/loader.tsnew file mode 100644index 000000000..2aa1b1825--- /dev/null+++ b/packages/core/src/patches/loader.ts@@ -0,0 +1,147 @@+import Module from "module"+import { join } from "path"++import type { PatchedFile } from "./apply-patch"++type CompilableModule = { _compile(source: string, filename: string): unknown }+type LoaderExtension = (module: CompilableModule, filename: string) => void+type ModuleInternals = {+ _extensions: Record<string, LoaderExtension>+}++const internals = Module as unknown as ModuleInternals++/** Absolute file path -> patched source, consulted on every `.js` load. */+const overrides = new Map<string, string>()++/** Paths whose patched source was actually compiled, not merely registered. */+const compiled = new Set<string>()++let installed = false++// Patches are applied in memory rather than written to `node_modules`: a server+// boot has no business mutating installed packages, workers would race each+// other doing it, and a file already required cannot be un-required cleanly.+// Intercepting the loader keeps the change scoped to this process.+function install(): void {+ if (installed) return++ const original = internals._extensions[".js"]++ internals._extensions[".js"] = function (module, filename) {+ const patched = overrides.get(filename)+ if (patched !== undefined) {+ module._compile(patched, filename)+ compiled.add(filename)+ return+ }+ original(module, filename)+ }++ installed = true+}++/**+ * Files whose patched source was compiled in place of the original. Registering+ * an override only takes effect if the module is required afterwards, so this+ * is the difference between a patch being staged and a patch being live.+ */+export function compiledPaths(): string[] {+ return [...compiled]+}++export function isAlreadyLoaded(absolutePath: string): boolean {+ return Object.prototype.hasOwnProperty.call(require.cache, absolutePath)+}++export function isOverridden(absolutePath: string): boolean {+ return overrides.has(absolutePath)+}++export function registerOverrides(+ packageDir: string,+ files: PatchedFile[],+ resolve: (packageDir: string, relativePath: string) => string+): void {+ install()++ for (const file of files) {+ overrides.set(resolve(packageDir, file.relativePath), file.source)+ }+}++// `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+// unpatched source forever, so the patched files are evicted and required again+// through the override above.+//+// Only the patched files are dropped, never the whole package: re-running an+// arbitrary core-flows module re-enters `createWorkflow`, and workflows whose+// step ids are generated rather than literal do not survive a second+// registration ("step definition already exists").+export function purgeFiles(absolutePaths: string[]): void {+ for (const filename of absolutePaths) {+ const cached = require.cache[filename]+ if (!cached) continue++ delete require.cache[filename]++ // Parents keep `children` arrays pointing at the evicted module; leaving it+ // there keeps the stale exports reachable through the module graph.+ for (const parent of Object.values(require.cache)) {+ const index = parent?.children?.indexOf(cached) ?? -1+ if (index !== -1) parent!.children.splice(index, 1)+ }+ }+}++type WorkflowManagerLike = {+ register: (workflowId: string, ...rest: unknown[]) => unknown+ unregister: (workflowId: string) => unknown+}++/**+ * Compiles the patched sources now, so the override is what the process holds.+ *+ * Re-running a module that calls `createWorkflow` hits Medusa's duplicate guard,+ * which only lets a workflow re-register when its step definition is byte-equal+ * — and step ids are generated, so a second load of the same file is not. The+ * reload replays the same source, so replacing the previous definition is the+ * correct outcome; `register` is swapped for the duration to say so.+ */+export function reload(packageDir: string, absolutePaths: string[]): void {+ const manager = loadWorkflowManager(packageDir)+ const original = manager?.register++ if (manager && original) {+ manager.register = function register(workflowId, ...rest) {+ manager.unregister(workflowId)+ return original.call(this, workflowId, ...rest)+ }+ }++ try {+ for (const filename of absolutePaths) {+ require(filename)+ }+ } finally {+ if (manager && original) manager.register = original+ }+}++// 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.+function loadWorkflowManager(packageDir: string): WorkflowManagerLike | null {+ try {+ const requireFrom = Module.createRequire(join(packageDir, "index.js"))+ return (+ requireFrom("@medusajs/orchestration") as {+ WorkflowManager: WorkflowManagerLike+ }+ ).WorkflowManager+ } catch {+ return null+ }+}diff --git a/packages/core/src/patches/manifest.ts b/packages/core/src/patches/manifest.tsnew file mode 100644index 000000000..9ebf2a8e8--- /dev/null+++ b/packages/core/src/patches/manifest.ts@@ -0,0 +1,30 @@+export interface PatchEntry {+ /** Patch file under `patches/`, named `<package>@<generated-from-version>.patch`. */+ file: string+ package: string+ /**+ * Versions the patch is allowed to be attempted against. Applying is still+ * gated on the diff's own context matching — this range only produces a+ * clearer error than a failed hunk when a bump is known to be incompatible.+ */+ compatible: { from: string; to: string }+ /** Surfaced in boot logs and in the error raised when the patch stops applying. */+ reason: string+}++export const PATCHES: PatchEntry[] = [+ {+ file: "@[email protected]",+ package: "@medusajs/core-flows",+ // Both targeted files are byte-identical in 2.17.2 and 2.18.0.+ compatible: { from: "2.17.0", to: "2.19.0" },+ reason:+ "refreshCartShippingMethodsWorkflow deletes any shipping method whose " ++ "profile is not required by a cart item, deriving that set from each " ++ "item's master product. In Mercur the profile belongs to the offer — the " ++ "product link is one-to-one and the first offerer wins it — so in a " ++ "multi-seller cart holding a co-sold product every other seller's method " ++ "is judged orphaned and checkout fails. The patch disables that cleanup. " ++ "See mercurjs/mercur#1442.",+ },+]diff --git a/packages/core/src/patches/patches/@[email protected] b/packages/core/src/patches/patches/@[email protected]new file mode 100644index 000000000..a19dc0e2b--- /dev/null+++ b/packages/core/src/patches/patches/@[email protected]@@ -0,0 +1,21 @@+diff --git a/dist/cart/workflows/refresh-cart-shipping-methods.js b/dist/cart/workflows/refresh-cart-shipping-methods.js+index 74e27fb..016edc9 100644+--- a/dist/cart/workflows/refresh-cart-shipping-methods.js++++ b/dist/cart/workflows/refresh-cart-shipping-methods.js+@@ -107,7 +107,15 @@ exports.refreshCartShippingMethodsWorkflow = (0, workflows_sdk_1.createWorkflow)+ // Collect profile IDs still required by remaining cart items so that+ // shipping methods for profiles with no matching items can be dropped.+ // Avoid clearing shipping methods for single-method carts.+- const shouldCleanupOrphanProfiles = shippingMethods.length > 1;++ // MERCUR: upstream drops a shipping method whose profile is not++ // required by any cart item, deriving that set from each item's++ // master product. Mercur's shipping profile belongs to the offer:++ // the product link is one-to-one and the first offerer wins it, so++ // in a multi-seller cart holding a co-sold product every other++ // seller's method is judged orphaned and checkout fails. The++ // cleanup is disabled rather than re-derived because the offer is++ // not on the cart this workflow is handed.++ const shouldCleanupOrphanProfiles = false;+ const requiredProfileIds = new Set(items+ .filter((item) => item.requires_shipping)+ .map((item) => item.variant?.product?.shipping_profile?.id)diff --git a/packages/core/src/patches/resolve-package-dirs.ts b/packages/core/src/patches/resolve-package-dirs.tsnew file mode 100644index 000000000..00ca6c0a1--- /dev/null+++ b/packages/core/src/patches/resolve-package-dirs.ts@@ -0,0 +1,96 @@+import { existsSync, readdirSync, readFileSync, realpathSync } from "fs"+import { dirname, join } from "path"+import pkgDir from "pkg-dir"+import resolveCwd from "resolve-cwd"++// A dependency can be present many times in one install, and where the copies+// live depends on the package manager: bun stores them under `node_modules/+// .bun/<name>@<ver>+<hash>/`, pnpm under `node_modules/.pnpm/<name>@<ver>/`,+// npm and yarn hoist to the nearest `node_modules` or nest per-dependency.+// `templates/basic` supports all four, so patching has to find every copy+// rather than assume a layout.+//+// Those stores are shared across checkouts, so a sweep also turns up copies at+// versions this project never loads. Only the copy the project itself resolves+// is required to accept a patch; the rest are patched opportunistically.++export type PackageCopy = {+ dir: string+ version: string | null+ /** The copy `require()` resolves from the project — the one that must work. */+ primary: boolean+}++function readVersion(dir: string): string | null {+ try {+ const raw = readFileSync(join(dir, "package.json"), "utf8")+ return (JSON.parse(raw) as { version?: string }).version ?? null+ } catch {+ return null+ }+}++function canonical(dir: string): string {+ try {+ return realpathSync(dir)+ } catch {+ return dir+ }+}++function sweepStore(+ storeDir: string,+ packageName: string,+ found: Set<string>+): void {+ if (!existsSync(storeDir)) return++ const prefix = `${packageName.replace("/", "+")}@`+ for (const entry of readdirSync(storeDir)) {+ if (!entry.startsWith(prefix)) continue+ const inner = join(storeDir, entry, "node_modules", ...packageName.split("/"))+ if (existsSync(join(inner, "package.json"))) found.add(canonical(inner))+ }+}++export function resolvePackageCopies(packageName: string): PackageCopy[] {+ let primary: string | null = null++ // Resolve the package entry point, not `<name>/package.json`: packages that+ // declare `exports` without a `./package.json` entry — core-flows is one —+ // make the subpath unresolvable, which would silently leave every copy+ // non-primary and drop the guarantee that the copy this project loads is the+ // one that must accept the patch.+ try {+ const entry = resolveCwd(packageName)+ const resolved = pkgDir.sync(dirname(entry))+ if (resolved) primary = canonical(resolved)+ } catch {+ // Not resolvable from cwd; the sweeps below may still find copies.+ }++ const found = new Set<string>()+ if (primary) found.add(primary)++ let cursor = process.cwd()+ while (true) {+ const nodeModules = join(cursor, "node_modules")+ if (existsSync(nodeModules)) {+ sweepStore(join(nodeModules, ".bun"), packageName, found)+ sweepStore(join(nodeModules, ".pnpm"), packageName, found)++ const hoisted = join(nodeModules, ...packageName.split("/"))+ if (existsSync(join(hoisted, "package.json"))) found.add(canonical(hoisted))+ }++ const parent = dirname(cursor)+ if (parent === cursor) break+ cursor = parent+ }++ return [...found].map((dir) => ({+ dir,+ version: readVersion(dir),+ primary: dir === primary,+ }))+}diff --git a/packages/core/src/patches/unified-diff.ts b/packages/core/src/patches/unified-diff.tsnew file mode 100644index 000000000..b24b999ac--- /dev/null+++ b/packages/core/src/patches/unified-diff.ts@@ -0,0 +1,150 @@+export type Hunk = {+ /** Context + removed lines: what the file must contain for the hunk to apply. */+ before: string[]+ /** Context + added lines: what replaces it. */+ after: string[]+ /** 1-based line the hunk was generated at, used as the first place to look. */+ oldStart: number+}++export type FilePatch = {+ /** Path relative to the package root. */+ path: string+ hunks: Hunk[]+}++const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/++function stripPrefix(path: string): string {+ return path.replace(/^[ab]\//, "").trim()+}++/**+ * Parses the subset of unified diff that `git diff --no-index` emits for text+ * files: file headers, hunk headers, and ` `/`-`/`+` body lines. Anything else+ * (rename, mode, binary) is unsupported on purpose — patches here are expected+ * to be small edits to shipped JavaScript.+ */+export function parseUnifiedDiff(patch: string): FilePatch[] {+ const files: FilePatch[] = []+ const lines = patch.split("\n")++ let current: FilePatch | null = null+ let hunk: Hunk | null = null++ const closeHunk = () => {+ if (current && hunk) current.hunks.push(hunk)+ hunk = null+ }++ for (const line of lines) {+ if (line.startsWith("+++ ")) {+ closeHunk()+ const path = stripPrefix(line.slice(4))+ if (path === "/dev/null") {+ throw new Error("Unified diff deletes a file, which is not supported")+ }+ current = { path, hunks: [] }+ files.push(current)+ continue+ }++ if (line.startsWith("--- ") || line.startsWith("diff --git ")) {+ closeHunk()+ continue+ }++ const header = HUNK_HEADER.exec(line)+ if (header) {+ closeHunk()+ hunk = { before: [], after: [], oldStart: Number.parseInt(header[1], 10) }+ continue+ }++ if (!hunk) continue++ const marker = line[0]+ const content = line.slice(1)++ if (marker === " ") {+ hunk.before.push(content)+ hunk.after.push(content)+ } else if (marker === "-") {+ hunk.before.push(content)+ } else if (marker === "+") {+ hunk.after.push(content)+ }+ // "\ No newline at end of file" and blank separators are ignored.+ }++ closeHunk()++ return files.filter((file) => file.hunks.length)+}++function matchesAt(source: string[], block: string[], at: number): boolean {+ if (at < 0 || at + block.length > source.length) return false+ return block.every((line, i) => source[at + i] === line)+}++/**+ * How far from the recorded line a hunk may drift and still be considered the+ * same code. Unbounded searching is unsafe: the same few lines of context can+ * legitimately appear elsewhere in a file — cartFieldsForRefreshSteps and+ * completeCartFields share several — and relocating a hunk that far would+ * silently patch the wrong site.+ */+const MAX_DRIFT_LINES = 50++/**+ * Locates a hunk by content, preferring the line it was generated at and+ * otherwise accepting a single unambiguous match nearby. Returns -1 when the+ * hunk does not apply, or could apply in more than one place — both mean the+ * patch is stale and must be regenerated rather than guessed at.+ */+function locate(source: string[], block: string[], oldStart: number): number {+ if (!block.length) return -1++ const expected = oldStart - 1+ if (matchesAt(source, block, expected)) return expected++ const from = Math.max(0, expected - MAX_DRIFT_LINES)+ const to = Math.min(source.length - block.length, expected + MAX_DRIFT_LINES)++ let found = -1+ for (let i = from; i <= to; i++) {+ if (!matchesAt(source, block, i)) continue+ if (found !== -1) return -1+ found = i+ }++ return found+}++/**+ * Applies every hunk, or returns `null`. A patch is never partially applied.+ */+export function applyHunks(source: string, hunks: Hunk[]): string | null {+ let lines = source.split("\n")++ for (const hunk of hunks) {+ const at = locate(lines, hunk.before, hunk.oldStart)+ if (at === -1) return null++ lines = [+ ...lines.slice(0, at),+ ...hunk.after,+ ...lines.slice(at + hunk.before.length),+ ]+ }++ return lines.join("\n")+}++export function reverse(hunks: Hunk[]): Hunk[] {+ return hunks.map((hunk) => ({+ before: hunk.after,+ after: hunk.before,+ oldStart: hunk.oldStart,+ }))+}diff --git a/packages/core/src/patches/version.ts b/packages/core/src/patches/version.tsnew file mode 100644index 000000000..6425bda41--- /dev/null+++ b/packages/core/src/patches/version.ts@@ -0,0 +1,30 @@+// Deliberately not semver: the range a patch declares is always a plain+// "verified from this version, up to that one" pair, and pulling a resolver in+// for that would be more machinery than the check deserves.++function parse(version: string): number[] {+ const core = version.split("-")[0]+ return core.split(".").map((part) => Number.parseInt(part, 10) || 0)+}++export function compareVersions(a: string, b: string): number {+ const left = parse(a)+ const right = parse(b)++ for (let i = 0; i < 3; i++) {+ const diff = (left[i] ?? 0) - (right[i] ?? 0)+ if (diff !== 0) return diff > 0 ? 1 : -1+ }++ return 0+}++export function isWithinRange(+ version: string,+ range: { from: string; to: string }+): boolean {+ return (+ compareVersions(version, range.from) >= 0 &&+ compareVersions(version, range.to) < 0+ )+}diff --git a/packages/core/src/with-mercur.ts b/packages/core/src/with-mercur.tsindex 9cf29b502..861ee351e 100644--- a/packages/core/src/with-mercur.ts+++ b/packages/core/src/with-mercur.ts@@ -1,5 +1,6 @@import type { InputConfigWithArrayModules } from "@medusajs/framework/types"import { defineConfig } from '@medusajs/framework/utils'+import { applyMercurPatches } from "./patches"import { disableMedusaMiddlewares } from "./utils/disable-medusa-middlewares"type HttpConfig = NonNullable<NonNullable<InputConfigWithArrayModules["projectConfig"]>["http"]>@@ -9,10 +10,26 @@ export type MercurInputConfig = Omit<InputConfigWithArrayModules, "projectConfighttp?: HttpConfig & {vendorCors?: string}+ 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.+ */+ disabledPatches?: string[]+ }}}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,+ })disableMedusaMiddlewares()const projectConfig = {