UNPKG

prettier-plugin-pkg

Version:

An opinionated package.json formatter plugin for Prettier

71 lines 2.16 kB
const DEFAULT_LIFECYCLE_SCRIPTS = new Set([ 'dependencies', 'install', 'pack', 'prepare', 'publish', 'restart', 'shrinkwrap', 'start', 'stop', 'test', 'version', ]); export function alphabetSort(a, b) { return a > b ? 1 : a < b ? -1 : 0; } export const sortObject = (a, b) => alphabetSort(a.key.value, b.key.value); export const sortStringArray = (a, b) => alphabetSort(a.value, b.value); const getScriptSortProps = (scriptName, allScriptNames) => { if (DEFAULT_LIFECYCLE_SCRIPTS.has(scriptName)) { return { base: scriptName, order: 0, }; } if (scriptName.length > 3 && scriptName.startsWith('pre')) { const base = scriptName.slice(3); if (allScriptNames.has(base) || DEFAULT_LIFECYCLE_SCRIPTS.has(base)) { return { base, order: -1, }; } } if (scriptName.length > 4 && scriptName.startsWith('post')) { const base = scriptName.slice(4); if (allScriptNames.has(base) || DEFAULT_LIFECYCLE_SCRIPTS.has(base)) { return { base, order: 1, }; } } return { base: scriptName, order: 0, }; }; export const sortScriptNames = (scriptNames) => { const scriptNameSet = new Set(scriptNames); scriptNames = [...scriptNameSet]; return scriptNames.sort((a, b) => { const left = getScriptSortProps(a, scriptNameSet); const right = getScriptSortProps(b, scriptNameSet); if (left.base !== right.base) { return alphabetSort(left.base, right.base); } if (left.order !== right.order) { return alphabetSort(left.order, right.order); } return alphabetSort(a, b); }); }; export const sortScripts = (props) => { const scriptOrder = Object.fromEntries(sortScriptNames(props.map(prop => prop.key.value)).map((name, index) => [ name, index, ])); props.sort((a, b) => alphabetSort(scriptOrder[a.key.value], scriptOrder[b.key.value])); }; //# sourceMappingURL=utils.js.map