@pedrolamas/plugin-vue2 2.4.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1260 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const fs = require('node:fs');
6
+ const vite = require('vite');
7
+ const node_module = require('node:module');
8
+ const path = require('node:path');
9
+ const node_crypto = require('node:crypto');
10
+
11
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
13
+
14
+ const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
15
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path);
16
+
17
+ function resolveCompiler(root) {
18
+ const compiler = tryRequire("vue/compiler-sfc", root) || tryRequire("vue/compiler-sfc");
19
+ if (!compiler) {
20
+ throw new Error(
21
+ `Failed to resolve vue/compiler-sfc.
22
+ @pedrolamas/plugin-vue2 requires vue (>=2.7.0) to be present in the dependency tree.`
23
+ );
24
+ }
25
+ return compiler;
26
+ }
27
+ const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
28
+ function tryRequire(id, from) {
29
+ try {
30
+ return from ? _require(_require.resolve(id, { paths: [from] })) : _require(id);
31
+ } catch (e) {
32
+ }
33
+ }
34
+
35
+ function parseVueRequest(id) {
36
+ const [filename, rawQuery] = id.split(`?`, 2);
37
+ const query = Object.fromEntries(new URLSearchParams(rawQuery));
38
+ if (query.vue != null) {
39
+ query.vue = true;
40
+ }
41
+ if (query.index != null) {
42
+ query.index = Number(query.index);
43
+ }
44
+ if (query.raw != null) {
45
+ query.raw = true;
46
+ }
47
+ if (query.scoped != null) {
48
+ query.scoped = true;
49
+ }
50
+ return {
51
+ filename,
52
+ query
53
+ };
54
+ }
55
+
56
+ function slash(path) {
57
+ const isExtendedLengthPath = path.startsWith('\\\\?\\');
58
+
59
+ if (isExtendedLengthPath) {
60
+ return path;
61
+ }
62
+
63
+ return path.replace(/\\/g, '/');
64
+ }
65
+
66
+ const cache = /* @__PURE__ */ new Map();
67
+ const prevCache = /* @__PURE__ */ new Map();
68
+ function createDescriptor(filename, source, { root, isProduction, sourceMap, compiler }) {
69
+ let descriptor;
70
+ let errors = [];
71
+ try {
72
+ descriptor = compiler.parse({
73
+ source,
74
+ filename,
75
+ sourceMap
76
+ });
77
+ } catch (e) {
78
+ errors = [e];
79
+ descriptor = compiler.parse({ source: ``, filename });
80
+ }
81
+ const normalizedPath = slash(path__default.normalize(path__default.relative(root, filename)));
82
+ descriptor.id = getHash(normalizedPath + (isProduction ? source : ""));
83
+ cache.set(filename, descriptor);
84
+ return { descriptor, errors };
85
+ }
86
+ function getPrevDescriptor(filename) {
87
+ return prevCache.get(filename);
88
+ }
89
+ function setPrevDescriptor(filename, entry) {
90
+ prevCache.set(filename, entry);
91
+ }
92
+ function getDescriptor(filename, options, createIfNotFound = true) {
93
+ if (cache.has(filename)) {
94
+ return cache.get(filename);
95
+ }
96
+ if (createIfNotFound) {
97
+ const { descriptor, errors } = createDescriptor(
98
+ filename,
99
+ fs__default.readFileSync(filename, "utf-8"),
100
+ options
101
+ );
102
+ if (errors.length) {
103
+ throw errors[0];
104
+ }
105
+ return descriptor;
106
+ }
107
+ }
108
+ function getSrcDescriptor(filename, query) {
109
+ if (query.scoped) {
110
+ return cache.get(`${filename}?src=${query.src}`);
111
+ }
112
+ return cache.get(filename);
113
+ }
114
+ function setSrcDescriptor(filename, entry, scoped) {
115
+ if (scoped) {
116
+ cache.set(`${filename}?src=${entry.id}`, entry);
117
+ return;
118
+ }
119
+ cache.set(filename, entry);
120
+ }
121
+ function getHash(text) {
122
+ return node_crypto.createHash("sha256").update(text).digest("hex").substring(0, 8);
123
+ }
124
+
125
+ const clientCache = /* @__PURE__ */ new WeakMap();
126
+ const ssrCache = /* @__PURE__ */ new WeakMap();
127
+ function getResolvedScript(descriptor, ssr) {
128
+ return (ssr ? ssrCache : clientCache).get(descriptor);
129
+ }
130
+ function setResolvedScript(descriptor, script, ssr) {
131
+ (clientCache).set(descriptor, script);
132
+ }
133
+ function resolveScript(descriptor, options, ssr) {
134
+ if (!descriptor.script && !descriptor.scriptSetup) {
135
+ return null;
136
+ }
137
+ const cacheToUse = ssr ? ssrCache : clientCache;
138
+ const cached = cacheToUse.get(descriptor);
139
+ if (cached) {
140
+ return cached;
141
+ }
142
+ const resolved = options.compiler.compileScript(descriptor, {
143
+ ...options.script,
144
+ id: descriptor.id,
145
+ isProd: options.isProduction,
146
+ sourceMap: options.sourceMap
147
+ });
148
+ cacheToUse.set(descriptor, resolved);
149
+ return resolved;
150
+ }
151
+
152
+ function getDefaultExportFromCjs (x) {
153
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
154
+ }
155
+
156
+ var hashSum;
157
+ var hasRequiredHashSum;
158
+
159
+ function requireHashSum () {
160
+ if (hasRequiredHashSum) return hashSum;
161
+ hasRequiredHashSum = 1;
162
+
163
+ function pad (hash, len) {
164
+ while (hash.length < len) {
165
+ hash = '0' + hash;
166
+ }
167
+ return hash;
168
+ }
169
+
170
+ function fold (hash, text) {
171
+ var i;
172
+ var chr;
173
+ var len;
174
+ if (text.length === 0) {
175
+ return hash;
176
+ }
177
+ for (i = 0, len = text.length; i < len; i++) {
178
+ chr = text.charCodeAt(i);
179
+ hash = ((hash << 5) - hash) + chr;
180
+ hash |= 0;
181
+ }
182
+ return hash < 0 ? hash * -2 : hash;
183
+ }
184
+
185
+ function foldObject (hash, o, seen) {
186
+ return Object.keys(o).sort().reduce(foldKey, hash);
187
+ function foldKey (hash, key) {
188
+ return foldValue(hash, o[key], key, seen);
189
+ }
190
+ }
191
+
192
+ function foldValue (input, value, key, seen) {
193
+ var hash = fold(fold(fold(input, key), toString(value)), typeof value);
194
+ if (value === null) {
195
+ return fold(hash, 'null');
196
+ }
197
+ if (value === undefined) {
198
+ return fold(hash, 'undefined');
199
+ }
200
+ if (typeof value === 'object' || typeof value === 'function') {
201
+ if (seen.indexOf(value) !== -1) {
202
+ return fold(hash, '[Circular]' + key);
203
+ }
204
+ seen.push(value);
205
+
206
+ var objHash = foldObject(hash, value, seen);
207
+
208
+ if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
209
+ return objHash;
210
+ }
211
+
212
+ try {
213
+ return fold(objHash, String(value.valueOf()))
214
+ } catch (err) {
215
+ return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
216
+ }
217
+ }
218
+ return fold(hash, value.toString());
219
+ }
220
+
221
+ function toString (o) {
222
+ return Object.prototype.toString.call(o);
223
+ }
224
+
225
+ function sum (o) {
226
+ return pad(foldValue(0, o, '', []).toString(16), 8);
227
+ }
228
+
229
+ hashSum = sum;
230
+ return hashSum;
231
+ }
232
+
233
+ var hashSumExports = requireHashSum();
234
+ const hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
235
+
236
+ function createRollupError(id, error) {
237
+ if ("msg" in error) {
238
+ return {
239
+ id,
240
+ plugin: "vue",
241
+ message: error.msg,
242
+ name: "vue-compiler-error"
243
+ };
244
+ } else {
245
+ return {
246
+ id,
247
+ plugin: "vue",
248
+ message: error.message,
249
+ name: error.name,
250
+ stack: error.stack
251
+ };
252
+ }
253
+ }
254
+
255
+ const HMR_RUNTIME_ID = "\0plugin-vue2:hmr-runtime";
256
+ const hmrRuntimeCode = `
257
+ var __VUE_HMR_RUNTIME__ = Object.create(null)
258
+ var map = Object.create(null)
259
+
260
+ __VUE_HMR_RUNTIME__.createRecord = function (id, options) {
261
+ if(map[id]) { return }
262
+
263
+ var Ctor = null
264
+ if (typeof options === 'function') {
265
+ Ctor = options
266
+ options = Ctor.options
267
+ }
268
+ makeOptionsHot(id, options)
269
+ map[id] = {
270
+ Ctor: Ctor,
271
+ options: options,
272
+ instances: []
273
+ }
274
+ }
275
+
276
+ __VUE_HMR_RUNTIME__.isRecorded = function (id) {
277
+ return typeof map[id] !== 'undefined'
278
+ }
279
+
280
+ function makeOptionsHot(id, options) {
281
+ if (options.functional) {
282
+ var render = options.render
283
+ options.render = function (h, ctx) {
284
+ var instances = map[id].instances
285
+ if (ctx && instances.indexOf(ctx.parent) < 0) {
286
+ instances.push(ctx.parent)
287
+ }
288
+ return render(h, ctx)
289
+ }
290
+ } else {
291
+ injectHook(options, 'beforeCreate', function() {
292
+ var record = map[id]
293
+ if (!record.Ctor) {
294
+ record.Ctor = this.constructor
295
+ }
296
+ record.instances.push(this)
297
+ })
298
+ injectHook(options, 'beforeDestroy', function() {
299
+ var instances = map[id].instances
300
+ instances.splice(instances.indexOf(this), 1)
301
+ })
302
+ }
303
+ }
304
+
305
+ function injectHook(options, name, hook) {
306
+ var existing = options[name]
307
+ options[name] = existing
308
+ ? Array.isArray(existing) ? existing.concat(hook) : [existing, hook]
309
+ : [hook]
310
+ }
311
+
312
+ function tryWrap(fn) {
313
+ return function (id, arg) {
314
+ try {
315
+ fn(id, arg)
316
+ } catch (e) {
317
+ console.error(e)
318
+ console.warn(
319
+ 'Something went wrong during Vue component hot-reload. Full reload required.'
320
+ )
321
+ }
322
+ }
323
+ }
324
+
325
+ function updateOptions (oldOptions, newOptions) {
326
+ for (var key in oldOptions) {
327
+ if (!(key in newOptions)) {
328
+ delete oldOptions[key]
329
+ }
330
+ }
331
+ for (var key$1 in newOptions) {
332
+ oldOptions[key$1] = newOptions[key$1]
333
+ }
334
+ }
335
+
336
+ __VUE_HMR_RUNTIME__.rerender = tryWrap(function (id, options) {
337
+ var record = map[id]
338
+ if (!options) {
339
+ record.instances.slice().forEach(function (instance) {
340
+ instance.$forceUpdate()
341
+ })
342
+ return
343
+ }
344
+ if (typeof options === 'function') {
345
+ options = options.options
346
+ }
347
+ if(record.functional){
348
+ record.render = options.render
349
+ record.staticRenderFns = options.staticRenderFns
350
+ __VUE_HMR_RUNTIME__.reload(id, record)
351
+ return
352
+ }
353
+ if (record.Ctor) {
354
+ record.Ctor.options.render = options.render
355
+ record.Ctor.options.staticRenderFns = options.staticRenderFns
356
+ record.instances.slice().forEach(function (instance) {
357
+ instance.$options.render = options.render
358
+ instance.$options.staticRenderFns = options.staticRenderFns
359
+ // reset static trees
360
+ // pre 2.5, all static trees are cached together on the instance
361
+ if (instance._staticTrees) {
362
+ instance._staticTrees = []
363
+ }
364
+ // 2.5.0
365
+ if (Array.isArray(record.Ctor.options.cached)) {
366
+ record.Ctor.options.cached = []
367
+ }
368
+ // 2.5.3
369
+ if (Array.isArray(instance.$options.cached)) {
370
+ instance.$options.cached = []
371
+ }
372
+
373
+ // post 2.5.4: v-once trees are cached on instance._staticTrees.
374
+ // Pure static trees are cached on the staticRenderFns array
375
+ // (both already reset above)
376
+
377
+ // 2.6: temporarily mark rendered scoped slots as unstable so that
378
+ // child components can be forced to update
379
+ var restore = patchScopedSlots(instance)
380
+ instance.$forceUpdate()
381
+ instance.$nextTick(restore)
382
+ })
383
+ } else {
384
+ // functional or no instance created yet
385
+ record.options.render = options.render
386
+ record.options.staticRenderFns = options.staticRenderFns
387
+
388
+ // handle functional component re-render
389
+ if (record.options.functional) {
390
+ // rerender with full options
391
+ if (Object.keys(options).length > 2) {
392
+ updateOptions(record.options, options)
393
+ } else {
394
+ // template-only rerender.
395
+ // need to inject the style injection code for CSS modules
396
+ // to work properly.
397
+ var injectStyles = record.options._injectStyles
398
+ if (injectStyles) {
399
+ var render = options.render
400
+ record.options.render = function (h, ctx) {
401
+ injectStyles.call(ctx)
402
+ return render(h, ctx)
403
+ }
404
+ }
405
+ }
406
+ record.options._Ctor = null
407
+ // 2.5.3
408
+ if (Array.isArray(record.options.cached)) {
409
+ record.options.cached = []
410
+ }
411
+ record.instances.slice().forEach(function (instance) {
412
+ instance.$forceUpdate()
413
+ })
414
+ }
415
+ }
416
+ })
417
+
418
+ __VUE_HMR_RUNTIME__.reload = tryWrap(function (id, options) {
419
+ var record = map[id]
420
+ if (options) {
421
+ if (typeof options === 'function') {
422
+ options = options.options
423
+ }
424
+ makeOptionsHot(id, options)
425
+ if (record.Ctor) {
426
+ var newCtor = record.Ctor.super.extend(options)
427
+ // prevent record.options._Ctor from being overwritten accidentally
428
+ newCtor.options._Ctor = record.options._Ctor
429
+ record.Ctor.options = newCtor.options
430
+ record.Ctor.cid = newCtor.cid
431
+ record.Ctor.prototype = newCtor.prototype
432
+ if (newCtor.release) {
433
+ // temporary global mixin strategy used in < 2.0.0-alpha.6
434
+ newCtor.release()
435
+ }
436
+ } else {
437
+ updateOptions(record.options, options)
438
+ }
439
+ }
440
+ record.instances.slice().forEach(function (instance) {
441
+ if (instance.$vnode && instance.$vnode.context) {
442
+ instance.$vnode.context.$forceUpdate()
443
+ } else {
444
+ console.warn(
445
+ 'Root or manually mounted instance modified. Full reload required.'
446
+ )
447
+ }
448
+ })
449
+ })
450
+
451
+ // 2.6 optimizes template-compiled scoped slots and skips updates if child
452
+ // only uses scoped slots. We need to patch the scoped slots resolving helper
453
+ // to temporarily mark all scoped slots as unstable in order to force child
454
+ // updates.
455
+ function patchScopedSlots (instance) {
456
+ if (!instance._u) { return }
457
+ // https://github.com/vuejs/vue/blob/dev/src/core/instance/render-helpers/resolve-scoped-slots.js
458
+ var original = instance._u
459
+ instance._u = function (slots) {
460
+ try {
461
+ // 2.6.4 ~ 2.6.6
462
+ return original(slots, true)
463
+ } catch (e) {
464
+ // 2.5 / >= 2.6.7
465
+ return original(slots, null, true)
466
+ }
467
+ }
468
+ return function () {
469
+ instance._u = original
470
+ }
471
+ }
472
+ export default __VUE_HMR_RUNTIME__
473
+ `;
474
+
475
+ async function transformTemplateAsModule(code, descriptor, options, pluginContext, ssr) {
476
+ let returnCode = compile(code, descriptor, options, pluginContext, ssr);
477
+ if (options.devServer && options.devServer.config.server.hmr !== false && !ssr && !options.isProduction) {
478
+ returnCode += `
479
+ import __VUE_HMR_RUNTIME__ from "${HMR_RUNTIME_ID}"`;
480
+ returnCode += `
481
+ import.meta.hot.accept((updated) => {
482
+ __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(descriptor.id)}, updated)
483
+ })`;
484
+ }
485
+ return returnCode + `
486
+ export { render, staticRenderFns }`;
487
+ }
488
+ function transformTemplateInMain(code, descriptor, options, pluginContext, ssr) {
489
+ return compile(code, descriptor, options, pluginContext, ssr).replace(/var (render|staticRenderFns) =/g, "var _sfc_$1 =").replace(/(render._withStripped)/, "_sfc_$1");
490
+ }
491
+ function compile(code, descriptor, options, pluginContext, ssr) {
492
+ const filename = descriptor.filename;
493
+ const result = options.compiler.compileTemplate({
494
+ ...resolveTemplateCompilerOptions(descriptor, options, ssr),
495
+ source: code
496
+ });
497
+ if (result.errors.length) {
498
+ result.errors.forEach(
499
+ (error) => pluginContext.error(
500
+ typeof error === "string" ? { id: filename, message: error } : createRollupError(filename, error)
501
+ )
502
+ );
503
+ }
504
+ if (result.tips.length) {
505
+ result.tips.forEach(
506
+ (tip) => pluginContext.warn({
507
+ id: filename,
508
+ message: typeof tip === "string" ? tip : tip.msg
509
+ })
510
+ );
511
+ }
512
+ return transformRequireToImport(result.code);
513
+ }
514
+ function resolveTemplateCompilerOptions(descriptor, options, ssr) {
515
+ const block = descriptor.template;
516
+ if (!block) {
517
+ return;
518
+ }
519
+ const resolvedScript = getResolvedScript(descriptor, ssr);
520
+ const hasScoped = descriptor.styles.some((s) => s.scoped);
521
+ const { id, filename } = descriptor;
522
+ let preprocessOptions = block.lang && options.template?.preprocessOptions;
523
+ if (block.lang === "pug") {
524
+ preprocessOptions = {
525
+ doctype: "html",
526
+ ...preprocessOptions
527
+ };
528
+ }
529
+ const transformAssetUrls = options.template?.transformAssetUrls ?? true;
530
+ let assetUrlOptions;
531
+ if (options.devServer) {
532
+ if (filename.startsWith(options.root)) {
533
+ assetUrlOptions = {
534
+ base: (options.devServer.config.server?.origin ?? "") + options.devServer.config.base + slash(path__default.relative(options.root, path__default.dirname(filename)))
535
+ };
536
+ }
537
+ } else if (transformAssetUrls !== false) {
538
+ assetUrlOptions = {
539
+ includeAbsolute: true
540
+ };
541
+ }
542
+ return {
543
+ transformAssetUrls,
544
+ ...options.template,
545
+ filename,
546
+ isProduction: options.isProduction,
547
+ isFunctional: !!block.attrs.functional,
548
+ optimizeSSR: ssr,
549
+ transformAssetUrlsOptions: {
550
+ ...assetUrlOptions,
551
+ ...options.template?.transformAssetUrlsOptions
552
+ },
553
+ preprocessLang: block.lang,
554
+ preprocessOptions,
555
+ bindings: resolvedScript ? resolvedScript.bindings : void 0,
556
+ prettify: false,
557
+ compilerOptions: {
558
+ whitespace: "condense",
559
+ outputSourceRange: true,
560
+ ...options.template?.compilerOptions,
561
+ scopeId: hasScoped ? `data-v-${id}` : void 0
562
+ }
563
+ };
564
+ }
565
+ function transformRequireToImport(code) {
566
+ const imports = {};
567
+ let strImports = "";
568
+ code = code.replace(
569
+ /require\(("(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+')\)/g,
570
+ (_, name) => {
571
+ if (!(name in imports)) {
572
+ imports[name] = `__$_require_${hash(name)}__`;
573
+ strImports += `import ${imports[name]} from ${name}
574
+ `;
575
+ }
576
+ return imports[name];
577
+ }
578
+ );
579
+ return strImports + code;
580
+ }
581
+
582
+ const directRequestRE = /(\?|&)direct\b/;
583
+ async function handleHotUpdate({ file, modules, read, server }, options) {
584
+ const prevDescriptor = getDescriptor(file, options, false);
585
+ if (!prevDescriptor) {
586
+ return;
587
+ }
588
+ setPrevDescriptor(file, prevDescriptor);
589
+ const content = await read();
590
+ const { descriptor } = createDescriptor(file, content, options);
591
+ let needRerender = false;
592
+ const affectedModules = /* @__PURE__ */ new Set();
593
+ const mainModule = modules.find(
594
+ (m) => !/type=/.test(m.url) || /type=script/.test(m.url)
595
+ );
596
+ const templateModule = modules.find((m) => /type=template/.test(m.url));
597
+ const scriptChanged = hasScriptChanged(prevDescriptor, descriptor);
598
+ if (scriptChanged) {
599
+ let scriptModule;
600
+ if (descriptor.scriptSetup?.lang && !descriptor.scriptSetup.src || descriptor.script?.lang && !descriptor.script.src) {
601
+ const scriptModuleRE = new RegExp(
602
+ `type=script.*&lang.${descriptor.scriptSetup?.lang || descriptor.script?.lang}$`
603
+ );
604
+ scriptModule = modules.find((m) => scriptModuleRE.test(m.url));
605
+ }
606
+ affectedModules.add(scriptModule || mainModule);
607
+ }
608
+ if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
609
+ if (!scriptChanged) {
610
+ setResolvedScript(
611
+ descriptor,
612
+ getResolvedScript(prevDescriptor, false));
613
+ }
614
+ affectedModules.add(templateModule);
615
+ needRerender = true;
616
+ }
617
+ const prevStyles = prevDescriptor.styles || [];
618
+ const nextStyles = descriptor.styles || [];
619
+ if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
620
+ affectedModules.add(templateModule);
621
+ affectedModules.add(mainModule);
622
+ }
623
+ for (let i = 0; i < nextStyles.length; i++) {
624
+ const prev = prevStyles[i];
625
+ const next = nextStyles[i];
626
+ if (!prev || !isEqualBlock(prev, next)) {
627
+ const mod = modules.find(
628
+ (m) => m.url.includes(`type=style&index=${i}`) && m.url.endsWith(`.${next.lang || "css"}`) && !directRequestRE.test(m.url)
629
+ );
630
+ if (mod) {
631
+ affectedModules.add(mod);
632
+ if (mod.url.includes("&inline")) {
633
+ affectedModules.add(mainModule);
634
+ }
635
+ } else {
636
+ affectedModules.add(mainModule);
637
+ }
638
+ }
639
+ }
640
+ if (prevStyles.length > nextStyles.length) {
641
+ affectedModules.add(mainModule);
642
+ }
643
+ const prevCustoms = prevDescriptor.customBlocks || [];
644
+ const nextCustoms = descriptor.customBlocks || [];
645
+ if (prevCustoms.length !== nextCustoms.length) {
646
+ affectedModules.add(mainModule);
647
+ } else {
648
+ for (let i = 0; i < nextCustoms.length; i++) {
649
+ const prev = prevCustoms[i];
650
+ const next = nextCustoms[i];
651
+ if (!prev || !isEqualBlock(prev, next)) {
652
+ const mod = modules.find(
653
+ (m) => m.url.includes(`type=${prev.type}&index=${i}`)
654
+ );
655
+ if (mod) {
656
+ affectedModules.add(mod);
657
+ } else {
658
+ affectedModules.add(mainModule);
659
+ }
660
+ }
661
+ }
662
+ }
663
+ if (needRerender) {
664
+ if (!templateModule) {
665
+ affectedModules.add(mainModule);
666
+ } else if (mainModule && !affectedModules.has(mainModule)) {
667
+ const styleImporters = [...mainModule.importers].filter(
668
+ (m) => /\.css($|\?)/.test(m.url)
669
+ );
670
+ styleImporters.forEach((m) => affectedModules.add(m));
671
+ }
672
+ }
673
+ return [...affectedModules].filter(Boolean);
674
+ }
675
+ function isEqualBlock(a, b) {
676
+ if (!a && !b) return true;
677
+ if (!a || !b) return false;
678
+ if (a.src && b.src && a.src === b.src) return true;
679
+ if (a.content !== b.content) return false;
680
+ const keysA = Object.keys(a.attrs);
681
+ const keysB = Object.keys(b.attrs);
682
+ if (keysA.length !== keysB.length) {
683
+ return false;
684
+ }
685
+ return keysA.every((key) => a.attrs[key] === b.attrs[key]);
686
+ }
687
+ function isOnlyTemplateChanged(prev, next) {
688
+ return !hasScriptChanged(prev, next) && prev.styles.length === next.styles.length && prev.styles.every((s, i) => isEqualBlock(s, next.styles[i])) && prev.customBlocks.length === next.customBlocks.length && prev.customBlocks.every((s, i) => isEqualBlock(s, next.customBlocks[i]));
689
+ }
690
+ function hasScriptChanged(prev, next) {
691
+ if (!isEqualBlock(prev.script, next.script)) {
692
+ return true;
693
+ }
694
+ if (!isEqualBlock(prev.scriptSetup, next.scriptSetup)) {
695
+ return true;
696
+ }
697
+ const prevResolvedScript = getResolvedScript(prev, false);
698
+ const prevImports = prevResolvedScript?.imports;
699
+ if (prevImports) {
700
+ return next.shouldForceReload(prevImports);
701
+ }
702
+ return false;
703
+ }
704
+
705
+ const NORMALIZER_ID = "\0plugin-vue2:normalizer";
706
+ const normalizerCode = `
707
+ export default function normalizeComponent (
708
+ scriptExports,
709
+ render,
710
+ staticRenderFns,
711
+ functionalTemplate,
712
+ injectStyles,
713
+ scopeId,
714
+ moduleIdentifier, /* server only */
715
+ shadowMode /* vue-cli only */
716
+ ) {
717
+ // Vue.extend constructor export interop
718
+ var options = typeof scriptExports === 'function'
719
+ ? scriptExports.options
720
+ : scriptExports
721
+
722
+ // render functions
723
+ if (render) {
724
+ options.render = render
725
+ options.staticRenderFns = staticRenderFns
726
+ options._compiled = true
727
+ }
728
+
729
+ // functional template
730
+ if (functionalTemplate) {
731
+ options.functional = true
732
+ }
733
+
734
+ // scopedId
735
+ if (scopeId) {
736
+ options._scopeId = 'data-v-' + scopeId
737
+ }
738
+
739
+ var hook
740
+ if (moduleIdentifier) { // server build
741
+ hook = function (context) {
742
+ // 2.3 injection
743
+ context =
744
+ context || // cached call
745
+ (this.$vnode && this.$vnode.ssrContext) || // stateful
746
+ (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
747
+ // 2.2 with runInNewContext: true
748
+ if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
749
+ context = __VUE_SSR_CONTEXT__
750
+ }
751
+ // inject component styles
752
+ if (injectStyles) {
753
+ injectStyles.call(this, context)
754
+ }
755
+ // register component module identifier for async chunk inference
756
+ if (context && context._registeredComponents) {
757
+ context._registeredComponents.add(moduleIdentifier)
758
+ }
759
+ }
760
+ // used by ssr in case component is cached and beforeCreate
761
+ // never gets called
762
+ options._ssrRegister = hook
763
+ } else if (injectStyles) {
764
+ hook = shadowMode
765
+ ? function () {
766
+ injectStyles.call(
767
+ this,
768
+ (options.functional ? this.parent : this).$root.$options.shadowRoot
769
+ )
770
+ }
771
+ : injectStyles
772
+ }
773
+
774
+ if (hook) {
775
+ if (options.functional) {
776
+ // for template-only hot-reload because in that case the render fn doesn't
777
+ // go through the normalizer
778
+ options._injectStyles = hook
779
+ // register for functional component in vue file
780
+ var originalRender = options.render
781
+ options.render = function renderWithStyleInjection (h, context) {
782
+ hook.call(context)
783
+ return originalRender(h, context)
784
+ }
785
+ } else {
786
+ // inject component registration as beforeCreate hook
787
+ var existing = options.beforeCreate
788
+ options.beforeCreate = existing
789
+ ? [].concat(existing, hook)
790
+ : [hook]
791
+ }
792
+ }
793
+
794
+ return {
795
+ exports: scriptExports,
796
+ options: options
797
+ }
798
+ }`;
799
+
800
+ async function transformMain(code, filename, options, pluginContext, ssr) {
801
+ const { devServer, isProduction, devToolsEnabled } = options;
802
+ const prevDescriptor = getPrevDescriptor(filename);
803
+ const { descriptor, errors } = createDescriptor(filename, code, options);
804
+ if (errors.length) {
805
+ errors.forEach(
806
+ (error) => pluginContext.error(createRollupError(filename, error))
807
+ );
808
+ return null;
809
+ }
810
+ const hasScoped = descriptor.styles.some((s) => s.scoped);
811
+ const hasCssModules = descriptor.styles.some((s) => s.module);
812
+ const hasFunctional = descriptor.template && descriptor.template.attrs.functional;
813
+ const { code: scriptCode, map: scriptMap } = await genScriptCode(
814
+ descriptor,
815
+ options,
816
+ pluginContext,
817
+ ssr
818
+ );
819
+ const templateCode = await genTemplateCode(
820
+ descriptor,
821
+ options,
822
+ pluginContext,
823
+ ssr
824
+ );
825
+ const stylesCode = await genStyleCode(descriptor, pluginContext);
826
+ const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext);
827
+ const output = [
828
+ scriptCode,
829
+ templateCode,
830
+ stylesCode,
831
+ customBlocksCode
832
+ ];
833
+ output.push(
834
+ `/* normalize component */
835
+ import __normalizer from "${NORMALIZER_ID}"
836
+ var __component__ = /*#__PURE__*/__normalizer(
837
+ _sfc_main,
838
+ _sfc_render,
839
+ _sfc_staticRenderFns,
840
+ ${hasFunctional ? "true" : "false"},
841
+ ${hasCssModules ? `_sfc_injectStyles` : `null`},
842
+ ${hasScoped ? JSON.stringify(descriptor.id) : "null"},
843
+ null,
844
+ null
845
+ )`
846
+ );
847
+ if (devToolsEnabled || devServer && !isProduction) {
848
+ output.push(
849
+ `__component__.options.__file = ${JSON.stringify(
850
+ isProduction ? path__default.basename(filename) : filename
851
+ )}`
852
+ );
853
+ }
854
+ if (devServer && devServer.config.server.hmr !== false && !ssr && !isProduction) {
855
+ const id = JSON.stringify(descriptor.id);
856
+ output.push(
857
+ `import __VUE_HMR_RUNTIME__ from "${HMR_RUNTIME_ID}"`,
858
+ `if (!__VUE_HMR_RUNTIME__.isRecorded(${id})) {`,
859
+ ` __VUE_HMR_RUNTIME__.createRecord(${id}, __component__.options)`,
860
+ `}`
861
+ );
862
+ if (hasFunctional || prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) {
863
+ output.push(`export const _rerender_only = true`);
864
+ }
865
+ output.push(
866
+ `import.meta.hot.accept(mod => {`,
867
+ ` if (!mod) return`,
868
+ ` const { default: updated, _rerender_only } = mod`,
869
+ ` if (_rerender_only) {`,
870
+ ` __VUE_HMR_RUNTIME__.rerender(${id}, updated)`,
871
+ ` } else {`,
872
+ ` __VUE_HMR_RUNTIME__.reload(${id}, updated)`,
873
+ ` }`,
874
+ `})`
875
+ );
876
+ }
877
+ let resolvedMap = scriptMap;
878
+ output.push(`export default __component__.exports`);
879
+ let resolvedCode = output.join("\n");
880
+ if ((descriptor.script?.lang === "ts" || descriptor.scriptSetup?.lang === "ts") && !descriptor.script?.src) {
881
+ resolvedMap = resolvedMap ? { ...resolvedMap, file: resolvedMap.file ?? filename } : void 0;
882
+ const { code: code2, map } = await vite.transformWithOxc(
883
+ resolvedCode,
884
+ filename,
885
+ {
886
+ lang: "ts",
887
+ sourcemap: options.sourceMap
888
+ },
889
+ resolvedMap
890
+ );
891
+ resolvedCode = code2;
892
+ resolvedMap = resolvedMap ? map : resolvedMap;
893
+ }
894
+ return {
895
+ code: resolvedCode,
896
+ map: resolvedMap || {
897
+ mappings: ""
898
+ },
899
+ meta: {
900
+ vite: {
901
+ lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js"
902
+ }
903
+ }
904
+ };
905
+ }
906
+ async function genTemplateCode(descriptor, options, pluginContext, ssr) {
907
+ const template = descriptor.template;
908
+ if (!template) {
909
+ return "const _sfc_render = null; const _sfc_staticRenderFns = null";
910
+ }
911
+ const hasScoped = descriptor.styles.some((style) => style.scoped);
912
+ if (!template.lang && !template.src) {
913
+ return transformTemplateInMain(
914
+ template.content,
915
+ descriptor,
916
+ options,
917
+ pluginContext,
918
+ ssr
919
+ );
920
+ } else {
921
+ if (template.src) {
922
+ await linkSrcToDescriptor(
923
+ template.src,
924
+ descriptor,
925
+ pluginContext,
926
+ hasScoped
927
+ );
928
+ }
929
+ const src = template.src || descriptor.filename;
930
+ const srcQuery = template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : "";
931
+ const scopedQuery = hasScoped ? `&scoped=${descriptor.id}` : ``;
932
+ const attrsQuery = attrsToQuery(template.attrs, "js", true);
933
+ const query = `?vue&type=template${srcQuery}${scopedQuery}${attrsQuery}`;
934
+ const request = JSON.stringify(src + query);
935
+ return `import { render as _sfc_render, staticRenderFns as _sfc_staticRenderFns } from ${request}`;
936
+ }
937
+ }
938
+ async function genScriptCode(descriptor, options, pluginContext, ssr) {
939
+ let scriptCode = `const _sfc_main = {}`;
940
+ let map;
941
+ const script = resolveScript(descriptor, options, ssr);
942
+ if (script) {
943
+ if ((!script.lang || script.lang === "ts" && options.devServer) && !script.src) {
944
+ const userPlugins = options.script?.babelParserPlugins || [];
945
+ const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
946
+ scriptCode = options.compiler.rewriteDefault(
947
+ script.content,
948
+ "_sfc_main",
949
+ [...defaultPlugins, ...userPlugins]
950
+ );
951
+ map = script.map;
952
+ } else {
953
+ if (script.src) {
954
+ await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
955
+ }
956
+ const src = script.src || descriptor.filename;
957
+ const langFallback = script.src && path__default.extname(src).slice(1) || "js";
958
+ const attrsQuery = attrsToQuery(script.attrs, langFallback);
959
+ const srcQuery = script.src ? `&src=true` : ``;
960
+ const query = `?vue&type=script${srcQuery}${attrsQuery}`;
961
+ const request = JSON.stringify(src + query);
962
+ scriptCode = `import _sfc_main from ${request}
963
+ export * from ${request}`;
964
+ }
965
+ }
966
+ return {
967
+ code: scriptCode,
968
+ map
969
+ };
970
+ }
971
+ async function genStyleCode(descriptor, pluginContext) {
972
+ let stylesCode = ``;
973
+ let cssModulesMap;
974
+ if (descriptor.styles.length) {
975
+ for (let i = 0; i < descriptor.styles.length; i++) {
976
+ const style = descriptor.styles[i];
977
+ if (style.src) {
978
+ await linkSrcToDescriptor(
979
+ style.src,
980
+ descriptor,
981
+ pluginContext,
982
+ style.scoped
983
+ );
984
+ }
985
+ const src = style.src || descriptor.filename;
986
+ const attrsQuery = attrsToQuery(style.attrs, "css");
987
+ const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
988
+ const directQuery = ``;
989
+ const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
990
+ const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}`;
991
+ const styleRequest = src + query + attrsQuery;
992
+ if (style.module) {
993
+ const [importCode, nameMap] = genCSSModulesCode(
994
+ i,
995
+ styleRequest,
996
+ style.module
997
+ );
998
+ stylesCode += importCode;
999
+ Object.assign(cssModulesMap ||= {}, nameMap);
1000
+ } else {
1001
+ stylesCode += `
1002
+ import ${JSON.stringify(styleRequest)}`;
1003
+ }
1004
+ }
1005
+ }
1006
+ if (cssModulesMap) {
1007
+ const mappingCode = Object.entries(cssModulesMap).reduce(
1008
+ (code, [key, value]) => code + `"${key}":${value},
1009
+ `,
1010
+ "{\n"
1011
+ ) + "}";
1012
+ stylesCode += `
1013
+ const __cssModules = ${mappingCode}`;
1014
+ stylesCode += `
1015
+ function _sfc_injectStyles(ctx) {
1016
+ for (var key in __cssModules) {
1017
+ this[key] = __cssModules[key]
1018
+ }
1019
+ }`;
1020
+ }
1021
+ return stylesCode;
1022
+ }
1023
+ function genCSSModulesCode(index, request, moduleName) {
1024
+ const styleVar = `style${index}`;
1025
+ const exposedName = typeof moduleName === "string" ? moduleName : "$style";
1026
+ const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
1027
+ return [
1028
+ `
1029
+ import ${styleVar} from ${JSON.stringify(moduleRequest)}`,
1030
+ { [exposedName]: styleVar }
1031
+ ];
1032
+ }
1033
+ async function genCustomBlockCode(descriptor, pluginContext) {
1034
+ let code = "";
1035
+ for (let index = 0; index < descriptor.customBlocks.length; index++) {
1036
+ const block = descriptor.customBlocks[index];
1037
+ if (block.src) {
1038
+ await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
1039
+ }
1040
+ const src = block.src || descriptor.filename;
1041
+ const attrsQuery = attrsToQuery(block.attrs, block.type);
1042
+ const srcQuery = block.src ? `&src=true` : ``;
1043
+ const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
1044
+ const request = JSON.stringify(src + query);
1045
+ code += `import block${index} from ${request}
1046
+ `;
1047
+ code += `if (typeof block${index} === 'function') block${index}(_sfc_main)
1048
+ `;
1049
+ }
1050
+ return code;
1051
+ }
1052
+ async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
1053
+ const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src;
1054
+ setSrcDescriptor(srcFile.replace(/\?.*$/, ""), descriptor, scoped);
1055
+ }
1056
+ const ignoreList = ["id", "index", "src", "type", "lang", "module", "scoped"];
1057
+ function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
1058
+ let query = ``;
1059
+ for (const name in attrs) {
1060
+ const value = attrs[name];
1061
+ if (!ignoreList.includes(name)) {
1062
+ query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
1063
+ }
1064
+ }
1065
+ if (langFallback || attrs.lang) {
1066
+ query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
1067
+ }
1068
+ return query;
1069
+ }
1070
+
1071
+ async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
1072
+ const block = descriptor.styles[index];
1073
+ const result = await options.compiler.compileStyleAsync({
1074
+ ...options.style,
1075
+ filename: descriptor.filename,
1076
+ id: `data-v-${descriptor.id}`,
1077
+ isProd: options.isProduction,
1078
+ source: code,
1079
+ scoped: !!block.scoped,
1080
+ ...options.cssDevSourcemap ? {
1081
+ postcssOptions: {
1082
+ map: {
1083
+ from: filename,
1084
+ inline: false,
1085
+ annotation: false
1086
+ }
1087
+ }
1088
+ } : {}
1089
+ });
1090
+ if (result.errors.length) {
1091
+ result.errors.forEach((error) => {
1092
+ if (error.line && error.column) {
1093
+ error.loc = {
1094
+ file: descriptor.filename,
1095
+ line: error.line + getLine(descriptor.source, block.start),
1096
+ column: error.column
1097
+ };
1098
+ }
1099
+ pluginContext.error(error);
1100
+ });
1101
+ return null;
1102
+ }
1103
+ const map = result.map ? await vite.formatPostcssSourceMap(
1104
+ // version property of result.map is declared as string
1105
+ // but actually it is a number
1106
+ result.map,
1107
+ filename
1108
+ ) : { mappings: "" };
1109
+ return {
1110
+ code: result.code,
1111
+ map
1112
+ };
1113
+ }
1114
+ function getLine(source, start) {
1115
+ const lines = source.split(/\r?\n/g);
1116
+ let cur = 0;
1117
+ for (let i = 0; i < lines.length; i++) {
1118
+ cur += lines[i].length;
1119
+ if (cur >= start) {
1120
+ return i;
1121
+ }
1122
+ }
1123
+ }
1124
+
1125
+ function vuePlugin(rawOptions = {}) {
1126
+ const {
1127
+ include = /\.vue$/,
1128
+ exclude
1129
+ // customElement = /\.ce\.vue$/,
1130
+ // reactivityTransform = false
1131
+ } = rawOptions;
1132
+ const filter = vite.createFilter(include, exclude);
1133
+ let options = {
1134
+ isProduction: process.env.NODE_ENV === "production",
1135
+ compiler: null,
1136
+ // to be set in buildStart
1137
+ ...rawOptions,
1138
+ include,
1139
+ exclude,
1140
+ // customElement,
1141
+ // reactivityTransform,
1142
+ root: process.cwd(),
1143
+ sourceMap: true,
1144
+ cssDevSourcemap: false,
1145
+ devToolsEnabled: process.env.NODE_ENV !== "production"
1146
+ };
1147
+ return {
1148
+ name: "vite:vue2",
1149
+ handleHotUpdate(ctx) {
1150
+ if (!filter(ctx.file)) {
1151
+ return;
1152
+ }
1153
+ return handleHotUpdate(ctx, options);
1154
+ },
1155
+ configResolved(config) {
1156
+ options = {
1157
+ ...options,
1158
+ root: config.root,
1159
+ isProduction: config.isProduction,
1160
+ sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
1161
+ cssDevSourcemap: config.css?.devSourcemap ?? false,
1162
+ devToolsEnabled: !config.isProduction
1163
+ };
1164
+ if (!config.resolve.alias.some(({ find }) => find === "vue")) {
1165
+ config.resolve.alias.push({
1166
+ find: "vue",
1167
+ replacement: "vue/dist/vue.runtime.esm.js"
1168
+ });
1169
+ }
1170
+ },
1171
+ configureServer(server) {
1172
+ options.devServer = server;
1173
+ },
1174
+ buildStart() {
1175
+ options.compiler = options.compiler || resolveCompiler(options.root);
1176
+ },
1177
+ async resolveId(id) {
1178
+ if (id === NORMALIZER_ID || id === HMR_RUNTIME_ID) {
1179
+ return id;
1180
+ }
1181
+ if (parseVueRequest(id).query.vue) {
1182
+ return id;
1183
+ }
1184
+ },
1185
+ load(id, opt) {
1186
+ const ssr = opt?.ssr === true;
1187
+ if (id === NORMALIZER_ID) {
1188
+ return normalizerCode;
1189
+ }
1190
+ if (id === HMR_RUNTIME_ID) {
1191
+ return hmrRuntimeCode;
1192
+ }
1193
+ const { filename, query } = parseVueRequest(id);
1194
+ if (query.vue) {
1195
+ if (query.src) {
1196
+ return fs__default.readFileSync(filename, "utf-8");
1197
+ }
1198
+ const descriptor = getDescriptor(filename, options);
1199
+ let block;
1200
+ if (query.type === "script") {
1201
+ block = getResolvedScript(descriptor, ssr);
1202
+ } else if (query.type === "template") {
1203
+ block = descriptor.template;
1204
+ } else if (query.type === "style") {
1205
+ block = descriptor.styles[query.index];
1206
+ } else if (query.index != null) {
1207
+ block = descriptor.customBlocks[query.index];
1208
+ }
1209
+ if (block) {
1210
+ return {
1211
+ code: block.content,
1212
+ map: block.map
1213
+ };
1214
+ }
1215
+ }
1216
+ },
1217
+ async transform(code, id, opt) {
1218
+ const ssr = opt?.ssr === true;
1219
+ const { filename, query } = parseVueRequest(id);
1220
+ if (query.raw) {
1221
+ return;
1222
+ }
1223
+ if (!filter(filename) && !query.vue) {
1224
+ return;
1225
+ }
1226
+ if (!query.vue) {
1227
+ return transformMain(code, filename, options, this, ssr);
1228
+ } else {
1229
+ const descriptor = query.src ? getSrcDescriptor(filename, query) : getDescriptor(filename, options);
1230
+ if (query.type === "template") {
1231
+ return {
1232
+ code: await transformTemplateAsModule(
1233
+ code,
1234
+ descriptor,
1235
+ options,
1236
+ this,
1237
+ ssr
1238
+ ),
1239
+ map: {
1240
+ mappings: ""
1241
+ }
1242
+ };
1243
+ } else if (query.type === "style") {
1244
+ return transformStyle(
1245
+ code,
1246
+ descriptor,
1247
+ Number(query.index),
1248
+ options,
1249
+ this,
1250
+ filename
1251
+ );
1252
+ }
1253
+ }
1254
+ }
1255
+ };
1256
+ }
1257
+
1258
+ module.exports = vuePlugin;
1259
+ module.exports.default = vuePlugin;
1260
+ module.exports.parseVueRequest = parseVueRequest;