weapp-vite 7.1.2 → 7.1.4

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.
@@ -1,5 +1,5 @@
1
1
  import { n as applyWeappViteHostMeta } from "./pluginHost--CaeyWpA.mjs";
2
- import { E as MINI_PROGRAM_PLATFORM_ADAPTERS, _ as templateExtensions, a as findJsonEntry, b as isNativeTemplateSource, c as isJsOrTs, d as touch, g as supportedCssLangs, h as scriptExtensions, i as findJsEntry, l as isTemplate, m as jsExtensions, n as changeFileExtension, o as findTemplateEntry, p as configExtensions, r as findCssEntry, s as findVueEntry, t as extractConfigFromVue, v as vueExtensions, w as inlineAutoRoutesImports, x as isSourceStyleExtension, y as ALL_NATIVE_STYLE_RESOLVER_EXTENSIONS } from "./file-CLo_LdAz.mjs";
2
+ import { E as MINI_PROGRAM_PLATFORM_ADAPTERS, _ as templateExtensions, a as findJsonEntry, b as isNativeTemplateSource, c as isJsOrTs, d as touch, g as supportedCssLangs, h as scriptExtensions, i as findJsEntry, l as isTemplate, m as jsExtensions, n as changeFileExtension, o as findTemplateEntry, p as configExtensions, r as findCssEntry, s as findVueEntry, t as extractConfigFromVue, v as vueExtensions, w as inlineAutoRoutesImports, x as isSourceStyleExtension, y as ALL_NATIVE_STYLE_RESOLVER_EXTENSIONS } from "./file-CHisoC18.mjs";
3
3
  import { n as configureLogger, r as logger_default } from "./logger-mt4mSTqV.mjs";
4
4
  import { createRequire, isBuiltin } from "node:module";
5
5
  import { createDebug } from "obug";
