unplugin-vue-components 29.2.0 → 31.0.0

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