All files default-import.ts

100% Statements 54/54
100% Branches 13/13
100% Functions 1/1
100% Lines 54/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 551x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 82x 18x 18x 64x 64x 64x 64x 20x 20x 20x 20x 20x 20x 20x 20x 44x 82x 82x 82x 64x 23x 82x 23x 82x 12x 12x 52x 52x  
// eslint-disable-next-line @typescript-eslint/naming-convention
type ExtractDefault<T> = T extends { __esModule?: boolean; default: infer U }
    ? // eslint-disable-next-line @typescript-eslint/naming-convention
      U extends { __esModule?: boolean; default: infer V }
        ? V
        : U
    : T;
 
/**
 * With ESM it is possible to export both a default value and multiple named exports.
 * With CJS it is possible to "mock" ESM functionality with a `__esModule=true` flag
 * but still only export a single "default" export, or multiple named exports.
 *
 * This helper method detects when a library tries to do a "default" export with other named values
 * and returns the "intended" default value.
 *
 * It also handles CJS exports that export an entire object via `module.exports = {}` rather than export syntax,
 * as well as extracting the `default` (if exists) from a dynamic import.
 *
 * Note there is not "namedImport" equivalent because it is assumed module loaders successfully parse that
 * out for both CJS and ESM.
 *
 * @param mod - "default" export that might be wrapped in another layer
 * @returns unwrapped module
 */
export const defaultImport = <T>(mod: T): ExtractDefault<T> => {
    if (typeof mod !== 'object' || mod === null) {
        return mod as ExtractDefault<T>;
    }
 
    // Webpack provides a Module tag to match NodeJS' Module module
    const defaultVal =
        Symbol.toStringTag in mod &&
        (mod as unknown as { [Symbol.toStringTag]: string; default: T })[Symbol.toStringTag] ===
            'Module'
            ? (
                  mod as unknown as {
                      [Symbol.toStringTag]: 'Module';
                      default?: T;
                  }
              ).default ?? mod
            : mod;
 
    if (
        typeof defaultVal === 'object' &&
        '__esModule' in defaultVal &&
        // eslint-disable-next-line @typescript-eslint/naming-convention
        (defaultVal as unknown as { __esModule?: boolean }).__esModule &&
        (defaultVal as unknown as { default?: ExtractDefault<T> | undefined }).default !== undefined
    ) {
        return (defaultVal as unknown as { default: ExtractDefault<T> }).default;
    }
    return defaultVal as ExtractDefault<T>;
};