Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@trivago/prettier-plugin-sort-imports

Package Overview
Dependencies
Maintainers
4
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@trivago/prettier-plugin-sort-imports - npm Package Compare versions

Comparing version 1.3.0 to 1.4.0-0

4

lib/src/index.js

@@ -16,2 +16,3 @@ "use strict";

var parser_typescript_1 = require("prettier/parser-typescript");
var parser_flow_1 = require("prettier/parser-flow");
var preprocessor_1 = require("./preprocessor");

@@ -35,6 +36,7 @@ var options = {

parsers: {
babel: __assign(__assign({}, parser_babel_1.parsers.babel), { preprocess: preprocessor_1.preprocessor }),
'babel-flow': __assign(__assign({}, parser_flow_1.parsers.flow), { preprocess: preprocessor_1.preprocessor }),
typescript: __assign(__assign({}, parser_typescript_1.parsers.typescript), { preprocess: preprocessor_1.preprocessor }),
babel: __assign(__assign({}, parser_babel_1.parsers.babel), { preprocess: preprocessor_1.preprocessor }),
},
options: options,
};

@@ -11,3 +11,2 @@ "use strict";

var traverse_1 = __importDefault(require("@babel/traverse"));
var types_1 = require("@babel/types");
var utils_1 = require("./utils");

