All files / src/loader js.ts

100% Statements 12/12
93.33% Branches 14/15
100% Functions 5/5
100% Lines 12/12

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        4x   17x           10x                               19x 19x 19x 19x 17x   2x     1x     18x       16x    
import jitiFactory from 'jiti';
import type { JITIOptions } from 'jiti/dist/types';
import { transform, Options } from 'sucrase';
 
let jiti: ReturnType<typeof jitiFactory> | null = null;
function lazyJiti(option: JITIOptions = {}, transformOpt = {} as Options) {
  return (
    jiti ??
    (jiti = jitiFactory(__filename, {
      interopDefault: true,
      ...option,
      transform: (opts) => {
        return transform(opts.source, {
          transforms: ['typescript', 'imports'],
          ...transformOpt,
        });
      },
    }))
  );
}
 
export interface LoadConfOption {
  jiti?: boolean;
  jitiOptions?: JITIOptions;
  transformOption?: Options;
}
 
export function loadConf<T>(path: string, option: LoadConfOption = {}): T {
  const { jiti = true, jitiOptions, transformOption } = option;
  let config = (function () {
    try {
      if (jiti) {
        return path ? lazyJiti(jitiOptions, transformOption)(path) : {};
      } else {
        return path ? require(path) : {};
      }
    } catch {
      return lazyJiti(jitiOptions, transformOption)(path);
    }
  })();
  return config.default ?? config;
}
 
export function jsLoader<T>(filepath: string, content: string, option: LoadConfOption = {}): T {
  return loadConf<T>(filepath, option);
}