chunk-VNVY5OWA.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. import {
  2. DIRECTIVE_IMPORT_PREFIX,
  3. DISABLE_COMMENT,
  4. getNameFromFilePath,
  5. getTransformedPath,
  6. matchGlobs,
  7. normalizeComponetInfo,
  8. parseId,
  9. pascalCase,
  10. resolveAlias,
  11. shouldTransform,
  12. stringifyComponentImport
  13. } from "./chunk-T47CWWYC.mjs";
  14. // src/core/unplugin.ts
  15. import { existsSync as existsSync2 } from "fs";
  16. import { createUnplugin } from "unplugin";
  17. import { createFilter } from "@rollup/pluginutils";
  18. import chokidar from "chokidar";
  19. // src/core/context.ts
  20. import { relative as relative2 } from "path";
  21. import Debug5 from "debug";
  22. import { slash as slash3, throttle, toArray as toArray2 } from "@antfu/utils";
  23. // src/core/options.ts
  24. import { join, resolve } from "path";
  25. import { slash, toArray } from "@antfu/utils";
  26. import { getPackageInfoSync, isPackageExists as isPackageExists2 } from "local-pkg";
  27. // src/core/type-imports/detect.ts
  28. import { isPackageExists } from "local-pkg";
  29. import { notNullish } from "@antfu/utils";
  30. // src/core/type-imports/index.ts
  31. var TypeImportPresets = [
  32. {
  33. from: "vue-router",
  34. names: [
  35. "RouterView",
  36. "RouterLink"
  37. ]
  38. },
  39. {
  40. from: "vue-starport",
  41. names: [
  42. "Starport",
  43. "StarportCarrier"
  44. ]
  45. }
  46. ];
  47. // src/core/type-imports/detect.ts
  48. function detectTypeImports() {
  49. return TypeImportPresets.map((i) => isPackageExists(i.from) ? i : void 0).filter(notNullish);
  50. }
  51. function resolveTypeImports(imports) {
  52. return imports.flatMap((i) => i.names.map((n) => ({ from: i.from, name: n, as: n })));
  53. }
  54. // src/core/options.ts
  55. var defaultOptions = {
  56. dirs: "src/components",
  57. extensions: "vue",
  58. deep: true,
  59. dts: isPackageExists2("typescript"),
  60. directoryAsNamespace: false,
  61. collapseSamePrefixes: false,
  62. globalNamespaces: [],
  63. resolvers: [],
  64. importPathTransform: (v) => v,
  65. allowOverrides: false
  66. };
  67. function normalizeResolvers(resolvers) {
  68. return toArray(resolvers).flat().map((r) => typeof r === "function" ? { resolve: r, type: "component" } : r);
  69. }
  70. function resolveOptions(options, root) {
  71. const resolved = Object.assign({}, defaultOptions, options);
  72. resolved.resolvers = normalizeResolvers(resolved.resolvers);
  73. resolved.extensions = toArray(resolved.extensions);
  74. if (resolved.globs) {
  75. resolved.globs = toArray(resolved.globs).map((glob) => slash(resolve(root, glob)));
  76. resolved.resolvedDirs = [];
  77. } else {
  78. const extsGlob = resolved.extensions.length === 1 ? resolved.extensions : `{${resolved.extensions.join(",")}}`;
  79. resolved.dirs = toArray(resolved.dirs);
  80. resolved.resolvedDirs = resolved.dirs.map((i) => slash(resolve(root, i)));
  81. resolved.globs = resolved.resolvedDirs.map(
  82. (i) => resolved.deep ? slash(join(i, `**/*.${extsGlob}`)) : slash(join(i, `*.${extsGlob}`))
  83. );
  84. if (!resolved.extensions.length)
  85. throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
  86. }
  87. resolved.dts = !resolved.dts ? false : resolve(
  88. root,
  89. typeof resolved.dts === "string" ? resolved.dts : "components.d.ts"
  90. );
  91. if (!resolved.types && resolved.dts)
  92. resolved.types = detectTypeImports();
  93. resolved.types = resolved.types || [];
  94. resolved.root = root;
  95. resolved.transformer = options.transformer || getVueVersion(root) || "vue3";
  96. resolved.directives = typeof options.directives === "boolean" ? options.directives : !resolved.resolvers.some((i) => i.type === "directive") ? false : getVueVersion(root) === "vue3";
  97. return resolved;
  98. }
  99. function getVueVersion(root) {
  100. var _a;
  101. const version = ((_a = getPackageInfoSync("vue", { paths: [root] })) == null ? void 0 : _a.version) || "3";
  102. return version.startsWith("2.") ? "vue2" : "vue3";
  103. }
  104. // src/core/fs/glob.ts
  105. import fg from "fast-glob";
  106. import Debug from "debug";
  107. var debug = Debug("unplugin-vue-components:glob");
  108. function searchComponents(ctx) {
  109. var _a;
  110. debug(`started with: [${ctx.options.globs.join(", ")}]`);
  111. const root = ctx.root;
  112. const files = fg.sync(ctx.options.globs, {
  113. ignore: ["node_modules"],
  114. onlyFiles: true,
  115. cwd: root,
  116. absolute: true
  117. });
  118. if (!files.length && !((_a = ctx.options.resolvers) == null ? void 0 : _a.length))
  119. console.warn("[unplugin-vue-components] no components found");
  120. debug(`${files.length} components found.`);
  121. ctx.addComponents(files);
  122. }
  123. // src/core/declaration.ts
  124. import { dirname, isAbsolute, relative } from "path";
  125. import { existsSync } from "fs";
  126. import { readFile, writeFile } from "fs/promises";
  127. import { notNullish as notNullish2, slash as slash2 } from "@antfu/utils";
  128. var multilineCommentsRE = /\/\*.*?\*\//gms;
  129. var singlelineCommentsRE = /\/\/.*$/gm;
  130. function extractImports(code) {
  131. return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map((i) => [i[1], i[2]]));
  132. }
  133. function parseDeclaration(code) {
  134. var _a, _b;
  135. if (!code)
  136. return;
  137. code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
  138. const imports = {
  139. component: {},
  140. directive: {}
  141. };
  142. const componentDeclaration = (_a = /export\s+interface\s+GlobalComponents\s*{(.*?)}/s.exec(code)) == null ? void 0 : _a[0];
  143. if (componentDeclaration)
  144. imports.component = extractImports(componentDeclaration);
  145. const directiveDeclaration = (_b = /export\s+interface\s+ComponentCustomProperties\s*{(.*?)}/s.exec(code)) == null ? void 0 : _b[0];
  146. if (directiveDeclaration)
  147. imports.directive = extractImports(directiveDeclaration);
  148. return imports;
  149. }
  150. function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
  151. if (!name)
  152. return void 0;
  153. path = getTransformedPath(path, importPathTransform);
  154. const related = isAbsolute(path) ? `./${relative(dirname(filepath), path)}` : path;
  155. const entry = `typeof import('${slash2(related)}')['${importName || "default"}']`;
  156. return [name, entry];
  157. }
  158. function stringifyComponentsInfo(filepath, components, importPathTransform) {
  159. return Object.fromEntries(
  160. components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(notNullish2)
  161. );
  162. }
  163. function getDeclarationImports(ctx, filepath) {
  164. const component = stringifyComponentsInfo(filepath, [
  165. ...Object.values({
  166. ...ctx.componentNameMap,
  167. ...ctx.componentCustomMap
  168. }),
  169. ...resolveTypeImports(ctx.options.types)
  170. ], ctx.options.importPathTransform);
  171. const directive = stringifyComponentsInfo(
  172. filepath,
  173. Object.values(ctx.directiveCustomMap),
  174. ctx.options.importPathTransform
  175. );
  176. if (Object.keys(component).length + Object.keys(directive).length === 0)
  177. return;
  178. return { component, directive };
  179. }
  180. function stringifyDeclarationImports(imports) {
  181. return Object.entries(imports).sort(([a], [b]) => a.localeCompare(b)).map(([name, v]) => {
  182. if (!/^\w+$/.test(name))
  183. name = `'${name}'`;
  184. return `${name}: ${v}`;
  185. });
  186. }
  187. function getDeclaration(ctx, filepath, originalImports) {
  188. const imports = getDeclarationImports(ctx, filepath);
  189. if (!imports)
  190. return;
  191. const declarations = {
  192. component: stringifyDeclarationImports({ ...originalImports == null ? void 0 : originalImports.component, ...imports.component }),
  193. directive: stringifyDeclarationImports({ ...originalImports == null ? void 0 : originalImports.directive, ...imports.directive })
  194. };
  195. let code = `// generated by unplugin-vue-components
  196. // We suggest you to commit this file into source control
  197. // Read more: https://github.com/vuejs/core/pull/3399
  198. import '@vue/runtime-core'
  199. export {}
  200. declare module '@vue/runtime-core' {`;
  201. if (Object.keys(declarations.component).length > 0) {
  202. code += `
  203. export interface GlobalComponents {
  204. ${declarations.component.join("\n ")}
  205. }`;
  206. }
  207. if (Object.keys(declarations.directive).length > 0) {
  208. code += `
  209. export interface ComponentCustomProperties {
  210. ${declarations.directive.join("\n ")}
  211. }`;
  212. }
  213. code += "\n}\n";
  214. return code;
  215. }
  216. async function writeDeclaration(ctx, filepath, removeUnused = false) {
  217. const originalContent = existsSync(filepath) ? await readFile(filepath, "utf-8") : "";
  218. const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
  219. const code = getDeclaration(ctx, filepath, originalImports);
  220. if (!code)
  221. return;
  222. if (code !== originalContent)
  223. await writeFile(filepath, code, "utf-8");
  224. }
  225. // src/core/transformer.ts
  226. import Debug4 from "debug";
  227. import MagicString from "magic-string";
  228. // src/core/transforms/component.ts
  229. import Debug2 from "debug";
  230. var debug2 = Debug2("unplugin-vue-components:transform:component");
  231. var resolveVue2 = (code, s) => {
  232. const results = [];
  233. for (const match of code.matchAll(/_c\([\s\n\t]*['"](.+?)["']([,)])/g)) {
  234. const [full, matchedName, append] = match;
  235. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  236. const start = match.index;
  237. const end = start + full.length;
  238. results.push({
  239. rawName: matchedName,
  240. replace: (resolved) => s.overwrite(start, end, `_c(${resolved}${append}`)
  241. });
  242. }
  243. }
  244. return results;
  245. };
  246. var resolveVue3 = (code, s) => {
  247. const results = [];
  248. for (const match of code.matchAll(/_resolveComponent[0-9]*\("(.+?)"\)/g)) {
  249. const matchedName = match[1];
  250. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  251. const start = match.index;
  252. const end = start + match[0].length;
  253. results.push({
  254. rawName: matchedName,
  255. replace: (resolved) => s.overwrite(start, end, resolved)
  256. });
  257. }
  258. }
  259. return results;
  260. };
  261. async function transformComponent(code, transformer2, s, ctx, sfcPath) {
  262. let no = 0;
  263. const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
  264. for (const { rawName, replace } of results) {
  265. debug2(`| ${rawName}`);
  266. const name = pascalCase(rawName);
  267. ctx.updateUsageMap(sfcPath, [name]);
  268. const component = await ctx.findComponent(name, "component", [sfcPath]);
  269. if (component) {
  270. const varName = `__unplugin_components_${no}`;
  271. s.prepend(`${stringifyComponentImport({ ...component, as: varName }, ctx)};
  272. `);
  273. no += 1;
  274. replace(varName);
  275. }
  276. }
  277. debug2(`^ (${no})`);
  278. }
  279. // src/core/transforms/directive/index.ts
  280. import Debug3 from "debug";
  281. // src/core/transforms/directive/vue2.ts
  282. import { importModule, isPackageExists as isPackageExists3 } from "local-pkg";
  283. var getRenderFnStart = (program) => {
  284. var _a, _b;
  285. const renderFn = program.body.find(
  286. (node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
  287. );
  288. const start = (_b = (_a = renderFn == null ? void 0 : renderFn.declarations[0].init) == null ? void 0 : _a.body) == null ? void 0 : _b.start;
  289. if (start === null || start === void 0)
  290. throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
  291. return start + 1;
  292. };
  293. async function resolveVue22(code, s) {
  294. var _a, _b, _c;
  295. if (!isPackageExists3("@babel/parser"))
  296. throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
  297. const { parse } = await importModule("@babel/parser");
  298. const { program } = parse(code, {
  299. sourceType: "module"
  300. });
  301. const nodes = [];
  302. const { walk } = await import("./src-Z5BCFXFD.mjs");
  303. walk(program, {
  304. enter(node) {
  305. if (node.type === "CallExpression")
  306. nodes.push(node);
  307. }
  308. });
  309. if (nodes.length === 0)
  310. return [];
  311. let _renderStart;
  312. const getRenderStart = () => {
  313. if (_renderStart !== void 0)
  314. return _renderStart;
  315. return _renderStart = getRenderFnStart(program);
  316. };
  317. const results = [];
  318. for (const node of nodes) {
  319. const { callee, arguments: args } = node;
  320. if (callee.type !== "Identifier" || callee.name !== "_c" || ((_a = args[1]) == null ? void 0 : _a.type) !== "ObjectExpression")
  321. continue;
  322. const directives = (_b = args[1].properties.find(
  323. (property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
  324. )) == null ? void 0 : _b.value;
  325. if (!directives || directives.type !== "ArrayExpression")
  326. continue;
  327. for (const directive of directives.elements) {
  328. if ((directive == null ? void 0 : directive.type) !== "ObjectExpression")
  329. continue;
  330. const nameNode = (_c = directive.properties.find(
  331. (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
  332. )) == null ? void 0 : _c.value;
  333. if ((nameNode == null ? void 0 : nameNode.type) !== "StringLiteral")
  334. continue;
  335. const name = nameNode.value;
  336. if (!name || name.startsWith("_"))
  337. continue;
  338. results.push({
  339. rawName: name,
  340. replace: (resolved) => {
  341. s.prependLeft(getRenderStart(), `
  342. this.$options.directives["${name}"] = ${resolved};`);
  343. }
  344. });
  345. }
  346. }
  347. return results;
  348. }
  349. // src/core/transforms/directive/vue3.ts
  350. function resolveVue32(code, s) {
  351. const results = [];
  352. for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
  353. const matchedName = match[1];
  354. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  355. const start = match.index;
  356. const end = start + match[0].length;
  357. results.push({
  358. rawName: matchedName,
  359. replace: (resolved) => s.overwrite(start, end, resolved)
  360. });
  361. }
  362. }
  363. return results;
  364. }
  365. // src/core/transforms/directive/index.ts
  366. var debug3 = Debug3("unplugin-vue-components:transform:directive");
  367. async function transformDirective(code, transformer2, s, ctx, sfcPath) {
  368. let no = 0;
  369. const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
  370. for (const { rawName, replace } of results) {
  371. debug3(`| ${rawName}`);
  372. const name = `${DIRECTIVE_IMPORT_PREFIX}${pascalCase(rawName)}`;
  373. ctx.updateUsageMap(sfcPath, [name]);
  374. const directive = await ctx.findComponent(name, "directive", [sfcPath]);
  375. if (!directive)
  376. continue;
  377. const varName = `__unplugin_directives_${no}`;
  378. s.prepend(`${stringifyComponentImport({ ...directive, as: varName }, ctx)};
  379. `);
  380. no += 1;
  381. replace(varName);
  382. }
  383. debug3(`^ (${no})`);
  384. }
  385. // src/core/transformer.ts
  386. var debug4 = Debug4("unplugin-vue-components:transformer");
  387. function transformer(ctx, transformer2) {
  388. return async (code, id, path) => {
  389. ctx.searchGlob();
  390. const sfcPath = ctx.normalizePath(path);
  391. debug4(sfcPath);
  392. const s = new MagicString(code);
  393. await transformComponent(code, transformer2, s, ctx, sfcPath);
  394. if (ctx.options.directives)
  395. await transformDirective(code, transformer2, s, ctx, sfcPath);
  396. s.prepend(DISABLE_COMMENT);
  397. const result = { code: s.toString() };
  398. if (ctx.sourcemap)
  399. result.map = s.generateMap({ source: id, includeContent: true });
  400. return result;
  401. };
  402. }
  403. // src/core/context.ts
  404. var debug5 = {
  405. components: Debug5("unplugin-vue-components:context:components"),
  406. search: Debug5("unplugin-vue-components:context:search"),
  407. hmr: Debug5("unplugin-vue-components:context:hmr"),
  408. decleration: Debug5("unplugin-vue-components:decleration"),
  409. env: Debug5("unplugin-vue-components:env")
  410. };
  411. var Context = class {
  412. constructor(rawOptions) {
  413. this.rawOptions = rawOptions;
  414. this.transformer = void 0;
  415. this._componentPaths = /* @__PURE__ */ new Set();
  416. this._componentNameMap = {};
  417. this._componentUsageMap = {};
  418. this._componentCustomMap = {};
  419. this._directiveCustomMap = {};
  420. this.root = process.cwd();
  421. this.sourcemap = true;
  422. this.alias = {};
  423. this._searched = false;
  424. this.options = resolveOptions(rawOptions, this.root);
  425. this.generateDeclaration = throttle(500, false, this._generateDeclaration.bind(this));
  426. this.setTransformer(this.options.transformer);
  427. }
  428. setRoot(root) {
  429. if (this.root === root)
  430. return;
  431. debug5.env("root", root);
  432. this.root = root;
  433. this.options = resolveOptions(this.rawOptions, this.root);
  434. }
  435. setTransformer(name) {
  436. debug5.env("transformer", name);
  437. this.transformer = transformer(this, name || "vue3");
  438. }
  439. transform(code, id) {
  440. const { path, query } = parseId(id);
  441. return this.transformer(code, id, path, query);
  442. }
  443. setupViteServer(server) {
  444. if (this._server === server)
  445. return;
  446. this._server = server;
  447. this.setupWatcher(server.watcher);
  448. }
  449. setupWatcher(watcher) {
  450. const { globs } = this.options;
  451. watcher.on("unlink", (path) => {
  452. if (!matchGlobs(path, globs))
  453. return;
  454. path = slash3(path);
  455. this.removeComponents(path);
  456. this.onUpdate(path);
  457. });
  458. watcher.on("add", (path) => {
  459. if (!matchGlobs(path, globs))
  460. return;
  461. path = slash3(path);
  462. this.addComponents(path);
  463. this.onUpdate(path);
  464. });
  465. }
  466. setupWatcherWebpack(watcher, emitUpdate) {
  467. const { globs } = this.options;
  468. watcher.on("unlink", (path) => {
  469. if (!matchGlobs(path, globs))
  470. return;
  471. path = slash3(path);
  472. this.removeComponents(path);
  473. emitUpdate(path, "unlink");
  474. });
  475. watcher.on("add", (path) => {
  476. if (!matchGlobs(path, globs))
  477. return;
  478. path = slash3(path);
  479. this.addComponents(path);
  480. emitUpdate(path, "add");
  481. });
  482. }
  483. updateUsageMap(path, paths) {
  484. if (!this._componentUsageMap[path])
  485. this._componentUsageMap[path] = /* @__PURE__ */ new Set();
  486. paths.forEach((p) => {
  487. this._componentUsageMap[path].add(p);
  488. });
  489. }
  490. addComponents(paths) {
  491. debug5.components("add", paths);
  492. const size = this._componentPaths.size;
  493. toArray2(paths).forEach((p) => this._componentPaths.add(p));
  494. if (this._componentPaths.size !== size) {
  495. this.updateComponentNameMap();
  496. return true;
  497. }
  498. return false;
  499. }
  500. addCustomComponents(info) {
  501. if (info.as)
  502. this._componentCustomMap[info.as] = info;
  503. }
  504. addCustomDirectives(info) {
  505. if (info.as)
  506. this._directiveCustomMap[info.as] = info;
  507. }
  508. removeComponents(paths) {
  509. debug5.components("remove", paths);
  510. const size = this._componentPaths.size;
  511. toArray2(paths).forEach((p) => this._componentPaths.delete(p));
  512. if (this._componentPaths.size !== size) {
  513. this.updateComponentNameMap();
  514. return true;
  515. }
  516. return false;
  517. }
  518. onUpdate(path) {
  519. this.generateDeclaration();
  520. if (!this._server)
  521. return;
  522. const payload = {
  523. type: "update",
  524. updates: []
  525. };
  526. const timestamp = +new Date();
  527. const name = pascalCase(getNameFromFilePath(path, this.options));
  528. Object.entries(this._componentUsageMap).forEach(([key, values]) => {
  529. if (values.has(name)) {
  530. const r = `/${slash3(relative2(this.root, key))}`;
  531. payload.updates.push({
  532. acceptedPath: r,
  533. path: r,
  534. timestamp,
  535. type: "js-update"
  536. });
  537. }
  538. });
  539. if (payload.updates.length)
  540. this._server.ws.send(payload);
  541. }
  542. updateComponentNameMap() {
  543. this._componentNameMap = {};
  544. Array.from(this._componentPaths).forEach((path) => {
  545. const name = pascalCase(getNameFromFilePath(path, this.options));
  546. if (this._componentNameMap[name] && !this.options.allowOverrides) {
  547. console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
  548. return;
  549. }
  550. this._componentNameMap[name] = {
  551. as: name,
  552. from: path
  553. };
  554. });
  555. }
  556. async findComponent(name, type, excludePaths = []) {
  557. let info = this._componentNameMap[name];
  558. if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
  559. return info;
  560. for (const resolver of this.options.resolvers) {
  561. if (resolver.type !== type)
  562. continue;
  563. const result = await resolver.resolve(type === "directive" ? name.slice(DIRECTIVE_IMPORT_PREFIX.length) : name);
  564. if (!result)
  565. continue;
  566. if (typeof result === "string") {
  567. info = {
  568. as: name,
  569. from: result
  570. };
  571. } else {
  572. info = {
  573. as: name,
  574. ...normalizeComponetInfo(result)
  575. };
  576. }
  577. if (type === "component")
  578. this.addCustomComponents(info);
  579. else if (type === "directive")
  580. this.addCustomDirectives(info);
  581. return info;
  582. }
  583. return void 0;
  584. }
  585. normalizePath(path) {
  586. var _a, _b, _c;
  587. return resolveAlias(path, ((_b = (_a = this.viteConfig) == null ? void 0 : _a.resolve) == null ? void 0 : _b.alias) || ((_c = this.viteConfig) == null ? void 0 : _c.alias) || []);
  588. }
  589. relative(path) {
  590. if (path.startsWith("/") && !path.startsWith(this.root))
  591. return slash3(path.slice(1));
  592. return slash3(relative2(this.root, path));
  593. }
  594. searchGlob() {
  595. if (this._searched)
  596. return;
  597. searchComponents(this);
  598. debug5.search(this._componentNameMap);
  599. this._searched = true;
  600. }
  601. _generateDeclaration(removeUnused = !this._server) {
  602. if (!this.options.dts)
  603. return;
  604. debug5.decleration("generating");
  605. return writeDeclaration(this, this.options.dts, removeUnused);
  606. }
  607. get componentNameMap() {
  608. return this._componentNameMap;
  609. }
  610. get componentCustomMap() {
  611. return this._componentCustomMap;
  612. }
  613. get directiveCustomMap() {
  614. return this._directiveCustomMap;
  615. }
  616. };
  617. // src/core/unplugin.ts
  618. var PLUGIN_NAME = "unplugin:webpack";
  619. var unplugin_default = createUnplugin((options = {}) => {
  620. const filter = createFilter(
  621. options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
  622. options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
  623. );
  624. const ctx = new Context(options);
  625. const api = {
  626. async findComponent(name, filename) {
  627. return await ctx.findComponent(name, "component", filename ? [filename] : []);
  628. },
  629. stringifyImport(info) {
  630. return stringifyComponentImport(info, ctx);
  631. }
  632. };
  633. return {
  634. name: "unplugin-vue-components",
  635. enforce: "post",
  636. api,
  637. transformInclude(id) {
  638. return filter(id);
  639. },
  640. async transform(code, id) {
  641. if (!shouldTransform(code))
  642. return null;
  643. try {
  644. const result = await ctx.transform(code, id);
  645. ctx.generateDeclaration();
  646. return result;
  647. } catch (e) {
  648. this.error(e);
  649. }
  650. },
  651. vite: {
  652. configResolved(config) {
  653. ctx.setRoot(config.root);
  654. ctx.sourcemap = true;
  655. if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
  656. ctx.setTransformer("vue2");
  657. if (ctx.options.dts) {
  658. ctx.searchGlob();
  659. if (!existsSync2(ctx.options.dts))
  660. ctx.generateDeclaration();
  661. }
  662. if (config.build.watch && config.command === "build")
  663. ctx.setupWatcher(chokidar.watch(ctx.options.globs));
  664. },
  665. configureServer(server) {
  666. ctx.setupViteServer(server);
  667. }
  668. },
  669. webpack(compiler) {
  670. let watcher;
  671. let fileDepQueue = [];
  672. compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
  673. if (!watcher && compiler.watching) {
  674. watcher = compiler.watching;
  675. ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path, type) => {
  676. fileDepQueue.push({ path, type });
  677. process.nextTick(() => {
  678. watcher.invalidate();
  679. });
  680. });
  681. }
  682. });
  683. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  684. if (fileDepQueue.length) {
  685. fileDepQueue.forEach(({ path, type }) => {
  686. if (type === "unlink")
  687. compilation.fileDependencies.delete(path);
  688. else
  689. compilation.fileDependencies.add(path);
  690. });
  691. fileDepQueue = [];
  692. }
  693. });
  694. }
  695. };
  696. });
  697. export {
  698. unplugin_default
  699. };