@@ -25,5 +24,2 @@ function preprocessor(code, options) {

traverse_1.default(ast, {
enter: function (path) {
types_1.removeComments(path.node);
},
ImportDeclaration: function (path) {

@@ -33,19 +29,8 @@ importNodes.push(path.node);

});
var thirdPartyImports = utils_1.getSortedNodesNotInTheImportOrder(importNodes, importOrder);
var localImports = utils_1.getSortedNodesByImportOrder(importNodes, importOrder);
var thirdPartyImportsAsCode = utils_1.getCodeFromAst(thirdPartyImports);
var localImportsAsCode = localImports
.map(utils_1.getCodeFromAst)
.join(utils_1.handleImportSeparation(importOrderSeparation));
var importsStart = importNodes[0]
? importNodes[0].start !== null
? importNodes[0].start
: 0
: 0;
var modifiedCode = utils_1.removeImportsFromOriginalCode(code, importNodes);
var initialCodeBlock = modifiedCode.substring(0, importsStart);
var middleCodeBlock = utils_1.getAllGeneratedImportCodeTogether(thirdPartyImportsAsCode, localImportsAsCode, importOrderSeparation);
var endCodeBlock = modifiedCode.substring(importsStart);
return "" + initialCodeBlock + middleCodeBlock + endCodeBlock;
// short-circuit if there are no import declaration
if (importNodes.length === 0)
return code;
var allImports = utils_1.getSortedNodes(importNodes, importOrder, importOrderSeparation);
return utils_1.getCodeFromAst(allImports, code);
}
exports.preprocessor = preprocessor;

@@ -13,3 +13,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getAllGeneratedImportCodeTogether = exports.getNewLine = exports.handleImportSeparation = exports.getCodeFromAst = exports.removeImportsFromOriginalCode = exports.getSortedNodesNotInTheImportOrder = exports.getSortedNodesByImportOrder = void 0;
exports.getCodeFromAst = exports.removeImportsFromOriginalCode = exports.getSortedNodes = void 0;
// we do not have types for javascript-natural-sort

@@ -20,7 +20,13 @@ //@ts-ignore

var types_1 = require("@babel/types");
var lodash_1 = require("lodash");
var PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE = 'PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE';
var newLineNode = types_1.expressionStatement(types_1.stringLiteral(PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE));
var newLineCharacters = '\n\n';
/**
* This function checks that specified string exists in the specified list.
* @param list
* @param text
*/
var isSimilarTextExistInArray = function (arr, text) {
return arr.some(function (element) { return text.match(new RegExp(element)) !== null; });
var isSimilarTextExistInArray = function (list, text) {
return list.some(function (element) { return text.match(new RegExp(element)) !== null; });
};

@@ -30,26 +36,45 @@ /**

* The plugin considered these import nodes as local import declarations.
* @param nodes all import nodes
* @param order import order
* @param importOrderSeparation boolean indicating if newline should be inserted after each import order
*/
exports.getSortedNodesByImportOrder = function (nodes, order) {
return order.reduce(function (res, val) {
var x = nodes.filter(function (node) { return node.source.value.match(new RegExp(val)) !== null; });
exports.getSortedNodes = function (nodes, order, importOrderSeparation) {
var originalNodes = nodes.map(lodash_1.clone);
var newLine = importOrderSeparation && nodes.length > 1 ? newLineNode : null;
var sortedNodesByImportOrder = order.reduce(function (res, val) {
var x = originalNodes.filter(function (node) { return node.source.value.match(new RegExp(val)) !== null; });
// remove "found" imports from the list of nodes
lodash_1.pull.apply(void 0, __spreadArrays([originalNodes], x));
if (x.length > 0) {
x.sort(function (a, b) { return javascript_natural_sort_1.default(a.source.value, b.source.value); });
return __spreadArrays(res, [x]);
return lodash_1.compact(__spreadArrays(res, [newLine], x));
}
return res;
}, []);
var sortedNodesNotInImportOrder = originalNodes.filter(function (node) { return !isSimilarTextExistInArray(order, node.source.value); });
sortedNodesNotInImportOrder.sort(function (a, b) {
return javascript_natural_sort_1.default(a.source.value, b.source.value);
});
var allSortedNodes = __spreadArrays(sortedNodesNotInImportOrder, sortedNodesByImportOrder, [
newLineNode,
]);
// maintain a copy of th nodes to extract comments from
var sortedNodesClone = allSortedNodes.map(lodash_1.clone);
var firstNodesComments = nodes[0].leadingComments;
// Remove all comments from sorted nodes
allSortedNodes.forEach(types_1.removeComments);
// insert comments other than the first commens
allSortedNodes.forEach(function (importDeclaration, index) {
types_1.addComments(importDeclaration, 'leading', sortedNodesClone[index].leadingComments || []);
});
if (firstNodesComments && !lodash_1.isEqual(nodes[0], allSortedNodes[0])) {
types_1.addComments(allSortedNodes[0], 'leading', firstNodesComments);
}
return allSortedNodes;
};
/**
* This function returns all the nodes which are not in the importOrder array.
* The plugin considered these import nodes as third party import declarations.
* Removes imports from original file
* @param code the whole file as text
* @param nodes to be removd
*/
exports.getSortedNodesNotInTheImportOrder = function (nodes, order) {
var x = nodes.filter(function (node) { return !isSimilarTextExistInArray(order, node.source.value); });
x.sort(function (a, b) { return javascript_natural_sort_1.default(a.source.value, b.source.value); });
return x;
};
/**
* When we get all the imports from the code, we remove these import statements
* from the original code which is passed to prettier preprocessor.
*/
exports.removeImportsFromOriginalCode = function (code, nodes) {

@@ -69,7 +94,12 @@ var text = code;

* This function generate a code string from the passed nodes.
* @param nodes all imports
* @param originalCode
*/
exports.getCodeFromAst = function (node) {
var ast = types_1.file({
exports.getCodeFromAst = function (nodes, originalCode) {
var allCommentsFromImports = getAllCommentsFromNodes(nodes);
var commentAndImportsToRemoveFromCode = __spreadArrays(nodes, allCommentsFromImports);
var codeWithoutImportDeclarations = exports.removeImportsFromOriginalCode(originalCode, commentAndImportsToRemoveFromCode);
var newAST = types_1.file({
type: 'Program',
body: node,
body: nodes,
directives: [],

@@ -89,17 +119,13 @@ sourceType: 'module',

});
return generator_1.default(ast).code;
var code = generator_1.default(newAST).code;
return (code.replace(/"PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE";/gi, newLineCharacters) + codeWithoutImportDeclarations);
};
exports.handleImportSeparation = function (isNewLine) {
return isNewLine ? '\n\n' : '';
var getAllCommentsFromNodes = function (nodes) {
return nodes.reduce(function (acc, node) {
if (Array.isArray(node.leadingComments) &&
node.leadingComments.length > 0) {
acc = __spreadArrays(acc, node.leadingComments);
}
return acc;
}, []);
};
exports.getNewLine = function () { return '\n'; };
/**
* This function stitches all the imports together. If import separation is
* enabled then this function adds new line accordingly.
*/
exports.getAllGeneratedImportCodeTogether = function (thirdPartyImportsAsCode, localImportsAsCode, importOrderSeparation) {
if (thirdPartyImportsAsCode.length > 0) {
return "" + thirdPartyImportsAsCode + exports.handleImportSeparation(importOrderSeparation) + localImportsAsCode + exports.handleImportSeparation(importOrderSeparation) + exports.getNewLine();
}
return "" + localImportsAsCode + exports.handleImportSeparation(importOrderSeparation) + exports.getNewLine();
};
{
"name": "@trivago/prettier-plugin-sort-imports",
"version": "1.3.0",
"version": "1.4.0-0",
"description": "A prettier plugins to sort imports in provided RegEx order",

@@ -5,0 +5,0 @@ "main": "lib/src/index.js",

@@ -92,4 +92,4 @@ # Prettier plugin sort imports

`npm run example` command.
```shell script

@@ -99,8 +99,7 @@ npm run example examples/example.tsx

### Maintainer
### Maintainers
| [Ayush Sharma](https://github.com/ayusharma)
|---|
| ![ayusharma](https://avatars2.githubusercontent.com/u/6918450?s=120&v=4)
| [@ayusharma_](https://twitter.com/ayusharma_)
| [Ayush Sharma](https://github.com/ayusharma) | [Behrang Yarahmadi](https://github.com/byara)
|---|---|
| ![ayusharma](https://avatars2.githubusercontent.com/u/6918450?s=120&v=4) | ![@byara](https://avatars2.githubusercontent.com/u/6979966?s=120&v=4)
| [@ayusharma_](https://twitter.com/ayusharma_) | [@behrang_y](https://twitter.com/behrang_y)
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc