weapp-vite 6.14.2 → 6.15.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.
@@ -1,6 +1,6 @@
1
1
  import { n as applyWeappViteHostMeta } from "./pluginHost-BzPJL4F-.mjs";
2
2
  import { n as configureLogger, r as logger_default } from "./logger-CgxdNjvb.mjs";
3
- import { _ as supportedCssLangs, a as findJsonEntry, c as inlineAutoRoutesImports, g as jsExtensions, h as configExtensions, i as findJsEntry, l as isJsOrTs, n as extractConfigFromVue, o as findTemplateEntry, p as touch, r as findCssEntry, s as findVueEntry, t as changeFileExtension, u as isTemplate, v as templateExtensions, y as vueExtensions } from "./file-PUFdKeUd.mjs";
3
+ import { _ as supportedCssLangs, a as findJsonEntry, c as inlineAutoRoutesImports, g as jsExtensions, h as configExtensions, i as findJsEntry, l as isJsOrTs, n as extractConfigFromVue, o as findTemplateEntry, p as touch, r as findCssEntry, s as findVueEntry, t as changeFileExtension, u as isTemplate, v as templateExtensions, y as vueExtensions } from "./file-DZdM8x0_.mjs";
4
4
  import { createRequire, isBuiltin } from "node:module";
5
5
  import { addExtension, defu, fs, get, isEmptyObject, isObject, objectHash, removeExtension, removeExtensionDeep, set } from "@weapp-core/shared";
6
6
  import { LRUCache } from "lru-cache";
