From 14eb72d0f571e06dcd127c0d5fec7b4fa49609f9 Mon Sep 17 00:00:00 2001 From: Pooya Parsa <pooya@pi0.io> Date: Thu, 11 Jan 2024 15:59:26 +0100 Subject: [PATCH] fix(interopDefault): skip nullish values for `default` and explicitly return non-objects as-is related to #194 --- src/cjs.ts | 20 +++++++++++++------- test/interop.test.ts | 12 +++++++++++- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/cjs.ts b/src/cjs.ts index e78ebde..eb2432b 100644 --- a/src/cjs.ts +++ b/src/cjs.ts @@ -35,24 +35,30 @@ export function interopDefault(sourceModule: any): any { if (!isObject(sourceModule) || !("default" in sourceModule)) { return sourceModule; } - const newModule = sourceModule.default; + const defaultValue = sourceModule.default; + if (defaultValue === undefined || defaultValue === null) { + return sourceModule; + } + if (typeof defaultValue !== "object") { + return defaultValue; + } for (const key in sourceModule) { if (key === "default") { try { - if (!(key in newModule)) { - Object.defineProperty(newModule, key, { + if (!(key in defaultValue)) { + Object.defineProperty(defaultValue, key, { enumerable: false, configurable: false, get() { - return newModule; + return defaultValue; }, }); } } catch {} } else { try { - if (!(key in newModule)) { - Object.defineProperty(newModule, key, { + if (!(key in defaultValue)) { + Object.defineProperty(defaultValue, key, { enumerable: true, configurable: true, get() { @@ -63,5 +69,5 @@ export function interopDefault(sourceModule: any): any { } catch {} } } - return newModule; + return defaultValue; } diff --git a/test/interop.test.ts b/test/interop.test.ts index 2e2f2b9..64f9f0c 100644 --- a/test/interop.test.ts +++ b/test/interop.test.ts @@ -16,6 +16,14 @@ const tests = [ { named: 1, default: { x: 2 } }, { named: 1, x: 2 }, ], + [ + { default: null, x: 1 }, // eslint-disable-line unicorn/no-null + { default: null, x: 1 }, // eslint-disable-line unicorn/no-null + ], + [ + { default: undefined, x: 1 }, + { default: undefined, x: 1 }, + ], ]; describe("interopDefault", () => { @@ -24,7 +32,9 @@ describe("interopDefault", () => { const interop = interopDefault(input); expect(interop).to.deep.equal(result); if (typeof input === "object" && "default" in input) { - expect(interop.default).to.deep.equal(result); + expect(interop.default).to.deep.equal( + "default" in (result as any) ? (result as any).default : result, + ); } else { expect(interop).to.deep.equal(result); }