UNPKG

unplugin-export-collector

Version:

Recursively get all named export from a file and out-of-the-box support unplugin-auto-import

81 lines (72 loc) 5.66 kB
import u from"node:process";import{promises as f,existsSync as g}from"node:fs";import{normalize as O,resolve as l,toNamespacedPath as L,join as S,dirname as T,extname as C}from"pathe";import{parse as P}from"@swc/core";import{isFunction as k,isUndefined as F,p as I}from"@s3xysteak/utils";async function A(n){return(await f.stat(n)).isDirectory()}async function J(n,t){const e=l(t??u.cwd(),n),r=g(e)&&await A(e)?l(e,"index"):e,s=E(r,t);if(F(s))throw new Error(`File not found: ${r}`);return r+s}async function w(n){const t=n?O(n):l(u.cwd(),"./package.json"),e=await f.readFile(t,"utf-8").then(s=>JSON.parse(s)),r=!!(e?.devDependencies?.typescript||e?.dependencies?.typescript);return{raw:e,isTs:r}}function E(n,t=u.cwd()){const e=l(t,n);return["",".mjs",".js",".mts",".ts",".jsx",".tsx",".json"].find(r=>g(e+r))}function K(n,t=u.cwd()){return n+E(n,t)}function z(n){return k(n)?n():n}const G=new Set(["/","\\",void 0]),$=Symbol.for("pathe:normalizedAlias");function V(n){if(n[$])return n;const t=Object.fromEntries(Object.entries(n).sort(([e],[r])=>M(e,r)));for(const e in t)for(const r in t)r===e||e.startsWith(r)||t[e].startsWith(r)&&G.has(t[e][r.length])&&(t[e]=t[r]+t[e].slice(r.length));return Object.defineProperty(t,$,{value:!0,enumerable:!1}),t}function W(n,t){const e=L(n);t=V(t);for(const[r,s]of Object.entries(t)){if(!e.startsWith(r))continue;const o=h(r)?r.slice(0,-1):r;if(h(e[o.length]))return S(s,e.slice(r.length))}return e}function M(n,t){return t.split("/").length-n.split("/").length}function h(n="/"){const t=n[n.length-1];return t==="/"||t==="\\"}async function v(n,t){const{base:e,alias:r={}}=t??{},s=new Set,o=async(a,i)=>{const p=await J(a,i),d=await f.readFile(p,"utf-8"),{exp:y,refer:m}=await _(d);y.forEach(c=>s.add(c)),await I(m,{concurrency:Number.POSITIVE_INFINITY}).forEach(async c=>await o(W(c,r),T(p)))};return await o(n,e??u.cwd()),Array.from(s)}async function _(n){const t=[],e=[],{raw:r,isTs:s}=await w();(await P(n,{syntax:s?"typescript":"ecmascript",target:"es2020"})).body.forEach(a=>{a.type==="ExportAllDeclaration"&&e.push(a.source.value),a.type==="ExportNamedDeclaration"&&a.specifiers.forEach(i=>{i.type==="ExportSpecifier"&&t.push(i?.exported?.value??i.orig.value),i.type==="ExportNamespaceSpecifier"&&e.push(i.name.value)}),a.type==="ExportDeclaration"&&(a.declaration.type==="VariableDeclaration"&&a.declaration.declarations.forEach(i=>i.id.type==="Identifier"&&t.push(i.id.value)),a.declaration.type==="FunctionDeclaration"&&t.push(a.declaration.identifier.value),a.declaration.type==="ClassDeclaration"&&t.push(a.declaration.identifier.value))});const o=[...Object.keys(r.dependencies??{}),...Object.keys(r.devDependencies??{})];return{exp:t,refer:e.filter(a=>!o.includes(a))}}const b="// --- Auto-Generated By Unplugin-Export-Collector ---";function R(n,t,e,r){return{ts:` const __UnExportList = ${JSON.stringify(n)} as const /** * @returns Call in \`imports\` option of \`unplugin-auto-import\`. */ ${r?"export default":"export"} function ${e}(map?: Partial<{ [K in typeof __UnExportList[number]]: string }>): Record<string, (string | [string, string])[]> { return { '${t}': __UnExportList.map(v => map && map[v] ? [v, map[v]] as [string, string] : v), } } `,js:` const __UnExportList = /** @type {const} */ (${JSON.stringify(n)}) /** * @param {Partial<{ [K in typeof __UnExportList[number]]: string }>} [map] * @returns {Record<string, (string | [string, string])[]>} Call in \`imports\` option of \`unplugin-auto-import\`. */ ${r?"export default":"export"} function ${e}(map) { return { '${t}': __UnExportList.map(v => map && map[v] ? [v, map[v]] : v), } } `}}function B(n,t,e,r){return{ts:` const __UnExportList = ${JSON.stringify(n)} as const /** * @returns Call in \`resolvers\` option of \`unplugin-auto-import\`. */ ${r?"export default":"export"} function ${e}(map?: Partial<{ [K in typeof __UnExportList[number]]: string }>) { return (name: string) => { if (!__UnExportList.includes(name as any)) return return map && (map as any)[name] ? { name, as: (map as any)[name], from: '${t}', } : { name, from: '${t}', } } } `,js:` const __UnExportList = /** @type {const} */ (${JSON.stringify(n)}) /** * @param {Partial<{ [K in typeof __UnExportList[number]]: string }>} [map] * @returns Call in \`resolvers\` option of \`unplugin-auto-import\`. */ ${r?"export default":"export"} function ${e}(map) { /** @param {string} name */ const func = (name) => { if (!__UnExportList.includes(name)) return return map && map[name] ? { name, as: map[name], from: '${t}', } : { name, from: '${t}', } } return func } `}}async function Y(n,t={}){const{data:e,pkgContext:{isTs:r}}=await j(n,t),{type:s,base:o,typescript:a=r,writeTo:i=`./src/${s}.${a?"ts":"js"}`}=D(t);return await f.writeFile(l(o,C(i)?i:`${i}.${a?"ts":"js"}`),e)}async function j(n,t={}){const{raw:e,isTs:r}=await w(),{base:s,include:o,exclude:a,rename:i,exportDefault:p,alias:d,type:y,typescript:m=r,pkgName:c=e.name}=D(t);a.push(i);const x=[...await v(n,{base:s,alias:d}),...o].filter(N=>!a.includes(N)).sort(),U=y==="imports"?R(x,c,i,p)[m?"ts":"js"]:B(x,c,i,p)[m?"ts":"js"];return{data:`${` ${b} ${U.trim()} ${b} `.trim()} `,pkgContext:{pkg:e,isTs:r}}}function D(n={}){const{type:t="imports",base:e=u.cwd(),include:r=[],exclude:s=[],rename:o="autoImport",exportDefault:a=!0,alias:i,...p}=n;return{type:t,base:e,include:r,exclude:s,rename:o,exportDefault:a,alias:i,...p}}export{K as a,v as b,j as c,Y as e,_ as p,z as t};