chunk-ERF3N54S.cjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2. var _chunk6UOGCAOYcjs = require('./chunk-6UOGCAOY.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/resolvers.ts
  30. function normalizeImport(info, name) {
  31. if (typeof info === "string") {
  32. return {
  33. name: "default",
  34. as: name,
  35. from: info
  36. };
  37. }
  38. if ("path" in info) {
  39. return {
  40. from: info.path,
  41. as: info.name,
  42. name: info.importName,
  43. sideEffects: info.sideEffects
  44. };
  45. }
  46. return _chunk6UOGCAOYcjs.__spreadValues.call(void 0, {
  47. name,
  48. as: name
  49. }, info);
  50. }
  51. async function firstMatchedResolver(resolvers, fullname) {
  52. let name = fullname;
  53. for (const resolver of resolvers) {
  54. if (typeof resolver === "object" && resolver.type === "directive") {
  55. if (name.startsWith("v"))
  56. name = name.slice(1);
  57. else
  58. continue;
  59. }
  60. const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
  61. if (resolved)
  62. return normalizeImport(resolved, fullname);
  63. }
  64. }
  65. function resolversAddon(resolvers) {
  66. return {
  67. async matchImports(names, matched) {
  68. if (!resolvers.length)
  69. return;
  70. const dynamic = [];
  71. const sideEffects = [];
  72. await Promise.all([...names].map(async (name) => {
  73. const matchedImport = matched.find((i) => i.as === name);
  74. if (matchedImport) {
  75. if ("sideEffects" in matchedImport)
  76. sideEffects.push(..._utils.toArray.call(void 0, matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
  77. return;
  78. }
  79. const resolved = await firstMatchedResolver(resolvers, name);
  80. if (resolved)
  81. dynamic.push(resolved);
  82. if (resolved == null ? void 0 : resolved.sideEffects)
  83. sideEffects.push(..._utils.toArray.call(void 0, resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
  84. }));
  85. if (dynamic.length) {
  86. this.dynamicImports.push(...dynamic);
  87. this.invalidate();
  88. }
  89. if (dynamic.length || sideEffects.length)
  90. return [...matched, ...dynamic, ...sideEffects];
  91. }
  92. };
  93. }
  94. // src/core/ctx.ts
  95. function resolveGlobsExclude(root, glob) {
  96. const excludeReg = /^!/;
  97. return `${excludeReg.test(glob) ? "!" : ""}${_path.resolve.call(void 0, root, glob.replace(excludeReg, ""))}`;
  98. }
  99. async function scanDirExports(dirs, root) {
  100. const result = await _fastglob2.default.call(void 0, dirs, {
  101. absolute: true,
  102. cwd: root,
  103. onlyFiles: true,
  104. followSymbolicLinks: true
  105. });
  106. const files = Array.from(new Set(result.flat())).map(_utils.slash);
  107. return (await Promise.all(files.map((i) => _unimport.scanExports.call(void 0, i, false)))).flat();
  108. }
  109. function createContext(options = {}, root = _process2.default.cwd()) {
  110. var _a;
  111. const {
  112. dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript")
  113. } = options;
  114. 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)));
  115. const eslintrc = options.eslintrc || {};
  116. eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
  117. eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
  118. eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
  119. const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
  120. const injectAtEnd = options.injectAtEnd !== false;
  121. const unimport = _unimport.createUnimport.call(void 0, {
  122. imports: [],
  123. presets: [],
  124. injectAtEnd,
  125. addons: [
  126. ...options.vueTemplate ? [_addons.vueTemplateAddon.call(void 0, )] : [],
  127. resolversAddon(resolvers),
  128. {
  129. declaration(dts2) {
  130. return `${`
  131. /* eslint-disable */
  132. /* prettier-ignore */
  133. // @ts-nocheck
  134. // noinspection JSUnusedGlobalSymbols
  135. // Generated by unplugin-auto-import
  136. ${dts2}`.trim()}
  137. `;
  138. }
  139. }
  140. ]
  141. });
  142. const importsPromise = flattenImports(options.imports).then((imports) => {
  143. var _a2;
  144. if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
  145. console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
  146. (_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
  147. const i = imports.find((i2) => i2.as === name);
  148. if (i)
  149. i.disabled = true;
  150. });
  151. return unimport.getInternalContext().replaceImports(imports);
  152. });
  153. const filter = _pluginutils.createFilter.call(void 0,
  154. options.include || [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
  155. options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
  156. );
  157. const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
  158. const multilineCommentsRE = new RegExp("\\/\\*.*?\\*\\/", "gms");
  159. const singlelineCommentsRE = /\/\/.*$/gm;
  160. const dtsReg = new RegExp("declare\\s+global\\s*{(.*?)[\\n\\r]}", "s");
  161. function parseDTS(dts2) {
  162. var _a2;
  163. dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
  164. const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
  165. if (!code)
  166. return;
  167. return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
  168. }
  169. async function generateDTS(file) {
  170. await importsPromise;
  171. const dir = _path.dirname.call(void 0, file);
  172. const originalContent = _fs.existsSync.call(void 0, file) ? await _fs.promises.readFile(file, "utf-8") : "";
  173. const originalDTS = parseDTS(originalContent);
  174. const currentContent = await unimport.generateTypeDeclarations({
  175. resolvePath: (i) => {
  176. if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
  177. const related = _utils.slash.call(void 0, _path.relative.call(void 0, dir, i.from).replace(/\.ts(x)?$/, ""));
  178. return !related.startsWith(".") ? `./${related}` : related;
  179. }
  180. return i.from;
  181. }
  182. });
  183. const currentDTS = parseDTS(currentContent);
  184. if (originalDTS) {
  185. Object.keys(currentDTS).forEach((key) => {
  186. originalDTS[key] = currentDTS[key];
  187. });
  188. const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
  189. return currentContent.replace(dtsReg, () => `declare global {
  190. ${dtsList.join("\n")}
  191. }`);
  192. }
  193. return currentContent;
  194. }
  195. async function parseESLint() {
  196. const configStr = _fs.existsSync.call(void 0, eslintrc.filepath) ? await _fs.promises.readFile(eslintrc.filepath, "utf-8") : "";
  197. const config = JSON.parse(configStr || '{ "globals": {} }');
  198. return config.globals;
  199. }
  200. async function generateESLint() {
  201. return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
  202. }
  203. const writeConfigFilesThrottled = _utils.throttle.call(void 0, 500, writeConfigFiles, { noLeading: false });
  204. async function writeFile(filePath, content = "") {
  205. await _fs.promises.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
  206. return await _fs.promises.writeFile(filePath, content, "utf-8");
  207. }
  208. let lastDTS;
  209. let lastESLint;
  210. async function writeConfigFiles() {
  211. const promises = [];
  212. if (dts) {
  213. promises.push(
  214. generateDTS(dts).then((content) => {
  215. if (content !== lastDTS) {
  216. lastDTS = content;
  217. return writeFile(dts, content);
  218. }
  219. })
  220. );
  221. }
  222. if (eslintrc.enabled && eslintrc.filepath) {
  223. promises.push(
  224. generateESLint().then((content) => {
  225. content = `${content}
  226. `;
  227. if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
  228. lastESLint = content;
  229. return writeFile(eslintrc.filepath, content);
  230. }
  231. })
  232. );
  233. }
  234. return Promise.all(promises);
  235. }
  236. async function scanDirs() {
  237. if (dirs == null ? void 0 : dirs.length) {
  238. await unimport.modifyDynamicImports(async (imports) => {
  239. const exports_ = await scanDirExports(dirs, root);
  240. exports_.forEach((i) => i.__source = "dir");
  241. return modifyDefaultExportsAlias([
  242. ...imports.filter((i) => i.__source !== "dir"),
  243. ...exports_
  244. ], options);
  245. });
  246. }
  247. writeConfigFilesThrottled();
  248. }
  249. async function transform(code, id) {
  250. await importsPromise;
  251. const s = new (0, _magicstring2.default)(code);
  252. await unimport.injectImports(s, id);
  253. if (!s.hasChanged())
  254. return;
  255. writeConfigFilesThrottled();
  256. return {
  257. code: s.toString(),
  258. map: s.generateMap({ source: id, includeContent: true, hires: true })
  259. };
  260. }
  261. return {
  262. root,
  263. dirs,
  264. filter,
  265. scanDirs,
  266. writeConfigFiles,
  267. writeConfigFilesThrottled,
  268. transform,
  269. generateDTS,
  270. generateESLint
  271. };
  272. }
  273. async function flattenImports(map) {
  274. const promises = await Promise.all(_utils.toArray.call(void 0, map).map(async (definition) => {
  275. if (typeof definition === "string") {
  276. if (!_chunk6UOGCAOYcjs.presets[definition])
  277. throw new Error(`[auto-import] preset ${definition} not found`);
  278. const preset = _chunk6UOGCAOYcjs.presets[definition];
  279. definition = typeof preset === "function" ? preset() : preset;
  280. }
  281. if ("from" in definition && "imports" in definition) {
  282. return await _unimport.resolvePreset.call(void 0, definition);
  283. } else {
  284. const resolved = [];
  285. for (const mod of Object.keys(definition)) {
  286. for (const id of definition[mod]) {
  287. const meta = {
  288. from: mod
  289. };
  290. if (Array.isArray(id)) {
  291. meta.name = id[0];
  292. meta.as = id[1];
  293. } else {
  294. meta.name = id;
  295. meta.as = id;
  296. }
  297. resolved.push(meta);
  298. }
  299. }
  300. return resolved;
  301. }
  302. }));
  303. return promises.flat();
  304. }
  305. function modifyDefaultExportsAlias(imports, options) {
  306. if (options.defaultExportByFilename) {
  307. imports.forEach((i) => {
  308. var _a, _b, _c;
  309. if (i.name === "default")
  310. i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
  311. });
  312. }
  313. return imports;
  314. }
  315. // src/core/unplugin.ts
  316. var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
  317. let ctx = createContext(options);
  318. return {
  319. name: "unplugin-auto-import",
  320. enforce: "post",
  321. transformInclude(id) {
  322. return ctx.filter(id);
  323. },
  324. async transform(code, id) {
  325. return ctx.transform(code, id);
  326. },
  327. async buildStart() {
  328. await ctx.scanDirs();
  329. },
  330. async buildEnd() {
  331. await ctx.writeConfigFiles();
  332. },
  333. vite: {
  334. async handleHotUpdate({ file }) {
  335. var _a;
  336. 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))))
  337. await ctx.scanDirs();
  338. },
  339. async configResolved(config) {
  340. if (ctx.root !== config.root) {
  341. ctx = createContext(options, config.root);
  342. await ctx.scanDirs();
  343. }
  344. }
  345. }
  346. };
  347. });
  348. exports.unplugin_default = unplugin_default;