@@ -17,7 +17,7 @@ import { VUE_COMPONENT_TAG_RE, WE_VU_MODULE_ID, WE_VU_RUNTIME_APIS, buildClassSt
17
17
  import process$1 from "node:process";
18
18
  import { parse as parse$1, stringify } from "comment-json";
19
19
  import fs$1, { readFile, readdir, rm } from "node:fs/promises";
20
- import { build, createLogger, createServer, loadConfigFromFile, preprocessCSS } from "vite";
20
+ import { build, createLogger, createServer, loadConfigFromFile, preprocessCSS, transformWithOxc } from "vite";
21
21
  import { createHash } from "node:crypto";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import semverGte from "semver/functions/gte.js";
@@ -266,10 +266,13 @@ function getAutoImportConfig(configService) {
266
266
  if (!weappConfig) return;
267
267
  const userConfigured = weappConfig.autoImportComponents ?? weappConfig.enhance?.autoImportComponents;
268
268
  const enabledDefaults = createEnabledAutoImportComponents(configService);
269
+ const hasMergeableSubPackageAutoImportConfig = Boolean(Object.values(weappConfig.subPackages ?? {}).some((subConfig) => {
270
+ const scoped = subConfig?.autoImportComponents;
271
+ return scoped !== void 0 && scoped !== false;
272
+ }));
269
273
  if (userConfigured === false) return;
270
274
  const normalizedConfig = userConfigured === true ? enabledDefaults : userConfigured ? mergeAutoImportComponents(enabledDefaults, cloneAutoImportComponents(userConfigured), true) : void 0;
271
- const fallbackConfig = normalizedConfig === void 0 ? createDefaultAutoImportComponents(configService) : void 0;
272
- const baseConfig = cloneAutoImportComponents(normalizedConfig ?? fallbackConfig);
275
+ const baseConfig = cloneAutoImportComponents(normalizedConfig ?? (normalizedConfig === void 0 && !hasMergeableSubPackageAutoImportConfig ? enabledDefaults : void 0));
273
276
  const subPackageConfigs = weappConfig.subPackages;
274
277
  const currentRoot = configService.currentSubPackageRoot;
275
278
  if (currentRoot) {
@@ -788,6 +791,7 @@ function shouldNormalizeNpmImportByPlatform(importee, options) {
788
791
  function normalizeNpmImportPathByPlatform(importee, options) {
789
792
  const trimmed = importee.trim();
790
793
  if (!shouldNormalizeNpmImportByPlatform(trimmed, options)) return importee;
794
+ if (!options.platform) return importee;
791
795
  const normalized = trimmed.replace(NPM_PROTOCOL_RE$1, "");
792
796
  return normalizePlatformNpmImportPath(options.platform, normalized, { alipayNpmMode: options.alipayNpmMode });
793
797
  }
@@ -4790,8 +4794,8 @@ async function resolveImplicitConfigFile(configRoot) {
4790
4794
  }
4791
4795
  }
4792
4796
  }
4793
- async function loadViteConfigFile(configEnv, configFile, configRoot, configFileDependencies, configFileExport, configLoader, runner) {
4794
- return loadConfigFromFile(configEnv, configFile ?? await resolveImplicitConfigFile(configRoot), configRoot, configFileDependencies, configFileExport, configLoader ?? "bundle", runner);
4797
+ async function loadViteConfigFile(configEnv, configFile, configRoot, configFileDependencies, configFileExport, configLoader) {
4798
+ return loadConfigFromFile(configEnv, configFile ?? await resolveImplicitConfigFile(configRoot), configRoot, void 0, void 0, configLoader ?? "bundle");
4795
4799
  }
4796
4800
  //#endregion
4797
4801
  //#region src/utils/projectConfig.ts
@@ -5237,7 +5241,7 @@ function createRegistryHelpers(state) {
5237
5241
  const htmlSettings = getHtmlCustomDataSettings(state.ctx);
5238
5242
  if (typedSettings.enabled || htmlSettings.enabled) {
5239
5243
  const astEngine = resolveAstEngine(state.ctx.configService.weappViteConfig);
5240
- let metadataSource = json;
5244
+ let metadataSource = json ?? void 0;
5241
5245
  try {
5242
5246
  if (!metadataSource && JSON_LIKE_FILE_RE.test(resolvedJsonPath)) metadataSource = await fs.readJson(resolvedJsonPath);
5243
5247
  } catch {}
@@ -5262,8 +5266,7 @@ function createRegistryHelpers(state) {
5262
5266
  state.scheduleVueComponentsWrite(vueSettings.enabled || removed || removedNames.length > 0);
5263
5267
  }
5264
5268
  function ensureMatcher() {
5265
- const configService = requireConfigService(state.ctx, "过滤组件前必须初始化 configService。");
5266
- const globs = getAutoImportConfig(configService)?.globs;
5269
+ const globs = getAutoImportConfig(requireConfigService(state.ctx, "过滤组件前必须初始化 configService。"))?.globs;
5267
5270
  if (!globs || globs.length === 0) {
5268
5271
  state.autoImportState.matcher = void 0;
5269
5272
  state.autoImportState.matcherKey = "";
@@ -5271,11 +5274,7 @@ function createRegistryHelpers(state) {
5271
5274
  }
5272
5275
  const nextKey = globs.join("\0");
5273
5276
  if (!state.autoImportState.matcher || state.autoImportState.matcherKey !== nextKey) {
5274
- state.autoImportState.matcher = picomatch(globs, {
5275
- cwd: configService.cwd,
5276
- windows: true,
5277
- posixSlashes: true
5278
- });
5277
+ state.autoImportState.matcher = picomatch(globs, { windows: true });
5279
5278
  state.autoImportState.matcherKey = nextKey;
5280
5279
  }
5281
5280
  return state.autoImportState.matcher;
@@ -5440,7 +5439,7 @@ function createResolverHelpers(state) {
5440
5439
  const allComponents = /* @__PURE__ */ new Map();
5441
5440
  for (const resolver of resolvers) {
5442
5441
  if (getSupportFilesStrategy(resolver) !== "full") continue;
5443
- for (const [name, from] of Object.entries(resolver?.components ?? {})) allComponents.set(name, from);
5442
+ for (const [name, from] of Object.entries(resolver?.components ?? {})) if (typeof from === "string") allComponents.set(name, from);
5444
5443
  }
5445
5444
  return Object.fromEntries(allComponents);
5446
5445
  }
@@ -5471,8 +5470,9 @@ function createResolverHelpers(state) {
5471
5470
  }
5472
5471
  for (const step of getCompiledResolvers(resolvers)) {
5473
5472
  if (step.kind === "static") {
5473
+ const components = step.components ?? {};
5474
5474
  for (const candidate of toComponentCandidates(componentName)) {
5475
- const from = step.components[candidate];
5475
+ const from = components[candidate];
5476
5476
  if (from) {
5477
5477
  const value = {
5478
5478
  name: componentName,
@@ -5484,6 +5484,7 @@ function createResolverHelpers(state) {
5484
5484
  }
5485
5485
  continue;
5486
5486
  }
5487
+ if (!step.resolver) continue;
5487
5488
  const value = resolveWithResolver(step.resolver, componentName, importerBaseName ?? "");
5488
5489
  if (value) {
5489
5490
  resolveCache.set(cacheKey, value);
@@ -5923,7 +5924,7 @@ async function discoverPagesRoots(root) {
5923
5924
  const classified = classifyPagesRootEntry(current, entry);
5924
5925
  if (!classified) continue;
5925
5926
  if ("pageRoot" in classified) {
5926
- pagesRoots.add(classified.pageRoot);
5927
+ if (classified.pageRoot) pagesRoots.add(classified.pageRoot);
5927
5928
  continue;
5928
5929
  }
5929
5930
  queue.push(classified.nextPath);
@@ -6045,7 +6046,7 @@ async function collectCandidates(absoluteSrcRoot, include, subPackageRoots, sear
6045
6046
  for (const entryPath of files) {
6046
6047
  const resolvedEntryPath = resolveCandidateEntryPath(absoluteSrcRoot, entryPath);
6047
6048
  if (!shouldCollectCandidateEntry(matcher, resolvedEntryPath)) continue;
6048
- applyCandidateEntryToMap(candidates, entryPath, resolvedEntryPath);
6049
+ if (resolvedEntryPath) applyCandidateEntryToMap(candidates, entryPath, resolvedEntryPath);
6049
6050
  }
6050
6051
  }
6051
6052
  return candidates;
@@ -7620,7 +7621,9 @@ function normalizeScriptModuleExtension(scriptModuleExtension) {
7620
7621
  }
7621
7622
  function getDefaultScriptModuleTagByExtension(scriptModuleExtension) {
7622
7623
  if (!scriptModuleExtension) return "wxs";
7623
- return DEFAULT_SCRIPT_MODULE_TAG_BY_EXTENSION[normalizeScriptModuleExtension(scriptModuleExtension)] ?? "wxs";
7624
+ const normalizedExtension = normalizeScriptModuleExtension(scriptModuleExtension);
7625
+ if (!normalizedExtension || !(normalizedExtension in DEFAULT_SCRIPT_MODULE_TAG_BY_EXTENSION)) return "wxs";
7626
+ return DEFAULT_SCRIPT_MODULE_TAG_BY_EXTENSION[normalizedExtension];
7624
7627
  }
7625
7628
  function resolveScriptModuleTagName(options) {
7626
7629
  if (options?.scriptModuleTag) return options.scriptModuleTag;
@@ -7637,6 +7640,7 @@ function isScriptModuleTagName(tagName) {
7637
7640
  }
7638
7641
  function getScriptModuleImportAttrs(tagName) {
7639
7642
  if (!tagName) return;
7643
+ if (!(tagName in SCRIPT_MODULE_IMPORT_ATTRS)) return;
7640
7644
  return SCRIPT_MODULE_IMPORT_ATTRS[tagName];
7641
7645
  }
7642
7646
  function isScriptModuleImportAttr(tagName, attrName) {
@@ -7659,14 +7663,12 @@ const TEMPLATE_IMPORT_ATTRS = Object.freeze({
7659
7663
  import: ["src"],
7660
7664
  include: ["src"]
7661
7665
  });
7662
- function getTemplateImportTagNames() {
7663
- return [...TEMPLATE_IMPORT_TAG_NAMES];
7664
- }
7665
7666
  function isTemplateImportTag(tagName) {
7666
- return typeof tagName === "string" && getTemplateImportTagNames().includes(tagName);
7667
+ return typeof tagName === "string" && TEMPLATE_IMPORT_TAG_NAMES.includes(tagName);
7667
7668
  }
7668
7669
  function getTemplateImportAttrs(tagName) {
7669
7670
  if (!tagName) return;
7671
+ if (!(tagName in TEMPLATE_IMPORT_ATTRS)) return;
7670
7672
  return TEMPLATE_IMPORT_ATTRS[tagName];
7671
7673
  }
7672
7674
  function isTemplateImportAttr(tagName, attrName) {
@@ -8218,6 +8220,7 @@ function normalizeRelativeDir(value) {
8218
8220
  return (normalized.startsWith("./") ? normalized.slice(2) : normalized).replace(EMPTY_VALUE_RE, ".");
8219
8221
  }
8220
8222
  function resolvePlatformProjectRoot(configService) {
8223
+ if (!configService) return "dist";
8221
8224
  return normalizeRelativeDir(resolveProjectConfigRoot(configService.projectConfig, configService.platform) ?? "dist");
8222
8225
  }
8223
8226
  function getPackNpmRelationList(ctx) {
@@ -8266,6 +8269,7 @@ function getPackNpmRelationList(ctx) {
8266
8269
  const LEADING_SLASHES_RE$2 = /^\/+/;
8267
8270
  const WINDOWS_PATH_RE = /\\|^[A-Z]:[\\/]/i;
8268
8271
  const TRAILING_SLASHES_RE$1 = /\/+$/;
8272
+ const DEFAULT_NPM_STRATEGY = "explicit";
8269
8273
  function matchDependencyName(patterns, dep) {
8270
8274
  return patterns.some((pattern) => {
8271
8275
  if (typeof pattern === "string") return pattern === dep;
@@ -8283,6 +8287,13 @@ function matchDependencyPath(patterns, value) {
8283
8287
  return pattern.test(value);
8284
8288
  });
8285
8289
  }
8290
+ function dedupeDependencies(dependencies) {
8291
+ return [...new Set(dependencies)];
8292
+ }
8293
+ function createDependencyRecord(dependencies) {
8294
+ if (dependencies.length === 0) return;
8295
+ return Object.fromEntries(dependencies.map((dep) => [dep, "*"]));
8296
+ }
8286
8297
  function resolveCopyFilterRelativePath(sourceRoot, sourcePath) {
8287
8298
  const normalizedRoot = normalizePath$1(sourceRoot).replace(TRAILING_SLASHES_RE$1, "");
8288
8299
  const normalizedPath = normalizePath$1(sourcePath);
@@ -8298,6 +8309,47 @@ function resolveTargetDependencies(allDependencies, patterns) {
8298
8309
  for (const pattern of patterns) if (typeof pattern === "string") selected.add(pattern);
8299
8310
  return [...selected];
8300
8311
  }
8312
+ function resolveNpmStrategy(ctx) {
8313
+ return ctx.configService?.weappViteConfig?.npm?.strategy ?? DEFAULT_NPM_STRATEGY;
8314
+ }
8315
+ function resolveConfiguredDependencyPatterns(ctx) {
8316
+ const npmConfig = ctx.configService?.weappViteConfig?.npm;
8317
+ const patterns = [...npmConfig?.include ?? []];
8318
+ if (ctx.configService?.pluginOnly) {
8319
+ if (Array.isArray(npmConfig?.pluginPackage?.dependencies)) patterns.push(...npmConfig.pluginPackage.dependencies);
8320
+ return patterns;
8321
+ }
8322
+ if (Array.isArray(npmConfig?.mainPackage?.dependencies)) patterns.push(...npmConfig.mainPackage.dependencies);
8323
+ for (const config of Object.values(npmConfig?.subPackages ?? {})) if (Array.isArray(config?.dependencies)) patterns.push(...config.dependencies);
8324
+ return patterns;
8325
+ }
8326
+ function resolveDeclaredDependencies(pkgJson) {
8327
+ return dedupeDependencies([...Object.keys(pkgJson.dependencies ?? {}), ...Object.keys(pkgJson.devDependencies ?? {})]);
8328
+ }
8329
+ function isMiniprogramPackage(pkg) {
8330
+ return Reflect.has(pkg, "miniprogram") && typeof pkg.miniprogram === "string";
8331
+ }
8332
+ function resolveMiniprogramCandidateDependenciesSync(allDependencies, cwd) {
8333
+ return allDependencies.filter((dep) => {
8334
+ let packageInfo = null;
8335
+ try {
8336
+ packageInfo = getPackageInfoSync(dep, cwd ? { paths: [cwd] } : void 0);
8337
+ } catch {
8338
+ packageInfo = null;
8339
+ }
8340
+ return !!packageInfo && isMiniprogramPackage(packageInfo.packageJson);
8341
+ });
8342
+ }
8343
+ function resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson) {
8344
+ if (resolveNpmStrategy(ctx) === "legacy") return Object.keys(pkgJson.dependencies ?? {});
8345
+ const declaredDependencies = resolveDeclaredDependencies(pkgJson);
8346
+ const explicitlyIncludedDependencies = resolveTargetDependencies(declaredDependencies, resolveConfiguredDependencyPatterns(ctx));
8347
+ return dedupeDependencies([...resolveMiniprogramCandidateDependenciesSync(declaredDependencies, ctx.configService?.cwd), ...explicitlyIncludedDependencies]);
8348
+ }
8349
+ function resolveNpmBuildCandidateDependencyRecordSync(ctx, pkgJson) {
8350
+ if (!pkgJson) return;
8351
+ return createDependencyRecord(resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson));
8352
+ }
8301
8353
  function hasSameDependencySet(source, target) {
8302
8354
  if (source.length !== target.length) return false;
8303
8355
  return source.every((dep) => target.includes(dep));
@@ -8324,6 +8376,26 @@ function createNpmService(ctx) {
8324
8376
  const oxcVitePlugin = createOxcRuntimeSupport().vitePlugin;
8325
8377
  const cache = createDependenciesCache(ctx);
8326
8378
  const builder = createPackageBuilder(ctx, oxcVitePlugin);
8379
+ async function resolveMiniprogramCandidateDependencies(allDependencies, cwd) {
8380
+ return (await Promise.all(allDependencies.map(async (dep) => {
8381
+ let packageInfo = null;
8382
+ try {
8383
+ packageInfo = await getPackageInfo(dep, cwd ? { paths: [cwd] } : void 0);
8384
+ } catch {
8385
+ packageInfo = null;
8386
+ }
8387
+ if (packageInfo && builder.isMiniprogramPackage(packageInfo.packageJson)) return dep;
8388
+ return null;
8389
+ }))).filter((dep) => typeof dep === "string");
8390
+ }
8391
+ async function resolveBuildCandidateDependencies(pkgJson) {
8392
+ const syncCandidates = resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson);
8393
+ if (resolveNpmStrategy(ctx) === "legacy") return syncCandidates;
8394
+ const declaredDependencies = resolveDeclaredDependencies(pkgJson);
8395
+ const miniprogramDependencies = await resolveMiniprogramCandidateDependencies(declaredDependencies, ctx.configService?.cwd);
8396
+ const explicitlyIncludedDependencies = resolveTargetDependencies(declaredDependencies, resolveConfiguredDependencyPatterns(ctx));
8397
+ return dedupeDependencies([...miniprogramDependencies, ...explicitlyIncludedDependencies]);
8398
+ }
8327
8399
  async function build(options) {
8328
8400
  if (!ctx.configService?.weappViteConfig?.npm?.enable) return;
8329
8401
  debug$2?.("buildNpm start");
@@ -8334,70 +8406,68 @@ function createNpmService(ctx) {
8334
8406
  const [mainRelation, ...subRelations] = getPackNpmRelationList(ctx);
8335
8407
  const packageJsonPath = path.resolve(ctx.configService.cwd, mainRelation.packageJsonPath);
8336
8408
  if (await fs.pathExists(packageJsonPath)) {
8337
- const pkgJson = await fs.readJson(packageJsonPath);
8409
+ const pkgJson = await fs.readJson(packageJsonPath) ?? {};
8338
8410
  const npmDistDirName = resolveNpmDistDirName(ctx.configService);
8339
8411
  const outDir = path.resolve(ctx.configService.cwd, mainRelation.miniprogramNpmDistDir, npmDistDirName);
8340
8412
  const cachedSourceOutDir = resolveNpmSourceCacheOutDir(ctx.configService.cwd, npmDistDirName);
8341
8413
  const localSubPackageOutRoot = ctx.configService.outDir || path.resolve(ctx.configService.cwd, mainRelation.miniprogramNpmDistDir);
8342
- if (pkgJson.dependencies) {
8343
- const allDependencies = Object.keys(pkgJson.dependencies);
8344
- const mainDependencies = resolveTargetDependencies(allDependencies, ctx.configService.pluginOnly ? resolvePluginPackageDependencyPatterns(ctx) : resolveMainPackageDependencyPatterns(ctx));
8345
- const sourceOutDir = hasSameDependencySet(allDependencies, mainDependencies) ? outDir : cachedSourceOutDir;
8346
- const localSubPackageMetas = [...ctx.scanService?.subPackageMap.values() ?? []].filter((meta) => Array.isArray(meta.subPackage.dependencies) && meta.subPackage.dependencies.length > 0);
8347
- const buildTargetDependencies = async (args) => {
8348
- const isDependenciesCacheOutdate = !await fs.pathExists(args.npmDistDir) || await cache.checkDependenciesCacheOutdate(args.cacheKey);
8349
- if (isDependenciesCacheOutdate) await fs.remove(args.npmDistDir);
8350
- if (args.dependencies.length === 0) {
8351
- await fs.remove(args.npmDistDir);
8352
- await cache.writeDependenciesCache(args.cacheKey);
8353
- return;
8354
- }
8355
- await Promise.all(args.dependencies.map((dep) => {
8356
- return builder.buildPackage({
8357
- dep,
8358
- outDir: args.npmDistDir,
8359
- options,
8360
- isDependenciesCacheOutdate
8361
- });
8362
- }));
8414
+ const allDependencies = await resolveBuildCandidateDependencies(pkgJson);
8415
+ const mainDependencies = resolveTargetDependencies(allDependencies, ctx.configService.pluginOnly ? resolvePluginPackageDependencyPatterns(ctx) : resolveMainPackageDependencyPatterns(ctx));
8416
+ const sourceOutDir = hasSameDependencySet(allDependencies, mainDependencies) ? outDir : cachedSourceOutDir;
8417
+ const localSubPackageMetas = [...ctx.scanService?.subPackageMap.values() ?? []].filter((meta) => Array.isArray(meta.subPackage.dependencies) && meta.subPackage.dependencies.length > 0);
8418
+ const buildTargetDependencies = async (args) => {
8419
+ const isDependenciesCacheOutdate = !await fs.pathExists(args.npmDistDir) || await cache.checkDependenciesCacheOutdate(args.cacheKey);
8420
+ if (isDependenciesCacheOutdate) await fs.remove(args.npmDistDir);
8421
+ if (args.dependencies.length === 0) {
8422
+ await fs.remove(args.npmDistDir);
8363
8423
  await cache.writeDependenciesCache(args.cacheKey);
8364
- };
8365
- if (sourceOutDir !== outDir) await buildTargetDependencies({
8366
- cacheKey: "__all__",
8367
- dependencies: allDependencies,
8368
- npmDistDir: sourceOutDir
8369
- });
8370
- await buildTargetDependencies({
8371
- cacheKey: ctx.configService.pluginOnly ? "__plugin__" : void 0,
8372
- dependencies: mainDependencies,
8373
- npmDistDir: outDir
8374
- });
8375
- if (mainDependencies.length === 0) await Promise.all(subRelations.map((relation) => {
8376
- return fs.remove(path.resolve(ctx.configService.cwd, relation.miniprogramNpmDistDir, npmDistDirName));
8424
+ return;
8425
+ }
8426
+ await Promise.all(args.dependencies.map((dep) => {
8427
+ return builder.buildPackage({
8428
+ dep,
8429
+ outDir: args.npmDistDir,
8430
+ options,
8431
+ isDependenciesCacheOutdate
8432
+ });
8377
8433
  }));
8378
- else await Promise.all(subRelations.map(async (relation) => {
8379
- const targetDir = path.resolve(ctx.configService.cwd, relation.miniprogramNpmDistDir, npmDistDirName);
8434
+ await cache.writeDependenciesCache(args.cacheKey);
8435
+ };
8436
+ if (sourceOutDir !== outDir) await buildTargetDependencies({
8437
+ cacheKey: "__all__",
8438
+ dependencies: allDependencies,
8439
+ npmDistDir: sourceOutDir
8440
+ });
8441
+ await buildTargetDependencies({
8442
+ cacheKey: ctx.configService.pluginOnly ? "__plugin__" : void 0,
8443
+ dependencies: mainDependencies,
8444
+ npmDistDir: outDir
8445
+ });
8446
+ if (mainDependencies.length === 0) await Promise.all(subRelations.map((relation) => {
8447
+ return fs.remove(path.resolve(ctx.configService.cwd, relation.miniprogramNpmDistDir, npmDistDirName));
8448
+ }));
8449
+ else await Promise.all(subRelations.map(async (relation) => {
8450
+ const targetDir = path.resolve(ctx.configService.cwd, relation.miniprogramNpmDistDir, npmDistDirName);
8451
+ await fs.remove(targetDir);
8452
+ await fs.copy(outDir, targetDir, { overwrite: true });
8453
+ }));
8454
+ for (const meta of localSubPackageMetas) {
8455
+ const targetDir = path.resolve(localSubPackageOutRoot, meta.subPackage.root, npmDistDirName);
8456
+ if (await cache.checkDependenciesCacheOutdate(meta.subPackage.root) || !await fs.pathExists(targetDir)) {
8380
8457
  await fs.remove(targetDir);
8381
- await fs.copy(outDir, targetDir, { overwrite: true });
8382
- }));
8383
- for (const meta of localSubPackageMetas) {
8384
- const targetDir = path.resolve(localSubPackageOutRoot, meta.subPackage.root, npmDistDirName);
8385
- if (await cache.checkDependenciesCacheOutdate(meta.subPackage.root) || !await fs.pathExists(targetDir)) {
8386
- await fs.remove(targetDir);
8387
- await fs.copy(sourceOutDir, targetDir, {
8388
- overwrite: true,
8389
- filter: (src) => {
8390
- if (Array.isArray(meta.subPackage.dependencies)) {
8391
- const relPath = resolveCopyFilterRelativePath(sourceOutDir, String(src));
8392
- if (relPath === "") return true;
8393
- return matchDependencyPath(meta.subPackage.dependencies, relPath);
8394
- }
8395
- return true;
8458
+ await fs.copy(sourceOutDir, targetDir, {
8459
+ overwrite: true,
8460
+ filter: (src) => {
8461
+ if (Array.isArray(meta.subPackage.dependencies)) {
8462
+ const relPath = resolveCopyFilterRelativePath(sourceOutDir, String(src));
8463
+ if (relPath === "") return true;
8464
+ return matchDependencyPath(meta.subPackage.dependencies, relPath);
8396
8465
  }
8397
- });
8398
- }
8399
- await cache.writeDependenciesCache(meta.subPackage.root);
8466
+ return true;
8467
+ }
8468
+ });
8400
8469
  }
8470
+ await cache.writeDependenciesCache(meta.subPackage.root);
8401
8471
  }
8402
8472
  }
8403
8473
  debug$2?.("buildNpm end");
@@ -8905,12 +8975,12 @@ function reserveUniqueFileName(reservedFileNames, fileName) {
8905
8975
  return candidate;
8906
8976
  }
8907
8977
  function rewriteChunkImportSpecifiersInCode(sourceCode, options) {
8908
- const { sourceFileName, sourceFileNames, targetFileName, imports, dynamicImports, runtimeFileName } = options;
8978
+ const { sourceFileName, sourceFileNames, targetFileName, imports, dynamicImports, runtimeFileName, resolveImportTarget } = options;
8909
8979
  const sourceFileNameCandidates = (sourceFileNames ?? [sourceFileName ?? ""]).filter(Boolean);
8910
8980
  const specifiers = new Set([...imports, ...dynamicImports].filter(Boolean));
8911
8981
  let rewrittenCode = sourceCode;
8912
8982
  for (const specifier of specifiers) {
8913
- const targetImportPath = createRelativeImportPath(targetFileName, posix.basename(specifier) === ROLLDOWN_RUNTIME_FILE_NAME$1 ? runtimeFileName : specifier);
8983
+ const targetImportPath = createRelativeImportPath(targetFileName, posix.basename(specifier) === ROLLDOWN_RUNTIME_FILE_NAME$1 ? runtimeFileName : resolveImportTarget?.(specifier) ?? specifier);
8914
8984
  if (!targetImportPath) continue;
8915
8985
  for (const sourceCandidate of sourceFileNameCandidates) {
8916
8986
  const sourceImportPath = createRelativeImportPath(sourceCandidate, specifier);
@@ -8945,6 +9015,80 @@ function applySharedChunkStrategy(bundle, options) {
8945
9015
  if (!this) throw new Error("applySharedChunkStrategy 需要 PluginContext。");
8946
9016
  const subPackageRoots = Array.from(options.subPackageRoots).filter(Boolean);
8947
9017
  const reservedFileNames = new Set(Object.keys(bundle));
9018
+ const localizedDuplicateFileMap = /* @__PURE__ */ new Map();
9019
+ const pendingLocalizedDuplicates = [];
9020
+ const emittedLocalizedDuplicateFiles = /* @__PURE__ */ new Set();
9021
+ const ensureLocalizedDuplicate = (root, sourceFileName) => {
9022
+ const sourceRoot = resolveSubPackagePrefix(sourceFileName, subPackageRoots);
9023
+ if (!sourceRoot || sourceRoot === root) return sourceFileName;
9024
+ const key = `${root}::${sourceFileName}`;
9025
+ const existing = localizedDuplicateFileMap.get(key);
9026
+ if (existing) return existing;
9027
+ const sourceOutput = bundle[sourceFileName];
9028
+ if (sourceOutput?.type !== "chunk") return sourceFileName;
9029
+ const duplicateBaseName = createCrossSubPackageDuplicateBaseName(sourceRoot, sourceFileName);
9030
+ const targetFileName = reserveUniqueFileName(reservedFileNames, posix.join(root, SUB_PACKAGE_SHARED_DIR, duplicateBaseName));
9031
+ localizedDuplicateFileMap.set(key, targetFileName);
9032
+ pendingLocalizedDuplicates.push({
9033
+ root,
9034
+ sourceFileName,
9035
+ targetFileName,
9036
+ chunk: sourceOutput
9037
+ });
9038
+ return targetFileName;
9039
+ };
9040
+ const rewriteDuplicatedChunkSource = (args) => {
9041
+ let rewrittenSource = rewriteChunkImportSpecifiersInCode(args.chunk.code ?? "", {
9042
+ sourceFileNames: createChunkSourceFileNameCandidates(args.sourceFileName),
9043
+ targetFileName: args.targetFileName,
9044
+ imports: args.chunk.imports,
9045
+ dynamicImports: args.chunk.dynamicImports,
9046
+ runtimeFileName: args.runtimeFileName,
9047
+ resolveImportTarget: (specifier) => {
9048
+ return ensureLocalizedDuplicate(args.root, specifier);
9049
+ }
9050
+ });
9051
+ for (const specifier of [...args.chunk.imports, ...args.chunk.dynamicImports]) {
9052
+ const localizedSpecifier = ensureLocalizedDuplicate(args.root, specifier);
9053
+ if (!localizedSpecifier || localizedSpecifier === specifier) continue;
9054
+ rewrittenSource = rewriteChunkImportSpecifiersInCode(rewrittenSource, {
9055
+ sourceFileName: args.targetFileName,
9056
+ targetFileName: args.targetFileName,
9057
+ imports: [specifier],
9058
+ dynamicImports: [],
9059
+ runtimeFileName: args.runtimeFileName,
9060
+ resolveImportTarget: () => localizedSpecifier
9061
+ });
9062
+ }
9063
+ return rewrittenSource;
9064
+ };
9065
+ const emitDuplicatedChunkAsset = (args) => {
9066
+ if (emittedLocalizedDuplicateFiles.has(args.targetFileName)) return;
9067
+ const runtimeFileName = posix.join(args.root, ROLLDOWN_RUNTIME_FILE_NAME);
9068
+ const duplicatedSource = rewriteDuplicatedChunkSource({
9069
+ root: args.root,
9070
+ sourceFileName: args.sourceFileName,
9071
+ targetFileName: args.targetFileName,
9072
+ chunk: args.chunk,
9073
+ runtimeFileName
9074
+ });
9075
+ this.emitFile({
9076
+ type: "asset",
9077
+ fileName: args.targetFileName,
9078
+ source: duplicatedSource
9079
+ });
9080
+ const sourceMapAssetInfo = findSourceMapAsset(bundle, collectSourceMapKeys(args.sourceFileName, args.chunk));
9081
+ const resolvedSourceMap = resolveSourceMapSource(args.chunk.map, sourceMapAssetInfo?.asset.source);
9082
+ if (resolvedSourceMap) {
9083
+ const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${args.targetFileName}.map`);
9084
+ this.emitFile({
9085
+ type: "asset",
9086
+ fileName: sourceMapFileName,
9087
+ source: cloneSourceLike(resolvedSourceMap)
9088
+ });
9089
+ }
9090
+ emittedLocalizedDuplicateFiles.add(args.targetFileName);
9091
+ };
8948
9092
  const entries = Object.entries(bundle);
8949
9093
  for (const [fileName, output] of entries) {
8950
9094
  if (!isSharedVirtualChunk(fileName, output)) continue;
@@ -9045,27 +9189,12 @@ function applySharedChunkStrategy(bundle, options) {
9045
9189
  });
9046
9190
  }
9047
9191
  for (const [root, { newFileName, importers: importerFiles }] of importerMap.entries()) {
9048
- const runtimeFileName = posix.join(root, ROLLDOWN_RUNTIME_FILE_NAME);
9049
- const duplicatedSource = rewriteChunkImportSpecifiersInCode(originalCode, {
9050
- sourceFileNames: createChunkSourceFileNameCandidates(fileName),
9192
+ emitDuplicatedChunkAsset({
9193
+ root,
9194
+ sourceFileName: fileName,
9051
9195
  targetFileName: newFileName,
9052
- imports: chunk.imports,
9053
- dynamicImports: chunk.dynamicImports,
9054
- runtimeFileName
9055
- });
9056
- this.emitFile({
9057
- type: "asset",
9058
- fileName: newFileName,
9059
- source: duplicatedSource
9196
+ chunk
9060
9197
  });
9061
- if (resolvedSourceMap) {
9062
- const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${newFileName}.map`);
9063
- this.emitFile({
9064
- type: "asset",
9065
- fileName: sourceMapFileName,
9066
- source: cloneSourceLike(resolvedSourceMap)
9067
- });
9068
- }
9069
9198
  for (const importerFile of importerFiles) importerToChunk.set(importerFile, newFileName);
9070
9199
  duplicates.push({
9071
9200
  fileName: newFileName,
@@ -9093,14 +9222,16 @@ function applySharedChunkStrategy(bundle, options) {
9093
9222
  localizeCrossSubPackageChunkLeaks.call(this, bundle, {
9094
9223
  subPackageRoots,
9095
9224
  reservedFileNames,
9225
+ localizedDuplicateFileMap,
9096
9226
  onDuplicate: options.onDuplicate
9097
9227
  });
9228
+ for (const task of pendingLocalizedDuplicates) emitDuplicatedChunkAsset(task);
9098
9229
  }
9099
9230
  function isSharedVirtualChunk(fileName, output) {
9100
9231
  return output?.type === "chunk" && fileName.startsWith(`weapp_shared_virtual/`);
9101
9232
  }
9102
9233
  function localizeCrossSubPackageChunkLeaks(bundle, options) {
9103
- const { subPackageRoots, reservedFileNames, onDuplicate } = options;
9234
+ const { subPackageRoots, reservedFileNames, localizedDuplicateFileMap, onDuplicate } = options;
9104
9235
  if (subPackageRoots.length === 0) return;
9105
9236
  const entries = Object.entries(bundle);
9106
9237
  for (const [fileName, output] of entries) {
@@ -9126,28 +9257,36 @@ function localizeCrossSubPackageChunkLeaks(bundle, options) {
9126
9257
  const importerToChunk = /* @__PURE__ */ new Map();
9127
9258
  const duplicates = [];
9128
9259
  for (const [targetRoot, importerFiles] of crossRootImporters.entries()) {
9129
- const duplicateBaseName = createCrossSubPackageDuplicateBaseName(sourceRoot, fileName);
9130
- const uniqueFileName = reserveUniqueFileName(reservedFileNames, posix.join(targetRoot, SUB_PACKAGE_SHARED_DIR, duplicateBaseName));
9260
+ const duplicateKey = `${targetRoot}::${fileName}`;
9261
+ const existingDuplicateFileName = localizedDuplicateFileMap.get(duplicateKey);
9262
+ const uniqueFileName = existingDuplicateFileName ?? (() => {
9263
+ const duplicateBaseName = createCrossSubPackageDuplicateBaseName(sourceRoot, fileName);
9264
+ const createdFileName = reserveUniqueFileName(reservedFileNames, posix.join(targetRoot, "weapp-shared", duplicateBaseName));
9265
+ localizedDuplicateFileMap.set(duplicateKey, createdFileName);
9266
+ return createdFileName;
9267
+ })();
9131
9268
  const runtimeFileName = posix.join(targetRoot, ROLLDOWN_RUNTIME_FILE_NAME);
9132
- const duplicatedSource = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
9133
- sourceFileName: fileName,
9134
- targetFileName: uniqueFileName,
9135
- imports: chunk.imports,
9136
- dynamicImports: chunk.dynamicImports,
9137
- runtimeFileName
9138
- });
9139
- this.emitFile({
9140
- type: "asset",
9141
- fileName: uniqueFileName,
9142
- source: duplicatedSource
9143
- });
9144
- if (resolvedSourceMap) {
9145
- const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
9269
+ if (!existingDuplicateFileName) {
9270
+ const duplicatedSource = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
9271
+ sourceFileName: fileName,
9272
+ targetFileName: uniqueFileName,
9273
+ imports: chunk.imports,
9274
+ dynamicImports: chunk.dynamicImports,
9275
+ runtimeFileName
9276
+ });
9146
9277
  this.emitFile({
9147
9278
  type: "asset",
9148
- fileName: sourceMapFileName,
9149
- source: cloneSourceLike(resolvedSourceMap)
9279
+ fileName: uniqueFileName,
9280
+ source: duplicatedSource
9150
9281
  });
9282
+ if (resolvedSourceMap) {
9283
+ const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
9284
+ this.emitFile({
9285
+ type: "asset",
9286
+ fileName: sourceMapFileName,
9287
+ source: cloneSourceLike(resolvedSourceMap)
9288
+ });
9289
+ }
9151
9290
  }
9152
9291
  for (const importerFile of importerFiles) importerToChunk.set(importerFile, uniqueFileName);
9153
9292
  duplicates.push({
@@ -9688,10 +9827,13 @@ function resolvePollingWatchConfig(configService) {
9688
9827
  const buildWatch = configService.inlineConfig?.build?.watch;
9689
9828
  const chokidar = buildWatch && typeof buildWatch === "object" && "chokidar" in buildWatch ? buildWatch.chokidar : void 0;
9690
9829
  const serverWatch = configService.inlineConfig?.server?.watch;
9830
+ const usePollingCandidate = chokidar?.usePolling ?? serverWatch?.usePolling;
9831
+ const intervalCandidate = chokidar?.interval ?? serverWatch?.interval;
9832
+ const binaryIntervalCandidate = chokidar?.binaryInterval ?? serverWatch?.binaryInterval;
9691
9833
  return {
9692
- usePolling: chokidar?.usePolling ?? serverWatch?.usePolling,
9693
- interval: chokidar?.interval ?? serverWatch?.interval,
9694
- binaryInterval: chokidar?.binaryInterval ?? serverWatch?.binaryInterval
9834
+ usePolling: typeof usePollingCandidate === "boolean" ? usePollingCandidate : void 0,
9835
+ interval: typeof intervalCandidate === "number" ? intervalCandidate : void 0,
9836
+ binaryInterval: typeof binaryIntervalCandidate === "number" ? binaryIntervalCandidate : void 0
9695
9837
  };
9696
9838
  }
9697
9839
  function createSidecarWatchOptions(configService, input) {
@@ -10140,6 +10282,7 @@ function getWeappViteConfig() {
10140
10282
  ],
10141
10283
  unhandledErrors: true
10142
10284
  },
10285
+ appPrelude: {},
10143
10286
  injectRequestGlobals: {},
10144
10287
  chunks: {
10145
10288
  sharedStrategy: "duplicate",
@@ -10885,6 +11028,7 @@ function createLoadConfig(options) {
10885
11028
  cwd,
10886
11029
  isDev,
10887
11030
  mode,
11031
+ emitDefaultAutoImportOutputs: opts.emitDefaultAutoImportOutputs ?? true,
10888
11032
  chunksConfigured,
10889
11033
  projectConfig,
10890
11034
  projectConfigPath: projectConfigPathResolved,
@@ -11151,7 +11295,7 @@ function createAutoImportPlugin(state) {
11151
11295
  if (fileWatcherStarted || !configService?.isDev || !globs?.length) return;
11152
11296
  const watchTargets = registerAutoImportWatchTargets(state, globs, void 0, { includeSrcRoot: false });
11153
11297
  if (!watchTargets?.size) return;
11154
- const watcher = chokidar.watch([...watchTargets], createSidecarWatchOptions(configService, {
11298
+ const watcher = chokidar.watch(Array.from(watchTargets, (target) => String(target)), createSidecarWatchOptions(configService, {
11155
11299
  ignoreInitial: true,
11156
11300
  persistent: true,
11157
11301
  awaitWriteFinish: {
@@ -12680,12 +12824,68 @@ const IDENTIFIER_CHAR_RE = /[\w$]/;
12680
12824
  function escapeRegExp(source) {
12681
12825
  return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12682
12826
  }
12827
+ function isInsideMustache(code, start, end) {
12828
+ const open = code.lastIndexOf("{{", start);
12829
+ if (open < 0) return false;
12830
+ return code.indexOf("}}", open + 2) >= end;
12831
+ }
12832
+ function getMustacheBounds(code, start, end) {
12833
+ const open = code.lastIndexOf("{{", start);
12834
+ if (open < 0) return null;
12835
+ const close = code.indexOf("}}", end);
12836
+ if (close < 0) return null;
12837
+ return {
12838
+ open,
12839
+ close
12840
+ };
12841
+ }
12842
+ function isWholeMustacheExpression(code, start, end, expression) {
12843
+ const bounds = getMustacheBounds(code, start, end);
12844
+ if (!bounds) return false;
12845
+ return code.slice(bounds.open + 2, bounds.close).trim() === expression;
12846
+ }
12847
+ function getMustacheOuterQuote(code, start) {
12848
+ const open = code.lastIndexOf("{{", start);
12849
+ if (open <= 0) return null;
12850
+ for (let index = open - 1; index >= 0; index--) {
12851
+ const char = code[index];
12852
+ if (char === "\"" || char === "'") return char;
12853
+ if (char === "<" || char === ">" || char === "\n" || char === "\r") break;
12854
+ }
12855
+ return null;
12856
+ }
12857
+ function toQuotedLiteral(value, quote, outerQuote = null) {
12858
+ try {
12859
+ const parsed = JSON.parse(value);
12860
+ let escaped = (typeof parsed === "string" ? parsed : JSON.stringify(parsed)).replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
12861
+ if (outerQuote === "\"") escaped = escaped.replace(/"/g, "&quot;");
12862
+ else if (outerQuote === "'") escaped = escaped.replace(/'/g, "&apos;");
12863
+ return quote === "'" ? `'${escaped.replace(/'/g, "\\'")}'` : `"${escaped.replace(/"/g, "\\\"")}"`;
12864
+ } catch {
12865
+ return value;
12866
+ }
12867
+ }
12868
+ function toMustacheReplacementValue(code, start, end, expression, value) {
12869
+ try {
12870
+ const parsed = JSON.parse(value);
12871
+ const outerQuote = getMustacheOuterQuote(code, start);
12872
+ if (typeof parsed === "string") return toQuotedLiteral(value, outerQuote === "'" ? "\"" : "'", outerQuote);
12873
+ if (isWholeMustacheExpression(code, start, end, expression)) {
12874
+ if (typeof parsed === "number") return Number.isFinite(parsed) ? String(parsed) : value;
12875
+ if (typeof parsed === "boolean") return parsed ? "true" : "false";
12876
+ if (parsed == null) return "null";
12877
+ }
12878
+ return String(value);
12879
+ } catch {
12880
+ return value;
12881
+ }
12882
+ }
12683
12883
  function replaceDefineImportMetaEnv(code, defineImportMetaEnv) {
12684
12884
  if (!defineImportMetaEnv || Object.keys(defineImportMetaEnv).length === 0) return code;
12685
12885
  const entries = Object.entries(defineImportMetaEnv).sort(([leftKey], [rightKey]) => rightKey.length - leftKey.length);
12686
12886
  const replacementRanges = [];
12687
12887
  for (const [key, value] of entries) {
12688
- if (!key.startsWith("import.meta")) continue;
12888
+ if (!(key === "import.meta.url" || key === "import.meta.dirname" || key.startsWith("import.meta.env.")) || key === "import.meta.env") continue;
12689
12889
  const pattern = new RegExp(escapeRegExp(key), "g");
12690
12890
  for (const match of code.matchAll(pattern)) {
12691
12891
  const start = match.index ?? -1;
@@ -12698,7 +12898,7 @@ function replaceDefineImportMetaEnv(code, defineImportMetaEnv) {
12698
12898
  replacementRanges.push({
12699
12899
  start,
12700
12900
  end,
12701
- value: String(value)
12901
+ value: isInsideMustache(code, start, end) ? toMustacheReplacementValue(code, start, end, key, String(value)) : String(value)
12702
12902
  });
12703
12903
  }
12704
12904
  }
@@ -13157,6 +13357,7 @@ async function resolveUsingComponentReference(ctx, configService, reExportResolu
13157
13357
  };
13158
13358
  }
13159
13359
  async function resolveUsingComponentPath(ctx, configService, reExportResolutionCache, importSource, importerFilename, info) {
13360
+ if (!info) return;
13160
13361
  return (await resolveUsingComponentReference(ctx, configService, reExportResolutionCache, importSource, importerFilename, info)).from;
13161
13362
  }
13162
13363
  function createUsingComponentPathResolver(ctx, configService, reExportResolutionCache) {
@@ -13209,6 +13410,7 @@ async function applyScriptSetupUsingComponents(options) {
13209
13410
  const usingComponents = json && typeof json.usingComponents === "object" && json.usingComponents && !Array.isArray(json.usingComponents) ? json.usingComponents : {};
13210
13411
  for (const { localName, importSource, importedName, kind } of imports) {
13211
13412
  let { from } = await resolveUsingComponentReference(pluginCtx, configService, reExportResolutionCache, importSource, vueEntryPath, {
13413
+ localName,
13212
13414
  kind,
13213
13415
  importedName,
13214
13416
  fallbackRelativeImporterDir: true
@@ -13917,7 +14119,8 @@ function resolveInjectRequestGlobalsOptions(config, packageJson) {
13917
14119
  if ((config && typeof config === "object" ? config.enabled : config) === true) return {
13918
14120
  mode: "explicit",
13919
14121
  targets: resolveTargets(config),
13920
- dependencyPatterns: resolveDependencyPatterns(config)
14122
+ dependencyPatterns: resolveDependencyPatterns(config),
14123
+ prelude: config && typeof config === "object" ? config.prelude === true : false
13921
14124
  };
13922
14125
  const autoRules = resolveAutoRules(config);
13923
14126
  const matchedTargets = /* @__PURE__ */ new Set();
@@ -13928,7 +14131,8 @@ function resolveInjectRequestGlobalsOptions(config, packageJson) {
13928
14131
  if (matchedTargets.size === 0) return null;
13929
14132
  return {
13930
14133
  mode: "auto",
13931
- targets: [...matchedTargets]
14134
+ targets: [...matchedTargets],
14135
+ prelude: config && typeof config === "object" ? config.prelude === true : false
13932
14136
  };
13933
14137
  }
13934
14138
  function resolveRequestGlobalsRuntimeModuleId() {
@@ -13939,6 +14143,15 @@ function resolveRequestGlobalsBindingTargets(targets) {
13939
14143
  if (targets.some((target) => target === "fetch" || target === "Request" || target === "Response" || target === "XMLHttpRequest")) bindingTargets.push("URL", "URLSearchParams", "Blob", "FormData");
13940
14144
  return [...new Set(bindingTargets)].filter((target) => REQUEST_GLOBAL_FREE_BINDING_TARGETS.has(target));
13941
14145
  }
14146
+ /**
14147
+ * @description 生成“被动局部绑定”代码。
14148
+ * @description 这层能力不能退化成只在 app.js 顶部安装全局对象。
14149
+ * @description 原因是 axios / graphql-request / socket.io-client 一类依赖经常会:
14150
+ * @description 1. 在模块初始化阶段直接读取自由变量;
14151
+ * @description 2. 在各自 chunk 作用域里执行 `typeof XMLHttpRequest` / `typeof fetch` / `new URL()`;
14152
+ * @description 3. 在全局对象完成安装前就完成环境探测并缓存结果。
14153
+ * @description 因此这里必须把 fetch / XMLHttpRequest / WebSocket / URL 等名字绑定到实际使用它们的产物作用域内。
14154
+ */
13942
14155
  function createRequestGlobalsPassiveBindingsCode(targets) {
13943
14156
  const bindingTargets = resolveRequestGlobalsBindingTargets(targets);
13944
14157
  if (bindingTargets.length === 0) return "";
@@ -14078,6 +14291,15 @@ const REQUEST_GLOBAL_ENTRY_NAME_RE = /\.[^/.]+$/;
14078
14291
  const REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE = /([A-Za-z_$][\w$]*)\s*=\s*require\((`([^`]+)`|'([^']+)'|"([^"]+)")\)/g;
14079
14292
  const DYNAMIC_GLOBAL_RESOLUTION_RE = /Function\(\s*(?:`return this`|'return this'|"return this")\s*\)\(\)/g;
14080
14293
  const BROWSER_GLOBAL_HOST_TERNARY_RE = /typeof self<[`'"]u[`'"]\?self:typeof window<[`'"]u[`'"]\?window:globalThis/g;
14294
+ const AXIOS_MODULE_ID_RE = /[/\\](?:\.pnpm[/\\][^/\\]+[/\\]node_modules[/\\])?axios[/\\]/u;
14295
+ const APP_PRELUDE_CHUNK_MARKER = "__weappViteAppPreludeRuntime__";
14296
+ const APP_PRELUDE_GUARD_KEY = "__weappViteAppPreludeInstalled__";
14297
+ const APP_PRELUDE_REQUIRE_MARKER = "__weappViteAppPreludeRequire__";
14298
+ const APP_PRELUDE_REQUIRE_FILE_BASENAME = "app.prelude.js";
14299
+ const REQUEST_GLOBAL_PRELUDE_MARKER = "__weappViteRequestGlobalsPrelude__";
14300
+ const REQUEST_GLOBAL_PRELUDE_GUARD_KEY = "__weappViteRequestGlobalsPreludeInstalled__";
14301
+ const DIRECTIVE_PROLOGUE_RE = /^(?:(['"])(?:\\.|(?!\1)[^\\])*\1;?\s*)+/u;
14302
+ const USE_STRICT_PREFIX_RE = /^(?:['"]use strict['"];\s*)+/u;
14081
14303
  function resolveInjectWeapiGlobalName(state) {
14082
14304
  const injectWeapi = state.ctx.configService.weappViteConfig?.injectWeapi;
14083
14305
  if (!injectWeapi) return null;
@@ -14232,7 +14454,9 @@ function resolveRequestGlobalsInstallerName(code) {
14232
14454
  const isInstallerFunctionNode = (node) => {
14233
14455
  if (!node) return false;
14234
14456
  const functionCode = generate(node).code;
14235
- return REQUEST_GLOBAL_TARGET_SIGNATURES.every((target) => functionCode.includes(target));
14457
+ return FULL_REQUEST_GLOBAL_TARGETS.every((target) => {
14458
+ return functionCode.includes(target);
14459
+ });
14236
14460
  };
14237
14461
  traverse(ast, {
14238
14462
  FunctionDeclaration(path) {
@@ -14327,7 +14551,7 @@ function injectRequestGlobalsPassiveBindings(bundle, installerChunks, targets, e
14327
14551
  if (chunk.code.includes("__weappViteRequestGlobalsPassiveBindings__") || chunk.code.includes("__weappViteRequestGlobalsLocalBindings__") || chunk.code.includes("__weappViteRequestGlobalsBundleInstalled__")) continue;
14328
14552
  const entryName = chunk.fileName.replace(REQUEST_GLOBAL_ENTRY_NAME_RE, "");
14329
14553
  const entryType = entriesMap?.get(entryName)?.type;
14330
- if (entryType === "page" || entryType === "component") continue;
14554
+ if (entryType === "page" || entryType === "component" || entryType === "app") continue;
14331
14555
  chunk.code = `/* __weappViteRequestGlobalsPassiveBindings__ */ ${passiveBindingsCode}\n${chunk.code}`;
14332
14556
  }
14333
14557
  }
@@ -14340,7 +14564,7 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, ent
14340
14564
  const chunk = output;
14341
14565
  const entryName = chunk.fileName.replace(REQUEST_GLOBAL_ENTRY_NAME_RE, "");
14342
14566
  const entryType = entriesMap?.get(entryName)?.type;
14343
- if (entryType !== "page" && entryType !== "component") continue;
14567
+ if (entryType !== "page" && entryType !== "component" && entryType !== "app") continue;
14344
14568
  if (chunk.code.includes("__weappViteRequestGlobalsLocalBindings__")) continue;
14345
14569
  let requireImportLiteral = null;
14346
14570
  let exportName;
@@ -14363,6 +14587,77 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, ent
14363
14587
  ].join(";")};\n${chunk.code}`;
14364
14588
  }
14365
14589
  }
14590
+ function resolveRequestGlobalsInstallerImport(chunk, installerChunks) {
14591
+ for (const requireMatch of chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
14592
+ const importee = requireMatch[3] ?? requireMatch[4] ?? requireMatch[5];
14593
+ if (!importee) continue;
14594
+ const installerChunkFileName = normalizeRelativeChunkImport(chunk.fileName, importee);
14595
+ const exportName = installerChunks.get(installerChunkFileName);
14596
+ if (!exportName) continue;
14597
+ return {
14598
+ exportName,
14599
+ requireImportLiteral: requireMatch[2] ?? null
14600
+ };
14601
+ }
14602
+ return null;
14603
+ }
14604
+ function createRequestGlobalsPreludeCode(chunk, installerChunks, targets) {
14605
+ if (targets.length === 0 || chunk.code.includes(REQUEST_GLOBAL_PRELUDE_MARKER)) return;
14606
+ const bindingTargets = resolveRequestGlobalsBindingTargets(targets);
14607
+ if (bindingTargets.length === 0) return;
14608
+ const installerName = resolveRequestGlobalsInstallerName(chunk.code);
14609
+ const exportName = resolveRequestGlobalsExportName(chunk.code);
14610
+ let installerHostCode;
14611
+ if (installerName && exportName) installerHostCode = `${installerName}({ targets: ${JSON.stringify(targets)} }) || globalThis`;
14612
+ else {
14613
+ const installerImport = resolveRequestGlobalsInstallerImport(chunk, installerChunks);
14614
+ if (!installerImport?.requireImportLiteral || !installerImport.exportName) return;
14615
+ installerHostCode = `require(${installerImport.requireImportLiteral})[${JSON.stringify(installerImport.exportName)}]({ targets: ${JSON.stringify(targets)} }) || globalThis`;
14616
+ }
14617
+ return [
14618
+ `/* ${REQUEST_GLOBAL_PRELUDE_MARKER} */`,
14619
+ `(() => {`,
14620
+ ` if (globalThis[${JSON.stringify(REQUEST_GLOBAL_PRELUDE_GUARD_KEY)}]) {`,
14621
+ ` return`,
14622
+ ` }`,
14623
+ ` globalThis[${JSON.stringify(REQUEST_GLOBAL_PRELUDE_GUARD_KEY)}] = true`,
14624
+ ` const __weappVitePreludeRequestGlobalsHost__ = ${installerHostCode}`,
14625
+ ` const __weappViteRequestGlobalsActuals__ = globalThis.__weappViteRequestGlobalsActuals__ || (globalThis.__weappViteRequestGlobalsActuals__ = Object.create(null))`,
14626
+ ...bindingTargets.map((target) => ` __weappViteRequestGlobalsActuals__[${JSON.stringify(target)}] = __weappVitePreludeRequestGlobalsHost__.${target}`),
14627
+ `})();`
14628
+ ].join("\n");
14629
+ }
14630
+ function injectAxiosFetchAdapterEnv(bundle) {
14631
+ const axiosEnvPatchCode = [
14632
+ "/* __weappViteAxiosFetchAdapterEnv__ */",
14633
+ "let __weappViteAxiosExport__ = null",
14634
+ "for (const __weappViteAxiosKey__ in exports) {",
14635
+ " const __weappViteAxiosCandidate__ = exports[__weappViteAxiosKey__]",
14636
+ " if (__weappViteAxiosCandidate__ && typeof __weappViteAxiosCandidate__ === \"function\" && __weappViteAxiosCandidate__.Axios && __weappViteAxiosCandidate__.defaults) {",
14637
+ " __weappViteAxiosExport__ = __weappViteAxiosCandidate__",
14638
+ " break",
14639
+ " }",
14640
+ "}",
14641
+ "if (__weappViteAxiosExport__) {",
14642
+ " __weappViteAxiosExport__.defaults.env = {",
14643
+ " ...(__weappViteAxiosExport__.defaults.env ?? {}),",
14644
+ " Request,",
14645
+ " Response,",
14646
+ " fetch,",
14647
+ " }",
14648
+ "}",
14649
+ ""
14650
+ ].join("\n");
14651
+ for (const output of Object.values(bundle)) {
14652
+ if (output?.type !== "chunk") continue;
14653
+ const chunk = output;
14654
+ if (chunk.code.includes("__weappViteAxiosFetchAdapterEnv__")) continue;
14655
+ const moduleIds = Array.isArray(chunk.moduleIds) ? chunk.moduleIds : [];
14656
+ const normalizedFileName = toPosixPath(chunk.fileName);
14657
+ if (!(moduleIds.some((id) => AXIOS_MODULE_ID_RE.test(id)) || normalizedFileName === "axios.js" || normalizedFileName.endsWith("/axios.js"))) continue;
14658
+ chunk.code = `${chunk.code}\n${axiosEnvPatchCode}`;
14659
+ }
14660
+ }
14366
14661
  function toRelativeRuntimeNpmImport(fileName, root, importee) {
14367
14662
  const normalized = normalizeWeappLocalNpmImport(importee);
14368
14663
  const target = root ? `${root}/miniprogram_npm/${normalized}` : `miniprogram_npm/${normalized}`;
@@ -14410,6 +14705,126 @@ function rewriteJsonNpmImportsToLocalRoot(bundle, root, dependencyPatterns, depe
14410
14705
  } catch {}
14411
14706
  }
14412
14707
  }
14708
+ function prependChunkCodePreservingDirectives(code, injectedCode) {
14709
+ const directiveMatch = code.match(DIRECTIVE_PROLOGUE_RE);
14710
+ if (!directiveMatch?.[0]) return `${injectedCode}\n${code}`;
14711
+ const directivePrologue = directiveMatch[0];
14712
+ return `${directivePrologue}${injectedCode}\n${code.slice(directivePrologue.length)}`;
14713
+ }
14714
+ function resolveAppPreludeOptions(state) {
14715
+ const option = state.ctx.configService.weappViteConfig?.appPrelude;
14716
+ if (option === false) return {
14717
+ enabled: false,
14718
+ mode: "inline"
14719
+ };
14720
+ if (option === true || option == null) return {
14721
+ enabled: true,
14722
+ mode: "inline"
14723
+ };
14724
+ return {
14725
+ enabled: option.enabled !== false,
14726
+ mode: option.mode ?? "inline"
14727
+ };
14728
+ }
14729
+ function collectAppPreludeEntryChunkFileNames(state) {
14730
+ const entryChunkFileNames = /* @__PURE__ */ new Set();
14731
+ for (const entry of state.entriesMap.values()) {
14732
+ if (!entry || entry.type !== "app" && entry.type !== "page" && entry.type !== "component") continue;
14733
+ const relative = state.ctx.configService.relativeAbsoluteSrcRoot(entry.path);
14734
+ entryChunkFileNames.add(changeFileExtension(relative, ".js"));
14735
+ }
14736
+ return entryChunkFileNames;
14737
+ }
14738
+ async function resolveAppPreludeCode(preludePath) {
14739
+ if (!preludePath) return;
14740
+ const source = await readFile(preludePath, "utf8");
14741
+ if (!source.trim()) return;
14742
+ const ast = parseJsLike(source);
14743
+ let hasModuleSyntax = false;
14744
+ traverse(ast, {
14745
+ ImportDeclaration() {
14746
+ hasModuleSyntax = true;
14747
+ },
14748
+ ExportAllDeclaration() {
14749
+ hasModuleSyntax = true;
14750
+ },
14751
+ ExportDefaultDeclaration() {
14752
+ hasModuleSyntax = true;
14753
+ },
14754
+ ExportNamedDeclaration() {
14755
+ hasModuleSyntax = true;
14756
+ }
14757
+ });
14758
+ if (hasModuleSyntax) throw new Error("[app.prelude] 当前仅支持无 import/export 的自包含脚本。");
14759
+ const extension = path.extname(preludePath).toLowerCase();
14760
+ const normalizedCode = (await transformWithOxc(source, preludePath, {
14761
+ charset: "utf8",
14762
+ format: "cjs",
14763
+ loader: extension === ".ts" || extension === ".mts" || extension === ".cts" ? "ts" : extension === ".jsx" ? "jsx" : extension === ".tsx" ? "tsx" : "js",
14764
+ minify: false,
14765
+ sourcemap: false,
14766
+ target: "es2020",
14767
+ treeShaking: false
14768
+ })).code.replace(USE_STRICT_PREFIX_RE, "").trim();
14769
+ if (!normalizedCode) return;
14770
+ return [
14771
+ `/* ${APP_PRELUDE_CHUNK_MARKER} */`,
14772
+ `(() => {`,
14773
+ ` if (globalThis[${JSON.stringify(APP_PRELUDE_GUARD_KEY)}]) {`,
14774
+ ` return`,
14775
+ ` }`,
14776
+ ` globalThis[${JSON.stringify(APP_PRELUDE_GUARD_KEY)}] = true`,
14777
+ normalizedCode,
14778
+ `})();`
14779
+ ].join("\n");
14780
+ }
14781
+ function resolveAppPreludeRequireFileName(fileName, state) {
14782
+ const matchedIndependentRoot = state.subPackageMeta?.subPackage.root;
14783
+ if (matchedIndependentRoot) return `${matchedIndependentRoot}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`;
14784
+ const matchedRoot = [...state.ctx.scanService.subPackageMap?.keys() ?? []].filter(Boolean).sort((left, right) => right.length - left.length).find((root) => fileName === root || fileName.startsWith(`${root}/`));
14785
+ if (!matchedRoot) return APP_PRELUDE_REQUIRE_FILE_BASENAME;
14786
+ return `${matchedRoot}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`;
14787
+ }
14788
+ function createAppPreludeRequireStatement(chunkFileName, preludeFileName) {
14789
+ const relativePath = toPosixPath(path.relative(path.dirname(chunkFileName), preludeFileName));
14790
+ const requestPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
14791
+ return `/* ${APP_PRELUDE_REQUIRE_MARKER} */require(${JSON.stringify(requestPath)})`;
14792
+ }
14793
+ function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, emitFile) {
14794
+ if (!appPreludeCode) return;
14795
+ const preludeFileNames = /* @__PURE__ */ new Set();
14796
+ if (state.subPackageMeta?.subPackage.root) preludeFileNames.add(`${state.subPackageMeta.subPackage.root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
14797
+ else {
14798
+ preludeFileNames.add(APP_PRELUDE_REQUIRE_FILE_BASENAME);
14799
+ for (const root of state.ctx.scanService.subPackageMap.keys()) {
14800
+ if (!root) continue;
14801
+ preludeFileNames.add(`${root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
14802
+ }
14803
+ }
14804
+ for (const fileName of preludeFileNames) {
14805
+ if (bundle[fileName]) continue;
14806
+ emitFile?.({
14807
+ type: "asset",
14808
+ fileName,
14809
+ source: `${appPreludeCode}\n`
14810
+ });
14811
+ }
14812
+ }
14813
+ function injectAppPreludeCode(bundle, appPreludeCode, options, state, requestGlobalsPreludeOptions, emitFile) {
14814
+ if (!options.enabled) return;
14815
+ const entryChunkFileNames = options.mode === "entry" ? collectAppPreludeEntryChunkFileNames(state) : void 0;
14816
+ if (options.mode === "require" && appPreludeCode) emitAppPreludeRequireAssets(bundle, appPreludeCode, state, emitFile);
14817
+ for (const output of Object.values(bundle)) {
14818
+ if (output?.type !== "chunk") continue;
14819
+ const chunk = output;
14820
+ if (chunk.code.includes(APP_PRELUDE_CHUNK_MARKER) || chunk.code.includes(APP_PRELUDE_REQUIRE_MARKER)) continue;
14821
+ const isTargetEntryChunk = chunk.isEntry === true || entryChunkFileNames?.has(chunk.fileName) === true;
14822
+ if (entryChunkFileNames && !isTargetEntryChunk) continue;
14823
+ const injectedCode = [requestGlobalsPreludeOptions.enabled ? createRequestGlobalsPreludeCode(chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets) : void 0, options.mode === "require" ? appPreludeCode ? createAppPreludeRequireStatement(chunk.fileName, resolveAppPreludeRequireFileName(chunk.fileName, state)) : void 0 : appPreludeCode].filter(Boolean).join("\n");
14824
+ if (!injectedCode) continue;
14825
+ chunk.code = prependChunkCodePreservingDirectives(chunk.code, injectedCode);
14826
+ }
14827
+ }
14413
14828
  function createRenderStartHook(state) {
14414
14829
  const { ctx, subPackageMeta, buildTarget } = state;
14415
14830
  return function renderStart() {
@@ -14435,6 +14850,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
14435
14850
  const { scanService, configService } = ctx;
14436
14851
  const astEngine = resolveAstEngine(configService.weappViteConfig);
14437
14852
  const injectRequestGlobalsOptions = resolveInjectRequestGlobalsOptions(configService.weappViteConfig?.injectRequestGlobals, configService.packageJson);
14853
+ const npmBuildCandidateDependencies = resolveNpmBuildCandidateDependencyRecordSync(ctx, configService.packageJson);
14438
14854
  return async function generateBundle(_options, bundle) {
14439
14855
  const rolldownBundle = bundle;
14440
14856
  await flushIndependentBuilds.call(this, state);
@@ -14443,9 +14859,9 @@ function createGenerateBundleHook(state, isPluginBuild) {
14443
14859
  if (!shouldRewriteBundleNpmImports(configService.platform)) {
14444
14860
  for (const output of Object.values(rolldownBundle)) {
14445
14861
  if (output?.type !== "chunk") continue;
14446
- rewriteChunkNpmImportsToLocalRoot(output, "", void 0, configService.packageJson.dependencies, { astEngine });
14862
+ rewriteChunkNpmImportsToLocalRoot(output, "", void 0, npmBuildCandidateDependencies, { astEngine });
14447
14863
  }
14448
- rewriteJsonNpmImportsToLocalRoot(rolldownBundle, "", void 0, configService.packageJson.dependencies);
14864
+ rewriteJsonNpmImportsToLocalRoot(rolldownBundle, "", void 0, npmBuildCandidateDependencies);
14449
14865
  }
14450
14866
  return;
14451
14867
  }
@@ -14550,7 +14966,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
14550
14966
  configService,
14551
14967
  entriesMap: state.entriesMap
14552
14968
  });
14553
- if (shouldRewriteBundleNpmImports(configService.platform)) rewriteBundleNpmImportsByPlatform(configService.platform, rolldownBundle, configService.packageJson.dependencies, configService.weappViteConfig?.npm?.alipayNpmMode, { astEngine });
14969
+ if (shouldRewriteBundleNpmImports(configService.platform)) rewriteBundleNpmImportsByPlatform(configService.platform, rolldownBundle, npmBuildCandidateDependencies, configService.weappViteConfig?.npm?.alipayNpmMode, { astEngine });
14554
14970
  else {
14555
14971
  const localSubPackageMetas = [...(scanService.subPackageMap ?? /* @__PURE__ */ new Map()).values()].filter((meta) => Array.isArray(meta?.subPackage?.dependencies) && meta.subPackage.dependencies.length > 0);
14556
14972
  for (const meta of localSubPackageMetas) {
@@ -14558,19 +14974,29 @@ function createGenerateBundleHook(state, isPluginBuild) {
14558
14974
  if (output?.type !== "chunk") continue;
14559
14975
  const chunk = output;
14560
14976
  if (chunk.fileName === meta.subPackage.root || !chunk.fileName.startsWith(`${meta.subPackage.root}/`)) continue;
14561
- rewriteChunkNpmImportsToLocalRoot(chunk, meta.subPackage.root, meta.subPackage.dependencies, configService.packageJson.dependencies, { astEngine });
14977
+ rewriteChunkNpmImportsToLocalRoot(chunk, meta.subPackage.root, meta.subPackage.dependencies, npmBuildCandidateDependencies, { astEngine });
14562
14978
  }
14563
- rewriteJsonNpmImportsToLocalRoot(rolldownBundle, meta.subPackage.root, meta.subPackage.dependencies, configService.packageJson.dependencies);
14979
+ rewriteJsonNpmImportsToLocalRoot(rolldownBundle, meta.subPackage.root, meta.subPackage.dependencies, npmBuildCandidateDependencies);
14564
14980
  }
14565
14981
  }
14566
14982
  const injectWeapiGlobalName = resolveInjectWeapiGlobalName(state);
14567
14983
  if (injectWeapiGlobalName) rewriteBundlePlatformApi(rolldownBundle, injectWeapiGlobalName, { astEngine });
14568
14984
  rewriteBundleDynamicGlobalResolution(rolldownBundle);
14985
+ const installerChunks = injectRequestGlobalsOptions?.targets?.length ? injectRequestGlobalsBundleRuntime(rolldownBundle, injectRequestGlobalsOptions.targets) : /* @__PURE__ */ new Map();
14569
14986
  if (injectRequestGlobalsOptions?.targets?.length) {
14570
- const installerChunks = injectRequestGlobalsBundleRuntime(rolldownBundle, injectRequestGlobalsOptions.targets);
14571
14987
  injectRequestGlobalsPassiveBindings(rolldownBundle, installerChunks, injectRequestGlobalsOptions.targets, state.entriesMap);
14572
14988
  injectRequestGlobalsLocalBindings(rolldownBundle, installerChunks, injectRequestGlobalsOptions.targets, state.entriesMap);
14573
- }
14989
+ injectAxiosFetchAdapterEnv(rolldownBundle);
14990
+ }
14991
+ const appPreludeOptions = resolveAppPreludeOptions(state);
14992
+ injectAppPreludeCode(rolldownBundle, await resolveAppPreludeCode(scanService.appEntry?.preludePath), {
14993
+ ...appPreludeOptions,
14994
+ enabled: appPreludeOptions.enabled || injectRequestGlobalsOptions?.prelude === true
14995
+ }, state, {
14996
+ enabled: injectRequestGlobalsOptions?.prelude === true,
14997
+ installerChunks,
14998
+ targets: injectRequestGlobalsOptions?.targets ?? []
14999
+ }, (asset) => this.emitFile(asset));
14574
15000
  refreshModuleGraph(this, state);
14575
15001
  if (configService.weappViteConfig?.debug?.watchFiles) {
14576
15002
  const watcherService = ctx.watcherService;
@@ -14873,10 +15299,10 @@ function createLoadHook(state) {
14873
15299
  const requestGlobalsTargets = resolveRequestGlobalsTargets();
14874
15300
  const passiveRequestGlobalsTargets = result && typeof result === "object" && "code" in result ? resolvePassiveRequestGlobalsTargets(result.code) : [];
14875
15301
  if (requestGlobalsTargets.length === 0 && passiveRequestGlobalsTargets.length > 0) return injectRequestGlobalsIntoLoadResult(result, sourceId, passiveRequestGlobalsTargets, { passiveLocalBindings: true });
14876
- if (!injectOptions || configService.weappLibConfig?.enabled) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets);
14877
- if (!await ensureWeapiAvailable(this, sourceId)) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets);
15302
+ if (!injectOptions || configService.weappLibConfig?.enabled) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, { localBindings: true });
15303
+ if (!await ensureWeapiAvailable(this, sourceId)) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, { localBindings: true });
14878
15304
  if (result && typeof result === "object" && "code" in result) {
14879
- const requestGlobalsInjectedResult = injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets);
15305
+ const requestGlobalsInjectedResult = injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, { localBindings: true });
14880
15306
  const platform = getMiniProgramPlatformGlobalKey(configService.platform) ?? "";
14881
15307
  const injectedCode = createWeapiInjectionCode({
14882
15308
  globalName: injectOptions.globalName,
@@ -29096,7 +29522,9 @@ function replaceImportMetaAccessInSfc(source, options) {
29096
29522
  ignoreEmpty: false
29097
29523
  });
29098
29524
  if (errors.length > 0) return source;
29099
- const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => block && !block.src);
29525
+ const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => {
29526
+ return Boolean(block && !block.src);
29527
+ });
29100
29528
  if (blocks.length === 0) return source;
29101
29529
  const ms = new MagicString(source);
29102
29530
  let mutated = false;
@@ -30656,6 +31084,7 @@ function createCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, con
30656
31084
  const scopedSlotsCompiler = configService.weappViteConfig?.vue?.template?.scopedSlotsCompiler ?? "auto";
30657
31085
  const scopedSlotsRequireProps = configService.weappViteConfig?.vue?.template?.scopedSlotsRequireProps ?? scopedSlotsCompiler !== "augmented";
30658
31086
  const slotMultipleInstance = configService.weappViteConfig?.vue?.template?.slotMultipleInstance ?? true;
31087
+ const htmlTagToWxml = configService.weappViteConfig?.vue?.template?.htmlTagToWxml;
30659
31088
  const classStyleRuntimeConfig = configService.weappViteConfig?.vue?.template?.classStyleRuntime ?? "js";
30660
31089
  const objectLiteralBindMode = configService.weappViteConfig?.vue?.template?.objectLiteralBindMode ?? "runtime";
30661
31090
  const mustacheInterpolation = configService.weappViteConfig?.vue?.template?.mustacheInterpolation ?? "compact";
@@ -30693,6 +31122,7 @@ function createCompileVueFileOptions(ctx, pluginCtx, vuePath, isPage, isApp, con
30693
31122
  },
30694
31123
  template: {
30695
31124
  platform: templatePlatformOptions.templatePlatform,
31125
+ htmlTagToWxml,
30696
31126
  scopedSlotsCompiler,
30697
31127
  scopedSlotsRequireProps,
30698
31128
  slotMultipleInstance,
@@ -31421,7 +31851,11 @@ function scanWxml(wxml, options) {
31421
31851
  const LEADING_DOT_SLASH_RE$1 = /^\.\//;
31422
31852
  function resolveVueBundlePlatformOptions(options) {
31423
31853
  return {
31424
- normalizeUsingComponents: resolveVueTransformJsonPlatformOptions({ platform: options.platform }).normalizeUsingComponents,
31854
+ normalizeUsingComponents: resolveVueTransformJsonPlatformOptions({
31855
+ platform: options.platform,
31856
+ weappViteConfig: {},
31857
+ packageJson: {}
31858
+ }).normalizeUsingComponents,
31425
31859
  normalizeTemplate: shouldNormalizeVueTemplateForPlatform(options.platform),
31426
31860
  emitGenericPlaceholder: shouldEmitGenericPlaceholderAsset(options.platform),
31427
31861
  scriptModuleTag: resolveScriptModuleTagByPlatform(options.platform, options.scriptModuleExtension)
@@ -32739,7 +33173,9 @@ function createVueTransformPlugin(ctx) {
32739
33173
  ctx,
32740
33174
  configService: ctx.configService,
32741
33175
  scanService: ctx.scanService,
32742
- collectFallbackPageEntryIds,
33176
+ collectFallbackPageEntryIds: async (configService, scanService) => {
33177
+ return Array.from(await collectFallbackPageEntryIds(configService, scanService));
33178
+ },
32743
33179
  findFirstResolvedVueLikeEntry,
32744
33180
  pathExists: fs.pathExists,
32745
33181
  readFile: fs.readFile
@@ -32754,9 +33190,11 @@ function createVueTransformPlugin(ctx) {
32754
33190
  pluginCtx: this,
32755
33191
  configService: ctx.configService,
32756
33192
  styleBlocksCache,
32757
- loadScopedSlotModule,
33193
+ loadScopedSlotModule: (id) => {
33194
+ return loadScopedSlotModule(id, scopedSlotModules)?.code ?? null;
33195
+ },
32758
33196
  scopedSlotModules,
32759
- parseWeappVueStyleRequest,
33197
+ parseWeappVueStyleRequest: (id) => parseWeappVueStyleRequest(id) ?? null,
32760
33198
  readAndParseSfc,
32761
33199
  createReadAndParseSfcOptions
32762
33200
  });
@@ -32938,7 +33376,7 @@ async function transformWxsFile(state, wxsPath) {
32938
33376
  }));
32939
33377
  }
32940
33378
  if (code === void 0) return;
32941
- const outputFileName = resolveRelativeOutputFileNameWithExtension(configService, isRaw ? wxsPath : removeExtension(wxsPath), scriptModuleExtension);
33379
+ const outputFileName = resolveRelativeOutputFileNameWithExtension(configService, isRaw ? wxsPath : removeExtension(wxsPath), scriptModuleExtension ?? "wxs");
32942
33380
  state.wxsMap.set(wxsPath, { emittedFile: {
32943
33381
  type: "asset",
32944
33382
  fileName: outputFileName,
@@ -33087,6 +33525,13 @@ function arrangePlugins(config, ctx, subPackageMeta) {
33087
33525
  //#endregion
33088
33526
  //#region src/runtime/config/internal/merge/miniprogram.ts
33089
33527
  const PACKAGE_NAME_REGEX = /[-/\\^$*+?.()|[\]{}]/g;
33528
+ const PATH_SEPARATOR_SPLIT_REGEX = /[/\\]+/;
33529
+ function escapeRegex(value) {
33530
+ return value.replace(PACKAGE_NAME_REGEX, "\\$&");
33531
+ }
33532
+ function createAbsolutePathPattern(value) {
33533
+ return value.split(PATH_SEPARATOR_SPLIT_REGEX).map((segment) => escapeRegex(segment)).join("[/\\\\]+");
33534
+ }
33090
33535
  function resolveMiniprogramWatchInclude(options) {
33091
33536
  const watchInclude = [path.join(options.cwd, options.srcRoot, "**")];
33092
33537
  if (!options.pluginRoot) return watchInclude;
@@ -33103,9 +33548,17 @@ function mergeMiniprogram(options, ...configs) {
33103
33548
  return createLogger("warn");
33104
33549
  };
33105
33550
  const external = [];
33106
- if (packageJson?.dependencies) external.push(...Object.keys(packageJson.dependencies).map((pkg) => {
33107
- return new RegExp(`^${pkg.replace(PACKAGE_NAME_REGEX, "\\$&")}(\\/|$)`);
33108
- }));
33551
+ const npmBuildCandidates = packageJson ? resolveNpmBuildCandidateDependenciesSync(ctx, packageJson) : [];
33552
+ if (npmBuildCandidates.length > 0) {
33553
+ const builtinAliases = resolveBuiltinPackageAliases();
33554
+ external.push(...npmBuildCandidates.map((pkg) => {
33555
+ return new RegExp(`^${escapeRegex(pkg)}(\\/|$)`);
33556
+ }), ...builtinAliases.filter(({ find }) => {
33557
+ return npmBuildCandidates.some((dep) => find === dep || find.startsWith(`${dep}/`));
33558
+ }).map(({ replacement }) => {
33559
+ return new RegExp(`^${createAbsolutePathPattern(replacement)}(?:\\?.*)?$`);
33560
+ }));
33561
+ }
33109
33562
  const rolldownOptions = {
33110
33563
  external,
33111
33564
  plugins: oxcRolldownPlugin ? [oxcRolldownPlugin] : void 0
@@ -34182,6 +34635,16 @@ function resolveSubPackageEntries(subPackage) {
34182
34635
  function resolveScanAppBasename(absoluteSrcRoot) {
34183
34636
  return path.resolve(absoluteSrcRoot, "app");
34184
34637
  }
34638
+ function resolveScanAppPreludeBasename(absoluteSrcRoot) {
34639
+ return path.resolve(absoluteSrcRoot, "app.prelude");
34640
+ }
34641
+ async function resolveScanAppPreludePath(absoluteSrcRoot) {
34642
+ const basename = resolveScanAppPreludeBasename(absoluteSrcRoot);
34643
+ for (const extension of jsExtensions) {
34644
+ const candidate = `${basename}.${extension}`;
34645
+ if (await fs.pathExists(candidate)) return candidate;
34646
+ }
34647
+ }
34185
34648
  function resolveScanPluginBasename(absolutePluginRoot) {
34186
34649
  return absolutePluginRoot ? path.resolve(absolutePluginRoot, "plugin") : void 0;
34187
34650
  }
@@ -34251,12 +34714,15 @@ function createScanService(ctx) {
34251
34714
  ctx.runtimeState.autoRoutes.loadingAppConfig = false;
34252
34715
  }
34253
34716
  const routes = autoRoutesService.getReference();
34254
- config.pages = mergeAutoRoutePages(config.pages, routes.pages);
34717
+ config.pages = mergeAutoRoutePages(config.pages, routes.pages) ?? [];
34255
34718
  const mergedSubPackages = mergeAutoRouteSubPackages(config.subPackages ?? config.subpackages, routes.subPackages.map((subPackage) => ({
34256
34719
  root: subPackage.root,
34257
34720
  pages: [...subPackage.pages]
34258
34721
  })));
34259
- if (mergedSubPackages) config.subPackages = mergedSubPackages;
34722
+ if (mergedSubPackages) config.subPackages = mergedSubPackages.map((subPackage) => ({
34723
+ ...subPackage,
34724
+ pages: Array.isArray(subPackage.pages) ? subPackage.pages : []
34725
+ }));
34260
34726
  return config;
34261
34727
  }
34262
34728
  async function loadAppEntry() {
@@ -34267,10 +34733,11 @@ function createScanService(ctx) {
34267
34733
  let { path: appConfigFile } = await findJsonEntry(appBasename);
34268
34734
  const discoveredAppConfigFile = appConfigFile;
34269
34735
  const { path: appEntryPath } = await findJsEntry(appBasename);
34736
+ const appPreludePath = await resolveScanAppPreludePath(appDirname);
34270
34737
  const vueAppPath = await findVueEntry(appBasename);
34271
34738
  let configFromVue;
34272
34739
  if (!appConfigFile && vueAppPath) {
34273
- const { extractConfigFromVue } = await import("./file-nOZc956t.mjs");
34740
+ const { extractConfigFromVue } = await import("./file-BKp0PdYt.mjs");
34274
34741
  configFromVue = await extractConfigFromVue(vueAppPath);
34275
34742
  if (configFromVue) appConfigFile = vueAppPath;
34276
34743
  }
@@ -34294,6 +34761,7 @@ function createScanService(ctx) {
34294
34761
  if (isObject(config)) {
34295
34762
  const resolvedAppEntry = {
34296
34763
  path: appEntryPath || vueAppPath,
34764
+ preludePath: appPreludePath,
34297
34765
  json: config,
34298
34766
  jsonPath: appConfigFile,
34299
34767
  type: "app"
@@ -35145,6 +35613,7 @@ async function collectAutoImportTemplateTags(ctx) {
35145
35613
  }));
35146
35614
  }
35147
35615
  async function syncProjectSupportFiles(ctx) {
35616
+ const configService = requireConfigService(ctx, "同步 support files 前必须初始化 configService。");
35148
35617
  const managedTsconfigChanged = await hasManagedTsconfigChanges(ctx);
35149
35618
  await syncManagedTsconfigFiles(ctx);
35150
35619
  if (ctx.autoRoutesService?.isEnabled()) await ctx.autoRoutesService.ensureFresh();
@@ -35155,8 +35624,11 @@ async function syncProjectSupportFiles(ctx) {
35155
35624
  const globs = autoImportConfig.globs;
35156
35625
  if (Array.isArray(globs) && globs.length > 0) {
35157
35626
  const files = await findAutoImportCandidates({
35158
- ctx,
35159
- resolvedConfig: { build: { outDir: ctx.configService.outDir } }
35627
+ ctx: {
35628
+ ...ctx,
35629
+ configService
35630
+ },
35631
+ resolvedConfig: { build: { outDir: configService.outDir } }
35160
35632
  }, globs);
35161
35633
  await Promise.all(files.map((file) => ctx.autoImportService.registerPotentialComponent(file)));
35162
35634
  } else if (!shouldBootstrapAutoImportWithoutGlobs(autoImportConfig)) {}