You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
372 lines
12 KiB
372 lines
12 KiB
|
2 years ago
|
import {
|
||
|
|
__spreadValues,
|
||
|
|
presets
|
||
|
|
} from "./chunk-UDE7NMNZ.js";
|
||
|
|
|
||
|
|
// src/core/unplugin.ts
|
||
|
|
import { minimatch } from "minimatch";
|
||
|
|
import { slash as slash2 } from "@antfu/utils";
|
||
|
|
import { createUnplugin } from "unplugin";
|
||
|
|
|
||
|
|
// src/core/ctx.ts
|
||
|
|
import { dirname, isAbsolute, posix, relative, resolve, sep } from "path";
|
||
|
|
import { promises as fs } from "fs";
|
||
|
|
import { slash, throttle, toArray as toArray2 } from "@antfu/utils";
|
||
|
|
import { createFilter } from "@rollup/pluginutils";
|
||
|
|
import { isPackageExists } from "local-pkg";
|
||
|
|
import { createUnimport, resolvePreset, scanDirExports } from "unimport";
|
||
|
|
import { vueTemplateAddon } from "unimport/addons";
|
||
|
|
import MagicString from "magic-string";
|
||
|
|
|
||
|
|
// src/core/eslintrc.ts
|
||
|
|
function generateESLintConfigs(imports, eslintrc) {
|
||
|
|
const eslintConfigs = { globals: {} };
|
||
|
|
imports.map((i) => {
|
||
|
|
var _a;
|
||
|
|
return (_a = i.as) != null ? _a : i.name;
|
||
|
|
}).filter(Boolean).sort().forEach((name) => {
|
||
|
|
eslintConfigs.globals[name] = eslintrc.globalsPropValue || true;
|
||
|
|
});
|
||
|
|
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
|
||
|
|
return jsonBody;
|
||
|
|
}
|
||
|
|
|
||
|
|
// src/core/resolvers.ts
|
||
|
|
import { toArray } from "@antfu/utils";
|
||
|
|
function normalizeImport(info, name) {
|
||
|
|
if (typeof info === "string") {
|
||
|
|
return {
|
||
|
|
name: "default",
|
||
|
|
as: name,
|
||
|
|
from: info
|
||
|
|
};
|
||
|
|
}
|
||
|
|
if ("path" in info) {
|
||
|
|
return {
|
||
|
|
from: info.path,
|
||
|
|
as: info.name,
|
||
|
|
name: info.importName,
|
||
|
|
sideEffects: info.sideEffects
|
||
|
|
};
|
||
|
|
}
|
||
|
|
return __spreadValues({
|
||
|
|
name,
|
||
|
|
as: name
|
||
|
|
}, info);
|
||
|
|
}
|
||
|
|
async function firstMatchedResolver(resolvers, fullname) {
|
||
|
|
let name = fullname;
|
||
|
|
for (const resolver of resolvers) {
|
||
|
|
if (typeof resolver === "object" && resolver.type === "directive") {
|
||
|
|
if (name.startsWith("v"))
|
||
|
|
name = name.slice(1);
|
||
|
|
else
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
|
||
|
|
if (resolved)
|
||
|
|
return normalizeImport(resolved, fullname);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
function resolversAddon(resolvers) {
|
||
|
|
return {
|
||
|
|
async matchImports(names, matched) {
|
||
|
|
if (!resolvers.length)
|
||
|
|
return;
|
||
|
|
const dynamic = [];
|
||
|
|
const sideEffects = [];
|
||
|
|
await Promise.all([...names].map(async (name) => {
|
||
|
|
const matchedImport = matched.find((i) => i.as === name);
|
||
|
|
if (matchedImport) {
|
||
|
|
if ("sideEffects" in matchedImport)
|
||
|
|
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
const resolved = await firstMatchedResolver(resolvers, name);
|
||
|
|
if (resolved)
|
||
|
|
dynamic.push(resolved);
|
||
|
|
if (resolved == null ? void 0 : resolved.sideEffects)
|
||
|
|
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
|
||
|
|
}));
|
||
|
|
if (dynamic.length) {
|
||
|
|
this.dynamicImports.push(...dynamic);
|
||
|
|
this.invalidate();
|
||
|
|
}
|
||
|
|
if (dynamic.length || sideEffects.length)
|
||
|
|
return [...matched, ...dynamic, ...sideEffects];
|
||
|
|
}
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
// src/core/ctx.ts
|
||
|
|
function createContext(options = {}, root = process.cwd()) {
|
||
|
|
var _a;
|
||
|
|
const {
|
||
|
|
dts: preferDTS = isPackageExists("typescript"),
|
||
|
|
cache: isCache = false
|
||
|
|
} = options;
|
||
|
|
const dirs = (_a = options.dirs) == null ? void 0 : _a.map((dir) => resolve(root, dir));
|
||
|
|
const eslintrc = options.eslintrc || {};
|
||
|
|
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
|
||
|
|
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
|
||
|
|
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
|
||
|
|
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
|
||
|
|
const cachePath = isCache === false ? false : resolve(root, typeof isCache === "string" ? isCache : "node_modules/.cache/unplugin-auto-import.json");
|
||
|
|
const injectAtEnd = options.injectAtEnd !== false;
|
||
|
|
const unimport = createUnimport({
|
||
|
|
imports: [],
|
||
|
|
presets: [],
|
||
|
|
injectAtEnd,
|
||
|
|
addons: [
|
||
|
|
...options.vueTemplate ? [vueTemplateAddon()] : [],
|
||
|
|
resolversAddon(resolvers),
|
||
|
|
{
|
||
|
|
declaration(dts2) {
|
||
|
|
return `${`
|
||
|
|
/* eslint-disable */
|
||
|
|
/* prettier-ignore */
|
||
|
|
// @ts-nocheck
|
||
|
|
// Generated by unplugin-auto-import
|
||
|
|
${dts2}`.trim()}
|
||
|
|
`;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
]
|
||
|
|
});
|
||
|
|
const importsPromise = flattenImports(options.imports).then((imports) => {
|
||
|
|
var _a2;
|
||
|
|
if (!imports.length && !resolvers.length)
|
||
|
|
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
|
||
|
|
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
|
||
|
|
const i = imports.find((i2) => i2.as === name);
|
||
|
|
if (i)
|
||
|
|
i.disabled = true;
|
||
|
|
});
|
||
|
|
return unimport.getInternalContext().replaceImports(imports);
|
||
|
|
});
|
||
|
|
const filter = createFilter(
|
||
|
|
options.include || [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
|
||
|
|
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
|
||
|
|
);
|
||
|
|
const dts = preferDTS === false ? false : preferDTS === true ? resolve(root, "auto-imports.d.ts") : resolve(root, preferDTS);
|
||
|
|
async function generateDTS(file) {
|
||
|
|
await importsPromise;
|
||
|
|
const dir = dirname(file);
|
||
|
|
return unimport.generateTypeDeclarations({
|
||
|
|
resolvePath: (i) => {
|
||
|
|
if (i.from.startsWith(".") || isAbsolute(i.from)) {
|
||
|
|
const related = slash(relative(dir, i.from).replace(/\.ts(x)?$/, ""));
|
||
|
|
return !related.startsWith(".") ? `./${related}` : related;
|
||
|
|
}
|
||
|
|
return i.from;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
async function generateESLint() {
|
||
|
|
return generateESLintConfigs(await unimport.getImports(), eslintrc);
|
||
|
|
}
|
||
|
|
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
|
||
|
|
const writeFileThrottled = throttle(500, writeFile, { noLeading: false });
|
||
|
|
async function writeFile(filePath, content = "") {
|
||
|
|
await fs.mkdir(dirname(filePath), { recursive: true });
|
||
|
|
return await fs.writeFile(filePath, content, "utf-8");
|
||
|
|
}
|
||
|
|
let lastDTS;
|
||
|
|
let lastESLint;
|
||
|
|
async function writeConfigFiles() {
|
||
|
|
const promises = [];
|
||
|
|
if (dts) {
|
||
|
|
promises.push(
|
||
|
|
generateDTS(dts).then((content) => {
|
||
|
|
if (content !== lastDTS) {
|
||
|
|
lastDTS = content;
|
||
|
|
return writeFile(dts, content);
|
||
|
|
}
|
||
|
|
})
|
||
|
|
);
|
||
|
|
}
|
||
|
|
if (eslintrc.enabled && eslintrc.filepath) {
|
||
|
|
promises.push(
|
||
|
|
generateESLint().then((content) => {
|
||
|
|
if (content !== lastESLint) {
|
||
|
|
lastESLint = `${content}
|
||
|
|
`;
|
||
|
|
return writeFile(eslintrc.filepath, content);
|
||
|
|
}
|
||
|
|
})
|
||
|
|
);
|
||
|
|
}
|
||
|
|
return Promise.all(promises);
|
||
|
|
}
|
||
|
|
async function scanDirs() {
|
||
|
|
if (dirs == null ? void 0 : dirs.length) {
|
||
|
|
await unimport.modifyDynamicImports(async (imports) => {
|
||
|
|
const exports = await scanDirExports(dirs, {
|
||
|
|
filePatterns: ["*.{tsx,jsx,ts,js,mjs,cjs,mts,cts}"]
|
||
|
|
});
|
||
|
|
exports.forEach((i) => i.__source = "dir");
|
||
|
|
return modifyDefaultExportsAlias([
|
||
|
|
...imports.filter((i) => i.__source !== "dir"),
|
||
|
|
...exports
|
||
|
|
], options);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
writeConfigFilesThrottled();
|
||
|
|
}
|
||
|
|
async function getCacheData(cache) {
|
||
|
|
const str = (await fs.readFile(cache, "utf-8")).trim();
|
||
|
|
return JSON.parse(str || "{}");
|
||
|
|
}
|
||
|
|
async function generateCache() {
|
||
|
|
if (!cachePath)
|
||
|
|
return {};
|
||
|
|
let cacheData = {};
|
||
|
|
try {
|
||
|
|
cacheData = await getCacheData(cachePath);
|
||
|
|
await Promise.allSettled(Object.keys(cacheData).map(async (filePath) => {
|
||
|
|
try {
|
||
|
|
const normalizeRoot = root.replaceAll(sep, posix.sep);
|
||
|
|
await fs.access(posix.join(normalizeRoot, filePath));
|
||
|
|
} catch (e) {
|
||
|
|
Reflect.deleteProperty(cacheData, filePath);
|
||
|
|
}
|
||
|
|
}));
|
||
|
|
await writeFile(cachePath, JSON.stringify(cacheData, null, 2));
|
||
|
|
} catch (e) {
|
||
|
|
await writeFile(cachePath, "{}");
|
||
|
|
}
|
||
|
|
return cacheData;
|
||
|
|
}
|
||
|
|
let isInitialCache = false;
|
||
|
|
const resolveCachePromise = generateCache();
|
||
|
|
async function updateCacheImports(id, importList) {
|
||
|
|
if (!cachePath || isInitialCache && !id)
|
||
|
|
return;
|
||
|
|
isInitialCache = true;
|
||
|
|
const cacheData = await resolveCachePromise;
|
||
|
|
await unimport.modifyDynamicImports(async (imports) => {
|
||
|
|
if (id && importList) {
|
||
|
|
const filePath = posix.normalize(posix.relative(root, id));
|
||
|
|
importList = importList.filter((i) => {
|
||
|
|
var _a2;
|
||
|
|
return ((_a2 = i.name) != null ? _a2 : i.as) && i.name !== "default";
|
||
|
|
});
|
||
|
|
if (importList.length)
|
||
|
|
cacheData[filePath] = importList;
|
||
|
|
else
|
||
|
|
delete cacheData[filePath];
|
||
|
|
writeFileThrottled(cachePath, JSON.stringify(cacheData, null, 2));
|
||
|
|
return imports.concat(importList);
|
||
|
|
}
|
||
|
|
return imports.concat(Object.values(cacheData).reduce((p, n) => p.concat(n), []));
|
||
|
|
});
|
||
|
|
}
|
||
|
|
async function transform(code, id) {
|
||
|
|
await importsPromise;
|
||
|
|
const s = new MagicString(code);
|
||
|
|
const res = await unimport.injectImports(s, id);
|
||
|
|
await updateCacheImports(id, res.imports);
|
||
|
|
if (!s.hasChanged())
|
||
|
|
return;
|
||
|
|
writeConfigFilesThrottled();
|
||
|
|
return {
|
||
|
|
code: s.toString(),
|
||
|
|
map: s.generateMap({ source: id, includeContent: true })
|
||
|
|
};
|
||
|
|
}
|
||
|
|
return {
|
||
|
|
root,
|
||
|
|
dirs,
|
||
|
|
filter,
|
||
|
|
scanDirs,
|
||
|
|
updateCacheImports,
|
||
|
|
writeConfigFiles,
|
||
|
|
writeConfigFilesThrottled,
|
||
|
|
transform,
|
||
|
|
generateDTS,
|
||
|
|
generateESLint
|
||
|
|
};
|
||
|
|
}
|
||
|
|
async function flattenImports(map) {
|
||
|
|
const promises = await Promise.all(toArray2(map).map(async (definition) => {
|
||
|
|
if (typeof definition === "string") {
|
||
|
|
if (!presets[definition])
|
||
|
|
throw new Error(`[auto-import] preset ${definition} not found`);
|
||
|
|
const preset = presets[definition];
|
||
|
|
definition = typeof preset === "function" ? preset() : preset;
|
||
|
|
}
|
||
|
|
if ("from" in definition && "imports" in definition) {
|
||
|
|
return await resolvePreset(definition);
|
||
|
|
} else {
|
||
|
|
const resolved = [];
|
||
|
|
for (const mod of Object.keys(definition)) {
|
||
|
|
for (const id of definition[mod]) {
|
||
|
|
const meta = {
|
||
|
|
from: mod
|
||
|
|
};
|
||
|
|
if (Array.isArray(id)) {
|
||
|
|
meta.name = id[0];
|
||
|
|
meta.as = id[1];
|
||
|
|
} else {
|
||
|
|
meta.name = id;
|
||
|
|
meta.as = id;
|
||
|
|
}
|
||
|
|
resolved.push(meta);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return resolved;
|
||
|
|
}
|
||
|
|
}));
|
||
|
|
return promises.flat();
|
||
|
|
}
|
||
|
|
function modifyDefaultExportsAlias(imports, options) {
|
||
|
|
if (options.defaultExportByFilename) {
|
||
|
|
imports.forEach((i) => {
|
||
|
|
var _a, _b, _c;
|
||
|
|
if (i.name === "default")
|
||
|
|
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
|
||
|
|
});
|
||
|
|
}
|
||
|
|
return imports;
|
||
|
|
}
|
||
|
|
|
||
|
|
// src/core/unplugin.ts
|
||
|
|
var unplugin_default = createUnplugin((options) => {
|
||
|
|
let ctx = createContext(options);
|
||
|
|
return {
|
||
|
|
name: "unplugin-auto-import",
|
||
|
|
enforce: "post",
|
||
|
|
transformInclude(id) {
|
||
|
|
return ctx.filter(id);
|
||
|
|
},
|
||
|
|
async transform(code, id) {
|
||
|
|
return ctx.transform(code, id);
|
||
|
|
},
|
||
|
|
async buildStart() {
|
||
|
|
await ctx.scanDirs();
|
||
|
|
await ctx.updateCacheImports();
|
||
|
|
await ctx.writeConfigFiles();
|
||
|
|
},
|
||
|
|
async buildEnd() {
|
||
|
|
await ctx.writeConfigFiles();
|
||
|
|
},
|
||
|
|
vite: {
|
||
|
|
async handleHotUpdate({ file }) {
|
||
|
|
var _a;
|
||
|
|
if ((_a = ctx.dirs) == null ? void 0 : _a.some((glob) => minimatch(slash2(file), glob)))
|
||
|
|
await ctx.scanDirs();
|
||
|
|
},
|
||
|
|
async configResolved(config) {
|
||
|
|
if (ctx.root !== config.root) {
|
||
|
|
ctx = createContext(options, config.root);
|
||
|
|
await ctx.scanDirs();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
});
|
||
|
|
|
||
|
|
export {
|
||
|
|
unplugin_default
|
||
|
|
};
|