prettier-plugin-sort-imports
Version:
A prettier plugin for sorting imports by length
7 lines (6 loc) • 11.4 kB
JavaScript
;var J=Object.create;var S=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var X=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var ee=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})},_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Q(t))!Z.call(e,o)&&o!==r&&S(e,o,{get:()=>t[o],enumerable:!(n=q(t,o))||n.enumerable});return e};var y=(e,t,r)=>(r=e!=null?J(X(e)):{},_(t||!e||!e.__esModule?S(r,"default",{value:e,enumerable:!0}):r,e)),te=e=>_(S({},"__esModule",{value:!0}),e);var Ee={};ee(Ee,{options:()=>A,parsers:()=>be});module.exports=te(Ee);var H=require("prettier/parser-typescript"),z=require("prettier/parser-babel");function N(e,t){return e<t?-1:e>t?1:0}function M(e){return[...e].sort((t,r)=>{let n=t.importPath,o=r.importPath;return N(n,o)})}function D(e){return[...e].sort((r,n)=>{let o=r.import.getText().length,s=n.import.getText().length;return o===s&&r.importPath&&n.importPath&&(o=r.importPath.length,s=n.importPath.length),s-o||N(n.importPath,r.importPath)})}var a=y(require("typescript"));function oe(e){if(e.importTypeOrder.length!==0){if(e.importTypeOrder.includes("all")){if(e.importTypeOrder.length>1)throw new Error('You cannot use the "all" import type with other types.');return}if(e.importTypeOrder.includes("localImports")&&(e.importTypeOrder.includes("localImportsValue")||e.importTypeOrder.includes("localImportsType")))throw new Error('You cannot use the "localImports" import type with other local import types. Choose between either using "localImports" (so all local imports) or specifying the order in which local imports are sorted by specifying both type and value options.');if(e.importTypeOrder.includes("localImportsType")!==e.importTypeOrder.includes("localImportsValue"))throw new Error('You must specify both the "localImportsType" and "localImportsValue" import types or use the "localImports" type that captures them both.');if((e.importTypeOrder.includes("localImportsType")||e.importTypeOrder.includes("localImportsValue")||e.importTypeOrder.includes("localImports")||e.importTypeOrder.includes("NPMPackages"))&&(e.importTypeOrder.includes("localImportsType")||e.importTypeOrder.includes("localImportsValue")||e.importTypeOrder.includes("localImports"))!==e.importTypeOrder.includes("NPMPackages"))throw new Error('You must specify one local-value import type (such as "localImports") and one npm-package import type (such as "NPMPackages") or none at all.')}}function F(e){oe(e)}var A={sortingMethod:{since:"1.15.0",category:"Global",type:"choice",default:"lineLength",description:"Which sorting method to use",choices:[{value:"alphabetical",description:"Sort imports alphabetically by the import path"},{value:"lineLength",description:"Sort by line length, descending"}]},sortingOrder:{since:"1.15.0",category:"Global",type:"choice",default:"descending",description:"Which sorting order to use (default descending)",choices:[{value:"ascending",description:"Sort imports in ascending order"},{value:"descending",description:"Sort imports in descending order"}]},stripNewlines:{since:"1.15.0",category:"Global",type:"boolean",default:!1,description:"Whether to strip newlines between blocks (joining blocks)"},importTypeOrder:{since:"1.15.0",category:"Global",array:!0,type:"choice",default:[{value:["all"]}],description:"Order in which to sort import types. Does not take import type into account by default.",choices:[{value:"NPMPackages",description:"NPM packages, inferred from your package.json file"},{value:"localImportsValue",description:"Value imports from within this project. Value imports are all non type-only imports"},{value:"localImportsType",description:"Type imports from within this project. Only available in typescript."},{value:"localImports",description:'All imports from within this project. Cannot be used together with any of the other "localImports" options'},{value:"all",description:"Every type of import. This is the default and means import type is not taken into account."}]},packageJSONFiles:{since:"1.15.0",category:"Global",array:!0,type:"string",default:[{value:["./package.json"]}],description:"Paths to package.json files relative to the .prettierrc.json file. These files will be used to infer NPM packages"},newlineBetweenTypes:{since:"1.15.0",category:"Global",type:"boolean",default:!1,description:"Puts a newline between imports of different groups (see importTypeOrder)"}};var Y=require("module"),m=y(require("path")),h=y(require("fs")),K=y(require("os"));function ie(e){let t=o=>{try{return h.statSync(o).isDirectory()}catch(s){if(s.code==="ENOENT")return!1;throw s}},r=function*(){let s=m.resolve(K.homedir()),i=m.dirname(m.resolve(e));yield i;let p=i;for(;p!==s;){let l=m.dirname(p);if(l===p)break;yield l,p=l}}();if(r.next().done)throw new Error;for(let o of r)if(t(o))for(let s of[".prettierrc",".prettierrc.json",".prettierrc.json5",".prettierrc.yaml",".prettierrc.yml",".prettierrc.js",".prettierrc.cjs",".prettierrc.mjs","prettier.config.js","prettier.config.cjs","prettier.config.mjs",".prettierrc.toml"]){let i=m.join(o,s);if(h.existsSync(i))return i}return null}function se(e,t){let r=[],n,o=process.cwd();for(let i of t){let p=(()=>{if(m.isAbsolute(i))return i;{let l=ie(e);return l&&(n=m.dirname(l)),m.join(n??o,i)}})();try{let l=h.readFileSync(p,"utf8"),c=JSON.parse(l);if(c.dependencies)for(let u in c.dependencies)r.push(u);if(c.devDependencies)for(let u in c.devDependencies)r.push(u)}catch{console.warn("Failed to read/parse package.json file:",p)}}return[...new Set(r)]}function j(e,t){let r=[];for(let n=0;n<e.length;n++){let o=e[n];t.includes(o)&&(r[n]=t.indexOf(o))}if(r.length!==e.length||r.length!==t.length)throw new Error("Unknown import type specified");return r}var f=class{constructor(t){this.values=t}};function k(e){return(...t)=>{let r=[];for(let n of e){let o=t[n];r.push(o)}return r}}var le=Y.builtinModules.filter(e=>!e.startsWith("_"));function $(e,t){let r=t.slice(1,-1);return[...e,...le].some(n=>r.startsWith(n))}function ce(...e){for(let t of e)if(t!==-1)return t;return-1}function U({importTypeOrder:e,packageJSONFiles:t,filepath:r,sortingMethod:n,newlineBetweenTypes:o}){if(e.includes("all"))return;let s=se(r,t);if(e.includes("localImportsValue")||e.includes("localImportsType")){let p=k(j(e,["localImportsValue","localImportsType","NPMPackages"])),l=e.indexOf("NPMPackages")<ce(e.indexOf("localImportsValue"),e.indexOf("localImports")),c=k(l?[0,1]:[1,0]);return u=>{let d=[],T=[],b=[],E=[];for(let g of u){let v=$(s,g.importPath);g.isTypeOnly?v?E.push(g):T.push(g):v?b.push(g):d.push(g)}return n==="lineLength"&&o?p(d,[...E,...T],b):p(d,new f(c(E,T)),b)}}let i=k(j(e,["NPMPackages","localImports"]));return p=>{let l=[],c=[];for(let u of p)$(s,u.importPath)?c.push(u):l.push(u);return i(c,l)}}var pe=1e3*60*2.5;function w(e,t){let r=0;for(;e.includes(t);){r++;let n=e.indexOf(t);e=e.slice(0,n)+e.slice(n+1)}return r}var L=Symbol("importNewline");function ae(e,t){let r=a.getTrailingCommentRanges(e,t.getFullStart()+t.getFullWidth());return r?r[r.length-1]:null}function ue(e,t){let r=a.getLeadingCommentRanges(e,t.getFullStart());return r?r[0]:null}function me(e,t,r,n,o){let i=e[e.length-1].length,p=r.getStart(),l=ue(t,r);l&&!fe(t,l)&&i!==0&&(p=l.pos);let c=r.end,u=ae(t,r);return u&&(c=u.end),{import:r,start:p,importPath:n,end:c,isTypeOnly:o,startLine:x(t,p),endLine:x(t,c)}}function de(e,t,r){for(let n of r)if(t>=n.start&&t<n.end||e>=n.start&&e<n.end)return!0;return!1}function fe(e,t){let r=e.slice(t.pos,t.end);return r.includes(B)||r.includes(G)}function ge(e){if(a.isImportDeclaration(e))return e.moduleSpecifier.getText();{if(e.declarationList.declarations.length!==1)return null;let t=e.declarationList.declarations[0];if(!a.isVariableDeclaration(t))return null;let r=t.initializer;return!r||!a.isCallExpression(r)?null:r.arguments[0].getText()}}function he(e,t,r){let n=[[]],o=e.getChildren()[0].kind===a.SyntaxKind.SyntaxList?e.getChildren()[0].getChildren():e.getChildren(),s=null;for(let i of o)if(a.isImportDeclaration(i)||a.isVariableStatement(i)&&i.declarationList&&i.declarationList.declarations.length===1&&a.isVariableDeclaration(i.declarationList.declarations[0])&&i.declarationList.declarations[0].initializer&&a.isCallExpression(i.declarationList.declarations[0].initializer)&&i.declarationList.declarations[0].initializer.expression.getText()==="require"){if(s){let l=i.getStart(),c=s.end,u=a.getLeadingCommentRanges(e.getFullText(),i.getFullStart());u&&u.length&&(l=u[0].pos);let d=e.getFullText().slice(c,l);if(de(l,i.getEnd(),r)){n.push([]),s=null;continue}t&&d.trim()!==""?n.push([]):!t&&w(d,`
`)>1&&n.push([])}let p=ge(i);if(p){let l=me(n,e.getFullText(),i,p,!!(a.isImportDeclaration(i)&&i.importClause?.isTypeOnly));s=l,n[n.length-1].push(l)}else s=null}return n.filter(i=>i.length>0)}function Ie(e){return e.map(t=>t===L?t:t.startsWith(`
`)?t.slice(1):t)}function Se(e,t,r){let n=r?r(e):[e],o=t.sortingMethod==="alphabetical"?M:D,s=t.sortingOrder==="ascending"?c=>o(c).reverse():o,p=n.map(c=>c instanceof f?new f(c.values.map(s)):s(c)).filter(c=>c instanceof f?c.values.filter(u=>u.length>0).length>0:c.length>0),l=[];for(let c=0;c<p.length;c++){let u=p[c];if(u instanceof f)for(let d of u.values)l=l.concat(d);else l=l.concat(u);t.newlineBetweenTypes&&c<p.length-1&&l.push(L)}return l}function ye(e,t,r,n){if(e.length===0)return t;let o=Se(e,r,n),s=t.split(`
`),i=[];for(let l of o)l===L?i.push(l):i.push(...s.slice(l.startLine,l.endLine+1));r.stripNewlines&&(i=Ie(i));let p=i.map(l=>l===L?"":l);return[...s.slice(0,e[0].startLine),...p,...s.slice(e[e.length-1].endLine+1)].join(`
`)}var B="sort-imports-begin-ignore",P=[`//${B}`,`// ${B}`],G="sort-imports-end-ignore",R=[`//${G}`,`// ${G}`];function C(e,t){for(let r of t){let n=e.indexOf(r);if(n!==-1)return n}return-1}function Oe(e,t){let r=P.reduce((o,s)=>o+w(t,s),0),n=R.reduce((o,s)=>o+w(t,s),0);return r!==n?(console.warn(`Number of ignore begin and end comments do not match in file "${e??"input"}". Found ${r} begin comments and ${n} end comments. Skipping file`),!1):!0}function x(e,t){let r=e.split(`
`),n=0;for(let o=0;o<r.length;o++){let s=r[o].length+1;if(n+s>t)return o;n+=s}return-1}function Pe(e){let t=[];if(C(e,P)===-1)return[];let r=e,n=0,o;for(;(o=C(e,P))!==-1;){let s=n+o;n=n+o+P[0].length,e=e.slice(n);let i=C(e,R);if(i===-1)return console.warn(`Failed to find end ignore comment for ignore begin comment on line ${x(r,s)}, ignoring file`),null;t.push({start:s,end:n+i}),n=n+i+R[0].length,e=e.slice(n)}return t}var I=null,Le=!1;function Te(e,t=!1){return I&&!process.argv.includes("--sort-imports-reinit")&&!t||(Le&&setInterval(()=>{I=null},pe).unref(),F(e),I={importTypeSorter:U(e)}),I}function O(e,t,r=!1){if(e.includes("// sort-imports-ignore")||e.includes("//sort-imports-ignore")||!Oe(t.filepath,e))return e;let n=Te(t,r),o=Pe(e);if(o===null)return e;let s=t.filepath||"file.ts",i=a.createSourceFile(s,e,a.ScriptTarget.Latest,!0,s.endsWith("ts")?a.ScriptKind.TS:a.ScriptKind.TSX),p=he(i,t.stripNewlines,o).reverse();for(let l of p)e=ye(l,e,t,n.importTypeSorter);return e}var W=(e,t)=>({typescript:{...e,preprocess:e.preprocess?(r,n,o)=>O(e.preprocess(r,n),n,o?.clearCache):O},babel:{...t,preprocess:t.preprocess?(r,n)=>O(t.preprocess(r,n),n):O}});var be=W(H.parsers.typescript,z.parsers.babel);0&&(module.exports={options,parsers});