版博士V2.0程序
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

chunk-WVTE3GCL.mjs 25 KiB

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