UNPKG

knip

Version:

Find and fix unused dependencies, exports and files in your TypeScript and JavaScript projects

70 lines (69 loc) 2.18 kB
import { statSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import yaml from 'js-yaml'; import { parse as parseTOML } from 'smol-toml'; import stripJsonComments from 'strip-json-comments'; import { LoaderError } from './errors.js'; import { extname, join } from './path.js'; export const isDirectory = (filePath) => { try { return statSync(filePath).isDirectory(); } catch (_error) { return false; } }; export const isFile = (filePath) => { try { return statSync(filePath).isFile(); } catch (_error) { return false; } }; export const findFile = (workingDir, fileName) => { const filePath = join(workingDir, fileName); return isFile(filePath) ? filePath : undefined; }; export const loadFile = async (filePath) => { try { const contents = await readFile(filePath); return contents.toString(); } catch (error) { throw new LoaderError(`Error loading ${filePath}`, { cause: error }); } }; export const loadJSON = async (filePath) => { const contents = await loadFile(filePath); try { return JSON.parse(contents); } catch { return parseJSONC(filePath, contents); } }; export const loadJSONC = async (filePath) => { const contents = await loadFile(filePath); return parseJSONC(filePath, contents); }; export const loadYAML = async (filePath) => { const contents = await loadFile(filePath); return parseYAML(contents); }; export const loadTOML = async (filePath) => { const contents = await loadFile(filePath); return parseTOML(contents); }; export const parseJSONC = async (filePath, contents) => { try { return JSON.parse(stripJsonComments(contents, { trailingCommas: true, whitespace: false })); } catch (error) { const message = `Error parsing ${filePath} ${extname(filePath) === '.json5' ? 'JSON5 features beyond comments and trailing commas are not fully supported. Consider converting to .jsonc format.' : ''}`; throw new LoaderError(message, { cause: error }); } }; export const parseYAML = (contents) => { return yaml.load(contents); };