@uni-helper/vite-plugin-uni-pages 0.5.0 → 0.6.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 +562 -54
- package/dist/index.d.mts +630 -282
- package/dist/index.mjs +3011 -595
- package/package.json +13 -8
package/dist/index.mjs
CHANGED
|
@@ -1,25 +1,628 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
+
import fs, { existsSync, mkdirSync, realpathSync } from "node:fs";
|
|
2
3
|
import path, { dirname, extname, join, resolve } from "node:path";
|
|
3
4
|
import process from "node:process";
|
|
4
5
|
import chokidar from "chokidar";
|
|
5
6
|
import MagicString from "magic-string";
|
|
6
7
|
import { createLogger, normalizePath } from "vite";
|
|
8
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { bundleRequire } from "bundle-require";
|
|
11
|
+
import { loadConfig } from "unconfig";
|
|
12
|
+
import { Buffer } from "node:buffer";
|
|
13
|
+
import babelGenerate from "@babel/generator";
|
|
14
|
+
import * as t from "@babel/types";
|
|
15
|
+
import { callExpression, identifier, removePropertiesDeep } from "@babel/types";
|
|
16
|
+
import { babelParse, isCallOf, walkAST } from "ast-kit";
|
|
17
|
+
import { transform } from "esbuild";
|
|
18
|
+
import Debug from "debug";
|
|
7
19
|
import { platform } from "@uni-helper/uni-env";
|
|
8
20
|
import { CommentArray, parse, stringify } from "comment-json";
|
|
9
|
-
import Debug from "debug";
|
|
10
21
|
import groupBy from "lodash.groupby";
|
|
11
|
-
import { loadConfig } from "unconfig";
|
|
12
|
-
import fs, { existsSync } from "node:fs";
|
|
13
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
14
22
|
import lockfile from "proper-lockfile";
|
|
15
|
-
import { globSync } from "tinyglobby";
|
|
23
|
+
import { escapePath, globSync, isDynamicPattern } from "tinyglobby";
|
|
24
|
+
import picomatch from "picomatch";
|
|
16
25
|
import vm from "node:vm";
|
|
17
|
-
import babelGenerate from "@babel/generator";
|
|
18
|
-
import * as t from "@babel/types";
|
|
19
26
|
import { parse as parse$1 } from "@vue/compiler-sfc";
|
|
20
|
-
import { babelParse, isCallOf } from "ast-kit";
|
|
21
27
|
import * as ts from "typescript";
|
|
22
28
|
import writeFileAtomic from "write-file-atomic";
|
|
29
|
+
//#region src/config-source.ts
|
|
30
|
+
/** 加载器给 import.meta 提供取值的成员,其余成员保持 undefined */
|
|
31
|
+
const providedMetaMembers = /* @__PURE__ */ new Set([
|
|
32
|
+
"dirname",
|
|
33
|
+
"env",
|
|
34
|
+
"filename",
|
|
35
|
+
"main",
|
|
36
|
+
"resolve",
|
|
37
|
+
"url"
|
|
38
|
+
]);
|
|
39
|
+
/**
|
|
40
|
+
* 找出模块里访问了加载器不提供的 import.meta 成员的位置
|
|
41
|
+
*
|
|
42
|
+
* @description 只在源码出现 `import.meta` 时解析;语法错误留给 esbuild 报,这里不重复
|
|
43
|
+
* @param code 模块的原始源码,必须早于 esbuild 的 define 替换
|
|
44
|
+
* @param filename 模块的绝对路径,决定按 TS 还是 JS 语法解析
|
|
45
|
+
* @returns 按源码顺序排列的每处访问
|
|
46
|
+
*/
|
|
47
|
+
function findUnprovidedMetaMembers(code, filename) {
|
|
48
|
+
if (!code.includes("import.meta")) return [];
|
|
49
|
+
const extension = path.extname(filename).slice(1);
|
|
50
|
+
const lang = extension === "tsx" ? "tsx" : extension === "jsx" ? "jsx" : /^(?:ts|mts|cts)$/.test(extension) ? "ts" : "js";
|
|
51
|
+
let ast;
|
|
52
|
+
try {
|
|
53
|
+
ast = babelParse(code, lang, { allowReturnOutsideFunction: true });
|
|
54
|
+
} catch {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
const warnings = [];
|
|
58
|
+
walkAST(ast, { enter(node) {
|
|
59
|
+
if (node.type !== "MemberExpression" || node.object.type !== "MetaProperty") return;
|
|
60
|
+
if (node.object.meta.name !== "import" || node.object.property.name !== "meta") return;
|
|
61
|
+
const member = node.property.type === "Identifier" ? node.property.name : node.property.type === "StringLiteral" ? node.property.value : void 0;
|
|
62
|
+
if (member === void 0 || providedMetaMembers.has(member)) return;
|
|
63
|
+
warnings.push({
|
|
64
|
+
file: filename,
|
|
65
|
+
line: node.loc?.start.line ?? 0,
|
|
66
|
+
column: (node.loc?.start.column ?? 0) + 1,
|
|
67
|
+
member
|
|
68
|
+
});
|
|
69
|
+
} });
|
|
70
|
+
return warnings;
|
|
71
|
+
}
|
|
72
|
+
/** 判断导入表达式能否交给 esbuild 收集依赖,未匹配的目标由运行时助手解析 */
|
|
73
|
+
function isBundledSpecifier(node) {
|
|
74
|
+
if (!node) return false;
|
|
75
|
+
if (node.type === "StringLiteral") return true;
|
|
76
|
+
if (node.type === "TemplateLiteral") return node.expressions.length === 0 || /^\.\.?\//.test(node.quasis[0].value.cooked ?? "");
|
|
77
|
+
if (node.type === "BinaryExpression" && node.operator === "+") {
|
|
78
|
+
let first = node.left;
|
|
79
|
+
while (first.type === "BinaryExpression" && first.operator === "+") first = first.left;
|
|
80
|
+
return first.type === "StringLiteral" && /^\.\.?\//.test(first.value);
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* 将脚本转换为绑定原文件位置的 JavaScript
|
|
86
|
+
*
|
|
87
|
+
* @description 注入运行时解析助手;可打包的调用及用户声明的局部 require 保持原语义
|
|
88
|
+
* import.meta 的解构、别名和计算式访问使用当前模块的源位置,各模块共享同一份 env
|
|
89
|
+
* @param code 当前模块的源码文本
|
|
90
|
+
* @param filename 当前模块的原始绝对路径,作为该模块运行时解析的基准
|
|
91
|
+
* @param runtime 本轮生成的公共辅助模块路径,供转换后的代码导入
|
|
92
|
+
* @returns 转换后的 JavaScript 及其发现的 import.meta 成员问题
|
|
93
|
+
*/
|
|
94
|
+
async function transformConfigSource(code, filename, runtime) {
|
|
95
|
+
let prefix = "__uni_pages_source";
|
|
96
|
+
while (code.includes(prefix)) prefix += "_";
|
|
97
|
+
const requireName = `${prefix}_require`;
|
|
98
|
+
const metaName = `${prefix}_meta`;
|
|
99
|
+
const importName = `${prefix}_import`;
|
|
100
|
+
const extension = path.extname(filename).slice(1);
|
|
101
|
+
const loader = extension === "jsx" || extension === "tsx" ? extension : /^(?:c|m)?js$/.test(extension) ? "js" : "ts";
|
|
102
|
+
const directory = path.dirname(filename);
|
|
103
|
+
const url = pathToFileURL(filename).href;
|
|
104
|
+
const result = await transform(code, {
|
|
105
|
+
loader,
|
|
106
|
+
sourcefile: filename,
|
|
107
|
+
sourcemap: "external",
|
|
108
|
+
target: "node22",
|
|
109
|
+
define: {
|
|
110
|
+
"require": requireName,
|
|
111
|
+
"import.meta": metaName,
|
|
112
|
+
"__dirname": JSON.stringify(directory),
|
|
113
|
+
"__filename": JSON.stringify(filename)
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
const ast = babelParse(result.code, "js", { allowReturnOutsideFunction: true });
|
|
117
|
+
walkAST(ast, { enter(node) {
|
|
118
|
+
if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === requireName && isBundledSpecifier(node.arguments[0])) node.callee.name = "require";
|
|
119
|
+
if (node.type === "ImportExpression" && !isBundledSpecifier(node.source)) this.replace(callExpression(identifier(importName), [node.source, ...node.options ? [node.options] : []]));
|
|
120
|
+
} });
|
|
121
|
+
const helpers = babelParse(`
|
|
122
|
+
import { createRequire as ${prefix}_createRequire, createMeta as ${prefix}_createMeta, importFrom as ${prefix}_importFrom } from ${JSON.stringify(runtime)};
|
|
123
|
+
const ${requireName} = ${prefix}_createRequire(${JSON.stringify(filename)});
|
|
124
|
+
const ${metaName} = ${prefix}_createMeta(${JSON.stringify(filename)}, ${JSON.stringify(url)}, ${JSON.stringify(directory)});
|
|
125
|
+
const ${importName} = (specifier, options) => ${prefix}_importFrom(specifier, ${JSON.stringify(url)}, options);
|
|
126
|
+
`, "js");
|
|
127
|
+
removePropertiesDeep(helpers);
|
|
128
|
+
ast.body.unshift(...helpers.body);
|
|
129
|
+
const output = babelGenerate(ast, {
|
|
130
|
+
sourceMaps: true,
|
|
131
|
+
sourceFileName: filename,
|
|
132
|
+
inputSourceMap: JSON.parse(result.map)
|
|
133
|
+
}, result.code);
|
|
134
|
+
return {
|
|
135
|
+
code: `${output.code}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(output.map)).toString("base64")}`,
|
|
136
|
+
warnings: findUnprovidedMetaMembers(code, filename)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* 生成配置执行所需的公共辅助模块源码
|
|
141
|
+
*
|
|
142
|
+
* @description 调用方将返回文本写入本轮 runtime.mjs;env 是配置图里 import.meta.env 的唯一一份
|
|
143
|
+
* @param env import.meta.env 的值,来自 Vite 解析后的 config.env 或进程环境兜底
|
|
144
|
+
* @param define Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
145
|
+
* @returns 供配置打包使用的 ESM 源码
|
|
146
|
+
*/
|
|
147
|
+
async function configRuntimeSource(env, define = {}) {
|
|
148
|
+
const prefix = "import.meta.env.";
|
|
149
|
+
const overrides = Object.entries(define).filter(([key]) => key.startsWith(prefix));
|
|
150
|
+
let envSource = `export const env = ${JSON.stringify(env)};`;
|
|
151
|
+
if (overrides.length) {
|
|
152
|
+
const values = overrides.map(([key]) => `${JSON.stringify(key.slice(16))}: () => ${key}`);
|
|
153
|
+
const transformed = await transform(`const overrides = { ${values.join(", ")} };`, {
|
|
154
|
+
loader: "js",
|
|
155
|
+
target: "node22",
|
|
156
|
+
define: Object.fromEntries(overrides.map(([key, value]) => [key, typeof value === "string" ? value : JSON.stringify(value) ?? "undefined"]))
|
|
157
|
+
});
|
|
158
|
+
envSource += `
|
|
159
|
+
${transformed.code}
|
|
160
|
+
function setEnvValue(key, value) {
|
|
161
|
+
Object.defineProperty(env, key, { value, enumerable: true, configurable: true, writable: true });
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
for (const [key, read] of Object.entries(overrides)) {
|
|
165
|
+
let loaded = false;
|
|
166
|
+
let value;
|
|
167
|
+
Object.defineProperty(env, key, {
|
|
168
|
+
enumerable: true,
|
|
169
|
+
configurable: true,
|
|
170
|
+
get() {
|
|
171
|
+
if (!loaded) {
|
|
172
|
+
value = read();
|
|
173
|
+
loaded = true;
|
|
174
|
+
}
|
|
175
|
+
if (Object.getOwnPropertyDescriptor(env, key)?.configurable)
|
|
176
|
+
setEnvValue(key, value);
|
|
177
|
+
return value;
|
|
178
|
+
},
|
|
179
|
+
set: value => setEnvValue(key, value),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
`;
|
|
183
|
+
}
|
|
184
|
+
return `
|
|
185
|
+
export { createRequire } from 'node:module';
|
|
186
|
+
import { resolve } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("import-meta-resolve")).href)};
|
|
187
|
+
${envSource}
|
|
188
|
+
export function resolveFrom(specifier, url) {
|
|
189
|
+
return resolve(\`\${specifier}\`, url);
|
|
190
|
+
}
|
|
191
|
+
export function createMeta(filename, url, dirname) {
|
|
192
|
+
return Object.assign(Object.create(null), { filename, url, dirname, main: false, resolve: specifier => resolveFrom(specifier, url), env });
|
|
193
|
+
}
|
|
194
|
+
export async function importFrom(specifier, url, options) {
|
|
195
|
+
return import(resolve(\`\${specifier}\`, url), options);
|
|
196
|
+
}
|
|
197
|
+
`;
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/logger.ts
|
|
201
|
+
/**
|
|
202
|
+
* 调试日志工具
|
|
203
|
+
* 基于 debug 包做分级日志输出
|
|
204
|
+
* 通过环境变量 DEBUG=vite-plugin-uni-pages:* 开启
|
|
205
|
+
*/
|
|
206
|
+
const debug = {
|
|
207
|
+
/** HMR 相关日志 */
|
|
208
|
+
hmr: Debug("vite-plugin-uni-pages:hmr"),
|
|
209
|
+
/** 配置项相关日志 */
|
|
210
|
+
options: Debug("vite-plugin-uni-pages:options"),
|
|
211
|
+
/** 主包页面扫描日志 */
|
|
212
|
+
pages: Debug("vite-plugin-uni-pages:pages"),
|
|
213
|
+
/** 分包页面扫描日志 */
|
|
214
|
+
subPages: Debug("vite-plugin-uni-pages:subPages"),
|
|
215
|
+
/** 错误日志 */
|
|
216
|
+
error: Debug("vite-plugin-uni-pages:error"),
|
|
217
|
+
/** 缓存相关日志 */
|
|
218
|
+
cache: Debug("vite-plugin-uni-pages:cache"),
|
|
219
|
+
/** 声明文件生成日志 */
|
|
220
|
+
declaration: Debug("vite-plugin-uni-pages:declaration"),
|
|
221
|
+
/** definePage 宏解析日志 */
|
|
222
|
+
definePage: Debug("vite-plugin-uni-pages:definePage")
|
|
223
|
+
};
|
|
224
|
+
//#endregion
|
|
225
|
+
//#region src/config-loader.ts
|
|
226
|
+
const scriptExtensions = /\.[cm]?[jt]sx?$/;
|
|
227
|
+
/** 目录恢复监听接受的文件类型;已知配置入口与依赖不受此限制 */
|
|
228
|
+
const configFileExtensions = /\.(?:[cm]?[jt]sx?|json)$/;
|
|
229
|
+
/** 省略扩展名时 esbuild 会依次尝试的后缀,用于列举恢复候选文件 */
|
|
230
|
+
const candidateExtensions = [
|
|
231
|
+
"",
|
|
232
|
+
".ts",
|
|
233
|
+
".tsx",
|
|
234
|
+
".js",
|
|
235
|
+
".jsx",
|
|
236
|
+
".mts",
|
|
237
|
+
".cts",
|
|
238
|
+
".mjs",
|
|
239
|
+
".cjs",
|
|
240
|
+
".json"
|
|
241
|
+
];
|
|
242
|
+
/** TS 约定里 `./x.js` 指向的就是 `./x.ts`,恢复候选也得列上 */
|
|
243
|
+
const typescriptAliases = {
|
|
244
|
+
".cjs": [".cts"],
|
|
245
|
+
".js": [".ts", ".tsx"],
|
|
246
|
+
".mjs": [".mts"]
|
|
247
|
+
};
|
|
248
|
+
function isNodeModulesPath(filepath) {
|
|
249
|
+
return normalizePath(filepath).split("/").includes("node_modules");
|
|
250
|
+
}
|
|
251
|
+
/** JSON 文件可能带 BOM 保存,JSON.parse 不接受它 */
|
|
252
|
+
function stripBom(code) {
|
|
253
|
+
return code.charCodeAt(0) === 65279 ? code.slice(1) : code;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* 由失败的导入说明符推出可能出现的文件
|
|
257
|
+
*
|
|
258
|
+
* @description `./missing/title` 这种缺扩展名的写法,创建 `title.ts`
|
|
259
|
+
* 或 `title/index.ts` 都算恢复,所以两种形态都要列出来
|
|
260
|
+
*/
|
|
261
|
+
function recoveryCandidatesFor(specifier, importerDirectory) {
|
|
262
|
+
const base = path.resolve(importerDirectory, specifier);
|
|
263
|
+
const candidates = candidateExtensions.map((extension) => `${base}${extension}`);
|
|
264
|
+
for (const extension of candidateExtensions.slice(1)) candidates.push(path.join(base, `index${extension}`));
|
|
265
|
+
for (const [extension, aliases] of Object.entries(typescriptAliases)) if (base.endsWith(extension)) for (const alias of aliases) candidates.push(`${base.slice(0, -extension.length)}${alias}`);
|
|
266
|
+
return candidates;
|
|
267
|
+
}
|
|
268
|
+
/** 将已存在和暂时缺失的文件统一到同一绝对路径 */
|
|
269
|
+
function normalizeConfigPath(filepath, root) {
|
|
270
|
+
const absolute = path.resolve(root, normalizePath(filepath));
|
|
271
|
+
let parent = absolute;
|
|
272
|
+
while (!existsSync(parent) && path.dirname(parent) !== parent) parent = path.dirname(parent);
|
|
273
|
+
try {
|
|
274
|
+
return normalizePath(path.join(realpathSync.native(parent), path.relative(parent, absolute)));
|
|
275
|
+
} catch {
|
|
276
|
+
return normalizePath(absolute);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** 返回可用于监听缺失文件恢复的现存祖先目录 */
|
|
280
|
+
function configWatchDirectory(filepath) {
|
|
281
|
+
let directory = path.dirname(filepath);
|
|
282
|
+
while (!existsSync(directory) && path.dirname(directory) !== directory) directory = path.dirname(directory);
|
|
283
|
+
return normalizePath(directory);
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* 判断路径是否位于加载器专用产物目录内
|
|
287
|
+
*
|
|
288
|
+
* @param filepath 待判断的绝对路径,应已通过 {@link normalizeConfigPath} 归一化
|
|
289
|
+
* @param directory 专用产物目录的绝对路径;目录本身也算产物
|
|
290
|
+
* @returns 位于目录内时返回 true,相邻前缀或父路径返回 false
|
|
291
|
+
*/
|
|
292
|
+
function isConfigLoaderArtifact(filepath, directory) {
|
|
293
|
+
const relative = path.relative(directory, filepath);
|
|
294
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* 没有 Vite 配置时的 import.meta.env
|
|
298
|
+
*
|
|
299
|
+
* @description 只给 Vite 会在 app 代码里提供的键:前缀变量加标准键。
|
|
300
|
+
* prepare() 在 Vite 解析配置之前运行,`.env` 文件的值此时还没有人读过
|
|
301
|
+
*/
|
|
302
|
+
function fallbackConfigEnv() {
|
|
303
|
+
const env = {};
|
|
304
|
+
for (const [key, value] of Object.entries(process.env)) if (value !== void 0 && key.startsWith("VITE_")) env[key] = value;
|
|
305
|
+
const production = process.env.NODE_ENV === "production";
|
|
306
|
+
return {
|
|
307
|
+
...env,
|
|
308
|
+
BASE_URL: "/",
|
|
309
|
+
MODE: process.env.NODE_ENV ?? "development",
|
|
310
|
+
DEV: !production,
|
|
311
|
+
PROD: production,
|
|
312
|
+
SSR: false
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* 页面配置加载器
|
|
317
|
+
*
|
|
318
|
+
* @description 按配置源顺序发现并加载首个有效配置,返回配置对象及依赖路径;加载失败时记录恢复路径并抛出错误
|
|
319
|
+
*/
|
|
320
|
+
var PagesConfigLoader = class {
|
|
321
|
+
root;
|
|
322
|
+
/** 装载失败时仍需监听重建的入口与已尝试路径 */
|
|
323
|
+
recoveryPaths = /* @__PURE__ */ new Set();
|
|
324
|
+
/** 这次失败中具体缺哪个文件;优先按它判断,命中时不看目录 */
|
|
325
|
+
recoveryCandidates = /* @__PURE__ */ new Set();
|
|
326
|
+
/** 目录导入的恢复范围,覆盖 package.json 和自定义入口 */
|
|
327
|
+
recoveryDirectories = /* @__PURE__ */ new Set();
|
|
328
|
+
knownSources = /* @__PURE__ */ new Set();
|
|
329
|
+
/** 临时工作目录的物理路径,每轮加载创建独占子目录,输入索引与事件过滤排除此目录 */
|
|
330
|
+
artifactDirectory;
|
|
331
|
+
/** 最近一次成功加载的入口及其依赖,失败恢复以它为基准 */
|
|
332
|
+
lastSources = [];
|
|
333
|
+
lastDependencies = [];
|
|
334
|
+
/** 最近一次加载尝试的监听输入;失败时也保留可恢复路径 */
|
|
335
|
+
currentWatchInput = {
|
|
336
|
+
sources: [],
|
|
337
|
+
dependencies: [],
|
|
338
|
+
recoveryCandidates: [],
|
|
339
|
+
recoveryDirectories: []
|
|
340
|
+
};
|
|
341
|
+
/** 配置图里 import.meta.env 的值,Vite 会话就绪后可能被替换 */
|
|
342
|
+
env;
|
|
343
|
+
envDefine = {};
|
|
344
|
+
/** 是否已接收当前 Vite 会话的环境 */
|
|
345
|
+
envFromVite = false;
|
|
346
|
+
warn;
|
|
347
|
+
/** 同一文件同一成员只提示一次;watch 每轮都会重新转换所有输入 */
|
|
348
|
+
reportedMetaMembers = /* @__PURE__ */ new Set();
|
|
349
|
+
/**
|
|
350
|
+
* @param root - 项目根目录,配置入口和依赖都按它解析
|
|
351
|
+
* @param warn - 提示出口,同一文件同一成员只调用一次
|
|
352
|
+
*/
|
|
353
|
+
constructor(root, warn) {
|
|
354
|
+
this.root = root;
|
|
355
|
+
this.artifactDirectory = normalizeConfigPath(path.join(root, "node_modules/.cache/uni-pages"), root);
|
|
356
|
+
this.env = fallbackConfigEnv();
|
|
357
|
+
this.warn = warn;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* 替换配置图里 import.meta.env 的值
|
|
361
|
+
*
|
|
362
|
+
* @param env - Vite 解析后的环境值;下一轮加载生效
|
|
363
|
+
* @param define - Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
364
|
+
* @returns 首次用上 Vite 的 env 时为 `true`,之前生成的 pages.json 需要重算;再次设置返回 `false`
|
|
365
|
+
*/
|
|
366
|
+
setEnv(env, define = {}) {
|
|
367
|
+
const replaced = !this.envFromVite;
|
|
368
|
+
this.env = env;
|
|
369
|
+
this.envDefine = define;
|
|
370
|
+
this.envFromVite = true;
|
|
371
|
+
return replaced;
|
|
372
|
+
}
|
|
373
|
+
/** 把成员问题转成带文件位置的提示;同一文件同一成员只报一次 */
|
|
374
|
+
reportMetaWarnings(warnings) {
|
|
375
|
+
if (!this.warn) return;
|
|
376
|
+
for (const { file, line, column, member } of warnings) {
|
|
377
|
+
const key = `${file}\u0000${member}`;
|
|
378
|
+
if (this.reportedMetaMembers.has(key)) continue;
|
|
379
|
+
this.reportedMetaMembers.add(key);
|
|
380
|
+
this.warn(`${normalizePath(path.relative(this.root, file))}:${line}:${column} reads import.meta.${member}, which is not available while the pages config runs. Read environment values from process.env, and move other Vite-only access out of the config's import graph.`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** 监听输入是一份只读快照,调用方不需要理解加载器的恢复状态 */
|
|
384
|
+
get watchInput() {
|
|
385
|
+
return this.currentWatchInput;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* 按来源顺序加载首个有效配置
|
|
389
|
+
*
|
|
390
|
+
* @description 内置 parser 使用转换后的文本;自定义 parser 接收原入口路径并自行读取
|
|
391
|
+
* @returns 配置对象、已加载入口及参与监听的依赖路径;没有有效配置时配置对象为空
|
|
392
|
+
* @throws 配置读取、转换、解析或执行失败时抛出错误
|
|
393
|
+
*/
|
|
394
|
+
async load(sources) {
|
|
395
|
+
this.recoveryCandidates.clear();
|
|
396
|
+
this.recoveryDirectories.clear();
|
|
397
|
+
const dependencies = /* @__PURE__ */ new Set();
|
|
398
|
+
const attemptedPaths = /* @__PURE__ */ new Set();
|
|
399
|
+
const normalize = (filepath) => normalizeConfigPath(filepath, this.root);
|
|
400
|
+
const adapted = sources.map((source) => ({
|
|
401
|
+
...source,
|
|
402
|
+
transform: void 0,
|
|
403
|
+
parser: async (filepath) => {
|
|
404
|
+
attemptedPaths.add(normalize(filepath));
|
|
405
|
+
if (typeof source.parser === "function") {
|
|
406
|
+
if (source.transform) await source.transform(await readFile(filepath, "utf8"), filepath);
|
|
407
|
+
return source.parser(filepath);
|
|
408
|
+
}
|
|
409
|
+
let code = await readFile(filepath, "utf8");
|
|
410
|
+
if (source.transform) code = await source.transform(code, filepath) || code;
|
|
411
|
+
const parser = source.parser || "auto";
|
|
412
|
+
if (parser === "json" || path.extname(filepath) === ".json") return JSON.parse(stripBom(code));
|
|
413
|
+
if (parser === "auto") try {
|
|
414
|
+
return JSON.parse(stripBom(code));
|
|
415
|
+
} catch {}
|
|
416
|
+
return this.loadScript(filepath, code, dependencies, attemptedPaths);
|
|
417
|
+
}
|
|
418
|
+
}));
|
|
419
|
+
try {
|
|
420
|
+
const result = await loadConfig({
|
|
421
|
+
cwd: this.root,
|
|
422
|
+
sources: adapted,
|
|
423
|
+
defaults: {}
|
|
424
|
+
});
|
|
425
|
+
this.recoveryPaths.clear();
|
|
426
|
+
this.recoveryCandidates.clear();
|
|
427
|
+
this.recoveryDirectories.clear();
|
|
428
|
+
for (const source of result.sources) this.knownSources.add(normalize(source));
|
|
429
|
+
for (const source of this.knownSources) if (!existsSync(source)) dependencies.add(source);
|
|
430
|
+
const sources = result.sources.map(normalize);
|
|
431
|
+
const dependencyPaths = [...dependencies];
|
|
432
|
+
this.lastSources = sources;
|
|
433
|
+
this.lastDependencies = dependencyPaths;
|
|
434
|
+
this.currentWatchInput = {
|
|
435
|
+
sources,
|
|
436
|
+
dependencies: dependencyPaths,
|
|
437
|
+
recoveryCandidates: [],
|
|
438
|
+
recoveryDirectories: []
|
|
439
|
+
};
|
|
440
|
+
return {
|
|
441
|
+
config: result.config,
|
|
442
|
+
sources,
|
|
443
|
+
dependencies: dependencyPaths
|
|
444
|
+
};
|
|
445
|
+
} catch (error) {
|
|
446
|
+
this.recoveryPaths.clear();
|
|
447
|
+
for (const filepath of attemptedPaths) this.recoveryPaths.add(filepath);
|
|
448
|
+
this.currentWatchInput = {
|
|
449
|
+
sources: [...this.lastSources],
|
|
450
|
+
dependencies: [.../* @__PURE__ */ new Set([...this.lastDependencies, ...this.recoveryPaths])],
|
|
451
|
+
recoveryCandidates: [...this.recoveryCandidates],
|
|
452
|
+
recoveryDirectories: [...this.recoveryDirectories]
|
|
453
|
+
};
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* 打包并执行脚本配置,返回其导出的配置对象
|
|
459
|
+
*
|
|
460
|
+
* @param source 原配置入口路径,作为入口导入和运行时相对路径的解析基准
|
|
461
|
+
* @param code 经过可选 transform 处理的入口文本,依赖模块按各自路径读取
|
|
462
|
+
* @param dependencies 接收成功打包涉及的本地依赖路径
|
|
463
|
+
* @param attempted 接收本轮尝试读取的本地源路径,供执行失败后恢复监听
|
|
464
|
+
*/
|
|
465
|
+
async loadScript(source, code, dependencies, attempted) {
|
|
466
|
+
const sourcePath = normalizeConfigPath(source, this.root);
|
|
467
|
+
const metaWarnings = [];
|
|
468
|
+
const importDirectories = /* @__PURE__ */ new Set();
|
|
469
|
+
const recoveryCandidates = /* @__PURE__ */ new Set();
|
|
470
|
+
let bundled = false;
|
|
471
|
+
const root = this.root;
|
|
472
|
+
const cacheDirectory = this.artifactDirectory;
|
|
473
|
+
mkdirSync(cacheDirectory, { recursive: true });
|
|
474
|
+
const bundleDirectory = await mkdtemp(path.join(cacheDirectory, "load-"));
|
|
475
|
+
const runtime = normalizePath(path.join(bundleDirectory, "runtime.mjs"));
|
|
476
|
+
const entry = scriptExtensions.test(source) ? source : path.join(bundleDirectory, "entry.ts");
|
|
477
|
+
try {
|
|
478
|
+
await writeFile(runtime, await configRuntimeSource(this.env, this.envDefine));
|
|
479
|
+
const { mod, dependencies: inputs } = await bundleRequire({
|
|
480
|
+
filepath: entry,
|
|
481
|
+
cwd: this.root,
|
|
482
|
+
format: "esm",
|
|
483
|
+
tsconfig: false,
|
|
484
|
+
preserveTemporaryFile: true,
|
|
485
|
+
getOutputFile: () => path.join(bundleDirectory, "config.mjs"),
|
|
486
|
+
notExternal: [/.*/],
|
|
487
|
+
esbuildOptions: {
|
|
488
|
+
logLevel: "silent",
|
|
489
|
+
target: "node22",
|
|
490
|
+
conditions: [],
|
|
491
|
+
mainFields: ["main"],
|
|
492
|
+
resolveExtensions: [
|
|
493
|
+
".ts",
|
|
494
|
+
".tsx",
|
|
495
|
+
".mts",
|
|
496
|
+
".cts",
|
|
497
|
+
".js",
|
|
498
|
+
".jsx",
|
|
499
|
+
".mjs",
|
|
500
|
+
".cjs",
|
|
501
|
+
".json"
|
|
502
|
+
],
|
|
503
|
+
banner: { js: `import { createRequire as __uniPagesCreateRequire } from 'node:module'; const require = __uniPagesCreateRequire(import.meta.url);` },
|
|
504
|
+
plugins: [{
|
|
505
|
+
name: "uni-pages-config-inputs",
|
|
506
|
+
setup(build) {
|
|
507
|
+
build.onEnd((result) => {
|
|
508
|
+
if (result.errors.length === 0) bundled = true;
|
|
509
|
+
});
|
|
510
|
+
build.onResolve({ filter: /.*/ }, async (args) => {
|
|
511
|
+
if (args.kind === "entry-point") return { path: path.resolve(sourcePath) };
|
|
512
|
+
if (args.pluginData?.resolvingPackage) return;
|
|
513
|
+
if (/^(?:node:|file:|data:)/.test(args.path)) return {
|
|
514
|
+
path: args.path,
|
|
515
|
+
external: true
|
|
516
|
+
};
|
|
517
|
+
if (args.path.startsWith(".") || path.isAbsolute(args.path)) {
|
|
518
|
+
const directory = normalizeConfigPath(path.resolve(args.resolveDir, args.path), root);
|
|
519
|
+
if (!isNodeModulesPath(directory) && !isConfigLoaderArtifact(directory, cacheDirectory)) {
|
|
520
|
+
importDirectories.add(directory);
|
|
521
|
+
for (const candidate of recoveryCandidatesFor(args.path, args.resolveDir)) recoveryCandidates.add(normalizeConfigPath(candidate, root));
|
|
522
|
+
}
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
const result = await build.resolve(args.path, {
|
|
526
|
+
importer: args.importer,
|
|
527
|
+
resolveDir: args.resolveDir,
|
|
528
|
+
kind: args.kind,
|
|
529
|
+
namespace: args.namespace,
|
|
530
|
+
pluginData: { resolvingPackage: true }
|
|
531
|
+
});
|
|
532
|
+
if (result.errors.length) return {
|
|
533
|
+
errors: result.errors,
|
|
534
|
+
warnings: result.warnings
|
|
535
|
+
};
|
|
536
|
+
if (path.isAbsolute(result.path) && (!isNodeModulesPath(result.path) || /\.(?:[cm]?tsx?|json)$/.test(result.path))) return { path: result.path };
|
|
537
|
+
return {
|
|
538
|
+
path: !(args.kind === "require-call" || args.kind === "require-resolve") && path.isAbsolute(result.path) ? pathToFileURL(result.path).href : result.path,
|
|
539
|
+
external: true
|
|
540
|
+
};
|
|
541
|
+
});
|
|
542
|
+
build.onLoad({
|
|
543
|
+
filter: /.*/,
|
|
544
|
+
namespace: "file"
|
|
545
|
+
}, async (args) => {
|
|
546
|
+
const file = normalizeConfigPath(args.path, root);
|
|
547
|
+
if (file === runtime) return {
|
|
548
|
+
contents: await readFile(runtime, "utf8"),
|
|
549
|
+
loader: "js"
|
|
550
|
+
};
|
|
551
|
+
if (!isNodeModulesPath(file) && !isConfigLoaderArtifact(file, cacheDirectory)) attempted.add(file);
|
|
552
|
+
if (file !== sourcePath && !scriptExtensions.test(file)) return;
|
|
553
|
+
const transformed = await transformConfigSource(file === sourcePath ? code : await readFile(args.path, "utf8"), path.resolve(file), runtime);
|
|
554
|
+
metaWarnings.push(...transformed.warnings);
|
|
555
|
+
return {
|
|
556
|
+
contents: transformed.code,
|
|
557
|
+
loader: "js"
|
|
558
|
+
};
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
}]
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
for (const input of inputs) {
|
|
565
|
+
const file = normalizeConfigPath(input, root);
|
|
566
|
+
if (!isNodeModulesPath(file) && !isConfigLoaderArtifact(file, cacheDirectory)) dependencies.add(file);
|
|
567
|
+
}
|
|
568
|
+
for (const directory of importDirectories) {
|
|
569
|
+
const manifest = normalizeConfigPath(path.join(directory, "package.json"), root);
|
|
570
|
+
if (existsSync(manifest) && !isNodeModulesPath(manifest) && !isConfigLoaderArtifact(manifest, cacheDirectory)) dependencies.add(manifest);
|
|
571
|
+
}
|
|
572
|
+
return unwrapConfig(mod.default ?? mod);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
if (bundled && error instanceof Error) explainEvaluationError(error, normalizePath(path.relative(this.root, sourcePath)));
|
|
575
|
+
if (!bundled) {
|
|
576
|
+
for (const candidate of recoveryCandidates) if (!existsSync(candidate)) this.recoveryCandidates.add(candidate);
|
|
577
|
+
for (const directory of importDirectories) this.recoveryDirectories.add(directory);
|
|
578
|
+
}
|
|
579
|
+
throw error;
|
|
580
|
+
} finally {
|
|
581
|
+
this.reportMetaWarnings(metaWarnings);
|
|
582
|
+
try {
|
|
583
|
+
await rm(bundleDirectory, {
|
|
584
|
+
recursive: true,
|
|
585
|
+
force: true,
|
|
586
|
+
maxRetries: 3,
|
|
587
|
+
retryDelay: 50
|
|
588
|
+
});
|
|
589
|
+
} catch (error) {
|
|
590
|
+
debug.error("Failed to remove config loader directory %s:", bundleDirectory, error);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
/**
|
|
596
|
+
* 说明执行阶段错误的来源,并写进 message 和 stack
|
|
597
|
+
*
|
|
598
|
+
* @description 字段只读或访问器抛错时保留原异常,诊断失败不能覆盖配置错误
|
|
599
|
+
* @param error 配置执行阶段抛出的错误
|
|
600
|
+
* @param file 相对项目根的配置入口路径,用于说明错误来自哪份配置
|
|
601
|
+
*/
|
|
602
|
+
function explainEvaluationError(error, file) {
|
|
603
|
+
const note = `\n[vite-plugin-uni-pages] The error happened while evaluating the config generated from ${file} and the modules it imports; the stack above points into that temporary bundle, not into your source.`;
|
|
604
|
+
try {
|
|
605
|
+
const stack = error.stack;
|
|
606
|
+
error.message += note;
|
|
607
|
+
if (typeof stack === "string") error.stack = stack + note;
|
|
608
|
+
} catch {}
|
|
609
|
+
}
|
|
610
|
+
function unwrapConfig(value) {
|
|
611
|
+
if (value === null || typeof value !== "object" || !("default" in value) || value.default === null || typeof value.default !== "object") return value;
|
|
612
|
+
const result = value.default;
|
|
613
|
+
for (const [key, item] of Object.entries(value)) {
|
|
614
|
+
if (key === "default" || key in result || item === result) continue;
|
|
615
|
+
try {
|
|
616
|
+
Object.defineProperty(result, key, {
|
|
617
|
+
configurable: true,
|
|
618
|
+
enumerable: true,
|
|
619
|
+
get: () => value[key]
|
|
620
|
+
});
|
|
621
|
+
} catch {}
|
|
622
|
+
}
|
|
623
|
+
return result;
|
|
624
|
+
}
|
|
625
|
+
//#endregion
|
|
23
626
|
//#region src/constant.ts
|
|
24
627
|
/** Vite 模块解析用的虚拟模块标识 */
|
|
25
628
|
const MODULE_ID_VIRTUAL = "virtual:uni-pages";
|
|
@@ -34,6 +637,84 @@ const FILE_EXTENSIONS = [
|
|
|
34
637
|
"uvue"
|
|
35
638
|
];
|
|
36
639
|
//#endregion
|
|
640
|
+
//#region src/config-watch.ts
|
|
641
|
+
function isWithin(directory, file) {
|
|
642
|
+
const normalized = directory.replace(/\/$/, "");
|
|
643
|
+
return file === normalized || file.startsWith(`${normalized}/`);
|
|
644
|
+
}
|
|
645
|
+
/** 把一次加载的输入归一化为可注册、可匹配的监听计划 */
|
|
646
|
+
function buildConfigWatchPlan(input) {
|
|
647
|
+
const files = [...new Set([
|
|
648
|
+
...input.sourcePaths,
|
|
649
|
+
...input.dependencyPaths,
|
|
650
|
+
...input.recoveryCandidates ?? []
|
|
651
|
+
].map((file) => normalizeConfigPath(file, input.root)).filter((file) => !isConfigLoaderArtifact(file, input.artifactDirectory)))];
|
|
652
|
+
const directories = [...new Set((input.recoveryDirectories ?? []).map((dir) => normalizeConfigPath(dir, input.root)))];
|
|
653
|
+
return {
|
|
654
|
+
files,
|
|
655
|
+
directories,
|
|
656
|
+
paths: [.../* @__PURE__ */ new Set([
|
|
657
|
+
...files,
|
|
658
|
+
...files.map(configWatchDirectory),
|
|
659
|
+
...directories.map((dir) => configWatchDirectory(path.join(dir, "_")))
|
|
660
|
+
])]
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* 配置事件判定与监听集合的当前视图。
|
|
665
|
+
*
|
|
666
|
+
* 监听器只新增路径、从不退回(chokidar 对文件 unwatch 会拆掉父目录监听),
|
|
667
|
+
* 所以真正决定事件是否触发的始终是最近一次 `update` 的依赖集合;
|
|
668
|
+
* `expanded` 用来在依赖集合扩大后补跑一轮生成。
|
|
669
|
+
*/
|
|
670
|
+
var ConfigWatchIndex = class {
|
|
671
|
+
root;
|
|
672
|
+
artifactDirectory;
|
|
673
|
+
plan = {
|
|
674
|
+
files: [],
|
|
675
|
+
directories: [],
|
|
676
|
+
paths: []
|
|
677
|
+
};
|
|
678
|
+
files = /* @__PURE__ */ new Set();
|
|
679
|
+
initialized = false;
|
|
680
|
+
expanded = false;
|
|
681
|
+
constructor(root, artifactDirectory) {
|
|
682
|
+
this.root = root;
|
|
683
|
+
this.artifactDirectory = artifactDirectory;
|
|
684
|
+
}
|
|
685
|
+
update(plan) {
|
|
686
|
+
const nextFiles = new Set(plan.files);
|
|
687
|
+
if (this.initialized && [...nextFiles].some((file) => !this.files.has(file))) this.expanded = true;
|
|
688
|
+
this.plan = plan;
|
|
689
|
+
this.files = nextFiles;
|
|
690
|
+
this.initialized = true;
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* 返回事件对应的归一化配置路径;不是当前配置输入时返回 undefined。
|
|
694
|
+
*
|
|
695
|
+
* 直接命中已知依赖时保留事件路径,避免为了识别符号链接别名而额外查
|
|
696
|
+
* 文件系统;未命中时才按真实路径归一化,覆盖别名和冗余路径段。
|
|
697
|
+
*/
|
|
698
|
+
match(filepath, excluded) {
|
|
699
|
+
const eventPath = normalizePath(path.resolve(this.root, normalizePath(filepath)));
|
|
700
|
+
if (excluded.includes(eventPath) || isConfigLoaderArtifact(eventPath, this.artifactDirectory)) return;
|
|
701
|
+
const absolute = this.files.has(eventPath) ? eventPath : normalizeConfigPath(filepath, this.root);
|
|
702
|
+
if (excluded.includes(absolute) || isConfigLoaderArtifact(absolute, this.artifactDirectory)) return;
|
|
703
|
+
const mightBeConfig = configFileExtensions.test(path.basename(filepath));
|
|
704
|
+
return this.files.has(absolute) || mightBeConfig && this.plan.directories.some((directory) => isWithin(directory, absolute)) ? absolute : void 0;
|
|
705
|
+
}
|
|
706
|
+
/** 共享 watcher 已覆盖的根目录无需重复注册,也不能撤销 */
|
|
707
|
+
watchPaths(sharedRoot) {
|
|
708
|
+
return this.plan.paths.filter((file) => !sharedRoot || file !== sharedRoot && !isWithin(sharedRoot, file));
|
|
709
|
+
}
|
|
710
|
+
/** 依赖集合在上一次生成期间扩大时,消费一次补跑标记 */
|
|
711
|
+
consumeExpanded() {
|
|
712
|
+
const expanded = this.expanded;
|
|
713
|
+
this.expanded = false;
|
|
714
|
+
return expanded;
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
//#endregion
|
|
37
718
|
//#region src/declaration.ts
|
|
38
719
|
/**
|
|
39
720
|
* 生成 TypeScript 声明文件内容
|
|
@@ -107,43 +788,118 @@ async function writeDeclaration(input, filepath) {
|
|
|
107
788
|
if (code !== originalContent) await writeFile$1(filepath, code);
|
|
108
789
|
}
|
|
109
790
|
//#endregion
|
|
110
|
-
//#region src/
|
|
791
|
+
//#region src/page-rules.ts
|
|
792
|
+
const ruleCache = /* @__PURE__ */ new WeakMap();
|
|
111
793
|
/**
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
794
|
+
* 编译以项目根为基准的规则,不查询目录是否存在
|
|
795
|
+
*
|
|
796
|
+
* @description 排除同时作用于路径自身和祖先;空模式忽略,否定排除报错,extglob 保留
|
|
115
797
|
*/
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
798
|
+
function compilePageRules(root, patterns, exclude) {
|
|
799
|
+
const absoluteRoot = normalizePath(path.resolve(root));
|
|
800
|
+
const escapedRoot = escapePath(absoluteRoot);
|
|
801
|
+
const relative = (absolute) => normalizePath(path.relative(absoluteRoot, absolute)) || ".";
|
|
802
|
+
const matchOptions = {
|
|
803
|
+
dot: true,
|
|
804
|
+
posix: true
|
|
805
|
+
};
|
|
806
|
+
const compilePattern = (pattern) => {
|
|
807
|
+
const portable = process.platform === "win32" ? pattern.replace(/\\(?![()[\]{}!+@])/g, "/") : pattern;
|
|
808
|
+
const absolute = path.isAbsolute(portable);
|
|
809
|
+
let normalized = absolute ? path.posix.normalize(portable) : path.posix.relative(escapedRoot, path.posix.resolve(escapedRoot, portable)) || ".";
|
|
810
|
+
if (absolute && normalized !== normalizePath(path.parse(portable).root)) normalized = normalized.replace(/\/$/, "");
|
|
811
|
+
const matches = picomatch(normalized, matchOptions);
|
|
812
|
+
return {
|
|
813
|
+
pattern: normalized,
|
|
814
|
+
absolute,
|
|
815
|
+
matches: (candidate) => matches(absolute ? normalizePath(candidate) : relative(candidate))
|
|
816
|
+
};
|
|
817
|
+
};
|
|
818
|
+
const exclusions = exclude.filter((pattern) => pattern !== "").map((pattern) => {
|
|
819
|
+
if (picomatch.scan(pattern).negated) throw new Error(`[vite-plugin-uni-pages] Negative exclude pattern "${pattern}" cannot re-include pages. Remove it from exclude.`);
|
|
820
|
+
return compilePattern(pattern);
|
|
821
|
+
});
|
|
822
|
+
const directoryPatterns = patterns.filter((pattern) => pattern !== "" && !picomatch.scan(pattern).negated);
|
|
823
|
+
const directories = directoryPatterns.map(compilePattern);
|
|
824
|
+
const isExcluded = (absoluteRulePath, cache) => {
|
|
825
|
+
let current = path.resolve(absoluteRulePath);
|
|
826
|
+
const visited = cache ? [] : void 0;
|
|
827
|
+
let excluded = false;
|
|
828
|
+
while (true) {
|
|
829
|
+
const cached = cache?.get(current);
|
|
830
|
+
if (cached !== void 0) {
|
|
831
|
+
excluded = cached;
|
|
832
|
+
break;
|
|
833
|
+
}
|
|
834
|
+
visited?.push(current);
|
|
835
|
+
if (exclusions.some((rule) => rule.matches(current))) {
|
|
836
|
+
excluded = true;
|
|
837
|
+
break;
|
|
838
|
+
}
|
|
839
|
+
const parent = path.dirname(current);
|
|
840
|
+
if (parent === current) break;
|
|
841
|
+
current = parent;
|
|
842
|
+
}
|
|
843
|
+
if (cache && visited) for (const directory of visited) cache.set(directory, excluded);
|
|
844
|
+
return excluded;
|
|
845
|
+
};
|
|
846
|
+
return {
|
|
847
|
+
patterns: directoryPatterns,
|
|
848
|
+
traversalIgnores: exclusions.filter((rule) => !rule.absolute && !/[!()[\]{}\\+@|]/.test(rule.pattern)).map((rule) => rule.pattern),
|
|
849
|
+
isExcluded,
|
|
850
|
+
createExcludeFilter: () => {
|
|
851
|
+
const cache = /* @__PURE__ */ new Map();
|
|
852
|
+
return (absolute) => isExcluded(absolute, cache);
|
|
853
|
+
},
|
|
854
|
+
matchesDirectory: (absolute) => !isExcluded(absolute) && directories.some((rule) => rule.matches(absolute))
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
/** 复用当前声明的编译结果,原地修改路径规则或排除项后重新编译 */
|
|
858
|
+
function getPageRules(options) {
|
|
859
|
+
const patterns = [options.dir, ...options.subPackagePatterns.map((pattern) => typeof pattern === "string" ? pattern : pattern.dir)];
|
|
860
|
+
const fingerprint = JSON.stringify([
|
|
861
|
+
options.root,
|
|
862
|
+
patterns,
|
|
863
|
+
options.exclude
|
|
864
|
+
]);
|
|
865
|
+
const cached = ruleCache.get(options);
|
|
866
|
+
if (cached?.fingerprint === fingerprint) return cached.rules;
|
|
867
|
+
const rules = compilePageRules(options.root, patterns, options.exclude);
|
|
868
|
+
ruleCache.set(options, {
|
|
869
|
+
fingerprint,
|
|
870
|
+
rules
|
|
871
|
+
});
|
|
872
|
+
return rules;
|
|
873
|
+
}
|
|
134
874
|
//#endregion
|
|
135
875
|
//#region src/files.ts
|
|
136
876
|
/**
|
|
137
|
-
*
|
|
877
|
+
* 判断是否为路径缺失或中间路径不是目录的文件系统错误
|
|
878
|
+
*
|
|
879
|
+
* @returns 错误码为 ENOENT 或 ENOTDIR 时返回 true,其他错误及空输入返回 false
|
|
880
|
+
*/
|
|
881
|
+
function isMissingFsError(error) {
|
|
882
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
|
883
|
+
return error.code === "ENOENT" || error.code === "ENOTDIR";
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* 获取扫描目录中未被排除的页面文件
|
|
887
|
+
*
|
|
888
|
+
* @param directory - 绝对扫描目录,或相对项目根的目录
|
|
889
|
+
* @param options - 已解析的页面选项,排除规则以其中的项目根为基准
|
|
890
|
+
* @returns 相对扫描目录、使用 `/` 分隔的文件路径
|
|
138
891
|
*/
|
|
139
|
-
function getPageFiles(
|
|
140
|
-
const
|
|
892
|
+
function getPageFiles(directory, options) {
|
|
893
|
+
const absolute = path.resolve(options.root, directory);
|
|
894
|
+
const rules = getPageRules(options);
|
|
895
|
+
if (rules.isExcluded(absolute)) return [];
|
|
141
896
|
const ext = FILE_EXTENSIONS.length > 1 ? `{${FILE_EXTENSIONS.join(",")}}` : FILE_EXTENSIONS[0] || "";
|
|
142
|
-
return globSync(
|
|
143
|
-
ignore:
|
|
897
|
+
return globSync(`${escapePath(normalizePath(absolute))}/**/*.${ext}`, {
|
|
898
|
+
ignore: rules.traversalIgnores,
|
|
899
|
+
expandDirectories: false,
|
|
144
900
|
onlyFiles: true,
|
|
145
|
-
cwd:
|
|
146
|
-
});
|
|
901
|
+
cwd: options.root
|
|
902
|
+
}).map((file) => path.resolve(options.root, file)).filter((file) => !rules.isExcluded(file)).map((file) => normalizePath(path.relative(absolute, file)));
|
|
147
903
|
}
|
|
148
904
|
/**
|
|
149
905
|
* 检查文件是否为目标页面文件
|
|
@@ -183,8 +939,15 @@ function checkPagesJsonFileSync(path) {
|
|
|
183
939
|
try {
|
|
184
940
|
fs.accessSync(path, fs.constants.F_OK);
|
|
185
941
|
} catch {
|
|
186
|
-
|
|
187
|
-
|
|
942
|
+
try {
|
|
943
|
+
fs.writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2), {
|
|
944
|
+
encoding: "utf-8",
|
|
945
|
+
flag: "wx"
|
|
946
|
+
});
|
|
947
|
+
return;
|
|
948
|
+
} catch (error) {
|
|
949
|
+
if (error.code !== "EEXIST") throw error;
|
|
950
|
+
}
|
|
188
951
|
}
|
|
189
952
|
if (!fs.statSync(path).isFile()) throw new Error(`[vite-plugin-uni-pages] ${path} exists but is not a regular file. Remove it manually if it is not needed; the plugin refuses to delete or overwrite it.`);
|
|
190
953
|
try {
|
|
@@ -216,6 +979,7 @@ const lockQueues = /* @__PURE__ */ new Map();
|
|
|
216
979
|
* @param task - 在锁内运行的异步任务;返回值原样返回给调用方
|
|
217
980
|
* @param retry - 锁被别人拿着时的重试次数,默认 3
|
|
218
981
|
* @returns `task` 的结果;一直拿不到锁时为 `undefined`
|
|
982
|
+
* @throws 权限不足、路径缺失等非竞争错误原样抛出,不重试
|
|
219
983
|
*/
|
|
220
984
|
function withFileLock(path, task, retry = 3) {
|
|
221
985
|
const current = (lockQueues.get(path) ?? Promise.resolve()).catch(() => {}).then(() => acquireAndRun(path, task, retry));
|
|
@@ -228,8 +992,9 @@ async function acquireAndRun(path, task, retry) {
|
|
|
228
992
|
let release;
|
|
229
993
|
try {
|
|
230
994
|
release = await lockfile.lock(path, { realpath: false });
|
|
231
|
-
} catch {
|
|
232
|
-
|
|
995
|
+
} catch (error) {
|
|
996
|
+
if (error.code !== "ELOCKED") throw error;
|
|
997
|
+
if (attempt > 1) await sleep(500);
|
|
233
998
|
continue;
|
|
234
999
|
}
|
|
235
1000
|
try {
|
|
@@ -249,74 +1014,394 @@ function sleep(ms) {
|
|
|
249
1014
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
250
1015
|
}
|
|
251
1016
|
//#endregion
|
|
252
|
-
//#region src/
|
|
1017
|
+
//#region src/page-sources.ts
|
|
253
1018
|
/**
|
|
254
|
-
*
|
|
255
|
-
* 将用户提供的配置与默认值合并,并处理路径解析
|
|
1019
|
+
* 读取本轮页面文件的物理身份
|
|
256
1020
|
*
|
|
257
|
-
* @
|
|
258
|
-
* @
|
|
259
|
-
* @returns 解析后的配置项
|
|
1021
|
+
* @returns 规范化的 native realpath;路径不存在或中间路径不是目录时为 undefined
|
|
1022
|
+
* @throws 权限不足等其他文件系统错误原样抛出
|
|
260
1023
|
*/
|
|
261
|
-
function
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
], minify = false, insertFinalNewline = false, indent = 2, eol = "\n", debug = false, onBeforeLoadUserConfig = () => {}, onAfterLoadUserConfig = () => {}, onBeforeScanPages = () => {}, onAfterScanPages = () => {}, onBeforeMergePageMetaData = () => {}, onAfterMergePageMetaData = () => {}, onBeforeWriteFile = () => {}, onAfterWriteFile = () => {} } = userOptions;
|
|
267
|
-
const root = viteRoot || normalizePath(process.env.VITE_ROOT_DIR || process.cwd());
|
|
268
|
-
const resolvedDirs = resolvePageDirs(dir, root, exclude);
|
|
269
|
-
const subPackageRootMap = /* @__PURE__ */ new Map();
|
|
270
|
-
const resolvedSubDirs = [];
|
|
271
|
-
for (const sub of subPackages) if (typeof sub === "string") resolvedSubDirs.push(normalizePath(sub));
|
|
272
|
-
else {
|
|
273
|
-
const dirPath = normalizePath(sub.dir);
|
|
274
|
-
resolvedSubDirs.push(dirPath);
|
|
275
|
-
subPackageRootMap.set(dirPath, sub.root);
|
|
1024
|
+
function resolvePageIdentity(file) {
|
|
1025
|
+
try {
|
|
1026
|
+
return normalizePath(fs.realpathSync.native(file));
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
if (!isMissingFsError(error)) throw error;
|
|
276
1029
|
}
|
|
277
|
-
const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
|
|
278
|
-
const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
|
|
279
|
-
return {
|
|
280
|
-
dts: !dts ? false : typeof dts === "string" ? dts : resolve(viteRoot, "uni-pages.d.ts"),
|
|
281
|
-
configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
|
|
282
|
-
homePage: resolvedHomePage,
|
|
283
|
-
mergePages,
|
|
284
|
-
dirs: resolvedDirs,
|
|
285
|
-
subPackages: resolvedSubDirs,
|
|
286
|
-
subPackageRootMap,
|
|
287
|
-
outDir,
|
|
288
|
-
exclude,
|
|
289
|
-
root,
|
|
290
|
-
minify,
|
|
291
|
-
insertFinalNewline,
|
|
292
|
-
indent,
|
|
293
|
-
eol,
|
|
294
|
-
debug,
|
|
295
|
-
onBeforeLoadUserConfig,
|
|
296
|
-
onAfterLoadUserConfig,
|
|
297
|
-
onBeforeScanPages,
|
|
298
|
-
onAfterScanPages,
|
|
299
|
-
onBeforeMergePageMetaData,
|
|
300
|
-
onAfterMergePageMetaData,
|
|
301
|
-
onBeforeWriteFile,
|
|
302
|
-
onAfterWriteFile
|
|
303
|
-
};
|
|
304
1030
|
}
|
|
305
1031
|
/**
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
* @
|
|
309
|
-
* @param exclude - 需要排除的 glob 模式
|
|
310
|
-
* @returns 匹配到的目录路径
|
|
1032
|
+
* 比较页面来源的代表优先级
|
|
1033
|
+
*
|
|
1034
|
+
* @description 显式来源优先,其余按声明和 glob 匹配顺序;相同优先级返回 0
|
|
311
1035
|
*/
|
|
312
|
-
function
|
|
313
|
-
return
|
|
314
|
-
|
|
1036
|
+
function comparePageSources(a, b) {
|
|
1037
|
+
return Number(b.explicitRoot) - Number(a.explicitRoot) || a.ruleIndex - b.ruleIndex || a.matchIndex - b.matchIndex;
|
|
1038
|
+
}
|
|
1039
|
+
function describeSource(source) {
|
|
1040
|
+
const declaration = source.root === void 0 ? "dir" : `subPackages[${source.ruleIndex}]`;
|
|
1041
|
+
const rule = source.rulePattern === void 0 ? "" : ` rule ${JSON.stringify(source.rulePattern)}`;
|
|
1042
|
+
const owner = source.root === void 0 ? "main package" : `subpackage "${source.root}"`;
|
|
1043
|
+
const rootSource = source.rootSource;
|
|
1044
|
+
const rootOrigin = rootSource ? `, root from subPackages[${rootSource.ruleIndex}] "${rootSource.dir}" (${rootSource.explicitRoot ? "explicit" : "default"})` : "";
|
|
1045
|
+
return `"${source.file}" (${declaration}${rule}, directory "${source.dir}", ${owner}${rootOrigin})`;
|
|
1046
|
+
}
|
|
1047
|
+
/** 关联记录仅保留来源信息,不携带其他 Page 实例 */
|
|
1048
|
+
function toPageSource(candidate) {
|
|
1049
|
+
return {
|
|
1050
|
+
file: candidate.file,
|
|
1051
|
+
identity: candidate.identity,
|
|
1052
|
+
dir: candidate.dir,
|
|
1053
|
+
root: candidate.root,
|
|
1054
|
+
explicitRoot: candidate.explicitRoot,
|
|
1055
|
+
ruleIndex: candidate.ruleIndex,
|
|
1056
|
+
matchIndex: candidate.matchIndex,
|
|
1057
|
+
rootSource: candidate.rootSource
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
function describeRelatedSource(source) {
|
|
1061
|
+
const owner = source.root === void 0 ? "main package" : `subpackage "${source.root}"`;
|
|
1062
|
+
return `"${source.file}" (directory "${source.dir}", ${owner})`;
|
|
1063
|
+
}
|
|
1064
|
+
function describeRelatedSources(source) {
|
|
1065
|
+
if (source.relatedSources.length === 0) return "";
|
|
1066
|
+
return `; related sources: ${source.relatedSources.map(describeRelatedSource).join(", ")}`;
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* 为每个物理页面选择一个有效代表来源
|
|
1070
|
+
*
|
|
1071
|
+
* @description 候选需先通过文件排除,且未被宏结果或平台规则跳过;有效分包优先于主包,
|
|
1072
|
+
* 同一归属内按显式来源和声明顺序选择,返回顺序按文件身份首次出现的位置排列,
|
|
1073
|
+
* 同身份的其他来源仅保留在代表记录中,用于本轮冲突诊断
|
|
1074
|
+
* @param candidates - 本轮有效候选,数组不会被修改
|
|
1075
|
+
* @throws 同一物理页面被不同分包 root 认领时抛出来源冲突
|
|
1076
|
+
*/
|
|
1077
|
+
function selectPageSources(candidates) {
|
|
1078
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1079
|
+
for (const candidate of candidates) {
|
|
1080
|
+
const group = groups.get(candidate.identity) ?? [];
|
|
1081
|
+
group.push(candidate);
|
|
1082
|
+
groups.set(candidate.identity, group);
|
|
1083
|
+
}
|
|
1084
|
+
const selected = [];
|
|
1085
|
+
for (const group of groups.values()) {
|
|
1086
|
+
const subPages = group.filter((source) => source.root !== void 0);
|
|
1087
|
+
const first = subPages[0];
|
|
1088
|
+
const conflict = subPages.find((source) => source.root !== first?.root);
|
|
1089
|
+
if (first && conflict) {
|
|
1090
|
+
const explanation = first.ruleIndex >= 0 && first.ruleIndex === conflict.ruleIndex && first.matchIndex !== conflict.matchIndex ? " The same directory rule matched multiple directories containing this page. For one subpackage tree, declare its parent directory once; for multiple entries in the same subpackage, use a common root." : "";
|
|
1091
|
+
throw new Error(`[vite-plugin-uni-pages] Conflicting subpackage ownership: ${describeSource(first)} and ${describeSource(conflict)} refer to the same page "${first.identity}".${explanation}`);
|
|
1092
|
+
}
|
|
1093
|
+
const representative = [...subPages.length ? subPages : group].sort(comparePageSources)[0];
|
|
1094
|
+
const relatedSources = group.filter((source) => source !== representative).map(toPageSource);
|
|
1095
|
+
selected.push({
|
|
1096
|
+
...representative,
|
|
1097
|
+
relatedSources
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
return selected;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* 获取允许格式或平台变体覆盖的物理文件族
|
|
1104
|
+
*
|
|
1105
|
+
* @description 格式变体共享去掉扩展名的真实路径;平台后缀只在主包且当前平台适用时处理
|
|
1106
|
+
* @returns 支持的真实页面格式对应的文件族,其他格式不参与覆盖例外
|
|
1107
|
+
*/
|
|
1108
|
+
function fileFamily(source, platform) {
|
|
1109
|
+
const extension = path.extname(source.identity);
|
|
1110
|
+
if (!FILE_EXTENSIONS.includes(extension.slice(1))) return;
|
|
1111
|
+
const stem = source.identity.slice(0, -extension.length);
|
|
1112
|
+
const filename = source.page.uri.slice(source.page.uri.lastIndexOf("/") + 1);
|
|
1113
|
+
if (platform === void 0 || source.root !== void 0 || !filename.includes(".") || !source.page.uri.includes(platform)) return stem;
|
|
1114
|
+
const slash = stem.lastIndexOf("/");
|
|
1115
|
+
const dot = stem.indexOf(".", slash + 1);
|
|
1116
|
+
return dot !== -1 && stem.slice(dot) === filename.slice(filename.indexOf(".")) ? stem.slice(0, dot) : stem;
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* 校验生成页面是否占用同一完整路由
|
|
1120
|
+
*
|
|
1121
|
+
* @description 比较时规范化分隔符、点段和末尾斜杠,不改写候选或输出路径
|
|
1122
|
+
* @param candidates - 已完成物理身份归属决议的代表来源,需在配置覆盖和输出去重前传入
|
|
1123
|
+
* @param platform - 启用主包平台后缀规则时的当前平台,省略时只允许格式变体覆盖
|
|
1124
|
+
* @throws 不同生成来源占用同一路由且不属于同一归属的允许文件族时抛出冲突
|
|
1125
|
+
*/
|
|
1126
|
+
function validateGeneratedRoutes(candidates, platform) {
|
|
1127
|
+
const routes = /* @__PURE__ */ new Map();
|
|
1128
|
+
for (const candidate of candidates) {
|
|
1129
|
+
const route = path.posix.normalize(candidate.route.replace(/\\/g, "/")).replace(/\/$/, "");
|
|
1130
|
+
const previous = routes.get(route);
|
|
1131
|
+
if (previous && previous.identity !== candidate.identity) {
|
|
1132
|
+
const previousFamily = fileFamily(previous, platform);
|
|
1133
|
+
if (!(previous.root === candidate.root && previousFamily !== void 0 && previousFamily === fileFamily(candidate, platform))) throw new Error(`[vite-plugin-uni-pages] Conflicting generated route "${route}": ${describeSource(previous)}${describeRelatedSources(previous)} and ${describeSource(candidate)}${describeRelatedSources(candidate)}.`);
|
|
1134
|
+
}
|
|
1135
|
+
routes.set(route, candidate);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
//#endregion
|
|
1139
|
+
//#region src/directories.ts
|
|
1140
|
+
/**
|
|
1141
|
+
* 规范化页面目录选择器中的路径分隔符
|
|
1142
|
+
*
|
|
1143
|
+
* @description 在 Windows 上将反斜杠路径分隔符转换为 `/`,保留 `\[`、`\(` 等 glob 转义
|
|
1144
|
+
*
|
|
1145
|
+
* @param pattern 页面目录路径或 glob 表达式
|
|
1146
|
+
* @returns Windows 返回规范化后的选择器,其他平台返回原字符串
|
|
1147
|
+
*
|
|
1148
|
+
* @example
|
|
1149
|
+
* ```ts
|
|
1150
|
+
* normalizePagePattern('src\\pages') // Windows: 'src/pages'
|
|
1151
|
+
* ```
|
|
1152
|
+
*/
|
|
1153
|
+
function normalizePagePattern(pattern) {
|
|
1154
|
+
return process.platform === "win32" ? pattern.replace(/\\(?![()[\]{}!+@])/g, "/") : pattern;
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* 将目录选择器中的 glob 转义还原为字面字符
|
|
1158
|
+
*
|
|
1159
|
+
* @description 用于已经确定的固定路径部分,还原后的字符串可传给 `path.resolve` 等路径 API
|
|
1160
|
+
*
|
|
1161
|
+
* @param pattern 以 `/` 分隔、可包含 glob 转义的固定目录路径
|
|
1162
|
+
* @returns 去除 glob 特殊字符前转义反斜杠的路径字符串
|
|
1163
|
+
*
|
|
1164
|
+
* @example
|
|
1165
|
+
* ```ts
|
|
1166
|
+
* unescapePagePattern('src/\\[demo\\]') // 'src/[demo]'
|
|
1167
|
+
* ```
|
|
1168
|
+
*/
|
|
1169
|
+
function unescapePagePattern(pattern) {
|
|
1170
|
+
return pattern.replace(/\\(?=[[\](){}!*+?@|])/g, "");
|
|
1171
|
+
}
|
|
1172
|
+
function findPageDirs(dir, root, rules) {
|
|
1173
|
+
if (dir === "" || picomatch.scan(dir).negated) return [];
|
|
1174
|
+
const pattern = path.posix.normalize(normalizePagePattern(dir));
|
|
1175
|
+
const scan = picomatch.scan(pattern);
|
|
1176
|
+
if (rules.isExcluded(path.resolve(root, unescapePagePattern(scan.base || ".")))) return [];
|
|
1177
|
+
return globSync(pattern, {
|
|
1178
|
+
ignore: rules.traversalIgnores,
|
|
315
1179
|
onlyDirectories: true,
|
|
316
1180
|
expandDirectories: false,
|
|
317
1181
|
dot: true,
|
|
318
1182
|
cwd: root
|
|
319
|
-
});
|
|
1183
|
+
}).map(normalizePath).filter((directory) => !rules.isExcluded(path.resolve(root, directory))).sort();
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* 查找当前可扫描的页面目录
|
|
1187
|
+
*
|
|
1188
|
+
* @description 应用目录排除后,返回相对 root、按路径排序的匹配结果;空规则或否定规则返回空数组
|
|
1189
|
+
*
|
|
1190
|
+
* @param dir 页面目录 glob,可使用绝对路径
|
|
1191
|
+
* @param root 相对目录和相对 exclude 的解析基准
|
|
1192
|
+
* @param exclude 目录及页面排除规则
|
|
1193
|
+
*/
|
|
1194
|
+
function resolvePageDirs(dir, root, exclude) {
|
|
1195
|
+
return findPageDirs(dir, root, compilePageRules(root, [dir], exclude));
|
|
1196
|
+
}
|
|
1197
|
+
function directoryIdentity(absolute) {
|
|
1198
|
+
try {
|
|
1199
|
+
if (fs.statSync(absolute, { throwIfNoEntry: false })?.isDirectory()) return normalizePath(fs.realpathSync.native(absolute));
|
|
1200
|
+
} catch (error) {
|
|
1201
|
+
if (!isMissingFsError(error)) throw error;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
function findCallbackDirectory(dir, root, rules) {
|
|
1205
|
+
if (dir === "") return [];
|
|
1206
|
+
const absolute = path.resolve(root, unescapePagePattern(path.posix.normalize(dir)));
|
|
1207
|
+
if (rules.isExcluded(absolute)) return [];
|
|
1208
|
+
try {
|
|
1209
|
+
if (fs.statSync(absolute, { throwIfNoEntry: false })?.isDirectory()) return [normalizePath(path.relative(root, absolute)) || "."];
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
if (!isMissingFsError(error)) throw error;
|
|
1212
|
+
}
|
|
1213
|
+
return [];
|
|
1214
|
+
}
|
|
1215
|
+
/** 展开分包声明,返回逐条来源记录和扫描目录投影 */
|
|
1216
|
+
function discoverSubPackageDirectories(patterns, root, outDir, exclude) {
|
|
1217
|
+
const rules = compilePageRules(root, [], exclude);
|
|
1218
|
+
const candidates = [];
|
|
1219
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1220
|
+
for (const [ruleIndex, pattern] of patterns.entries()) {
|
|
1221
|
+
const dir = normalizePagePattern(typeof pattern === "string" ? pattern : pattern.dir);
|
|
1222
|
+
if (picomatch.scan(dir).negated) throw new Error("[vite-plugin-uni-pages] Use exclude for negative subpackage patterns.");
|
|
1223
|
+
const customRoot = typeof pattern === "string" ? void 0 : pattern.root;
|
|
1224
|
+
const glob = isDynamicPattern(dir);
|
|
1225
|
+
const dynamic = glob || typeof customRoot === "function";
|
|
1226
|
+
const dirs = glob ? findPageDirs(dir, root, rules) : typeof customRoot === "function" ? findCallbackDirectory(dir, root, rules) : [dir];
|
|
1227
|
+
for (const [matchIndex, matched] of dirs.entries()) {
|
|
1228
|
+
const resolved = dynamic ? matched : unescapePagePattern(matched);
|
|
1229
|
+
const absolute = normalizePath(path.resolve(root, resolved));
|
|
1230
|
+
if (rules.isExcluded(absolute)) continue;
|
|
1231
|
+
const relative = normalizePath(path.relative(root, absolute)) || ".";
|
|
1232
|
+
const resolvedRoot = typeof customRoot === "function" ? customRoot(relative) : customRoot;
|
|
1233
|
+
if (typeof customRoot === "function" && (typeof resolvedRoot !== "string" || !resolvedRoot || resolvedRoot === "." || path.posix.isAbsolute(resolvedRoot) || path.win32.isAbsolute(resolvedRoot) || resolvedRoot.replace(/\\/g, "/").split("/").includes(".."))) throw new Error(`[vite-plugin-uni-pages] Invalid subpackage root returned for "${relative}": expected a non-empty relative path without "..".`);
|
|
1234
|
+
const defaultRoot = normalizePath(path.relative(path.resolve(root, outDir), absolute));
|
|
1235
|
+
const identity = directoryIdentity(absolute);
|
|
1236
|
+
const candidate = {
|
|
1237
|
+
dir: dynamic ? relative : resolved,
|
|
1238
|
+
absolute,
|
|
1239
|
+
identity,
|
|
1240
|
+
root: resolvedRoot === void 0 ? defaultRoot : normalizePath(resolvedRoot),
|
|
1241
|
+
explicitRoot: resolvedRoot !== void 0,
|
|
1242
|
+
ruleIndex,
|
|
1243
|
+
matchIndex,
|
|
1244
|
+
rootSource: {
|
|
1245
|
+
dir: dynamic ? relative : resolved,
|
|
1246
|
+
ruleIndex,
|
|
1247
|
+
explicitRoot: resolvedRoot !== void 0
|
|
1248
|
+
},
|
|
1249
|
+
defaultRoot
|
|
1250
|
+
};
|
|
1251
|
+
candidates.push(candidate);
|
|
1252
|
+
const key = identity ?? absolute;
|
|
1253
|
+
const group = groups.get(key) ?? [];
|
|
1254
|
+
group.push(candidate);
|
|
1255
|
+
groups.set(key, group);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
for (const group of groups.values()) {
|
|
1259
|
+
const explicit = group.filter((candidate) => candidate.explicitRoot);
|
|
1260
|
+
const selected = explicit[0] ?? group[0];
|
|
1261
|
+
for (const candidate of explicit) if (candidate.root !== selected.root) throw new Error(`[vite-plugin-uni-pages] Conflicting subpackage roots: "${selected.dir}" (subPackages[${selected.ruleIndex}]) uses "${selected.root}", but "${candidate.dir}" (subPackages[${candidate.ruleIndex}]) uses "${candidate.root}".`);
|
|
1262
|
+
for (const candidate of group) {
|
|
1263
|
+
candidate.root = selected.root;
|
|
1264
|
+
candidate.rootSource = selected.rootSource;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
const directories = /* @__PURE__ */ new Map();
|
|
1268
|
+
for (const candidate of candidates) {
|
|
1269
|
+
const previous = directories.get(candidate.absolute);
|
|
1270
|
+
if (!previous || comparePageSources(candidate, previous) < 0) directories.set(candidate.absolute, candidate);
|
|
1271
|
+
}
|
|
1272
|
+
const roots = /* @__PURE__ */ new Map();
|
|
1273
|
+
for (const candidate of directories.values()) if (candidate.explicitRoot || candidate.root !== candidate.defaultRoot) roots.set(candidate.dir, candidate.root);
|
|
1274
|
+
return {
|
|
1275
|
+
sources: candidates.map(({ defaultRoot: _defaultRoot, ...source }) => source),
|
|
1276
|
+
projection: {
|
|
1277
|
+
subPackages: [...directories.values()].map((candidate) => candidate.dir),
|
|
1278
|
+
subPackageRootMap: roots
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* 展开分包目录并确定各目录的最终 root
|
|
1284
|
+
*
|
|
1285
|
+
* @description 每次调用重新发现目录并求值回调;按声明顺序排列,glob 内按路径排序
|
|
1286
|
+
* 同一物理目录的显式 root 优先于默认值,词法别名分别保留,重复目录投影只登记一次
|
|
1287
|
+
*
|
|
1288
|
+
* @param patterns 原始分包目录声明
|
|
1289
|
+
* @param root 相对目录和相对 exclude 的解析基准
|
|
1290
|
+
* @param outDir 默认分包 root 的换算基准,相对 root 解析
|
|
1291
|
+
* @param exclude 目录及页面排除规则
|
|
1292
|
+
* @returns 目录列表及最终 root 映射
|
|
1293
|
+
* @throws 目录规则无效、root 回调失败、显式 root 冲突或非缺失类目录访问错误
|
|
1294
|
+
*/
|
|
1295
|
+
function resolveSubPackageDirs(patterns, root, outDir, exclude) {
|
|
1296
|
+
return discoverSubPackageDirectories(patterns, root, outDir, exclude).projection;
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* 读取当前分包目录来源
|
|
1300
|
+
*
|
|
1301
|
+
* @description 每次调用重新发现目录并求值回调;需要与扫描共用同一份结果时,
|
|
1302
|
+
* 使用 ScanPlan 而不是在扫描中途再次调用
|
|
1303
|
+
*
|
|
1304
|
+
* @returns 按声明及匹配顺序排列的来源,调用方应只读使用记录
|
|
1305
|
+
* @throws 目录规则、root 决议或目录访问错误
|
|
1306
|
+
*/
|
|
1307
|
+
function getSubPackageDirectorySources(options) {
|
|
1308
|
+
return discoverSubPackageDirectories(options.subPackagePatterns, options.root, options.outDir, options.exclude).sources;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* 刷新扫描目录与分包 root 投影
|
|
1312
|
+
*
|
|
1313
|
+
* @description 仅用于兼容仍读取 `ResolvedOptions` 的调用方;内部扫描走
|
|
1314
|
+
* `createScanPlan()`,每次重新发现目录来源与物理身份,不保留上一轮快照
|
|
1315
|
+
*
|
|
1316
|
+
* @throws 目录规则、root 决议或目录访问失败时抛出,应中止本轮扫描
|
|
1317
|
+
*/
|
|
1318
|
+
function refreshPageDirectories(options) {
|
|
1319
|
+
const { projection } = discoverSubPackageDirectories(options.subPackagePatterns, options.root, options.outDir, options.exclude);
|
|
1320
|
+
options.dirs = resolvePageDirs(options.dir, options.root, options.exclude);
|
|
1321
|
+
Object.assign(options, projection);
|
|
1322
|
+
}
|
|
1323
|
+
function contains$1(directory, entry) {
|
|
1324
|
+
return entry === directory || entry.startsWith(`${directory.replace(/\/$/, "")}/`);
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* 判断目录事件是否可能改变扫描目录集合
|
|
1328
|
+
*
|
|
1329
|
+
* @description directory 相对 options.root 解析,允许目录已删除;关闭 mergePages 时返回 false
|
|
1330
|
+
*/
|
|
1331
|
+
function isPageDirectoryEvent(directory, options) {
|
|
1332
|
+
if (!options.mergePages) return false;
|
|
1333
|
+
const absolute = normalizePath(path.resolve(options.root, directory));
|
|
1334
|
+
const rules = getPageRules(options);
|
|
1335
|
+
if (rules.isExcluded(absolute)) return false;
|
|
1336
|
+
if (rules.matchesDirectory(absolute)) return true;
|
|
1337
|
+
return [...options.dirs, ...options.subPackages].some((dir) => contains$1(absolute, normalizePath(path.resolve(options.root, dir))));
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* 判断文件路径是否位于当前页面规则内
|
|
1341
|
+
*
|
|
1342
|
+
* @description file 相对 options.root 解析,按原始规则与 exclude 判断,不要求文件存在或目录已展开
|
|
1343
|
+
* 关闭 mergePages 时返回 false,文件扩展名由调用方校验
|
|
1344
|
+
*/
|
|
1345
|
+
function isPageFileInDirectories(file, options) {
|
|
1346
|
+
if (!options.mergePages) return false;
|
|
1347
|
+
const absolute = normalizePath(path.resolve(options.root, file));
|
|
1348
|
+
const rules = getPageRules(options);
|
|
1349
|
+
if (rules.isExcluded(absolute)) return false;
|
|
1350
|
+
let directory = normalizePath(path.dirname(absolute));
|
|
1351
|
+
while (true) {
|
|
1352
|
+
if (rules.matchesDirectory(directory)) return true;
|
|
1353
|
+
const parent = normalizePath(path.dirname(directory));
|
|
1354
|
+
if (parent === directory) return false;
|
|
1355
|
+
directory = parent;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
//#endregion
|
|
1359
|
+
//#region src/options.ts
|
|
1360
|
+
/**
|
|
1361
|
+
* 解析用户配置项
|
|
1362
|
+
* 将用户提供的配置与默认值合并,并处理路径解析
|
|
1363
|
+
*
|
|
1364
|
+
* @param userOptions - 用户配置项
|
|
1365
|
+
* @param viteRoot - Vite 项目根目录
|
|
1366
|
+
* @returns 解析后的配置项
|
|
1367
|
+
*/
|
|
1368
|
+
function resolveOptions(userOptions, viteRoot = process.cwd()) {
|
|
1369
|
+
const { dts = true, configSource = "pages.config", homePage = ["pages/index", "pages/index/index"], mergePages = true, dir = "src/pages", subPackages = [], outDir = "src", exclude = [
|
|
1370
|
+
"**/node_modules/**",
|
|
1371
|
+
"**/.git/**",
|
|
1372
|
+
"**/__*__/**"
|
|
1373
|
+
], minify = false, insertFinalNewline = false, indent = 2, eol = "\n", debug = false, onBeforeLoadUserConfig = () => {}, onAfterLoadUserConfig = () => {}, onBeforeScanPages = () => {}, onAfterScanPages = () => {}, onBeforeMergePageMetaData = () => {}, onAfterMergePageMetaData = () => {}, onBeforeWriteFile = () => {}, onAfterWriteFile = () => {} } = userOptions;
|
|
1374
|
+
const root = normalizePath(resolve(viteRoot || process.env.VITE_ROOT_DIR || process.cwd()));
|
|
1375
|
+
const resolvedDirs = resolvePageDirs(dir, root, exclude);
|
|
1376
|
+
const resolvedSubPackages = resolveSubPackageDirs(subPackages, root, outDir, exclude);
|
|
1377
|
+
const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
|
|
1378
|
+
const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
|
|
1379
|
+
return {
|
|
1380
|
+
dts: !dts ? false : typeof dts === "string" ? resolve(root, dts) : resolve(root, "uni-pages.d.ts"),
|
|
1381
|
+
configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
|
|
1382
|
+
homePage: resolvedHomePage,
|
|
1383
|
+
mergePages,
|
|
1384
|
+
dir,
|
|
1385
|
+
dirs: resolvedDirs,
|
|
1386
|
+
subPackagePatterns: subPackages,
|
|
1387
|
+
...resolvedSubPackages,
|
|
1388
|
+
outDir,
|
|
1389
|
+
exclude,
|
|
1390
|
+
root,
|
|
1391
|
+
minify,
|
|
1392
|
+
insertFinalNewline,
|
|
1393
|
+
indent,
|
|
1394
|
+
eol,
|
|
1395
|
+
debug,
|
|
1396
|
+
onBeforeLoadUserConfig,
|
|
1397
|
+
onAfterLoadUserConfig,
|
|
1398
|
+
onBeforeScanPages,
|
|
1399
|
+
onAfterScanPages,
|
|
1400
|
+
onBeforeMergePageMetaData,
|
|
1401
|
+
onAfterMergePageMetaData,
|
|
1402
|
+
onBeforeWriteFile,
|
|
1403
|
+
onAfterWriteFile
|
|
1404
|
+
};
|
|
320
1405
|
}
|
|
321
1406
|
//#endregion
|
|
322
1407
|
//#region src/condition.ts
|
|
@@ -694,97 +1779,84 @@ async function parseCode(options) {
|
|
|
694
1779
|
//#endregion
|
|
695
1780
|
//#region src/page.ts
|
|
696
1781
|
/**
|
|
697
|
-
* 表示一个 Vue
|
|
1782
|
+
* 表示一个 Vue 页面文件的读取适配器
|
|
698
1783
|
*
|
|
699
|
-
*
|
|
700
|
-
*
|
|
701
|
-
* 2. 解析 definePage 宏定义的页面配置
|
|
702
|
-
* 3. 提供 tabBar 配置信息
|
|
703
|
-
* 4. 跟踪页面文件变更状态
|
|
1784
|
+
* 调用方只需要 `load()`:文件读取、宏求值、跳过状态、tabBar 补全和
|
|
1785
|
+
* 变更检测都在快照里返回。`getPageMeta` / `getTabBar` 保留为兼容入口。
|
|
704
1786
|
*/
|
|
705
1787
|
var Page = class {
|
|
706
|
-
|
|
707
|
-
ctx;
|
|
1788
|
+
environment;
|
|
708
1789
|
/** 页面路径信息,包含相对路径与绝对路径 */
|
|
709
1790
|
path;
|
|
710
1791
|
/** 页面 URI,用于 pages.json 的 path 字段 */
|
|
711
1792
|
uri;
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
/**
|
|
715
|
-
* 页面是否通过 `definePage(null)` 或函数式宏在当前平台返回 null 而
|
|
716
|
-
* 退出了 pages.json
|
|
717
|
-
*/
|
|
718
|
-
skipped = false;
|
|
719
|
-
/** 页面文件是否至少被读取过一次 */
|
|
1793
|
+
snapshot;
|
|
1794
|
+
/** 当前读取缓存是否有效 */
|
|
720
1795
|
loaded = false;
|
|
721
|
-
/**
|
|
1796
|
+
/** 当前缓存是否已尝试读取;失败后等下次失效再重试 */
|
|
1797
|
+
readAttempted = false;
|
|
1798
|
+
/** 上一次成功读取的配置,用于变更检测 */
|
|
722
1799
|
raw = "";
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
/**
|
|
726
|
-
* 创建页面实例
|
|
727
|
-
* @param ctx - 页面上下文实例
|
|
728
|
-
* @param path - 页面路径信息
|
|
729
|
-
*/
|
|
730
|
-
constructor(ctx, path) {
|
|
731
|
-
this.ctx = ctx;
|
|
1800
|
+
constructor(environment, path) {
|
|
1801
|
+
this.environment = environment;
|
|
732
1802
|
this.path = path;
|
|
733
1803
|
const ext = extname(path.relativePath);
|
|
734
1804
|
this.uri = normalizePath(ext ? path.relativePath.slice(0, -ext.length) : path.relativePath);
|
|
735
1805
|
}
|
|
1806
|
+
/** 页面是否通过 definePage(null) 退出 */
|
|
1807
|
+
get skipped() {
|
|
1808
|
+
return this.snapshot?.skipped ?? false;
|
|
1809
|
+
}
|
|
1810
|
+
/** 页面内容是否相对上次成功读取发生变化 */
|
|
1811
|
+
get changed() {
|
|
1812
|
+
return this.snapshot?.changed ?? true;
|
|
1813
|
+
}
|
|
736
1814
|
/**
|
|
737
|
-
*
|
|
738
|
-
* 解析 definePage 宏定义的配置并返回用于 pages.json 的配置
|
|
1815
|
+
* 读取页面并返回快照
|
|
739
1816
|
*
|
|
740
|
-
* @param forceUpdate -
|
|
741
|
-
* @returns 页面配置对象
|
|
1817
|
+
* @param forceUpdate - 忽略缓存强制重读
|
|
742
1818
|
*/
|
|
743
|
-
async
|
|
744
|
-
if (forceUpdate || !this.loaded) await this.read();
|
|
745
|
-
|
|
746
|
-
return {
|
|
747
|
-
path: path ?? this.uri,
|
|
748
|
-
...others
|
|
749
|
-
};
|
|
1819
|
+
async load(forceUpdate = false) {
|
|
1820
|
+
if (forceUpdate || !this.loaded && !this.readAttempted) await this.read();
|
|
1821
|
+
return this.snapshot ?? this.fallbackSnapshot();
|
|
750
1822
|
}
|
|
751
1823
|
/**
|
|
752
|
-
*
|
|
753
|
-
* 从 definePage 宏中提取 tabBar 相关配置
|
|
1824
|
+
* 获取页面配置,保留给既有调用方
|
|
754
1825
|
*
|
|
755
|
-
*
|
|
756
|
-
*
|
|
1826
|
+
* 返回副本:合并阶段会原地写 `type: 'home'`,不能让首页标记留在
|
|
1827
|
+
* 读取快照里,否则增量更新会继续把旧首页当成首页。
|
|
757
1828
|
*/
|
|
1829
|
+
async getPageMeta(forceUpdate = false) {
|
|
1830
|
+
return { ...(await this.load(forceUpdate)).meta };
|
|
1831
|
+
}
|
|
1832
|
+
/** 获取 tabBar 项,保留给既有调用方 */
|
|
758
1833
|
async getTabBar(forceUpdate = false) {
|
|
759
|
-
|
|
760
|
-
if (this.skipped) return void 0;
|
|
761
|
-
const { tabBar } = this.meta || {};
|
|
762
|
-
if (tabBar === void 0) return;
|
|
763
|
-
return {
|
|
764
|
-
...tabBar,
|
|
765
|
-
pagePath: tabBar.pagePath || this.uri,
|
|
766
|
-
index: tabBar.index ?? 0
|
|
767
|
-
};
|
|
1834
|
+
return (await this.load(forceUpdate)).tabBar;
|
|
768
1835
|
}
|
|
769
|
-
/**
|
|
770
|
-
* 确保页面文件至少被读取过一次,使 `skipped` 与缓存的配置反映
|
|
771
|
-
* 当前文件内容
|
|
772
|
-
*/
|
|
1836
|
+
/** 加载尚未读取的页面配置,缓存失效前不重复尝试失败的读取 */
|
|
773
1837
|
async ensureLoaded() {
|
|
774
|
-
|
|
1838
|
+
await this.load();
|
|
775
1839
|
}
|
|
776
1840
|
/**
|
|
777
|
-
*
|
|
778
|
-
*
|
|
1841
|
+
* 使页面读取缓存失效
|
|
1842
|
+
*
|
|
1843
|
+
* @description 下次访问时重新读取,保留上次成功快照作为读取失败时的回退
|
|
779
1844
|
*/
|
|
1845
|
+
invalidate() {
|
|
1846
|
+
this.loaded = false;
|
|
1847
|
+
this.readAttempted = false;
|
|
1848
|
+
}
|
|
1849
|
+
/** 检查页面是否发生变化 */
|
|
780
1850
|
hasChanged() {
|
|
781
1851
|
return this.changed;
|
|
782
1852
|
}
|
|
783
1853
|
/**
|
|
784
1854
|
* 读取页面文件并解析配置
|
|
785
|
-
*
|
|
1855
|
+
*
|
|
1856
|
+
* @description 成功后替换快照;失败时保留上次成功快照,只记录警告
|
|
786
1857
|
*/
|
|
787
1858
|
async read() {
|
|
1859
|
+
this.readAttempted = true;
|
|
788
1860
|
let meta;
|
|
789
1861
|
let skipped = false;
|
|
790
1862
|
try {
|
|
@@ -793,22 +1865,46 @@ var Page = class {
|
|
|
793
1865
|
else meta = result;
|
|
794
1866
|
} catch (err) {
|
|
795
1867
|
debug.error(err);
|
|
796
|
-
this.
|
|
1868
|
+
(this.environment.getLogger?.())?.warn(err?.message ?? String(err), { timestamp: true });
|
|
797
1869
|
return;
|
|
798
1870
|
}
|
|
799
1871
|
let raw = "";
|
|
800
1872
|
try {
|
|
801
1873
|
raw = JSON.stringify(meta) ?? "";
|
|
802
1874
|
} catch {}
|
|
803
|
-
|
|
804
|
-
this.loaded = true;
|
|
805
|
-
this.meta = meta;
|
|
1875
|
+
const changed = this.raw !== raw || this.skipped !== skipped;
|
|
806
1876
|
this.raw = raw;
|
|
807
|
-
this.
|
|
1877
|
+
this.loaded = true;
|
|
1878
|
+
this.snapshot = this.createSnapshot(meta, skipped, changed);
|
|
1879
|
+
}
|
|
1880
|
+
createSnapshot(meta, skipped, changed) {
|
|
1881
|
+
const { path, tabBar, ...others } = meta ?? {};
|
|
1882
|
+
return {
|
|
1883
|
+
meta: {
|
|
1884
|
+
path: path ?? this.uri,
|
|
1885
|
+
...others
|
|
1886
|
+
},
|
|
1887
|
+
tabBar: !skipped && tabBar ? {
|
|
1888
|
+
...tabBar,
|
|
1889
|
+
pagePath: tabBar.pagePath || this.uri,
|
|
1890
|
+
index: tabBar.index ?? 0
|
|
1891
|
+
} : void 0,
|
|
1892
|
+
skipped,
|
|
1893
|
+
changed
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
/** 读取失败且从未成功时的默认快照,保持页面仍以 uri 参与生成 */
|
|
1897
|
+
fallbackSnapshot() {
|
|
1898
|
+
return {
|
|
1899
|
+
meta: { path: this.uri },
|
|
1900
|
+
tabBar: void 0,
|
|
1901
|
+
skipped: false,
|
|
1902
|
+
changed: true
|
|
1903
|
+
};
|
|
808
1904
|
}
|
|
809
1905
|
async readPageMetaFromFile() {
|
|
810
1906
|
try {
|
|
811
|
-
const meta = await evaluateDefinePage(await fs.promises.readFile(this.path.absolutePath, { encoding: "utf-8" }), this.path.absolutePath, this.
|
|
1907
|
+
const meta = await evaluateDefinePage(await fs.promises.readFile(this.path.absolutePath, { encoding: "utf-8" }), this.path.absolutePath, this.environment.platform);
|
|
812
1908
|
return meta === void 0 ? { type: "page" } : meta;
|
|
813
1909
|
} catch (err) {
|
|
814
1910
|
throw new Error(`Read page meta fail in ${this.path.relativePath}\n${err.message}`);
|
|
@@ -816,6 +1912,619 @@ var Page = class {
|
|
|
816
1912
|
}
|
|
817
1913
|
};
|
|
818
1914
|
//#endregion
|
|
1915
|
+
//#region src/page-watch-filter.ts
|
|
1916
|
+
/**
|
|
1917
|
+
* 编译 Vite 的 ignored 规则,匹配单个页面来源的词法路径
|
|
1918
|
+
*
|
|
1919
|
+
* @description 返回 true 表示忽略;否定模式优先于其他匹配,目录祖先由调用方检查
|
|
1920
|
+
* @param ignored - Vite 的字符串、正则或函数过滤规则
|
|
1921
|
+
* @param root - 待检查路径的解析基准
|
|
1922
|
+
* @param cwd - watcher 为相对字符串规则指定的基准;未指定时与 chokidar 一致使用 process.cwd()
|
|
1923
|
+
*/
|
|
1924
|
+
function createPageWatchFilter(ignored, root, cwd = process.cwd()) {
|
|
1925
|
+
const base = cwd || process.cwd();
|
|
1926
|
+
const normalized = (ignored === void 0 ? [] : Array.isArray(ignored) ? ignored : [ignored]).map((matcher) => {
|
|
1927
|
+
if (typeof matcher !== "string") return matcher;
|
|
1928
|
+
const negative = matcher.startsWith("!");
|
|
1929
|
+
const pattern = negative ? matcher.slice(1) : matcher;
|
|
1930
|
+
const resolved = path.isAbsolute(pattern) || pattern.startsWith("**/") || pattern.startsWith("**\\") ? normalizePath(pattern) : normalizePath(path.resolve(path.join(base, pattern)));
|
|
1931
|
+
return negative ? `!${resolved}` : resolved;
|
|
1932
|
+
});
|
|
1933
|
+
const matchers = [...normalized, ...normalized.filter((matcher) => typeof matcher === "string" && !matcher.startsWith("!") && !picomatch.scan(matcher).isGlob).map((matcher) => `${matcher}/**`)];
|
|
1934
|
+
const negative = matchers.filter((matcher) => typeof matcher === "string" && matcher.startsWith("!")).map((matcher) => picomatch(matcher.slice(1), { dot: true }));
|
|
1935
|
+
const positive = matchers.filter((matcher) => typeof matcher !== "string" || !matcher.startsWith("!")).map((matcher) => {
|
|
1936
|
+
if (typeof matcher === "function") return matcher;
|
|
1937
|
+
if (matcher instanceof RegExp) return (file) => matcher.test(file);
|
|
1938
|
+
const matches = picomatch(matcher, { dot: true });
|
|
1939
|
+
return (file) => file === matcher || matches(file);
|
|
1940
|
+
});
|
|
1941
|
+
return (file, stats) => {
|
|
1942
|
+
const absolute = normalizePath(path.resolve(root, file));
|
|
1943
|
+
return !negative.some((matches) => matches(absolute)) && positive.some((matches) => matches(absolute, stats));
|
|
1944
|
+
};
|
|
1945
|
+
}
|
|
1946
|
+
//#endregion
|
|
1947
|
+
//#region src/page-watch-sources.ts
|
|
1948
|
+
/** 单轮来源发现最多登记的链接来源数,避免别名层叠造成指数级遍历和订阅膨胀 */
|
|
1949
|
+
const PAGE_WATCH_SOURCE_LIMIT = 1024;
|
|
1950
|
+
/** 目标不可访问与缺失一样按暂不可用处理,权限恢复后再由后续刷新重新发现 */
|
|
1951
|
+
function isUnavailableSourceError(error) {
|
|
1952
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
|
1953
|
+
const code = error.code;
|
|
1954
|
+
return code === "EACCES" || code === "EPERM";
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* 将监听目标统一到真实路径
|
|
1958
|
+
*
|
|
1959
|
+
* @description 与事件 identity 使用同一基准,避免目标拼写差异(大小写、Unicode
|
|
1960
|
+
* 规范化)导致映射失败;尚未创建的部分保留在最近存在祖先的真实路径下
|
|
1961
|
+
*/
|
|
1962
|
+
function canonicalTargetPath(target) {
|
|
1963
|
+
let current = target;
|
|
1964
|
+
const missing = [];
|
|
1965
|
+
while (true) try {
|
|
1966
|
+
const real = fs.realpathSync.native(current);
|
|
1967
|
+
return normalizePath(missing.length ? path.join(real, ...missing) : real);
|
|
1968
|
+
} catch (error) {
|
|
1969
|
+
if (!isMissingFsError(error)) return normalizePath(target);
|
|
1970
|
+
const parent = path.dirname(current);
|
|
1971
|
+
if (parent === current) return normalizePath(target);
|
|
1972
|
+
missing.unshift(path.basename(current));
|
|
1973
|
+
current = parent;
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
/** 逐段解析链接,保留悬空目标及恢复所需的链接入口 */
|
|
1977
|
+
function resolveWatchTarget(source) {
|
|
1978
|
+
let remaining = path.resolve(source);
|
|
1979
|
+
const links = /* @__PURE__ */ new Set();
|
|
1980
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1981
|
+
while (!visited.has(remaining) && visited.size < 40) {
|
|
1982
|
+
visited.add(remaining);
|
|
1983
|
+
const root = path.parse(remaining).root;
|
|
1984
|
+
const parts = remaining.slice(root.length).split(path.sep).filter(Boolean);
|
|
1985
|
+
let current = root;
|
|
1986
|
+
let redirected = false;
|
|
1987
|
+
let stat;
|
|
1988
|
+
for (const [index, part] of parts.entries()) {
|
|
1989
|
+
current = path.join(current, part);
|
|
1990
|
+
try {
|
|
1991
|
+
stat = fs.lstatSync(current, { bigint: true });
|
|
1992
|
+
if (stat.isSymbolicLink()) {
|
|
1993
|
+
links.add(normalizePath(current));
|
|
1994
|
+
let linkTarget;
|
|
1995
|
+
try {
|
|
1996
|
+
linkTarget = fs.readlinkSync(current);
|
|
1997
|
+
} catch (error) {
|
|
1998
|
+
if (!isMissingFsError(error) && !isUnavailableSourceError(error)) throw error;
|
|
1999
|
+
return {
|
|
2000
|
+
target: canonicalTargetPath(path.join(current, ...parts.slice(index + 1))),
|
|
2001
|
+
exists: false,
|
|
2002
|
+
links: [...links]
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
remaining = path.resolve(path.dirname(current), linkTarget, ...parts.slice(index + 1));
|
|
2006
|
+
redirected = true;
|
|
2007
|
+
break;
|
|
2008
|
+
}
|
|
2009
|
+
} catch (error) {
|
|
2010
|
+
if (!isMissingFsError(error) && !isUnavailableSourceError(error)) throw error;
|
|
2011
|
+
return {
|
|
2012
|
+
target: canonicalTargetPath(path.join(current, ...parts.slice(index + 1))),
|
|
2013
|
+
exists: false,
|
|
2014
|
+
links: [...links]
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
if (!redirected) {
|
|
2019
|
+
stat ??= fs.lstatSync(root, { bigint: true });
|
|
2020
|
+
return {
|
|
2021
|
+
target: canonicalTargetPath(current),
|
|
2022
|
+
exists: true,
|
|
2023
|
+
links: [...links],
|
|
2024
|
+
kind: stat.isDirectory() ? "directory" : "file",
|
|
2025
|
+
identity: `${stat.dev}:${stat.ino}`
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
return {
|
|
2030
|
+
target: canonicalTargetPath(remaining),
|
|
2031
|
+
exists: false,
|
|
2032
|
+
links: [...links]
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
* 发现声明目录及其嵌套链接的监听依赖
|
|
2037
|
+
*
|
|
2038
|
+
* @description 按词法入口应用过滤;同目标的别名分别保留,只有当前祖先链中的循环停止展开
|
|
2039
|
+
* 链接来源超过 {@link PAGE_WATCH_SOURCE_LIMIT} 时停止继续展开,页面扫描与生成不受影响
|
|
2040
|
+
*/
|
|
2041
|
+
function collectPageWatchSources(roots, excluded) {
|
|
2042
|
+
const directories = /* @__PURE__ */ new Map();
|
|
2043
|
+
const files = /* @__PURE__ */ new Map();
|
|
2044
|
+
const links = /* @__PURE__ */ new Set();
|
|
2045
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2046
|
+
let discovered = 0;
|
|
2047
|
+
let truncated = false;
|
|
2048
|
+
const visit = (source, target, ancestors) => {
|
|
2049
|
+
if (truncated || ancestors.has(target)) return;
|
|
2050
|
+
const branch = new Set(ancestors).add(target);
|
|
2051
|
+
let children = entries.get(target);
|
|
2052
|
+
if (!children) {
|
|
2053
|
+
try {
|
|
2054
|
+
children = fs.readdirSync(target, { withFileTypes: true });
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
if (!isMissingFsError(error) && !isUnavailableSourceError(error)) throw error;
|
|
2057
|
+
return;
|
|
2058
|
+
}
|
|
2059
|
+
entries.set(target, children);
|
|
2060
|
+
}
|
|
2061
|
+
for (const child of children) {
|
|
2062
|
+
if (truncated) return;
|
|
2063
|
+
if (!child.isDirectory() && !child.isSymbolicLink()) continue;
|
|
2064
|
+
const lexical = normalizePath(path.join(source, child.name));
|
|
2065
|
+
if (excluded(lexical)) continue;
|
|
2066
|
+
if (child.isSymbolicLink()) {
|
|
2067
|
+
if (discovered >= 1024) {
|
|
2068
|
+
truncated = true;
|
|
2069
|
+
return;
|
|
2070
|
+
}
|
|
2071
|
+
const resolved = resolveWatchTarget(lexical);
|
|
2072
|
+
const file = resolved.kind === "file" || !resolved.exists && isTargetFile(lexical);
|
|
2073
|
+
if (file && !isTargetFile(lexical)) continue;
|
|
2074
|
+
discovered++;
|
|
2075
|
+
for (const link of resolved.links) links.add(link);
|
|
2076
|
+
if (file) files.set(lexical, resolved);
|
|
2077
|
+
else {
|
|
2078
|
+
directories.set(lexical, resolved);
|
|
2079
|
+
if (resolved.exists) visit(lexical, resolved.target, branch);
|
|
2080
|
+
}
|
|
2081
|
+
} else visit(lexical, normalizePath(path.join(target, child.name)), branch);
|
|
2082
|
+
}
|
|
2083
|
+
};
|
|
2084
|
+
for (const root of roots) {
|
|
2085
|
+
if (truncated) break;
|
|
2086
|
+
if (excluded(root)) continue;
|
|
2087
|
+
const resolved = resolveWatchTarget(root);
|
|
2088
|
+
directories.set(root, resolved);
|
|
2089
|
+
for (const link of resolved.links) links.add(link);
|
|
2090
|
+
if (resolved.kind === "directory") visit(root, resolved.target, /* @__PURE__ */ new Set());
|
|
2091
|
+
}
|
|
2092
|
+
return {
|
|
2093
|
+
directories,
|
|
2094
|
+
files,
|
|
2095
|
+
links,
|
|
2096
|
+
truncated
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
//#endregion
|
|
2100
|
+
//#region src/scan-plan.ts
|
|
2101
|
+
/** 发现当前声明对应的扫描计划;目录、身份与回调都在这里刷新 */
|
|
2102
|
+
function createScanPlan(options) {
|
|
2103
|
+
const { sources, projection } = discoverSubPackageDirectories(options.subPackagePatterns, options.root, options.outDir, options.exclude);
|
|
2104
|
+
return {
|
|
2105
|
+
root: options.root,
|
|
2106
|
+
basePath: normalizePath(path.join(options.root, options.outDir)),
|
|
2107
|
+
mainDirs: resolvePageDirs(options.dir, options.root, options.exclude).map((dir) => dir.replace(/\/$/, "")),
|
|
2108
|
+
subPackageDirs: projection.subPackages,
|
|
2109
|
+
subPackageSources: sources,
|
|
2110
|
+
subPackageRootMap: new Map(projection.subPackageRootMap),
|
|
2111
|
+
rules: getPageRules(options)
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
/**
|
|
2115
|
+
* 把计划同步回 ResolvedOptions。
|
|
2116
|
+
*
|
|
2117
|
+
* `dirs`、`subPackages` 与 `subPackageRootMap` 是给既有调用方和测试看的
|
|
2118
|
+
* 兼容投影;内部扫描与监听应读取 ScanPlan,而不是这些字段。
|
|
2119
|
+
*/
|
|
2120
|
+
function applyScanPlan(options, plan) {
|
|
2121
|
+
options.dirs = [...plan.mainDirs];
|
|
2122
|
+
options.subPackages = [...plan.subPackageDirs];
|
|
2123
|
+
options.subPackageRootMap = new Map(plan.subPackageRootMap);
|
|
2124
|
+
}
|
|
2125
|
+
//#endregion
|
|
2126
|
+
//#region src/page-watch.ts
|
|
2127
|
+
function contains(directory, file) {
|
|
2128
|
+
return file === directory || file.startsWith(`${directory.replace(/\/$/, "")}/`);
|
|
2129
|
+
}
|
|
2130
|
+
function isDirectory(file) {
|
|
2131
|
+
try {
|
|
2132
|
+
return fs.statSync(file, { throwIfNoEntry: false })?.isDirectory() ?? false;
|
|
2133
|
+
} catch (error) {
|
|
2134
|
+
if (!isMissingFsError(error) && !isUnavailableSourceError(error) && error.code !== "ELOOP") throw error;
|
|
2135
|
+
return false;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
/**
|
|
2139
|
+
* 一轮监听刷新内复用的 Vite ignored 判定
|
|
2140
|
+
*
|
|
2141
|
+
* 监听检查沿候选路径逐级询问 ignored,同一批页面共享的祖先目录会在
|
|
2142
|
+
* 大量候选之间重复出现。每个路径在一轮内只求值一次,stat 次数从
|
|
2143
|
+
* “候选数 × 深度”降到“路径数”。来源结构或权限变化由下一次 refresh
|
|
2144
|
+
* 的 clear() 重新计算。
|
|
2145
|
+
*/
|
|
2146
|
+
var SourceIgnoreIndex = class {
|
|
2147
|
+
ignored;
|
|
2148
|
+
verdicts = /* @__PURE__ */ new Map();
|
|
2149
|
+
constructor(ignored) {
|
|
2150
|
+
this.ignored = ignored;
|
|
2151
|
+
}
|
|
2152
|
+
/** 丢弃本轮结论;新的来源结构、忽略规则或权限要重新询问 */
|
|
2153
|
+
clear() {
|
|
2154
|
+
this.verdicts.clear();
|
|
2155
|
+
}
|
|
2156
|
+
/** 判定路径是否被忽略;祖先结论会被后代复用 */
|
|
2157
|
+
matches(file, stats) {
|
|
2158
|
+
const cached = this.verdicts.get(file);
|
|
2159
|
+
if (cached !== void 0) return cached;
|
|
2160
|
+
let entry = stats;
|
|
2161
|
+
if (!entry) try {
|
|
2162
|
+
entry = fs.statSync(file, { throwIfNoEntry: false });
|
|
2163
|
+
} catch (error) {
|
|
2164
|
+
if (isUnavailableSourceError(error)) {
|
|
2165
|
+
this.verdicts.set(file, true);
|
|
2166
|
+
return true;
|
|
2167
|
+
}
|
|
2168
|
+
if (!isMissingFsError(error) && error.code !== "ELOOP") throw error;
|
|
2169
|
+
}
|
|
2170
|
+
if (this.ignored(file, entry)) {
|
|
2171
|
+
this.verdicts.set(file, true);
|
|
2172
|
+
return true;
|
|
2173
|
+
}
|
|
2174
|
+
const parent = normalizePath(path.dirname(file));
|
|
2175
|
+
const inherited = parent === file ? false : this.matches(parent);
|
|
2176
|
+
this.verdicts.set(file, inherited);
|
|
2177
|
+
return inherited;
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
/** 当前词法页面来源、物理内容订阅及非递归入口观察 */
|
|
2181
|
+
var PageSourceWatch = class {
|
|
2182
|
+
options;
|
|
2183
|
+
onFile;
|
|
2184
|
+
onStructure;
|
|
2185
|
+
onError;
|
|
2186
|
+
onWarning;
|
|
2187
|
+
rules;
|
|
2188
|
+
roots = /* @__PURE__ */ new Set();
|
|
2189
|
+
links = /* @__PURE__ */ new Set();
|
|
2190
|
+
directories = /* @__PURE__ */ new Map();
|
|
2191
|
+
files = /* @__PURE__ */ new Map();
|
|
2192
|
+
contentKey = "";
|
|
2193
|
+
contentRules;
|
|
2194
|
+
recoveryWatchers = /* @__PURE__ */ new Map();
|
|
2195
|
+
closing = /* @__PURE__ */ new Set();
|
|
2196
|
+
sourceRefreshQueued = false;
|
|
2197
|
+
started = false;
|
|
2198
|
+
warnedSourceLimit = false;
|
|
2199
|
+
usePolling = false;
|
|
2200
|
+
interval = 100;
|
|
2201
|
+
awaitWriteFinish;
|
|
2202
|
+
atomic;
|
|
2203
|
+
ignored;
|
|
2204
|
+
/** 当前 ignored 规则的判定缓存,随刷新清空 */
|
|
2205
|
+
sourceIgnored;
|
|
2206
|
+
watcher;
|
|
2207
|
+
constructor(options, onFile, onStructure, onError, onWarning = () => {}) {
|
|
2208
|
+
this.options = options;
|
|
2209
|
+
this.onFile = onFile;
|
|
2210
|
+
this.onStructure = onStructure;
|
|
2211
|
+
this.onError = onError;
|
|
2212
|
+
this.onWarning = onWarning;
|
|
2213
|
+
this.rules = getPageRules(options);
|
|
2214
|
+
}
|
|
2215
|
+
/** 内容监听是否已建立;启动失败时调用方可用其他事件源重试 */
|
|
2216
|
+
get running() {
|
|
2217
|
+
return this.started;
|
|
2218
|
+
}
|
|
2219
|
+
start(options = {}, ignored, plan) {
|
|
2220
|
+
if (this.started) return;
|
|
2221
|
+
const polling = process.env.CHOKIDAR_USEPOLLING?.toLowerCase();
|
|
2222
|
+
this.usePolling = polling === void 0 ? !!options.usePolling : !!polling && polling !== "false" && polling !== "0";
|
|
2223
|
+
const interval = process.env.CHOKIDAR_INTERVAL ? Number.parseInt(process.env.CHOKIDAR_INTERVAL, 10) : options.interval ?? 100;
|
|
2224
|
+
this.interval = Number.isFinite(interval) && interval > 0 ? interval : 100;
|
|
2225
|
+
this.awaitWriteFinish = options.awaitWriteFinish;
|
|
2226
|
+
this.atomic = options.atomic;
|
|
2227
|
+
this.ignored = ignored === void 0 || Array.isArray(ignored) && ignored.length === 0 ? void 0 : createPageWatchFilter(ignored, this.options.root, options.cwd ?? process.cwd());
|
|
2228
|
+
this.sourceIgnored = this.ignored ? new SourceIgnoreIndex(this.ignored) : void 0;
|
|
2229
|
+
this.started = true;
|
|
2230
|
+
try {
|
|
2231
|
+
this.refresh(plan ?? createScanPlan(this.options));
|
|
2232
|
+
} catch (error) {
|
|
2233
|
+
this.started = false;
|
|
2234
|
+
throw error;
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
ignoresSource(source, stats) {
|
|
2238
|
+
return this.sourceIgnored?.matches(source, stats) ?? false;
|
|
2239
|
+
}
|
|
2240
|
+
createContentWatcher() {
|
|
2241
|
+
const watcher = chokidar.watch([], {
|
|
2242
|
+
ignoreInitial: true,
|
|
2243
|
+
followSymlinks: false,
|
|
2244
|
+
usePolling: this.usePolling,
|
|
2245
|
+
interval: this.interval,
|
|
2246
|
+
...this.awaitWriteFinish !== void 0 && { awaitWriteFinish: this.awaitWriteFinish },
|
|
2247
|
+
...this.atomic !== void 0 && { atomic: this.atomic },
|
|
2248
|
+
ignored: (file, stats) => {
|
|
2249
|
+
const absolute = normalizePath(path.resolve(file));
|
|
2250
|
+
if (contains(normalizePath(path.resolve(this.options.root, this.options.outDir, "pages.json.lock")), absolute)) return true;
|
|
2251
|
+
for (const [source, { target }] of this.files) if (contains(absolute, target) && !this.rules.isExcluded(source) && !this.ignoresSource(source)) return false;
|
|
2252
|
+
for (const [source, { target }] of this.directories) {
|
|
2253
|
+
if (contains(absolute, target)) return false;
|
|
2254
|
+
if (contains(target, absolute)) {
|
|
2255
|
+
const lexical = normalizePath(path.join(source, path.relative(target, absolute)));
|
|
2256
|
+
if (!this.rules.isExcluded(lexical) && !this.ignoresSource(lexical, stats)) return false;
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
return true;
|
|
2260
|
+
}
|
|
2261
|
+
});
|
|
2262
|
+
for (const event of [
|
|
2263
|
+
"add",
|
|
2264
|
+
"change",
|
|
2265
|
+
"unlink"
|
|
2266
|
+
]) watcher.on(event, (file) => {
|
|
2267
|
+
if (!this.started || this.watcher !== watcher) return;
|
|
2268
|
+
if (this.links.has(normalizePath(path.resolve(file)))) this.queueSourceRefresh();
|
|
2269
|
+
else this.onFile(event, file);
|
|
2270
|
+
});
|
|
2271
|
+
watcher.on("raw", (event, file, raw) => {
|
|
2272
|
+
if (!this.started || this.watcher !== watcher) return;
|
|
2273
|
+
const details = raw ?? {};
|
|
2274
|
+
if (details.curr?.isDirectory()) this.queueSourceRefresh();
|
|
2275
|
+
else if (event === "rename" && details.watchedPath) {
|
|
2276
|
+
if (!file) {
|
|
2277
|
+
this.queueSourceRefresh();
|
|
2278
|
+
return;
|
|
2279
|
+
}
|
|
2280
|
+
const entry = normalizePath(path.resolve(details.watchedPath, file));
|
|
2281
|
+
try {
|
|
2282
|
+
if (this.links.has(entry) || fs.lstatSync(entry, { throwIfNoEntry: false })?.isSymbolicLink()) this.queueSourceRefresh();
|
|
2283
|
+
} catch (error) {
|
|
2284
|
+
if (!isMissingFsError(error)) this.onError(error);
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
});
|
|
2288
|
+
const onStructure = () => {
|
|
2289
|
+
if (this.started && this.watcher === watcher) this.onStructure();
|
|
2290
|
+
};
|
|
2291
|
+
watcher.on("addDir", onStructure);
|
|
2292
|
+
watcher.on("unlinkDir", onStructure);
|
|
2293
|
+
watcher.on("ready", onStructure);
|
|
2294
|
+
watcher.on("error", (error) => this.onError(error));
|
|
2295
|
+
return watcher;
|
|
2296
|
+
}
|
|
2297
|
+
/** 来源声明或扫描结果变化后重新解析当前目标 */
|
|
2298
|
+
refresh(plan) {
|
|
2299
|
+
if (!this.started) return;
|
|
2300
|
+
this.sourceIgnored?.clear();
|
|
2301
|
+
const rules = plan.rules;
|
|
2302
|
+
const currentDirectories = /* @__PURE__ */ new Set([
|
|
2303
|
+
...this.roots,
|
|
2304
|
+
...plan.mainDirs.map((dir) => normalizePath(path.resolve(this.options.root, dir))),
|
|
2305
|
+
...plan.subPackageDirs.map((dir) => normalizePath(path.resolve(this.options.root, dir)))
|
|
2306
|
+
]);
|
|
2307
|
+
for (const pattern of rules.patterns) {
|
|
2308
|
+
const portable = normalizePagePattern(pattern);
|
|
2309
|
+
if (!picomatch.scan(portable).isGlob) currentDirectories.add(normalizePath(path.resolve(this.options.root, unescapePagePattern(portable))));
|
|
2310
|
+
}
|
|
2311
|
+
this.roots = new Set([...currentDirectories].filter((source) => this.options.mergePages && rules.matchesDirectory(source)));
|
|
2312
|
+
const isExcluded = rules.createExcludeFilter();
|
|
2313
|
+
const sources = collectPageWatchSources(this.roots, (source) => isExcluded(source) || this.ignoresSource(source));
|
|
2314
|
+
this.rules = rules;
|
|
2315
|
+
this.directories = sources.directories;
|
|
2316
|
+
this.files = sources.files;
|
|
2317
|
+
this.links = sources.links;
|
|
2318
|
+
this.reconcile();
|
|
2319
|
+
if (sources.truncated) {
|
|
2320
|
+
if (!this.warnedSourceLimit) {
|
|
2321
|
+
this.warnedSourceLimit = true;
|
|
2322
|
+
this.onWarning(`Page watch discovery reached the ${PAGE_WATCH_SOURCE_LIMIT} linked-source safety limit and stopped expanding this round. Pages are still generated, but sources beyond the limit are not watched while it is reached. Narrow the page roots or exclude unused links to restore full watch coverage.`);
|
|
2323
|
+
}
|
|
2324
|
+
} else this.warnedSourceLimit = false;
|
|
2325
|
+
}
|
|
2326
|
+
fileForEvent(file, identity) {
|
|
2327
|
+
const absolute = normalizePath(path.resolve(this.options.root, file));
|
|
2328
|
+
if (isTargetFile(absolute) && isPageFileInDirectories(absolute, this.options) && !this.ignoresSource(absolute)) return absolute;
|
|
2329
|
+
for (const [source, { target }] of this.files) if (target === identity && isPageFileInDirectories(source, this.options) && !this.ignoresSource(source) && resolveWatchTarget(source).target === target) return source;
|
|
2330
|
+
for (const [source, { target }] of this.directories) {
|
|
2331
|
+
if (!contains(target, identity) || resolveWatchTarget(source).target !== target) continue;
|
|
2332
|
+
const lexical = normalizePath(path.join(source, path.relative(target, identity)));
|
|
2333
|
+
if (isTargetFile(lexical) && isPageFileInDirectories(lexical, this.options) && !this.ignoresSource(lexical) && resolveWatchTarget(lexical).target === identity) return lexical;
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
directoryForEvent(directory) {
|
|
2337
|
+
if (!this.options.mergePages) return false;
|
|
2338
|
+
const absolute = normalizePath(path.resolve(this.options.root, directory));
|
|
2339
|
+
if (!this.ignoresSource(absolute) && (getPageRules(this.options).matchesDirectory(absolute) || [...this.directories.keys()].some((source) => contains(absolute, source)))) return true;
|
|
2340
|
+
return [...this.directories, ...this.files].some(([source, { target }]) => contains(absolute, target) && (isPageDirectoryEvent(source, this.options) || isPageFileInDirectories(source, this.options)) && !this.ignoresSource(source) && resolveWatchTarget(source).target === target);
|
|
2341
|
+
}
|
|
2342
|
+
async close() {
|
|
2343
|
+
this.started = false;
|
|
2344
|
+
for (const { close } of this.recoveryWatchers.values()) close();
|
|
2345
|
+
this.recoveryWatchers.clear();
|
|
2346
|
+
this.contentKey = "";
|
|
2347
|
+
this.contentRules = void 0;
|
|
2348
|
+
this.sourceIgnored = void 0;
|
|
2349
|
+
this.warnedSourceLimit = false;
|
|
2350
|
+
const watcher = this.watcher;
|
|
2351
|
+
this.watcher = void 0;
|
|
2352
|
+
await Promise.all([watcher?.close(), ...this.closing]);
|
|
2353
|
+
}
|
|
2354
|
+
reconcile() {
|
|
2355
|
+
const directories = [...this.directories.values()].filter((source) => source.exists);
|
|
2356
|
+
const covered = (target) => directories.some((directory) => directory.target !== target && contains(directory.target, target));
|
|
2357
|
+
const wanted = /* @__PURE__ */ new Set();
|
|
2358
|
+
for (const target of [...directories, ...this.files.values()].filter((source) => source.exists)) if (!covered(target.target)) wanted.add(target.target);
|
|
2359
|
+
const key = this.sourceSignature();
|
|
2360
|
+
if (key !== this.contentKey || this.contentRules !== this.rules) {
|
|
2361
|
+
if (this.watcher) {
|
|
2362
|
+
const closing = this.watcher.close();
|
|
2363
|
+
this.closing.add(closing);
|
|
2364
|
+
closing.then(() => this.closing.delete(closing), (error) => {
|
|
2365
|
+
this.closing.delete(closing);
|
|
2366
|
+
this.onError(error);
|
|
2367
|
+
});
|
|
2368
|
+
this.watcher = void 0;
|
|
2369
|
+
}
|
|
2370
|
+
if (wanted.size) {
|
|
2371
|
+
this.watcher = this.createContentWatcher();
|
|
2372
|
+
this.watcher.add([...wanted]);
|
|
2373
|
+
}
|
|
2374
|
+
this.contentKey = key;
|
|
2375
|
+
this.contentRules = this.rules;
|
|
2376
|
+
}
|
|
2377
|
+
this.refreshEntrances();
|
|
2378
|
+
}
|
|
2379
|
+
refreshFromEntrance() {
|
|
2380
|
+
try {
|
|
2381
|
+
const previous = this.sourceSignature();
|
|
2382
|
+
this.refresh(createScanPlan(this.options));
|
|
2383
|
+
if (this.sourceSignature() !== previous) this.onStructure();
|
|
2384
|
+
} catch (error) {
|
|
2385
|
+
this.onError(error);
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
queueSourceRefresh() {
|
|
2389
|
+
if (this.sourceRefreshQueued) return;
|
|
2390
|
+
this.sourceRefreshQueued = true;
|
|
2391
|
+
queueMicrotask(() => {
|
|
2392
|
+
this.sourceRefreshQueued = false;
|
|
2393
|
+
if (this.started) this.refreshFromEntrance();
|
|
2394
|
+
});
|
|
2395
|
+
}
|
|
2396
|
+
sourceSignature() {
|
|
2397
|
+
return JSON.stringify([...this.directories, ...this.files].map(([source, { target, exists, kind, identity }]) => [
|
|
2398
|
+
source,
|
|
2399
|
+
target,
|
|
2400
|
+
exists,
|
|
2401
|
+
kind,
|
|
2402
|
+
kind === "directory" ? identity : null
|
|
2403
|
+
]).sort(([a], [b]) => String(a).localeCompare(String(b))));
|
|
2404
|
+
}
|
|
2405
|
+
refreshEntrances() {
|
|
2406
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
2407
|
+
const observe = (directory, entry) => {
|
|
2408
|
+
const normalized = normalizePath(directory);
|
|
2409
|
+
if (!entry) {
|
|
2410
|
+
wanted.set(normalized, void 0);
|
|
2411
|
+
return;
|
|
2412
|
+
}
|
|
2413
|
+
if (wanted.has(normalized) && !wanted.get(normalized)) return;
|
|
2414
|
+
const entries = wanted.get(normalized) ?? /* @__PURE__ */ new Set();
|
|
2415
|
+
entries.add(entry);
|
|
2416
|
+
wanted.set(normalized, entries);
|
|
2417
|
+
};
|
|
2418
|
+
const entrance = (file) => {
|
|
2419
|
+
let child = file;
|
|
2420
|
+
let directory = path.dirname(child);
|
|
2421
|
+
while (!isDirectory(directory)) {
|
|
2422
|
+
child = directory;
|
|
2423
|
+
const parent = path.dirname(directory);
|
|
2424
|
+
if (parent === directory) return;
|
|
2425
|
+
directory = parent;
|
|
2426
|
+
}
|
|
2427
|
+
observe(directory, path.basename(child));
|
|
2428
|
+
};
|
|
2429
|
+
for (const [source, resolved] of [...this.directories, ...this.files]) {
|
|
2430
|
+
entrance(source);
|
|
2431
|
+
entrance(resolved.target);
|
|
2432
|
+
for (const link of resolved.links) entrance(link);
|
|
2433
|
+
}
|
|
2434
|
+
if (this.options.mergePages) {
|
|
2435
|
+
const rules = getPageRules(this.options);
|
|
2436
|
+
for (const pattern of rules.patterns) {
|
|
2437
|
+
const portable = normalizePagePattern(pattern);
|
|
2438
|
+
const normalized = path.posix.normalize(portable);
|
|
2439
|
+
const scan = picomatch.scan(normalized, { parts: true });
|
|
2440
|
+
if (!scan.isGlob) continue;
|
|
2441
|
+
const base = normalizePath(path.resolve(this.options.root, unescapePagePattern(scan.base || ".")));
|
|
2442
|
+
if (rules.isExcluded(base) || this.ignoresSource(base)) continue;
|
|
2443
|
+
entrance(base);
|
|
2444
|
+
if (isDirectory(base)) observe(base);
|
|
2445
|
+
const parts = scan.parts ?? [];
|
|
2446
|
+
for (let length = 1; length < parts.length; length++) {
|
|
2447
|
+
const prefix = parts.slice(0, length).join("/") || "/";
|
|
2448
|
+
if (!picomatch.scan(prefix).isGlob) continue;
|
|
2449
|
+
const directories = globSync(prefix, {
|
|
2450
|
+
cwd: this.options.root,
|
|
2451
|
+
onlyDirectories: true,
|
|
2452
|
+
expandDirectories: false,
|
|
2453
|
+
dot: true,
|
|
2454
|
+
ignore: rules.traversalIgnores
|
|
2455
|
+
});
|
|
2456
|
+
for (const directory of directories) {
|
|
2457
|
+
const absolute = normalizePath(path.resolve(this.options.root, directory));
|
|
2458
|
+
if (!rules.isExcluded(absolute) && !this.ignoresSource(absolute)) {
|
|
2459
|
+
entrance(absolute);
|
|
2460
|
+
observe(absolute);
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
for (const [directory, entry] of this.recoveryWatchers) if (!wanted.has(directory)) {
|
|
2467
|
+
entry.close();
|
|
2468
|
+
this.recoveryWatchers.delete(directory);
|
|
2469
|
+
}
|
|
2470
|
+
for (const [directory, entries] of wanted) try {
|
|
2471
|
+
const stat = fs.statSync(directory, { bigint: true });
|
|
2472
|
+
const identity = `${stat.dev}:${stat.ino}`;
|
|
2473
|
+
const existing = this.recoveryWatchers.get(directory);
|
|
2474
|
+
if (existing?.identity === identity) {
|
|
2475
|
+
existing.entries = entries;
|
|
2476
|
+
continue;
|
|
2477
|
+
}
|
|
2478
|
+
existing?.close();
|
|
2479
|
+
let entry;
|
|
2480
|
+
let watcher;
|
|
2481
|
+
let stop;
|
|
2482
|
+
if (this.usePolling) {
|
|
2483
|
+
const onChange = () => {
|
|
2484
|
+
if (this.recoveryWatchers.get(directory) === entry) this.queueSourceRefresh();
|
|
2485
|
+
};
|
|
2486
|
+
watcher = fs.watchFile(directory, {
|
|
2487
|
+
persistent: false,
|
|
2488
|
+
interval: this.interval
|
|
2489
|
+
}, onChange);
|
|
2490
|
+
stop = () => fs.unwatchFile(directory, onChange);
|
|
2491
|
+
} else {
|
|
2492
|
+
const nativeWatcher = fs.watch(directory, {
|
|
2493
|
+
recursive: false,
|
|
2494
|
+
persistent: false
|
|
2495
|
+
}, (event, filename) => {
|
|
2496
|
+
const observed = this.recoveryWatchers.get(directory);
|
|
2497
|
+
if (observed !== entry || event !== "rename") return;
|
|
2498
|
+
const name = filename?.toString();
|
|
2499
|
+
if (!name || !observed.entries || observed.entries.has(name) || name === path.basename(directory)) this.refreshFromEntrance();
|
|
2500
|
+
});
|
|
2501
|
+
watcher = nativeWatcher;
|
|
2502
|
+
stop = () => nativeWatcher.close();
|
|
2503
|
+
}
|
|
2504
|
+
const onError = (error) => {
|
|
2505
|
+
if (this.recoveryWatchers.get(directory) !== entry) return;
|
|
2506
|
+
entry.close();
|
|
2507
|
+
this.recoveryWatchers.delete(directory);
|
|
2508
|
+
if (!isMissingFsError(error)) this.onError(error);
|
|
2509
|
+
if (this.started) this.refreshFromEntrance();
|
|
2510
|
+
};
|
|
2511
|
+
watcher.on("error", onError);
|
|
2512
|
+
entry = {
|
|
2513
|
+
watcher,
|
|
2514
|
+
entries,
|
|
2515
|
+
identity,
|
|
2516
|
+
close: () => {
|
|
2517
|
+
watcher.off("error", onError);
|
|
2518
|
+
stop();
|
|
2519
|
+
}
|
|
2520
|
+
};
|
|
2521
|
+
this.recoveryWatchers.set(directory, entry);
|
|
2522
|
+
} catch (error) {
|
|
2523
|
+
if (!isMissingFsError(error) && !isUnavailableSourceError(error)) this.onError(error);
|
|
2524
|
+
}
|
|
2525
|
+
}
|
|
2526
|
+
};
|
|
2527
|
+
//#endregion
|
|
819
2528
|
//#region src/platform-variants.ts
|
|
820
2529
|
/**
|
|
821
2530
|
* 把 `||` 分隔的平台列表拆开,去掉当前平台,剩下的排好序(规则 1)
|
|
@@ -830,7 +2539,7 @@ function platformsExcluding(platformList, currentPlatform) {
|
|
|
830
2539
|
return platformList.split("||").map((p) => p.trim()).filter((p) => p && p !== currentPlatform).sort();
|
|
831
2540
|
}
|
|
832
2541
|
/**
|
|
833
|
-
*
|
|
2542
|
+
* 把本轮的一个载荷并入变体列表(规则 2):
|
|
834
2543
|
* - 内容相同的手写 #ifndef 变体优先:当前平台没被排除时,那条
|
|
835
2544
|
* #ifndef 已经覆盖了它;当前平台正好被排除时,尊重手写的隐藏规
|
|
836
2545
|
* 则。两种情况下再单独写一份都会产生重复路由或覆盖用户的条件
|
|
@@ -838,7 +2547,7 @@ function platformsExcluding(platformList, currentPlatform) {
|
|
|
838
2547
|
* - 没有内容相同的变体:新建只属于当前平台的变体
|
|
839
2548
|
*
|
|
840
2549
|
* @param variants - 同一个键下已有的变体列表,原地修改
|
|
841
|
-
* @param payload -
|
|
2550
|
+
* @param payload - 本轮的载荷
|
|
842
2551
|
* @param valueStr - 载荷的比较字符串
|
|
843
2552
|
* @param currentPlatform - 当前平台标识(大写)
|
|
844
2553
|
* @param compatible - 可选的额外相容判断。数组侧用它区分两个平台各自
|
|
@@ -854,90 +2563,391 @@ function upsertCurrentVariant(variants, payload, valueStr, currentPlatform, comp
|
|
|
854
2563
|
equal.platformStr = equal.platforms.join(" || ");
|
|
855
2564
|
return;
|
|
856
2565
|
}
|
|
857
|
-
variants.push({
|
|
858
|
-
payload,
|
|
859
|
-
valueStr,
|
|
860
|
-
platforms: [currentPlatform],
|
|
861
|
-
platformStr: currentPlatform
|
|
862
|
-
});
|
|
2566
|
+
variants.push({
|
|
2567
|
+
payload,
|
|
2568
|
+
valueStr,
|
|
2569
|
+
platforms: [currentPlatform],
|
|
2570
|
+
platformStr: currentPlatform
|
|
2571
|
+
});
|
|
2572
|
+
}
|
|
2573
|
+
/**
|
|
2574
|
+
* 输出前按平台列表把变体排好序(规则 4)
|
|
2575
|
+
*
|
|
2576
|
+
* 当前平台的变体在收集时被排除、并入时又补到列表末尾,两个平台轮流
|
|
2577
|
+
* 运行(dev:h5 和 dev:mp-weixin 交替写)时,同一个键的变体顺序就会
|
|
2578
|
+
* 来回翻转。条件编译的结果没变,但文件每次都有无意义的变动。
|
|
2579
|
+
* platformStr 由排好序的平台列表拼成,手写 #ifndef 变体是空串、排最
|
|
2580
|
+
* 前。排序是稳定的:并列时(同键两组平台列表相同,只出现在手写文件
|
|
2581
|
+
* 里)保持收集顺序
|
|
2582
|
+
*/
|
|
2583
|
+
function sortVariants(variants) {
|
|
2584
|
+
variants.sort((a, b) => a.platformStr < b.platformStr ? -1 : a.platformStr > b.platformStr ? 1 : 0);
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* 决定变体列表的输出顺序(规则 6)
|
|
2588
|
+
*
|
|
2589
|
+
* 此前条目一律按磁盘上的旧顺序输出、配置里新增的条目追加到末尾:
|
|
2590
|
+
* 「哪个平台先构建」决定了文件长什么样,配置里的声明顺序会被丢掉
|
|
2591
|
+
* (比如某平台把一个新条目声明在 tabBar 第二位,生成的文件里却垫
|
|
2592
|
+
* 着底,该平台编译剥掉注释后实际顺序就是错的)。
|
|
2593
|
+
*
|
|
2594
|
+
* 排序分两种情况:
|
|
2595
|
+
* - 配置声明了全部既有键:这是全量超集,声明顺序是唯一已知的权威
|
|
2596
|
+
* 顺序,整个列表按配置顺序输出
|
|
2597
|
+
* - 配置没有覆盖全部键(其他平台有本平台不认识的条目,谁也不知道
|
|
2598
|
+
* 完整顺序):既有键保持磁盘序,只把新增的键插到它前面最近
|
|
2599
|
+
* 的、已在输出里的声明键之后;没有这样的前驱就放到最前。既有键
|
|
2600
|
+
* 之间的相对顺序永不变动,所以两端构建不会来回翻转
|
|
2601
|
+
*
|
|
2602
|
+
* 两个平台的配置都覆盖全部键但顺序不同时,共享文件跟随最后写入者。
|
|
2603
|
+
* 条目内容相同而合并成一条时没有按平台区分的副本,另一个正在运行
|
|
2604
|
+
* 的平台在下一次生成前可能读到对方顺序;并发开发时建议各平台保持
|
|
2605
|
+
* 一致的完整 tab 顺序。
|
|
2606
|
+
*
|
|
2607
|
+
* @param mergedMap - 键 → 变体列表的合并结果。迭代顺序一般是磁盘序,
|
|
2608
|
+
* 但被跳过的当前平台旧条目会追加到末尾,需要靠 options.diskOrder 修正
|
|
2609
|
+
* @param declaredKeys - 配置声明的键,按配置顺序,可含新增键;
|
|
2610
|
+
* 传 null 表示不启用配置序摆放,保持磁盘序
|
|
2611
|
+
* @param options - 磁盘上已有键的顺序,见 {@link OrderVariantListsOptions}
|
|
2612
|
+
* @returns 按输出顺序排列的变体列表(mergedMap 中列表的原引用)
|
|
2613
|
+
*/
|
|
2614
|
+
function orderVariantLists(mergedMap, declaredKeys, options = {}) {
|
|
2615
|
+
const diskOrder = [...mergedMap.keys()];
|
|
2616
|
+
if (mergedMap.size === 0 || declaredKeys === null) return diskOrder.map((key) => mergedMap.get(key));
|
|
2617
|
+
const declared = [...new Set(declaredKeys)].filter((key) => mergedMap.has(key));
|
|
2618
|
+
const declaredSet = new Set(declared);
|
|
2619
|
+
if (diskOrder.every((key) => declaredSet.has(key))) return declared.map((key) => mergedMap.get(key));
|
|
2620
|
+
const ordered = (options.diskOrder ?? diskOrder).filter((key) => mergedMap.has(key));
|
|
2621
|
+
const placed = new Set(ordered);
|
|
2622
|
+
for (const [index, key] of declared.entries()) {
|
|
2623
|
+
if (placed.has(key)) continue;
|
|
2624
|
+
let anchor = -1;
|
|
2625
|
+
for (let i = index - 1; i >= 0; i--) {
|
|
2626
|
+
const candidate = ordered.indexOf(declared[i]);
|
|
2627
|
+
if (candidate !== -1) {
|
|
2628
|
+
anchor = candidate;
|
|
2629
|
+
break;
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
ordered.splice(anchor + 1, 0, key);
|
|
2633
|
+
placed.add(key);
|
|
2634
|
+
}
|
|
2635
|
+
for (const key of diskOrder) if (!placed.has(key)) {
|
|
2636
|
+
ordered.push(key);
|
|
2637
|
+
placed.add(key);
|
|
2638
|
+
}
|
|
2639
|
+
return ordered.map((key) => mergedMap.get(key));
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* 收集所有变体记录过的平台(手写 #ifndef 不算,它没有正向列表),
|
|
2643
|
+
* 这个集合同时也是「拥有至少一个变体」的平台集合
|
|
2644
|
+
*/
|
|
2645
|
+
function collectVariantPlatforms(mergedMap) {
|
|
2646
|
+
const platforms = /* @__PURE__ */ new Set();
|
|
2647
|
+
for (const variants of mergedMap.values()) for (const { platforms: variantPlatforms } of variants) if (variantPlatforms) for (const platform of variantPlatforms) platforms.add(platform);
|
|
2648
|
+
return platforms;
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* 把所有变体记录的平台合在一起,算出「平台全集」
|
|
2652
|
+
*
|
|
2653
|
+
* 平台全集会写进生成标记,也决定哪些变体可以不加 #ifdef 直接输出:
|
|
2654
|
+
* 没被包裹的条目在 uni-app 条件编译下所有平台都看得见,所以只有
|
|
2655
|
+
* 覆盖了全部平台的变体才能"裸着"输出(规则 5)。
|
|
2656
|
+
*
|
|
2657
|
+
* 当前平台一定在全集里,哪怕这次运行一个变体都没贡献。比如页面
|
|
2658
|
+
* 只在 H5 存在,而 MP-WEIXIN 运行把每个页面都 definePage(null) 掉了。
|
|
2659
|
+
* 如果只从剩下的条目推全集,全集就只有 'H5',H5 专属条目看起来
|
|
2660
|
+
* "覆盖了全集",会不加包裹地输出,泄漏进微信的构建产物。老版本按
|
|
2661
|
+
* "最常用平台组合当默认值"的做法也有同样的问题:可能算出单平台
|
|
2662
|
+
* 组合,把那个平台的条目裸着输出,变成其他平台里的重复路由。这个
|
|
2663
|
+
* 全集同样管着 tabBar 属性的包裹:没有它,一次没有 tabBar 的运行
|
|
2664
|
+
* 会以为"拥有平台 == 全集",把别的平台的 tabBar 裸着输出出去。
|
|
2665
|
+
*
|
|
2666
|
+
* 上一次运行记在标记里的平台也进全集({@link extractLastPlatforms})。
|
|
2667
|
+
* 否则当某平台的条目都被重新扫描替换后,它"来过"这件事只记在标记
|
|
2668
|
+
* 里:只看条目推全集,全集会一会儿大一会儿小,条目一会儿包一会儿
|
|
2669
|
+
* 裸。把标记也算进来,全集就只增不减;多算的平台最多带来多余的包
|
|
2670
|
+
* 裹,不会泄漏。
|
|
2671
|
+
*
|
|
2672
|
+
* 只增不减的代价:彻底不用的平台会一直留在标记里。这无害,但别
|
|
2673
|
+
* 手工去改标记行。想清理就删掉整个生成的 pages.json,下次运行会
|
|
2674
|
+
* 从头生成。
|
|
2675
|
+
*/
|
|
2676
|
+
function resolvePlatformUnion(mergedMap, currentPlatform, lastPlatforms) {
|
|
2677
|
+
return [.../* @__PURE__ */ new Set([
|
|
2678
|
+
currentPlatform,
|
|
2679
|
+
...lastPlatforms,
|
|
2680
|
+
...collectVariantPlatforms(mergedMap)
|
|
2681
|
+
])].sort();
|
|
2682
|
+
}
|
|
2683
|
+
const GENERATION_MARKER_PREFIX = "GENERATED BY UNI-PAGES, PLATFORM:";
|
|
2684
|
+
/** 判断注释令牌是否为 pages.json 的生成标记行 */
|
|
2685
|
+
function isGenerationMarker(token) {
|
|
2686
|
+
return token.type !== "BlankLine" && typeof token.value === "string" && token.value.trim().startsWith("GENERATED BY UNI-PAGES, PLATFORM:");
|
|
2687
|
+
}
|
|
2688
|
+
/** 判断一个 pages 数组是否由插件写入(携带生成标记) */
|
|
2689
|
+
function hasGenerationMarker(src) {
|
|
2690
|
+
if (!src) return false;
|
|
2691
|
+
return (src[Symbol.for("before:0")] || []).some(isGenerationMarker);
|
|
2692
|
+
}
|
|
2693
|
+
/**
|
|
2694
|
+
* 从 before:0 的生成标记里读出上一次运行记录了哪些平台,
|
|
2695
|
+
* 去掉当前平台后返回
|
|
2696
|
+
*/
|
|
2697
|
+
function extractLastPlatforms(src, currentPlatform) {
|
|
2698
|
+
let lastPlatforms = [];
|
|
2699
|
+
for (const comment of src[Symbol.for("before:0")] || []) {
|
|
2700
|
+
if (comment.type === "BlankLine") continue;
|
|
2701
|
+
const trimmed = comment.value.trim();
|
|
2702
|
+
if (trimmed.startsWith("GENERATED BY UNI-PAGES, PLATFORM:")) lastPlatforms = platformsExcluding(trimmed.split(":")[1], currentPlatform);
|
|
2703
|
+
}
|
|
2704
|
+
return lastPlatforms;
|
|
2705
|
+
}
|
|
2706
|
+
//#endregion
|
|
2707
|
+
//#region src/pages-json-tokens.ts
|
|
2708
|
+
/** 构建用于序列化 pages.json 输出或数组元素包裹的行注释令牌 */
|
|
2709
|
+
function lineComment(value) {
|
|
2710
|
+
return {
|
|
2711
|
+
type: "LineComment",
|
|
2712
|
+
value,
|
|
2713
|
+
inline: false,
|
|
2714
|
+
loc: {
|
|
2715
|
+
start: {
|
|
2716
|
+
line: 0,
|
|
2717
|
+
column: 0
|
|
2718
|
+
},
|
|
2719
|
+
end: {
|
|
2720
|
+
line: 0,
|
|
2721
|
+
column: 0
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
};
|
|
2725
|
+
}
|
|
2726
|
+
/**
|
|
2727
|
+
* 找到条目前面的条件编译开启指令。
|
|
2728
|
+
*
|
|
2729
|
+
* comment-json 会把包裹层的 #endif(输出在值的逗号后面)挂到下一个条目
|
|
2730
|
+
* 前面,所以只认 #ifdef/#ifndef 开头,绝不能把 #endif 当成开启符。
|
|
2731
|
+
*/
|
|
2732
|
+
function findConditionalComment(beforeComments) {
|
|
2733
|
+
return beforeComments?.find((comment) => comment.type !== "BlankLine" && /^#(?:ifdef|ifndef)/.test(comment.value.trim()));
|
|
2734
|
+
}
|
|
2735
|
+
/**
|
|
2736
|
+
* 手写 #ifndef 块原样保留时清理包裹注释。
|
|
2737
|
+
*
|
|
2738
|
+
* 只保留开启这个块的那条指令和用户写的说明文字;前一个块收尾的 #endif
|
|
2739
|
+
* 和重复的结构指令都要丢掉,否则每次重跑都会多出游离的 #endif 或嵌套。
|
|
2740
|
+
*/
|
|
2741
|
+
function sanitizePassthroughComments(beforeComments, opening) {
|
|
2742
|
+
const sanitized = [];
|
|
2743
|
+
let openingKept = false;
|
|
2744
|
+
for (const comment of beforeComments || []) {
|
|
2745
|
+
if (isGenerationMarker(comment)) continue;
|
|
2746
|
+
if (comment.type === "BlankLine") {
|
|
2747
|
+
sanitized.push(comment);
|
|
2748
|
+
continue;
|
|
2749
|
+
}
|
|
2750
|
+
if (/^#(?:ifdef|ifndef|endif)/.test(comment.value.trim())) {
|
|
2751
|
+
if (!openingKept && comment === opening) {
|
|
2752
|
+
sanitized.push(comment);
|
|
2753
|
+
openingKept = true;
|
|
2754
|
+
}
|
|
2755
|
+
continue;
|
|
2756
|
+
}
|
|
2757
|
+
sanitized.push(comment);
|
|
2758
|
+
}
|
|
2759
|
+
return sanitized;
|
|
2760
|
+
}
|
|
2761
|
+
//#endregion
|
|
2762
|
+
//#region src/pages-json-items.ts
|
|
2763
|
+
/**
|
|
2764
|
+
* 把条目转成字符串用于比较,比较前先拿掉内部的 `type` 标记。
|
|
2765
|
+
*
|
|
2766
|
+
* 从 pages.json 读回来的条目可能没有这个标记(手写条目从不带它),
|
|
2767
|
+
* 直接 JSON.stringify 会把同一个页面当成两个不同的条目,多平台运行时
|
|
2768
|
+
* 就会生成重复路由(见 https://github.com/uni-helper/vite-plugin-uni-pages/issues/283)。
|
|
2769
|
+
*
|
|
2770
|
+
* 键的顺序也参与比较(JSON.stringify 按写入顺序输出):同一页面在两个
|
|
2771
|
+
* 平台下键序不同时不会被合并,会各占一个 #ifdef 块留在文件里。代价只是
|
|
2772
|
+
* 多一份内容相同的变体,构建时每个平台仍只看自己那一条。
|
|
2773
|
+
*/
|
|
2774
|
+
function stringifyForCompare(val) {
|
|
2775
|
+
if ("type" in val) {
|
|
2776
|
+
const { type: _type, ...rest } = val;
|
|
2777
|
+
return JSON.stringify(rest);
|
|
2778
|
+
}
|
|
2779
|
+
return JSON.stringify(val);
|
|
2780
|
+
}
|
|
2781
|
+
/**
|
|
2782
|
+
* 两个内容相同的条目,首页状态是否一致?
|
|
2783
|
+
*
|
|
2784
|
+
* `type` 标记不参与内容比较,没有标记的条目也能和扫描到的条目合并。
|
|
2785
|
+
* 但如果两边都明确带着标记、而且一个是 'home' 一个是 'page',说明这是
|
|
2786
|
+
* 两个平台各自声明的不同首页,必须留在各自的 #ifdef 块里。
|
|
2787
|
+
*/
|
|
2788
|
+
function homeStatusCompatible(a, b) {
|
|
2789
|
+
const typeA = a.type;
|
|
2790
|
+
const typeB = b.type;
|
|
2791
|
+
return typeA === void 0 || typeB === void 0 || typeA === typeB;
|
|
2792
|
+
}
|
|
2793
|
+
/**
|
|
2794
|
+
* 合并多平台的配置条目(数组侧适配器)。
|
|
2795
|
+
*
|
|
2796
|
+
* 处理条件编译注释(#ifdef / #ifndef / #endif),把 pages.json 里
|
|
2797
|
+
* 已有的条目和本轮扫描的条目合并成一个数组;合并规则(同值叠平台、
|
|
2798
|
+
* 排除当前平台、排序、并集)用 platform-variants.ts 的共享核心。
|
|
2799
|
+
*
|
|
2800
|
+
* @param source - 现有条目数组(来自 pages.json)
|
|
2801
|
+
* @param currentPlatform - 当前平台标识(如 H5、MP-WEIXIN)
|
|
2802
|
+
* @param items - 新配置条目数组
|
|
2803
|
+
* @param uniqueKeyName - 用于识别条目唯一性的字段名(如 'path' 或 'pagePath')
|
|
2804
|
+
* @param options - 输出顺序选项,见 {@link MergePlatformItemsOptions}
|
|
2805
|
+
* @returns 带 #ifdef 块的合并条目,以及平台全集与拥有平台
|
|
2806
|
+
*/
|
|
2807
|
+
function mergePlatformItems(source, currentPlatform, items, uniqueKeyName, options = {}) {
|
|
2808
|
+
const { orderByConfig = false } = options;
|
|
2809
|
+
const src = source || new CommentArray();
|
|
2810
|
+
currentPlatform = currentPlatform.toUpperCase();
|
|
2811
|
+
const lastPlatforms = extractLastPlatforms(src, currentPlatform);
|
|
2812
|
+
const mergedMap = /* @__PURE__ */ new Map();
|
|
2813
|
+
const sourceOrder = orderByConfig ? {
|
|
2814
|
+
seen: /* @__PURE__ */ new Set(),
|
|
2815
|
+
order: []
|
|
2816
|
+
} : void 0;
|
|
2817
|
+
const variantsOf = (uniqueKey) => {
|
|
2818
|
+
const list = mergedMap.get(uniqueKey) || [];
|
|
2819
|
+
mergedMap.set(uniqueKey, list);
|
|
2820
|
+
return list;
|
|
2821
|
+
};
|
|
2822
|
+
for (let i = 0; i < src.length; i++) {
|
|
2823
|
+
const item = src[i];
|
|
2824
|
+
const uniqueKey = item[uniqueKeyName];
|
|
2825
|
+
if (!uniqueKey) continue;
|
|
2826
|
+
if (sourceOrder && !sourceOrder.seen.has(uniqueKey)) {
|
|
2827
|
+
sourceOrder.seen.add(uniqueKey);
|
|
2828
|
+
sourceOrder.order.push(uniqueKey);
|
|
2829
|
+
}
|
|
2830
|
+
const beforeComments = src[Symbol.for(`before:${i}`)];
|
|
2831
|
+
const conditionalComment = findConditionalComment(beforeComments);
|
|
2832
|
+
if (conditionalComment?.value.trim().startsWith("#ifndef")) {
|
|
2833
|
+
variantsOf(uniqueKey).push({
|
|
2834
|
+
payload: item,
|
|
2835
|
+
valueStr: stringifyForCompare(item),
|
|
2836
|
+
platforms: null,
|
|
2837
|
+
platformStr: "",
|
|
2838
|
+
passthrough: {
|
|
2839
|
+
before: sanitizePassthroughComments(beforeComments, conditionalComment),
|
|
2840
|
+
after: [lineComment(" #endif")]
|
|
2841
|
+
}
|
|
2842
|
+
});
|
|
2843
|
+
continue;
|
|
2844
|
+
}
|
|
2845
|
+
let platforms = [...lastPlatforms];
|
|
2846
|
+
if (conditionalComment) {
|
|
2847
|
+
const match = conditionalComment.value.match(/#ifdef\s+(.+)/);
|
|
2848
|
+
if (match) platforms = platformsExcluding(match[1], currentPlatform);
|
|
2849
|
+
}
|
|
2850
|
+
if (platforms.length === 0) continue;
|
|
2851
|
+
variantsOf(uniqueKey).push({
|
|
2852
|
+
payload: item,
|
|
2853
|
+
valueStr: stringifyForCompare(item),
|
|
2854
|
+
platforms,
|
|
2855
|
+
platformStr: platforms.join(" || ")
|
|
2856
|
+
});
|
|
2857
|
+
}
|
|
2858
|
+
const orderOptions = sourceOrder ? { diskOrder: sourceOrder.order } : void 0;
|
|
2859
|
+
for (const item of items) {
|
|
2860
|
+
const uniqueKey = item[uniqueKeyName];
|
|
2861
|
+
if (!uniqueKey) continue;
|
|
2862
|
+
upsertCurrentVariant(variantsOf(uniqueKey), item, stringifyForCompare(item), currentPlatform, homeStatusCompatible);
|
|
2863
|
+
}
|
|
2864
|
+
const result = new CommentArray();
|
|
2865
|
+
for (const variants of mergedMap.values()) sortVariants(variants);
|
|
2866
|
+
const platformUnion = resolvePlatformUnion(mergedMap, currentPlatform, lastPlatforms);
|
|
2867
|
+
const platformUnionStr = platformUnion.join(" || ");
|
|
2868
|
+
const owningPlatforms = collectVariantPlatforms(mergedMap);
|
|
2869
|
+
result[Symbol.for("before:0")] = [lineComment(` ${GENERATION_MARKER_PREFIX} ${platformUnionStr}`)];
|
|
2870
|
+
const declaredKeys = orderByConfig ? items.map((item) => item[uniqueKeyName]).filter((key) => typeof key === "string" && key.length > 0) : null;
|
|
2871
|
+
for (const list of orderVariantLists(mergedMap, declaredKeys, orderOptions)) for (const { payload: item, platformStr, passthrough } of list) {
|
|
2872
|
+
result.push(item);
|
|
2873
|
+
if (passthrough) {
|
|
2874
|
+
result[Symbol.for(`before:${result.length - 1}`)] = [...result[Symbol.for(`before:${result.length - 1}`)] || [], ...passthrough.before];
|
|
2875
|
+
if (passthrough.after.length > 0) result[Symbol.for(`after:${result.length - 1}`)] = passthrough.after;
|
|
2876
|
+
continue;
|
|
2877
|
+
}
|
|
2878
|
+
if (platformStr !== platformUnionStr) {
|
|
2879
|
+
result[Symbol.for(`before:${result.length - 1}`)] = [...result[Symbol.for(`before:${result.length - 1}`)] || [], lineComment(` #ifdef ${platformStr}`)];
|
|
2880
|
+
result[Symbol.for(`after:${result.length - 1}`)] = [lineComment(" #endif")];
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
return {
|
|
2884
|
+
items: result,
|
|
2885
|
+
platformUnion,
|
|
2886
|
+
owningPlatforms: [...owningPlatforms].sort()
|
|
2887
|
+
};
|
|
863
2888
|
}
|
|
2889
|
+
//#endregion
|
|
2890
|
+
//#region src/pages-json-structure.ts
|
|
864
2891
|
/**
|
|
865
|
-
*
|
|
2892
|
+
* 把所有首页条目移到最前面,注释跟着条目一起移动。
|
|
866
2893
|
*
|
|
867
|
-
*
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
871
|
-
* 前。排序是稳定的:并列时(同键两组平台列表相同,只出现在手写文件
|
|
872
|
-
* 里)保持收集顺序
|
|
873
|
-
*/
|
|
874
|
-
function sortVariants(variants) {
|
|
875
|
-
variants.sort((a, b) => a.platformStr < b.platformStr ? -1 : a.platformStr > b.platformStr ? 1 : 0);
|
|
876
|
-
}
|
|
877
|
-
/**
|
|
878
|
-
* 收集所有变体记录过的平台(手写 #ifndef 不算,它没有正向列表),
|
|
879
|
-
* 这个集合同时也是「拥有至少一个变体」的平台集合
|
|
2894
|
+
* 每个平台可以在自己的 #ifdef 块里声明自己的首页,没被包裹的条目
|
|
2895
|
+
* 所有平台都能看到。所以一个平台的首页必须排在它可见的所有条目
|
|
2896
|
+
* 之前:把所有首页放到所有非首页条目前面,组内顺序不变,一次满足
|
|
2897
|
+
* 所有平台。
|
|
880
2898
|
*/
|
|
881
|
-
function
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
2899
|
+
function ensureHomePageFirst(pagesArray, homePath) {
|
|
2900
|
+
if (!pagesArray || pagesArray.length === 0) return;
|
|
2901
|
+
const isHome = pagesArray.map((page) => page.type === "home");
|
|
2902
|
+
if (homePath && !pagesArray.some((page) => page.path === homePath && page.type === "home")) pagesArray.forEach((page, index) => {
|
|
2903
|
+
if (page.path === homePath) isHome[index] = true;
|
|
2904
|
+
});
|
|
2905
|
+
const homeCount = isHome.filter(Boolean).length;
|
|
2906
|
+
if (homeCount === 0) return;
|
|
2907
|
+
if (isHome.slice(0, homeCount).every(Boolean)) return;
|
|
2908
|
+
const commentArray = pagesArray;
|
|
2909
|
+
const length = pagesArray.length;
|
|
2910
|
+
const beforeTokens = [];
|
|
2911
|
+
const afterTokens = [];
|
|
2912
|
+
for (let i = 0; i < length; i++) {
|
|
2913
|
+
beforeTokens.push(commentArray[Symbol.for(`before:${i}`)] || []);
|
|
2914
|
+
afterTokens.push(commentArray[Symbol.for(`after:${i}`)] || []);
|
|
2915
|
+
Reflect.deleteProperty(commentArray, Symbol.for(`before:${i}`));
|
|
2916
|
+
Reflect.deleteProperty(commentArray, Symbol.for(`after:${i}`));
|
|
2917
|
+
}
|
|
2918
|
+
const markerTokens = beforeTokens[0].filter(isGenerationMarker);
|
|
2919
|
+
beforeTokens[0] = beforeTokens[0].filter((token) => !isGenerationMarker(token));
|
|
2920
|
+
const order = [];
|
|
2921
|
+
for (let i = 0; i < length; i++) if (isHome[i]) order.push(i);
|
|
2922
|
+
for (let i = 0; i < length; i++) if (!isHome[i]) order.push(i);
|
|
2923
|
+
pagesArray.splice(0, length, ...order.map((i) => pagesArray[i]));
|
|
2924
|
+
for (let i = 0; i < length; i++) {
|
|
2925
|
+
const sourceIndex = order[i];
|
|
2926
|
+
const before = i === 0 ? [...markerTokens, ...beforeTokens[sourceIndex]] : beforeTokens[sourceIndex];
|
|
2927
|
+
if (before.length > 0) commentArray[Symbol.for(`before:${i}`)] = before;
|
|
2928
|
+
if (afterTokens[sourceIndex].length > 0) commentArray[Symbol.for(`after:${i}`)] = afterTokens[sourceIndex];
|
|
2929
|
+
}
|
|
885
2930
|
}
|
|
886
2931
|
/**
|
|
887
|
-
*
|
|
2932
|
+
* 删除本轮扫描不到、但确实由插件生成的分包。
|
|
888
2933
|
*
|
|
889
|
-
*
|
|
890
|
-
*
|
|
891
|
-
* 覆盖了全部平台的变体才能"裸着"输出(规则 5)。
|
|
892
|
-
*
|
|
893
|
-
* 当前平台一定在全集里,哪怕这次运行一个变体都没贡献——比如页面
|
|
894
|
-
* 只在 H5 存在,而 MP-WEIXIN 运行把每个页面都 definePage(null) 掉了。
|
|
895
|
-
* 如果只从剩下的条目推全集,全集就只有 'H5',H5 专属条目看起来
|
|
896
|
-
* "覆盖了全集",会不加包裹地输出,泄漏进微信的构建产物。老版本按
|
|
897
|
-
* "最常用平台组合当默认值"的做法也有同样的问题:可能算出单平台
|
|
898
|
-
* 组合,把那个平台的条目裸着输出,变成其他平台里的重复路由。这个
|
|
899
|
-
* 全集同样管着 tabBar 属性的包裹:没有它,一次没有 tabBar 的运行
|
|
900
|
-
* 会以为"拥有平台 == 全集",把别的平台的 tabBar 裸着输出出去。
|
|
901
|
-
*
|
|
902
|
-
* 上一次运行记在标记里的平台也进全集({@link extractLastPlatforms})。
|
|
903
|
-
* 否则当某平台的条目都被重新扫描替换后,它"来过"这件事只记在标记
|
|
904
|
-
* 里:只看条目推全集,全集会一会儿大一会儿小,条目一会儿包一会儿
|
|
905
|
-
* 裸。把标记也算进来,全集就只增不减;多算的平台最多带来多余的包
|
|
906
|
-
* 裹,不会泄漏。
|
|
2934
|
+
* 不删的话,这个 root 会以空分包进入本平台构建产物(app.json 里留
|
|
2935
|
+
* 一个指向不存在目录的 pages 数组)。手写分包没有生成标记,原样保留。
|
|
907
2936
|
*
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
*
|
|
911
|
-
*/
|
|
912
|
-
function resolvePlatformUnion(mergedMap, currentPlatform, lastPlatforms) {
|
|
913
|
-
return [.../* @__PURE__ */ new Set([
|
|
914
|
-
currentPlatform,
|
|
915
|
-
...lastPlatforms,
|
|
916
|
-
...collectVariantPlatforms(mergedMap)
|
|
917
|
-
])].sort();
|
|
918
|
-
}
|
|
919
|
-
const GENERATION_MARKER_PREFIX = "GENERATED BY UNI-PAGES, PLATFORM:";
|
|
920
|
-
/** 判断注释令牌是否为 pages.json 的生成标记行 */
|
|
921
|
-
function isGenerationMarker(token) {
|
|
922
|
-
return token.type !== "BlankLine" && typeof token.value === "string" && token.value.trim().startsWith("GENERATED BY UNI-PAGES, PLATFORM:");
|
|
923
|
-
}
|
|
924
|
-
/** 判断一个 pages 数组是否由插件写入(携带生成标记) */
|
|
925
|
-
function hasGenerationMarker(src) {
|
|
926
|
-
if (!src) return false;
|
|
927
|
-
return (src[Symbol.for("before:0")] || []).some(isGenerationMarker);
|
|
928
|
-
}
|
|
929
|
-
/**
|
|
930
|
-
* 从 before:0 的生成标记里读出上一次运行记录了哪些平台,
|
|
931
|
-
* 去掉当前平台后返回
|
|
2937
|
+
* 倒序遍历;删除条目注释符号再 splice,让 comment-json 把 `#ifdef`
|
|
2938
|
+
* 块和用户注释一起带走。`after-value:i`(条目的 `}` 和 `,` 之间的
|
|
2939
|
+
* 用户注释)也必须删掉:splice 只挪注释、不删注释。
|
|
932
2940
|
*/
|
|
933
|
-
function
|
|
934
|
-
let
|
|
935
|
-
|
|
936
|
-
if (
|
|
937
|
-
|
|
938
|
-
|
|
2941
|
+
function removeStaleSubPackages(subPackagesArray, staleRoots) {
|
|
2942
|
+
for (let i = subPackagesArray.length - 1; i >= 0; i--) {
|
|
2943
|
+
const existing = subPackagesArray[i];
|
|
2944
|
+
if (!staleRoots.includes(existing.root)) continue;
|
|
2945
|
+
debug.subPages(`Removing converged sub-package root: ${existing.root}`);
|
|
2946
|
+
Reflect.deleteProperty(subPackagesArray, Symbol.for(`before:${i}`));
|
|
2947
|
+
Reflect.deleteProperty(subPackagesArray, Symbol.for(`after:${i}`));
|
|
2948
|
+
Reflect.deleteProperty(subPackagesArray, Symbol.for(`after-value:${i}`));
|
|
2949
|
+
subPackagesArray.splice(i, 1);
|
|
939
2950
|
}
|
|
940
|
-
return lastPlatforms;
|
|
941
2951
|
}
|
|
942
2952
|
//#endregion
|
|
943
2953
|
//#region src/jsonc-scan.ts
|
|
@@ -1040,7 +3050,7 @@ function readJsonStringToken(content, start) {
|
|
|
1040
3050
|
* tabBar 不是对象、或文件结构看不懂时返回 undefined。
|
|
1041
3051
|
*/
|
|
1042
3052
|
function extractTabBarProps(content) {
|
|
1043
|
-
let i = skipJsoncFiller(content, 0);
|
|
3053
|
+
let i = skipJsoncFiller(content, content.charCodeAt(0) === 65279 ? 1 : 0);
|
|
1044
3054
|
if (content[i] !== "{") return void 0;
|
|
1045
3055
|
i = skipJsoncFiller(content, i + 1);
|
|
1046
3056
|
while (i < content.length) {
|
|
@@ -1139,11 +3149,12 @@ function mergeTabBarProps(existingContent, currentProps, contributesProps, curre
|
|
|
1139
3149
|
};
|
|
1140
3150
|
for (const [key, variants] of rawProps || []) {
|
|
1141
3151
|
if (key === "list") continue;
|
|
3152
|
+
const keyVariants = variantsOf(key);
|
|
1142
3153
|
for (const raw of variants) {
|
|
1143
3154
|
const valueStr = JSON.stringify(raw.value);
|
|
1144
3155
|
if (valueStr === void 0) continue;
|
|
1145
3156
|
if (raw.condition?.startsWith("#ifndef")) {
|
|
1146
|
-
|
|
3157
|
+
keyVariants.push({
|
|
1147
3158
|
payload: raw.value,
|
|
1148
3159
|
valueStr,
|
|
1149
3160
|
platforms: null,
|
|
@@ -1159,7 +3170,7 @@ function mergeTabBarProps(existingContent, currentProps, contributesProps, curre
|
|
|
1159
3170
|
if (raw.condition?.startsWith("#ifdef")) platforms = platformsExcluding(raw.condition.slice(6).trim(), currentPlatform);
|
|
1160
3171
|
else platforms = platformUnion.filter((p) => p !== currentPlatform);
|
|
1161
3172
|
if (platforms.length === 0) continue;
|
|
1162
|
-
|
|
3173
|
+
keyVariants.push({
|
|
1163
3174
|
payload: raw.value,
|
|
1164
3175
|
valueStr,
|
|
1165
3176
|
platforms,
|
|
@@ -1173,6 +3184,7 @@ function mergeTabBarProps(existingContent, currentProps, contributesProps, curre
|
|
|
1173
3184
|
if (valueStr === void 0) continue;
|
|
1174
3185
|
upsertCurrentVariant(variantsOf(key), value, valueStr, currentPlatform);
|
|
1175
3186
|
}
|
|
3187
|
+
for (const [key, variants] of merged) if (variants.length === 0) merged.delete(key);
|
|
1176
3188
|
for (const variants of merged.values()) sortVariants(variants);
|
|
1177
3189
|
return merged;
|
|
1178
3190
|
}
|
|
@@ -1194,13 +3206,19 @@ function renderTabBarPropLines(merged, platformUnion, format) {
|
|
|
1194
3206
|
const unit = indentUnitOf(format);
|
|
1195
3207
|
const unionStr = platformUnion.join(" || ");
|
|
1196
3208
|
const lines = [];
|
|
3209
|
+
const pushComments = (comments) => {
|
|
3210
|
+
for (const comment of comments) for (const line of comment.split(/\r?\n/)) {
|
|
3211
|
+
const text = line.trim();
|
|
3212
|
+
if (text) lines.push(`${unit}${unit}// ${text}`);
|
|
3213
|
+
}
|
|
3214
|
+
};
|
|
1197
3215
|
for (const [key, variants] of merged) for (const variant of variants) {
|
|
1198
3216
|
const valueText = indentContinuation(stringify(variant.payload, null, format?.indent ?? 2), unit + unit);
|
|
1199
3217
|
const propLine = `${unit}${unit}${JSON.stringify(key)}: ${valueText},`;
|
|
1200
3218
|
if (variant.passthrough) {
|
|
1201
|
-
|
|
3219
|
+
pushComments(variant.passthrough.before);
|
|
1202
3220
|
lines.push(propLine);
|
|
1203
|
-
|
|
3221
|
+
pushComments(variant.passthrough.after);
|
|
1204
3222
|
continue;
|
|
1205
3223
|
}
|
|
1206
3224
|
if (variant.platformStr === unionStr) lines.push(propLine);
|
|
@@ -1253,7 +3271,7 @@ async function writePagesJson(jsonPath, data, options) {
|
|
|
1253
3271
|
content
|
|
1254
3272
|
};
|
|
1255
3273
|
}
|
|
1256
|
-
await writeFileAtomic(jsonPath, content);
|
|
3274
|
+
await retryOnEperm(() => writeFileAtomic(jsonPath, content));
|
|
1257
3275
|
return {
|
|
1258
3276
|
updated: true,
|
|
1259
3277
|
content
|
|
@@ -1261,6 +3279,23 @@ async function writePagesJson(jsonPath, data, options) {
|
|
|
1261
3279
|
});
|
|
1262
3280
|
}
|
|
1263
3281
|
/**
|
|
3282
|
+
* Retries an async operation up to 3 times on EPERM, waiting 50ms between
|
|
3283
|
+
* attempts. Other errors propagate immediately.
|
|
3284
|
+
*
|
|
3285
|
+
* Windows file rename (used by write-file-atomic) can fail with EPERM when
|
|
3286
|
+
* another process holds the destination open with a sharing mode that excludes
|
|
3287
|
+
* rename (e.g. chokidar's watcher). The lock clears in under a frame.
|
|
3288
|
+
*/
|
|
3289
|
+
async function retryOnEperm(operation) {
|
|
3290
|
+
for (let attempt = 3; attempt > 0; attempt--) try {
|
|
3291
|
+
await operation();
|
|
3292
|
+
return;
|
|
3293
|
+
} catch (error) {
|
|
3294
|
+
if (error.code !== "EPERM" || attempt === 1) throw error;
|
|
3295
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
/**
|
|
1264
3299
|
* 根据现有文件内容计算合并后的 pages.json 对象
|
|
1265
3300
|
*
|
|
1266
3301
|
* @returns pages.json 对象;美化输出模式下附带预渲染的 tabBar 主体
|
|
@@ -1274,6 +3309,7 @@ function mergeIntoPagesJson(existingContent, data, options) {
|
|
|
1274
3309
|
} catch (error) {
|
|
1275
3310
|
throw new Error(`[vite-plugin-uni-pages] Failed to parse the existing pages.json, please fix its syntax first: ${error?.message ?? error}`, { cause: error });
|
|
1276
3311
|
}
|
|
3312
|
+
if (Object.prototype.toString.call(oldConfig) !== "[object Object]") throw new Error("[vite-plugin-uni-pages] The existing pages.json must contain a JSON object, please fix its syntax first");
|
|
1277
3313
|
const { pages: oldPages, subPackages: oldSubPackages, tabBar: oldTabBar } = oldConfig;
|
|
1278
3314
|
for (const [field, value] of Object.entries({
|
|
1279
3315
|
pages: oldPages,
|
|
@@ -1298,15 +3334,7 @@ function mergeIntoPagesJson(existingContent, data, options) {
|
|
|
1298
3334
|
newSubPackages.delete(existing.root);
|
|
1299
3335
|
} else if (hasGenerationMarker(existing.pages)) staleRoots.push(existing.root);
|
|
1300
3336
|
}
|
|
1301
|
-
|
|
1302
|
-
const existing = subPackagesArray[i];
|
|
1303
|
-
if (!staleRoots.includes(existing.root)) continue;
|
|
1304
|
-
debug.subPages(`Removing converged sub-package root: ${existing.root}`);
|
|
1305
|
-
Reflect.deleteProperty(subPackagesArray, Symbol.for(`before:${i}`));
|
|
1306
|
-
Reflect.deleteProperty(subPackagesArray, Symbol.for(`after:${i}`));
|
|
1307
|
-
Reflect.deleteProperty(subPackagesArray, Symbol.for(`after-value:${i}`));
|
|
1308
|
-
subPackagesArray.splice(i, 1);
|
|
1309
|
-
}
|
|
3337
|
+
removeStaleSubPackages(subPackagesArray, staleRoots);
|
|
1310
3338
|
for (const [_, newSub] of newSubPackages) {
|
|
1311
3339
|
const subPackage = {
|
|
1312
3340
|
root: newSub.root,
|
|
@@ -1318,7 +3346,7 @@ function mergeIntoPagesJson(existingContent, data, options) {
|
|
|
1318
3346
|
const { list, ...tabBarOthers } = data.tabBar || {};
|
|
1319
3347
|
const contributesProps = !!(list && list.length);
|
|
1320
3348
|
const oldTabBarObj = oldTabBar;
|
|
1321
|
-
const tabBarMerge = mergePlatformItems(oldTabBarObj?.list, currentPlatform, list || [], "pagePath");
|
|
3349
|
+
const tabBarMerge = mergePlatformItems(oldTabBarObj?.list, currentPlatform, list || [], "pagePath", { orderByConfig: true });
|
|
1322
3350
|
let tabBarBodyLines;
|
|
1323
3351
|
if (tabBarMerge.items.length === 0) pageJson.tabBar = void 0;
|
|
1324
3352
|
else {
|
|
@@ -1344,231 +3372,70 @@ function mergeIntoPagesJson(existingContent, data, options) {
|
|
|
1344
3372
|
tabBarBodyLines
|
|
1345
3373
|
};
|
|
1346
3374
|
}
|
|
1347
|
-
/**
|
|
1348
|
-
*
|
|
1349
|
-
*
|
|
1350
|
-
*
|
|
1351
|
-
* 所有平台都能看到。所以一个平台的首页必须排在它可见的所有条目
|
|
1352
|
-
* 之前。解决办法很简单:把所有平台的首页都放到所有非首页条目的
|
|
1353
|
-
* 前面(各组内部顺序不变),一次满足所有平台。
|
|
1354
|
-
*
|
|
1355
|
-
* 只移动当前平台的首页是不够的:就算它已经在第 0 位,另一个平台的
|
|
1356
|
-
* 首页可能还排在它自己可见的某个非首页条目后面。
|
|
1357
|
-
*
|
|
1358
|
-
* 判断哪些条目是首页:先看条目自带的 `type: 'home'` 标记(扫描出来
|
|
1359
|
-
* 的条目都带),再看 homePath 路径兜底(手写条目不带标记)。标记在
|
|
1360
|
-
* 合并时不会保留下来,所以每次运行都要重新判断一遍。
|
|
1361
|
-
*/
|
|
1362
|
-
function ensureHomePageFirst(pagesArray, homePath) {
|
|
1363
|
-
if (!pagesArray || pagesArray.length === 0) return;
|
|
1364
|
-
const isHome = pagesArray.map((page) => page.type === "home");
|
|
1365
|
-
if (homePath && !pagesArray.some((page) => page.path === homePath && page.type === "home")) pagesArray.forEach((page, index) => {
|
|
1366
|
-
if (page.path === homePath) isHome[index] = true;
|
|
1367
|
-
});
|
|
1368
|
-
const homeCount = isHome.filter(Boolean).length;
|
|
1369
|
-
if (homeCount === 0) return;
|
|
1370
|
-
if (isHome.slice(0, homeCount).every(Boolean)) return;
|
|
1371
|
-
const commentArray = pagesArray;
|
|
1372
|
-
const length = pagesArray.length;
|
|
1373
|
-
const beforeTokens = [];
|
|
1374
|
-
const afterTokens = [];
|
|
1375
|
-
for (let i = 0; i < length; i++) {
|
|
1376
|
-
beforeTokens.push(commentArray[Symbol.for(`before:${i}`)] || []);
|
|
1377
|
-
afterTokens.push(commentArray[Symbol.for(`after:${i}`)] || []);
|
|
1378
|
-
Reflect.deleteProperty(commentArray, Symbol.for(`before:${i}`));
|
|
1379
|
-
Reflect.deleteProperty(commentArray, Symbol.for(`after:${i}`));
|
|
1380
|
-
}
|
|
1381
|
-
const markerTokens = beforeTokens[0].filter(isGenerationMarker);
|
|
1382
|
-
beforeTokens[0] = beforeTokens[0].filter((token) => !isGenerationMarker(token));
|
|
1383
|
-
const order = [];
|
|
1384
|
-
for (let i = 0; i < length; i++) if (isHome[i]) order.push(i);
|
|
1385
|
-
for (let i = 0; i < length; i++) if (!isHome[i]) order.push(i);
|
|
1386
|
-
pagesArray.splice(0, length, ...order.map((i) => pagesArray[i]));
|
|
1387
|
-
for (let i = 0; i < length; i++) {
|
|
1388
|
-
const sourceIndex = order[i];
|
|
1389
|
-
const before = i === 0 ? [...markerTokens, ...beforeTokens[sourceIndex]] : beforeTokens[sourceIndex];
|
|
1390
|
-
if (before.length > 0) commentArray[Symbol.for(`before:${i}`)] = before;
|
|
1391
|
-
if (afterTokens[sourceIndex].length > 0) commentArray[Symbol.for(`after:${i}`)] = afterTokens[sourceIndex];
|
|
1392
|
-
}
|
|
1393
|
-
}
|
|
1394
|
-
/**
|
|
1395
|
-
* 判断输出是不是带注释的多行格式(只有多行才放得下按平台区分的
|
|
1396
|
-
* `#ifdef` 块)。`indent: 0` 或空字符串会让 comment-json 输出成
|
|
1397
|
-
* 单行,这里和它的行为保持一致。
|
|
1398
|
-
*/
|
|
1399
|
-
function isPrettyFormat(format) {
|
|
1400
|
-
return !(format?.minify ?? false) && !!(format?.indent ?? 2);
|
|
1401
|
-
}
|
|
1402
|
-
/**
|
|
1403
|
-
* 不碰文件系统,只做计算:把路由数据合并进现有 pages.json 文本
|
|
1404
|
-
* (多平台 `#ifdef` 块、首页重排、生成标记、过期子包清理)并序列化
|
|
1405
|
-
* 成字符串。文件锁、变更检测和原子写入都在 {@link writePagesJson}
|
|
1406
|
-
* 里;测试直接用字符串检查这个函数。
|
|
1407
|
-
*
|
|
1408
|
-
* @param existingContent - 当前 pages.json 文本,没有时传空字符串
|
|
1409
|
-
* @param data - 由扫描/合并流水线组装的路由数据
|
|
1410
|
-
* @param options - 平台、用户配置与序列化格式
|
|
1411
|
-
* @returns 序列化后的 pages.json 内容
|
|
1412
|
-
*/
|
|
1413
|
-
function mergePagesJson(existingContent, data, options) {
|
|
1414
|
-
const { pageJson, tabBarBodyLines } = mergeIntoPagesJson(existingContent, data, options);
|
|
1415
|
-
const minify = options.format?.minify ?? false;
|
|
1416
|
-
const indent = options.format?.indent ?? 2;
|
|
1417
|
-
const eol = options.format?.eol ?? "\n";
|
|
1418
|
-
let content = stringify(pageJson, null, minify ? void 0 : indent);
|
|
1419
|
-
if (tabBarBodyLines) {
|
|
1420
|
-
const unit = typeof indent === "number" ? " ".repeat(indent) : indent;
|
|
1421
|
-
content = content.replace(`"tabBar": ${JSON.stringify(TAB_BAR_PLACEHOLDER)}`, () => `"tabBar": {\n${tabBarBodyLines.join("\n")}\n${unit}}`);
|
|
1422
|
-
}
|
|
1423
|
-
if (eol !== "\n") content = content.replaceAll("\n", eol);
|
|
1424
|
-
if (options.format?.insertFinalNewline) content += eol;
|
|
1425
|
-
return content;
|
|
1426
|
-
}
|
|
1427
|
-
/** 构建用于序列化 pages.json 输出的行注释令牌 */
|
|
1428
|
-
function lineComment(value) {
|
|
1429
|
-
return {
|
|
1430
|
-
type: "LineComment",
|
|
1431
|
-
value,
|
|
1432
|
-
inline: false,
|
|
1433
|
-
loc: {
|
|
1434
|
-
start: {
|
|
1435
|
-
line: 0,
|
|
1436
|
-
column: 0
|
|
1437
|
-
},
|
|
1438
|
-
end: {
|
|
1439
|
-
line: 0,
|
|
1440
|
-
column: 0
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
};
|
|
1444
|
-
}
|
|
1445
|
-
/**
|
|
1446
|
-
* 把条目转成字符串用于比较,比较前要先把内部的 `type` 标记
|
|
1447
|
-
* ('home' | 'page')拿掉。
|
|
1448
|
-
*
|
|
1449
|
-
* 从 pages.json 读回来的条目可能没有这个标记(手写条目从不带它),
|
|
1450
|
-
* 直接 JSON.stringify 会把同一个页面当成两个不同的条目,多平台
|
|
1451
|
-
* 运行时就会生成重复的路由
|
|
1452
|
-
* (见 https://github.com/uni-helper/vite-plugin-uni-pages/issues/283)。
|
|
1453
|
-
*
|
|
1454
|
-
* 键的顺序也参与比较(JSON.stringify 按写入顺序输出):同一页面在
|
|
1455
|
-
* 两个平台下键序不同时不会被合并,会各占一个 #ifdef 块留在文件
|
|
1456
|
-
* 里。代价只是文件里多一份内容相同的变体,构建时每个平台仍然只看
|
|
1457
|
-
* 得见自己那一条、不会出现重复路由,不值得为它做键序归一化。
|
|
1458
|
-
*/
|
|
1459
|
-
function stringifyForCompare(val) {
|
|
1460
|
-
if ("type" in val) {
|
|
1461
|
-
const { type: _type, ...rest } = val;
|
|
1462
|
-
return JSON.stringify(rest);
|
|
1463
|
-
}
|
|
1464
|
-
return JSON.stringify(val);
|
|
1465
|
-
}
|
|
1466
|
-
/**
|
|
1467
|
-
* 两个内容相同的条目,首页状态是否一致?
|
|
1468
|
-
*
|
|
1469
|
-
* `type` 标记不参与内容比较(见 stringifyForCompare),没有标记的
|
|
1470
|
-
* 条目也能和扫描到的条目合并。但如果两边都明确带着标记、而且一个
|
|
1471
|
-
* 是 'home' 一个是 'page',说明这是两个平台各自声明的不同首页,
|
|
1472
|
-
* 必须作为两个条目待在各自的 #ifdef 块里,不能合并成一条——之前
|
|
1473
|
-
* 的合并正是"切换首页后旧首页标记残留、某个平台的首页声明被悄悄
|
|
1474
|
-
* 丢掉"这两个 bug 的根源。
|
|
3375
|
+
/**
|
|
3376
|
+
* 判断输出是不是带注释的多行格式(只有多行才放得下按平台区分的
|
|
3377
|
+
* `#ifdef` 块)。`indent: 0` 或空字符串会让 comment-json 输出成
|
|
3378
|
+
* 单行,这里和它的行为保持一致。
|
|
1475
3379
|
*/
|
|
1476
|
-
function
|
|
1477
|
-
|
|
1478
|
-
const typeB = b.type;
|
|
1479
|
-
return typeA === void 0 || typeB === void 0 || typeA === typeB;
|
|
3380
|
+
function isPrettyFormat(format) {
|
|
3381
|
+
return !(format?.minify ?? false) && !!(format?.indent ?? 2);
|
|
1480
3382
|
}
|
|
1481
3383
|
/**
|
|
1482
|
-
*
|
|
1483
|
-
*
|
|
1484
|
-
*
|
|
1485
|
-
*
|
|
1486
|
-
* 排除当前平台、排序、并集)用 platform-variants.ts 的共享核心:
|
|
1487
|
-
* - 内容相同的条目自动合并,平台标识叠在一起
|
|
1488
|
-
* - 内容不同的条目各写各的 #ifdef 块
|
|
1489
|
-
* - 手写的 `#ifndef` 块原样保留:否定条件翻译不成正向平台列表,
|
|
1490
|
-
* 所以条目连同原始包裹一起输出,永不修改、也永不清理
|
|
3384
|
+
* 不碰文件系统,只做计算:把路由数据合并进现有 pages.json 文本
|
|
3385
|
+
* (多平台 `#ifdef` 块、首页重排、生成标记、过期分包清理)并序列化
|
|
3386
|
+
* 成字符串。文件锁、变更检测和原子写入都在 {@link writePagesJson}
|
|
3387
|
+
* 里;测试直接用字符串检查这个函数。
|
|
1491
3388
|
*
|
|
1492
|
-
* @param
|
|
1493
|
-
* @param
|
|
1494
|
-
* @param
|
|
1495
|
-
* @
|
|
1496
|
-
* @returns 带 #ifdef 块的合并条目,以及平台全集与拥有平台
|
|
3389
|
+
* @param existingContent - 当前 pages.json 文本,没有时传空字符串
|
|
3390
|
+
* @param data - 由扫描/合并流水线组装的路由数据
|
|
3391
|
+
* @param options - 平台、用户配置与序列化格式
|
|
3392
|
+
* @returns 序列化后的 pages.json 内容
|
|
1497
3393
|
*/
|
|
1498
|
-
function
|
|
1499
|
-
const
|
|
1500
|
-
|
|
1501
|
-
const
|
|
1502
|
-
const
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
};
|
|
1508
|
-
for (let i = 0; i < src.length; i++) {
|
|
1509
|
-
const item = src[i];
|
|
1510
|
-
const uniqueKey = item[uniqueKeyName];
|
|
1511
|
-
if (!uniqueKey) continue;
|
|
1512
|
-
const beforeComments = src[Symbol.for(`before:${i}`)];
|
|
1513
|
-
const conditionalComment = beforeComments?.find((c) => c.type !== "BlankLine" && /^#(?:ifdef|ifndef)/.test(c.value.trim()));
|
|
1514
|
-
if (conditionalComment?.value.trim().startsWith("#ifndef")) {
|
|
1515
|
-
variantsOf(uniqueKey).push({
|
|
1516
|
-
payload: item,
|
|
1517
|
-
valueStr: stringifyForCompare(item),
|
|
1518
|
-
platforms: null,
|
|
1519
|
-
platformStr: "",
|
|
1520
|
-
passthrough: {
|
|
1521
|
-
before: [...beforeComments || []].filter((c) => !isGenerationMarker(c)),
|
|
1522
|
-
after: [lineComment(" #endif")]
|
|
1523
|
-
}
|
|
1524
|
-
});
|
|
1525
|
-
continue;
|
|
1526
|
-
}
|
|
1527
|
-
let platforms = [...lastPlatforms];
|
|
1528
|
-
if (conditionalComment) {
|
|
1529
|
-
const match = conditionalComment.value.match(/#ifdef\s+(.+)/);
|
|
1530
|
-
if (match) platforms = platformsExcluding(match[1], currentPlatform);
|
|
1531
|
-
}
|
|
1532
|
-
if (platforms.length === 0) continue;
|
|
1533
|
-
variantsOf(uniqueKey).push({
|
|
1534
|
-
payload: item,
|
|
1535
|
-
valueStr: stringifyForCompare(item),
|
|
1536
|
-
platforms,
|
|
1537
|
-
platformStr: platforms.join(" || ")
|
|
1538
|
-
});
|
|
1539
|
-
}
|
|
1540
|
-
for (const item of items) {
|
|
1541
|
-
const uniqueKey = item[uniqueKeyName];
|
|
1542
|
-
if (!uniqueKey) continue;
|
|
1543
|
-
upsertCurrentVariant(variantsOf(uniqueKey), item, stringifyForCompare(item), currentPlatform, homeStatusCompatible);
|
|
1544
|
-
}
|
|
1545
|
-
const result = new CommentArray();
|
|
1546
|
-
for (const variants of mergedMap.values()) sortVariants(variants);
|
|
1547
|
-
const platformUnion = resolvePlatformUnion(mergedMap, currentPlatform, lastPlatforms);
|
|
1548
|
-
const platformUnionStr = platformUnion.join(" || ");
|
|
1549
|
-
const owningPlatforms = collectVariantPlatforms(mergedMap);
|
|
1550
|
-
result[Symbol.for("before:0")] = [lineComment(` ${GENERATION_MARKER_PREFIX} ${platformUnionStr}`)];
|
|
1551
|
-
for (const [_, list] of mergedMap) for (const { payload: item, platformStr, passthrough } of list) {
|
|
1552
|
-
result.push(item);
|
|
1553
|
-
if (passthrough) {
|
|
1554
|
-
result[Symbol.for(`before:${result.length - 1}`)] = [...result[Symbol.for(`before:${result.length - 1}`)] || [], ...passthrough.before];
|
|
1555
|
-
if (passthrough.after.length > 0) result[Symbol.for(`after:${result.length - 1}`)] = passthrough.after;
|
|
1556
|
-
continue;
|
|
1557
|
-
}
|
|
1558
|
-
if (platformStr !== platformUnionStr) {
|
|
1559
|
-
result[Symbol.for(`before:${result.length - 1}`)] = [...result[Symbol.for(`before:${result.length - 1}`)] || [], lineComment(` #ifdef ${platformStr}`)];
|
|
1560
|
-
result[Symbol.for(`after:${result.length - 1}`)] = [lineComment(" #endif")];
|
|
1561
|
-
}
|
|
3394
|
+
function mergePagesJson(existingContent, data, options) {
|
|
3395
|
+
const { pageJson, tabBarBodyLines } = mergeIntoPagesJson(existingContent, data, options);
|
|
3396
|
+
const minify = options.format?.minify ?? false;
|
|
3397
|
+
const indent = options.format?.indent ?? 2;
|
|
3398
|
+
const eol = options.format?.eol ?? "\n";
|
|
3399
|
+
let content = stringify(pageJson, null, minify ? void 0 : indent);
|
|
3400
|
+
if (tabBarBodyLines) {
|
|
3401
|
+
const unit = typeof indent === "number" ? " ".repeat(indent) : indent;
|
|
3402
|
+
content = content.replace(`"tabBar": ${JSON.stringify(TAB_BAR_PLACEHOLDER)}`, () => `"tabBar": {\n${tabBarBodyLines.join("\n")}\n${unit}}`);
|
|
1562
3403
|
}
|
|
3404
|
+
if (eol !== "\n") content = content.replaceAll("\n", eol);
|
|
3405
|
+
if (options.format?.insertFinalNewline) content += eol;
|
|
3406
|
+
return content;
|
|
3407
|
+
}
|
|
3408
|
+
//#endregion
|
|
3409
|
+
//#region src/pages-snapshot.ts
|
|
3410
|
+
function createPagesSnapshot(input) {
|
|
1563
3411
|
return {
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
3412
|
+
pages: [...input.pages],
|
|
3413
|
+
subPackages: [...input.subPackages],
|
|
3414
|
+
tabBar: input.tabBar ? {
|
|
3415
|
+
...input.tabBar,
|
|
3416
|
+
list: input.tabBar.list ? [...input.tabBar.list] : void 0
|
|
3417
|
+
} : void 0,
|
|
3418
|
+
globConfig: input.globConfig,
|
|
3419
|
+
homePath: input.homePath
|
|
1567
3420
|
};
|
|
1568
3421
|
}
|
|
1569
3422
|
//#endregion
|
|
1570
3423
|
//#region src/context.ts
|
|
1571
3424
|
/**
|
|
3425
|
+
* 在 watcher 回调里查页面规则
|
|
3426
|
+
*
|
|
3427
|
+
* 规则会在声明变化后重新编译,编译失败属于配置错误;此时记日志并按
|
|
3428
|
+
* “不是页面事件”处理,异常不能穿过 watcher 回调,否则会崩在事件循环里。
|
|
3429
|
+
*/
|
|
3430
|
+
function queryPageRules(fallback, query) {
|
|
3431
|
+
try {
|
|
3432
|
+
return query();
|
|
3433
|
+
} catch (error) {
|
|
3434
|
+
debug.error("Failed to evaluate page rules, the event is ignored:", error);
|
|
3435
|
+
return fallback;
|
|
3436
|
+
}
|
|
3437
|
+
}
|
|
3438
|
+
/**
|
|
1572
3439
|
* 页面上下文:负责扫描页面、加载配置、合并页面信息、生成 pages.json
|
|
1573
3440
|
*
|
|
1574
3441
|
* 做的事情按固定顺序是:加载用户配置 → 扫描页面文件 → 合并页面
|
|
@@ -1578,17 +3445,45 @@ function mergePlatformItems(source, currentPlatform, items, uniqueKeyName) {
|
|
|
1578
3445
|
*/
|
|
1579
3446
|
var PageContext = class {
|
|
1580
3447
|
_server;
|
|
3448
|
+
configLoader;
|
|
3449
|
+
watchers = /* @__PURE__ */ new Map();
|
|
3450
|
+
watchedConfigPaths = /* @__PURE__ */ new Map();
|
|
3451
|
+
/** 当前配置依赖与恢复范围;事件判定和路径展开都从这里取 */
|
|
3452
|
+
configWatch;
|
|
3453
|
+
/** 生成物(pages.json、d.ts)的绝对路径,只在首次事件时算一次 */
|
|
3454
|
+
generatedPathsCache;
|
|
3455
|
+
pendingUpdate = Promise.resolve();
|
|
3456
|
+
disposed = false;
|
|
3457
|
+
disposal;
|
|
3458
|
+
/** 本轮扫描的目录、分包来源与规则;扫描和监听共用 */
|
|
3459
|
+
scanPlan;
|
|
3460
|
+
/** 最近一次生成的完整快照;虚拟模块、路由与声明都读它 */
|
|
3461
|
+
generatedSnapshot;
|
|
3462
|
+
/** 随扫描更新的 Page 来源,用于复用检查和冲突诊断 */
|
|
3463
|
+
pageSources = /* @__PURE__ */ new WeakMap();
|
|
3464
|
+
/** 扫描候选独立于归属裁剪后的输出映射,保留非代表来源的内容缓存 */
|
|
3465
|
+
mainPageCandidates = /* @__PURE__ */ new Map();
|
|
3466
|
+
subPageCandidates = /* @__PURE__ */ new Map();
|
|
3467
|
+
pageWatcher;
|
|
3468
|
+
/** 待处理的页面更新:生成期间到达的事件合并到下一轮 */
|
|
3469
|
+
pendingPageUpdate;
|
|
3470
|
+
/** 当前事件更新循环;dispose 时等待它排空 */
|
|
3471
|
+
pendingPageFlush;
|
|
3472
|
+
/** 页面监听启动参数;初始化失败时保留,后续生成会重试 */
|
|
3473
|
+
pageWatcherStart;
|
|
3474
|
+
/** 当前配置本地依赖及加载失败后仍需监听的恢复路径 */
|
|
3475
|
+
pagesConfigDependencyPaths = [];
|
|
1581
3476
|
/** 从用户配置文件(pages.config.ts)解析出的配置对象 */
|
|
1582
3477
|
pagesGlobConfig;
|
|
1583
3478
|
/** 用户配置文件的来源路径列表 */
|
|
1584
3479
|
pagesConfigSourcePaths = [];
|
|
1585
|
-
/**
|
|
3480
|
+
/** 主包页面映射,键为页面文件的词法绝对路径 */
|
|
1586
3481
|
pages = /* @__PURE__ */ new Map();
|
|
1587
|
-
/**
|
|
3482
|
+
/** 分包页面映射,外层键为词法扫描目录,内层键为页面文件的词法绝对路径 */
|
|
1588
3483
|
subPages = /* @__PURE__ */ new Map();
|
|
1589
3484
|
/** 主包页面配置数组,用于生成 pages.json 的 pages 字段 */
|
|
1590
3485
|
pageMetaData = [];
|
|
1591
|
-
/**
|
|
3486
|
+
/** 分包页面配置数组,用于生成 pages.json 的 subPackages 字段 */
|
|
1592
3487
|
subPageMetaData = [];
|
|
1593
3488
|
/**
|
|
1594
3489
|
* 最近一次合并出的 tabBar(配置文件与 definePage 声明的合体)。
|
|
@@ -1609,7 +3504,7 @@ var PageContext = class {
|
|
|
1609
3504
|
withUniPlatform = false;
|
|
1610
3505
|
/** pages.json 中页面路径的解析基准路径 */
|
|
1611
3506
|
get basePath() {
|
|
1612
|
-
return resolveBasePath(this.options);
|
|
3507
|
+
return this.scanPlan?.basePath ?? resolveBasePath(this.options);
|
|
1613
3508
|
}
|
|
1614
3509
|
/**
|
|
1615
3510
|
* 创建 PageContext 实例
|
|
@@ -1619,9 +3514,18 @@ var PageContext = class {
|
|
|
1619
3514
|
*/
|
|
1620
3515
|
constructor(userOptions, viteRoot = process.cwd(), platform$1 = platform) {
|
|
1621
3516
|
this.root = normalizePath(viteRoot);
|
|
3517
|
+
this.configLoader = new PagesConfigLoader(this.root, (message) => this.logger?.warn(message, { timestamp: true }));
|
|
3518
|
+
this.configWatch = new ConfigWatchIndex(this.root, this.configLoader.artifactDirectory);
|
|
1622
3519
|
this.platform = platform$1;
|
|
1623
3520
|
debug.options("root", this.root);
|
|
1624
3521
|
this.options = resolveOptions(userOptions, this.root);
|
|
3522
|
+
this.pageWatcher = new PageSourceWatch(this.options, (event, file) => {
|
|
3523
|
+
const pageFile = queryPageRules(void 0, () => this.pageFileForEvent(file, normalizeConfigPath(file, this.root)));
|
|
3524
|
+
if (pageFile) {
|
|
3525
|
+
debug.pages(`File changed: ${pageFile}`);
|
|
3526
|
+
this.queuePageUpdate(event === "change" ? pageFile : void 0);
|
|
3527
|
+
}
|
|
3528
|
+
}, () => this.queuePageUpdate(), (error) => this.logUpdateFailure(error), (message) => this.logger?.warn(message, { timestamp: true }));
|
|
1625
3529
|
const debugOption = this.options.debug;
|
|
1626
3530
|
if (debugOption) {
|
|
1627
3531
|
const prefix = "vite-plugin-uni-pages:";
|
|
@@ -1639,77 +3543,271 @@ var PageContext = class {
|
|
|
1639
3543
|
this.logger = logger;
|
|
1640
3544
|
}
|
|
1641
3545
|
/**
|
|
3546
|
+
* 设置配置图里 import.meta.env 的值
|
|
3547
|
+
*
|
|
3548
|
+
* @description 下一次配置加载时生效,不会自行触发页面生成
|
|
3549
|
+
* @param env - Vite 解析后的环境值
|
|
3550
|
+
* @param define - Vite 的定义映射,只应用 import.meta.env.* 条目
|
|
3551
|
+
* @returns 首次用上 Vite 的 env 时为 `true`,已经生成的 pages.json 需要重算
|
|
3552
|
+
*/
|
|
3553
|
+
setConfigEnv(env, define = {}) {
|
|
3554
|
+
return this.configLoader.setEnv(env, define);
|
|
3555
|
+
}
|
|
3556
|
+
/**
|
|
1642
3557
|
* 加载用户页面配置文件(如 pages.config.ts)
|
|
1643
3558
|
* 使用 unconfig 加载配置,支持多种配置文件格式
|
|
1644
3559
|
*/
|
|
1645
3560
|
async loadUserPagesConfig() {
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
sources
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
3561
|
+
try {
|
|
3562
|
+
const { config, sources, dependencies } = await this.configLoader.load(this.options.configSource);
|
|
3563
|
+
this.pagesGlobConfig = config.default || config;
|
|
3564
|
+
this.pagesConfigSourcePaths = sources;
|
|
3565
|
+
this.pagesConfigDependencyPaths = dependencies;
|
|
3566
|
+
debug.options(this.pagesGlobConfig);
|
|
3567
|
+
} catch (error) {
|
|
3568
|
+
this.pagesConfigDependencyPaths = [...this.configLoader.watchInput.dependencies];
|
|
3569
|
+
throw error;
|
|
3570
|
+
} finally {
|
|
3571
|
+
this.refreshConfigWatchers();
|
|
3572
|
+
}
|
|
1655
3573
|
}
|
|
1656
3574
|
/**
|
|
1657
|
-
*
|
|
3575
|
+
* 按顺序跑完扫描与合并:先扫描主包和分包的页面,再合并它们的
|
|
1658
3576
|
* 信息。步骤顺序只维护在这里,调用方和测试都不用关心。
|
|
1659
3577
|
*/
|
|
1660
3578
|
async scanAndMerge() {
|
|
3579
|
+
this.generatedSnapshot = void 0;
|
|
3580
|
+
this.refreshScanPlan();
|
|
1661
3581
|
await this.scanPages();
|
|
1662
3582
|
await this.scanSubPages();
|
|
3583
|
+
this.startPageWatcher();
|
|
3584
|
+
this.pageWatcher.refresh(this.requireScanPlan());
|
|
1663
3585
|
await this.mergePageMetaData();
|
|
1664
3586
|
await this.mergeSubPageMetaData();
|
|
1665
3587
|
}
|
|
3588
|
+
/** 刷新本轮扫描计划,并同步兼容投影供既有调用方读取 */
|
|
3589
|
+
refreshScanPlan() {
|
|
3590
|
+
this.scanPlan = createScanPlan(this.options);
|
|
3591
|
+
applyScanPlan(this.options, this.scanPlan);
|
|
3592
|
+
}
|
|
3593
|
+
/** 扫描与监听阶段读取本轮计划;计划在 refreshScanPlan 之后必定存在 */
|
|
3594
|
+
requireScanPlan() {
|
|
3595
|
+
if (!this.scanPlan) throw new Error("[vite-plugin-uni-pages] Scan plan is not ready");
|
|
3596
|
+
return this.scanPlan;
|
|
3597
|
+
}
|
|
1666
3598
|
/**
|
|
1667
3599
|
* 设置 Vite 开发服务器,用于 HMR 与文件监听
|
|
1668
3600
|
* @param server - Vite 开发服务器实例
|
|
1669
3601
|
*/
|
|
1670
3602
|
setupViteServer(server) {
|
|
1671
|
-
if (this._server === server) return;
|
|
3603
|
+
if (this.disposed || this._server === server) return;
|
|
1672
3604
|
this._server = server;
|
|
1673
|
-
this.setupWatcher(server.watcher);
|
|
3605
|
+
this.setupWatcher(server.watcher).catch((error) => this.logUpdateFailure(error));
|
|
3606
|
+
}
|
|
3607
|
+
/**
|
|
3608
|
+
* 生成物(pages.json 与 d.ts)的绝对路径
|
|
3609
|
+
*
|
|
3610
|
+
* 只依赖构造后不再变化的 `options` 与 `resolvedPagesJSONPath`,
|
|
3611
|
+
* 算一次缓存即可,不必每个事件重新解析
|
|
3612
|
+
*/
|
|
3613
|
+
generatedFilePaths() {
|
|
3614
|
+
if (!this.generatedPathsCache) this.generatedPathsCache = [normalizeConfigPath(this.resolvedPagesJSONPath, this.root), ...this.options.dts ? [normalizeConfigPath(this.options.dts, this.root)] : []];
|
|
3615
|
+
return this.generatedPathsCache;
|
|
3616
|
+
}
|
|
3617
|
+
/** 按当前词法规则识别页面事件,真实路径只用于关联已收录来源 */
|
|
3618
|
+
pageFileForEvent(file, identity) {
|
|
3619
|
+
return this.pageWatcher.fileForEvent(file, identity);
|
|
3620
|
+
}
|
|
3621
|
+
pageDirectoryForEvent(directory) {
|
|
3622
|
+
return this.pageWatcher.directoryForEvent(directory);
|
|
1674
3623
|
}
|
|
1675
3624
|
/**
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
* @param watcher - chokidar
|
|
3625
|
+
* 注册配置文件与页面目录结构监听,并启动页面内容监听
|
|
3626
|
+
*
|
|
3627
|
+
* @param watcher - 配置文件及目录结构事件使用的 chokidar 监听器
|
|
1679
3628
|
*/
|
|
1680
3629
|
async setupWatcher(watcher) {
|
|
1681
|
-
|
|
1682
|
-
const
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
3630
|
+
if (this.disposed || this.watchers.has(watcher)) return;
|
|
3631
|
+
const onConfigFile = (filepath) => {
|
|
3632
|
+
const absolute = this.configWatch.match(filepath, this.generatedFilePaths());
|
|
3633
|
+
if (!absolute) return;
|
|
3634
|
+
debug.pages(`Config changed: ${absolute}`);
|
|
3635
|
+
this.updatePagesAndNotify();
|
|
1686
3636
|
};
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
if (
|
|
3637
|
+
const onDirectory = (directory) => {
|
|
3638
|
+
if (queryPageRules(false, () => this.pageDirectoryForEvent(directory))) this.queuePageUpdate();
|
|
3639
|
+
};
|
|
3640
|
+
const onSharedPageFile = (filepath) => {
|
|
3641
|
+
if (this.disposed || this.pageWatcher.running || !this.pageWatcherStart) return;
|
|
3642
|
+
if (!isTargetFile(normalizePath(filepath))) return;
|
|
3643
|
+
this.startPageWatcher();
|
|
3644
|
+
if (this.pageWatcher.running) this.queuePageUpdate();
|
|
3645
|
+
};
|
|
3646
|
+
const onReady = () => this.queuePageUpdate();
|
|
3647
|
+
watcher.on("add", onConfigFile);
|
|
3648
|
+
watcher.on("change", onConfigFile);
|
|
3649
|
+
watcher.on("unlink", onConfigFile);
|
|
3650
|
+
watcher.on("add", onSharedPageFile);
|
|
3651
|
+
watcher.on("change", onSharedPageFile);
|
|
3652
|
+
watcher.on("unlink", onSharedPageFile);
|
|
3653
|
+
watcher.on("addDir", onDirectory);
|
|
3654
|
+
watcher.on("unlinkDir", onDirectory);
|
|
3655
|
+
watcher.on("ready", onReady);
|
|
3656
|
+
this.watchers.set(watcher, () => {
|
|
3657
|
+
watcher.off("add", onConfigFile);
|
|
3658
|
+
watcher.off("change", onConfigFile);
|
|
3659
|
+
watcher.off("unlink", onConfigFile);
|
|
3660
|
+
watcher.off("add", onSharedPageFile);
|
|
3661
|
+
watcher.off("change", onSharedPageFile);
|
|
3662
|
+
watcher.off("unlink", onSharedPageFile);
|
|
3663
|
+
watcher.off("addDir", onDirectory);
|
|
3664
|
+
watcher.off("unlinkDir", onDirectory);
|
|
3665
|
+
watcher.off("ready", onReady);
|
|
1692
3666
|
});
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
3667
|
+
this.watchedConfigPaths.set(watcher, /* @__PURE__ */ new Set());
|
|
3668
|
+
this.refreshConfigWatchers();
|
|
3669
|
+
if (!(this._server?.watcher === watcher && this._server?.config.server.watch === null)) {
|
|
3670
|
+
this.pageWatcherStart = {
|
|
3671
|
+
options: watcher.options,
|
|
3672
|
+
ignored: this._server?.watcher === watcher ? this._server?.watcher.options.ignored : void 0
|
|
3673
|
+
};
|
|
3674
|
+
this.startPageWatcher();
|
|
3675
|
+
}
|
|
3676
|
+
}
|
|
3677
|
+
/**
|
|
3678
|
+
* 启动页面监听
|
|
3679
|
+
*
|
|
3680
|
+
* @description 初始化失败只记录并保留启动参数,后续生成会重新尝试;监听属于辅助
|
|
3681
|
+
* 能力,不能阻断页面生成,也不能留下未处理的拒绝
|
|
3682
|
+
*/
|
|
3683
|
+
startPageWatcher() {
|
|
3684
|
+
if (this.disposed || !this.pageWatcherStart) return;
|
|
3685
|
+
try {
|
|
3686
|
+
this.pageWatcher.start(this.pageWatcherStart.options, this.pageWatcherStart.ignored, this.scanPlan);
|
|
3687
|
+
} catch (error) {
|
|
3688
|
+
this.logUpdateFailure(error);
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
/**
|
|
3692
|
+
* 释放本上下文的监听与待处理更新
|
|
3693
|
+
*
|
|
3694
|
+
* @description 关闭后不再接受监听注册或更新;已开始的生成会完成,重复调用等待同一次释放
|
|
3695
|
+
* 共享 watcher 的关闭仍由 Vite 负责
|
|
3696
|
+
*/
|
|
3697
|
+
async disposeWatchers() {
|
|
3698
|
+
if (this.disposal) return this.disposal;
|
|
3699
|
+
this.disposed = true;
|
|
3700
|
+
this.pendingPageUpdate = void 0;
|
|
3701
|
+
for (const dispose of this.watchers.values()) dispose();
|
|
3702
|
+
this.watchers.clear();
|
|
3703
|
+
this.watchedConfigPaths.clear();
|
|
3704
|
+
this._server = void 0;
|
|
3705
|
+
this.pageWatcherStart = void 0;
|
|
3706
|
+
this.disposal = (async () => {
|
|
3707
|
+
try {
|
|
3708
|
+
await this.pageWatcher.close();
|
|
3709
|
+
} finally {
|
|
3710
|
+
await this.pendingPageFlush;
|
|
3711
|
+
await this.pendingUpdate;
|
|
1699
3712
|
}
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
3713
|
+
})();
|
|
3714
|
+
return this.disposal;
|
|
3715
|
+
}
|
|
3716
|
+
/** 补充未覆盖的监听路径,注册成功后记账,失败时保留重试机会 */
|
|
3717
|
+
addWatchPaths(watcher, paths, added, description) {
|
|
3718
|
+
const wanted = paths.filter((file) => !added.has(file) && ![...added].some((existing) => file.startsWith(`${existing}/`)));
|
|
3719
|
+
if (!wanted.length) return;
|
|
3720
|
+
try {
|
|
3721
|
+
watcher.add(wanted);
|
|
3722
|
+
for (const file of wanted) added.add(file);
|
|
3723
|
+
} catch (error) {
|
|
3724
|
+
this.logger?.error(`Failed to watch ${description}: ${error instanceof Error ? error.message : error}`, {
|
|
3725
|
+
timestamp: true,
|
|
3726
|
+
error: error instanceof Error ? error : void 0
|
|
3727
|
+
});
|
|
3728
|
+
}
|
|
3729
|
+
}
|
|
3730
|
+
/**
|
|
3731
|
+
* 让监听路径与当前配置依赖保持一致
|
|
3732
|
+
*
|
|
3733
|
+
* 只新增路径,从不 unwatch:chokidar 对文件调用 unwatch 会连带
|
|
3734
|
+
* 拆掉父目录监听,新建文件就再也发现不了。因此监听集合是并集,
|
|
3735
|
+
* 会随着会话累积;每次刷新都按当前依赖重建配置监听计划,
|
|
3736
|
+
* 真正决定是否触发的始终是计划里的依赖集合(恢复目录除外,那是
|
|
3737
|
+
* 故意留的兜底)。
|
|
3738
|
+
*/
|
|
3739
|
+
refreshConfigWatchers() {
|
|
3740
|
+
this.configWatch.update(buildConfigWatchPlan({
|
|
3741
|
+
root: this.root,
|
|
3742
|
+
artifactDirectory: this.configLoader.artifactDirectory,
|
|
3743
|
+
sourcePaths: this.pagesConfigSourcePaths,
|
|
3744
|
+
dependencyPaths: this.pagesConfigDependencyPaths,
|
|
3745
|
+
recoveryCandidates: this.configLoader.watchInput.recoveryCandidates,
|
|
3746
|
+
recoveryDirectories: this.configLoader.watchInput.recoveryDirectories
|
|
3747
|
+
}));
|
|
3748
|
+
for (const watcher of this.watchers.keys()) {
|
|
3749
|
+
const added = this.watchedConfigPaths.get(watcher);
|
|
3750
|
+
const sharedRoot = this._server && watcher === this._server.watcher ? normalizeConfigPath(this._server.config.root, this.root) : void 0;
|
|
3751
|
+
this.addWatchPaths(watcher, this.configWatch.watchPaths(sharedRoot), added, "pages config dependencies");
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
/** 配置变化的完整更新:失败只记录,不让 Promise 拒绝 */
|
|
3755
|
+
async updatePagesAndNotify() {
|
|
3756
|
+
try {
|
|
3757
|
+
if (await this.updatePagesJSON() && !this.disposed) this.onUpdate();
|
|
3758
|
+
} catch (error) {
|
|
3759
|
+
this.logUpdateFailure(error);
|
|
3760
|
+
}
|
|
3761
|
+
}
|
|
3762
|
+
/** 记录 watcher 更新失败,避免未处理的拒绝终止进程 */
|
|
3763
|
+
logUpdateFailure(error) {
|
|
3764
|
+
this.logger?.error(`Failed to update pages.json after a file change: ${error instanceof Error ? error.message : error}`, {
|
|
3765
|
+
timestamp: true,
|
|
3766
|
+
error: error instanceof Error ? error : void 0
|
|
1710
3767
|
});
|
|
1711
3768
|
}
|
|
1712
3769
|
/**
|
|
3770
|
+
* 登记页面事件触发的更新:生成期间到达的事件合并到下一轮
|
|
3771
|
+
*
|
|
3772
|
+
* @description 连续删除、重建会一次性派发大量事件,逐个生成会反复
|
|
3773
|
+
* 重读全部页面;内容变更合并待刷新文件,结构变更执行完整刷新
|
|
3774
|
+
* @param filepath - 只读取该页面;省略时执行完整扫描
|
|
3775
|
+
*/
|
|
3776
|
+
queuePageUpdate(filepath) {
|
|
3777
|
+
if (this.disposed) return;
|
|
3778
|
+
if (!this.pendingPageUpdate) this.pendingPageUpdate = {
|
|
3779
|
+
full: false,
|
|
3780
|
+
files: /* @__PURE__ */ new Set()
|
|
3781
|
+
};
|
|
3782
|
+
if (filepath) this.pendingPageUpdate.files.add(filepath);
|
|
3783
|
+
else this.pendingPageUpdate.full = true;
|
|
3784
|
+
if (!this.pendingPageFlush) this.pendingPageFlush = this.flushPageUpdates();
|
|
3785
|
+
}
|
|
3786
|
+
/**
|
|
3787
|
+
* 排空页面事件队列;失败只记录,不让 Promise 拒绝
|
|
3788
|
+
*
|
|
3789
|
+
* 页面事件的回调走这里而不是直接调 {@link updatePagesJSON}:一旦
|
|
3790
|
+
* 它拒绝(拿不到文件锁、声明文件写不进去),就成了未处理的拒绝,
|
|
3791
|
+
* Node 默认直接终止进程。开发时正在编辑文件,一次偶发的锁冲突
|
|
3792
|
+
* 不该把 dev server 打死。用户改一次文件就会再触发一次事件,
|
|
3793
|
+
* 所以这里报错即可。
|
|
3794
|
+
*/
|
|
3795
|
+
async flushPageUpdates() {
|
|
3796
|
+
try {
|
|
3797
|
+
while (this.pendingPageUpdate) {
|
|
3798
|
+
const { full, files } = this.pendingPageUpdate;
|
|
3799
|
+
this.pendingPageUpdate = void 0;
|
|
3800
|
+
try {
|
|
3801
|
+
if ((full ? await this.updatePagesJSON() : files.size === 1 ? await this.updatePagesJSON([...files][0]) : await this.enqueuePagesUpdate([...files])) && !this.disposed) this.onUpdate();
|
|
3802
|
+
} catch (error) {
|
|
3803
|
+
this.logUpdateFailure(error);
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
} finally {
|
|
3807
|
+
this.pendingPageFlush = void 0;
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
/**
|
|
1713
3811
|
* 页面更新回调,页面文件或配置变化时触发
|
|
1714
3812
|
* 负责使虚拟模块失效并通知浏览器整页刷新
|
|
1715
3813
|
*/
|
|
@@ -1720,36 +3818,47 @@ var PageContext = class {
|
|
|
1720
3818
|
this._server.ws.send({ type: "full-reload" });
|
|
1721
3819
|
}
|
|
1722
3820
|
/**
|
|
1723
|
-
*
|
|
1724
|
-
*
|
|
1725
|
-
*
|
|
1726
|
-
*
|
|
1727
|
-
*
|
|
1728
|
-
*
|
|
1729
|
-
*
|
|
1730
|
-
* @param filepath - 发生变更的文件路径,用于增量更新判断
|
|
1731
|
-
* @returns pages.json 是否成功更新
|
|
3821
|
+
* 刷新页面配置并更新 pages.json
|
|
3822
|
+
*
|
|
3823
|
+
* @description 同一实例的调用按顺序执行;指定页面时尝试增量读取,页面尚未收录或物理身份变化时执行完整刷新
|
|
3824
|
+
*
|
|
3825
|
+
* @param filepath 变更页面的绝对路径或相对 root 的路径;省略时执行完整刷新
|
|
3826
|
+
* @returns pages.json 写入新内容时为 `true`,内容未变、上下文已关闭或跳过生成时为 `false`
|
|
3827
|
+
* @throws 生成、写入或声明输出失败时拒绝;声明输出失败前 pages.json 可能已更新
|
|
1732
3828
|
*/
|
|
1733
3829
|
async updatePagesJSON(filepath) {
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
3830
|
+
return this.enqueuePagesUpdate(filepath ? [filepath] : void 0);
|
|
3831
|
+
}
|
|
3832
|
+
enqueuePagesUpdate(files) {
|
|
3833
|
+
if (this.disposed) return Promise.resolve(false);
|
|
3834
|
+
const update = this.pendingUpdate.then(() => this.disposed ? false : this.generatePagesJSON(files));
|
|
3835
|
+
this.pendingUpdate = update.then(() => {}, () => {});
|
|
3836
|
+
return update;
|
|
3837
|
+
}
|
|
3838
|
+
async generatePagesJSON(files) {
|
|
3839
|
+
const candidates = files?.map((file) => this.findPages(file));
|
|
3840
|
+
const incremental = !!candidates?.length && candidates.every((pages) => pages.length > 0);
|
|
3841
|
+
if (incremental) {
|
|
3842
|
+
const pages = [...new Set(candidates.flat())];
|
|
3843
|
+
await Promise.all(pages.map((page) => page.read()));
|
|
3844
|
+
if (!pages.some((page) => page.hasChanged())) {
|
|
3845
|
+
debug.cache("Page metadata is unchanged, skipping generation");
|
|
3846
|
+
return false;
|
|
1742
3847
|
}
|
|
1743
3848
|
}
|
|
3849
|
+
this.generatedSnapshot = void 0;
|
|
1744
3850
|
checkPagesJsonFileSync(this.resolvedPagesJSONPath);
|
|
1745
3851
|
this.options.onBeforeLoadUserConfig();
|
|
1746
3852
|
await this.loadUserPagesConfig();
|
|
1747
3853
|
this.options.onAfterLoadUserConfig(this.pagesGlobConfig);
|
|
1748
3854
|
if (this.options.mergePages) {
|
|
1749
3855
|
this.options.onBeforeScanPages();
|
|
1750
|
-
|
|
1751
|
-
await this.
|
|
3856
|
+
this.refreshScanPlan();
|
|
3857
|
+
await this.scanPages(!incremental);
|
|
3858
|
+
await this.scanSubPages(!incremental);
|
|
1752
3859
|
this.options.onAfterScanPages(this.pages, this.subPages);
|
|
3860
|
+
this.startPageWatcher();
|
|
3861
|
+
this.pageWatcher.refresh(this.requireScanPlan());
|
|
1753
3862
|
}
|
|
1754
3863
|
this.options.onBeforeMergePageMetaData(this.pages, this.pagesGlobConfig);
|
|
1755
3864
|
await this.mergePageMetaData();
|
|
@@ -1760,6 +3869,13 @@ var PageContext = class {
|
|
|
1760
3869
|
this.options.onBeforeWriteFile(this.resolvedPagesJSONPath);
|
|
1761
3870
|
const homePath = this.pageMetaData.find((meta) => meta.type === "home")?.path;
|
|
1762
3871
|
this.tabBar = await this.resolveTabBar();
|
|
3872
|
+
this.generatedSnapshot = createPagesSnapshot({
|
|
3873
|
+
pages: this.pageMetaData,
|
|
3874
|
+
subPackages: this.subPageMetaData,
|
|
3875
|
+
tabBar: this.tabBar,
|
|
3876
|
+
globConfig: this.pagesGlobConfig,
|
|
3877
|
+
homePath
|
|
3878
|
+
});
|
|
1763
3879
|
const result = await writePagesJson(this.resolvedPagesJSONPath, {
|
|
1764
3880
|
pages: this.pageMetaData,
|
|
1765
3881
|
subPackages: this.subPageMetaData,
|
|
@@ -1775,9 +3891,29 @@ var PageContext = class {
|
|
|
1775
3891
|
insertFinalNewline: this.options.insertFinalNewline
|
|
1776
3892
|
}
|
|
1777
3893
|
});
|
|
1778
|
-
this.
|
|
1779
|
-
|
|
1780
|
-
|
|
3894
|
+
if (!result) throw new Error(`[vite-plugin-uni-pages] Failed to acquire the pages.json file lock: ${this.resolvedPagesJSONPath}`);
|
|
3895
|
+
try {
|
|
3896
|
+
await this.generateDeclaration();
|
|
3897
|
+
} catch (error) {
|
|
3898
|
+
if (result.updated) {
|
|
3899
|
+
this.options.onAfterWriteFile(this.resolvedPagesJSONPath, result.content);
|
|
3900
|
+
this.onUpdate();
|
|
3901
|
+
}
|
|
3902
|
+
throw error;
|
|
3903
|
+
}
|
|
3904
|
+
if (result.updated) this.options.onAfterWriteFile(this.resolvedPagesJSONPath, result.content);
|
|
3905
|
+
if (this.configWatch.consumeExpanded() && !this.disposed) this.queuePageUpdate();
|
|
3906
|
+
return result.updated;
|
|
3907
|
+
}
|
|
3908
|
+
/** 最近一次生成的路由快照;未写入文件时由当前工作字段合成 */
|
|
3909
|
+
get snapshot() {
|
|
3910
|
+
return this.generatedSnapshot ?? createPagesSnapshot({
|
|
3911
|
+
pages: this.pageMetaData,
|
|
3912
|
+
subPackages: this.subPageMetaData,
|
|
3913
|
+
tabBar: this.tabBar,
|
|
3914
|
+
globConfig: this.pagesGlobConfig,
|
|
3915
|
+
homePath: this.pageMetaData.find((meta) => meta.type === "home")?.path
|
|
3916
|
+
});
|
|
1781
3917
|
}
|
|
1782
3918
|
/**
|
|
1783
3919
|
* 生成虚拟模块内容
|
|
@@ -1785,21 +3921,22 @@ var PageContext = class {
|
|
|
1785
3921
|
* @returns 虚拟模块代码字符串
|
|
1786
3922
|
*/
|
|
1787
3923
|
virtualModule() {
|
|
1788
|
-
|
|
3924
|
+
const { pages, subPackages } = this.snapshot;
|
|
3925
|
+
return [`export const pages = ${stringify(pages, null, 2)};`, `export const subPackages = ${stringify(subPackages, null, 2)};`].join("\n");
|
|
1789
3926
|
}
|
|
1790
3927
|
/**
|
|
1791
3928
|
* 将主包路由数据解析为 JSON 字符串
|
|
1792
3929
|
* @returns 主包页面配置的 JSON 字符串
|
|
1793
3930
|
*/
|
|
1794
3931
|
resolveRoutes() {
|
|
1795
|
-
return stringify(this.
|
|
3932
|
+
return stringify(this.snapshot.pages, null, 2);
|
|
1796
3933
|
}
|
|
1797
3934
|
/**
|
|
1798
|
-
*
|
|
1799
|
-
* @returns
|
|
3935
|
+
* 将分包路由数据解析为 JSON 字符串
|
|
3936
|
+
* @returns 分包页面配置的 JSON 字符串
|
|
1800
3937
|
*/
|
|
1801
3938
|
resolveSubRoutes() {
|
|
1802
|
-
return stringify(this.
|
|
3939
|
+
return stringify(this.snapshot.subPackages, null, 2);
|
|
1803
3940
|
}
|
|
1804
3941
|
/**
|
|
1805
3942
|
* 解析 tabBar 配置
|
|
@@ -1832,64 +3969,183 @@ var PageContext = class {
|
|
|
1832
3969
|
generateDeclaration() {
|
|
1833
3970
|
if (!this.options.dts) return;
|
|
1834
3971
|
debug.declaration("generating");
|
|
1835
|
-
return writeDeclaration(
|
|
1836
|
-
pages: this.pageMetaData,
|
|
1837
|
-
subPackages: this.subPageMetaData,
|
|
1838
|
-
tabBar: this.tabBar,
|
|
1839
|
-
globConfig: this.pagesGlobConfig
|
|
1840
|
-
}, this.options.dts);
|
|
3972
|
+
return writeDeclaration(this.snapshot, this.options.dts);
|
|
1841
3973
|
}
|
|
1842
3974
|
/**
|
|
1843
|
-
*
|
|
1844
|
-
*
|
|
3975
|
+
* 按词法目录扫描主包页面
|
|
3976
|
+
*
|
|
3977
|
+
* @description 各目录分别执行文件排除,物理别名保留到页面有效性与归属决议阶段
|
|
1845
3978
|
*/
|
|
1846
|
-
async scanPages() {
|
|
1847
|
-
const
|
|
1848
|
-
debug.pages(paths);
|
|
3979
|
+
async scanPages(refreshContent = true) {
|
|
3980
|
+
const plan = this.requireScanPlan();
|
|
1849
3981
|
const pages = /* @__PURE__ */ new Map();
|
|
1850
|
-
for (const
|
|
1851
|
-
|
|
1852
|
-
pages.
|
|
3982
|
+
for (const [matchIndex, dir] of plan.mainDirs.entries()) for (const pagePath of getPagePaths(dir, this.options, plan.basePath)) {
|
|
3983
|
+
if (pages.has(pagePath.absolutePath)) continue;
|
|
3984
|
+
const page = this.trackPage(pagePath, this.pages.get(pagePath.absolutePath) ?? this.mainPageCandidates.get(pagePath.absolutePath), {
|
|
3985
|
+
dir,
|
|
3986
|
+
explicitRoot: false,
|
|
3987
|
+
ruleIndex: 0,
|
|
3988
|
+
matchIndex
|
|
3989
|
+
}, refreshContent);
|
|
3990
|
+
if (page) pages.set(pagePath.absolutePath, page);
|
|
1853
3991
|
}
|
|
1854
|
-
|
|
3992
|
+
debug.pages([...pages.keys()]);
|
|
3993
|
+
this.mainPageCandidates = pages;
|
|
3994
|
+
this.pages = new Map(pages);
|
|
3995
|
+
}
|
|
3996
|
+
/**
|
|
3997
|
+
* 登记本轮来源并复用身份与输出基准均未变化的 Page
|
|
3998
|
+
*
|
|
3999
|
+
* @description 整轮更新使读取缓存失效,增量更新复用目标页的预读结果与其他页面缓存
|
|
4000
|
+
* @returns 路径仍存在时返回页面实例,扫描期间已消失时为 undefined
|
|
4001
|
+
*/
|
|
4002
|
+
trackPage(pagePath, previous, source, refreshContent) {
|
|
4003
|
+
const identity = resolvePageIdentity(pagePath.absolutePath);
|
|
4004
|
+
if (!identity) return;
|
|
4005
|
+
const page = previous && this.pageSources.get(previous)?.identity === identity && previous.path.relativePath === pagePath.relativePath ? previous : new Page(this.pageEnvironment(), pagePath);
|
|
4006
|
+
if (refreshContent) page.invalidate();
|
|
4007
|
+
this.pageSources.set(page, {
|
|
4008
|
+
file: pagePath.absolutePath,
|
|
4009
|
+
identity,
|
|
4010
|
+
dir: source.dir,
|
|
4011
|
+
root: source.root,
|
|
4012
|
+
explicitRoot: source.explicitRoot,
|
|
4013
|
+
ruleIndex: source.ruleIndex,
|
|
4014
|
+
matchIndex: source.matchIndex,
|
|
4015
|
+
rootSource: source.rootSource,
|
|
4016
|
+
rulePattern: this.configuredRule(source)
|
|
4017
|
+
});
|
|
4018
|
+
return page;
|
|
4019
|
+
}
|
|
4020
|
+
pageEnvironment() {
|
|
4021
|
+
return {
|
|
4022
|
+
platform: this.platform,
|
|
4023
|
+
getLogger: () => this.logger
|
|
4024
|
+
};
|
|
4025
|
+
}
|
|
4026
|
+
/** 页面来源的原始声明规则,用于冲突诊断;hook 页面可能没有 */
|
|
4027
|
+
configuredRule(source) {
|
|
4028
|
+
if (source.root === void 0) return this.options.dir;
|
|
4029
|
+
const pattern = this.options.subPackagePatterns[source.ruleIndex];
|
|
4030
|
+
return typeof pattern === "string" ? pattern : pattern?.dir;
|
|
1855
4031
|
}
|
|
1856
4032
|
/**
|
|
1857
|
-
*
|
|
4033
|
+
* 按词法路径或物理身份查找全部缓存候选
|
|
1858
4034
|
* @param filepath - 页面文件的绝对路径
|
|
1859
|
-
* @returns
|
|
4035
|
+
* @returns 主包和分包中属于同一文件的页面实例,每个实例只返回一次
|
|
1860
4036
|
*/
|
|
1861
|
-
|
|
1862
|
-
const
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
4037
|
+
findPages(filepath) {
|
|
4038
|
+
const absolute = normalizePath(path.resolve(this.root, filepath));
|
|
4039
|
+
const groups = [
|
|
4040
|
+
this.mainPageCandidates,
|
|
4041
|
+
...this.subPageCandidates.values(),
|
|
4042
|
+
this.pages,
|
|
4043
|
+
...this.subPages.values()
|
|
4044
|
+
];
|
|
4045
|
+
const identity = resolvePageIdentity(absolute);
|
|
4046
|
+
if (!identity) return [];
|
|
4047
|
+
const matched = groups.flatMap((pages) => [...pages.entries()].flatMap(([file, page]) => {
|
|
4048
|
+
const source = this.pageSources.get(page);
|
|
4049
|
+
return file === absolute || source?.identity === identity ? [page] : [];
|
|
4050
|
+
}));
|
|
4051
|
+
if (matched.some((page) => this.pageSources.get(page)?.identity !== identity || resolvePageIdentity(page.path.absolutePath) !== identity)) return [];
|
|
4052
|
+
return [...new Set(matched)];
|
|
1868
4053
|
}
|
|
1869
4054
|
/**
|
|
1870
|
-
*
|
|
1871
|
-
*
|
|
4055
|
+
* 按词法来源扫描分包页面
|
|
4056
|
+
*
|
|
4057
|
+
* @description 同一物理目录的不同别名仍分别执行文件排除,避免某个别名被排除后漏页
|
|
1872
4058
|
*/
|
|
1873
|
-
async scanSubPages() {
|
|
4059
|
+
async scanSubPages(refreshContent = true) {
|
|
4060
|
+
const plan = this.requireScanPlan();
|
|
1874
4061
|
const paths = {};
|
|
1875
4062
|
const subPages = /* @__PURE__ */ new Map();
|
|
1876
|
-
|
|
1877
|
-
|
|
4063
|
+
const sources = this.subPackageSourcesByDir();
|
|
4064
|
+
for (const [dir, source] of sources) {
|
|
4065
|
+
const pagePaths = getPagePaths(dir, this.options, plan.basePath);
|
|
1878
4066
|
paths[dir] = pagePaths;
|
|
1879
4067
|
const pages = /* @__PURE__ */ new Map();
|
|
1880
|
-
for (const
|
|
1881
|
-
const page = this.subPages.get(dir)?.get(
|
|
1882
|
-
pages.set(
|
|
4068
|
+
for (const pagePath of pagePaths) {
|
|
4069
|
+
const page = this.trackPage(pagePath, this.subPages.get(dir)?.get(pagePath.absolutePath) ?? this.subPageCandidates.get(dir)?.get(pagePath.absolutePath), source, refreshContent);
|
|
4070
|
+
if (page) pages.set(pagePath.absolutePath, page);
|
|
1883
4071
|
}
|
|
1884
4072
|
subPages.set(dir, pages);
|
|
1885
4073
|
}
|
|
1886
4074
|
debug.subPages(JSON.stringify(paths, null, 2));
|
|
1887
|
-
this.
|
|
4075
|
+
this.subPageCandidates = subPages;
|
|
4076
|
+
this.subPages = new Map([...subPages].map(([dir, pages]) => [dir, new Map(pages)]));
|
|
4077
|
+
}
|
|
4078
|
+
/**
|
|
4079
|
+
* 为每个物理扫描目录选取声明来源
|
|
4080
|
+
*
|
|
4081
|
+
* @description 同一路径的不同写法只扫描一次,定位信息按显式优先选择;
|
|
4082
|
+
* 符号链接别名是不同的 absolute,仍分别保留各自的词法路径
|
|
4083
|
+
*/
|
|
4084
|
+
subPackageSourcesByDir() {
|
|
4085
|
+
const selected = /* @__PURE__ */ new Map();
|
|
4086
|
+
const sources = this.scanPlan?.subPackageSources ?? [];
|
|
4087
|
+
for (const source of sources) {
|
|
4088
|
+
const previous = selected.get(source.absolute);
|
|
4089
|
+
if (!previous || comparePageSources(source, previous) < 0) selected.set(source.absolute, source);
|
|
4090
|
+
}
|
|
4091
|
+
return new Map([...selected.values()].map((source) => [source.dir, source]));
|
|
4092
|
+
}
|
|
4093
|
+
/** 获取目录的最终分包 root,未登记时相对 outDir 计算默认值 */
|
|
4094
|
+
subPackageRoot(dir) {
|
|
4095
|
+
return this.scanPlan?.subPackageRootMap.get(dir) ?? this.options.subPackageRootMap.get(dir) ?? normalizePath(path.relative(this.basePath, path.resolve(this.options.root, dir)));
|
|
4096
|
+
}
|
|
4097
|
+
/**
|
|
4098
|
+
* 决议有效页面的归属并校验生成路由
|
|
4099
|
+
*
|
|
4100
|
+
* @description 先读取宏并应用既有平台规则,再选择代表;冲突校验通过后才裁剪页面映射,
|
|
4101
|
+
* 配置覆盖与输出去重在此之后执行
|
|
4102
|
+
*/
|
|
4103
|
+
async resolveScanSources() {
|
|
4104
|
+
const candidates = [];
|
|
4105
|
+
const subSources = this.options.mergePages ? this.subPackageSourcesByDir() : /* @__PURE__ */ new Map();
|
|
4106
|
+
const groups = [[void 0, this.pages], ...this.subPages];
|
|
4107
|
+
await Promise.all(groups.flatMap(([, pages]) => [...pages.values()].map((page) => page.ensureLoaded())));
|
|
4108
|
+
for (const [dir, pages] of groups) {
|
|
4109
|
+
const root = dir === void 0 ? void 0 : this.subPackageRoot(dir);
|
|
4110
|
+
for (const [file, page] of pages) {
|
|
4111
|
+
if (page.skipped) continue;
|
|
4112
|
+
const meta = await page.getPageMeta();
|
|
4113
|
+
const effective = dir === void 0 && this.withUniPlatform ? filterPlatformSuffixPages([meta], this.platform)[0] : meta;
|
|
4114
|
+
if (!effective) continue;
|
|
4115
|
+
const original = this.pageSources.get(page);
|
|
4116
|
+
const identity = original?.identity ?? resolvePageIdentity(file);
|
|
4117
|
+
if (!identity) continue;
|
|
4118
|
+
const source = dir === void 0 ? void 0 : subSources.get(dir);
|
|
4119
|
+
const ruleIndex = source?.ruleIndex ?? original?.ruleIndex ?? this.options.subPackages.indexOf(dir);
|
|
4120
|
+
candidates.push({
|
|
4121
|
+
...original,
|
|
4122
|
+
...source,
|
|
4123
|
+
page,
|
|
4124
|
+
file,
|
|
4125
|
+
identity,
|
|
4126
|
+
dir: dir ?? original?.dir ?? this.options.dir,
|
|
4127
|
+
root,
|
|
4128
|
+
explicitRoot: source?.explicitRoot ?? original?.explicitRoot ?? false,
|
|
4129
|
+
ruleIndex,
|
|
4130
|
+
matchIndex: source?.matchIndex ?? original?.matchIndex ?? 0,
|
|
4131
|
+
rulePattern: original?.rulePattern ?? this.configuredRule({
|
|
4132
|
+
root,
|
|
4133
|
+
ruleIndex
|
|
4134
|
+
}),
|
|
4135
|
+
route: root === void 0 ? effective.path : path.posix.join(root, normalizePath(path.relative(root, effective.path)))
|
|
4136
|
+
});
|
|
4137
|
+
}
|
|
4138
|
+
}
|
|
4139
|
+
const selected = selectPageSources(candidates);
|
|
4140
|
+
validateGeneratedRoutes(selected, this.withUniPlatform ? this.platform : void 0);
|
|
4141
|
+
const active = new Set(candidates.map((source) => source.page));
|
|
4142
|
+
const representatives = new Set(selected.map((source) => source.page));
|
|
4143
|
+
for (const pages of [this.pages, ...this.subPages.values()]) for (const [file, page] of pages) if (active.has(page) && !representatives.has(page)) pages.delete(file);
|
|
1888
4144
|
}
|
|
1889
4145
|
/**
|
|
1890
4146
|
* 解析 pages 规则并设置页面类型
|
|
1891
4147
|
* @param pages 页面路径映射
|
|
1892
|
-
* @param packageType
|
|
4148
|
+
* @param packageType 页面包类型(主包或分包)
|
|
1893
4149
|
* @param overrides 自定义页面配置
|
|
1894
4150
|
* @returns pages 规则
|
|
1895
4151
|
*/
|
|
@@ -1929,25 +4185,33 @@ var PageContext = class {
|
|
|
1929
4185
|
return result;
|
|
1930
4186
|
}
|
|
1931
4187
|
/**
|
|
1932
|
-
*
|
|
1933
|
-
*
|
|
4188
|
+
* 决议扫描来源后合并主包页面配置
|
|
4189
|
+
*
|
|
4190
|
+
* @description 有效分包优先认领物理页面,生成来源冲突在用户配置覆盖前检查
|
|
1934
4191
|
*/
|
|
1935
4192
|
async mergePageMetaData() {
|
|
1936
|
-
|
|
4193
|
+
await this.resolveScanSources();
|
|
1937
4194
|
const pageMetaData = await this.parsePages(this.pages, "main", this.pagesGlobConfig?.pages);
|
|
1938
4195
|
this.pageMetaData = pageMetaData;
|
|
1939
4196
|
debug.pages(this.pageMetaData);
|
|
1940
4197
|
}
|
|
1941
4198
|
/**
|
|
1942
|
-
*
|
|
1943
|
-
*
|
|
1944
|
-
*
|
|
4199
|
+
* 合并分包页面配置
|
|
4200
|
+
*
|
|
4201
|
+
* @description 静态、glob 和回调来源先按最终 root 汇集,再对整组应用一次配置覆盖,
|
|
4202
|
+
* 保留手工页面和分包 plugins 配置
|
|
1945
4203
|
*/
|
|
1946
4204
|
async mergeSubPageMetaData() {
|
|
1947
4205
|
const packagesByRoot = /* @__PURE__ */ new Map();
|
|
1948
4206
|
const subPackages = this.pagesGlobConfig?.subPackages || [];
|
|
4207
|
+
const pagesByRoot = /* @__PURE__ */ new Map();
|
|
1949
4208
|
for (const [dir, pages] of this.subPages) {
|
|
1950
|
-
const root = this.
|
|
4209
|
+
const root = this.subPackageRoot(dir);
|
|
4210
|
+
const collected = pagesByRoot.get(root) ?? /* @__PURE__ */ new Map();
|
|
4211
|
+
for (const [file, page] of pages) collected.set(file, page);
|
|
4212
|
+
pagesByRoot.set(root, collected);
|
|
4213
|
+
}
|
|
4214
|
+
for (const [root, pages] of pagesByRoot) {
|
|
1951
4215
|
const globPackage = subPackages?.find((v) => v.root === root);
|
|
1952
4216
|
const overrides = globPackage?.pages?.map((page) => {
|
|
1953
4217
|
if (!page.path || page.path.startsWith(`${root}/`)) return page;
|
|
@@ -1989,9 +4253,8 @@ function resolveBasePath(options) {
|
|
|
1989
4253
|
* @param options - 解析后的配置项
|
|
1990
4254
|
* @returns 包含相对路径与绝对路径的页面路径数组
|
|
1991
4255
|
*/
|
|
1992
|
-
function getPagePaths(dir, options) {
|
|
4256
|
+
function getPagePaths(dir, options, basePath) {
|
|
1993
4257
|
const pagesDirPath = normalizePath(path.resolve(options.root, dir));
|
|
1994
|
-
const basePath = resolveBasePath(options);
|
|
1995
4258
|
const files = getPageFiles(pagesDirPath, options);
|
|
1996
4259
|
debug.pages(dir, files);
|
|
1997
4260
|
return files.map((file) => normalizePath(file)).map((file) => ({
|
|
@@ -2134,25 +4397,78 @@ async function generateAll(userOptions = {}, overrides = {}) {
|
|
|
2134
4397
|
* @returns Vite 插件实例
|
|
2135
4398
|
*/
|
|
2136
4399
|
function VitePluginUniPages(userOptions = {}) {
|
|
2137
|
-
let
|
|
2138
|
-
|
|
2139
|
-
|
|
4400
|
+
let initialization;
|
|
4401
|
+
let preparedParams;
|
|
4402
|
+
const resolvedPagesJSONPath = resolvePagesJsonPath(process.env.VITE_ROOT_DIR || process.cwd(), userOptions.outDir ?? "src");
|
|
4403
|
+
if (existsSync(path.dirname(resolvedPagesJSONPath))) checkPagesJsonFileSync(resolvedPagesJSONPath);
|
|
4404
|
+
const plugin = {
|
|
2140
4405
|
name: "vite-plugin-uni-pages",
|
|
2141
4406
|
enforce: "pre",
|
|
4407
|
+
prepare(options) {
|
|
4408
|
+
if (typeof options?.platformSuffix !== "boolean") return Promise.reject(/* @__PURE__ */ new TypeError("[vite-plugin-uni-pages] prepare() requires an explicit boolean platformSuffix option."));
|
|
4409
|
+
try {
|
|
4410
|
+
return initialize(options.root ?? process.env.VITE_ROOT_DIR ?? process.cwd(), options.platformSuffix, "prepare").promise;
|
|
4411
|
+
} catch (error) {
|
|
4412
|
+
return Promise.reject(error);
|
|
4413
|
+
}
|
|
4414
|
+
},
|
|
2142
4415
|
/**
|
|
2143
4416
|
* Vite configResolved 钩子
|
|
2144
4417
|
* 初始化 PageContext,设置 logger,生成初始 pages.json
|
|
2145
4418
|
*/
|
|
2146
4419
|
async configResolved(config) {
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
4420
|
+
const state = initialize(config.root, config.plugins.some((v) => v.name === "vite-plugin-uni-platform"), config.command, {
|
|
4421
|
+
...config.env,
|
|
4422
|
+
SSR: false
|
|
4423
|
+
}, config.define);
|
|
4424
|
+
state.watching = config.command === "build" && !!config.build.watch;
|
|
4425
|
+
try {
|
|
4426
|
+
await state.promise;
|
|
4427
|
+
if (state.closing) throw new Error("[vite-plugin-uni-pages] The pages context was closed during initialization.");
|
|
4428
|
+
if (state.watching) {
|
|
4429
|
+
const lockDirectory = normalizeConfigPath(`${state.context.resolvedPagesJSONPath}.lock`, config.root);
|
|
4430
|
+
state.buildWatcher = chokidar.watch([], {
|
|
4431
|
+
ignoreInitial: true,
|
|
4432
|
+
followSymlinks: false,
|
|
4433
|
+
ignored: (file) => {
|
|
4434
|
+
const absolute = normalizeConfigPath(file, config.root);
|
|
4435
|
+
return absolute.split("/").some((part) => part === "node_modules" || part === ".git") || absolute === lockDirectory || absolute.startsWith(`${lockDirectory}/`);
|
|
4436
|
+
}
|
|
4437
|
+
});
|
|
4438
|
+
await state.context.setupWatcher(state.buildWatcher);
|
|
4439
|
+
}
|
|
4440
|
+
} catch (error) {
|
|
4441
|
+
await release(state);
|
|
4442
|
+
throw error;
|
|
2154
4443
|
}
|
|
2155
4444
|
},
|
|
4445
|
+
options(options) {
|
|
4446
|
+
const state = initialization;
|
|
4447
|
+
if (state?.command !== "build") return;
|
|
4448
|
+
const hooks = {
|
|
4449
|
+
options: void 0,
|
|
4450
|
+
load: (id) => loadVirtualModule(state, id),
|
|
4451
|
+
closeWatcher: () => release(state),
|
|
4452
|
+
closeBundle: () => state.watching ? void 0 : release(state)
|
|
4453
|
+
};
|
|
4454
|
+
const plugins = Array.isArray(options.plugins) ? options.plugins : [options.plugins];
|
|
4455
|
+
plugins.forEach((candidate, index) => {
|
|
4456
|
+
if (candidate && typeof candidate === "object" && "options" in candidate && candidate.options === plugin.options) plugins[index] = {
|
|
4457
|
+
...candidate,
|
|
4458
|
+
...hooks
|
|
4459
|
+
};
|
|
4460
|
+
});
|
|
4461
|
+
return {
|
|
4462
|
+
...options,
|
|
4463
|
+
plugins
|
|
4464
|
+
};
|
|
4465
|
+
},
|
|
4466
|
+
async closeWatcher() {
|
|
4467
|
+
if (initialization) await release(initialization);
|
|
4468
|
+
},
|
|
4469
|
+
async closeBundle() {
|
|
4470
|
+
if (initialization && !initialization.watching) await release(initialization);
|
|
4471
|
+
},
|
|
2156
4472
|
/**
|
|
2157
4473
|
* 代码转换钩子
|
|
2158
4474
|
* 从 Vue SFC 中移除 definePage 宏调用,避免运行时报错
|
|
@@ -2179,7 +4495,7 @@ function VitePluginUniPages(userOptions = {}) {
|
|
|
2179
4495
|
* 设置文件监听与 HMR 支持
|
|
2180
4496
|
*/
|
|
2181
4497
|
configureServer(server) {
|
|
2182
|
-
|
|
4498
|
+
initialization?.context.setupViteServer(server);
|
|
2183
4499
|
},
|
|
2184
4500
|
/**
|
|
2185
4501
|
* 模块解析钩子
|
|
@@ -2193,9 +4509,109 @@ function VitePluginUniPages(userOptions = {}) {
|
|
|
2193
4509
|
* 返回虚拟模块的代码内容
|
|
2194
4510
|
*/
|
|
2195
4511
|
load(id) {
|
|
2196
|
-
|
|
4512
|
+
return loadVirtualModule(initialization, id);
|
|
2197
4513
|
}
|
|
2198
4514
|
};
|
|
4515
|
+
function initialize(root, platformSuffix, source, configEnv, configDefine) {
|
|
4516
|
+
const resolvedRoot = normalizePath(path.resolve(root));
|
|
4517
|
+
const platform = process.env.UNI_PLATFORM;
|
|
4518
|
+
if (!platform) throw new Error("[vite-plugin-uni-pages] UNI_PLATFORM must be set before initializing pages. Run through the uni-app CLI or set the compilation platform before calling the plugin.");
|
|
4519
|
+
const params = {
|
|
4520
|
+
root: resolvedRoot,
|
|
4521
|
+
platform,
|
|
4522
|
+
platformSuffix
|
|
4523
|
+
};
|
|
4524
|
+
if (initialization?.closing || source !== "prepare" && initialization?.command) throw new Error("[vite-plugin-uni-pages] This plugin instance already has an active Vite session. Wait for it to close, or create a separate UniPages() instance for overlapping builds and servers. If Vite exited before starting Rollup or the dev server, this instance cannot be released either.");
|
|
4525
|
+
const expected = preparedParams ?? initialization?.params;
|
|
4526
|
+
const mismatched = expected && Object.keys(params).find((key) => expected[key] !== params[key]);
|
|
4527
|
+
if (mismatched) throw new Error(`[vite-plugin-uni-pages] ${mismatched} does not match the initialized pages context. Use the same root, UNI_PLATFORM and UniPlatform setting for prepare() and Vite.`);
|
|
4528
|
+
if (initialization) {
|
|
4529
|
+
if (source === "prepare") {
|
|
4530
|
+
initialization.prepared = true;
|
|
4531
|
+
if (initialization.ready) preparedParams = params;
|
|
4532
|
+
} else initialization.command = source;
|
|
4533
|
+
if (configEnv) {
|
|
4534
|
+
const state = initialization;
|
|
4535
|
+
state.promise = state.promise.then(async () => {
|
|
4536
|
+
if (state.closing) throw new Error("[vite-plugin-uni-pages] The pages context was closed during initialization.");
|
|
4537
|
+
if (state.context.setConfigEnv(configEnv, configDefine)) await state.context.updatePagesJSON();
|
|
4538
|
+
if (state.closing) throw new Error("[vite-plugin-uni-pages] The pages context was closed during initialization.");
|
|
4539
|
+
return plugin;
|
|
4540
|
+
});
|
|
4541
|
+
}
|
|
4542
|
+
return initialization;
|
|
4543
|
+
}
|
|
4544
|
+
const context = new PageContext(userOptions, resolvedRoot, platform);
|
|
4545
|
+
context.withUniPlatform = platformSuffix;
|
|
4546
|
+
if (configEnv) context.setConfigEnv(configEnv, configDefine);
|
|
4547
|
+
context.setLogger(createLogger(void 0, { prefix: "[vite-plugin-uni-pages]" }));
|
|
4548
|
+
const state = {
|
|
4549
|
+
params,
|
|
4550
|
+
context,
|
|
4551
|
+
prepared: source === "prepare",
|
|
4552
|
+
ready: false,
|
|
4553
|
+
command: source === "prepare" ? void 0 : source,
|
|
4554
|
+
watching: false,
|
|
4555
|
+
promise: Promise.resolve().then(async () => {
|
|
4556
|
+
await context.updatePagesJSON();
|
|
4557
|
+
if (state.closing) throw new Error("[vite-plugin-uni-pages] The pages context was closed during initialization.");
|
|
4558
|
+
state.ready = true;
|
|
4559
|
+
if (state.prepared) preparedParams = params;
|
|
4560
|
+
return plugin;
|
|
4561
|
+
}).catch(async (error) => {
|
|
4562
|
+
try {
|
|
4563
|
+
await context.disposeWatchers();
|
|
4564
|
+
} catch (cleanupError) {
|
|
4565
|
+
reportReleaseFailure(state, cleanupError);
|
|
4566
|
+
} finally {
|
|
4567
|
+
if (initialization === state && !state.closing) initialization = void 0;
|
|
4568
|
+
}
|
|
4569
|
+
throw error;
|
|
4570
|
+
})
|
|
4571
|
+
};
|
|
4572
|
+
initialization = state;
|
|
4573
|
+
return state;
|
|
4574
|
+
}
|
|
4575
|
+
function loadVirtualModule(state, id) {
|
|
4576
|
+
if (id !== "\0virtual:uni-pages") return;
|
|
4577
|
+
if (!state || state.closing) throw new Error("[vite-plugin-uni-pages] The pages context is closed.");
|
|
4578
|
+
return state.context.virtualModule();
|
|
4579
|
+
}
|
|
4580
|
+
/** 记录释放失败;关闭流程不因清理错误失败 */
|
|
4581
|
+
function reportReleaseFailure(state, error) {
|
|
4582
|
+
state.context.logger?.error(`Failed to release the pages context: ${error instanceof Error ? error.message : error}`, {
|
|
4583
|
+
timestamp: true,
|
|
4584
|
+
error: error instanceof Error ? error : void 0
|
|
4585
|
+
});
|
|
4586
|
+
}
|
|
4587
|
+
/**
|
|
4588
|
+
* 释放当前会话
|
|
4589
|
+
*
|
|
4590
|
+
* @description 解绑监听、等待已开始的生成并关闭构建 watcher;清理错误只记录,完成后释放实例占用
|
|
4591
|
+
*/
|
|
4592
|
+
function release(state) {
|
|
4593
|
+
if (!state.closing) {
|
|
4594
|
+
const disposing = state.context.disposeWatchers();
|
|
4595
|
+
state.closing = (async () => {
|
|
4596
|
+
try {
|
|
4597
|
+
await disposing;
|
|
4598
|
+
} catch (error) {
|
|
4599
|
+
reportReleaseFailure(state, error);
|
|
4600
|
+
} finally {
|
|
4601
|
+
await state.promise.catch(() => {});
|
|
4602
|
+
try {
|
|
4603
|
+
await state.buildWatcher?.close();
|
|
4604
|
+
} catch (error) {
|
|
4605
|
+
reportReleaseFailure(state, error);
|
|
4606
|
+
} finally {
|
|
4607
|
+
if (initialization === state) initialization = void 0;
|
|
4608
|
+
}
|
|
4609
|
+
}
|
|
4610
|
+
})();
|
|
4611
|
+
}
|
|
4612
|
+
return state.closing;
|
|
4613
|
+
}
|
|
4614
|
+
return plugin;
|
|
2199
4615
|
}
|
|
2200
4616
|
//#endregion
|
|
2201
|
-
export { DefineConditional, FILE_EXTENSIONS, MODULE_ID_VIRTUAL, OUTPUT_NAME, Page, PageContext, RESOLVED_MODULE_ID_VIRTUAL, VitePluginUniPages, VitePluginUniPages as default, checkPagesJsonFileSync, createPages, debug, defineUniPages, evaluateDefinePage, filterPlatformSuffixPages, findDefinePageMacro, generateAll, getPageFiles, isConditional, isTargetFile, mergePagesJson, parseSFC, resolveConditional, resolveOptions, resolvePageDirs, resolvePagesJsonPath, withFileLock, writePagesJson };
|
|
4617
|
+
export { DefineConditional, FILE_EXTENSIONS, MODULE_ID_VIRTUAL, OUTPUT_NAME, Page, PageContext, RESOLVED_MODULE_ID_VIRTUAL, VitePluginUniPages, VitePluginUniPages as default, checkPagesJsonFileSync, createPages, debug, defineUniPages, discoverSubPackageDirectories, evaluateDefinePage, filterPlatformSuffixPages, findDefinePageMacro, generateAll, getPageFiles, getSubPackageDirectorySources, isConditional, isMissingFsError, isPageDirectoryEvent, isPageFileInDirectories, isTargetFile, mergePagesJson, normalizePagePattern, parseSFC, refreshPageDirectories, resolveConditional, resolveOptions, resolvePageDirs, resolvePagesJsonPath, resolveSubPackageDirs, retryOnEperm, unescapePagePattern, withFileLock, writePagesJson };
|