chunk-L42GFWTA.js 26 KB

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