@vizejs/vite-plugin 0.101.0 → 0.104.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 (2) hide show
  1. package/dist/index.mjs +109 -90
  2. package/package.json +10 -3
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from "node:module";
2
- import fs from "node:fs";
3
2
  import { createHash } from "node:crypto";
4
3
  import * as native from "@vizejs/native";
5
- import { applyViteDefineReplacements, classifyVitePluginRequest, createViteBareImportBases, createViteBareImportCandidates, createViteVirtualId, detectViteHmrUpdateType, generateViteHmrCode, hasViteHmrChanges, isViteBareSpecifier, normalizeViteRequireBase, normalizeViteResolvedVuePath, resolveViteAliasRequest, resolveViteCssImports, resolveViteRelativeImport, resolveViteVuePath, rewriteViteDynamicTemplateImports, rewriteViteStaticAssetUrls, scopeViteCssForPipeline, shouldApplyViteDefineInVirtualModule, splitViteIdQuery, toViteBrowserImportPrefix } from "@vizejs/native";
4
+ import { applyViteDefineReplacements, chunkVitePrecompileFiles, classifyVitePluginRequest, createViteBareImportBases, createViteBareImportCandidates, createViteVirtualId, detectViteHmrUpdateType, diffVitePrecompileFiles, generateViteHmrCode, hasViteHmrChanges, isViteBareSpecifier, normalizeViteCssModuleFilename, normalizeViteDevMiddlewareUrl, normalizeVitePrecompileBatchSize, normalizeViteRequireBase, normalizeViteResolvedVuePath, resolveViteAliasRequest, resolveViteCssImports, resolveViteRelativeImport, resolveViteVuePath, rewriteViteDynamicTemplateImports, rewriteViteStaticAssetUrls, scopeViteCssForPipeline, shouldApplyViteDefineInVirtualModule, splitViteIdQuery, toViteBrowserImportPrefix } from "@vizejs/native";
6
5
  import { CONFIG_FILE_NAMES, defineConfig, loadConfig } from "vize";
6
+ import fs from "node:fs";
7
7
  import { glob } from "tinyglobby";
8
8
  import path from "node:path";
9
9
  import { pathToFileURL } from "node:url";
