weapp-vite 6.12.4 → 6.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/client.d.ts +2 -0
- package/dist/auto-import-components/resolvers.d.mts +1 -1
- package/dist/auto-routes.d.mts +1 -1
- package/dist/auto-routes.mjs +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/{config-DKt372Bv.d.mts → config-WBWY_UlE.d.mts} +13 -3
- package/dist/config.d.mts +1 -1
- package/dist/{createContext-D0UJheyD.mjs → createContext-CwnO-Jw3.mjs} +612 -102
- package/dist/docs/README.md +3 -0
- package/dist/{file-Bf2vfymR.mjs → file-WyRp0uK0.mjs} +35 -6
- package/dist/index.d.mts +2 -3
- package/dist/index.mjs +2 -3
- package/dist/json.d.mts +1 -1
- package/dist/mcp.d.mts +1 -1
- package/dist/runtime-CpQutkhu.d.mts +39 -0
- package/dist/runtime-gyZnAGCZ.mjs +53 -0
- package/dist/runtime.d.mts +1 -30
- package/dist/runtime.mjs +1 -31
- package/dist/types.d.mts +4 -4
- package/dist/web-apis.d.mts +1 -0
- package/dist/web-apis.mjs +2 -0
- package/package.json +13 -8
- /package/dist/{index-BQqQ_BLM.d.mts → index-B5wBsuYI.d.mts} +0 -0
- /package/dist/{routes-DUBjYF43.d.mts → routes-o20IHwXa.d.mts} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-twds-ZHy.mjs";
|
|
2
2
|
import { n as applyWeappViteHostMeta } from "./pluginHost-SJdl15d3.mjs";
|
|
3
3
|
import { n as configureLogger, r as logger_default } from "./logger-gutcwWKE.mjs";
|
|
4
|
-
import { _ as templateExtensions, a as findJsEntry, c as findVueEntry, d as isTemplate, f as touch, g as supportedCssLangs, h as jsExtensions, i as findCssEntry, l as inlineAutoRoutesImports, m as configExtensions, n as extractConfigFromVue, o as findJsonEntry, s as findTemplateEntry, t as changeFileExtension, u as isJsOrTs, v as vueExtensions } from "./file-
|
|
4
|
+
import { _ as templateExtensions, a as findJsEntry, c as findVueEntry, d as isTemplate, f as touch, g as supportedCssLangs, h as jsExtensions, i as findCssEntry, l as inlineAutoRoutesImports, m as configExtensions, n as extractConfigFromVue, o as findJsonEntry, s as findTemplateEntry, t as changeFileExtension, u as isJsOrTs, v as vueExtensions } from "./file-WyRp0uK0.mjs";
|
|
5
5
|
import { createRequire, isBuiltin } from "node:module";
|
|
6
6
|
import { addExtension, defu, get, isEmptyObject, isObject, objectHash, removeExtension, removeExtensionDeep, set } from "@weapp-core/shared";
|
|
7
7
|
import { LRUCache } from "lru-cache";
|
|
@@ -334,7 +334,7 @@ function getVueComponentsSettings(ctx) {
|
|
|
334
334
|
return { enabled: false };
|
|
335
335
|
}
|
|
336
336
|
//#endregion
|
|
337
|
-
//#region src/ast/
|
|
337
|
+
//#region src/ast/index.ts
|
|
338
338
|
/**
|
|
339
339
|
* 解析 AST 引擎配置。
|
|
340
340
|
*/
|
|
@@ -8195,6 +8195,13 @@ function normalizeSharedPathCandidate(absoluteId) {
|
|
|
8195
8195
|
stripLeadingNullByte: true
|
|
8196
8196
|
});
|
|
8197
8197
|
}
|
|
8198
|
+
function resolveNodeModulesSharedPath(cleanedAbsoluteId) {
|
|
8199
|
+
const normalized = cleanedAbsoluteId.replaceAll("\\", "/");
|
|
8200
|
+
const markerIndex = normalized.lastIndexOf("/node_modules/");
|
|
8201
|
+
if (markerIndex < 0) return;
|
|
8202
|
+
const packageRelativePath = normalizeNpmImportLookupPath(normalized.slice(markerIndex));
|
|
8203
|
+
return packageRelativePath ? normalizeRelativePath(packageRelativePath) : void 0;
|
|
8204
|
+
}
|
|
8198
8205
|
function createStringOrRegExpMatcher(pattern) {
|
|
8199
8206
|
if (typeof pattern === "string") {
|
|
8200
8207
|
const matcher = picomatch(pattern, { dot: true });
|
|
@@ -8237,7 +8244,7 @@ function createSharedPathResolver(configService, sharedPathRoot) {
|
|
|
8237
8244
|
return (absoluteId) => {
|
|
8238
8245
|
const cleaned = normalizeSharedPathCandidate(absoluteId);
|
|
8239
8246
|
if (!path.isAbsolute(cleaned)) return;
|
|
8240
|
-
if (!isPathInside(resolvedRoot, cleaned)) return;
|
|
8247
|
+
if (!isPathInside(resolvedRoot, cleaned)) return resolveNodeModulesSharedPath(cleaned);
|
|
8241
8248
|
return normalizeRelativePath(path.relative(resolvedRoot, cleaned));
|
|
8242
8249
|
};
|
|
8243
8250
|
}
|
|
@@ -8820,19 +8827,90 @@ function createOxcRuntimeSupport() {
|
|
|
8820
8827
|
}
|
|
8821
8828
|
//#endregion
|
|
8822
8829
|
//#region src/runtime/packageAliases.ts
|
|
8823
|
-
const
|
|
8824
|
-
|
|
8825
|
-
|
|
8826
|
-
|
|
8830
|
+
const WEVU_WORKSPACE_PACKAGE_PATH = "packages-runtime/wevu";
|
|
8831
|
+
const PACKAGE_ALIASES = [
|
|
8832
|
+
{
|
|
8833
|
+
find: "class-variance-authority",
|
|
8834
|
+
packageName: "class-variance-authority",
|
|
8835
|
+
distEntry: "dist/index.js"
|
|
8836
|
+
},
|
|
8837
|
+
{
|
|
8838
|
+
find: "wevu",
|
|
8839
|
+
packageName: "wevu",
|
|
8840
|
+
distEntry: "dist/index.mjs",
|
|
8841
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8842
|
+
},
|
|
8843
|
+
{
|
|
8844
|
+
find: "wevu/compiler",
|
|
8845
|
+
packageName: "wevu",
|
|
8846
|
+
distEntry: "dist/compiler.mjs",
|
|
8847
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8848
|
+
},
|
|
8849
|
+
{
|
|
8850
|
+
find: "wevu/jsx-runtime",
|
|
8851
|
+
packageName: "wevu",
|
|
8852
|
+
distEntry: "dist/jsx-runtime.mjs",
|
|
8853
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8854
|
+
},
|
|
8855
|
+
{
|
|
8856
|
+
find: "wevu/store",
|
|
8857
|
+
packageName: "wevu",
|
|
8858
|
+
distEntry: "dist/store.mjs",
|
|
8859
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8860
|
+
},
|
|
8861
|
+
{
|
|
8862
|
+
find: "wevu/api",
|
|
8863
|
+
packageName: "wevu",
|
|
8864
|
+
distEntry: "dist/api.mjs",
|
|
8865
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8866
|
+
},
|
|
8867
|
+
{
|
|
8868
|
+
find: "wevu/fetch",
|
|
8869
|
+
packageName: "wevu",
|
|
8870
|
+
distEntry: "dist/fetch.mjs",
|
|
8871
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8872
|
+
},
|
|
8873
|
+
{
|
|
8874
|
+
find: "wevu/router",
|
|
8875
|
+
packageName: "wevu",
|
|
8876
|
+
distEntry: "dist/router.mjs",
|
|
8877
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8878
|
+
},
|
|
8879
|
+
{
|
|
8880
|
+
find: "vue-demi",
|
|
8881
|
+
packageName: "wevu",
|
|
8882
|
+
distEntry: "dist/vue-demi.mjs",
|
|
8883
|
+
fallbackWorkspacePackagePath: WEVU_WORKSPACE_PACKAGE_PATH
|
|
8884
|
+
}
|
|
8885
|
+
];
|
|
8886
|
+
function resolveRepoRoot(fromDir) {
|
|
8887
|
+
let currentDir = fromDir;
|
|
8888
|
+
while (true) {
|
|
8889
|
+
if (existsSync(path.join(currentDir, "pnpm-workspace.yaml"))) return currentDir;
|
|
8890
|
+
const parentDir = path.dirname(currentDir);
|
|
8891
|
+
if (parentDir === currentDir) return;
|
|
8892
|
+
currentDir = parentDir;
|
|
8893
|
+
}
|
|
8894
|
+
}
|
|
8895
|
+
function resolvePackageEntry(packageName, distEntry, fallbackWorkspacePackagePath) {
|
|
8896
|
+
const packageInfo = getPackageInfoSync(packageName);
|
|
8897
|
+
if (packageInfo) {
|
|
8898
|
+
const resolvedEntry = path.resolve(packageInfo.rootPath, distEntry);
|
|
8899
|
+
if (existsSync(resolvedEntry)) return resolvedEntry;
|
|
8900
|
+
}
|
|
8901
|
+
if (!fallbackWorkspacePackagePath) return;
|
|
8902
|
+
const repoRoot = resolveRepoRoot(path.dirname(fileURLToPath(import.meta.url)));
|
|
8903
|
+
if (!repoRoot) return;
|
|
8904
|
+
const fallbackEntry = path.resolve(repoRoot, fallbackWorkspacePackagePath, distEntry);
|
|
8905
|
+
if (existsSync(fallbackEntry)) return fallbackEntry;
|
|
8906
|
+
}
|
|
8827
8907
|
function resolveBuiltinPackageAliases() {
|
|
8828
8908
|
const aliases = [];
|
|
8829
|
-
for (const { packageName, distEntry } of
|
|
8830
|
-
const
|
|
8831
|
-
if (!
|
|
8832
|
-
const resolvedEntry = path.resolve(info.rootPath, distEntry);
|
|
8833
|
-
if (!existsSync(resolvedEntry)) continue;
|
|
8909
|
+
for (const { find, packageName, distEntry, fallbackWorkspacePackagePath } of PACKAGE_ALIASES) {
|
|
8910
|
+
const resolvedEntry = resolvePackageEntry(packageName, distEntry, fallbackWorkspacePackagePath);
|
|
8911
|
+
if (!resolvedEntry) continue;
|
|
8834
8912
|
aliases.push({
|
|
8835
|
-
find
|
|
8913
|
+
find,
|
|
8836
8914
|
replacement: resolvedEntry
|
|
8837
8915
|
});
|
|
8838
8916
|
}
|
|
@@ -8942,6 +9020,7 @@ function getWeappViteConfig() {
|
|
|
8942
9020
|
],
|
|
8943
9021
|
unhandledErrors: true
|
|
8944
9022
|
},
|
|
9023
|
+
injectRequestGlobals: {},
|
|
8945
9024
|
chunks: {
|
|
8946
9025
|
sharedStrategy: "duplicate",
|
|
8947
9026
|
sharedMode: "common",
|
|
@@ -9800,7 +9879,7 @@ function asset(ctx) {
|
|
|
9800
9879
|
const LEADING_DOT_SLASH_RE$2 = /^\.\//;
|
|
9801
9880
|
const LEADING_SLASHES_RE$2 = /^\/+/;
|
|
9802
9881
|
const GLOB_WILDCARD_RE = /[*?[{]/;
|
|
9803
|
-
const TRAILING_SLASHES_RE$
|
|
9882
|
+
const TRAILING_SLASHES_RE$1 = /\/+$/;
|
|
9804
9883
|
const AUTO_IMPORT_WATCHER_KEY = "__auto-import-vue-watcher__";
|
|
9805
9884
|
function isEnabledOutputOption(option) {
|
|
9806
9885
|
if (option === true) return true;
|
|
@@ -9864,7 +9943,7 @@ function registerAutoImportWatchTargets(state, globs, registrar, options = {}) {
|
|
|
9864
9943
|
for (const pattern of globs ?? []) {
|
|
9865
9944
|
const normalizedPattern = toPosixPath(pattern).replace(LEADING_DOT_SLASH_RE$2, "").replace(LEADING_SLASHES_RE$2, "");
|
|
9866
9945
|
const wildcardIndex = normalizedPattern.search(GLOB_WILDCARD_RE);
|
|
9867
|
-
const cleanedBase = (wildcardIndex >= 0 ? normalizedPattern.slice(0, wildcardIndex) : normalizedPattern).replace(TRAILING_SLASHES_RE$
|
|
9946
|
+
const cleanedBase = (wildcardIndex >= 0 ? normalizedPattern.slice(0, wildcardIndex) : normalizedPattern).replace(TRAILING_SLASHES_RE$1, "");
|
|
9868
9947
|
if (!cleanedBase) continue;
|
|
9869
9948
|
watchTargets.add(path.resolve(configService.absoluteSrcRoot, cleanedBase));
|
|
9870
9949
|
}
|
|
@@ -10508,9 +10587,52 @@ function injectNativePageLayoutSetter(pageOptions) {
|
|
|
10508
10587
|
pageOptions.properties.push(t.objectMethod("method", createStaticObjectKey("__wevuSetPageLayout"), [t.identifier("layout"), t.identifier("props")], t.blockStatement([
|
|
10509
10588
|
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("__wv_next_layout_name"), t.conditionalExpression(t.binaryExpression("===", t.identifier("layout"), t.booleanLiteral(false)), t.stringLiteral("__wv_no_layout"), t.identifier("layout")))]),
|
|
10510
10589
|
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("__wv_next_layout_props"), t.conditionalExpression(t.binaryExpression("===", t.identifier("layout"), t.booleanLiteral(false)), t.objectExpression([]), t.logicalExpression("||", t.identifier("props"), t.objectExpression([]))))]),
|
|
10590
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("__wv_current_layout_name"), t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier("data")), t.identifier("__wv_page_layout_name")))]),
|
|
10591
|
+
t.variableDeclaration("const", [t.variableDeclarator(t.identifier("__wv_current_layout_props"), t.logicalExpression("||", t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier("data")), t.identifier("__wv_page_layout_props")), t.objectExpression([])))]),
|
|
10592
|
+
t.ifStatement(t.logicalExpression("&&", t.binaryExpression("===", t.identifier("__wv_current_layout_name"), t.identifier("__wv_next_layout_name")), t.callExpression(t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [t.identifier("__wv_current_layout_props")]), t.identifier("every")), [t.arrowFunctionExpression([t.identifier("__wv_key")], t.logicalExpression("&&", t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Object"), t.identifier("prototype")), t.identifier("hasOwnProperty")), t.identifier("call")), [t.identifier("__wv_next_layout_props"), t.identifier("__wv_key")]), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("is")), [t.memberExpression(t.identifier("__wv_current_layout_props"), t.identifier("__wv_key"), true), t.memberExpression(t.identifier("__wv_next_layout_props"), t.identifier("__wv_key"), true)])))])), t.blockStatement([t.ifStatement(t.binaryExpression("===", t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [t.identifier("__wv_current_layout_props")]), t.identifier("length")), t.memberExpression(t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("keys")), [t.identifier("__wv_next_layout_props")]), t.identifier("length"))), t.blockStatement([t.returnStatement()]))])),
|
|
10511
10593
|
t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("setData")), [t.objectExpression([t.objectProperty(t.identifier("__wv_page_layout_name"), t.identifier("__wv_next_layout_name")), t.objectProperty(t.identifier("__wv_page_layout_props"), t.identifier("__wv_next_layout_props"))])]))
|
|
10512
10594
|
])));
|
|
10513
10595
|
}
|
|
10596
|
+
function toStaticLayoutValueExpression(value) {
|
|
10597
|
+
if (typeof value === "string") return t.stringLiteral(value);
|
|
10598
|
+
if (typeof value === "number") return t.numericLiteral(value);
|
|
10599
|
+
if (typeof value === "boolean") return t.booleanLiteral(value);
|
|
10600
|
+
if (value === null) return t.nullLiteral();
|
|
10601
|
+
return t.identifier("undefined");
|
|
10602
|
+
}
|
|
10603
|
+
function buildInitialNativePageLayoutState(currentLayout) {
|
|
10604
|
+
const layoutName = currentLayout?.layoutName;
|
|
10605
|
+
const layoutProps = currentLayout?.props ?? {};
|
|
10606
|
+
return t.objectExpression([t.objectProperty(t.identifier("__wv_page_layout_name"), layoutName ? t.stringLiteral(layoutName) : t.identifier("undefined")), t.objectProperty(t.identifier("__wv_page_layout_props"), t.objectExpression(Object.entries(layoutProps).filter(([, value]) => !(typeof value === "object" && value && "kind" in value && value.kind === "expression")).map(([key, value]) => t.objectProperty(createStaticObjectKey(key), toStaticLayoutValueExpression(value)))))]);
|
|
10607
|
+
}
|
|
10608
|
+
function buildInitialNativePageLayoutNameExpression(currentLayout) {
|
|
10609
|
+
return currentLayout?.layoutName ? t.stringLiteral(currentLayout.layoutName) : t.identifier("undefined");
|
|
10610
|
+
}
|
|
10611
|
+
function buildInitialNativePageLayoutPropsExpression(currentLayout) {
|
|
10612
|
+
const layoutProps = currentLayout?.props ?? {};
|
|
10613
|
+
return t.objectExpression(Object.entries(layoutProps).filter(([, value]) => !(typeof value === "object" && value && "kind" in value && value.kind === "expression")).map(([key, value]) => t.objectProperty(createStaticObjectKey(key), toStaticLayoutValueExpression(value))));
|
|
10614
|
+
}
|
|
10615
|
+
function injectNativePageLayoutState(pageOptions, currentLayout) {
|
|
10616
|
+
const initialState = buildInitialNativePageLayoutState(currentLayout);
|
|
10617
|
+
const existingData = getObjectPropertyByKey$1(pageOptions, "data");
|
|
10618
|
+
if (!existingData) {
|
|
10619
|
+
pageOptions.properties.unshift(t.objectProperty(createStaticObjectKey("data"), initialState));
|
|
10620
|
+
return;
|
|
10621
|
+
}
|
|
10622
|
+
if (t.isObjectExpression(existingData.value)) {
|
|
10623
|
+
const dataObject = existingData.value;
|
|
10624
|
+
const layoutNameProp = getObjectPropertyByKey$1(dataObject, "__wv_page_layout_name");
|
|
10625
|
+
const layoutPropsProp = getObjectPropertyByKey$1(dataObject, "__wv_page_layout_props");
|
|
10626
|
+
if (!layoutNameProp) dataObject.properties.unshift(t.objectProperty(t.identifier("__wv_page_layout_name"), buildInitialNativePageLayoutNameExpression(currentLayout)));
|
|
10627
|
+
if (!layoutPropsProp) dataObject.properties.push(t.objectProperty(t.identifier("__wv_page_layout_props"), buildInitialNativePageLayoutPropsExpression(currentLayout)));
|
|
10628
|
+
return;
|
|
10629
|
+
}
|
|
10630
|
+
existingData.value = t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("assign")), [
|
|
10631
|
+
t.objectExpression([]),
|
|
10632
|
+
existingData.value,
|
|
10633
|
+
initialState
|
|
10634
|
+
]);
|
|
10635
|
+
}
|
|
10514
10636
|
function injectLayoutBindingComputed(script, props) {
|
|
10515
10637
|
if (!script || !props) return script;
|
|
10516
10638
|
const runtimeEntries = Object.entries(props).filter((entry) => typeof entry[1] === "object" && entry[1] !== null && "kind" in entry[1] && entry[1].kind === "expression");
|
|
@@ -10585,6 +10707,7 @@ function injectNativePageLayoutRuntime(script, filename, plan) {
|
|
|
10585
10707
|
if (!shouldInjectSetter) return generate(ast, { retainLines: true }).code;
|
|
10586
10708
|
const pageOptions = findNativePageOptionsObject(ast);
|
|
10587
10709
|
if (!pageOptions) throw new Error(`${filename} 中未找到可注入 layout 运行时的 Page({}) 定义。`);
|
|
10710
|
+
injectNativePageLayoutState(pageOptions, plan?.currentLayout);
|
|
10588
10711
|
injectNativePageLayoutSetter(pageOptions);
|
|
10589
10712
|
return generate(ast, { retainLines: true }).code;
|
|
10590
10713
|
}
|
|
@@ -11773,8 +11896,6 @@ function createTemplateScanner(wxmlService, debug) {
|
|
|
11773
11896
|
}
|
|
11774
11897
|
//#endregion
|
|
11775
11898
|
//#region src/plugins/hooks/useLoadEntry/index.ts
|
|
11776
|
-
const LEADING_RELATIVE_SEGMENTS_RE = /^[./]+/;
|
|
11777
|
-
const TRAILING_SLASHES_RE$1 = /\/+$/;
|
|
11778
11899
|
function useLoadEntry(ctx, options) {
|
|
11779
11900
|
const debug = createDebugger("weapp-vite:load-entry");
|
|
11780
11901
|
const buildTarget = options?.buildTarget ?? "app";
|
|
@@ -11881,54 +12002,23 @@ function resolvePendingEntryIds(options) {
|
|
|
11881
12002
|
const pending = new Set(options.dirtyEntrySet);
|
|
11882
12003
|
if (options.mode === "full") return new Set(options.resolvedEntryMap.keys());
|
|
11883
12004
|
if (!options.isDev || options.mode === "off") return pending;
|
|
11884
|
-
let hasDependencyDrivenEntry = false;
|
|
11885
|
-
for (const entryId of options.dirtyEntrySet) if (options.dirtyEntryReasons.get(entryId) === "dependency") {
|
|
11886
|
-
hasDependencyDrivenEntry = true;
|
|
11887
|
-
break;
|
|
11888
|
-
}
|
|
11889
12005
|
if (!options.sharedChunkImporters?.size) return pending;
|
|
11890
|
-
if (!hasDependencyDrivenEntry && !hasCrossPackageDirectDirtyImporter(options)) return pending;
|
|
11891
12006
|
for (const importers of options.sharedChunkImporters.values()) {
|
|
11892
12007
|
if (importers.size <= 1) continue;
|
|
11893
12008
|
let hasDependencyDrivenImporter = false;
|
|
11894
|
-
|
|
11895
|
-
|
|
11896
|
-
|
|
11897
|
-
|
|
11898
|
-
|
|
11899
|
-
|
|
12009
|
+
let hasDirectDirtyImporter = false;
|
|
12010
|
+
for (const importer of importers) {
|
|
12011
|
+
if (options.dirtyEntrySet.has(importer) && options.dirtyEntryReasons.get(importer) === "dependency") {
|
|
12012
|
+
hasDependencyDrivenImporter = true;
|
|
12013
|
+
break;
|
|
12014
|
+
}
|
|
12015
|
+
if (options.dirtyEntrySet.has(importer) && options.dirtyEntryReasons.get(importer) === "direct") hasDirectDirtyImporter = true;
|
|
11900
12016
|
}
|
|
12017
|
+
if (!hasDependencyDrivenImporter && !hasDirectDirtyImporter) continue;
|
|
11901
12018
|
for (const importer of importers) pending.add(importer);
|
|
11902
12019
|
}
|
|
11903
12020
|
return pending;
|
|
11904
12021
|
}
|
|
11905
|
-
function shouldExpandDirectUpdateAcrossPackageScopes(importers, options) {
|
|
11906
|
-
let hasDirectDirtyImporter = false;
|
|
11907
|
-
const scopes = /* @__PURE__ */ new Set();
|
|
11908
|
-
for (const importer of importers) {
|
|
11909
|
-
if (options.dirtyEntrySet.has(importer) && options.dirtyEntryReasons.get(importer) === "direct") hasDirectDirtyImporter = true;
|
|
11910
|
-
const scope = resolveEntryPackageScope(importer, options.subPackageRoots, options.relativeAbsoluteSrcRoot);
|
|
11911
|
-
scopes.add(scope);
|
|
11912
|
-
if (scopes.size > 1 && hasDirectDirtyImporter) return true;
|
|
11913
|
-
}
|
|
11914
|
-
return false;
|
|
11915
|
-
}
|
|
11916
|
-
function hasCrossPackageDirectDirtyImporter(options) {
|
|
11917
|
-
for (const importers of options.sharedChunkImporters?.values() ?? []) {
|
|
11918
|
-
if (importers.size <= 1) continue;
|
|
11919
|
-
if (shouldExpandDirectUpdateAcrossPackageScopes(importers, options)) return true;
|
|
11920
|
-
}
|
|
11921
|
-
return false;
|
|
11922
|
-
}
|
|
11923
|
-
function resolveEntryPackageScope(entryId, subPackageRoots, relativeAbsoluteSrcRoot) {
|
|
11924
|
-
const normalized = (relativeAbsoluteSrcRoot?.(entryId) ?? entryId).replace(LEADING_RELATIVE_SEGMENTS_RE, "");
|
|
11925
|
-
for (const root of subPackageRoots ?? []) {
|
|
11926
|
-
const normalizedRoot = posix.normalize(root).replace(LEADING_RELATIVE_SEGMENTS_RE, "").replace(TRAILING_SLASHES_RE$1, "");
|
|
11927
|
-
if (!normalizedRoot) continue;
|
|
11928
|
-
if (normalized === normalizedRoot || normalized.startsWith(`${normalizedRoot}/`)) return normalizedRoot;
|
|
11929
|
-
}
|
|
11930
|
-
return "";
|
|
11931
|
-
}
|
|
11932
12022
|
//#endregion
|
|
11933
12023
|
//#region src/utils/wxmlScriptModule.ts
|
|
11934
12024
|
const IMPORT_SJS_TAG_RE = /<import-sjs([\s\S]*?)>/g;
|
|
@@ -12408,37 +12498,32 @@ function refreshModuleGraph(pluginCtx, state) {
|
|
|
12408
12498
|
if (importers.size) state.moduleImporters.set(normalizedId, importers);
|
|
12409
12499
|
}
|
|
12410
12500
|
}
|
|
12411
|
-
function refreshSharedChunkImporters(bundle, state) {
|
|
12412
|
-
state.hmrSharedChunkImporters.clear();
|
|
12413
|
-
appendSharedChunkImporters(bundle, state);
|
|
12414
|
-
}
|
|
12415
|
-
function refreshPartialSharedChunkImporters(bundle, state, entryIds) {
|
|
12416
|
-
if (!entryIds.size) return;
|
|
12417
|
-
for (const [chunkId, importers] of state.hmrSharedChunkImporters) {
|
|
12418
|
-
for (const entryId of entryIds) importers.delete(entryId);
|
|
12419
|
-
if (importers.size === 0) state.hmrSharedChunkImporters.delete(chunkId);
|
|
12420
|
-
}
|
|
12421
|
-
appendSharedChunkImporters(bundle, state, entryIds);
|
|
12422
|
-
}
|
|
12423
12501
|
function appendSharedChunkImporters(bundle, state, onlyEntryIds) {
|
|
12424
|
-
const
|
|
12425
|
-
|
|
12426
|
-
if (
|
|
12427
|
-
|
|
12428
|
-
|
|
12502
|
+
const getTrackedImporterIds = (chunk) => {
|
|
12503
|
+
const trackedImporterIds = /* @__PURE__ */ new Set();
|
|
12504
|
+
if (chunk.facadeModuleId) {
|
|
12505
|
+
const entryId = normalizeFsResolvedId(chunk.facadeModuleId);
|
|
12506
|
+
if (chunk.isEntry || state.resolvedEntryMap.has(entryId)) trackedImporterIds.add(entryId);
|
|
12507
|
+
}
|
|
12508
|
+
if (Array.isArray(chunk.moduleIds)) for (const moduleId of chunk.moduleIds) {
|
|
12509
|
+
const normalizedModuleId = normalizeFsResolvedId(moduleId);
|
|
12510
|
+
if (state.resolvedEntryMap.has(normalizedModuleId)) trackedImporterIds.add(normalizedModuleId);
|
|
12511
|
+
}
|
|
12512
|
+
return trackedImporterIds;
|
|
12429
12513
|
};
|
|
12430
12514
|
const entryChunks = [];
|
|
12431
12515
|
for (const output of Object.values(bundle)) {
|
|
12432
12516
|
if (output?.type !== "chunk") continue;
|
|
12433
12517
|
const chunk = output;
|
|
12434
|
-
|
|
12435
|
-
if (!
|
|
12436
|
-
const
|
|
12437
|
-
|
|
12438
|
-
|
|
12439
|
-
|
|
12440
|
-
|
|
12441
|
-
|
|
12518
|
+
const trackedImporterIds = getTrackedImporterIds(chunk);
|
|
12519
|
+
if (!trackedImporterIds.size) continue;
|
|
12520
|
+
for (const trackedImporterId of trackedImporterIds) {
|
|
12521
|
+
if (onlyEntryIds && !onlyEntryIds.has(trackedImporterId)) continue;
|
|
12522
|
+
entryChunks.push({
|
|
12523
|
+
entryId: trackedImporterId,
|
|
12524
|
+
chunk
|
|
12525
|
+
});
|
|
12526
|
+
}
|
|
12442
12527
|
}
|
|
12443
12528
|
if (!entryChunks.length) return;
|
|
12444
12529
|
for (const { chunk, entryId } of entryChunks) {
|
|
@@ -12449,13 +12534,25 @@ function appendSharedChunkImporters(bundle, state, onlyEntryIds) {
|
|
|
12449
12534
|
for (const imported of imports) {
|
|
12450
12535
|
const target = bundle[imported];
|
|
12451
12536
|
if (!target || target.type !== "chunk") continue;
|
|
12452
|
-
if (
|
|
12537
|
+
if (getTrackedImporterIds(target).size) continue;
|
|
12453
12538
|
const current = state.hmrSharedChunkImporters.get(imported);
|
|
12454
12539
|
if (current) current.add(entryId);
|
|
12455
12540
|
else state.hmrSharedChunkImporters.set(imported, new Set([entryId]));
|
|
12456
12541
|
}
|
|
12457
12542
|
}
|
|
12458
12543
|
}
|
|
12544
|
+
function refreshSharedChunkImporters(bundle, state) {
|
|
12545
|
+
state.hmrSharedChunkImporters.clear();
|
|
12546
|
+
appendSharedChunkImporters(bundle, state);
|
|
12547
|
+
}
|
|
12548
|
+
function refreshPartialSharedChunkImporters(bundle, state, entryIds) {
|
|
12549
|
+
if (!entryIds.size) return;
|
|
12550
|
+
for (const [chunkId, importers] of state.hmrSharedChunkImporters) {
|
|
12551
|
+
for (const entryId of entryIds) importers.delete(entryId);
|
|
12552
|
+
if (importers.size === 0) state.hmrSharedChunkImporters.delete(chunkId);
|
|
12553
|
+
}
|
|
12554
|
+
appendSharedChunkImporters(bundle, state, entryIds);
|
|
12555
|
+
}
|
|
12459
12556
|
//#endregion
|
|
12460
12557
|
//#region src/plugins/core/helpers/independent.ts
|
|
12461
12558
|
async function flushIndependentBuilds(state) {
|
|
@@ -12479,6 +12576,140 @@ async function flushIndependentBuilds(state) {
|
|
|
12479
12576
|
state.pendingIndependentBuilds = [];
|
|
12480
12577
|
}
|
|
12481
12578
|
//#endregion
|
|
12579
|
+
//#region src/runtime/config/internal/injectRequestGlobals.ts
|
|
12580
|
+
const FULL_REQUEST_GLOBAL_TARGETS = [
|
|
12581
|
+
"fetch",
|
|
12582
|
+
"Headers",
|
|
12583
|
+
"Request",
|
|
12584
|
+
"Response",
|
|
12585
|
+
"AbortController",
|
|
12586
|
+
"AbortSignal",
|
|
12587
|
+
"XMLHttpRequest"
|
|
12588
|
+
];
|
|
12589
|
+
const ABORT_REQUEST_GLOBAL_TARGETS = ["AbortController", "AbortSignal"];
|
|
12590
|
+
const DEFAULT_REQUEST_GLOBAL_DEPENDENCIES = ["axios", "graphql-request"];
|
|
12591
|
+
const DEFAULT_ABORT_GLOBAL_DEPENDENCIES = ["@tanstack/query-core", "@tanstack/vue-query"];
|
|
12592
|
+
const REQUEST_GLOBAL_FREE_BINDING_TARGETS$1 = new Set([
|
|
12593
|
+
...FULL_REQUEST_GLOBAL_TARGETS,
|
|
12594
|
+
"URL",
|
|
12595
|
+
"URLSearchParams",
|
|
12596
|
+
"Blob",
|
|
12597
|
+
"FormData"
|
|
12598
|
+
]);
|
|
12599
|
+
function hasMatchedDependency(packageJson, patterns) {
|
|
12600
|
+
return [...new Set([
|
|
12601
|
+
...Object.keys(packageJson?.dependencies ?? {}),
|
|
12602
|
+
...Object.keys(packageJson?.devDependencies ?? {}),
|
|
12603
|
+
...Object.keys(packageJson?.peerDependencies ?? {})
|
|
12604
|
+
])].some((dependency) => {
|
|
12605
|
+
return patterns.some((pattern) => {
|
|
12606
|
+
if (typeof pattern === "string") return pattern === dependency;
|
|
12607
|
+
pattern.lastIndex = 0;
|
|
12608
|
+
return pattern.test(dependency);
|
|
12609
|
+
});
|
|
12610
|
+
});
|
|
12611
|
+
}
|
|
12612
|
+
function resolveTargets(config) {
|
|
12613
|
+
if (config && typeof config === "object" && Array.isArray(config.targets) && config.targets.length > 0) return [...new Set(config.targets)];
|
|
12614
|
+
return [...FULL_REQUEST_GLOBAL_TARGETS];
|
|
12615
|
+
}
|
|
12616
|
+
function resolveDependencyPatterns(config) {
|
|
12617
|
+
if (config && typeof config === "object" && Array.isArray(config.dependencies) && config.dependencies.length > 0) return config.dependencies;
|
|
12618
|
+
return DEFAULT_REQUEST_GLOBAL_DEPENDENCIES;
|
|
12619
|
+
}
|
|
12620
|
+
function hasCustomAutoRuleConfig(config) {
|
|
12621
|
+
if (!config || typeof config !== "object") return false;
|
|
12622
|
+
return Boolean(Array.isArray(config.dependencies) && config.dependencies.length > 0 || Array.isArray(config.targets) && config.targets.length > 0);
|
|
12623
|
+
}
|
|
12624
|
+
function resolveAutoRules(config) {
|
|
12625
|
+
if (hasCustomAutoRuleConfig(config)) return [{
|
|
12626
|
+
dependencyPatterns: resolveDependencyPatterns(config),
|
|
12627
|
+
targets: resolveTargets(config)
|
|
12628
|
+
}];
|
|
12629
|
+
return [{
|
|
12630
|
+
dependencyPatterns: DEFAULT_REQUEST_GLOBAL_DEPENDENCIES,
|
|
12631
|
+
targets: [...FULL_REQUEST_GLOBAL_TARGETS]
|
|
12632
|
+
}, {
|
|
12633
|
+
dependencyPatterns: DEFAULT_ABORT_GLOBAL_DEPENDENCIES,
|
|
12634
|
+
targets: [...ABORT_REQUEST_GLOBAL_TARGETS]
|
|
12635
|
+
}];
|
|
12636
|
+
}
|
|
12637
|
+
/**
|
|
12638
|
+
* @description 解析按需注入请求相关全局对象的最终配置。
|
|
12639
|
+
*/
|
|
12640
|
+
function resolveInjectRequestGlobalsOptions(config, packageJson) {
|
|
12641
|
+
if (config === false) return null;
|
|
12642
|
+
if (config && typeof config === "object" && config.enabled === false) return null;
|
|
12643
|
+
if ((config && typeof config === "object" ? config.enabled : config) === true) return {
|
|
12644
|
+
mode: "explicit",
|
|
12645
|
+
targets: resolveTargets(config),
|
|
12646
|
+
dependencyPatterns: resolveDependencyPatterns(config)
|
|
12647
|
+
};
|
|
12648
|
+
const autoRules = resolveAutoRules(config);
|
|
12649
|
+
const matchedTargets = /* @__PURE__ */ new Set();
|
|
12650
|
+
for (const rule of autoRules) {
|
|
12651
|
+
if (!hasMatchedDependency(packageJson, rule.dependencyPatterns)) continue;
|
|
12652
|
+
for (const target of rule.targets) matchedTargets.add(target);
|
|
12653
|
+
}
|
|
12654
|
+
if (matchedTargets.size === 0) return null;
|
|
12655
|
+
return {
|
|
12656
|
+
mode: "auto",
|
|
12657
|
+
targets: [...matchedTargets]
|
|
12658
|
+
};
|
|
12659
|
+
}
|
|
12660
|
+
function resolveRequestGlobalsRuntimeModuleId() {
|
|
12661
|
+
return "weapp-vite/web-apis";
|
|
12662
|
+
}
|
|
12663
|
+
function resolveRequestGlobalsBindingTargets$1(targets) {
|
|
12664
|
+
const bindingTargets = [...targets];
|
|
12665
|
+
if (targets.some((target) => target === "fetch" || target === "Request" || target === "Response" || target === "XMLHttpRequest")) bindingTargets.push("URL", "URLSearchParams", "Blob", "FormData");
|
|
12666
|
+
return [...new Set(bindingTargets)].filter((target) => REQUEST_GLOBAL_FREE_BINDING_TARGETS$1.has(target));
|
|
12667
|
+
}
|
|
12668
|
+
/**
|
|
12669
|
+
* @description 生成入口文件用的请求全局对象注入代码。
|
|
12670
|
+
*/
|
|
12671
|
+
function createInjectRequestGlobalsCode(targets, options) {
|
|
12672
|
+
const runtimeModuleId = resolveRequestGlobalsRuntimeModuleId();
|
|
12673
|
+
const lines = [`import { installRequestGlobals as __weappViteInstallRequestGlobals } from ${JSON.stringify(runtimeModuleId)}`];
|
|
12674
|
+
if (options?.localBindings) {
|
|
12675
|
+
const bindingTargets = resolveRequestGlobalsBindingTargets$1(targets);
|
|
12676
|
+
lines.push(`const __weappViteRequestGlobalsHost__ = __weappViteInstallRequestGlobals({ targets: ${JSON.stringify(targets)} }) || globalThis`, ...bindingTargets.map((target) => `var ${target} = __weappViteRequestGlobalsHost__.${target}`));
|
|
12677
|
+
} else lines.push(`__weappViteInstallRequestGlobals({ targets: ${JSON.stringify(targets)} })`);
|
|
12678
|
+
lines.push("");
|
|
12679
|
+
return lines.join("\n");
|
|
12680
|
+
}
|
|
12681
|
+
/**
|
|
12682
|
+
* @description 为 Vue SFC 入口生成合法的请求全局注入脚本块。
|
|
12683
|
+
*/
|
|
12684
|
+
function createInjectRequestGlobalsSfcCode(targets, options) {
|
|
12685
|
+
return `<script${options?.setup ? " setup lang=\"ts\"" : " lang=\"ts\""}>\n${createInjectRequestGlobalsCode(targets, options)}<\/script>\n`;
|
|
12686
|
+
}
|
|
12687
|
+
function injectCodeIntoSfcBlock(source, startOffset, injection) {
|
|
12688
|
+
return `${source.slice(0, startOffset)}${injection}${source.slice(startOffset)}`;
|
|
12689
|
+
}
|
|
12690
|
+
/**
|
|
12691
|
+
* @description 将请求全局对象注入到现有 SFC 脚本块,避免生成额外的重复 `<script>`。
|
|
12692
|
+
*/
|
|
12693
|
+
function injectRequestGlobalsIntoSfc(source, targets, options) {
|
|
12694
|
+
if (targets.length === 0) return source;
|
|
12695
|
+
const injection = createInjectRequestGlobalsCode(targets, options);
|
|
12696
|
+
const { descriptor, errors } = parse(source, {
|
|
12697
|
+
filename: "request-globals.vue",
|
|
12698
|
+
ignoreEmpty: false
|
|
12699
|
+
});
|
|
12700
|
+
if (errors.length > 0) return `${createInjectRequestGlobalsSfcCode(targets, options)}${source}`;
|
|
12701
|
+
const inlineScript = descriptor.script && !descriptor.script.src ? descriptor.script : void 0;
|
|
12702
|
+
if (inlineScript) return injectCodeIntoSfcBlock(source, inlineScript.loc.start.offset, injection);
|
|
12703
|
+
const inlineScriptSetup = descriptor.scriptSetup && !descriptor.scriptSetup.src ? descriptor.scriptSetup : void 0;
|
|
12704
|
+
if (inlineScriptSetup) return injectCodeIntoSfcBlock(source, inlineScriptSetup.loc.start.offset, injection);
|
|
12705
|
+
if (!descriptor.script) return `${createInjectRequestGlobalsSfcCode(targets, options)}${source}`;
|
|
12706
|
+
if (!descriptor.scriptSetup) return `${createInjectRequestGlobalsSfcCode(targets, {
|
|
12707
|
+
...options,
|
|
12708
|
+
setup: true
|
|
12709
|
+
})}${source}`;
|
|
12710
|
+
return source;
|
|
12711
|
+
}
|
|
12712
|
+
//#endregion
|
|
12482
12713
|
//#region src/utils/weapi.ts
|
|
12483
12714
|
function getWeapiGlobalHostCandidates() {
|
|
12484
12715
|
return [
|
|
@@ -12526,6 +12757,26 @@ const platformApiIdentifiers = new Set([
|
|
|
12526
12757
|
const NPM_PROTOCOL_RE = /^npm:/;
|
|
12527
12758
|
const ABSOLUTE_NPM_PREFIX_RE = /^\/(?:miniprogram_npm|node_modules)\//;
|
|
12528
12759
|
const PRETTY_NODE_MODULES_RE = /node_modules\/(?:\.pnpm\/[^/]+\/node_modules\/)?(.+)/;
|
|
12760
|
+
const REQUEST_GLOBAL_EXPORT_RE = /Object\.defineProperty\(exports,\s*(?:`([^`]+)`|'([^']+)'|"([^"]+)"),\s*\{[\s\S]*?get:function\(\)\{return ([A-Za-z_$][\w$]*)\}\}\)/g;
|
|
12761
|
+
const REQUEST_GLOBAL_INSTALLER_RE = /function\s+([A-Za-z_$][\w$]*)\([^)]*=\{\}\)\{[\s\S]{0,200}?targets\?\?\[[\s\S]{0,80}?fetch[\s\S]{0,80}?Headers[\s\S]{0,80}?Request[\s\S]{0,80}?Response[\s\S]{0,80}?AbortController[\s\S]{0,80}?AbortSignal[\s\S]{0,80}?XMLHttpRequest[\s\S]{0,240}?return [^}]+\}/;
|
|
12762
|
+
const REQUEST_GLOBAL_ENTRY_NAME_RE = /\.[^/.]+$/;
|
|
12763
|
+
const REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE = /([A-Za-z_$][\w$]*)\s*=\s*require\((`([^`]+)`|'([^']+)'|"([^"]+)")\)/g;
|
|
12764
|
+
const REQUEST_GLOBAL_TARGET_SIGNATURES = [
|
|
12765
|
+
"fetch",
|
|
12766
|
+
"Headers",
|
|
12767
|
+
"Request",
|
|
12768
|
+
"Response",
|
|
12769
|
+
"AbortController",
|
|
12770
|
+
"AbortSignal",
|
|
12771
|
+
"XMLHttpRequest"
|
|
12772
|
+
];
|
|
12773
|
+
const REQUEST_GLOBAL_FREE_BINDING_TARGETS = new Set([
|
|
12774
|
+
...REQUEST_GLOBAL_TARGET_SIGNATURES,
|
|
12775
|
+
"URL",
|
|
12776
|
+
"URLSearchParams",
|
|
12777
|
+
"Blob",
|
|
12778
|
+
"FormData"
|
|
12779
|
+
]);
|
|
12529
12780
|
function resolveInjectWeapiGlobalName(state) {
|
|
12530
12781
|
const injectWeapi = state.ctx.configService.weappViteConfig?.injectWeapi;
|
|
12531
12782
|
if (!injectWeapi) return null;
|
|
@@ -12645,6 +12896,9 @@ function getRequireImportLiteral(node) {
|
|
|
12645
12896
|
if (node.type === "TemplateLiteral" && node.expressions?.length === 0 && node.quasis?.length === 1) return node.quasis[0]?.value?.cooked ?? null;
|
|
12646
12897
|
return null;
|
|
12647
12898
|
}
|
|
12899
|
+
function getStaticStringLiteral(node) {
|
|
12900
|
+
return getRequireImportLiteral(node);
|
|
12901
|
+
}
|
|
12648
12902
|
function setRequireImportLiteral(node, nextValue) {
|
|
12649
12903
|
if (!node) return;
|
|
12650
12904
|
if (node.type === "StringLiteral" || node.type === "Literal") {
|
|
@@ -12656,6 +12910,175 @@ function setRequireImportLiteral(node, nextValue) {
|
|
|
12656
12910
|
node.quasis[0].value.cooked = nextValue;
|
|
12657
12911
|
}
|
|
12658
12912
|
}
|
|
12913
|
+
function resolveRequestGlobalsInstallerName(code) {
|
|
12914
|
+
const installerMatch = code.match(REQUEST_GLOBAL_INSTALLER_RE);
|
|
12915
|
+
if (installerMatch?.[1]) return installerMatch[1];
|
|
12916
|
+
try {
|
|
12917
|
+
const ast = parseJsLike(code);
|
|
12918
|
+
let installerName = null;
|
|
12919
|
+
const isInstallerFunctionNode = (node) => {
|
|
12920
|
+
if (!node) return false;
|
|
12921
|
+
const functionCode = generate(node).code;
|
|
12922
|
+
return REQUEST_GLOBAL_TARGET_SIGNATURES.every((target) => functionCode.includes(target));
|
|
12923
|
+
};
|
|
12924
|
+
traverse(ast, {
|
|
12925
|
+
FunctionDeclaration(path) {
|
|
12926
|
+
if (installerName || !path.node?.id?.name) return;
|
|
12927
|
+
if (isInstallerFunctionNode(path.node.body)) installerName = path.node.id.name;
|
|
12928
|
+
},
|
|
12929
|
+
VariableDeclarator(path) {
|
|
12930
|
+
if (installerName || path.node?.id?.type !== "Identifier") return;
|
|
12931
|
+
const init = path.node.init;
|
|
12932
|
+
if (!init || init.type !== "FunctionExpression" && init.type !== "ArrowFunctionExpression") return;
|
|
12933
|
+
if (isInstallerFunctionNode(init.body)) installerName = path.node.id.name;
|
|
12934
|
+
}
|
|
12935
|
+
});
|
|
12936
|
+
return installerName;
|
|
12937
|
+
} catch {
|
|
12938
|
+
return null;
|
|
12939
|
+
}
|
|
12940
|
+
}
|
|
12941
|
+
function resolveRequestGlobalsExportName(code) {
|
|
12942
|
+
const installerName = resolveRequestGlobalsInstallerName(code);
|
|
12943
|
+
if (!installerName) return null;
|
|
12944
|
+
for (const match of code.matchAll(REQUEST_GLOBAL_EXPORT_RE)) {
|
|
12945
|
+
const candidateExportName = match[1] ?? match[2] ?? match[3];
|
|
12946
|
+
const returnedIdentifier = match[4];
|
|
12947
|
+
if (candidateExportName && returnedIdentifier === installerName) return candidateExportName;
|
|
12948
|
+
}
|
|
12949
|
+
try {
|
|
12950
|
+
const ast = parseJsLike(code);
|
|
12951
|
+
let exportName = null;
|
|
12952
|
+
traverse(ast, { CallExpression(path) {
|
|
12953
|
+
if (exportName) return;
|
|
12954
|
+
const callee = path.node?.callee;
|
|
12955
|
+
if (!callee || callee.type !== "MemberExpression" || callee.object?.type !== "Identifier" || callee.object.name !== "Object" || callee.property?.type !== "Identifier" || callee.property.name !== "defineProperty") return;
|
|
12956
|
+
const args = path.node.arguments;
|
|
12957
|
+
if (!Array.isArray(args) || args.length < 3) return;
|
|
12958
|
+
if (args[0]?.type !== "Identifier" || args[0].name !== "exports") return;
|
|
12959
|
+
const candidateExportName = getStaticStringLiteral(args[1]);
|
|
12960
|
+
if (!candidateExportName || args[2]?.type !== "ObjectExpression") return;
|
|
12961
|
+
const getterProperty = args[2].properties.find((property) => {
|
|
12962
|
+
return property?.type === "ObjectProperty" && property.key?.type === "Identifier" && property.key.name === "get" || property?.type === "ObjectMethod" && property.key?.type === "Identifier" && property.key.name === "get";
|
|
12963
|
+
});
|
|
12964
|
+
const getterValue = getterProperty?.type === "ObjectMethod" ? getterProperty : getterProperty?.value;
|
|
12965
|
+
if (!getterValue) return;
|
|
12966
|
+
const getterBody = getterValue.body;
|
|
12967
|
+
const returnIdentifier = getterBody?.type === "BlockStatement" ? getterBody.body.find((statement) => statement?.type === "ReturnStatement")?.argument : getterBody;
|
|
12968
|
+
if (returnIdentifier?.type === "Identifier" && returnIdentifier.name === installerName) exportName = candidateExportName;
|
|
12969
|
+
} });
|
|
12970
|
+
return exportName;
|
|
12971
|
+
} catch {
|
|
12972
|
+
return null;
|
|
12973
|
+
}
|
|
12974
|
+
}
|
|
12975
|
+
function normalizeRelativeChunkImport(fileName, importee) {
|
|
12976
|
+
return toPosixPath(path.normalize(path.join(path.dirname(fileName), importee)));
|
|
12977
|
+
}
|
|
12978
|
+
function resolveRequestGlobalsBindingTargets(targets) {
|
|
12979
|
+
const bindingTargets = [...targets];
|
|
12980
|
+
if (targets.some((target) => target === "fetch" || target === "Request" || target === "Response" || target === "XMLHttpRequest")) bindingTargets.push("URL", "URLSearchParams", "Blob", "FormData");
|
|
12981
|
+
return [...new Set(bindingTargets)].filter((target) => REQUEST_GLOBAL_FREE_BINDING_TARGETS.has(target));
|
|
12982
|
+
}
|
|
12983
|
+
function createRequestGlobalsPassiveBindingsCode(bindingTargets) {
|
|
12984
|
+
return `${[
|
|
12985
|
+
"const __weappViteRequestGlobalsActuals__ = globalThis.__weappViteRequestGlobalsActuals__ || (globalThis.__weappViteRequestGlobalsActuals__ = Object.create(null))",
|
|
12986
|
+
"function __weappViteMarkRequestGlobalsPlaceholder__(value){try{Object.defineProperty(value,\"__weappViteRequestGlobalsPlaceholder__\",{value:true,configurable:true})}catch{value.__weappViteRequestGlobalsPlaceholder__=true}return value}",
|
|
12987
|
+
"function __weappViteCreateLazyRequestGlobalsFunction__(name){const placeholder=function(...args){const actual=__weappViteRequestGlobalsActuals__[name];if(typeof actual!==\"function\"){throw new Error(name+\" is not initialized\")}return actual.apply(this,args)};return __weappViteMarkRequestGlobalsPlaceholder__(placeholder)}",
|
|
12988
|
+
"function __weappViteCreateLazyRequestGlobalsConstructor__(name){const placeholder=function(...args){const actual=__weappViteRequestGlobalsActuals__[name];if(typeof actual!==\"function\"){throw new Error(name+\" is not initialized\")}return Reflect.construct(actual,args)};return __weappViteMarkRequestGlobalsPlaceholder__(placeholder)}",
|
|
12989
|
+
"function __weappViteHasUsableRequestGlobalsConstructor__(value,args){if(typeof value!==\"function\"||value?.__weappViteRequestGlobalsPlaceholder__===true){return false}try{return Reflect.construct(value,args),true}catch{return false}}"
|
|
12990
|
+
].join(";")};${bindingTargets.map((target) => {
|
|
12991
|
+
if (target === "fetch") return "var fetch = typeof __weappViteRequestGlobalsActuals__[\"fetch\"]===\"function\"&&__weappViteRequestGlobalsActuals__[\"fetch\"]?.__weappViteRequestGlobalsPlaceholder__!==true?__weappViteRequestGlobalsActuals__[\"fetch\"]:typeof globalThis.fetch===\"function\"&&globalThis.fetch?.__weappViteRequestGlobalsPlaceholder__!==true?globalThis.fetch:__weappViteCreateLazyRequestGlobalsFunction__(\"fetch\")";
|
|
12992
|
+
const placeholderFactory = `__weappViteCreateLazyRequestGlobalsConstructor__(${JSON.stringify(target)})`;
|
|
12993
|
+
const actualRef = `__weappViteRequestGlobalsActuals__[${JSON.stringify(target)}]`;
|
|
12994
|
+
if (target === "URL") return `var URL = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},["https://request-globals.invalid"])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.URL,["https://request-globals.invalid"])?globalThis.URL:${placeholderFactory}`;
|
|
12995
|
+
if (target === "URLSearchParams") return `var URLSearchParams = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},["client=graphql-request"])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.URLSearchParams,["client=graphql-request"])?globalThis.URLSearchParams:${placeholderFactory}`;
|
|
12996
|
+
if (target === "Blob") return `var Blob = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},[])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.Blob,[])?globalThis.Blob:${placeholderFactory}`;
|
|
12997
|
+
if (target === "FormData") return `var FormData = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},[])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.FormData,[])?globalThis.FormData:${placeholderFactory}`;
|
|
12998
|
+
if (target === "Headers") return `var Headers = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},[])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.Headers,[])?globalThis.Headers:${placeholderFactory}`;
|
|
12999
|
+
if (target === "Request") return `var Request = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},["https://request-globals.invalid"])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.Request,["https://request-globals.invalid"])?globalThis.Request:${placeholderFactory}`;
|
|
13000
|
+
if (target === "Response") return `var Response = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},[null])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.Response,[null])?globalThis.Response:${placeholderFactory}`;
|
|
13001
|
+
if (target === "XMLHttpRequest") return `var XMLHttpRequest = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},[])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.XMLHttpRequest,[])?globalThis.XMLHttpRequest:${placeholderFactory}`;
|
|
13002
|
+
if (target === "AbortController") return `var AbortController = __weappViteHasUsableRequestGlobalsConstructor__(${actualRef},[])?${actualRef}:__weappViteHasUsableRequestGlobalsConstructor__(globalThis.AbortController,[])?globalThis.AbortController:${placeholderFactory}`;
|
|
13003
|
+
return `var ${target} = typeof ${actualRef}==="function"&&${actualRef}?.__weappViteRequestGlobalsPlaceholder__!==true?${actualRef}:typeof globalThis.${target}==="function"&&globalThis.${target}?.__weappViteRequestGlobalsPlaceholder__!==true?globalThis.${target}:${placeholderFactory}`;
|
|
13004
|
+
}).join(";")};`;
|
|
13005
|
+
}
|
|
13006
|
+
function injectRequestGlobalsBundleRuntime(bundle, targets) {
|
|
13007
|
+
const installerChunks = /* @__PURE__ */ new Map();
|
|
13008
|
+
if (targets.length === 0) return installerChunks;
|
|
13009
|
+
const bindingTargets = resolveRequestGlobalsBindingTargets(targets);
|
|
13010
|
+
for (const output of Object.values(bundle)) {
|
|
13011
|
+
if (output?.type !== "chunk") continue;
|
|
13012
|
+
const chunk = output;
|
|
13013
|
+
if (chunk.code.includes("__weappViteRequestGlobalsBundleInstalled__")) continue;
|
|
13014
|
+
const installerName = resolveRequestGlobalsInstallerName(chunk.code);
|
|
13015
|
+
const exportName = resolveRequestGlobalsExportName(chunk.code);
|
|
13016
|
+
if (!installerName || !exportName) continue;
|
|
13017
|
+
installerChunks.set(toPosixPath(chunk.fileName), exportName);
|
|
13018
|
+
const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(bindingTargets);
|
|
13019
|
+
const runtimeBindingCode = [
|
|
13020
|
+
`const __weappViteRequestGlobalsBundleHost__ = ${installerName}({ targets: ${JSON.stringify(targets)} }) || globalThis`,
|
|
13021
|
+
...bindingTargets.map((target) => `__weappViteRequestGlobalsActuals__[${JSON.stringify(target)}] = __weappViteRequestGlobalsBundleHost__.${target}`),
|
|
13022
|
+
...bindingTargets.map((target) => `${target} = __weappViteRequestGlobalsBundleHost__.${target}`)
|
|
13023
|
+
].join(";");
|
|
13024
|
+
const bundlePrelude = `/* __weappViteRequestGlobalsBundleInstalled__ */ ${passiveBindingsCode}\n`;
|
|
13025
|
+
const firstRequireMatch = chunk.code.match(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE);
|
|
13026
|
+
if (firstRequireMatch?.[0]) {
|
|
13027
|
+
chunk.code = `${bundlePrelude}${chunk.code.replace(firstRequireMatch[0], (match) => `${match};${runtimeBindingCode}`)}\n`;
|
|
13028
|
+
continue;
|
|
13029
|
+
}
|
|
13030
|
+
chunk.code = `${bundlePrelude}${chunk.code}\n;${runtimeBindingCode};\n`;
|
|
13031
|
+
}
|
|
13032
|
+
return installerChunks;
|
|
13033
|
+
}
|
|
13034
|
+
function injectRequestGlobalsPassiveBindings(bundle, installerChunks, targets, entriesMap) {
|
|
13035
|
+
if (installerChunks.size === 0 || targets.length === 0) return;
|
|
13036
|
+
const bindingTargets = resolveRequestGlobalsBindingTargets(targets);
|
|
13037
|
+
if (bindingTargets.length === 0) return;
|
|
13038
|
+
const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(bindingTargets);
|
|
13039
|
+
for (const output of Object.values(bundle)) {
|
|
13040
|
+
if (output?.type !== "chunk") continue;
|
|
13041
|
+
const chunk = output;
|
|
13042
|
+
if (installerChunks.has(toPosixPath(chunk.fileName))) continue;
|
|
13043
|
+
if (chunk.code.includes("__weappViteRequestGlobalsPassiveBindings__") || chunk.code.includes("__weappViteRequestGlobalsLocalBindings__") || chunk.code.includes("__weappViteRequestGlobalsBundleInstalled__")) continue;
|
|
13044
|
+
const entryName = chunk.fileName.replace(REQUEST_GLOBAL_ENTRY_NAME_RE, "");
|
|
13045
|
+
const entryType = entriesMap?.get(entryName)?.type;
|
|
13046
|
+
if (entryType === "page" || entryType === "component") continue;
|
|
13047
|
+
chunk.code = `/* __weappViteRequestGlobalsPassiveBindings__ */ ${passiveBindingsCode}\n${chunk.code}`;
|
|
13048
|
+
}
|
|
13049
|
+
}
|
|
13050
|
+
function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, entriesMap) {
|
|
13051
|
+
if (installerChunks.size === 0 || targets.length === 0) return;
|
|
13052
|
+
const bindingTargets = resolveRequestGlobalsBindingTargets(targets);
|
|
13053
|
+
if (bindingTargets.length === 0) return;
|
|
13054
|
+
for (const output of Object.values(bundle)) {
|
|
13055
|
+
if (output?.type !== "chunk") continue;
|
|
13056
|
+
const chunk = output;
|
|
13057
|
+
const entryName = chunk.fileName.replace(REQUEST_GLOBAL_ENTRY_NAME_RE, "");
|
|
13058
|
+
const entryType = entriesMap?.get(entryName)?.type;
|
|
13059
|
+
if (entryType !== "page" && entryType !== "component") continue;
|
|
13060
|
+
if (chunk.code.includes("__weappViteRequestGlobalsLocalBindings__")) continue;
|
|
13061
|
+
let requireImportLiteral = null;
|
|
13062
|
+
let exportName;
|
|
13063
|
+
for (const requireMatch of chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
|
|
13064
|
+
const importee = requireMatch[3] ?? requireMatch[4] ?? requireMatch[5];
|
|
13065
|
+
if (!importee) continue;
|
|
13066
|
+
const installerChunkFileName = normalizeRelativeChunkImport(chunk.fileName, importee);
|
|
13067
|
+
exportName = installerChunks.get(installerChunkFileName);
|
|
13068
|
+
if (!exportName) continue;
|
|
13069
|
+
requireImportLiteral = requireMatch[2] ?? null;
|
|
13070
|
+
break;
|
|
13071
|
+
}
|
|
13072
|
+
if (!requireImportLiteral || !exportName) continue;
|
|
13073
|
+
chunk.code = `/* __weappViteRequestGlobalsLocalBindings__ */ ${[
|
|
13074
|
+
`const __weappViteChunkRequestGlobalsModule__ = require(${requireImportLiteral})`,
|
|
13075
|
+
`const __weappViteChunkRequestGlobalsHost__ = __weappViteChunkRequestGlobalsModule__[${JSON.stringify(exportName)}]({ targets: ${JSON.stringify(targets)} }) || globalThis`,
|
|
13076
|
+
"const __weappViteRequestGlobalsActuals__ = globalThis.__weappViteRequestGlobalsActuals__ || (globalThis.__weappViteRequestGlobalsActuals__ = Object.create(null))",
|
|
13077
|
+
...bindingTargets.map((target) => `__weappViteRequestGlobalsActuals__[${JSON.stringify(target)}] = __weappViteChunkRequestGlobalsHost__.${target}`),
|
|
13078
|
+
...bindingTargets.map((target) => `var ${target} = __weappViteChunkRequestGlobalsHost__.${target}`)
|
|
13079
|
+
].join(";")};\n${chunk.code}`;
|
|
13080
|
+
}
|
|
13081
|
+
}
|
|
12659
13082
|
function toRelativeRuntimeNpmImport(fileName, root, importee) {
|
|
12660
13083
|
const normalized = normalizeWeappLocalNpmImport(importee);
|
|
12661
13084
|
const target = root ? `${root}/miniprogram_npm/${normalized}` : `miniprogram_npm/${normalized}`;
|
|
@@ -12727,6 +13150,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
|
|
|
12727
13150
|
const { ctx, subPackageMeta } = state;
|
|
12728
13151
|
const { scanService, configService } = ctx;
|
|
12729
13152
|
const astEngine = resolveAstEngine(configService.weappViteConfig);
|
|
13153
|
+
const injectRequestGlobalsOptions = resolveInjectRequestGlobalsOptions(configService.weappViteConfig?.injectRequestGlobals, configService.packageJson);
|
|
12730
13154
|
return async function generateBundle(_options, bundle) {
|
|
12731
13155
|
const rolldownBundle = bundle;
|
|
12732
13156
|
await flushIndependentBuilds.call(this, state);
|
|
@@ -12857,6 +13281,11 @@ function createGenerateBundleHook(state, isPluginBuild) {
|
|
|
12857
13281
|
}
|
|
12858
13282
|
const injectWeapiGlobalName = resolveInjectWeapiGlobalName(state);
|
|
12859
13283
|
if (injectWeapiGlobalName) rewriteBundlePlatformApi(rolldownBundle, injectWeapiGlobalName, { astEngine });
|
|
13284
|
+
if (injectRequestGlobalsOptions?.targets?.length) {
|
|
13285
|
+
const installerChunks = injectRequestGlobalsBundleRuntime(rolldownBundle, injectRequestGlobalsOptions.targets);
|
|
13286
|
+
injectRequestGlobalsPassiveBindings(rolldownBundle, installerChunks, injectRequestGlobalsOptions.targets, state.entriesMap);
|
|
13287
|
+
injectRequestGlobalsLocalBindings(rolldownBundle, installerChunks, injectRequestGlobalsOptions.targets, state.entriesMap);
|
|
13288
|
+
}
|
|
12860
13289
|
refreshModuleGraph(this, state);
|
|
12861
13290
|
if (configService.weappViteConfig?.debug?.watchFiles) {
|
|
12862
13291
|
const watcherService = ctx.watcherService;
|
|
@@ -13002,6 +13431,7 @@ function createLoadHook(state) {
|
|
|
13002
13431
|
checked: false,
|
|
13003
13432
|
available: false
|
|
13004
13433
|
};
|
|
13434
|
+
const injectRequestGlobalsOptions = resolveInjectRequestGlobalsOptions(configService.weappViteConfig?.injectRequestGlobals, configService.packageJson);
|
|
13005
13435
|
function resolveInjectWeapiOptions() {
|
|
13006
13436
|
const injectWeapi = configService.weappViteConfig?.injectWeapi;
|
|
13007
13437
|
if (!injectWeapi) return null;
|
|
@@ -13088,6 +13518,25 @@ function createLoadHook(state) {
|
|
|
13088
13518
|
code: replacedCode
|
|
13089
13519
|
};
|
|
13090
13520
|
}
|
|
13521
|
+
function prependCodeToLoadResult(result, code) {
|
|
13522
|
+
if (!result || typeof result !== "object" || !("code" in result) || typeof result.code !== "string") return result;
|
|
13523
|
+
return {
|
|
13524
|
+
...result,
|
|
13525
|
+
code: `${code}${result.code}`
|
|
13526
|
+
};
|
|
13527
|
+
}
|
|
13528
|
+
function resolveRequestGlobalsTargets() {
|
|
13529
|
+
if (!injectRequestGlobalsOptions) return [];
|
|
13530
|
+
return injectRequestGlobalsOptions.targets;
|
|
13531
|
+
}
|
|
13532
|
+
function injectRequestGlobalsIntoLoadResult(result, sourceId, targets, options) {
|
|
13533
|
+
if (!result || typeof result !== "object" || !("code" in result) || typeof result.code !== "string" || targets.length === 0) return result;
|
|
13534
|
+
if (sourceId.endsWith(".vue")) return {
|
|
13535
|
+
...result,
|
|
13536
|
+
code: injectRequestGlobalsIntoSfc(result.code, targets, options)
|
|
13537
|
+
};
|
|
13538
|
+
return prependCodeToLoadResult(result, createInjectRequestGlobalsCode(targets, options));
|
|
13539
|
+
}
|
|
13091
13540
|
async function ensureWeapiAvailable(pluginCtx, importer) {
|
|
13092
13541
|
if (weapiResolution.checked) return weapiResolution.available;
|
|
13093
13542
|
weapiResolution.checked = true;
|
|
@@ -13123,32 +13572,42 @@ function createLoadHook(state) {
|
|
|
13123
13572
|
}
|
|
13124
13573
|
const sourceId = normalizeFsResolvedId(id);
|
|
13125
13574
|
const injectOptions = resolveInjectWeapiOptions();
|
|
13126
|
-
if (configService.weappLibConfig?.enabled ? ctx.runtimeState.lib.entries.get(sourceId) : void 0)
|
|
13575
|
+
if (configService.weappLibConfig?.enabled ? ctx.runtimeState.lib.entries.get(sourceId) : void 0) {
|
|
13576
|
+
const result = await loadEntry.call(this, sourceId, "component");
|
|
13577
|
+
const requestGlobalsTargets = resolveRequestGlobalsTargets();
|
|
13578
|
+
if (requestGlobalsTargets.length === 0) return result;
|
|
13579
|
+
return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, { localBindings: true });
|
|
13580
|
+
}
|
|
13127
13581
|
const relativeBasename = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(sourceId));
|
|
13128
13582
|
if (relativeBasename === resolveRootEntryBasename()) {
|
|
13129
13583
|
const result = await loadEntry.call(this, sourceId, "app");
|
|
13130
|
-
|
|
13131
|
-
if (!
|
|
13584
|
+
const requestGlobalsTargets = resolveRequestGlobalsTargets();
|
|
13585
|
+
if (!injectOptions || configService.weappLibConfig?.enabled) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets);
|
|
13586
|
+
if (!await ensureWeapiAvailable(this, sourceId)) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets);
|
|
13132
13587
|
if (result && typeof result === "object" && "code" in result) {
|
|
13133
|
-
const
|
|
13588
|
+
const requestGlobalsInjectedResult = injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets);
|
|
13589
|
+
const platform = getMiniProgramPlatformGlobalKey(configService.platform) ?? "";
|
|
13134
13590
|
const injectedCode = createWeapiInjectionCode({
|
|
13135
13591
|
globalName: injectOptions.globalName,
|
|
13136
13592
|
replaceWx: injectOptions.replaceWx,
|
|
13137
13593
|
platform
|
|
13138
13594
|
});
|
|
13139
13595
|
return replacePlatformApiInLoadResult({
|
|
13140
|
-
...
|
|
13141
|
-
code: `${injectedCode}${
|
|
13596
|
+
...requestGlobalsInjectedResult,
|
|
13597
|
+
code: `${injectedCode}${requestGlobalsInjectedResult.code}`
|
|
13142
13598
|
}, injectOptions, this);
|
|
13143
13599
|
}
|
|
13144
13600
|
return result;
|
|
13145
13601
|
}
|
|
13146
|
-
|
|
13147
|
-
|
|
13602
|
+
const declaredEntryType = state.entriesMap?.get(relativeBasename)?.type;
|
|
13603
|
+
const isDeclaredEntry = Boolean(declaredEntryType);
|
|
13604
|
+
if (loadedEntrySet.has(sourceId) || isDeclaredEntry || subPackageMeta?.entries.includes(relativeBasename)) {
|
|
13605
|
+
const loadType = declaredEntryType === "page" ? "page" : "component";
|
|
13148
13606
|
const result = await loadEntry.call(this, sourceId, loadType);
|
|
13149
|
-
|
|
13150
|
-
if (!
|
|
13151
|
-
return
|
|
13607
|
+
const requestGlobalsTargets = resolveRequestGlobalsTargets();
|
|
13608
|
+
if (!injectOptions || !injectOptions.replaceWx || configService.weappLibConfig?.enabled) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, { localBindings: true });
|
|
13609
|
+
if (!await ensureWeapiAvailable(this, sourceId)) return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, { localBindings: true });
|
|
13610
|
+
return injectRequestGlobalsIntoLoadResult(replacePlatformApiInLoadResult(result, injectOptions, this), sourceId, requestGlobalsTargets, { localBindings: true });
|
|
13152
13611
|
}
|
|
13153
13612
|
};
|
|
13154
13613
|
}
|
|
@@ -13162,6 +13621,8 @@ function resolveInjectWeapiOptions(configService) {
|
|
|
13162
13621
|
return { globalName: injectWeapi.globalName?.trim() || "wpi" };
|
|
13163
13622
|
}
|
|
13164
13623
|
function shouldTransformId(id, absoluteSrcRoot) {
|
|
13624
|
+
if (isCSSRequest(id)) return false;
|
|
13625
|
+
if (parseRequest(id).query.type === "style") return false;
|
|
13165
13626
|
const sourceId = normalizeFsResolvedId(id);
|
|
13166
13627
|
if (!sourceId || sourceId.includes("/node_modules/")) return false;
|
|
13167
13628
|
if (sourceId === absoluteSrcRoot) return true;
|
|
@@ -13198,11 +13659,30 @@ function replacePlatformApiAccess(code, globalName, options) {
|
|
|
13198
13659
|
function createTransformHook(state) {
|
|
13199
13660
|
const { configService } = state.ctx;
|
|
13200
13661
|
const astEngine = resolveAstEngine(configService.weappViteConfig);
|
|
13662
|
+
const injectRequestGlobalsOptions = resolveInjectRequestGlobalsOptions(configService.weappViteConfig?.injectRequestGlobals, configService.packageJson);
|
|
13663
|
+
function resolveRequestGlobalsTransformCode(id, code) {
|
|
13664
|
+
if (!injectRequestGlobalsOptions?.targets?.length) return null;
|
|
13665
|
+
if (code.includes("__weappViteInstallRequestGlobals")) return null;
|
|
13666
|
+
const sourceId = normalizeFsResolvedId(id);
|
|
13667
|
+
if (!sourceId) return null;
|
|
13668
|
+
const relativeBasename = removeExtensionDeep(configService.relativeAbsoluteSrcRoot(sourceId));
|
|
13669
|
+
const declaredEntryType = state.entriesMap?.get(relativeBasename)?.type;
|
|
13670
|
+
const isLoadedEntry = state.loadedEntrySet?.has(sourceId) === true;
|
|
13671
|
+
const isRootEntry = relativeBasename === "app";
|
|
13672
|
+
if (!isLoadedEntry && declaredEntryType !== "page" && declaredEntryType !== "component") return null;
|
|
13673
|
+
if (isLoadedEntry && isRootEntry) return null;
|
|
13674
|
+
if (sourceId.endsWith(".vue") && code.includes("<")) return injectRequestGlobalsIntoSfc(code, injectRequestGlobalsOptions.targets, { localBindings: true });
|
|
13675
|
+
return `${createInjectRequestGlobalsCode(injectRequestGlobalsOptions.targets, { localBindings: true })}${code}`;
|
|
13676
|
+
}
|
|
13201
13677
|
return async function transform(code, id) {
|
|
13202
13678
|
const injectOptions = resolveInjectWeapiOptions(configService);
|
|
13203
|
-
if (!injectOptions) return null;
|
|
13204
13679
|
if (!shouldTransformId(id, configService.absoluteSrcRoot)) return null;
|
|
13205
|
-
const
|
|
13680
|
+
const nextCode = resolveRequestGlobalsTransformCode(id, code) ?? code;
|
|
13681
|
+
if (!injectOptions) return nextCode === code ? null : {
|
|
13682
|
+
code: nextCode,
|
|
13683
|
+
map: null
|
|
13684
|
+
};
|
|
13685
|
+
const replaced = replacePlatformApiAccess(nextCode, injectOptions.globalName, {
|
|
13206
13686
|
engine: astEngine,
|
|
13207
13687
|
parserLike: this
|
|
13208
13688
|
});
|
|
@@ -16256,8 +16736,11 @@ async function emitVueBundleAssets(bundle, state) {
|
|
|
16256
16736
|
//#endregion
|
|
16257
16737
|
//#region src/plugins/vue/transform/plugin/shared.ts
|
|
16258
16738
|
const APP_ENTRY_RE = /[\\/]app\.(?:vue|jsx|tsx)$/;
|
|
16259
|
-
const AUTO_ROUTES_DEFAULT_IMPORT_RE = /import\s+([A-Za-z_$][\w$]*)\s+from\s+['"](?:weapp-vite\/auto-routes|virtual:weapp-vite-auto-routes)['"];?/g;
|
|
16260
16739
|
const AUTO_ROUTES_DYNAMIC_IMPORT_RE = /import\(\s*['"](?:weapp-vite\/auto-routes|virtual:weapp-vite-auto-routes)['"]\s*\)/g;
|
|
16740
|
+
const AUTO_ROUTES_ID = "weapp-vite/auto-routes";
|
|
16741
|
+
const AUTO_ROUTES_VIRTUAL_ID = "virtual:weapp-vite-auto-routes";
|
|
16742
|
+
const AUTO_ROUTES_NAMED_IMPORT_ALIAS_RE = /\s+as\s+/g;
|
|
16743
|
+
const AUTO_ROUTES_DEFAULT_AND_NAMED_IMPORT_RE = /^([A-Z_$][\w$]*)\s*,\s*(\{[^}]+\})$/i;
|
|
16261
16744
|
const TEMPLATE_DYNAMIC_HINT_RE = /\{\{|wx:|bind[A-Za-z:_-]+=|catch[A-Za-z:_-]+=/;
|
|
16262
16745
|
const PAGE_FEATURE_HOOK_HINTS = [
|
|
16263
16746
|
"onPageScroll",
|
|
@@ -16291,7 +16774,25 @@ function mayNeedTransformPageScrollDiagnostics(script) {
|
|
|
16291
16774
|
return script.includes(PAGE_SCROLL_HOOK_HINT);
|
|
16292
16775
|
}
|
|
16293
16776
|
function mayNeedInlineAutoRoutes(source) {
|
|
16294
|
-
return
|
|
16777
|
+
return source.includes(AUTO_ROUTES_ID) || source.includes(AUTO_ROUTES_VIRTUAL_ID);
|
|
16778
|
+
}
|
|
16779
|
+
function toObjectDestructureClause(namedImportClause) {
|
|
16780
|
+
return namedImportClause.replace(AUTO_ROUTES_NAMED_IMPORT_ALIAS_RE, ": ");
|
|
16781
|
+
}
|
|
16782
|
+
function resolveInlineAutoRoutesImport(line, inlineRoutes, replacementIndex) {
|
|
16783
|
+
const trimmedLine = line.trim();
|
|
16784
|
+
if (!trimmedLine.startsWith("import ") || !trimmedLine.includes(" from ") || !trimmedLine.includes(`'${AUTO_ROUTES_ID}'`) && !trimmedLine.includes(`"${AUTO_ROUTES_ID}"`) && !trimmedLine.includes(`'${AUTO_ROUTES_VIRTUAL_ID}'`) && !trimmedLine.includes(`"${AUTO_ROUTES_VIRTUAL_ID}"`)) return;
|
|
16785
|
+
const clause = trimmedLine.slice(7, trimmedLine.lastIndexOf(" from ")).trim();
|
|
16786
|
+
const inlineLiteral = JSON.stringify(inlineRoutes);
|
|
16787
|
+
if (clause.startsWith("{")) return `const ${toObjectDestructureClause(clause)} = ${inlineLiteral};`;
|
|
16788
|
+
if (clause.startsWith("* as ")) return `const ${clause.slice(5).trim()} = ${inlineLiteral};`;
|
|
16789
|
+
const defaultAndNamedMatch = clause.match(AUTO_ROUTES_DEFAULT_AND_NAMED_IMPORT_RE);
|
|
16790
|
+
if (defaultAndNamedMatch) {
|
|
16791
|
+
const [, defaultName, namedClause] = defaultAndNamedMatch;
|
|
16792
|
+
const localRef = `__weappViteAutoRoutesInline${replacementIndex}`;
|
|
16793
|
+
return `const ${localRef} = ${inlineLiteral};\nconst ${defaultName} = ${localRef};\nconst ${toObjectDestructureClause(namedClause)} = ${localRef};`;
|
|
16794
|
+
}
|
|
16795
|
+
return `const ${clause} = ${inlineLiteral};`;
|
|
16295
16796
|
}
|
|
16296
16797
|
function createTransformStageMeasurer(vueTransformTiming) {
|
|
16297
16798
|
const stageTimings = {};
|
|
@@ -16444,7 +16945,6 @@ function finalizeTransformEntryCode(options) {
|
|
|
16444
16945
|
async function inlineTransformAutoRoutes(options) {
|
|
16445
16946
|
const { source, autoRoutesService } = options;
|
|
16446
16947
|
if (!mayNeedInlineAutoRoutes(source)) return source;
|
|
16447
|
-
AUTO_ROUTES_DEFAULT_IMPORT_RE.lastIndex = 0;
|
|
16448
16948
|
AUTO_ROUTES_DYNAMIC_IMPORT_RE.lastIndex = 0;
|
|
16449
16949
|
await autoRoutesService?.ensureFresh?.();
|
|
16450
16950
|
const routesRef = autoRoutesService?.getReference?.();
|
|
@@ -16453,7 +16953,15 @@ async function inlineTransformAutoRoutes(options) {
|
|
|
16453
16953
|
entries: routesRef?.entries ?? [],
|
|
16454
16954
|
subPackages: routesRef?.subPackages ?? []
|
|
16455
16955
|
};
|
|
16456
|
-
|
|
16956
|
+
let importReplacementIndex = 0;
|
|
16957
|
+
return source.split("\n").map((line) => {
|
|
16958
|
+
const replaced = resolveInlineAutoRoutesImport(line, inlineRoutes, importReplacementIndex);
|
|
16959
|
+
if (replaced) {
|
|
16960
|
+
importReplacementIndex += 1;
|
|
16961
|
+
return replaced;
|
|
16962
|
+
}
|
|
16963
|
+
return line;
|
|
16964
|
+
}).join("\n").replace(AUTO_ROUTES_DYNAMIC_IMPORT_RE, `Promise.resolve(${JSON.stringify(inlineRoutes)})`);
|
|
16457
16965
|
}
|
|
16458
16966
|
async function resolveTransformEntryFlags(options) {
|
|
16459
16967
|
const { pageMatcher, setPageMatcher, createPageMatcher, configService, scanService, scanDirty, filename } = options;
|
|
@@ -18974,15 +19482,17 @@ function createScanService(ctx) {
|
|
|
18974
19482
|
const appDirname = ctx.configService.absoluteSrcRoot;
|
|
18975
19483
|
const appBasename = resolveScanAppBasename(appDirname);
|
|
18976
19484
|
let { path: appConfigFile } = await findJsonEntry(appBasename);
|
|
19485
|
+
const discoveredAppConfigFile = appConfigFile;
|
|
18977
19486
|
const { path: appEntryPath } = await findJsEntry(appBasename);
|
|
19487
|
+
const vueAppPath = await findVueEntry(appBasename);
|
|
18978
19488
|
let configFromVue;
|
|
18979
|
-
let vueAppPath;
|
|
18980
|
-
if (!appEntryPath) vueAppPath = await findVueEntry(appBasename);
|
|
18981
19489
|
if (!appConfigFile && vueAppPath) {
|
|
18982
|
-
const { extractConfigFromVue } = await import("./file-
|
|
19490
|
+
const { extractConfigFromVue } = await import("./file-WyRp0uK0.mjs").then((n) => n.r);
|
|
18983
19491
|
configFromVue = await extractConfigFromVue(vueAppPath);
|
|
18984
19492
|
if (configFromVue) appConfigFile = vueAppPath;
|
|
18985
19493
|
}
|
|
19494
|
+
if (appEntryPath && vueAppPath) logger_default.warn(`[app] 检测到 ${path.basename(appEntryPath)} 与 ${path.basename(vueAppPath)} 同时存在,当前将优先使用 ${path.basename(appEntryPath)} 作为应用入口,${path.basename(vueAppPath)} 将被忽略。`);
|
|
19495
|
+
if (discoveredAppConfigFile && vueAppPath) logger_default.warn(`[app] 检测到 ${path.basename(discoveredAppConfigFile)} 与 ${path.basename(vueAppPath)} 同时存在,当前将优先使用 ${path.basename(discoveredAppConfigFile)} 作为应用配置来源,${path.basename(vueAppPath)} 中的 app 配置不会生效。`);
|
|
18986
19496
|
if (ctx.configService.absolutePluginRoot) {
|
|
18987
19497
|
const { path: pluginConfigFile } = await findJsonEntry(resolveScanPluginBasename(ctx.configService.absolutePluginRoot));
|
|
18988
19498
|
if (pluginConfigFile) {
|