chunk-LAHXDHMT.js 25 KB

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