chunk-CXITMYZH.cjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2. var _chunk53W4H52Qcjs = require('./chunk-53W4H52Q.cjs');
  3. // src/core/unplugin.ts
  4. var _minimatch = require('minimatch');
  5. var _utils = require('@antfu/utils');
  6. var _unplugin = require('unplugin');
  7. // src/core/ctx.ts
  8. var _path = require('path');
  9. var _fs = require('fs');
  10. var _process = require('process'); var _process2 = _interopRequireDefault(_process);
  11. var _pluginutils = require('@rollup/pluginutils');
  12. var _localpkg = require('local-pkg');
  13. var _unimport = require('unimport');
  14. var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
  15. var _addons = require('unimport/addons');
  16. var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
  17. // src/core/eslintrc.ts
  18. function generateESLintConfigs(imports, eslintrc, globals = {}) {
  19. const eslintConfigs = { globals };
  20. imports.map((i) => {
  21. var _a;
  22. return (_a = i.as) != null ? _a : i.name;
  23. }).filter(Boolean).sort().forEach((name) => {
  24. eslintConfigs.globals[name] = eslintrc.globalsPropValue;
  25. });
  26. const jsonBody = JSON.stringify(eslintConfigs, null, 2);
  27. return jsonBody;
  28. }
  29. // src/core/biomelintrc.ts
  30. function generateBiomeLintConfigs(imports) {
  31. const names = imports.map((i) => {
  32. var _a;
  33. return (_a = i.as) != null ? _a : i.name;
  34. }).filter(Boolean).sort();
  35. const config = { javascript: { globals: names } };
  36. const jsonBody = JSON.stringify(config, null, 2);
  37. return jsonBody;
  38. }
  39. // src/core/resolvers.ts
  40. function normalizeImport(info, name) {
  41. if (typeof info === "string") {
  42. return {
  43. name: "default",
  44. as: name,
  45. from: info
  46. };
  47. }
  48. if ("path" in info) {
  49. return {
  50. from: info.path,
  51. as: info.name,
  52. name: info.importName,
  53. sideEffects: info.sideEffects
  54. };
  55. }
  56. return {
  57. name,
  58. as: name,
  59. ...info
  60. };
  61. }
  62. async function firstMatchedResolver(resolvers, fullname) {
  63. let name = fullname;
  64. for (const resolver of resolvers) {
  65. if (typeof resolver === "object" && resolver.type === "directive") {
  66. if (name.startsWith("v"))
  67. name = name.slice(1);
  68. else
  69. continue;
  70. }
  71. const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
  72. if (resolved)
  73. return normalizeImport(resolved, fullname);
  74. }
  75. }
  76. function resolversAddon(resolvers) {
  77. return {
  78. async matchImports(names, matched) {
  79. if (!resolvers.length)
  80. return;
  81. const dynamic = [];
  82. const sideEffects = [];
  83. await Promise.all([...names].map(async (name) => {
  84. const matchedImport = matched.find((i) => i.as === name);
  85. if (matchedImport) {
  86. if ("sideEffects" in matchedImport)
  87. sideEffects.push(..._utils.toArray.call(void 0, matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
  88. return;
  89. }
  90. const resolved = await firstMatchedResolver(resolvers, name);
  91. if (resolved)
  92. dynamic.push(resolved);
  93. if (resolved == null ? void 0 : resolved.sideEffects)
  94. sideEffects.push(..._utils.toArray.call(void 0, resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
  95. }));
  96. if (dynamic.length) {
  97. this.dynamicImports.push(...dynamic);
  98. this.invalidate();
  99. }
  100. if (dynamic.length || sideEffects.length)
  101. return [...matched, ...dynamic, ...sideEffects];
  102. }
  103. };
  104. }
  105. // src/core/ctx.ts
  106. function resolveGlobsExclude(root, glob) {
  107. const excludeReg = /^!/;
  108. return `${excludeReg.test(glob) ? "!" : ""}${_path.resolve.call(void 0, root, glob.replace(excludeReg, ""))}`;
  109. }
  110. async function scanDirExports(dirs, root) {
  111. const result = await _fastglob2.default.call(void 0, dirs, {
  112. absolute: true,
  113. cwd: root,
  114. onlyFiles: true,
  115. followSymbolicLinks: true
  116. });
  117. const files = Array.from(new Set(result.flat())).map(_utils.slash);
  118. return (await Promise.all(files.map((i) => _unimport.scanExports.call(void 0, i, false)))).flat();
  119. }
  120. function createContext(options = {}, root = _process2.default.cwd()) {
  121. var _a, _b, _c;
  122. root = _utils.slash.call(void 0, root);
  123. const {
  124. dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript")
  125. } = options;
  126. const dirs = (_a = options.dirs) == null ? void 0 : _a.concat(options.dirs.map((dir) => _path.join.call(void 0, dir, "*.{tsx,jsx,ts,js,mjs,cjs,mts,cts}"))).map((dir) => _utils.slash.call(void 0, resolveGlobsExclude(root, dir)));
  127. const eslintrc = options.eslintrc || {};
  128. eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
  129. eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
  130. eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
  131. const biomelintrc = options.biomelintrc || {};
  132. biomelintrc.enabled = biomelintrc.enabled !== void 0;
  133. biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
  134. const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
  135. const injectAtEnd = options.injectAtEnd !== false;
  136. const unimport = _unimport.createUnimport.call(void 0, {
  137. imports: [],
  138. presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
  139. injectAtEnd,
  140. parser: options.parser,
  141. addons: [
  142. ...options.vueTemplate ? [_addons.vueTemplateAddon.call(void 0, )] : [],
  143. resolversAddon(resolvers),
  144. {
  145. declaration(dts2) {
  146. return `${`
  147. /* eslint-disable */
  148. /* prettier-ignore */
  149. // @ts-nocheck
  150. // noinspection JSUnusedGlobalSymbols
  151. // Generated by unplugin-auto-import
  152. ${dts2}`.trim()}
  153. `;
  154. }
  155. }
  156. ]
  157. });
  158. const importsPromise = flattenImports(options.imports).then((imports) => {
  159. var _a2, _b2;
  160. if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
  161. console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
  162. const compare = (left, right) => {
  163. return right instanceof RegExp ? right.test(left) : right === left;
  164. };
  165. (_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
  166. const i = imports.find((i2) => compare(i2.as, name));
  167. if (i)
  168. i.disabled = true;
  169. });
  170. (_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
  171. const i = imports.find((i2) => compare(i2.as, name));
  172. if (i)
  173. i.dtsDisabled = true;
  174. });
  175. return unimport.getInternalContext().replaceImports(imports);
  176. });
  177. const filter = _pluginutils.createFilter.call(void 0,
  178. options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
  179. options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
  180. );
  181. const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
  182. const multilineCommentsRE = /\/\*.*?\*\//gs;
  183. const singlelineCommentsRE = /\/\/.*$/gm;
  184. const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
  185. const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
  186. function parseDTS(dts2) {
  187. var _a2;
  188. dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
  189. const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
  190. if (!code)
  191. return;
  192. return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
  193. }
  194. async function generateDTS(file) {
  195. await importsPromise;
  196. const dir = _path.dirname.call(void 0, file);
  197. const originalContent = _fs.existsSync.call(void 0, file) ? await _fs.promises.readFile(file, "utf-8") : "";
  198. const originalDTS = parseDTS(originalContent);
  199. let currentContent = await unimport.generateTypeDeclarations({
  200. resolvePath: (i) => {
  201. if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
  202. const related = _utils.slash.call(void 0, _path.relative.call(void 0, dir, i.from).replace(/\.ts(x)?$/, ""));
  203. return !related.startsWith(".") ? `./${related}` : related;
  204. }
  205. return i.from;
  206. }
  207. });
  208. const currentDTS = parseDTS(currentContent);
  209. if (options.vueTemplate) {
  210. currentContent = currentContent.replace(
  211. componentCustomPropertiesReg,
  212. ($1) => `interface GlobalComponents {}
  213. ${$1}`
  214. );
  215. }
  216. if (originalDTS) {
  217. Object.keys(currentDTS).forEach((key) => {
  218. originalDTS[key] = currentDTS[key];
  219. });
  220. const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
  221. return currentContent.replace(dtsReg, () => `declare global {
  222. ${dtsList.join("\n")}
  223. }`);
  224. }
  225. return currentContent;
  226. }
  227. async function parseESLint() {
  228. if (!eslintrc.filepath)
  229. return {};
  230. if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
  231. return {};
  232. const configStr = _fs.existsSync.call(void 0, eslintrc.filepath) ? await _fs.promises.readFile(eslintrc.filepath, "utf-8") : "";
  233. const config = JSON.parse(configStr || '{ "globals": {} }');
  234. return config.globals;
  235. }
  236. async function generateESLint() {
  237. return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
  238. }
  239. async function generateBiomeLint() {
  240. return generateBiomeLintConfigs(await unimport.getImports());
  241. }
  242. const writeConfigFilesThrottled = _utils.throttle.call(void 0, 500, writeConfigFiles, { noLeading: false });
  243. async function writeFile(filePath, content = "") {
  244. await _fs.promises.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
  245. return await _fs.promises.writeFile(filePath, content, "utf-8");
  246. }
  247. let lastDTS;
  248. let lastESLint;
  249. let lastBiomeLint;
  250. async function writeConfigFiles() {
  251. const promises = [];
  252. if (dts) {
  253. promises.push(
  254. generateDTS(dts).then((content) => {
  255. if (content !== lastDTS) {
  256. lastDTS = content;
  257. return writeFile(dts, content);
  258. }
  259. })
  260. );
  261. }
  262. if (eslintrc.enabled && eslintrc.filepath) {
  263. const filepath = eslintrc.filepath;
  264. promises.push(
  265. generateESLint().then(async (content) => {
  266. if (filepath.endsWith(".cjs"))
  267. content = `module.exports = ${content}`;
  268. else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
  269. content = `export default ${content}`;
  270. content = `${content}
  271. `;
  272. if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
  273. lastESLint = content;
  274. return writeFile(eslintrc.filepath, content);
  275. }
  276. })
  277. );
  278. }
  279. if (biomelintrc.enabled) {
  280. promises.push(
  281. generateBiomeLint().then((content) => {
  282. if (content !== lastBiomeLint) {
  283. lastBiomeLint = content;
  284. return writeFile(biomelintrc.filepath, content);
  285. }
  286. })
  287. );
  288. }
  289. return Promise.all(promises);
  290. }
  291. async function scanDirs() {
  292. if (dirs == null ? void 0 : dirs.length) {
  293. await unimport.modifyDynamicImports(async (imports) => {
  294. const exports_ = await scanDirExports(dirs, root);
  295. exports_.forEach((i) => i.__source = "dir");
  296. return modifyDefaultExportsAlias([
  297. ...imports.filter((i) => i.__source !== "dir"),
  298. ...exports_
  299. ], options);
  300. });
  301. }
  302. writeConfigFilesThrottled();
  303. }
  304. async function transform(code, id) {
  305. await importsPromise;
  306. const s = new (0, _magicstring2.default)(code);
  307. await unimport.injectImports(s, id);
  308. if (!s.hasChanged())
  309. return;
  310. writeConfigFilesThrottled();
  311. return {
  312. code: s.toString(),
  313. map: s.generateMap({ source: id, includeContent: true, hires: true })
  314. };
  315. }
  316. return {
  317. root,
  318. dirs,
  319. filter,
  320. scanDirs,
  321. writeConfigFiles,
  322. writeConfigFilesThrottled,
  323. transform,
  324. generateDTS,
  325. generateESLint,
  326. unimport
  327. };
  328. }
  329. async function flattenImports(map) {
  330. const promises = await Promise.all(_utils.toArray.call(void 0, map).map(async (definition) => {
  331. if (typeof definition === "string") {
  332. if (!_chunk53W4H52Qcjs.presets[definition])
  333. throw new Error(`[auto-import] preset ${definition} not found`);
  334. const preset = _chunk53W4H52Qcjs.presets[definition];
  335. definition = typeof preset === "function" ? preset() : preset;
  336. }
  337. if ("from" in definition && "imports" in definition) {
  338. return await _unimport.resolvePreset.call(void 0, definition);
  339. } else {
  340. const resolved = [];
  341. for (const mod of Object.keys(definition)) {
  342. for (const id of definition[mod]) {
  343. const meta = {
  344. from: mod
  345. };
  346. if (Array.isArray(id)) {
  347. meta.name = id[0];
  348. meta.as = id[1];
  349. } else {
  350. meta.name = id;
  351. meta.as = id;
  352. }
  353. resolved.push(meta);
  354. }
  355. }
  356. return resolved;
  357. }
  358. }));
  359. return promises.flat();
  360. }
  361. function modifyDefaultExportsAlias(imports, options) {
  362. if (options.defaultExportByFilename) {
  363. imports.forEach((i) => {
  364. var _a, _b, _c;
  365. if (i.name === "default")
  366. i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
  367. });
  368. }
  369. return imports;
  370. }
  371. // src/core/unplugin.ts
  372. var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
  373. let ctx = createContext(options);
  374. return {
  375. name: "unplugin-auto-import",
  376. enforce: "post",
  377. transformInclude(id) {
  378. return ctx.filter(id);
  379. },
  380. async transform(code, id) {
  381. return ctx.transform(code, id);
  382. },
  383. async buildStart() {
  384. await ctx.scanDirs();
  385. },
  386. async buildEnd() {
  387. await ctx.writeConfigFiles();
  388. },
  389. vite: {
  390. async config(config) {
  391. var _a;
  392. if (!options.viteOptimizeDeps)
  393. return;
  394. const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
  395. const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i)));
  396. if (!imports.size)
  397. return;
  398. return {
  399. optimizeDeps: {
  400. include: [...imports]
  401. }
  402. };
  403. },
  404. async handleHotUpdate({ file }) {
  405. var _a;
  406. if ((_a = ctx.dirs) == null ? void 0 : _a.some((glob) => _minimatch.minimatch.call(void 0, _utils.slash.call(void 0, file), _utils.slash.call(void 0, glob))))
  407. await ctx.scanDirs();
  408. },
  409. async configResolved(config) {
  410. if (ctx.root !== config.root) {
  411. ctx = createContext(options, config.root);
  412. await ctx.scanDirs();
  413. }
  414. }
  415. }
  416. };
  417. });
  418. exports.unplugin_default = unplugin_default;