UNPKG

prettier-plugin-imports

Version:

A prettier plugins to sort imports in provided RegEx order

4 lines (3 loc) 15.6 kB
Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("prettier/plugins/babel"),r=require("prettier/plugins/flow"),i=require("prettier/plugins/html"),n=require("prettier/plugins/typescript"),o=require("module"),s=require("@babel/types"),l=require("@babel/parser"),a=require("@babel/traverse"),p=require("@babel/generator"),c=require("semver"),u=require("assert");function m(e){return e&&e.__esModule?e:{default:e}}var f=m(a),d=m(p),g=m(c),h=m(u);const y="unsortable",v="value",C="type",S=[v,C],I=`(^(?:node:)?(?:${o.builtinModules.join("|")})$)|(^node:test$)`,O="<BUILTIN_MODULES>",b="<THIRD_PARTY_MODULES>",E="<TYPES>",P=s.expressionStatement(s.stringLiteral("PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE")),w=/("PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE";|\/\/PRETTIER_PLUGIN_SORT_IMPORTS_NEWLINE_COMMENT)/gi,N=[O,b,"^[.]"],T=e=>e.reduce((e,t)=>(Array.isArray(t.leadingComments)&&t.leadingComments.length>0&&(e=[...e,...t.leadingComments]),Array.isArray(t.innerComments)&&t.innerComments.length>0&&(e=[...e,...t.innerComments]),Array.isArray(t.trailingComments)&&t.trailingComments.length>0&&(e=[...e,...t.trailingComments]),"ImportDeclaration"===t.type&&(e=[...e,...T(t.specifiers)]),e),[]);function K(e,t){return e[0]<t[0]?-1:+(e[0]>t[0])}function A(e){return null!==e[0]&&null!==e[1]&&Number.isSafeInteger(e[0])&&Number.isSafeInteger(e[1])}const _=(e,t)=>(function(e,t){if(0===e.length)return e;let r=[],i=(e,t)=>t>e,n=e[0];i(0,n[0])&&r.push([0,n[0]]);for(let t=0;t<e.length-1;t+=1){let n=e[t],o=e[t+1],s=n[1],l=o[0];i(s,l)&&r.push([s,l])}let o=e[e.length-1];return i(o[1],t)&&r.push([o[1],t]),r})(function(e){let t=[];for(let r of e){let e=t[t.length-1];void 0!==e&&e[1]>r[0]&&r[1]>e[0]?t[t.length-1]=[Math.min(e[0],r[0]),Math.max(e[1],r[1])]:t.push(r)}return t}(t.map(e=>[e.start,e.end]).filter(A).sort(K)),e.length).map(t=>e.substring(t[0],t[1])).join(""),x=({nodesToOutput:e,allOriginalImportNodes:t=e,originalCode:r,directives:i,interpreter:n})=>{let o=T(e),l=_(r,[...e,...t,...o,...T(i),...n?T([n]):[],...n?[n]:[],...i]),a=s.file({type:"Program",body:e,directives:i,sourceType:"module",interpreter:n,leadingComments:[],innerComments:[],trailingComments:[],start:0,end:0,loc:{start:{line:0,column:0,index:0},end:{line:0,column:0,index:0},filename:"",identifierName:""}}),{code:p}=d.default(a,{importAttributesKeyword:"with"});return p.replace(w,"\n\n")+l.trim()},M=e=>(e??[]).some(D),D=e=>"prettier-ignore"===e.value.trim(),$=["ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier"];function R(e){return"ImportSpecifier"===e.type?`${e.type}::${e.start}::${"StringLiteral"===e.imported.type?e.imported.value:e.imported.name}`:"CommentLine"===e.type?`${e.type}::${e.start}::${e.loc?.start.line}`:`${e.type}::${e.start}`}const L={leadingComments:"leading",innerComments:"inner",trailingComments:"trailing"},q={leading:"leadingComments",inner:"innerComments",trailing:"trailingComments"},j=["innerComments","trailingComments","leadingComments"];var F=((e=F||{})[e.leadingSpecifier=1e4]="leadingSpecifier",e[e.leadingAboveAllImports=2e4]="leadingAboveAllImports",e[e.trailingCommentForSpecifier=3e4]="trailingCommentForSpecifier",e);const G=({commentRegistry:e,deferredCommentClaims:t,attachmentKey:r,comments:i,owner:n,firstImport:o})=>{let s=0;for(let l of i){let i=R(l);if(e.has(i))continue;let a=$.includes(n.type),p={owner:n,ownerIsSpecifier:a,commentId:i,comment:l,association:L[r],processingPriority:s++};if("innerComments"===r){e.set(i,p);continue}if("trailingComments"===r){n.loc?.start.line===l.loc?.start.line?e.set(i,p):a&&t.push({...p,needsLastSpecifierOwner:!0,processingPriority:p.processingPriority+F.trailingCommentForSpecifier});continue}if("leadingComments"===r){let r=R(n)===R(o),s=(l.loc?.end.line||0)<(n.loc?.start.line||0);r&&s?t.push({...p,needsTopOfFileOwner:!0,association:"trailing",processingPriority:p.processingPriority+F.leadingAboveAllImports}):a?t.push({...p,processingPriority:p.processingPriority+F.leadingSpecifier}):e.set(i,p);continue}else throw Error(`Unimplemented attachmentKey ${r} for ${R(n)}`)}},U=({firstImport:e,outputNodes:t})=>{if(0===t.length)return[];let r=new Map,i=[],n=new Map;for(let o of(t.map(e=>e.specifiers).flat().forEach(e=>{n.has(e.loc?.start.line||0)||n.set(e.loc?.start.line||0,e)}),j))for(let n of t)for(let t of(G({commentRegistry:r,deferredCommentClaims:i,attachmentKey:o,comments:Array.from(n[o]||[]),owner:n,firstImport:e}),n.specifiers))G({commentRegistry:r,deferredCommentClaims:i,attachmentKey:o,comments:Array.from(t[o]||[]),owner:t,firstImport:e});for(let e of(i.sort((e,t)=>e.processingPriority-t.processingPriority),i)){let{commentId:t}=e;if(!r.has(t))if(e.ownerIsSpecifier){let i=e.comment.loc?.start.line||0,o=n.get(i)||e.owner,s=R(o)!==R(e.owner),l="leading"===e.association&&s?"trailing":e.association;r.set(t,{...e,owner:o,association:l})}else r.set(t,e)}let o=Array.from(r.values());return o.sort((e,t)=>e.processingPriority-t.processingPriority),o},W=(e,t,r)=>{let i=t.filter(e=>"ImportDeclaration"===e.type);if(0===e.length||0===i.length)return[...t];let n=e[0],o=U({outputNodes:i,firstImport:n}),l=t.map(e=>{let t=s.removeComments(e);return"ImportDeclaration"===t.type&&(t.specifiers=(t.specifiers||[]).map(e=>s.removeComments(e))),t});return!function(e,t,r,{leadingSeparator:i}={}){if(0===t.length)throw Error("Fatal Internal Error: Can't attach comments to empty output");let n=t[0],o=e=>`parent::${R(e)}`,l=new Map;for(let e of t)if(l.set(R(e),e),"ImportDeclaration"===e.type)for(let t of e.specifiers)l.set(R(t),t),l.set(o(t),e);let a=!1,p=()=>{var e;if(a)return;let t=Array.isArray((e=n).leadingComments)&&e.leadingComments.length&&e.leadingComments[0].loc&&e.loc?Math.max(0,e.loc.start.line-e.leadingComments[0].loc.start.line):0,i=n.loc;if(r.loc&&i){n.loc={start:{...r.loc?.start,line:r.loc?.start.line+t},end:{...r.loc?.end,line:r.loc?.end.line+t},filename:"",identifierName:""};let e=i.start.line-n.loc.start.line;for(let t of j)n[t]?.forEach(t=>{t.loc&&(t.loc.start.line-=e,t.loc.end.line-=e)})}a=!0},c=[];for(let r of e){let{owner:e,comment:i,association:a,needsTopOfFileOwner:u,needsLastSpecifierOwner:m}=r;u&&(function(e){if("EmptyStatement"===e[0].type)return;let t=s.emptyStatement();t.loc={start:{line:0,column:0,index:0},end:{line:0,column:0,index:0},filename:"",identifierName:""},e.unshift(t)}(t),p(),c.push(i));let f=u?t[0]:l.get(R(e));if(m){let t=l.get(o(e));if(!t||0===(t.specifiers?.length||0))throw Error("Fatal Internal Error: Couldn't find parent declaration for a specifier");f=t.specifiers[t.specifiers.length-1],i.loc?.start.line!==void 0&&f.loc?.end.line&&(i.loc.start.line=f.loc?.end.line+1)}if(!f)throw Error("Fatal Internal Error: Couldn't find owner node");f===n&&"leading"!==a&&i.loc&&f.loc&&!m&&(i.loc.start.line=f.loc.start.line);let d=q[a];(f[d]=f[d]||[]).push(i)}i&&a&&c.length&&!M(c)&&(n.loc||{start:{line:0}}).start.line++}(o,l,n,r),l},J=e=>{let t=[];for(let r of e){if("type"===r.importKind||r.specifiers.length<=1){t.push(r);continue}let e=r.specifiers.filter(e=>"ImportSpecifier"===e.type&&"type"===e.importKind);if(e.length&&e.length<r.specifiers.length){let i=r.specifiers.filter(e=>"ImportSpecifier"!==e.type||"type"!==e.importKind),n=s.importDeclaration(i,r.source);t.push(n),e.forEach(e=>e.importKind="value");let o=s.importDeclaration(e,r.source);o.importKind="type",t.push(o);continue}t.push(r)}return t},V=e=>{let t=0===e.specifiers.length;return M(e.leadingComments)||t?y:"other"},Y=new Map,z=e=>{if(Y.has(e))return Y.get(e);let t=new RegExp(e.replace(E,""));return Y.set(e,t),t},B=(e,t)=>{let r=t.some(e=>e.includes(E));for(let{group:i,regExp:n}of t.map(e=>({group:e,regExp:z(e)})).filter(({group:e})=>e!==E)){let t=!1;if(i.includes(E)?"type"===e.importKind&&null!==e.source.value.match(n):r?"type"!==e.importKind&&null!==e.source.value.match(n):null!==e.source.value.match(n))return i}return"type"===e.importKind&&r?E:b};function k(e,t){return("string"==typeof e?e:String(e)).localeCompare(t,"en",{sensitivity:"base",numeric:!0,caseFirst:"lower"})}const H=/^\d+/;function Q(e,t){let r=0,i=0;for(;r<Math.max(e.length,t.length);){let n=e.slice(r).match(H),o=t.slice(i).match(H);if(n&&!o)return -1;if(!n&&o)return 1;if(n&&o){let e=parseInt(n[0]),t=parseInt(o[0]);if(e>t)return 1;if(e<t)return -1;r+=n[0].length,i+=o[0].length}let s=e[r],l=t[i];if(s&&!l)return 1;if(!s&&l)return -1;if(s!==l)return s.charCodeAt(0)-l.charCodeAt(0);r++,i++}return 0}const X=(e,t)=>{let{importOrderCaseSensitive:r}=t||{};return e.specifiers.sort((e,t)=>e.type!==t.type?"ImportDefaultSpecifier"===e.type?-1:1:"ImportSpecifier"===e.type&&"ImportSpecifier"===t.type&&e.importKind!==t.importKind?"value"===e.importKind||null==e.importKind?-1:1:(r?Q:k)(e.local.name,t.local.name)),e},Z=(e,t)=>{let{importOrderCaseSensitive:r}=t||{},i=r?Q:k;return e.sort((e,t)=>i(e.source.value,t.source.value))},ee=e=>e.map(e=>{let t;if(e.startsWith("["))try{t=JSON.parse(e)}catch(t){throw Error("Invalid JSON in importOrderParserPlugins: "+e)}else t=e;return t}),et=(e,t)=>{for(let r of e){let e;if(r.startsWith("["))try{e=JSON.parse(r)[0]}catch(e){throw Error("Invalid JSON in importOrderParserPlugins: "+r)}else e=r;if(e===t)return!0}return!1};function er(e){if(Array.isArray(e)&&!e.length)return e;let t=+!!((e=[...e]).length>0&&ei(e[0]));return e.includes(b)||e.splice(t,0,b),e.includes(O)||e.includes(I)||e.splice(t,0,O),e=e.map(e=>e===O?I:e)}function ei(e){return e?.trim()===""}const en={normalizeImportOrderOption:er},eo=(e,{importOrder:t,importOrderCaseSensitive:r})=>{if("test"===process.env.NODE_ENV&&JSON.stringify(t)!==JSON.stringify(en.normalizeImportOrderOption(t)))throw Error("API Misuse: getSortedNodesByImportOrder::importOrder option already should be normalized.");let i=[],n=t.reduce((e,t)=>ei(t)?e:{...e,[t]:[]},{}),o=t.filter(e=>!ei(e)&&e!==b);for(let t of e){let e=n[B(t,o)];if(e)e.push(t);else throw Error(`Could not find a matching group in importOrder for: "${t.source.value}" on line ${t.source.loc?.start.line}.${"type"===t.importKind?' Did you forget to include "<TYPES>"?':""}`)}for(let e of t){if(ei(e)){let e=i[i.length-1];if(!e||"ExpressionStatement"===e.type)continue;i.push(P);continue}let t=n[e];if(0===t.length)continue;let o=Z(t,{importOrderCaseSensitive:r});o.forEach(e=>X(e,{importOrderCaseSensitive:r})),i.push(...o)}return i},es=e=>M(e.leadingComments)?"prettier-ignore":0===e.specifiers.length?"side-effect":"type"===e.importKind?C:v;function el(e){return"ImportNamespaceSpecifier"===e.type}function ea(e){return"ImportDefaultSpecifier"===e.type}function ep(e){return"ImportSpecifier"===e.type}function ec(e){h.default("value"===e.importKind||"type"===e.importKind||null===e.importKind),e.importKind="type"}function eu(e){h.default("type"===e.importKind),e.importKind="value",e.specifiers.filter(ep).forEach(ec)}function em(e,t){return e.specifiers.some(el)||t.specifiers.some(el)||e.specifiers.some(ea)&&t.specifiers.some(ea)||"type"===e.importKind&&e.specifiers.some(ea)||"type"===t.importKind&&t.specifiers.some(ea)?null:("type"===e.importKind&&"value"===t.importKind?eu(e):"value"===e.importKind&&"type"===t.importKind&&eu(t),e.specifiers.push(...t.specifiers),e.leadingComments=[...e.leadingComments||[],...t.leadingComments||[]],e.innerComments=[...e.innerComments||[],...t.innerComments||[]],e.trailingComments=[...e.trailingComments||[],...t.trailingComments||[]],e)}const ef=(e,{importOrderCombineTypeAndValueImports:t})=>{let r=[],i={},n=e.reduce((e,t)=>{let r=es(t);return S.includes(r)&&e[r].push(t),e},{[v]:[],[C]:[]});for(let e of S)for(let o of(t||(i={}),n[e]))!function({context:e,nodesToDelete:t,insertableNode:r}){let i=r.source.value,n=e[i];if(n)if(n.start&&r.start&&n.start>r.start){let o=em(r,n);o&&(t.push(n),e[i]=o)}else em(n,r)&&t.push(r);else e[i]=r}({context:i,nodesToDelete:r,insertableNode:o});return e.filter(e=>!r.includes(e))},ed=(e,t)=>{let{importOrder:r,importOrderCombineTypeAndValueImports:i,hasAnyCustomGroupSeparatorsInImportOrder:n,provideGapAfterTopOfFileComments:o}=t,s=e.reduce((e,t)=>{let r=V(t),i=e[e.length-1];return void 0===i||i.type!==r?e.push({type:r,nodes:[t]}):i.nodes.push(t),e},[]),l=[];for(let e of s)if(e.type===y)n?(e.nodes[0].leadingComments?.length||l.push(P),l.push(...e.nodes,P)):l.push(...e.nodes);else{let n=ef(e.nodes,{importOrderCombineTypeAndValueImports:i});r.some(e=>e.includes(E))&&(n=J(n));let o=eo(n,t);l.push(...o)}return l.length>0&&l.push(P),W(e,l,{leadingSeparator:o})};function eg(e,t){let r,{plugins:i,...n}=function(e){let{importOrderParserPlugins:t,filepath:r}=e,{importOrderTypeScriptVersion:i}=e;g.default.valid(i)||(console.warn("[@ianvs/prettier-plugin-sort-imports]: The option importOrderTypeScriptVersion is not a valid semver version and will be ignored."),i="1.0.0");let n=er(e.importOrder),o=!n.some(e=>e.includes(E)),s=ee(t);return r?.endsWith(".ts")&&(s=s.filter(e=>"jsx"!==e)),s.includes("typescript")&&g.default.lt(i,"4.5.0")&&(o=!1),{importOrder:n,importOrderCombineTypeAndValueImports:o,importOrderCaseSensitive:!!e.importOrderCaseSensitive,hasAnyCustomGroupSeparatorsInImportOrder:n.some(ei),provideGapAfterTopOfFileComments:ei(n[0]),plugins:s}}(t),o={sourceType:"module",attachComment:!0,plugins:i};"astro"===t.parentParser&&(o.allowReturnOutsideFunction=!0);try{r=l.parse(e,o)}catch(t){return console.error(" [error] [prettier-plugin-sort-imports]: import sorting aborted due to babel parsing error."),e}let a=r.program.directives,p=r.program.interpreter,c=[];return(f.default(r,{ImportDeclaration(e){e.findParent(e=>s.isTSModuleDeclaration(e.node))||c.push(e.node)}}),0!==c.length&&n.importOrder.length)?x({nodesToOutput:ed(c,n),allOriginalImportNodes:c,originalCode:e,directives:a,interpreter:p}):e}function eh(e,t){return t.filepath?.endsWith(".vue")?e:eg(e,t)}function ey(e){return"ts"===e||"tsx"===e}const ev={babel:{...t.parsers.babel,preprocess:eh},"babel-ts":{...t.parsers["babel-ts"],preprocess:eh},flow:{...r.parsers.flow,preprocess:eh},typescript:{...n.parsers.typescript,preprocess:eh},vue:{...i.parsers.vue,preprocess:function(e,t){try{let{parse:r}=require("@vue/compiler-sfc"),i=require("@vue/compiler-sfc/package.json").version?.split(".")[0],n="2"===i?r({source:e}):r(e).descriptor,o=[n.script,n.scriptSetup].filter(e=>!!e?.content);if(!o.length)return e;o.sort((e,t)=>e.loc.start.offset-t.loc.start.offset);let s=0,l="";for(let r of o){let{start:i,end:n}=r;"loc"in r&&(i=r.loc.start.offset,n=r.loc.end.offset);let o=function({content:e,lang:t},r){let{importOrderParserPlugins:i=[]}=r,n=[...i],o=[];ey(t)&&"tsx"!==t?n=n.filter(e=>"jsx"!==e):o.push("jsx"),o.push(...n),ey(t)&&!et(o,"typescript")&&o.push("typescript");let s={...r,importOrderParserPlugins:o};return` ${eg(e,s)} `}(r,t);l+=e.slice(s,i)+o,s=n}return l+=e.slice(s)}catch(e){throw"MODULE_NOT_FOUND"===e.code&&console.warn('[@ianvs/prettier-plugin-sort-imports]: Could not process .vue file. Please be sure that "@vue/compiler-sfc" is installed in your project.'),e}}}};exports.options={importOrder:{type:"path",category:"Global",array:!0,default:[{value:N}],description:"Provide an order to sort imports. [node.js built-ins are always first]"},importOrderParserPlugins:{type:"path",category:"Global",array:!0,default:[{value:["typescript","jsx"]}],description:"Provide a list of plugins for special syntax"},importOrderTypeScriptVersion:{type:"string",category:"Global",default:"1.0.0",description:"Version of TypeScript in use in the project. Determines some output syntax when using TypeScript."},importOrderCaseSensitive:{type:"boolean",category:"Global",default:!1,description:"Provide a case sensitivity boolean flag"}},exports.parsers=ev;