@@ -266,6 +266,19 @@ function buildCompileBatchOptions(options) {
266
266
  //#endregion
267
267
  //#region src/compiler.ts
268
268
  const { compileSfc, compileSfcBatchWithResults } = native;
269
+ var VizeSfcCompileError = class extends Error {
270
+ filePath;
271
+ diagnostics;
272
+ constructor(filePath, diagnostics) {
273
+ super(formatCompileErrorMessage(filePath, diagnostics));
274
+ this.name = "VizeSfcCompileError";
275
+ this.filePath = filePath;
276
+ this.diagnostics = diagnostics;
277
+ }
278
+ };
279
+ function formatCompileErrorMessage(filePath, diagnostics) {
280
+ return `[vize] Compilation failed in ${filePath}:\n${diagnostics.map((diagnostic) => ` - ${diagnostic}`).join("\n")}`;
281
+ }
269
282
  function normalizeStyleBlocks(styles) {
270
283
  if (!styles) return [];
271
284
  return styles.map((block) => ({
@@ -280,10 +293,7 @@ function compileFile(filePath, cache, options, source) {
280
293
  const content = source ?? fs.readFileSync(filePath, "utf-8");
281
294
  const scopeId = generateScopeId(filePath);
282
295
  const result = compileSfc(content, buildCompileFileOptions(filePath, options));
283
- if (result.errors.length > 0) {
284
- const errorMsg = result.errors.join("\n");
285
- console.error(`[vize] Compilation error in ${filePath}:\n${errorMsg}`);
286
- }
296
+ if (result.errors.length > 0) throw new VizeSfcCompileError(filePath, result.errors);
287
297
  if (result.warnings.length > 0) result.warnings.forEach((warning) => {
288
298
  console.warn(`[vize] Warning in ${filePath}: ${warning}`);
289
299
  });
@@ -319,13 +329,15 @@ function compileBatch(files, cache, options) {
319
329
  macroArtifacts: fileResult.macroArtifacts ?? [],
320
330
  styles: normalizeStyleBlocks(fileResult.styles)
321
331
  });
322
- if (fileResult.errors.length > 0) console.error(`[vize] Compilation error in ${fileResult.path}:\n${fileResult.errors.join("\n")}`);
332
+ if (fileResult.errors.length > 0) console.error(formatCompileErrorMessage(fileResult.path, fileResult.errors));
323
333
  if (fileResult.warnings.length > 0) fileResult.warnings.forEach((warning) => {
324
334
  console.warn(`[vize] Warning in ${fileResult.path}: ${warning}`);
325
335
  });
326
336
  }
327
337
  return result;
328
338
  }
339
+ //#endregion
340
+ //#region src/plugin/precompile.ts
329
341
  const DEFAULT_PRECOMPILE_IGNORE_PATTERNS = [
330
342
  "node_modules/**",
331
343
  "dist/**",
@@ -335,46 +347,29 @@ const DEFAULT_PRECOMPILE_IGNORE_PATTERNS = [
335
347
  ".nitro/**",
336
348
  "coverage/**"
337
349
  ];
338
- function hasFileMetadataChanged(previous, next) {
339
- return previous === void 0 || previous.mtimeMs !== next.mtimeMs || previous.size !== next.size;
340
- }
341
350
  function diffPrecompileFiles(files, currentMetadata, previousMetadata) {
342
- const changedFiles = [];
343
- const seenFiles = new Set(files);
344
- for (const file of files) {
345
- const metadata = currentMetadata.get(file);
346
- if (!metadata || hasFileMetadataChanged(previousMetadata.get(file), metadata)) changedFiles.push(file);
347
- }
348
- const deletedFiles = [];
349
- for (const file of previousMetadata.keys()) if (!seenFiles.has(file)) deletedFiles.push(file);
350
- return {
351
- changedFiles,
352
- deletedFiles
353
- };
351
+ return diffVitePrecompileFiles([...files], toNativePrecompileMetadataEntries(currentMetadata), toNativePrecompileMetadataEntries(previousMetadata));
354
352
  }
355
353
  function normalizePrecompileBatchSize(value) {
356
- if (value === void 0 || !Number.isFinite(value) || value <= 0) return 128;
357
- return Math.max(1, Math.floor(value));
354
+ return normalizeVitePrecompileBatchSize(value);
358
355
  }
359
356
  function chunkPrecompileFiles(files, batchSize, options = {}) {
360
- const normalizedBatchSize = normalizePrecompileBatchSize(batchSize);
361
- const maxBytes = Math.max(1, Math.floor(options.maxBytes ?? 33554432));
362
- const chunks = [];
363
- let current = [];
364
- let currentBytes = 0;
365
- for (const file of files) {
366
- const fileBytes = Math.max(0, options.metadata?.get(file)?.size ?? 0);
367
- if (current.length > 0 && (current.length >= normalizedBatchSize || currentBytes + fileBytes > maxBytes)) {
368
- chunks.push(current);
369
- current = [];
370
- currentBytes = 0;
371
- }
372
- current.push(file);
373
- currentBytes += fileBytes;
374
- }
375
- if (current.length > 0) chunks.push(current);
376
- return chunks;
357
+ return chunkVitePrecompileFiles([...files], batchSize, {
358
+ maxBytes: options.maxBytes,
359
+ metadata: options.metadata ? toNativePrecompileMetadataEntries(options.metadata) : void 0
360
+ });
377
361
  }
362
+ function toNativePrecompileMetadataEntries(metadata) {
363
+ const entries = [];
364
+ for (const [path, value] of metadata) entries.push({
365
+ path,
366
+ mtimeMs: value.mtimeMs,
367
+ size: value.size
368
+ });
369
+ return entries;
370
+ }
371
+ //#endregion
372
+ //#region src/plugin/state.ts
378
373
  function getEnvironmentCache(state, ssr) {
379
374
  return ssr ? state.ssrCache : state.cache;
380
375
  }
@@ -433,6 +428,7 @@ async function compileAll(state) {
433
428
  let successCount = 0;
434
429
  let failedCount = 0;
435
430
  let nativeTimeMs = 0;
431
+ const precompileFailures = [];
436
432
  const chunks = chunkPrecompileFiles(changedFiles, state.precompileBatchSize, { metadata: currentMetadata });
437
433
  for (const chunk of chunks) {
438
434
  const fileContents = [];
@@ -447,6 +443,7 @@ async function compileAll(state) {
447
443
  state.cache.delete(file);
448
444
  state.collectedCss.delete(file);
449
445
  state.precompileMetadata.delete(file);
446
+ precompileFailures.push(`[vize] Failed to read ${file}: ${formatUnknownError$1(e)}`);
450
447
  state.logger.error(`Failed to read ${file}:`, e);
451
448
  }
452
449
  if (fileContents.length === 0) continue;
@@ -455,8 +452,9 @@ async function compileAll(state) {
455
452
  vapor: state.mergedOptions.vapor ?? false,
456
453
  customRenderer: state.mergedOptions.customRenderer ?? false
457
454
  });
458
- successCount += result.successCount;
459
- failedCount += result.failedCount;
455
+ const chunkFailedCount = result.results.filter((fileResult) => fileResult.errors.length > 0).length;
456
+ failedCount += chunkFailedCount;
457
+ successCount += result.results.length - chunkFailedCount;
460
458
  nativeTimeMs += result.timeMs;
461
459
  for (const fileResult of result.results) {
462
460
  const metadata = currentMetadata.get(fileResult.path);
@@ -464,6 +462,7 @@ async function compileAll(state) {
464
462
  state.cache.delete(fileResult.path);
465
463
  state.collectedCss.delete(fileResult.path);
466
464
  state.precompileMetadata.delete(fileResult.path);
465
+ precompileFailures.push(formatCompileErrorMessage(fileResult.path, fileResult.errors));
467
466
  continue;
468
467
  }
469
468
  if (metadata) state.precompileMetadata.set(fileResult.path, metadata);
@@ -473,6 +472,13 @@ async function compileAll(state) {
473
472
  const elapsed = (performance.now() - startTime).toFixed(2);
474
473
  const batchLabel = chunks.length === 1 ? "batch" : "batches";
475
474
  state.logger.info(`Pre-compilation complete: ${successCount} recompiled, ${cachedFileCount} reused, ${failedCount} failed (${elapsed}ms, native ${batchLabel}: ${nativeTimeMs.toFixed(2)}ms)`);
475
+ if (failedCount > 0) {
476
+ const details = precompileFailures.length > 0 ? `\n\n${precompileFailures.join("\n\n")}` : "";
477
+ throw new Error(`[vize] Pre-compilation failed for ${failedCount} file(s).${details}`);
478
+ }
479
+ }
480
+ function formatUnknownError$1(error) {
481
+ return error instanceof Error ? error.message : String(error);
476
482
  }
477
483
  //#endregion
478
484
  //#region src/plugin/resolve.ts
@@ -503,6 +509,12 @@ function normalizeResolvedVuePath(id) {
503
509
  function nativeCssAliasRules(state) {
504
510
  return state.cssAliasRules.length === 0 ? EMPTY_NATIVE_ALIAS_RULES : state.cssAliasRules.map(toNativeCssAliasRule);
505
511
  }
512
+ function isPotentialVizeResolveId(id) {
513
+ return id.startsWith("\0") || id.startsWith("vize:") || id.startsWith("/@fs") || id === "virtual:vize-styles" || id.endsWith(".vue") || id.includes(".vue?") || id.includes("?macro=true") || id.includes("?definePage");
514
+ }
515
+ function isPotentialVizeImporter(importer) {
516
+ return importer !== void 0 && (importer.startsWith("\0") || importer.startsWith("vize:"));
517
+ }
506
518
  async function resolveAliasedVueImport(ctx, state, id, importer, isSsrRequest, handleNodeModules) {
507
519
  if (path.isAbsolute(id)) return null;
508
520
  const viteImporter = normalizeViteRequireBase(importer) ?? importer;
@@ -525,6 +537,7 @@ async function resolveAliasedVueImport(ctx, state, id, importer, isSsrRequest, h
525
537
  return null;
526
538
  }
527
539
  async function resolveIdHook(ctx, state, id, importer, options) {
540
+ if (!isPotentialVizeResolveId(id) && !isPotentialVizeImporter(importer)) return null;
528
541
  const isBuild = state.server === null;
529
542
  const importerRequest = importer ? classifyVitePluginRequest(importer) : null;
530
543
  const isSsrRequest = !!options?.ssr || (importerRequest?.isVizeSsrVirtual ?? false);
@@ -599,12 +612,14 @@ async function resolveIdHook(ctx, state, id, importer, options) {
599
612
  ...resolved,
600
613
  id: normalizedFsId
601
614
  };
602
- const nodeResolved = resolveBareImportCandidatesWithNode(state, id, cleanImporter, resolved.id);
603
- if (nodeResolved) {
604
- state.logger.log(`resolveId: normalized bare ${id} to ${nodeResolved} via Node fallback`);
605
- return nodeResolved;
615
+ if (isViteBareSpecifier(resolved.id)) {
616
+ const nodeResolved = resolveBareImportCandidatesWithNode(state, id, cleanImporter, resolved.id);
617
+ if (nodeResolved) {
618
+ state.logger.log(`resolveId: normalized bare ${id} to ${nodeResolved} via Node fallback`);
619
+ return nodeResolved;
620
+ }
621
+ return null;
606
622
  }
607
- if (isViteBareSpecifier(resolved.id)) return null;
608
623
  return resolved;
609
624
  }
610
625
  } catch {}
@@ -623,12 +638,14 @@ async function resolveIdHook(ctx, state, id, importer, options) {
623
638
  ...resolved,
624
639
  id: normalizedFsId
625
640
  };
626
- const nodeResolved = resolveBareImportCandidatesWithNode(state, id, cleanImporter, resolved.id);
627
- if (nodeResolved) {
628
- state.logger.log(`resolveId: normalized aliased bare ${id} to ${nodeResolved} via Node fallback`);
629
- return nodeResolved;
641
+ if (isViteBareSpecifier(resolved.id)) {
642
+ const nodeResolved = resolveBareImportCandidatesWithNode(state, id, cleanImporter, resolved.id);
643
+ if (nodeResolved) {
644
+ state.logger.log(`resolveId: normalized aliased bare ${id} to ${nodeResolved} via Node fallback`);
645
+ return nodeResolved;
646
+ }
647
+ return null;
630
648
  }
631
- if (isViteBareSpecifier(resolved.id)) return null;
632
649
  return resolved;
633
650
  }
634
651
  } catch {}
@@ -745,6 +762,7 @@ function loadDefinePageMetaArtifact(state, realPath, ssr) {
745
762
  } : null;
746
763
  }
747
764
  function loadHook(state, id, loadOptions) {
765
+ if (id !== "\0vize:all-styles.css" && !id.startsWith("\0")) return null;
748
766
  const currentBase = loadOptions?.ssr ? state.serverViteBase : state.clientViteBase;
749
767
  const request = classifyVitePluginRequest(id);
750
768
  if (id === "\0vize:all-styles.css") {
@@ -866,6 +884,7 @@ function loadHook(state, id, loadOptions) {
866
884
  return null;
867
885
  }
868
886
  async function transformHook(state, code, id, options) {
887
+ if (!id.startsWith("\0")) return null;
869
888
  const request = classifyVitePluginRequest(id);
870
889
  if (request.isVizeVirtual || request.isMacroVirtualId) {
871
890
  const realPath = request.isMacroVirtualId ? request.strippedVirtualPath ?? "" : request.vizeVirtualPath ?? "";
@@ -883,17 +902,23 @@ async function transformHook(state, code, id, options) {
883
902
  };
884
903
  } catch (e) {
885
904
  state.logger.error(`transformWithOxc failed for ${realPath}:`, e);
886
- const dumpPath = getOxcDumpPath(state.root, realPath);
887
- fs.writeFileSync(dumpPath, code, "utf-8");
888
- state.logger.error(`Dumped failing code to ${dumpPath}`);
889
- return {
890
- code: "export default {}",
891
- map: null
892
- };
905
+ let dumpPath = null;
906
+ try {
907
+ dumpPath = getOxcDumpPath(state.root, realPath);
908
+ fs.writeFileSync(dumpPath, code, "utf-8");
909
+ state.logger.error(`Dumped failing code to ${dumpPath}`);
910
+ } catch (dumpError) {
911
+ state.logger.error(`Failed to dump failing virtual module for ${realPath}:`, dumpError);
912
+ }
913
+ const message = [`[vize] Virtual module transform failed for ${realPath}: ${formatUnknownError(e)}`, dumpPath ? `Dumped failing code to ${dumpPath}` : null].filter(Boolean).join("\n");
914
+ throw new Error(message);
893
915
  }
894
916
  }
895
917
  return null;
896
918
  }
919
+ function formatUnknownError(error) {
920
+ return error instanceof Error ? error.message : String(error);
921
+ }
897
922
  //#endregion
898
923
  //#region src/plugin/hmr.ts
899
924
  async function handleHotUpdateHook(state, ctx) {
@@ -1086,6 +1111,28 @@ function patchUnoCssBridge(plugins) {
1086
1111
  }
1087
1112
  }
1088
1113
  //#endregion
1114
+ //#region src/plugin/css-modules.ts
1115
+ function patchCssModuleGenerateScopedName(userConfig) {
1116
+ const cssModules = userConfig.css?.modules;
1117
+ if (!cssModules || typeof cssModules.generateScopedName !== "function") return;
1118
+ const origFn = cssModules.generateScopedName;
1119
+ cssModules.generateScopedName = function(name, filename, css) {
1120
+ return origFn.call(this, name, normalizeViteCssModuleFilename(filename), css);
1121
+ };
1122
+ }
1123
+ //#endregion
1124
+ //#region src/plugin/dev-middleware.ts
1125
+ function installVirtualAssetMiddleware(devServer, state) {
1126
+ devServer.middlewares.use((req, _res, next) => {
1127
+ const rewrite = req.url ? normalizeViteDevMiddlewareUrl(req.url) : null;
1128
+ if (rewrite && fs.existsSync(rewrite.fsPath) && fs.statSync(rewrite.fsPath).isFile()) {
1129
+ state.logger.log(`middleware: rewriting ${req.url} -> ${rewrite.cleanedUrl}`);
1130
+ req.url = rewrite.cleanedUrl;
1131
+ }
1132
+ next();
1133
+ });
1134
+ }
1135
+ //#endregion
1089
1136
  //#region src/plugin/index.ts
1090
1137
  function aliasSortKey(find) {
1091
1138
  return typeof find === "string" ? find.length : find.source.length;
@@ -1121,18 +1168,7 @@ function vize(options = {}) {
1121
1168
  name: "vite-plugin-vize",
1122
1169
  enforce: "pre",
1123
1170
  config(userConfig, env) {
1124
- const cssModules = userConfig.css?.modules;
1125
- if (cssModules && typeof cssModules.generateScopedName === "function") {
1126
- const origFn = cssModules.generateScopedName;
1127
- cssModules.generateScopedName = function(name, filename, css) {
1128
- let clean = filename;
1129
- const nulIdx = clean.indexOf("\0");
1130
- if (nulIdx >= 0) clean = clean.slice(nulIdx + 1);
1131
- clean = clean.replace(/\.module\.\w+$/, "").replace(/\.\w+$/, "");
1132
- if (clean.includes("?")) clean = clean.split("?")[0];
1133
- return origFn.call(this, name, clean, css);
1134
- };
1135
- }
1171
+ patchCssModuleGenerateScopedName(userConfig);
1136
1172
  return {
1137
1173
  // @vitejs/plugin-vue normally provides them; vize must do so as its replacement.
1138
1174
  define: {
@@ -1223,24 +1259,7 @@ function vize(options = {}) {
1223
1259
  },
1224
1260
  configureServer(devServer) {
1225
1261
  state.server = devServer;
1226
- devServer.middlewares.use((req, _res, next) => {
1227
- if (req.url && req.url.includes("__x00__")) {
1228
- const [urlPath, queryPart] = req.url.split("?");
1229
- let cleanedPath = urlPath.replace(/__x00__/g, "");
1230
- cleanedPath = cleanedPath.replace(/^\/@id\/\//, "/@fs/");
1231
- if (cleanedPath.startsWith("/@fs/")) {
1232
- const fsPath = cleanedPath.slice(4);
1233
- if (fsPath.startsWith("/") && fs.existsSync(fsPath) && fs.statSync(fsPath).isFile() && !fsPath.endsWith(".vue.ts")) {
1234
- const cleaned = queryPart ? `${cleanedPath}?${queryPart}` : cleanedPath;
1235
- if (cleaned !== req.url) {
1236
- state.logger.log(`middleware: rewriting ${req.url} -> ${cleaned}`);
1237
- req.url = cleaned;
1238
- }
1239
- }
1240
- }
1241
- }
1242
- next();
1243
- });
1262
+ installVirtualAssetMiddleware(devServer, state);
1244
1263
  },
1245
1264
  async buildStart() {
1246
1265
  if (!state.scanPatterns || state.scanPatterns.length === 0) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vizejs/vite-plugin",
3
- "version": "0.101.0",
3
+ "version": "0.104.0",
4
4
  "description": "High-performance native Vite plugin for Vue SFC compilation powered by Vize",
5
5
  "keywords": [
6
6
  "compiler",
@@ -11,6 +11,10 @@
11
11
  "vite",
12
12
  "vue"
13
13
  ],
14
+ "homepage": "https://github.com/ubugeeei/vize",
15
+ "bugs": {
16
+ "url": "https://github.com/ubugeeei/vize/issues"
17
+ },
14
18
  "license": "MIT",
15
19
  "repository": {
16
20
  "type": "git",
@@ -33,9 +37,9 @@
33
37
  "access": "public"
34
38
  },
35
39
  "dependencies": {
36
- "@vizejs/native": "0.101.0",
40
+ "@vizejs/native": "0.104.0",
37
41
  "tinyglobby": "0.2.16",
38
- "vize": "0.101.0"
42
+ "vize": "0.104.0"
39
43
  },
40
44
  "devDependencies": {
41
45
  "@types/node": "25.7.0",
@@ -46,6 +50,9 @@
46
50
  "peerDependencies": {
47
51
  "vite": "^8.0.0"
48
52
  },
53
+ "engines": {
54
+ "node": ">=22"
55
+ },
49
56
  "scripts": {
50
57
  "build": "vp pack",
51
58
  "dev": "vp pack --watch",