版博士V2.0程序
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

chunk-Z3TQFCNG.js 26 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2. var _chunkHCIFGIWSjs = require('./chunk-HCIFGIWS.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 = _chunkHCIFGIWSjs.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 = `/* eslint-disable */
  188. /* prettier-ignore */
  189. // @ts-nocheck
  190. // Generated by unplugin-vue-components
  191. // Read more: https://github.com/vuejs/core/pull/3399
  192. ${head}`;
  193. if (Object.keys(declarations.component).length > 0) {
  194. code += `
  195. export interface GlobalComponents {
  196. ${declarations.component.join("\n ")}
  197. }`;
  198. }
  199. if (Object.keys(declarations.directive).length > 0) {
  200. code += `
  201. export interface ComponentCustomProperties {
  202. ${declarations.directive.join("\n ")}
  203. }`;
  204. }
  205. code += "\n}\n";
  206. return code;
  207. }
  208. async function writeFile(filePath, content) {
  209. await _promises.mkdir.call(void 0, _path.dirname.call(void 0, filePath), { recursive: true });
  210. return await _promises.writeFile.call(void 0, filePath, content, "utf-8");
  211. }
  212. async function writeDeclaration(ctx, filepath, removeUnused = false) {
  213. const originalContent = _fs.existsSync.call(void 0, filepath) ? await _promises.readFile.call(void 0, filepath, "utf-8") : "";
  214. const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
  215. const code = getDeclaration(ctx, filepath, originalImports);
  216. if (!code)
  217. return;
  218. if (code !== originalContent)
  219. await writeFile(filepath, code);
  220. }
  221. // src/core/transformer.ts
  222. var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
  223. // src/core/transforms/component.ts
  224. var debug2 = _debug2.default.call(void 0, "unplugin-vue-components:transform:component");
  225. var resolveVue2 = (code, s) => {
  226. const results = [];
  227. for (const match of code.matchAll(/\b(_c|h)\([\s\n\t]*['"](.+?)["']([,)])/g)) {
  228. const [full, renderFunctionName, matchedName, append] = match;
  229. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  230. const start = match.index;
  231. const end = start + full.length;
  232. results.push({
  233. rawName: matchedName,
  234. replace: (resolved) => s.overwrite(start, end, `${renderFunctionName}(${resolved}${append}`)
  235. });
  236. }
  237. }
  238. return results;
  239. };
  240. var resolveVue3 = (code, s) => {
  241. const results = [];
  242. for (const match of code.matchAll(/_resolveComponent[0-9]*\("(.+?)"\)/g)) {
  243. const matchedName = match[1];
  244. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  245. const start = match.index;
  246. const end = start + match[0].length;
  247. results.push({
  248. rawName: matchedName,
  249. replace: (resolved) => s.overwrite(start, end, resolved)
  250. });
  251. }
  252. }
  253. return results;
  254. };
  255. async function transformComponent(code, transformer2, s, ctx, sfcPath) {
  256. let no = 0;
  257. const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
  258. for (const { rawName, replace } of results) {
  259. debug2(`| ${rawName}`);
  260. const name = _chunkHCIFGIWSjs.pascalCase.call(void 0, rawName);
  261. ctx.updateUsageMap(sfcPath, [name]);
  262. const component = await ctx.findComponent(name, "component", [sfcPath]);
  263. if (component) {
  264. const varName = `__unplugin_components_${no}`;
  265. s.prepend(`${_chunkHCIFGIWSjs.stringifyComponentImport.call(void 0, _chunkBTQOTIPQjs.__spreadProps.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, component), { as: varName }), ctx)};
  266. `);
  267. no += 1;
  268. replace(varName);
  269. }
  270. }
  271. debug2(`^ (${no})`);
  272. }
  273. // src/core/transforms/directive/index.ts
  274. // src/core/transforms/directive/vue2.ts
  275. var getRenderFnStart = (program) => {
  276. var _a, _b;
  277. const renderFn = program.body.find(
  278. (node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
  279. );
  280. const start = (_b = (_a = renderFn == null ? void 0 : renderFn.declarations[0].init) == null ? void 0 : _a.body) == null ? void 0 : _b.start;
  281. if (start === null || start === void 0)
  282. throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
  283. return start + 1;
  284. };
  285. async function resolveVue22(code, s) {
  286. var _a, _b, _c;
  287. if (!_localpkg.isPackageExists.call(void 0, "@babel/parser"))
  288. throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
  289. const { parse } = await _localpkg.importModule.call(void 0, "@babel/parser");
  290. const { program } = parse(code, {
  291. sourceType: "module"
  292. });
  293. const nodes = [];
  294. const { walk } = await Promise.resolve().then(() => require("./src-FZTNZZMC.js"));
  295. walk(program, {
  296. enter(node) {
  297. if (node.type === "CallExpression")
  298. nodes.push(node);
  299. }
  300. });
  301. if (nodes.length === 0)
  302. return [];
  303. let _renderStart;
  304. const getRenderStart = () => {
  305. if (_renderStart !== void 0)
  306. return _renderStart;
  307. return _renderStart = getRenderFnStart(program);
  308. };
  309. const results = [];
  310. for (const node of nodes) {
  311. const { callee, arguments: args } = node;
  312. if (callee.type !== "Identifier" || callee.name !== "_c" || ((_a = args[1]) == null ? void 0 : _a.type) !== "ObjectExpression")
  313. continue;
  314. const directives = (_b = args[1].properties.find(
  315. (property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
  316. )) == null ? void 0 : _b.value;
  317. if (!directives || directives.type !== "ArrayExpression")
  318. continue;
  319. for (const directive of directives.elements) {
  320. if ((directive == null ? void 0 : directive.type) !== "ObjectExpression")
  321. continue;
  322. const nameNode = (_c = directive.properties.find(
  323. (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
  324. )) == null ? void 0 : _c.value;
  325. if ((nameNode == null ? void 0 : nameNode.type) !== "StringLiteral")
  326. continue;
  327. const name = nameNode.value;
  328. if (!name || name.startsWith("_"))
  329. continue;
  330. results.push({
  331. rawName: name,
  332. replace: (resolved) => {
  333. s.prependLeft(getRenderStart(), `
  334. this.$options.directives["${name}"] = ${resolved};`);
  335. }
  336. });
  337. }
  338. }
  339. return results;
  340. }
  341. // src/core/transforms/directive/vue3.ts
  342. function resolveVue32(code, s) {
  343. const results = [];
  344. for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
  345. const matchedName = match[1];
  346. if (match.index != null && matchedName && !matchedName.startsWith("_")) {
  347. const start = match.index;
  348. const end = start + match[0].length;
  349. results.push({
  350. rawName: matchedName,
  351. replace: (resolved) => s.overwrite(start, end, resolved)
  352. });
  353. }
  354. }
  355. return results;
  356. }
  357. // src/core/transforms/directive/index.ts
  358. var debug3 = _debug2.default.call(void 0, "unplugin-vue-components:transform:directive");
  359. async function transformDirective(code, transformer2, s, ctx, sfcPath) {
  360. let no = 0;
  361. const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
  362. for (const { rawName, replace } of results) {
  363. debug3(`| ${rawName}`);
  364. const name = `${_chunkHCIFGIWSjs.DIRECTIVE_IMPORT_PREFIX}${_chunkHCIFGIWSjs.pascalCase.call(void 0, rawName)}`;
  365. ctx.updateUsageMap(sfcPath, [name]);
  366. const directive = await ctx.findComponent(name, "directive", [sfcPath]);
  367. if (!directive)
  368. continue;
  369. const varName = `__unplugin_directives_${no}`;
  370. s.prepend(`${_chunkHCIFGIWSjs.stringifyComponentImport.call(void 0, _chunkBTQOTIPQjs.__spreadProps.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, directive), { as: varName }), ctx)};
  371. `);
  372. no += 1;
  373. replace(varName);
  374. }
  375. debug3(`^ (${no})`);
  376. }
  377. // src/core/transformer.ts
  378. var debug4 = _debug2.default.call(void 0, "unplugin-vue-components:transformer");
  379. function transformer(ctx, transformer2) {
  380. return async (code, id, path) => {
  381. ctx.searchGlob();
  382. const sfcPath = ctx.normalizePath(path);
  383. debug4(sfcPath);
  384. const s = new (0, _magicstring2.default)(code);
  385. await transformComponent(code, transformer2, s, ctx, sfcPath);
  386. if (ctx.options.directives)
  387. await transformDirective(code, transformer2, s, ctx, sfcPath);
  388. s.prepend(_chunkHCIFGIWSjs.DISABLE_COMMENT);
  389. const result = { code: s.toString() };
  390. if (ctx.sourcemap)
  391. result.map = s.generateMap({ source: id, includeContent: true });
  392. return result;
  393. };
  394. }
  395. // src/core/context.ts
  396. var debug5 = {
  397. components: _debug2.default.call(void 0, "unplugin-vue-components:context:components"),
  398. search: _debug2.default.call(void 0, "unplugin-vue-components:context:search"),
  399. hmr: _debug2.default.call(void 0, "unplugin-vue-components:context:hmr"),
  400. decleration: _debug2.default.call(void 0, "unplugin-vue-components:decleration"),
  401. env: _debug2.default.call(void 0, "unplugin-vue-components:env")
  402. };
  403. var Context = class {
  404. constructor(rawOptions) {
  405. this.rawOptions = rawOptions;
  406. this.transformer = void 0;
  407. this._componentPaths = /* @__PURE__ */ new Set();
  408. this._componentNameMap = {};
  409. this._componentUsageMap = {};
  410. this._componentCustomMap = {};
  411. this._directiveCustomMap = {};
  412. this.root = process.cwd();
  413. this.sourcemap = true;
  414. this.alias = {};
  415. this._searched = false;
  416. this.options = resolveOptions(rawOptions, this.root);
  417. this.generateDeclaration = _utils.throttle.call(void 0, 500, this._generateDeclaration.bind(this), { noLeading: false });
  418. this.setTransformer(this.options.transformer);
  419. }
  420. setRoot(root) {
  421. if (this.root === root)
  422. return;
  423. debug5.env("root", root);
  424. this.root = root;
  425. this.options = resolveOptions(this.rawOptions, this.root);
  426. }
  427. setTransformer(name) {
  428. debug5.env("transformer", name);
  429. this.transformer = transformer(this, name || "vue3");
  430. }
  431. transform(code, id) {
  432. const { path, query } = _chunkHCIFGIWSjs.parseId.call(void 0, id);
  433. return this.transformer(code, id, path, query);
  434. }
  435. setupViteServer(server) {
  436. if (this._server === server)
  437. return;
  438. this._server = server;
  439. this.setupWatcher(server.watcher);
  440. }
  441. setupWatcher(watcher) {
  442. const { globs } = this.options;
  443. watcher.on("unlink", (path) => {
  444. if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
  445. return;
  446. path = _utils.slash.call(void 0, path);
  447. this.removeComponents(path);
  448. this.onUpdate(path);
  449. });
  450. watcher.on("add", (path) => {
  451. if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
  452. return;
  453. path = _utils.slash.call(void 0, path);
  454. this.addComponents(path);
  455. this.onUpdate(path);
  456. });
  457. }
  458. /**
  459. * start watcher for webpack
  460. */
  461. setupWatcherWebpack(watcher, emitUpdate) {
  462. const { globs } = this.options;
  463. watcher.on("unlink", (path) => {
  464. if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
  465. return;
  466. path = _utils.slash.call(void 0, path);
  467. this.removeComponents(path);
  468. emitUpdate(path, "unlink");
  469. });
  470. watcher.on("add", (path) => {
  471. if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
  472. return;
  473. path = _utils.slash.call(void 0, path);
  474. this.addComponents(path);
  475. emitUpdate(path, "add");
  476. });
  477. }
  478. /**
  479. * Record the usage of components
  480. * @param path
  481. * @param paths paths of used components
  482. */
  483. updateUsageMap(path, paths) {
  484. if (!this._componentUsageMap[path])
  485. this._componentUsageMap[path] = /* @__PURE__ */ new Set();
  486. paths.forEach((p) => {
  487. this._componentUsageMap[path].add(p);
  488. });
  489. }
  490. addComponents(paths) {
  491. debug5.components("add", paths);
  492. const size = this._componentPaths.size;
  493. _utils.toArray.call(void 0, paths).forEach((p) => this._componentPaths.add(p));
  494. if (this._componentPaths.size !== size) {
  495. this.updateComponentNameMap();
  496. return true;
  497. }
  498. return false;
  499. }
  500. addCustomComponents(info) {
  501. if (info.as)
  502. this._componentCustomMap[info.as] = info;
  503. }
  504. addCustomDirectives(info) {
  505. if (info.as)
  506. this._directiveCustomMap[info.as] = info;
  507. }
  508. removeComponents(paths) {
  509. debug5.components("remove", paths);
  510. const size = this._componentPaths.size;
  511. _utils.toArray.call(void 0, paths).forEach((p) => this._componentPaths.delete(p));
  512. if (this._componentPaths.size !== size) {
  513. this.updateComponentNameMap();
  514. return true;
  515. }
  516. return false;
  517. }
  518. onUpdate(path) {
  519. this.generateDeclaration();
  520. if (!this._server)
  521. return;
  522. const payload = {
  523. type: "update",
  524. updates: []
  525. };
  526. const timestamp = +/* @__PURE__ */ new Date();
  527. const name = _chunkHCIFGIWSjs.pascalCase.call(void 0, _chunkHCIFGIWSjs.getNameFromFilePath.call(void 0, path, this.options));
  528. Object.entries(this._componentUsageMap).forEach(([key, values]) => {
  529. if (values.has(name)) {
  530. const r = `/${_utils.slash.call(void 0, _path.relative.call(void 0, this.root, key))}`;
  531. payload.updates.push({
  532. acceptedPath: r,
  533. path: r,
  534. timestamp,
  535. type: "js-update"
  536. });
  537. }
  538. });
  539. if (payload.updates.length)
  540. this._server.ws.send(payload);
  541. }
  542. updateComponentNameMap() {
  543. this._componentNameMap = {};
  544. Array.from(this._componentPaths).forEach((path) => {
  545. const name = _chunkHCIFGIWSjs.pascalCase.call(void 0, _chunkHCIFGIWSjs.getNameFromFilePath.call(void 0, path, this.options));
  546. if (this._componentNameMap[name] && !this.options.allowOverrides) {
  547. console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
  548. return;
  549. }
  550. this._componentNameMap[name] = {
  551. as: name,
  552. from: path
  553. };
  554. });
  555. }
  556. async findComponent(name, type, excludePaths = []) {
  557. let info = this._componentNameMap[name];
  558. if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
  559. return info;
  560. for (const resolver of this.options.resolvers) {
  561. if (resolver.type !== type)
  562. continue;
  563. const result = await resolver.resolve(type === "directive" ? name.slice(_chunkHCIFGIWSjs.DIRECTIVE_IMPORT_PREFIX.length) : name);
  564. if (!result)
  565. continue;
  566. if (typeof result === "string") {
  567. info = {
  568. as: name,
  569. from: result
  570. };
  571. } else {
  572. info = _chunkBTQOTIPQjs.__spreadValues.call(void 0, {
  573. as: name
  574. }, _chunkHCIFGIWSjs.normalizeComponetInfo.call(void 0, result));
  575. }
  576. if (type === "component")
  577. this.addCustomComponents(info);
  578. else if (type === "directive")
  579. this.addCustomDirectives(info);
  580. return info;
  581. }
  582. return void 0;
  583. }
  584. normalizePath(path) {
  585. var _a, _b, _c;
  586. return _chunkHCIFGIWSjs.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) || []);
  587. }
  588. relative(path) {
  589. if (path.startsWith("/") && !path.startsWith(this.root))
  590. return _utils.slash.call(void 0, path.slice(1));
  591. return _utils.slash.call(void 0, _path.relative.call(void 0, this.root, path));
  592. }
  593. /**
  594. * This search for components in with the given options.
  595. * Will be called multiple times to ensure file loaded,
  596. * should normally run only once.
  597. */
  598. searchGlob() {
  599. if (this._searched)
  600. return;
  601. searchComponents(this);
  602. debug5.search(this._componentNameMap);
  603. this._searched = true;
  604. }
  605. _generateDeclaration(removeUnused = !this._server) {
  606. if (!this.options.dts)
  607. return;
  608. debug5.decleration("generating");
  609. return writeDeclaration(this, this.options.dts, removeUnused);
  610. }
  611. get componentNameMap() {
  612. return this._componentNameMap;
  613. }
  614. get componentCustomMap() {
  615. return this._componentCustomMap;
  616. }
  617. get directiveCustomMap() {
  618. return this._directiveCustomMap;
  619. }
  620. };
  621. // src/core/unplugin.ts
  622. var PLUGIN_NAME = "unplugin:webpack";
  623. var unplugin_default = _unplugin.createUnplugin.call(void 0, (options = {}) => {
  624. const filter = _pluginutils.createFilter.call(void 0,
  625. options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
  626. options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
  627. );
  628. const ctx = new Context(options);
  629. const api = {
  630. async findComponent(name, filename) {
  631. return await ctx.findComponent(name, "component", filename ? [filename] : []);
  632. },
  633. stringifyImport(info) {
  634. return _chunkHCIFGIWSjs.stringifyComponentImport.call(void 0, info, ctx);
  635. }
  636. };
  637. return {
  638. name: "unplugin-vue-components",
  639. enforce: "post",
  640. api,
  641. transformInclude(id) {
  642. return filter(id);
  643. },
  644. async transform(code, id) {
  645. if (!_chunkHCIFGIWSjs.shouldTransform.call(void 0, code))
  646. return null;
  647. try {
  648. const result = await ctx.transform(code, id);
  649. ctx.generateDeclaration();
  650. return result;
  651. } catch (e) {
  652. this.error(e);
  653. }
  654. },
  655. vite: {
  656. configResolved(config) {
  657. ctx.setRoot(config.root);
  658. ctx.sourcemap = true;
  659. if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
  660. ctx.setTransformer("vue2");
  661. if (ctx.options.dts) {
  662. ctx.searchGlob();
  663. if (!_fs.existsSync.call(void 0, ctx.options.dts))
  664. ctx.generateDeclaration();
  665. }
  666. if (config.build.watch && config.command === "build")
  667. ctx.setupWatcher(_chokidar2.default.watch(ctx.options.globs));
  668. },
  669. configureServer(server) {
  670. ctx.setupViteServer(server);
  671. }
  672. },
  673. webpack(compiler) {
  674. let watcher;
  675. let fileDepQueue = [];
  676. compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
  677. if (!watcher && compiler.watching) {
  678. watcher = compiler.watching;
  679. ctx.setupWatcherWebpack(_chokidar2.default.watch(ctx.options.globs), (path, type) => {
  680. fileDepQueue.push({ path, type });
  681. process.nextTick(() => {
  682. watcher.invalidate();
  683. });
  684. });
  685. }
  686. });
  687. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  688. if (fileDepQueue.length) {
  689. fileDepQueue.forEach(({ path, type }) => {
  690. if (type === "unlink")
  691. compilation.fileDependencies.delete(path);
  692. else
  693. compilation.fileDependencies.add(path);
  694. });
  695. fileDepQueue = [];
  696. }
  697. });
  698. }
  699. };
  700. });
  701. exports.unplugin_default = unplugin_default;