@@ -10199,6 +10199,7 @@ function createProviderPlugin(ctx, config, onChange) {
10199
10199
  async function createDevModuleGraphProvider(ctx, buildConfig, onChange) {
10200
10200
  const configService = ctx.configService;
10201
10201
  const userWatch = buildConfig.server?.watch;
10202
+ const pollingWatchOptions = resolvePollingWatchOptions({ inlineConfig: configService?.inlineConfig ?? {} });
10202
10203
  const ignored = configService?.outDir ? createViteWatchIgnored(buildConfig.root ?? configService.cwd, configService.outDir, userWatch?.ignored) : userWatch?.ignored;
10203
10204
  const server = await createServer({
10204
10205
  ...buildConfig,
@@ -10213,6 +10214,7 @@ async function createDevModuleGraphProvider(ctx, buildConfig, onChange) {
10213
10214
  middlewareMode: true,
10214
10215
  watch: {
10215
10216
  ...userWatch ?? {},
10217
+ ...Object.fromEntries(Object.entries(pollingWatchOptions).filter(([, value]) => value !== void 0)),
10216
10218
  ...ignored !== void 0 ? { ignored } : {}
10217
10219
  }
10218
10220
  },
@@ -10229,6 +10231,73 @@ async function createDevModuleGraphProvider(ctx, buildConfig, onChange) {
10229
10231
  } };
10230
10232
  }
10231
10233
  //#endregion
10234
+ //#region src/plugins/utils/vueSfc.ts
10235
+ function createSfcResolveSrcOptions(pluginCtx, configService) {
10236
+ return {
10237
+ resolveId: async (source, importer) => {
10238
+ if (typeof pluginCtx.resolve !== "function") return;
10239
+ return (await pluginCtx.resolve(source, importer))?.id;
10240
+ },
10241
+ checkMtime: getSfcCheckMtime(configService)
10242
+ };
10243
+ }
10244
+ function createReadAndParseSfcOptions(pluginCtx, configService, options) {
10245
+ const resolveCheckMtime = getSfcCheckMtime(configService);
10246
+ return {
10247
+ source: options?.source,
10248
+ checkMtime: options?.checkMtime ?? resolveCheckMtime,
10249
+ resolveSrc: createSfcResolveSrcOptions(pluginCtx, configService)
10250
+ };
10251
+ }
10252
+ //#endregion
10253
+ //#region src/plugins/vue/transform/styleOnly.ts
10254
+ function hasCssModules(styleBlocks) {
10255
+ return styleBlocks?.some((styleBlock) => Boolean(styleBlock.module)) === true;
10256
+ }
10257
+ function hasSameStyleSources(previous, current) {
10258
+ return !previous?.some((block, index) => block.src !== current[index]?.src) && !current.some((block, index) => block.src !== previous?.[index]?.src);
10259
+ }
10260
+ function hasSameCssVars(previous, current) {
10261
+ if (!previous || !current || previous.length !== current.length) return false;
10262
+ return previous.every((expression, index) => expression === current[index]);
10263
+ }
10264
+ async function refreshStyleOnlyVueTransformResult(result, filename, styleBlocks, cssVars, stylePreprocessOptions) {
10265
+ if (!styleBlocks || hasCssModules(styleBlocks) || !hasSameCssVars(result.meta?.cssVars, cssVars) || !hasSameStyleSources(result.meta?.styleBlocks, styleBlocks)) return false;
10266
+ if (!styleBlocks.length) {
10267
+ result.style = void 0;
10268
+ if (result.meta) {
10269
+ result.meta.cssVars = cssVars;
10270
+ result.meta.styleBlocks = styleBlocks;
10271
+ }
10272
+ return true;
10273
+ }
10274
+ const scopedId = generateScopedId(filename);
10275
+ result.style = (await Promise.all(styleBlocks.map(async (styleBlock) => await compileVueStyleToWxss(styleBlock, {
10276
+ id: scopedId,
10277
+ filename,
10278
+ scoped: styleBlock.scoped,
10279
+ modules: styleBlock.module,
10280
+ preprocessOptions: stylePreprocessOptions?.[styleBlock.lang || "css"]
10281
+ })))).map((result) => result.code.trim()).filter(Boolean).join("\n\n") || void 0;
10282
+ if (result.meta) {
10283
+ result.meta.cssVars = cssVars;
10284
+ result.meta.styleBlocks = styleBlocks;
10285
+ }
10286
+ return true;
10287
+ }
10288
+ //#endregion
10289
+ //#region src/plugins/core/lifecycle/vueStyleDependency.ts
10290
+ /** 在原生入口发射前识别外部样式引起的脚本绑定变化。 */
10291
+ async function collectVueStyleScriptChanges(ctx, filename, configService) {
10292
+ const changedEntries = /* @__PURE__ */ new Set();
10293
+ for (const [entryId, bindings] of ctx.runtimeState.build.hmr.vueEntryStyleBindings) {
10294
+ if (!bindings.sources.some((source) => normalizeFsResolvedId(source) === filename)) continue;
10295
+ const { descriptor } = await readAndParseSfc(entryId, createReadAndParseSfcOptions(ctx.moduleGraphService, configService));
10296
+ if (!hasSameCssVars(bindings.expressions, descriptor.cssVars)) changedEntries.add(entryId);
10297
+ }
10298
+ return changedEntries;
10299
+ }
10300
+ //#endregion
10232
10301
  //#region src/plugins/tailwindcssMarker.ts
10233
10302
  const MANAGED_TAILWINDCSS_ENTRY_MARKER_PREFIX = ".__weapp_vite_managed_tailwindcss_entry_";
10234
10303
  const MANAGED_TAILWINDCSS_ENTRY_MARKER_SUFFIX = "__{--weapp-vite-managed-tailwindcss-entry:1}";
@@ -10411,6 +10480,9 @@ function resolveHmrRuntimeDecision(options) {
10411
10480
  runtime: "classic"
10412
10481
  };
10413
10482
  }
10483
+ function resolveHmrRuntime(options) {
10484
+ return resolveHmrRuntimeDecision(options).runtime;
10485
+ }
10414
10486
  function findSkylineRendererFiles(output) {
10415
10487
  const jsonConfigs = /* @__PURE__ */ new Map();
10416
10488
  for (const item of output) {
@@ -11446,6 +11518,7 @@ function createRuntimeState() {
11446
11518
  entriesMap: /* @__PURE__ */ new Map(),
11447
11519
  vueEntryHasTemplate: /* @__PURE__ */ new Map(),
11448
11520
  vueEntrySfcSignatures: /* @__PURE__ */ new Map(),
11521
+ vueEntryStyleBindings: /* @__PURE__ */ new Map(),
11449
11522
  vueEntryTailwindContentSignatures: /* @__PURE__ */ new Map(),
11450
11523
  vueEntryTailwindTemplateContentSignatures: /* @__PURE__ */ new Map(),
11451
11524
  vueEntryTailwindScriptContentSignatures: /* @__PURE__ */ new Map(),
@@ -13116,6 +13189,29 @@ function createPreserveModulesGroup(configService, getSubPackageRoots) {
13116
13189
  };
13117
13190
  }
13118
13191
  //#endregion
13192
+ //#region src/runtime/sharedBuildConfig/virtualChunk.ts
13193
+ /** 虚拟模块的完整路径只作为标识参与散列,避免泄漏到文件名并超过文件系统长度限制。 */
13194
+ function resolveVirtualChunkFileName(chunk, root) {
13195
+ const ids = chunk.facadeModuleId ? [chunk.facadeModuleId] : chunk.moduleIds ?? [];
13196
+ if (ids.length !== 1) return;
13197
+ const id = ids[0];
13198
+ const entry = parseLogicalEntryId(id);
13199
+ const sidecar = parseSidecarModuleId(id);
13200
+ const identity = entry ? [
13201
+ "entry",
13202
+ entry.type,
13203
+ path.relative(root, entry.sourceId)
13204
+ ] : sidecar ? [
13205
+ "sidecar",
13206
+ sidecar.kind,
13207
+ path.relative(root, sidecar.ownerId),
13208
+ path.relative(root, sidecar.sourceId)
13209
+ ] : void 0;
13210
+ if (!identity) return;
13211
+ const hash = createHash("sha256").update(JSON.stringify(identity)).digest("hex").slice(0, 16);
13212
+ return `weapp-${identity[0]}-${identity[1]}-${hash}.js`;
13213
+ }
13214
+ //#endregion
13119
13215
  //#region src/runtime/wevuModules.ts
13120
13216
  const WEVU_RUNTIME_MODULE_IDS = [
13121
13217
  "wevu",
@@ -13451,7 +13547,7 @@ function createSharedBuildOutput(configService, getSubPackageRoots, options = {}
13451
13547
  const stableHashedDistChunkFileName = resolveStableHashedDistChunkFileName(chunk);
13452
13548
  if (stableHashedDistChunkFileName) return stableHashedDistChunkFileName;
13453
13549
  }
13454
- return "[name].js";
13550
+ return resolveVirtualChunkFileName(chunk, configService.absoluteSrcRoot) ?? "[name].js";
13455
13551
  }
13456
13552
  };
13457
13553
  }
@@ -14207,37 +14303,6 @@ function isStatefulHmrRuntimeCompatibilityError(error) {
14207
14303
  return error instanceof StatefulHmrRuntimeCompatibilityError || typeof error === "object" && error !== null && Reflect.get(error, "code") === "WEAPP_VITE_STATEFUL_HMR_RUNTIME_INCOMPATIBLE";
14208
14304
  }
14209
14305
  //#endregion
14210
- //#region src/runtime/statefulHmr/componentPageStyles.ts
14211
- /** 以完整产物中的最终 JSON 覆盖注册选项,只接纳已确认的 Component 页面。 */
14212
- function resolveComponentPageGlobalStyleRoutes(output, pageOptions) {
14213
- const assets = new Map(output.flatMap((item) => item.type === "asset" ? [[item.fileName, item]] : []));
14214
- const appAsset = assets.get("app.json");
14215
- const appConfig = appAsset ? JSON.parse(Buffer.from(appAsset.source).toString("utf8")) : void 0;
14216
- const independentRoots = [];
14217
- if (appConfig && typeof appConfig === "object" && !Array.isArray(appConfig)) {
14218
- const config = appConfig;
14219
- for (const key of ["subPackages", "subpackages"]) {
14220
- const packages = config[key];
14221
- if (!Array.isArray(packages)) continue;
14222
- for (const entry of packages) if (entry && typeof entry === "object" && "independent" in entry && entry.independent === true && "root" in entry && typeof entry.root === "string") independentRoots.push(path.normalize(entry.root).replace(/^\/+|\/+$/g, ""));
14223
- }
14224
- }
14225
- const routes = [];
14226
- for (const [sourceRoute, options] of pageOptions) {
14227
- const route = path.normalize(sourceRoute);
14228
- if (independentRoots.some((root) => route === root || route.startsWith(`${root}/`))) continue;
14229
- const jsonAsset = assets.get(`${route}.json`);
14230
- let isolation = options.styleIsolation.kind === "known" ? options.styleIsolation.value : void 0;
14231
- if (jsonAsset) {
14232
- const config = JSON.parse(Buffer.from(jsonAsset.source).toString("utf8"));
14233
- if (config === null || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid Component page JSON: ${route}.json`);
14234
- if ("styleIsolation" in config && config.styleIsolation !== void 0) isolation = config.styleIsolation;
14235
- }
14236
- if (isolation === "apply-shared") routes.push(route);
14237
- }
14238
- return routes.sort();
14239
- }
14240
- //#endregion
14241
14306
  //#region src/plugins/hooks/useLoadEntry/entryChunkLifecycle.ts
14242
14307
  const ENTRY_GRAPH_CHANGE_REASON = "entry-graph-changed";
14243
14308
  /** 入口注册属于完整扫描;局部扫描只能复用已注册入口或请求重建入口图。 */
@@ -14939,6 +15004,21 @@ function normalizeRoute(route) {
14939
15004
  }
14940
15005
  const globalStart = `/* ${WEAPP_VITE_STATEFUL_HMR_GLOBAL_STYLE_BASENAME}:start */\n`;
14941
15006
  const globalEnd = `\n/* ${WEAPP_VITE_STATEFUL_HMR_GLOBAL_STYLE_BASENAME}:end */\n`;
15007
+ const pageStyleRefreshMarkerPrefix = ".weapp-vite-stateful-hmr-style-";
15008
+ function pageStyleRefreshMarker(token) {
15009
+ return `${pageStyleRefreshMarkerPrefix}${token} { --weapp-vite-stateful-hmr-style-token: ${token}; }\n`;
15010
+ }
15011
+ function stripPageStyleRefreshMarker(source) {
15012
+ const markerStart = source.lastIndexOf(pageStyleRefreshMarkerPrefix);
15013
+ if (markerStart < 0 || !source.endsWith(" }\n")) return source;
15014
+ const markerEnd = source.indexOf(" {", markerStart);
15015
+ if (markerEnd < 0) return source;
15016
+ const token = source.slice(markerStart + 31, markerEnd);
15017
+ return /^[a-f0-9]+$/.test(token) ? source.slice(0, markerStart).replace(/\n$/, "") : source;
15018
+ }
15019
+ function styleRefreshToken(source) {
15020
+ return createHash("sha256").update(source).digest("hex").slice(0, 16);
15021
+ }
14942
15022
  function localStyleSource(source) {
14943
15023
  if (!source.startsWith(globalStart)) return source;
14944
15024
  const end = source.indexOf(globalEnd, globalStart.length);
@@ -14979,7 +15059,7 @@ function createStatefulHmrGlobalStyleAssets(output, styleExtension, options = {}
14979
15059
  const index = result.findIndex((item) => item.fileName === fileName);
14980
15060
  const asset = result[index];
14981
15061
  if (asset && asset.type !== "asset") throw new Error(`Stateful HMR component page stylesheet conflicts with emitted chunk: ${fileName}`);
14982
- const original = asset ? Buffer.from(asset.source).toString("utf8") : "";
15062
+ const original = asset ? stripPageStyleRefreshMarker(Buffer.from(asset.source).toString("utf8")) : "";
14983
15063
  const localSource = localStyleSource(original);
14984
15064
  const source = routes.has(route) ? globalStart + rebase(styleFile, fileName) + globalEnd + localSource : localSource;
14985
15065
  if (asset && original === source) continue;
@@ -14992,6 +15072,22 @@ function createStatefulHmrGlobalStyleAssets(output, styleExtension, options = {}
14992
15072
  if (index >= 0) result[index] = next;
14993
15073
  else result.push(next);
14994
15074
  }
15075
+ if (!options.refreshPageStyles) return result;
15076
+ const globalStyle = result.find((item) => item.type === "asset" && item.fileName === styleFile);
15077
+ const marker = pageStyleRefreshMarker(styleRefreshToken(globalStyle?.type === "asset" ? globalStyle.source : ""));
15078
+ for (const [index, item] of result.entries()) {
15079
+ if (item.type !== "asset" || path.extname(item.fileName) !== path.extname(styleFile) || !routes.has(item.fileName.slice(0, -path.extname(styleFile).length))) continue;
15080
+ const original = Buffer.from(item.source).toString("utf8");
15081
+ const source = stripPageStyleRefreshMarker(original);
15082
+ if (!source) continue;
15083
+ const nextSource = `${source}${source && !source.endsWith("\n") ? "\n" : ""}${marker}`;
15084
+ if (original === nextSource) continue;
15085
+ if (result === output) result = [...output];
15086
+ result[index] = {
15087
+ ...item,
15088
+ source: nextSource
15089
+ };
15090
+ }
14995
15091
  return result;
14996
15092
  }
14997
15093
  //#endregion
@@ -17709,6 +17805,7 @@ async function runStatefulHmrDev(ctx, buildOptions, restart, snapshots) {
17709
17805
  port: 0,
17710
17806
  watch: {
17711
17807
  ...buildOptions.server?.watch ?? {},
17808
+ ...Object.fromEntries(Object.entries(pollingWatchOptions).filter(([, value]) => value !== void 0)),
17712
17809
  ignored: createViteWatchIgnored(buildOptions.root ?? configService.cwd, configService.outDir, buildOptions.server?.watch?.ignored)
17713
17810
  }
17714
17811
  },
@@ -17851,7 +17948,10 @@ var StatefulHmrSession = class {
17851
17948
  }
17852
17949
  const snapshot = snapshotBatch?.snapshot ?? this.initialSnapshot;
17853
17950
  const snapshotOutput = snapshot ? this.createSnapshotAssets(snapshot) : void 0;
17854
- const compatibleOutput = createStatefulHmrGlobalStyleAssets(await transformOutput(output), resolveOutputExtensions(this.ctx.configService?.outputExtensions).styleExtension, { componentPageGlobalStyleRoutes: snapshot?.componentPageGlobalStyleRoutes ?? this.componentPageGlobalStyleRoutes });
17951
+ const compatibleOutput = createStatefulHmrGlobalStyleAssets(await transformOutput(output), resolveOutputExtensions(this.ctx.configService?.outputExtensions).styleExtension, {
17952
+ componentPageGlobalStyleRoutes: snapshot?.componentPageGlobalStyleRoutes ?? this.componentPageGlobalStyleRoutes,
17953
+ refreshPageStyles: true
17954
+ });
17855
17955
  if (snapshotBatch?.isSuperseded()) {
17856
17956
  this.diagnostics?.discarded(snapshotBatch.traceBatchId, "after-transform");
17857
17957
  return;
@@ -17911,7 +18011,7 @@ var StatefulHmrSession = class {
17911
18011
  entryIds: this.entryIds
17912
18012
  })) {
17913
18013
  if (shouldRestartStatefulHmrServer(files, this.ctx.configService?.configFileDependencies)) this.requestServerRestart();
17914
- else if (files.length > 0 && files.every(isStatefulHmrAssetFile) || shouldUseStatefulHmrSnapshotOnly(dirtyReasonSummary)) {
18014
+ else if (!dirtyReasonSummary.some((reason) => reason.startsWith("entry-mixed-asset:")) && (files.length > 0 && files.every(isStatefulHmrAssetFile) || shouldUseStatefulHmrSnapshotOnly(dirtyReasonSummary))) {
17915
18015
  if (!this.snapshotScheduler.isPending()) this.requestSnapshotRefresh(files);
17916
18016
  } else this.requestFullBuild(files);
17917
18017
  return false;
@@ -18033,7 +18133,8 @@ var StatefulHmrSession = class {
18033
18133
  return createStatefulHmrGlobalStyleAssets(snapshot.output, resolveOutputExtensions(this.ctx.configService?.outputExtensions).styleExtension, {
18034
18134
  createIfMissing: true,
18035
18135
  componentPageGlobalStyleRoutes: snapshot.componentPageGlobalStyleRoutes,
18036
- previousComponentPageGlobalStyleRoutes: this.componentPageGlobalStyleRoutes
18136
+ previousComponentPageGlobalStyleRoutes: this.componentPageGlobalStyleRoutes,
18137
+ refreshPageStyles: true
18037
18138
  });
18038
18139
  }
18039
18140
  adoptSnapshot(snapshot, output) {
@@ -18175,6 +18276,65 @@ function formatStatefulHmrError(error) {
18175
18276
  return String(error);
18176
18277
  }
18177
18278
  //#endregion
18279
+ //#region src/runtime/statefulHmr/componentPageStyles.ts
18280
+ function hasNativePageRegistration(code) {
18281
+ if (!code.includes("Page")) return false;
18282
+ let found = false;
18283
+ traverse(parseJsLike(code), { CallExpression(callPath) {
18284
+ const callee = callPath.node.callee;
18285
+ if (callee.type === "Identifier" && callee.name === "Page" && !callPath.scope.hasBinding("Page")) {
18286
+ found = true;
18287
+ callPath.stop();
18288
+ }
18289
+ } });
18290
+ return found;
18291
+ }
18292
+ /** 以最终 JSON 和注册方式确认继承全局样式的页面,保留独立分包与隔离边界。 */
18293
+ function resolveComponentPageGlobalStyleRoutes(output, pageOptions) {
18294
+ const assets = new Map(output.flatMap((item) => item.type === "asset" ? [[item.fileName, item]] : []));
18295
+ const appAsset = assets.get("app.json");
18296
+ const appConfig = appAsset ? JSON.parse(Buffer.from(appAsset.source).toString("utf8")) : void 0;
18297
+ const independentRoots = [];
18298
+ const nativeCandidates = [];
18299
+ if (appConfig && typeof appConfig === "object" && !Array.isArray(appConfig)) {
18300
+ const config = appConfig;
18301
+ if (Array.isArray(config.pages)) nativeCandidates.push(...config.pages.filter((route) => typeof route === "string"));
18302
+ for (const key of ["subPackages", "subpackages"]) {
18303
+ const packages = config[key];
18304
+ if (!Array.isArray(packages)) continue;
18305
+ for (const entry of packages) if (entry && typeof entry === "object" && "independent" in entry && entry.independent === true && "root" in entry && typeof entry.root === "string") independentRoots.push(path.normalize(entry.root).replace(/^\/+|\/+$/g, ""));
18306
+ else if (entry && typeof entry === "object" && "root" in entry && typeof entry.root === "string" && "pages" in entry && Array.isArray(entry.pages)) nativeCandidates.push(...entry.pages.filter((route) => typeof route === "string").map((route) => path.join(entry.root, route)));
18307
+ }
18308
+ }
18309
+ const routes = [];
18310
+ const componentRoutes = new Set(Array.from(pageOptions.keys(), (route) => path.normalize(route)));
18311
+ for (const [sourceRoute, options] of pageOptions) {
18312
+ const route = path.normalize(sourceRoute);
18313
+ if (independentRoots.some((root) => route === root || route.startsWith(`${root}/`))) continue;
18314
+ const jsonAsset = assets.get(`${route}.json`);
18315
+ let isolation = options.styleIsolation.kind === "known" ? options.styleIsolation.value : void 0;
18316
+ if (jsonAsset) {
18317
+ const config = JSON.parse(Buffer.from(jsonAsset.source).toString("utf8"));
18318
+ if (config === null || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid Component page JSON: ${route}.json`);
18319
+ if ("styleIsolation" in config && config.styleIsolation !== void 0) isolation = config.styleIsolation;
18320
+ }
18321
+ if (isolation === "apply-shared") routes.push(route);
18322
+ }
18323
+ const chunks = new Map(output.flatMap((item) => item.type === "chunk" ? [[item.fileName, item]] : []));
18324
+ for (const sourceRoute of nativeCandidates) {
18325
+ const route = path.normalize(sourceRoute);
18326
+ if (componentRoutes.has(route) || independentRoots.some((root) => route === root || route.startsWith(`${root}/`))) continue;
18327
+ const chunk = chunks.get(`${route}.js`);
18328
+ if (!chunk || !hasNativePageRegistration(chunk.code)) continue;
18329
+ const json = assets.get(`${route}.json`);
18330
+ const config = json ? JSON.parse(Buffer.from(json.source).toString("utf8")) : {};
18331
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid native page JSON: ${route}.json`);
18332
+ if ("component" in config && config.component === true) continue;
18333
+ routes.push(route);
18334
+ }
18335
+ return [...new Set(routes)].sort();
18336
+ }
18337
+ //#endregion
18178
18338
  //#region src/runtime/statefulHmr/snapshotBuild.ts
18179
18339
  /** 快照独立编译;初始化到构建收尾均不写支持文件,由活动 DevEngine 统一维护。 */
18180
18340
  async function buildStatefulHmrSnapshot(loadOptions, configure = (options) => options) {
@@ -18184,7 +18344,16 @@ async function buildStatefulHmrSnapshot(loadOptions, configure = (options) => op
18184
18344
  await ctx.configService.load(loadOptions);
18185
18345
  await ctx.scanService.loadAppEntry();
18186
18346
  ctx.scanService.loadSubPackages();
18187
- const options = configure(ctx.configService.merge(void 0, createSharedBuildConfig(ctx.configService, ctx.scanService)));
18347
+ let globalStyleRoutes = [];
18348
+ const baseOptions = ctx.configService.merge(void 0, createSharedBuildConfig(ctx.configService, ctx.scanService));
18349
+ baseOptions.plugins = [...baseOptions.plugins ?? [], {
18350
+ name: "weapp-vite:stateful-hmr-page-style-metadata",
18351
+ enforce: "post",
18352
+ generateBundle(_options, bundle) {
18353
+ globalStyleRoutes = resolveComponentPageGlobalStyleRoutes(Object.values(bundle), ctx.runtimeState.build.hmr.componentPageStyleOptions);
18354
+ }
18355
+ }];
18356
+ const options = configure(baseOptions);
18188
18357
  options.build = {
18189
18358
  ...options.build,
18190
18359
  watch: void 0,
@@ -18194,7 +18363,7 @@ async function buildStatefulHmrSnapshot(loadOptions, configure = (options) => op
18194
18363
  output: await build(options),
18195
18364
  getEntryIds: () => ctx.runtimeState.build.hmr.resolvedEntryMap.keys(),
18196
18365
  getDelegatedComponentEntryIds: () => Array.from(ctx.runtimeState.build.hmr.resolvedEntryMap.keys()).filter((id) => /\.(?:vue|jsx|tsx)$/.test(id) && ctx.runtimeState.build.hmr.entriesMap.get(ctx.configService.relativeAbsoluteSrcRoot(removeExtensionDeep(id)))?.type === "component"),
18197
- getComponentPageStyleOptions: () => ctx.runtimeState.build.hmr.componentPageStyleOptions
18366
+ getGlobalStyleRoutes: () => globalStyleRoutes
18198
18367
  };
18199
18368
  });
18200
18369
  }
@@ -18479,25 +18648,6 @@ function autoImport(ctx) {
18479
18648
  return [createAutoImportPlugin({ ctx })];
18480
18649
  }
18481
18650
  //#endregion
18482
- //#region src/plugins/utils/vueSfc.ts
18483
- function createSfcResolveSrcOptions(pluginCtx, configService) {
18484
- return {
18485
- resolveId: async (source, importer) => {
18486
- if (typeof pluginCtx.resolve !== "function") return;
18487
- return (await pluginCtx.resolve(source, importer))?.id;
18488
- },
18489
- checkMtime: getSfcCheckMtime(configService)
18490
- };
18491
- }
18492
- function createReadAndParseSfcOptions(pluginCtx, configService, options) {
18493
- const resolveCheckMtime = getSfcCheckMtime(configService);
18494
- return {
18495
- source: options?.source,
18496
- checkMtime: options?.checkMtime ?? resolveCheckMtime,
18497
- resolveSrc: createSfcResolveSrcOptions(pluginCtx, configService)
18498
- };
18499
- }
18500
- //#endregion
18501
18651
  //#region src/plugins/vue/transform/usingComponentResolver.ts
18502
18652
  const JS_LIKE_FILE_RE = /\.(?:[cm]?ts|[cm]?js)$/;
18503
18653
  async function resolveUsingComponentReference(ctx, configService, reExportResolutionCache, importSource, importerFilename, info) {
@@ -19644,10 +19794,11 @@ function omitDeprecatedCompilerOptions(compilerOptions) {
19644
19794
  }
19645
19795
  function resolveAppWevuJsxImportSource(ctx, legacyConfig) {
19646
19796
  const configService = requireConfigService(ctx, "解析 app JSX 类型入口前必须初始化 configService。");
19647
- if (!hasDependency(configService.packageJson, "wevu")) return;
19797
+ const reactEnabled = Boolean(configService.weappViteConfig.react);
19798
+ if (!reactEnabled && !hasDependency(configService.packageJson, "wevu")) return;
19648
19799
  const configuredJsxImportSource = getManagedTypeScriptConfig(ctx)?.app?.compilerOptions?.jsxImportSource;
19649
19800
  const legacyJsxImportSource = legacyConfig?.app?.compilerOptions?.jsxImportSource;
19650
- return typeof configuredJsxImportSource === "string" && configuredJsxImportSource.trim() ? configuredJsxImportSource.trim() : typeof legacyJsxImportSource === "string" && legacyJsxImportSource.trim() ? legacyJsxImportSource.trim() : resolveWevuJsxImportSource(configService.weappViteConfig.platform);
19801
+ return typeof configuredJsxImportSource === "string" && configuredJsxImportSource.trim() ? configuredJsxImportSource.trim() : typeof legacyJsxImportSource === "string" && legacyJsxImportSource.trim() ? legacyJsxImportSource.trim() : reactEnabled ? "react" : resolveWevuJsxImportSource(configService.weappViteConfig.platform);
19651
19802
  }
19652
19803
  function getAppTypes(ctx, legacyConfig) {
19653
19804
  const config = requireConfigService(ctx, "生成 app tsconfig 前必须初始化 configService。").weappViteConfig;
@@ -19790,7 +19941,7 @@ async function createManagedTsconfigFiles(ctx) {
19790
19941
  const managedDir = resolveManagedDir(ctx);
19791
19942
  const legacyConfig = await getLegacyManagedTypeScriptConfig(ctx);
19792
19943
  const jsxImportSource = resolveAppWevuJsxImportSource(ctx, legacyConfig);
19793
- const jsxPlatformBridgeSource = isWevuJsxImportSource(jsxImportSource) && jsxImportSource !== "wevu" ? jsxImportSource : void 0;
19944
+ const jsxPlatformBridgeSource = isWevuJsxImportSource(jsxImportSource) && jsxImportSource !== "wevu" ? jsxImportSource : ctx.configService?.weappViteConfig.react && hasDependency(ctx.configService.packageJson, "wevu") ? resolveWevuJsxImportSource(ctx.configService.weappViteConfig.platform) : void 0;
19794
19945
  const sharedEmptyContent = jsxPlatformBridgeSource ? [
19795
19946
  `import type { JSX as WevuPlatformJSX } from '${jsxPlatformBridgeSource}/jsx-runtime'`,
19796
19947
  "",
@@ -20466,6 +20617,10 @@ function resetEmittedOutputCaches(runtimeState) {
20466
20617
  runtimeState.css.transformedSidecarSource.clear();
20467
20618
  runtimeState.wxml.emittedCode.clear();
20468
20619
  }
20620
+ function shouldCleanOutputs(configService, phase) {
20621
+ if (configService.inlineConfig.build?.emptyOutDir === false) return false;
20622
+ return phase === "rebuild" || !configService.isDev || configService.weappViteConfig.cleanOutputsInDev !== false;
20623
+ }
20469
20624
  async function cleanOutputs(configService) {
20470
20625
  if (configService.mpDistRoot) {
20471
20626
  const preservedNpmDirNames = resolvePreservedNpmDirNames(configService);
@@ -21330,7 +21485,7 @@ function createBuildService(ctx) {
21330
21485
  if (target === "app" && hmrDecision.runtime === "stateful-experimental") try {
21331
21486
  const snapshot = await buildStatefulHmrSnapshot(configService.loadOptions, appendHmrMetricsPlugin);
21332
21487
  const initialSnapshot = toStatefulHmrOutput(snapshot.output);
21333
- const initialGlobalStyleRoutes = resolveComponentPageGlobalStyleRoutes(initialSnapshot, snapshot.getComponentPageStyleOptions());
21488
+ const initialGlobalStyleRoutes = snapshot.getGlobalStyleRoutes();
21334
21489
  const initialEntryIds = collectStatefulHmrEntryIds(snapshot.getEntryIds());
21335
21490
  const skylineFiles = findSkylineRendererFiles(initialSnapshot);
21336
21491
  if (skylineFiles.length > 0) await applySkylineHmrFallback({
@@ -21390,12 +21545,11 @@ function createBuildService(ctx) {
21390
21545
  }];
21391
21546
  return snapshotOptions;
21392
21547
  });
21393
- const output = toStatefulHmrOutput(snapshot.output);
21394
21548
  return {
21395
- output,
21549
+ output: toStatefulHmrOutput(snapshot.output),
21396
21550
  entryIds: [...collectStatefulHmrEntryIds(snapshot.getEntryIds())],
21397
21551
  delegatedComponentEntryIds: snapshot.getDelegatedComponentEntryIds(),
21398
- componentPageGlobalStyleRoutes: resolveComponentPageGlobalStyleRoutes(output, snapshot.getComponentPageStyleOptions())
21552
+ componentPageGlobalStyleRoutes: snapshot.getGlobalStyleRoutes()
21399
21553
  };
21400
21554
  }
21401
21555
  }), workerPromise]);
@@ -21492,16 +21646,25 @@ function createBuildService(ctx) {
21492
21646
  const snapshotBuildStartedAt = performance.now();
21493
21647
  const requiresFullRescan = batchReasons.some((batchReason) => batchReason.forceFullRescan || batchReason.event === "create" || batchReason.event === "delete");
21494
21648
  await refreshSnapshotSources(ctx, batchReasons.flatMap((batchReason) => batchReason.file ? [batchReason.file] : []));
21649
+ const styleScriptChanges = /* @__PURE__ */ new Set();
21650
+ for (const batchReason of batchReasons) {
21651
+ if (!batchReason.file) continue;
21652
+ for (const entryId of await collectVueStyleScriptChanges(ctx, batchReason.file, configService)) {
21653
+ styleScriptChanges.add(entryId);
21654
+ graphAffectedEntries.add(entryId);
21655
+ }
21656
+ }
21495
21657
  if (!requiresFullRescan && graphAffectedEntries.size) {
21496
21658
  const dirtyReasons = batchReasons.map(resolveSnapshotDirtyReason);
21497
21659
  const dirtyReason = dirtyReasons.includes("direct") ? "direct" : dirtyReasons.includes("dependency") ? "dependency" : "metadata";
21498
- for (const entryId of graphAffectedEntries) if (ctx.runtimeState.build.hmr.resolvedEntryMap.has(entryId)) markSnapshotEntryDirty(entryId, reason, dirtyReason);
21660
+ for (const entryId of graphAffectedEntries) if (ctx.runtimeState.build.hmr.resolvedEntryMap.has(entryId)) markSnapshotEntryDirty(entryId, reason, styleScriptChanges.has(entryId) ? "direct" : dirtyReason);
21499
21661
  const summaryCounts = /* @__PURE__ */ new Map();
21500
21662
  for (const batchReason of batchReasons) {
21501
21663
  if (!batchReason.file) continue;
21502
21664
  const summary = resolveSnapshotSidecarDirtySummary(batchReason.file, graphAffectedEntriesByFile.get(normalizeFsResolvedId(batchReason.file))).replace(/:\d+$/, "");
21503
21665
  summaryCounts.set(summary, (summaryCounts.get(summary) ?? 0) + 1);
21504
21666
  }
21667
+ if (styleScriptChanges.size) summaryCounts.set("entry-mixed-asset", styleScriptChanges.size);
21505
21668
  ctx.runtimeState.build.hmr.profile.dirtyReasonSummary = Array.from(summaryCounts, ([summary, count]) => `${summary}:${count}`);
21506
21669
  try {
21507
21670
  devBuildWatcher?.emitEvent({ code: "START" });
@@ -21529,7 +21692,7 @@ function createBuildService(ctx) {
21529
21692
  ...snapshotBuildOptions,
21530
21693
  build: {
21531
21694
  ...snapshotBuildOptions.build ?? {},
21532
- emptyOutDir: true
21695
+ emptyOutDir: shouldCleanOutputs(configService, "rebuild")
21533
21696
  }
21534
21697
  });
21535
21698
  devBuildWatcher?.emitEvent({ code: "END" });
@@ -21781,6 +21944,8 @@ function createBuildService(ctx) {
21781
21944
  const pluginOutputRoot = configService.absolutePluginOutputRoot;
21782
21945
  if (!pluginOutputRoot) return;
21783
21946
  const inlineConfig = { build: { outDir: pluginOutputRoot } };
21947
+ const emptyOutDir = configService.inlineConfig.build?.emptyOutDir;
21948
+ if (typeof emptyOutDir === "boolean") inlineConfig.build.emptyOutDir = emptyOutDir;
21784
21949
  const isolatedCtx = await createCompilerContext({
21785
21950
  key: `plugin-build:${configService.cwd}`,
21786
21951
  cwd: configService.cwd,
@@ -21809,7 +21974,7 @@ function createBuildService(ctx) {
21809
21974
  return await runProd(target);
21810
21975
  }
21811
21976
  async function buildEntry(options) {
21812
- if (!configService.isDev || configService.weappViteConfig.cleanOutputsInDev !== false) {
21977
+ if (shouldCleanOutputs(configService, "startup")) {
21813
21978
  await cleanOutputs(configService);
21814
21979
  resetEmittedOutputCaches(ctx.runtimeState);
21815
21980
  }
@@ -28312,7 +28477,7 @@ function rewriteStableWevuRuntimeAccess(chunk, wevuChunkFileName, aliases, usage
28312
28477
  if (!aliases.size) return;
28313
28478
  for (const [exportName, stableName] of WEVU_EXPORT_ALIASES) {
28314
28479
  const localName = aliases.get(exportName);
28315
- if (!localName) continue;
28480
+ if (!localName || localName === exportName) continue;
28316
28481
  if (usage.inlineMembers.has(localName) || usage.inlineMembers.has(stableName)) replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
28317
28482
  const rawSpecifier = match[1];
28318
28483
  const property = match[2];
@@ -28337,13 +28502,15 @@ function stabilizeWevuRuntimeChunkAccess(bundle, snapshot = createBundleChunkSna
28337
28502
  const aliases = resolveWevuExportAliasMap(wevuChunk);
28338
28503
  const usageByChunk = usageByRuntimeChunk.get(wevuChunk.fileName);
28339
28504
  const importedMembers = collectImportedWevuRuntimeMembers(usageByChunk);
28505
+ const existingExports = collectExistingExportNames(wevuChunk.code);
28506
+ const missingMembers = new Set([...importedMembers].filter((name) => !existingExports.has(name)));
28340
28507
  appendWevuRuntimeExports(wevuChunk, aliases, importedMembers);
28341
28508
  appendSyntheticWevuHookExports(wevuChunk, importedMembers);
28342
28509
  for (const usage of usageByChunk?.values() ?? []) {
28343
28510
  const chunk = usage.chunk;
28344
28511
  rewriteStableWevuRuntimeAccess(chunk, wevuChunk.fileName, aliases, usage);
28345
28512
  if (baseChunk?.fileName) {
28346
- rewriteSyntheticWevuHookAccess(chunk, wevuChunk.fileName, baseChunk.fileName, importedMembers, usage);
28513
+ rewriteSyntheticWevuHookAccess(chunk, wevuChunk.fileName, baseChunk.fileName, missingMembers, usage);
28347
28514
  if (chunk.code.includes(normalizeRelativeRequireSpecifier(chunk.fileName, baseChunk.fileName))) {
28348
28515
  const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
28349
28516
  nextImports.add(baseChunk.fileName);
@@ -32202,7 +32369,7 @@ function createBuildEndHook(state) {
32202
32369
  state.hmrState.styleSidecarFiles = styleSidecarFiles;
32203
32370
  const affectedEntries = /* @__PURE__ */ new Set();
32204
32371
  const causes = /* @__PURE__ */ new Map();
32205
- let metadataOnly = pendingChanges.length > 0;
32372
+ let metadataOnly = pendingChanges.length > 0 && !state.hmrState.lastEmittedEntryIds?.size;
32206
32373
  for (const change of pendingChanges) {
32207
32374
  const affected = state.ctx.moduleGraphService.collectAffectedEntries(change.file);
32208
32375
  const cause = resolveChangeCause(state, change.file, affected);
@@ -33241,7 +33408,12 @@ async function processChangedFile(state, id, event) {
33241
33408
  const relativeSrc = configService.relativeAbsoluteSrcRoot(normalizedId);
33242
33409
  const affectedLayoutEntryIds = /* @__PURE__ */ new Set();
33243
33410
  const dirtyReasonStats = /* @__PURE__ */ new Map();
33411
+ let styleScriptChanges;
33244
33412
  const markEntryDirtyWithCause = (entryId, reason, cause) => {
33413
+ if (styleScriptChanges?.has(entryId)) {
33414
+ reason = "direct";
33415
+ cause = "entry-mixed-asset";
33416
+ }
33245
33417
  state.markEntryDirty(entryId, reason);
33246
33418
  const isJsxTemplateDependency = reason === "dependency" && /\.(?:jsx|tsx)$/.test(normalizedId);
33247
33419
  if (/\.(?:vue|jsx|tsx)$/.test(entryId) && (reason !== "dependency" || isJsxTemplateDependency)) {
@@ -33255,6 +33427,10 @@ async function processChangedFile(state, id, event) {
33255
33427
  const isDeletedMissingSelf = event === "delete" && !await fs$1.pathExists(normalizedId);
33256
33428
  const isAutoRouteFile = Boolean(ctx.autoRoutesService?.isRouteFile(normalizedId));
33257
33429
  const pathKind = resolveWatchPathKind(normalizedId);
33430
+ if (pathKind.isStyle) {
33431
+ styleScriptChanges = await collectVueStyleScriptChanges(ctx, normalizedId, configService);
33432
+ for (const entryId of styleScriptChanges) importerGraphAffectedEntryIds.add(entryId);
33433
+ }
33258
33434
  const isReactStaticTemplateUpdate = event === "update" && isReactStaticTemplateSource(configService.weappViteConfig?.react, normalizedId);
33259
33435
  const isScriptModuleSidecar = pathKind.isScriptModuleSidecar;
33260
33436
  const concreteChangedEntryId = isAppVueFile(normalizedId) && scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : normalizedId;
@@ -33308,6 +33484,7 @@ async function processChangedFile(state, id, event) {
33308
33484
  if (isDeletedMissingSelf) {
33309
33485
  ctx.runtimeState.build.hmr.vueEntryHasTemplate.delete(normalizedId);
33310
33486
  ctx.runtimeState.build.hmr.vueEntrySfcSignatures.delete(normalizedId);
33487
+ ctx.runtimeState.build.hmr.vueEntryStyleBindings.delete(normalizedId);
33311
33488
  ctx.runtimeState.build.hmr.vueEntryTailwindContentSignatures?.delete(normalizedId);
33312
33489
  ctx.runtimeState.build.hmr.vueEntryTailwindTemplateContentSignatures?.delete(normalizedId);
33313
33490
  ctx.runtimeState.build.hmr.vueEntryTailwindScriptContentSignatures?.delete(normalizedId);
@@ -33837,6 +34014,37 @@ function preflight(ctx) {
33837
34014
  return [createPluginPruner(), createEnvSynchronizer(ctx)];
33838
34015
  }
33839
34016
  //#endregion
34017
+ //#region src/plugins/tailwindcss/imports.ts
34018
+ /** 只判断样式导入链的所有权;解析、条件包装与转换仍由 Tailwind 编译器负责。 */
34019
+ async function findManagedStyleImports(code, filename, options) {
34020
+ const dependencies = /* @__PURE__ */ new Set();
34021
+ let managed = false;
34022
+ const visit = async (source, importer) => {
34023
+ if (!source.includes("@import")) return;
34024
+ const requests = [];
34025
+ postcss.parse(source, { from: importer }).walkAtRules("import", (rule) => {
34026
+ const node = valueParser(rule.params).nodes[0];
34027
+ const value = node?.type === "string" ? node.value : node?.type === "function" && node.value === "url" ? node.nodes[0]?.value : void 0;
34028
+ if (value && !/^(?:[a-z]+:|\/\/|#)/i.test(value)) requests.push(value);
34029
+ });
34030
+ for (const request of requests) {
34031
+ const resolved = await options.resolve(request, importer, { skipSelf: true });
34032
+ if (!resolved || resolved.external) continue;
34033
+ const sourcePath = getCssRealPath(parseRequest(resolved.id));
34034
+ const file = normalizeManagedTailwindcssEntryPath(path$1.resolve(path$1.dirname(importer), sourcePath));
34035
+ if (dependencies.has(file)) continue;
34036
+ dependencies.add(file);
34037
+ if (options.isManaged(file)) managed = true;
34038
+ else await visit(await fs$2.readFile(file, "utf8"), file);
34039
+ }
34040
+ };
34041
+ await visit(code, filename);
34042
+ return {
34043
+ managed,
34044
+ dependencies
34045
+ };
34046
+ }
34047
+ //#endregion
33840
34048
  //#region src/plugins/tailwindcss/vueStyle.ts
33841
34049
  /** 根据 SFC 外部样式的文件身份解析入口,避免依赖编译前后 CSS 文本一致。 */
33842
34050
  async function resolveVueStyleSource(request, resolve) {
@@ -34010,6 +34218,7 @@ function createTailwindcssPlugin(ctx) {
34010
34218
  const contextualSlots = /* @__PURE__ */ new Set();
34011
34219
  const dirtySlots = /* @__PURE__ */ new Set();
34012
34220
  const transformedSources = /* @__PURE__ */ new Map();
34221
+ const importedSources = /* @__PURE__ */ new Map();
34013
34222
  const previousEntrySources = /* @__PURE__ */ new Map();
34014
34223
  const resolvedEntryIndexes = /* @__PURE__ */ new Set();
34015
34224
  const loadedEntryIndexes = /* @__PURE__ */ new Set();
@@ -34136,8 +34345,8 @@ function createTailwindcssPlugin(ctx) {
34136
34345
  classSet: [],
34137
34346
  target: resolved.generatorTarget
34138
34347
  })];
34139
- const snapshot = compiler.mergeSnapshots(snapshots);
34140
- const seenEntries = /* @__PURE__ */ new Set();
34348
+ const snapshot = compiler.mergeSnapshots([...snapshots, ...Array.from(importedSources.values(), (source) => source.snapshot)]);
34349
+ const seenEntries = new Set(Array.from(importedSources.values()).flatMap((source) => source.entries));
34141
34350
  const styleExtension = ctx.configService.outputExtensions.wxss;
34142
34351
  const templateExtension = ctx.configService.outputExtensions.wxml;
34143
34352
  const scriptSourceMap = Boolean(resolvedConfig?.build.sourcemap);
@@ -34195,6 +34404,65 @@ function createTailwindcssPlugin(ctx) {
34195
34404
  applyOutputChunkTransform(output, transformed.code, transformed.map);
34196
34405
  }
34197
34406
  }
34407
+ function importedSourceKey(id) {
34408
+ const style = parseWeappVueStyleRequest(id);
34409
+ return style ? `${style.filename}?style=${style.index}` : id.split("?")[0];
34410
+ }
34411
+ async function transformImportedSource(code, id) {
34412
+ const style = parseWeappVueStyleRequest(id);
34413
+ const filename = requestSources.get(id) ?? style?.filename ?? normalizeFsResolvedId(id.split("?")[0], { stripLeadingNullByte: true });
34414
+ if (!style && !/\.(?:css|pcss|postcss)$/.test(filename)) return null;
34415
+ const query = new URLSearchParams(id.split("?")[1] ?? "");
34416
+ if (query.has("raw") || query.has("url")) return null;
34417
+ const imports = await findManagedStyleImports(code, filename, {
34418
+ resolve: this.resolve.bind(this),
34419
+ isManaged: (file) => isManagedTailwindcssEntry(ctx, file)
34420
+ });
34421
+ const key = importedSourceKey(id);
34422
+ if (!imports.managed) {
34423
+ const previous = importedSources.get(key);
34424
+ if (previous) {
34425
+ await (await getCompiler()).remove(previous.rootId);
34426
+ importedSources.delete(key);
34427
+ }
34428
+ return null;
34429
+ }
34430
+ const compiler = await getCompiler();
34431
+ const rootId = `${MANAGED_PLUGIN_NAME}:import:${key}`;
34432
+ const configuredSource = createTailwindV4SourceOptions(resolved, filename);
34433
+ const generated = await compiler.generate({
34434
+ id: rootId,
34435
+ target: resolved.generatorTarget,
34436
+ scanSources: true,
34437
+ sourceOptions: {
34438
+ ...configuredSource,
34439
+ cssEntries: [],
34440
+ cssSources: [...configuredSource.cssSources ?? [], {
34441
+ css: code,
34442
+ file: filename,
34443
+ base: path.dirname(filename),
34444
+ dependencies: [...imports.dependencies]
34445
+ }]
34446
+ },
34447
+ bareArbitraryValues: resolved.options.arbitraryValues?.bareArbitraryValues,
34448
+ styleOptions: typeof resolved.options.generator === "object" ? resolved.options.generator.styleOptions : void 0
34449
+ });
34450
+ importedSources.set(key, {
34451
+ rootId,
34452
+ snapshot: generated.snapshot,
34453
+ entries: [...imports.dependencies].flatMap((file) => {
34454
+ const index = parseManagedEntryIndex(file, entryIndex);
34455
+ return index === void 0 ? [] : [index];
34456
+ })
34457
+ });
34458
+ const dependencies = /* @__PURE__ */ new Set([...imports.dependencies, ...generated.dependencies]);
34459
+ for (const dependency of dependencies) this.addWatchFile(dependency);
34460
+ return {
34461
+ code: await stripResidualTailwindSourceDirectives((await compiler.transformCss(generated.rawCss, generated.snapshot, { isMainChunk: filename === path.resolve(ctx.configService.absoluteSrcRoot, "app.vue") })).css),
34462
+ map: null,
34463
+ meta: createStyleSourceMeta(dependencies)
34464
+ };
34465
+ }
34198
34466
  return [{
34199
34467
  name: MANAGED_PLUGIN_NAME,
34200
34468
  enforce: "pre",
@@ -34256,7 +34524,14 @@ function createTailwindcssPlugin(ctx) {
34256
34524
  return source;
34257
34525
  },
34258
34526
  load(id) {
34259
- if (resolved.options.generator === false || parseSidecarSourceRequest(id)?.dependencyOnly || parseWeappVueStyleRequest(id)) return null;
34527
+ if (resolved.options.generator === false || parseWeappVueStyleRequest(id)) return null;
34528
+ const sidecar = parseSidecarSourceRequest(id);
34529
+ if (sidecar?.dependencyOnly) return null;
34530
+ if (sidecar?.kind === "style" && isManagedTailwindcssEntry(ctx, sidecar.sourceId)) return {
34531
+ code: "export default \"\"",
34532
+ map: null,
34533
+ meta: createStyleSourceMeta([sidecar.sourceId])
34534
+ };
34260
34535
  const normalizedId = normalizeManagedTailwindcssEntryPath(requestSources.get(id) ?? id.split("?")[0]);
34261
34536
  const index = entryIndex.get(normalizedId);
34262
34537
  if (index === void 0) return null;
@@ -34271,7 +34546,7 @@ function createTailwindcssPlugin(ctx) {
34271
34546
  if (resolved.options.generator === false || parseSidecarSourceRequest(id)?.dependencyOnly) return null;
34272
34547
  const sourceId = requestSources.get(id) ?? id;
34273
34548
  const entry = parseManagedEntryIndex(sourceId, entryIndex) ?? resolveAutoEntryIndex(sourceId, code);
34274
- if (entry === void 0) return null;
34549
+ if (entry === void 0) return code.includes("@import") || importedSources.has(importedSourceKey(id)) ? transformImportedSource.call(this, code, id) : null;
34275
34550
  const index = getSourceSlot(id, entry);
34276
34551
  dirtySlots.delete(index);
34277
34552
  loadedEntryIndexes.add(index);
@@ -34288,6 +34563,7 @@ function createTailwindcssPlugin(ctx) {
34288
34563
  };
34289
34564
  },
34290
34565
  shouldTransformCachedModule({ id }) {
34566
+ if (importedSources.has(importedSourceKey(id))) return true;
34291
34567
  const index = parseManagedEntryIndex(requestSources.get(id) ?? id, entryIndex);
34292
34568
  if (index !== void 0 && dirtySlots.has(getSourceSlot(id, index))) return true;
34293
34569
  },
@@ -35139,6 +35415,11 @@ function buildCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, conf
35139
35415
  const wevuMinify = isWevuMinifyEnabled(configService.weappViteConfig, configService.isDev);
35140
35416
  const jsonKind = isApp ? "app" : isPage ? "page" : "component";
35141
35417
  const sourceMap = isVueTransformSourceMapEnabled(configService);
35418
+ const stabilizeCssVarsRuntime = configService.isDev && resolveHmrRuntime({
35419
+ platform: configService.platform,
35420
+ configured: configService.weappViteConfig?.hmr?.runtime,
35421
+ compileHotReLoad: configService.projectPrivateConfig?.setting?.compileHotReLoad
35422
+ }) === "stateful-experimental";
35142
35423
  async function resolvePotentialVueSfcEntryId(candidate) {
35143
35424
  const trimmed = candidate?.trim();
35144
35425
  if (!trimmed) return;
@@ -35199,6 +35480,7 @@ function buildCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, conf
35199
35480
  isApp,
35200
35481
  skipComponentTransform: delegatesComponentRegistration,
35201
35482
  autoSetDataPick: isAutoSetDataPickEnabledWithPreset(configService.weappViteConfig),
35483
+ stabilizeCssVarsRuntime,
35202
35484
  bindingManifestSourceFile: resolveBindingManifestSourceFile(vuePath, configService),
35203
35485
  runtimeBindingManifest: configService.isDev ? "diagnostic" : "compact",
35204
35486
  pageLayout,
@@ -35273,7 +35555,7 @@ function createCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, con
35273
35555
  const appShellSignature = createCompilerAppShellSignature(isPage && !isApp ? resolvedAppShell : void 0);
35274
35556
  const cacheKey = getCompileVueFileOptionsCacheKey(vuePath, isPage, isApp, delegatesComponentRegistration, state.emitResolvedComponentEntries !== false, pageLayoutSignature, appShellSignature);
35275
35557
  const cached = state.compileOptionsCache?.get(cacheKey);
35276
- if (cached && compileOptionsOwners.get(cached) === pluginCtx) return cached;
35558
+ if (!configService.isDev && cached && compileOptionsOwners.get(cached) === pluginCtx) return cached;
35277
35559
  const created = buildCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, configService, state, delegatesComponentRegistration, pageLayout, appShell);
35278
35560
  compileOptionsOwners.set(created, pluginCtx);
35279
35561
  state.compileOptionsCache?.set(cacheKey, created);
@@ -35622,7 +35904,18 @@ async function finalizeTransformCompiledResult(options) {
35622
35904
  const transformResult = result;
35623
35905
  if (isApp) setAppShell?.(hasAppShellTemplate(result) ? resolveAppShellLayout(configService) : void 0);
35624
35906
  if (!isApp) registerVueTemplateToken(ctx, filename, result.template);
35625
- if (Array.isArray(result.meta?.sfcSrcDeps)) ctx.moduleGraphService.replaceEntryDependencies(filename, "style", result.meta.sfcSrcDeps);
35907
+ if (Array.isArray(result.meta?.sfcSrcDeps)) {
35908
+ addNormalizedWatchFiles(pluginCtx, result.meta.sfcSrcDeps);
35909
+ ctx.moduleGraphService.replaceEntryDependencies(filename, "style", result.meta.sfcSrcDeps);
35910
+ }
35911
+ if (configService.isDev) {
35912
+ const styleBindings = ctx.runtimeState.build.hmr.vueEntryStyleBindings;
35913
+ if (result.meta?.sfcSrcDeps?.length) styleBindings.set(filename, {
35914
+ sources: result.meta.sfcSrcDeps,
35915
+ expressions: result.meta.cssVars
35916
+ });
35917
+ else styleBindings.delete(filename);
35918
+ }
35626
35919
  const jsxDependencies = result.meta?.jsxDependencies ?? [];
35627
35920
  addNormalizedWatchFiles(pluginCtx, jsxDependencies);
35628
35921
  ctx.moduleGraphService.replaceEntryDependencies(filename, "jsx", jsxDependencies);
@@ -35746,27 +36039,6 @@ async function loadTransformStyleBlock(options) {
35746
36039
  };
35747
36040
  }
35748
36041
  //#endregion
35749
- //#region src/plugins/vue/transform/styleOnly.ts
35750
- function hasCssModules(styleBlocks) {
35751
- return styleBlocks?.some((styleBlock) => Boolean(styleBlock.module)) === true;
35752
- }
35753
- async function refreshStyleOnlyVueTransformResult(result, filename, styleBlocks, stylePreprocessOptions) {
35754
- if (!styleBlocks || hasCssModules(styleBlocks)) return false;
35755
- if (!styleBlocks.length) {
35756
- result.style = void 0;
35757
- return true;
35758
- }
35759
- const scopedId = generateScopedId(filename);
35760
- result.style = (await Promise.all(styleBlocks.map(async (styleBlock) => await compileVueStyleToWxss(styleBlock, {
35761
- id: scopedId,
35762
- filename,
35763
- scoped: styleBlock.scoped,
35764
- modules: styleBlock.module,
35765
- preprocessOptions: stylePreprocessOptions?.[styleBlock.lang || "css"]
35766
- })))).map((result) => result.code.trim()).filter(Boolean).join("\n\n") || void 0;
35767
- return true;
35768
- }
35769
- //#endregion
35770
36042
  //#region src/plugins/vue/transform/bundle/shared/types.ts
35771
36043
  function getVueBundlePageLayoutPlan(result) {
35772
36044
  return result.meta?.pageLayoutPlan;
@@ -35881,7 +36153,7 @@ async function refreshCompiledVueEntryCacheInDev(options) {
35881
36153
  source,
35882
36154
  checkMtime: configService.isDev
35883
36155
  });
35884
- if (!await refreshStyleOnlyVueTransformResult(cached.result, filename, descriptor.styles, resolveSfcStylePreprocessOptions(configService))) cached.styleIndependentSignature = void 0;
36156
+ if (!await refreshStyleOnlyVueTransformResult(cached.result, filename, descriptor.styles, descriptor.cssVars, resolveSfcStylePreprocessOptions(configService))) cached.styleIndependentSignature = void 0;
35885
36157
  else {
35886
36158
  cached.source = source;
35887
36159
  cached.styleIndependentSignature = currentStyleIndependentSignature;
@@ -36167,7 +36439,7 @@ function emitAppShellAssetsIfNeeded(options) {
36167
36439
  //#endregion
36168
36440
  //#region src/plugins/vue/transform/bundle/emitCompiledEntry.ts
36169
36441
  function shouldReplaceAppScriptBundleEntry(options) {
36170
- if (!isAppVueFile(options.filename) || !options.isDev || !options.hasDevHmrEvent) return false;
36442
+ if (options.isBundledDev || !isAppVueFile(options.filename) || !options.isDev || !options.hasDevHmrEvent) return false;
36171
36443
  return true;
36172
36444
  }
36173
36445
  function hasUnresolvedModuleImportDeclaration(script) {
@@ -36202,7 +36474,8 @@ async function emitResolvedCompiledVueEntryAssets(options) {
36202
36474
  const shouldReplaceAppScript = shouldReplaceAppScriptBundleEntry({
36203
36475
  filename,
36204
36476
  isDev: configService.isDev,
36205
- hasDevHmrEvent: hmrState?.profile?.event !== void 0
36477
+ hasDevHmrEvent: hmrState?.profile?.event !== void 0,
36478
+ isBundledDev: state.isBundledDev
36206
36479
  });
36207
36480
  if (isAppVueFile(filename) && hasAppShellTemplate(result)) emitAppShellAssetsIfNeeded({
36208
36481
  bundle,
@@ -36577,21 +36850,30 @@ function createSfcStyleBlocksSignature(styleBlocks) {
36577
36850
  scoped: styleBlock.scoped
36578
36851
  })));
36579
36852
  }
36580
- async function loadStyleBlocksForStyleOnlyRefresh(options) {
36853
+ async function loadSfcStyleStateForStyleOnlyRefresh(options) {
36581
36854
  const { filename, source, styleBlocksCache, force, readAndParseSfc, createReadAndParseSfcOptions, pluginCtx, configService } = options;
36582
36855
  if (force) styleBlocksCache.delete(filename);
36583
- await preloadTransformSfcStyleBlocks({
36856
+ let cssVars;
36857
+ const styleBlocks = await preloadTransformSfcStyleBlocks({
36584
36858
  filename,
36585
36859
  source,
36586
36860
  styleBlocksCache,
36587
36861
  load: async (target, source) => {
36588
- return (await readAndParseSfc(target, createReadAndParseSfcOptions(pluginCtx, configService, {
36862
+ const parsed = await readAndParseSfc(target, createReadAndParseSfcOptions(pluginCtx, configService, {
36589
36863
  source,
36590
36864
  checkMtime: configService.isDev
36591
- }))).descriptor.styles;
36865
+ }));
36866
+ cssVars = parsed.descriptor.cssVars;
36867
+ return parsed.descriptor.styles;
36592
36868
  }
36593
36869
  });
36594
- return styleBlocksCache.get(filename);
36870
+ return {
36871
+ cssVars,
36872
+ styleBlocks
36873
+ };
36874
+ }
36875
+ async function loadStyleBlocksForStyleOnlyRefresh(options) {
36876
+ return (await loadSfcStyleStateForStyleOnlyRefresh(options)).styleBlocks;
36595
36877
  }
36596
36878
  //#endregion
36597
36879
  //#region src/plugins/vue/transform/plugin/usingComponents.ts
@@ -36689,8 +36971,8 @@ async function tryReuseVueCompilation(options) {
36689
36971
  const cachedResult = normalizeVueTransformResult(cachedCompilation.result);
36690
36972
  let cachedStyleBlocks = cachedResult.meta?.styleBlocks ?? styleBlocksCache.get(filename);
36691
36973
  let canReturnCachedCompilation = true;
36692
- if (dirtyEntryId && canAttemptStyleOnlyReuse && filename.endsWith(".vue")) {
36693
- const refreshedStyleBlocks = await measureStage("loadStyleOnlySfcStyles", async () => await loadStyleBlocksForStyleOnlyRefresh({
36974
+ if (filename.endsWith(".vue") && (dirtyEntryId && canAttemptStyleOnlyReuse || cachedStyleBlocks?.some((style) => Boolean(style.src)))) {
36975
+ const refreshedStyleState = await measureStage("loadStyleOnlySfcStyles", async () => await loadSfcStyleStateForStyleOnlyRefresh({
36694
36976
  filename,
36695
36977
  source,
36696
36978
  styleBlocksCache,
@@ -36700,7 +36982,8 @@ async function tryReuseVueCompilation(options) {
36700
36982
  pluginCtx,
36701
36983
  configService
36702
36984
  }));
36703
- if (!await refreshStyleOnlyVueTransformResult(cachedResult, filename, refreshedStyleBlocks, resolveSfcStylePreprocessOptions(configService))) {
36985
+ const refreshedStyleBlocks = refreshedStyleState.styleBlocks;
36986
+ if (!await refreshStyleOnlyVueTransformResult(cachedResult, filename, refreshedStyleBlocks, refreshedStyleState.cssVars, resolveSfcStylePreprocessOptions(configService))) {
36704
36987
  cachedCompilation.styleIndependentSignature = void 0;
36705
36988
  canReturnCachedCompilation = false;
36706
36989
  } else {
@@ -36732,7 +37015,7 @@ async function tryReuseVueCompilation(options) {
36732
37015
  const currentStyleIndependentSignature = configService.isDev && dirtyEntryId && canAttemptStyleOnlyReuse && filename.endsWith(".vue") ? resolveVueSfcStyleIndependentSignature(source, filename) : void 0;
36733
37016
  if (Boolean(configService.isDev && cachedCompilation && dirtyEntryId && canAttemptStyleOnlyReuse && filename.endsWith(".vue") && !ctx.runtimeState.scan.isDirty && cachedCompilation.autoRoutesSignature === autoRoutesSignature && cachedCompilation.styleIndependentSignature && currentStyleIndependentSignature && cachedCompilation.styleIndependentSignature === currentStyleIndependentSignature && cachedCompilation.source !== source) && cachedCompilation) {
36734
37017
  const cachedResult = normalizeVueTransformResult(cachedCompilation.result);
36735
- const styleBlocks = await measureStage("loadStyleOnlySfcStyles", async () => await loadStyleBlocksForStyleOnlyRefresh({
37018
+ const styleState = await measureStage("loadStyleOnlySfcStyles", async () => await loadSfcStyleStateForStyleOnlyRefresh({
36736
37019
  filename,
36737
37020
  source,
36738
37021
  styleBlocksCache,
@@ -36742,7 +37025,8 @@ async function tryReuseVueCompilation(options) {
36742
37025
  pluginCtx,
36743
37026
  configService
36744
37027
  }));
36745
- if (!await refreshStyleOnlyVueTransformResult(cachedResult, filename, styleBlocks, resolveSfcStylePreprocessOptions(configService))) cachedCompilation.styleIndependentSignature = void 0;
37028
+ const styleBlocks = styleState.styleBlocks;
37029
+ if (!await refreshStyleOnlyVueTransformResult(cachedResult, filename, styleBlocks, styleState.cssVars, resolveSfcStylePreprocessOptions(configService))) cachedCompilation.styleIndependentSignature = void 0;
36746
37030
  else {
36747
37031
  cachedCompilation.source = source;
36748
37032
  cachedCompilation.result = cachedResult;
@@ -36993,6 +37277,7 @@ function createVueTransformPlugin(ctx, options = {}) {
36993
37277
  let appShell;
36994
37278
  let pageMatcher = null;
36995
37279
  let scanDirtySynced = false;
37280
+ let isBundledDev = false;
36996
37281
  const reExportResolutionCache = /* @__PURE__ */ new Map();
36997
37282
  const compileOptionsCache = /* @__PURE__ */ new Map();
36998
37283
  const componentMetaCache = /* @__PURE__ */ new Map();
@@ -37008,6 +37293,9 @@ function createVueTransformPlugin(ctx, options = {}) {
37008
37293
  }
37009
37294
  return {
37010
37295
  name: `${VUE_PLUGIN_NAME}:transform`,
37296
+ configResolved(config) {
37297
+ isBundledDev = config.command === "serve" && Boolean(config.experimental.bundledDev);
37298
+ },
37011
37299
  async buildStart() {
37012
37300
  scopedSlotModules.clear();
37013
37301
  emittedScopedSlotChunks.clear();
@@ -37092,6 +37380,7 @@ function createVueTransformPlugin(ctx, options = {}) {
37092
37380
  async generateBundle(_options, bundle) {
37093
37381
  await emitVueBundleAssets(bundle, {
37094
37382
  ctx,
37383
+ isBundledDev,
37095
37384
  pluginCtx: this,
37096
37385
  compilationCache,
37097
37386
  appShell,
@@ -38446,7 +38735,7 @@ async function loadAppEntry(ctx, scanState) {
38446
38735
  const { path: appEntryPath } = appEntry;
38447
38736
  let configFromVue;
38448
38737
  if (!appConfigFile && vueAppPath) {
38449
- const { extractConfigFromVue } = await import("./file-BRQqRekU.mjs");
38738
+ const { extractConfigFromVue } = await import("./file-DxMrh1lh.mjs");
38450
38739
  configFromVue = await extractConfigFromVue(vueAppPath);
38451
38740
  if (configFromVue) appConfigFile = vueAppPath;
38452
38741
  }