unimport.2cd87f74.mjs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. import { V as VUE_TEMPLATE_NAME, v as vueTemplateAddon, q as VUE_DIRECTIVES_NAME, u as vueDirectivesAddon, l as getMagicString, a as stripCommentsAndStrings, m as matchRE, e as excludeRE, s as separatorRE, i as importAsRE, d as defineUnimportPreset, t as toExports, o as normalizeImports, c as dedupeImports, f as stripFileExtension, h as toTypeDeclarationFile, j as toTypeReExports, n as addImportToCode } from './unimport.1c509f98.mjs';
  2. import { detectSyntax, findStaticImports, parseStaticImport, findExports, findTypeExports, resolve as resolve$1, resolveModuleExportNames } from 'mlly';
  3. import { existsSync, promises, accessSync, constants, readFileSync } from 'node:fs';
  4. import { readFile } from 'node:fs/promises';
  5. import process from 'node:process';
  6. import { fileURLToPath } from 'node:url';
  7. import fg from 'fast-glob';
  8. import { normalize, parse, resolve, join, basename, dirname } from 'pathe';
  9. import pm from 'picomatch';
  10. import { camelCase } from 'scule';
  11. import os from 'node:os';
  12. import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
  13. import { resolveModule } from 'local-pkg';
  14. const version = "3.14.5";
  15. function configureAddons(opts) {
  16. const addons = [];
  17. if (Array.isArray(opts.addons)) {
  18. addons.push(...opts.addons);
  19. } else {
  20. const addonsMap = /* @__PURE__ */ new Map();
  21. if (opts.addons?.addons?.length) {
  22. let i = 0;
  23. for (const addon of opts.addons.addons) {
  24. addonsMap.set(addon.name || `external:custom-${i++}`, addon);
  25. }
  26. }
  27. if (opts.addons?.vueTemplate) {
  28. if (!addonsMap.has(VUE_TEMPLATE_NAME)) {
  29. addonsMap.set(VUE_TEMPLATE_NAME, vueTemplateAddon());
  30. }
  31. }
  32. if (opts.addons?.vueDirectives) {
  33. if (!addonsMap.has(VUE_DIRECTIVES_NAME)) {
  34. addonsMap.set(VUE_DIRECTIVES_NAME, vueDirectivesAddon(
  35. typeof opts.addons.vueDirectives === "object" ? opts.addons.vueDirectives : void 0
  36. ));
  37. }
  38. }
  39. addons.push(...addonsMap.values());
  40. }
  41. return addons;
  42. }
  43. async function detectImportsRegex(code, ctx, options) {
  44. const s = getMagicString(code);
  45. const original = s.original;
  46. const strippedCode = stripCommentsAndStrings(
  47. original,
  48. // Do not strip comments if they are virtual import names
  49. options?.transformVirtualImports !== false && ctx.options.virtualImports?.length ? {
  50. filter: (i) => !ctx.options.virtualImports.includes(i),
  51. fillChar: "-"
  52. } : void 0
  53. );
  54. const syntax = detectSyntax(strippedCode);
  55. const isCJSContext = syntax.hasCJS && !syntax.hasESM;
  56. let matchedImports = [];
  57. const occurrenceMap = /* @__PURE__ */ new Map();
  58. const map = await ctx.getImportMap();
  59. if (options?.autoImport !== false) {
  60. Array.from(strippedCode.matchAll(matchRE)).forEach((i) => {
  61. if (i[1] === ".")
  62. return null;
  63. const end = strippedCode[i.index + i[0].length];
  64. const before = strippedCode[i.index - 1];
  65. if (end === ":" && !["?", "case"].includes(i[1].trim()) && before !== ":")
  66. return null;
  67. const name = i[2];
  68. const occurrence = i.index + i[1].length;
  69. if (occurrenceMap.get(name) || Number.POSITIVE_INFINITY > occurrence)
  70. occurrenceMap.set(name, occurrence);
  71. });
  72. for (const regex of excludeRE) {
  73. for (const match of strippedCode.matchAll(regex)) {
  74. const segments = [...match[1]?.split(separatorRE) || [], ...match[2]?.split(separatorRE) || []];
  75. for (const segment of segments) {
  76. const identifier = segment.replace(importAsRE, "").trim();
  77. occurrenceMap.delete(identifier);
  78. }
  79. }
  80. }
  81. const identifiers = new Set(occurrenceMap.keys());
  82. matchedImports = Array.from(identifiers).map((name) => {
  83. const item = map.get(name);
  84. if (item && !item.disabled)
  85. return item;
  86. occurrenceMap.delete(name);
  87. return null;
  88. }).filter(Boolean);
  89. for (const addon of ctx.addons)
  90. matchedImports = await addon.matchImports?.call(ctx, identifiers, matchedImports) || matchedImports;
  91. }
  92. if (options?.transformVirtualImports !== false && ctx.options.virtualImports?.length) {
  93. const virtualImports = parseVirtualImportsRegex(strippedCode, map, ctx.options.virtualImports);
  94. virtualImports.ranges.forEach(([start, end]) => {
  95. s.remove(start, end);
  96. });
  97. matchedImports.push(...virtualImports.imports);
  98. }
  99. const firstOccurrence = Math.min(...Array.from(occurrenceMap.entries()).map((i) => i[1]));
  100. return {
  101. s,
  102. strippedCode,
  103. isCJSContext,
  104. matchedImports,
  105. firstOccurrence
  106. };
  107. }
  108. function parseVirtualImportsRegex(strippedCode, importMap, virtualImports) {
  109. const imports = [];
  110. const ranges = [];
  111. if (virtualImports?.length) {
  112. findStaticImports(strippedCode).filter((i) => virtualImports.includes(i.specifier)).map((i) => parseStaticImport(i)).forEach((i) => {
  113. ranges.push([i.start, i.end]);
  114. Object.entries(i.namedImports || {}).forEach(([name, as]) => {
  115. const original = importMap.get(name);
  116. if (!original)
  117. throw new Error(`[unimport] failed to find "${name}" imported from "${i.specifier}"`);
  118. imports.push({
  119. from: original.from,
  120. name: original.name,
  121. as
  122. });
  123. });
  124. });
  125. }
  126. return {
  127. imports,
  128. ranges
  129. };
  130. }
  131. async function detectImports(code, ctx, options) {
  132. if (options?.parser === "acorn")
  133. return import('../chunks/detect-acorn.mjs').then((r) => r.detectImportsAcorn(code, ctx, options));
  134. return detectImportsRegex(code, ctx, options);
  135. }
  136. const FileExtensionLookup = [
  137. "mts",
  138. "cts",
  139. "ts",
  140. "tsx",
  141. "mjs",
  142. "cjs",
  143. "js",
  144. "jsx"
  145. ];
  146. const FileLookupPatterns = `*.{${FileExtensionLookup.join(",")}}`;
  147. function resolveGlobsExclude(glob, cwd) {
  148. return `${glob.startsWith("!") ? "!" : ""}${resolve(cwd, glob.replace(/^!/, ""))}`;
  149. }
  150. function joinGlobFilePattern(glob, filePattern) {
  151. return join(basename(glob) === "*" ? dirname(glob) : glob, filePattern);
  152. }
  153. function normalizeScanDirs(dirs, options) {
  154. const topLevelTypes = options?.types ?? true;
  155. const cwd = options?.cwd ?? process.cwd();
  156. const filePatterns = options?.filePatterns || [FileLookupPatterns];
  157. return dirs.map((dir) => {
  158. const isString = typeof dir === "string";
  159. const glob = resolveGlobsExclude(isString ? dir : dir.glob, cwd);
  160. const types = isString ? topLevelTypes : dir.types ?? topLevelTypes;
  161. if (glob.match(/\.\w+$/))
  162. return { glob, types };
  163. const withFilePatterns = filePatterns.map((filePattern) => ({ glob: joinGlobFilePattern(glob, filePattern), types }));
  164. return [{ glob, types }, ...withFilePatterns];
  165. }).flat();
  166. }
  167. async function scanFilesFromDir(dir, options) {
  168. const dirGlobs = (Array.isArray(dir) ? dir : [dir]).map((i) => i.glob);
  169. const files = (await fg(
  170. dirGlobs,
  171. {
  172. absolute: true,
  173. cwd: options?.cwd || process.cwd(),
  174. onlyFiles: true,
  175. followSymbolicLinks: true,
  176. unique: true
  177. }
  178. )).map((i) => normalize(i));
  179. const fileFilter = options?.fileFilter || (() => true);
  180. const indexOfDirs = (file) => dirGlobs.findIndex((glob) => pm.isMatch(file, glob));
  181. const fileSortByDirs = files.reduce((acc, file) => {
  182. const index = indexOfDirs(file);
  183. if (acc[index])
  184. acc[index].push(normalize(file));
  185. else
  186. acc[index] = [normalize(file)];
  187. return acc;
  188. }, []).map((files2) => files2.sort()).flat();
  189. return fileSortByDirs.filter(fileFilter);
  190. }
  191. async function scanDirExports(dirs, options) {
  192. const normalizedDirs = normalizeScanDirs(dirs, options);
  193. const files = await scanFilesFromDir(normalizedDirs, options);
  194. const includeTypesDirs = normalizedDirs.filter((dir) => !dir.glob.startsWith("!") && dir.types);
  195. const isIncludeTypes = (file) => includeTypesDirs.some((dir) => pm.isMatch(file, dir.glob));
  196. const imports = (await Promise.all(files.map((file) => scanExports(file, isIncludeTypes(file))))).flat();
  197. const deduped = dedupeDtsExports(imports);
  198. return deduped;
  199. }
  200. function dedupeDtsExports(exports) {
  201. return exports.filter((i) => {
  202. if (!i.type)
  203. return true;
  204. if (i.declarationType === "enum" || i.declarationType === "class")
  205. return true;
  206. return !exports.find((e) => e.as === i.as && e.name === i.name && !e.type);
  207. });
  208. }
  209. async function scanExports(filepath, includeTypes, seen = /* @__PURE__ */ new Set()) {
  210. if (seen.has(filepath)) {
  211. console.warn(`[unimport] "${filepath}" is already scanned, skipping`);
  212. return [];
  213. }
  214. seen.add(filepath);
  215. const imports = [];
  216. const code = await readFile(filepath, "utf-8");
  217. const exports = findExports(code);
  218. const defaultExport = exports.find((i) => i.type === "default");
  219. if (defaultExport) {
  220. let name = parse(filepath).name;
  221. if (name === "index")
  222. name = parse(filepath.split("/").slice(0, -1).join("/")).name;
  223. const as = /[-_.]/.test(name) ? camelCase(name) : name;
  224. imports.push({ name: "default", as, from: filepath });
  225. }
  226. async function toImport(exports2, additional) {
  227. for (const exp of exports2) {
  228. if (exp.type === "named") {
  229. for (const name of exp.names)
  230. imports.push({ name, as: name, from: filepath, ...additional });
  231. } else if (exp.type === "declaration") {
  232. if (exp.name) {
  233. imports.push({ name: exp.name, as: exp.name, from: filepath, ...additional });
  234. if (exp.declarationType === "enum" || exp.declarationType === "class") {
  235. imports.push({ name: exp.name, as: exp.name, from: filepath, type: true, declarationType: exp.declarationType, ...additional });
  236. }
  237. }
  238. } else if (exp.type === "star" && exp.specifier) {
  239. if (exp.name) {
  240. imports.push({ name: exp.name, as: exp.name, from: filepath, ...additional });
  241. } else {
  242. const subfile = exp.specifier;
  243. let subfilepath = resolve(dirname(filepath), subfile);
  244. let subfilepathResolved = false;
  245. for (const ext of FileExtensionLookup) {
  246. if (existsSync(`${subfilepath}.${ext}`)) {
  247. subfilepath = `${subfilepath}.${ext}`;
  248. break;
  249. } else if (existsSync(`${subfilepath}/index.${ext}`)) {
  250. subfilepath = `${subfilepath}/index.${ext}`;
  251. break;
  252. }
  253. }
  254. if (existsSync(subfilepath)) {
  255. subfilepathResolved = true;
  256. } else {
  257. try {
  258. subfilepath = await resolve$1(exp.specifier);
  259. subfilepath = normalize(fileURLToPath(subfilepath));
  260. if (existsSync(subfilepath)) {
  261. subfilepathResolved = true;
  262. }
  263. } catch {
  264. }
  265. }
  266. if (!subfilepathResolved) {
  267. console.warn(`[unimport] failed to resolve "${subfilepath}", skip scanning`);
  268. continue;
  269. }
  270. const nested = await scanExports(subfilepath, includeTypes, seen);
  271. imports.push(...additional ? nested.map((i) => ({ ...i, ...additional })) : nested);
  272. }
  273. }
  274. }
  275. }
  276. const isDts = filepath.match(/\.d\.[mc]?ts$/);
  277. if (isDts) {
  278. if (includeTypes) {
  279. await toImport(exports, { type: true });
  280. await toImport(findTypeExports(code), { type: true });
  281. }
  282. } else {
  283. await toImport(exports);
  284. if (includeTypes)
  285. await toImport(findTypeExports(code), { type: true });
  286. }
  287. return imports;
  288. }
  289. const CACHE_PATH = /* @__PURE__ */ join(os.tmpdir(), "unimport");
  290. let CACHE_WRITEABLE;
  291. async function resolvePackagePreset(preset) {
  292. const scanned = await extractExports(preset.package, preset.url, preset.cache);
  293. const filtered = scanned.filter((name) => {
  294. for (const item of preset.ignore || []) {
  295. if (typeof item === "string" && item === name)
  296. return false;
  297. if (item instanceof RegExp && item.test(name))
  298. return false;
  299. if (typeof item === "function" && item(name) === false)
  300. return false;
  301. }
  302. return true;
  303. });
  304. return filtered.map((name) => ({
  305. from: preset.package,
  306. name
  307. }));
  308. }
  309. async function extractExports(name, url, cache = true) {
  310. const packageJsonPath = await resolvePackageJSON(name, { url });
  311. const packageJson = await readPackageJSON(packageJsonPath);
  312. const version = packageJson.version;
  313. const cachePath = join(CACHE_PATH, `${name}@${version}`, "exports.json");
  314. if (cache && CACHE_WRITEABLE === void 0) {
  315. try {
  316. CACHE_WRITEABLE = isWritable(CACHE_PATH);
  317. } catch {
  318. CACHE_WRITEABLE = false;
  319. }
  320. }
  321. const useCache = cache && version && CACHE_WRITEABLE;
  322. if (useCache && existsSync(cachePath))
  323. return JSON.parse(await promises.readFile(cachePath, "utf-8"));
  324. const scanned = await resolveModuleExportNames(name, { url });
  325. if (useCache) {
  326. await promises.mkdir(dirname(cachePath), { recursive: true });
  327. await promises.writeFile(cachePath, JSON.stringify(scanned), "utf-8");
  328. }
  329. return scanned;
  330. }
  331. function isWritable(filename) {
  332. try {
  333. accessSync(filename, constants.W_OK);
  334. return true;
  335. } catch {
  336. return false;
  337. }
  338. }
  339. const dateFns = defineUnimportPreset({
  340. from: "date-fns",
  341. imports: [
  342. "add",
  343. "addBusinessDays",
  344. "addDays",
  345. "addHours",
  346. "addISOWeekYears",
  347. "addMilliseconds",
  348. "addMinutes",
  349. "addMonths",
  350. "addQuarters",
  351. "addSeconds",
  352. "addWeeks",
  353. "addYears",
  354. "areIntervalsOverlapping",
  355. "clamp",
  356. "closestIndexTo",
  357. "closestTo",
  358. "compareAsc",
  359. "compareDesc",
  360. "constants",
  361. "daysToWeeks",
  362. "differenceInBusinessDays",
  363. "differenceInCalendarDays",
  364. "differenceInCalendarISOWeekYears",
  365. "differenceInCalendarISOWeeks",
  366. "differenceInCalendarMonths",
  367. "differenceInCalendarQuarters",
  368. "differenceInCalendarWeeks",
  369. "differenceInCalendarYears",
  370. "differenceInDays",
  371. "differenceInHours",
  372. "differenceInISOWeekYears",
  373. "differenceInMilliseconds",
  374. "differenceInMinutes",
  375. "differenceInMonths",
  376. "differenceInQuarters",
  377. "differenceInSeconds",
  378. "differenceInWeeks",
  379. "differenceInYears",
  380. "eachDayOfInterval",
  381. "eachHourOfInterval",
  382. "eachMinuteOfInterval",
  383. "eachMonthOfInterval",
  384. "eachQuarterOfInterval",
  385. "eachWeekOfInterval",
  386. "eachWeekendOfInterval",
  387. "eachWeekendOfMonth",
  388. "eachWeekendOfYear",
  389. "eachYearOfInterval",
  390. "endOfDay",
  391. "endOfDecade",
  392. "endOfHour",
  393. "endOfISOWeek",
  394. "endOfISOWeekYear",
  395. "endOfMinute",
  396. "endOfMonth",
  397. "endOfQuarter",
  398. "endOfSecond",
  399. "endOfToday",
  400. "endOfTomorrow",
  401. "endOfWeek",
  402. "endOfYear",
  403. "endOfYesterday",
  404. "format",
  405. "formatDistance",
  406. "formatDistanceStrict",
  407. "formatDistanceToNow",
  408. "formatDistanceToNowStrict",
  409. "formatDuration",
  410. "formatISO",
  411. "formatISO9075",
  412. "formatISODuration",
  413. "formatRFC3339",
  414. "formatRFC7231",
  415. "formatRelative",
  416. "fromUnixTime",
  417. "getDate",
  418. "getDay",
  419. "getDayOfYear",
  420. "getDaysInMonth",
  421. "getDaysInYear",
  422. "getDecade",
  423. "getDefaultOptions",
  424. "getHours",
  425. "getISODay",
  426. "getISOWeek",
  427. "getISOWeekYear",
  428. "getISOWeeksInYear",
  429. "getMilliseconds",
  430. "getMinutes",
  431. "getMonth",
  432. "getOverlappingDaysInIntervals",
  433. "getQuarter",
  434. "getSeconds",
  435. "getTime",
  436. "getUnixTime",
  437. "getWeek",
  438. "getWeekOfMonth",
  439. "getWeekYear",
  440. "getWeeksInMonth",
  441. "getYear",
  442. "hoursToMilliseconds",
  443. "hoursToMinutes",
  444. "hoursToSeconds",
  445. "intervalToDuration",
  446. "intlFormat",
  447. "intlFormatDistance",
  448. "isAfter",
  449. "isBefore",
  450. "isDate",
  451. "isEqual",
  452. "isExists",
  453. "isFirstDayOfMonth",
  454. "isFriday",
  455. "isFuture",
  456. "isLastDayOfMonth",
  457. "isLeapYear",
  458. "isMatch",
  459. "isMonday",
  460. "isPast",
  461. "isSameDay",
  462. "isSameHour",
  463. "isSameISOWeek",
  464. "isSameISOWeekYear",
  465. "isSameMinute",
  466. "isSameMonth",
  467. "isSameQuarter",
  468. "isSameSecond",
  469. "isSameWeek",
  470. "isSameYear",
  471. "isSaturday",
  472. "isSunday",
  473. "isThisHour",
  474. "isThisISOWeek",
  475. "isThisMinute",
  476. "isThisMonth",
  477. "isThisQuarter",
  478. "isThisSecond",
  479. "isThisWeek",
  480. "isThisYear",
  481. "isThursday",
  482. "isToday",
  483. "isTomorrow",
  484. "isTuesday",
  485. "isValid",
  486. "isWednesday",
  487. "isWeekend",
  488. "isWithinInterval",
  489. "isYesterday",
  490. "lastDayOfDecade",
  491. "lastDayOfISOWeek",
  492. "lastDayOfISOWeekYear",
  493. "lastDayOfMonth",
  494. "lastDayOfQuarter",
  495. "lastDayOfWeek",
  496. "lastDayOfYear",
  497. "lightFormat",
  498. "max",
  499. "milliseconds",
  500. "millisecondsToHours",
  501. "millisecondsToMinutes",
  502. "millisecondsToSeconds",
  503. "min",
  504. "minutesToHours",
  505. "minutesToMilliseconds",
  506. "minutesToSeconds",
  507. "monthsToQuarters",
  508. "monthsToYears",
  509. "nextDay",
  510. "nextFriday",
  511. "nextMonday",
  512. "nextSaturday",
  513. "nextSunday",
  514. "nextThursday",
  515. "nextTuesday",
  516. "nextWednesday",
  517. "parse",
  518. "parseISO",
  519. "parseJSON",
  520. "previousDay",
  521. "previousFriday",
  522. "previousMonday",
  523. "previousSaturday",
  524. "previousSunday",
  525. "previousThursday",
  526. "previousTuesday",
  527. "previousWednesday",
  528. "quartersToMonths",
  529. "quartersToYears",
  530. "roundToNearestMinutes",
  531. "secondsToHours",
  532. "secondsToMilliseconds",
  533. "secondsToMinutes",
  534. "set",
  535. "setDate",
  536. "setDay",
  537. "setDayOfYear",
  538. "setDefaultOptions",
  539. "setHours",
  540. "setISODay",
  541. "setISOWeek",
  542. "setISOWeekYear",
  543. "setMilliseconds",
  544. "setMinutes",
  545. "setMonth",
  546. "setQuarter",
  547. "setSeconds",
  548. "setWeek",
  549. "setWeekYear",
  550. "setYear",
  551. "startOfDay",
  552. "startOfDecade",
  553. "startOfHour",
  554. "startOfISOWeek",
  555. "startOfISOWeekYear",
  556. "startOfMinute",
  557. "startOfMonth",
  558. "startOfQuarter",
  559. "startOfSecond",
  560. "startOfToday",
  561. "startOfTomorrow",
  562. "startOfWeek",
  563. "startOfWeekYear",
  564. "startOfYear",
  565. "startOfYesterday",
  566. "sub",
  567. "subBusinessDays",
  568. "subDays",
  569. "subHours",
  570. "subISOWeekYears",
  571. "subMilliseconds",
  572. "subMinutes",
  573. "subMonths",
  574. "subQuarters",
  575. "subSeconds",
  576. "subWeeks",
  577. "subYears",
  578. "toDate",
  579. "weeksToDays",
  580. "yearsToMonths",
  581. "yearsToQuarters"
  582. ]
  583. });
  584. const pinia = defineUnimportPreset({
  585. from: "pinia",
  586. imports: [
  587. // https://pinia.esm.dev/api/modules/pinia.html#functions
  588. "acceptHMRUpdate",
  589. "createPinia",
  590. "defineStore",
  591. "getActivePinia",
  592. "mapActions",
  593. "mapGetters",
  594. "mapState",
  595. "mapStores",
  596. "mapWritableState",
  597. "setActivePinia",
  598. "setMapStoreSuffix",
  599. "storeToRefs"
  600. ]
  601. });
  602. const preact = defineUnimportPreset({
  603. from: "preact",
  604. imports: [
  605. "useState",
  606. "useCallback",
  607. "useMemo",
  608. "useEffect",
  609. "useRef",
  610. "useContext",
  611. "useReducer"
  612. ]
  613. });
  614. const quasar = defineUnimportPreset({
  615. from: "quasar",
  616. imports: [
  617. // https://quasar.dev/vue-composables
  618. "useQuasar",
  619. "useDialogPluginComponent",
  620. "useFormChild",
  621. "useMeta"
  622. ]
  623. });
  624. const react = defineUnimportPreset({
  625. from: "react",
  626. imports: [
  627. "useState",
  628. "useCallback",
  629. "useMemo",
  630. "useEffect",
  631. "useRef",
  632. "useContext",
  633. "useReducer"
  634. ]
  635. });
  636. const ReactRouterHooks = [
  637. "useOutletContext",
  638. "useHref",
  639. "useInRouterContext",
  640. "useLocation",
  641. "useNavigationType",
  642. "useNavigate",
  643. "useOutlet",
  644. "useParams",
  645. "useResolvedPath",
  646. "useRoutes"
  647. ];
  648. const reactRouter = defineUnimportPreset({
  649. from: "react-router",
  650. imports: [
  651. ...ReactRouterHooks
  652. ]
  653. });
  654. const reactRouterDom = defineUnimportPreset({
  655. from: "react-router-dom",
  656. imports: [
  657. ...ReactRouterHooks,
  658. // react-router-dom only hooks
  659. "useLinkClickHandler",
  660. "useSearchParams",
  661. // react-router-dom Component
  662. // call once in general
  663. // 'BrowserRouter',
  664. // 'HashRouter',
  665. // 'MemoryRouter',
  666. "Link",
  667. "NavLink",
  668. "Navigate",
  669. "Outlet",
  670. "Route",
  671. "Routes"
  672. ]
  673. });
  674. const rxjs = defineUnimportPreset({
  675. from: "rxjs",
  676. imports: [
  677. "of",
  678. "from",
  679. "map",
  680. "tap",
  681. "filter",
  682. "forkJoin",
  683. "throwError",
  684. "catchError",
  685. "Observable",
  686. "mergeMap",
  687. "switchMap",
  688. "merge",
  689. "zip",
  690. "take",
  691. "takeUntil",
  692. "first",
  693. "lastValueFrom",
  694. "skip",
  695. "skipUntil",
  696. "distinct",
  697. "distinctUntilChanged",
  698. "throttle",
  699. "throttleTime",
  700. "retry",
  701. "retryWhen",
  702. "timeout",
  703. "delay",
  704. "debounce",
  705. "debounceTime",
  706. "find",
  707. "every"
  708. ]
  709. });
  710. const solidCore = defineUnimportPreset({
  711. from: "solid-js",
  712. imports: [
  713. "createSignal",
  714. "createEffect",
  715. "createMemo",
  716. "createResource",
  717. "onMount",
  718. "onCleanup",
  719. "onError",
  720. "untrack",
  721. "batch",
  722. "on",
  723. "createRoot",
  724. "mergeProps",
  725. "splitProps",
  726. "useTransition",
  727. "observable",
  728. "mapArray",
  729. "indexArray",
  730. "createContext",
  731. "useContext",
  732. "children",
  733. "lazy",
  734. "createDeferred",
  735. "createRenderEffect",
  736. "createSelector",
  737. "For",
  738. "Show",
  739. "Switch",
  740. "Match",
  741. "Index",
  742. "ErrorBoundary",
  743. "Suspense",
  744. "SuspenseList"
  745. ]
  746. });
  747. const solidStore = defineUnimportPreset({
  748. from: "solid-js/store",
  749. imports: [
  750. "createStore",
  751. "produce",
  752. "reconcile",
  753. "createMutable"
  754. ]
  755. });
  756. const solidWeb = defineUnimportPreset({
  757. from: "solid-js/web",
  758. imports: [
  759. "Dynamic",
  760. "hydrate",
  761. "render",
  762. "renderToString",
  763. "renderToStringAsync",
  764. "renderToStream",
  765. "isServer",
  766. "Portal"
  767. ]
  768. });
  769. const solid = defineUnimportPreset({
  770. from: "solid-js",
  771. imports: [
  772. solidCore,
  773. solidStore,
  774. solidWeb
  775. ]
  776. });
  777. const solidAppRouter = defineUnimportPreset({
  778. from: "solid-app-router",
  779. imports: [
  780. "Link",
  781. "NavLink",
  782. "Navigate",
  783. "Outlet",
  784. "Route",
  785. "Router",
  786. "Routes",
  787. "_mergeSearchString",
  788. "createIntegration",
  789. "hashIntegration",
  790. "normalizeIntegration",
  791. "pathIntegration",
  792. "staticIntegration",
  793. "useHref",
  794. "useIsRouting",
  795. "useLocation",
  796. "useMatch",
  797. "useNavigate",
  798. "useParams",
  799. "useResolvedPath",
  800. "useRouteData",
  801. "useRoutes",
  802. "useSearchParams"
  803. ]
  804. });
  805. const svelteAnimate = defineUnimportPreset({
  806. from: "svelte/animate",
  807. imports: [
  808. "flip"
  809. ]
  810. });
  811. const svelteEasing = defineUnimportPreset({
  812. from: "svelte/easing",
  813. imports: [
  814. "back",
  815. "bounce",
  816. "circ",
  817. "cubic",
  818. "elastic",
  819. "expo",
  820. "quad",
  821. "quart",
  822. "quint",
  823. "sine"
  824. ].reduce((acc, e) => {
  825. acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
  826. return acc;
  827. }, ["linear"])
  828. });
  829. const svelteStore = defineUnimportPreset({
  830. from: "svelte/store",
  831. imports: [
  832. "writable",
  833. "readable",
  834. "derived",
  835. "get"
  836. ]
  837. });
  838. const svelteMotion = defineUnimportPreset({
  839. from: "svelte/motion",
  840. imports: [
  841. "tweened",
  842. "spring"
  843. ]
  844. });
  845. const svelteTransition = defineUnimportPreset({
  846. from: "svelte/transition",
  847. imports: [
  848. "fade",
  849. "blur",
  850. "fly",
  851. "slide",
  852. "scale",
  853. "draw",
  854. "crossfade"
  855. ]
  856. });
  857. const svelte = defineUnimportPreset({
  858. from: "svelte",
  859. imports: [
  860. // lifecycle
  861. "onMount",
  862. "beforeUpdate",
  863. "afterUpdate",
  864. "onDestroy",
  865. // tick
  866. "tick",
  867. // context
  868. "setContext",
  869. "getContext",
  870. "hasContext",
  871. "getAllContexts",
  872. // event dispatcher
  873. "createEventDispatcher"
  874. ]
  875. });
  876. const uniApp = defineUnimportPreset({
  877. from: "@dcloudio/uni-app",
  878. imports: [
  879. "onAddToFavorites",
  880. "onBackPress",
  881. "onError",
  882. "onHide",
  883. "onLaunch",
  884. "onLoad",
  885. "onNavigationBarButtonTap",
  886. "onNavigationBarSearchInputChanged",
  887. "onNavigationBarSearchInputClicked",
  888. "onNavigationBarSearchInputConfirmed",
  889. "onNavigationBarSearchInputFocusChanged",
  890. "onPageNotFound",
  891. "onPageScroll",
  892. "onPullDownRefresh",
  893. "onReachBottom",
  894. "onReady",
  895. "onResize",
  896. "onShareAppMessage",
  897. "onShareTimeline",
  898. "onShow",
  899. "onTabItemTap",
  900. "onThemeChange",
  901. "onUnhandledRejection",
  902. "onUnload"
  903. ]
  904. });
  905. const veeValidate = defineUnimportPreset({
  906. from: "vee-validate",
  907. imports: [
  908. // https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
  909. // https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
  910. "validate",
  911. "defineRule",
  912. "configure",
  913. "useField",
  914. "useForm",
  915. "useFieldArray",
  916. "useResetForm",
  917. "useIsFieldDirty",
  918. "useIsFieldTouched",
  919. "useIsFieldValid",
  920. "useIsSubmitting",
  921. "useValidateField",
  922. "useIsFormDirty",
  923. "useIsFormTouched",
  924. "useIsFormValid",
  925. "useValidateForm",
  926. "useSubmitCount",
  927. "useFieldValue",
  928. "useFormValues",
  929. "useFormErrors",
  930. "useFieldError",
  931. "useSubmitForm",
  932. "FormContextKey",
  933. "FieldContextKey"
  934. ]
  935. });
  936. const vitepress = defineUnimportPreset({
  937. from: "vitepress",
  938. imports: [
  939. // helper methods
  940. "useData",
  941. "useRoute",
  942. "useRouter",
  943. "withBase"
  944. ]
  945. });
  946. const vitest = defineUnimportPreset({
  947. from: "vitest",
  948. imports: [
  949. // suite
  950. "suite",
  951. "test",
  952. "describe",
  953. "it",
  954. // chai
  955. "chai",
  956. "expect",
  957. "assert",
  958. // utils
  959. "vitest",
  960. "vi",
  961. // hooks
  962. "beforeAll",
  963. "afterAll",
  964. "beforeEach",
  965. "afterEach"
  966. ]
  967. });
  968. const CommonCompositionAPI = [
  969. // lifecycle
  970. "onActivated",
  971. "onBeforeMount",
  972. "onBeforeUnmount",
  973. "onBeforeUpdate",
  974. "onErrorCaptured",
  975. "onDeactivated",
  976. "onMounted",
  977. "onServerPrefetch",
  978. "onUnmounted",
  979. "onUpdated",
  980. // setup helpers
  981. "useAttrs",
  982. "useSlots",
  983. // reactivity,
  984. "computed",
  985. "customRef",
  986. "isReadonly",
  987. "isRef",
  988. "isProxy",
  989. "isReactive",
  990. "markRaw",
  991. "reactive",
  992. "readonly",
  993. "ref",
  994. "shallowReactive",
  995. "shallowReadonly",
  996. "shallowRef",
  997. "triggerRef",
  998. "toRaw",
  999. "toRef",
  1000. "toRefs",
  1001. "toValue",
  1002. "unref",
  1003. "watch",
  1004. "watchEffect",
  1005. "watchPostEffect",
  1006. "watchSyncEffect",
  1007. // component
  1008. "defineComponent",
  1009. "defineAsyncComponent",
  1010. "getCurrentInstance",
  1011. "h",
  1012. "inject",
  1013. "nextTick",
  1014. "provide",
  1015. "useCssModule",
  1016. "createApp",
  1017. // effect scope
  1018. "effectScope",
  1019. "EffectScope",
  1020. "getCurrentScope",
  1021. "onScopeDispose",
  1022. // types
  1023. ...[
  1024. "Component",
  1025. "ComponentPublicInstance",
  1026. "ComputedRef",
  1027. "DirectiveBinding",
  1028. "ExtractDefaultPropTypes",
  1029. "ExtractPropTypes",
  1030. "ExtractPublicPropTypes",
  1031. "InjectionKey",
  1032. "PropType",
  1033. "Ref",
  1034. "MaybeRef",
  1035. "MaybeRefOrGetter",
  1036. "VNode",
  1037. "WritableComputedRef"
  1038. ].map((name) => ({ name, type: true }))
  1039. ];
  1040. const vue = defineUnimportPreset({
  1041. from: "vue",
  1042. imports: [
  1043. ...CommonCompositionAPI,
  1044. // vue3 only
  1045. "onRenderTracked",
  1046. "onRenderTriggered",
  1047. "resolveComponent",
  1048. "useCssVars",
  1049. // vue3.4+
  1050. "useModel",
  1051. // vue3.5+
  1052. "onWatcherCleanup",
  1053. "useId",
  1054. "useTemplateRef"
  1055. ]
  1056. });
  1057. const vueCompositionApi = defineUnimportPreset({
  1058. from: "@vue/composition-api",
  1059. imports: CommonCompositionAPI
  1060. });
  1061. const vueDemi = defineUnimportPreset({
  1062. from: "vue-demi",
  1063. imports: CommonCompositionAPI
  1064. });
  1065. const vueI18n = defineUnimportPreset({
  1066. from: "vue-i18n",
  1067. imports: [
  1068. "useI18n"
  1069. ]
  1070. });
  1071. const vueMacros = defineUnimportPreset({
  1072. from: "vue/macros",
  1073. imports: [
  1074. // https://vuejs.org/guide/extras/reactivity-transform.html#refs-vs-reactive-variables
  1075. "$",
  1076. "$$",
  1077. "$ref",
  1078. "$shallowRef",
  1079. "$toRef",
  1080. "$customRef",
  1081. "$computed"
  1082. ]
  1083. });
  1084. const vueRouter = defineUnimportPreset({
  1085. from: "vue-router",
  1086. imports: [
  1087. "useRouter",
  1088. "useRoute",
  1089. "useLink",
  1090. "onBeforeRouteLeave",
  1091. "onBeforeRouteUpdate"
  1092. ]
  1093. });
  1094. const vueRouterComposables = defineUnimportPreset({
  1095. from: "vue-router/composables",
  1096. imports: [
  1097. "useRouter",
  1098. "useRoute",
  1099. "useLink",
  1100. "onBeforeRouteLeave",
  1101. "onBeforeRouteUpdate"
  1102. ]
  1103. });
  1104. let _cache;
  1105. const vueuseCore = () => {
  1106. const excluded = ["toRefs", "utils"];
  1107. if (!_cache) {
  1108. try {
  1109. const corePath = resolveModule("@vueuse/core") || process.cwd();
  1110. const path = resolveModule("@vueuse/core/indexes.json") || resolveModule("@vueuse/metadata/index.json") || resolveModule("@vueuse/metadata/index.json", { paths: [corePath] });
  1111. const indexesJson = JSON.parse(readFileSync(path, "utf-8"));
  1112. _cache = defineUnimportPreset({
  1113. from: "@vueuse/core",
  1114. imports: indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).map((i) => i.name).filter((i) => i && i.length >= 4 && !excluded.includes(i))
  1115. });
  1116. } catch (error) {
  1117. console.error(error);
  1118. throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
  1119. }
  1120. }
  1121. return _cache;
  1122. };
  1123. const vueuseHead = defineUnimportPreset({
  1124. from: "@vueuse/head",
  1125. imports: [
  1126. "useHead"
  1127. ]
  1128. });
  1129. const vuex = defineUnimportPreset({
  1130. from: "vuex",
  1131. imports: [
  1132. // https://next.vuex.vuejs.org/api/#createstore
  1133. "createStore",
  1134. // https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
  1135. "createLogger",
  1136. // https://next.vuex.vuejs.org/api/#component-binding-helpers
  1137. "mapState",
  1138. "mapGetters",
  1139. "mapActions",
  1140. "mapMutations",
  1141. "createNamespacedHelpers",
  1142. // https://next.vuex.vuejs.org/api/#composable-functions
  1143. "useStore"
  1144. ]
  1145. });
  1146. const builtinPresets = {
  1147. "@vue/composition-api": vueCompositionApi,
  1148. "@vueuse/core": vueuseCore,
  1149. "@vueuse/head": vueuseHead,
  1150. "pinia": pinia,
  1151. "preact": preact,
  1152. "quasar": quasar,
  1153. "react": react,
  1154. "react-router": reactRouter,
  1155. "react-router-dom": reactRouterDom,
  1156. "svelte": svelte,
  1157. "svelte/animate": svelteAnimate,
  1158. "svelte/easing": svelteEasing,
  1159. "svelte/motion": svelteMotion,
  1160. "svelte/store": svelteStore,
  1161. "svelte/transition": svelteTransition,
  1162. "vee-validate": veeValidate,
  1163. "vitepress": vitepress,
  1164. "vue-demi": vueDemi,
  1165. "vue-i18n": vueI18n,
  1166. "vue-router": vueRouter,
  1167. "vue-router-composables": vueRouterComposables,
  1168. "vue": vue,
  1169. "vue/macros": vueMacros,
  1170. "vuex": vuex,
  1171. "vitest": vitest,
  1172. "uni-app": uniApp,
  1173. "solid-js": solid,
  1174. "solid-app-router": solidAppRouter,
  1175. "rxjs": rxjs,
  1176. "date-fns": dateFns
  1177. };
  1178. const commonProps = [
  1179. "from",
  1180. "priority",
  1181. "disabled",
  1182. "dtsDisabled",
  1183. "meta",
  1184. "type"
  1185. ];
  1186. async function resolvePreset(preset) {
  1187. const imports = [];
  1188. if ("package" in preset)
  1189. return await resolvePackagePreset(preset);
  1190. const common = {};
  1191. commonProps.forEach((i) => {
  1192. if (i in preset) {
  1193. common[i] = preset[i];
  1194. }
  1195. });
  1196. for (const _import of preset.imports) {
  1197. if (typeof _import === "string")
  1198. imports.push({ ...common, name: _import, as: _import });
  1199. else if (Array.isArray(_import))
  1200. imports.push({ ...common, name: _import[0], as: _import[1] || _import[0], from: _import[2] || preset.from });
  1201. else if (_import.imports)
  1202. imports.push(...await resolvePreset(_import));
  1203. else
  1204. imports.push({ ...common, ..._import });
  1205. }
  1206. return imports;
  1207. }
  1208. async function resolveBuiltinPresets(presets) {
  1209. const resolved = await Promise.all(presets.map(async (p) => {
  1210. let preset = typeof p === "string" ? builtinPresets[p] : p;
  1211. if (typeof preset === "function")
  1212. preset = preset();
  1213. return await resolvePreset(preset);
  1214. }));
  1215. return resolved.flat();
  1216. }
  1217. function createUnimport(opts) {
  1218. const ctx = createInternalContext(opts);
  1219. async function generateTypeDeclarations(options) {
  1220. const opts2 = {
  1221. resolvePath: (i) => stripFileExtension(i.typeFrom || i.from),
  1222. ...options
  1223. };
  1224. const {
  1225. typeReExports = true
  1226. } = opts2;
  1227. const imports = await ctx.getImports();
  1228. let dts = toTypeDeclarationFile(imports.filter((i) => !i.type && !i.dtsDisabled), opts2);
  1229. const typeOnly = imports.filter((i) => i.type);
  1230. if (typeReExports && typeOnly.length)
  1231. dts += `
  1232. ${toTypeReExports(typeOnly, opts2)}`;
  1233. for (const addon of ctx.addons)
  1234. dts = await addon.declaration?.call(ctx, dts, opts2) ?? dts;
  1235. return dts;
  1236. }
  1237. async function scanImportsFromFile(filepath, includeTypes = true) {
  1238. const additions = await scanExports(filepath, includeTypes);
  1239. await ctx.modifyDynamicImports((imports) => imports.filter((i) => i.from !== filepath).concat(additions));
  1240. return additions;
  1241. }
  1242. async function scanImportsFromDir(dirs = ctx.options.dirs || [], options = ctx.options.dirsScanOptions) {
  1243. const imports = await scanDirExports(dirs, options);
  1244. const files = new Set(imports.map((f) => f.from));
  1245. await ctx.modifyDynamicImports((i) => i.filter((i2) => !files.has(i2.from)).concat(imports));
  1246. return imports;
  1247. }
  1248. async function injectImportsWithContext(code, id, options) {
  1249. const result = await injectImports(code, id, ctx, {
  1250. ...opts,
  1251. ...options
  1252. });
  1253. const metadata = ctx.getMetadata();
  1254. if (metadata) {
  1255. result.imports.forEach((i) => {
  1256. metadata.injectionUsage[i.name] = metadata.injectionUsage[i.name] || { import: i, count: 0, moduleIds: [] };
  1257. metadata.injectionUsage[i.name].count++;
  1258. if (id && !metadata.injectionUsage[i.name].moduleIds.includes(id))
  1259. metadata.injectionUsage[i.name].moduleIds.push(id);
  1260. });
  1261. }
  1262. return result;
  1263. }
  1264. async function init() {
  1265. if (ctx.options.dirs?.length)
  1266. await scanImportsFromDir();
  1267. }
  1268. return {
  1269. version,
  1270. init,
  1271. clearDynamicImports: () => ctx.clearDynamicImports(),
  1272. modifyDynamicImports: (fn) => ctx.modifyDynamicImports(fn),
  1273. scanImportsFromDir,
  1274. scanImportsFromFile,
  1275. getImports: () => ctx.getImports(),
  1276. getImportMap: () => ctx.getImportMap(),
  1277. detectImports: (code) => detectImports(code, ctx),
  1278. injectImports: injectImportsWithContext,
  1279. generateTypeDeclarations: (options) => generateTypeDeclarations(options),
  1280. getMetadata: () => ctx.getMetadata(),
  1281. getInternalContext: () => ctx,
  1282. // Deprecated
  1283. toExports: async (filepath, includeTypes = false) => toExports(await ctx.getImports(), filepath, includeTypes)
  1284. };
  1285. }
  1286. function createInternalContext(opts) {
  1287. let _combinedImports;
  1288. const _map = /* @__PURE__ */ new Map();
  1289. const addons = configureAddons(opts);
  1290. opts.addons = addons;
  1291. opts.commentsDisable = opts.commentsDisable ?? ["@unimport-disable", "@imports-disable"];
  1292. opts.commentsDebug = opts.commentsDebug ?? ["@unimport-debug", "@imports-debug"];
  1293. let metadata;
  1294. if (opts.collectMeta) {
  1295. metadata = {
  1296. injectionUsage: {}
  1297. };
  1298. }
  1299. let resolvePromise;
  1300. const ctx = {
  1301. version,
  1302. options: opts,
  1303. addons,
  1304. staticImports: [...opts.imports || []].filter(Boolean),
  1305. dynamicImports: [],
  1306. modifyDynamicImports,
  1307. clearDynamicImports,
  1308. async getImports() {
  1309. await resolvePromise;
  1310. return updateImports();
  1311. },
  1312. async replaceImports(imports) {
  1313. ctx.staticImports = [...imports || []].filter(Boolean);
  1314. ctx.invalidate();
  1315. await resolvePromise;
  1316. return updateImports();
  1317. },
  1318. async getImportMap() {
  1319. await ctx.getImports();
  1320. return _map;
  1321. },
  1322. getMetadata() {
  1323. return metadata;
  1324. },
  1325. invalidate() {
  1326. _combinedImports = void 0;
  1327. },
  1328. resolveId: (id, parentId) => opts.resolveId?.(id, parentId)
  1329. };
  1330. resolvePromise = resolveBuiltinPresets(opts.presets || []).then((r) => {
  1331. ctx.staticImports.unshift(...r);
  1332. _combinedImports = void 0;
  1333. updateImports();
  1334. });
  1335. function updateImports() {
  1336. if (!_combinedImports) {
  1337. let imports = normalizeImports(dedupeImports([...ctx.staticImports, ...ctx.dynamicImports], opts.warn || console.warn));
  1338. for (const addon of ctx.addons) {
  1339. if (addon.extendImports)
  1340. imports = addon.extendImports.call(ctx, imports) ?? imports;
  1341. }
  1342. imports = imports.filter((i) => !i.disabled);
  1343. _map.clear();
  1344. for (const _import of imports) {
  1345. if (!_import.type)
  1346. _map.set(_import.as ?? _import.name, _import);
  1347. }
  1348. _combinedImports = imports;
  1349. }
  1350. return _combinedImports;
  1351. }
  1352. async function modifyDynamicImports(fn) {
  1353. const result = await fn(ctx.dynamicImports);
  1354. if (Array.isArray(result))
  1355. ctx.dynamicImports = result;
  1356. ctx.invalidate();
  1357. }
  1358. function clearDynamicImports() {
  1359. ctx.dynamicImports.length = 0;
  1360. ctx.invalidate();
  1361. }
  1362. return ctx;
  1363. }
  1364. async function injectImports(code, id, ctx, options) {
  1365. const s = getMagicString(code);
  1366. if (ctx.options.commentsDisable?.some((c) => s.original.includes(c))) {
  1367. return {
  1368. s,
  1369. get code() {
  1370. return s.toString();
  1371. },
  1372. imports: []
  1373. };
  1374. }
  1375. for (const addon of ctx.addons)
  1376. await addon.transform?.call(ctx, s, id);
  1377. const { isCJSContext, matchedImports, firstOccurrence } = await detectImports(s, ctx, options);
  1378. const imports = await resolveImports(ctx, matchedImports, id);
  1379. if (ctx.options.commentsDebug?.some((c) => s.original.includes(c))) {
  1380. const log = ctx.options.debugLog || console.log;
  1381. log(`[unimport] ${imports.length} imports detected in "${id}"${imports.length ? `: ${imports.map((i) => i.name).join(", ")}` : ""}`);
  1382. }
  1383. return {
  1384. ...addImportToCode(
  1385. s,
  1386. imports,
  1387. isCJSContext,
  1388. options?.mergeExisting,
  1389. options?.injectAtEnd,
  1390. firstOccurrence,
  1391. (imports2) => {
  1392. for (const addon of ctx.addons)
  1393. imports2 = addon.injectImportsResolved?.call(ctx, imports2, s, id) ?? imports2;
  1394. return imports2;
  1395. },
  1396. (str, imports2) => {
  1397. for (const addon of ctx.addons)
  1398. str = addon.injectImportsStringified?.call(ctx, str, imports2, s, id) ?? str;
  1399. return str;
  1400. }
  1401. ),
  1402. imports
  1403. };
  1404. }
  1405. async function resolveImports(ctx, imports, id) {
  1406. const resolveCache = /* @__PURE__ */ new Map();
  1407. const _imports = await Promise.all(imports.map(async (i) => {
  1408. if (!resolveCache.has(i.from))
  1409. resolveCache.set(i.from, await ctx.resolveId(i.from, id) || i.from);
  1410. const from = resolveCache.get(i.from);
  1411. if (i.from === id || !from || from === "." || from === id)
  1412. return;
  1413. return {
  1414. ...i,
  1415. from
  1416. };
  1417. }));
  1418. return _imports.filter(Boolean);
  1419. }
  1420. export { resolvePreset as a, builtinPresets as b, createUnimport as c, scanDirExports as d, dedupeDtsExports as e, scanExports as f, normalizeScanDirs as n, resolveBuiltinPresets as r, scanFilesFromDir as s, version as v };