chunk-ALMYXVCO.js 25 KB

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