@mpcore/simulator 0.0.0 → 0.0.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/LICENSE +21 -0
- package/dist/index.d.mts +489 -36
- package/dist/index.mjs +1844 -169
- package/package.json +10 -10
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,207 @@
|
|
|
1
|
+
import { dirname, join, normalize, posix } from "pathe";
|
|
2
|
+
import { parseDocument } from "htmlparser2";
|
|
1
3
|
import fs from "node:fs";
|
|
2
4
|
import path from "node:path";
|
|
3
|
-
import { normalize } from "pathe";
|
|
4
5
|
import process from "node:process";
|
|
5
6
|
import vm from "node:vm";
|
|
6
|
-
|
|
7
|
+
//#region src/host/globals.ts
|
|
8
|
+
function createDuplicateRegistrationError(kind, id) {
|
|
9
|
+
return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
|
|
10
|
+
}
|
|
11
|
+
function createHostRegistries() {
|
|
12
|
+
return {
|
|
13
|
+
appDefinition: null,
|
|
14
|
+
components: /* @__PURE__ */ new Map(),
|
|
15
|
+
currentLoadContext: null,
|
|
16
|
+
pages: /* @__PURE__ */ new Map()
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function registerAppDefinition(registries, definition) {
|
|
20
|
+
if (registries.appDefinition) throw createDuplicateRegistrationError("app", "app");
|
|
21
|
+
registries.appDefinition = definition;
|
|
22
|
+
return definition;
|
|
23
|
+
}
|
|
24
|
+
function registerPageDefinition(registries, definition) {
|
|
25
|
+
const route = registries.currentLoadContext?.route;
|
|
26
|
+
if (!route) throw new Error("Cannot register Page() without an active page load context in headless runtime.");
|
|
27
|
+
if (registries.pages.has(route)) throw createDuplicateRegistrationError("page", route);
|
|
28
|
+
registries.pages.set(route, definition);
|
|
29
|
+
return definition;
|
|
30
|
+
}
|
|
31
|
+
function registerComponentDefinition(registries, definition) {
|
|
32
|
+
const id = registries.currentLoadContext?.route ?? `anonymous:${registries.components.size}`;
|
|
33
|
+
if (registries.components.has(id)) throw createDuplicateRegistrationError("component", id);
|
|
34
|
+
registries.components.set(id, definition);
|
|
35
|
+
return definition;
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/host/wx.ts
|
|
39
|
+
function invokeWxApi(operation, option) {
|
|
40
|
+
try {
|
|
41
|
+
const result = operation();
|
|
42
|
+
option?.success?.(result);
|
|
43
|
+
option?.complete?.(result);
|
|
44
|
+
return result;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
option?.fail?.(error);
|
|
47
|
+
option?.complete?.();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function createHeadlessWx(driver) {
|
|
52
|
+
return {
|
|
53
|
+
clearStorageSync: () => driver.clearStorageSync(),
|
|
54
|
+
getStorageSync: (key) => driver.getStorageSync(key),
|
|
55
|
+
hideToast: () => driver.hideToast(),
|
|
56
|
+
navigateBack: (option) => invokeWxApi(() => driver.navigateBack(option), option),
|
|
57
|
+
navigateTo: (option) => invokeWxApi(() => driver.navigateTo(option), option),
|
|
58
|
+
pageScrollTo: (option) => invokeWxApi(() => driver.pageScrollTo(option), option),
|
|
59
|
+
reLaunch: (option) => invokeWxApi(() => driver.reLaunch(option), option),
|
|
60
|
+
redirectTo: (option) => invokeWxApi(() => driver.redirectTo(option), option),
|
|
61
|
+
removeStorageSync: (key) => driver.removeStorageSync(key),
|
|
62
|
+
request: (option) => {
|
|
63
|
+
invokeWxApi(() => driver.request(option), option);
|
|
64
|
+
return { abort() {} };
|
|
65
|
+
},
|
|
66
|
+
setStorageSync: (key, value) => driver.setStorageSync(key, value),
|
|
67
|
+
showToast: (option) => invokeWxApi(() => driver.showToast(option), option),
|
|
68
|
+
stopPullDownRefresh: () => driver.stopPullDownRefresh(),
|
|
69
|
+
switchTab: (option) => invokeWxApi(() => driver.switchTab(option), option)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/browser/virtualFiles.ts
|
|
74
|
+
function normalizeBrowserFilePath(filePath) {
|
|
75
|
+
return normalize(filePath).replace(/^\/+/, "").replace(/^\.\//, "");
|
|
76
|
+
}
|
|
77
|
+
function createBrowserVirtualFiles(entries) {
|
|
78
|
+
const files = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const [filePath, content] of entries) files.set(normalizeBrowserFilePath(filePath), content);
|
|
80
|
+
return files;
|
|
81
|
+
}
|
|
82
|
+
async function createBrowserVirtualFilesFromDirectory(files) {
|
|
83
|
+
return createBrowserVirtualFiles(await Promise.all(files.map(async (file) => {
|
|
84
|
+
return [file.webkitRelativePath?.trim() || file.name, await file.text()];
|
|
85
|
+
})));
|
|
86
|
+
}
|
|
87
|
+
function readBrowserVirtualFile(files, filePath) {
|
|
88
|
+
return files.get(normalizeBrowserFilePath(filePath));
|
|
89
|
+
}
|
|
90
|
+
function hasBrowserVirtualFile(files, filePath) {
|
|
91
|
+
return files.has(normalizeBrowserFilePath(filePath));
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/browser/moduleLoader.ts
|
|
95
|
+
function createRequireNotFoundError$1(request, importer) {
|
|
96
|
+
return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
|
|
97
|
+
}
|
|
98
|
+
function resolveRequiredModulePath$1(files, importer, request) {
|
|
99
|
+
if (!request.startsWith(".")) throw createRequireNotFoundError$1(request, importer);
|
|
100
|
+
const basePath = normalize(join(dirname(importer), request));
|
|
101
|
+
const candidates = [
|
|
102
|
+
basePath,
|
|
103
|
+
`${basePath}.js`,
|
|
104
|
+
`${basePath}.json`,
|
|
105
|
+
join(basePath, "index.js")
|
|
106
|
+
];
|
|
107
|
+
for (const candidate of candidates) if (hasBrowserVirtualFile(files, candidate)) return candidate;
|
|
108
|
+
throw createRequireNotFoundError$1(request, importer);
|
|
109
|
+
}
|
|
110
|
+
function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver) {
|
|
111
|
+
const wx = createHeadlessWx(wxDriver);
|
|
112
|
+
return {
|
|
113
|
+
App(definition) {
|
|
114
|
+
return registerAppDefinition(registries, definition);
|
|
115
|
+
},
|
|
116
|
+
Behavior(definition) {
|
|
117
|
+
return {
|
|
118
|
+
...definition,
|
|
119
|
+
__isHeadlessBehavior__: true
|
|
120
|
+
};
|
|
121
|
+
},
|
|
122
|
+
Component(definition) {
|
|
123
|
+
return registerComponentDefinition(registries, definition);
|
|
124
|
+
},
|
|
125
|
+
Page(definition) {
|
|
126
|
+
return registerPageDefinition(registries, definition);
|
|
127
|
+
},
|
|
128
|
+
URLSearchParams,
|
|
129
|
+
clearInterval,
|
|
130
|
+
clearTimeout,
|
|
131
|
+
console,
|
|
132
|
+
getApp,
|
|
133
|
+
getCurrentPages,
|
|
134
|
+
globalThis: void 0,
|
|
135
|
+
require: void 0,
|
|
136
|
+
setInterval,
|
|
137
|
+
setTimeout,
|
|
138
|
+
wx
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver) {
|
|
142
|
+
const moduleCache = /* @__PURE__ */ new Map();
|
|
143
|
+
const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver);
|
|
144
|
+
executionContext.globalThis = executionContext;
|
|
145
|
+
function executeModule(filePath, loadContext) {
|
|
146
|
+
const resolvedPath = normalize(filePath);
|
|
147
|
+
const cached = moduleCache.get(resolvedPath);
|
|
148
|
+
if (cached) return cached.exports;
|
|
149
|
+
const source = readBrowserVirtualFile(files, resolvedPath);
|
|
150
|
+
if (typeof source !== "string") throw new Error(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
|
|
151
|
+
const module = { exports: {} };
|
|
152
|
+
moduleCache.set(resolvedPath, module);
|
|
153
|
+
const previousLoadContext = registries.currentLoadContext;
|
|
154
|
+
registries.currentLoadContext = loadContext;
|
|
155
|
+
const localRequire = (request) => {
|
|
156
|
+
const requiredPath = resolveRequiredModulePath$1(files, resolvedPath, request);
|
|
157
|
+
if (requiredPath.endsWith(".json")) {
|
|
158
|
+
const content = readBrowserVirtualFile(files, requiredPath);
|
|
159
|
+
if (typeof content !== "string") throw new Error(`Missing virtual json module in browser simulator runtime: ${requiredPath}`);
|
|
160
|
+
return JSON.parse(content);
|
|
161
|
+
}
|
|
162
|
+
return executeModule(requiredPath, null);
|
|
163
|
+
};
|
|
164
|
+
try {
|
|
165
|
+
const contextEntries = Object.entries(executionContext);
|
|
166
|
+
new Function(...contextEntries.map(([key]) => key), "exports", "module", "require", "__filename", "__dirname", source)(...contextEntries.map(([, value]) => value), module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
|
|
167
|
+
return module.exports;
|
|
168
|
+
} finally {
|
|
169
|
+
registries.currentLoadContext = previousLoadContext;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
executeAppModule(filePath) {
|
|
174
|
+
executeModule(filePath, { kind: "app" });
|
|
175
|
+
if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in browser simulator runtime.`);
|
|
176
|
+
return registries.appDefinition;
|
|
177
|
+
},
|
|
178
|
+
executePageModule(filePath, route) {
|
|
179
|
+
executeModule(filePath, {
|
|
180
|
+
kind: "page",
|
|
181
|
+
route
|
|
182
|
+
});
|
|
183
|
+
const definition = registries.pages.get(route);
|
|
184
|
+
if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
|
|
185
|
+
return definition;
|
|
186
|
+
},
|
|
187
|
+
executeComponentModule(filePath, id) {
|
|
188
|
+
executeModule(filePath, {
|
|
189
|
+
kind: "component",
|
|
190
|
+
route: id
|
|
191
|
+
});
|
|
192
|
+
const definition = registries.components.get(id);
|
|
193
|
+
if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
|
|
194
|
+
return definition;
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
//#endregion
|
|
7
199
|
//#region src/project/resolveRoutes.ts
|
|
8
|
-
const LEADING_SLASH_RE$
|
|
200
|
+
const LEADING_SLASH_RE$4 = /^\/+/;
|
|
9
201
|
const TRAILING_SLASH_RE = /\/+$/;
|
|
10
202
|
const DUPLICATE_SLASH_RE = /\/{2,}/g;
|
|
11
203
|
function normalizeSegment(value) {
|
|
12
|
-
return value.replace(LEADING_SLASH_RE$
|
|
204
|
+
return value.replace(LEADING_SLASH_RE$4, "").replace(TRAILING_SLASH_RE, "");
|
|
13
205
|
}
|
|
14
206
|
function pushRoute(records, seen, record) {
|
|
15
207
|
if (!record.route || seen.has(record.route)) return;
|
|
@@ -29,24 +221,1394 @@ function resolveRoutesFromAppConfig(config) {
|
|
|
29
221
|
source: "pages"
|
|
30
222
|
});
|
|
31
223
|
}
|
|
32
|
-
const subPackages = [...Array.isArray(config.subPackages) ? config.subPackages : [], ...Array.isArray(config.subpackages) ? config.subpackages : []];
|
|
33
|
-
for (const subPackage of subPackages) {
|
|
34
|
-
if (!subPackage || typeof subPackage !== "object") continue;
|
|
35
|
-
const root = typeof subPackage.root === "string" ? normalizeSegment(subPackage.root) : "";
|
|
36
|
-
const pages = Array.isArray(subPackage.pages) ? subPackage.pages : [];
|
|
37
|
-
for (const page of pages) {
|
|
38
|
-
if (typeof page !== "string") continue;
|
|
39
|
-
const normalizedPage = normalizeSegment(page);
|
|
40
|
-
if (!normalizedPage) continue;
|
|
41
|
-
pushRoute(records, seen, {
|
|
42
|
-
kind: "page",
|
|
43
|
-
route: root ? `${root}/${normalizedPage}`.replace(DUPLICATE_SLASH_RE, "/") : normalizedPage,
|
|
44
|
-
source: "subPackages",
|
|
45
|
-
subpackageRoot: root || void 0
|
|
46
|
-
});
|
|
224
|
+
const subPackages = [...Array.isArray(config.subPackages) ? config.subPackages : [], ...Array.isArray(config.subpackages) ? config.subpackages : []];
|
|
225
|
+
for (const subPackage of subPackages) {
|
|
226
|
+
if (!subPackage || typeof subPackage !== "object") continue;
|
|
227
|
+
const root = typeof subPackage.root === "string" ? normalizeSegment(subPackage.root) : "";
|
|
228
|
+
const pages = Array.isArray(subPackage.pages) ? subPackage.pages : [];
|
|
229
|
+
for (const page of pages) {
|
|
230
|
+
if (typeof page !== "string") continue;
|
|
231
|
+
const normalizedPage = normalizeSegment(page);
|
|
232
|
+
if (!normalizedPage) continue;
|
|
233
|
+
pushRoute(records, seen, {
|
|
234
|
+
kind: "page",
|
|
235
|
+
route: root ? `${root}/${normalizedPage}`.replace(DUPLICATE_SLASH_RE, "/") : normalizedPage,
|
|
236
|
+
source: "subPackages",
|
|
237
|
+
subpackageRoot: root || void 0
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return records;
|
|
242
|
+
}
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/project/createProjectDescriptor.ts
|
|
245
|
+
function createProjectDescriptor(options) {
|
|
246
|
+
return {
|
|
247
|
+
appConfig: options.appConfig,
|
|
248
|
+
appConfigPath: options.appConfigPath,
|
|
249
|
+
miniprogramRoot: options.miniprogramRoot,
|
|
250
|
+
miniprogramRootPath: options.miniprogramRootPath,
|
|
251
|
+
projectPath: options.projectPath,
|
|
252
|
+
projectConfigFiles: options.projectConfigFiles ?? [],
|
|
253
|
+
routes: resolveRoutesFromAppConfig(options.appConfig)
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/browser/project.ts
|
|
258
|
+
function readJsonObject$1(files, filePath) {
|
|
259
|
+
const content = readBrowserVirtualFile(files, filePath);
|
|
260
|
+
if (!content) return;
|
|
261
|
+
try {
|
|
262
|
+
const value = JSON.parse(content);
|
|
263
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
264
|
+
} catch {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function createBrowserProject(files, options = {}) {
|
|
269
|
+
const appConfigPath = options.appConfigPath ?? "app.json";
|
|
270
|
+
if (!hasBrowserVirtualFile(files, appConfigPath)) throw new Error(`Missing built app.json for browser simulator project: ${appConfigPath}`);
|
|
271
|
+
const appConfig = readJsonObject$1(files, appConfigPath);
|
|
272
|
+
if (!appConfig) throw new Error(`Failed to read built app.json for browser simulator project: ${appConfigPath}`);
|
|
273
|
+
return createProjectDescriptor({
|
|
274
|
+
appConfig,
|
|
275
|
+
appConfigPath,
|
|
276
|
+
miniprogramRoot: options.miniprogramRoot ?? ".",
|
|
277
|
+
miniprogramRootPath: options.miniprogramRootPath ?? "/",
|
|
278
|
+
projectPath: options.projectPath ?? "browser://simulator",
|
|
279
|
+
projectConfigFiles: []
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
//#endregion
|
|
283
|
+
//#region src/runtime/componentInstance.ts
|
|
284
|
+
function bindFunction$2(target, key, value) {
|
|
285
|
+
if (typeof value !== "function") {
|
|
286
|
+
target[key] = value;
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
target[key] = (...args) => value.apply(target, args);
|
|
290
|
+
}
|
|
291
|
+
function cloneObject$1(value) {
|
|
292
|
+
return JSON.parse(JSON.stringify(value));
|
|
293
|
+
}
|
|
294
|
+
function cloneValue(value) {
|
|
295
|
+
if (Array.isArray(value)) return JSON.parse(JSON.stringify(value));
|
|
296
|
+
if (value && typeof value === "object") return cloneObject$1(value);
|
|
297
|
+
return value;
|
|
298
|
+
}
|
|
299
|
+
function parseDataPath$1(path) {
|
|
300
|
+
return path.replace(/\[(\d+)\]/g, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
|
|
301
|
+
}
|
|
302
|
+
function isArrayIndexSegment$1(segment) {
|
|
303
|
+
return /^\d+$/.test(segment);
|
|
304
|
+
}
|
|
305
|
+
function createContainerByNextSegment$1(nextSegment) {
|
|
306
|
+
return isArrayIndexSegment$1(nextSegment ?? "") ? [] : {};
|
|
307
|
+
}
|
|
308
|
+
function assignByPath$1(target, path, value) {
|
|
309
|
+
const segments = parseDataPath$1(path);
|
|
310
|
+
if (segments.length === 0) return;
|
|
311
|
+
let current = target;
|
|
312
|
+
for (let index = 0; index < segments.length - 1; index += 1) {
|
|
313
|
+
const segment = segments[index];
|
|
314
|
+
const nextSegment = segments[index + 1];
|
|
315
|
+
const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
|
|
316
|
+
const next = current?.[normalizedSegment];
|
|
317
|
+
if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment$1(nextSegment);
|
|
318
|
+
current = current[normalizedSegment];
|
|
319
|
+
}
|
|
320
|
+
const leafSegment = segments[segments.length - 1];
|
|
321
|
+
const normalizedLeafSegment = isArrayIndexSegment$1(leafSegment) ? Number(leafSegment) : leafSegment;
|
|
322
|
+
current[normalizedLeafSegment] = value;
|
|
323
|
+
}
|
|
324
|
+
function resolveInitialData$2(definition) {
|
|
325
|
+
const rawData = definition.data;
|
|
326
|
+
if (typeof rawData === "function") {
|
|
327
|
+
const next = rawData.call(definition);
|
|
328
|
+
return next && typeof next === "object" && !Array.isArray(next) ? cloneObject$1(next) : {};
|
|
329
|
+
}
|
|
330
|
+
return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject$1(rawData) : {};
|
|
331
|
+
}
|
|
332
|
+
function isBehaviorDefinition(value) {
|
|
333
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && value.__isHeadlessBehavior__ === true;
|
|
334
|
+
}
|
|
335
|
+
function flattenBehaviors(definition) {
|
|
336
|
+
const flattened = [];
|
|
337
|
+
const queue = Array.isArray(definition.behaviors) ? definition.behaviors : [];
|
|
338
|
+
for (const item of queue) {
|
|
339
|
+
if (!isBehaviorDefinition(item)) continue;
|
|
340
|
+
flattened.push(...flattenBehaviors(item));
|
|
341
|
+
flattened.push(item);
|
|
342
|
+
}
|
|
343
|
+
return flattened;
|
|
344
|
+
}
|
|
345
|
+
function mergeRecord(...records) {
|
|
346
|
+
return Object.assign({}, ...records.filter(Boolean));
|
|
347
|
+
}
|
|
348
|
+
function normalizeComponentDefinition(definition) {
|
|
349
|
+
const behaviors = flattenBehaviors(definition);
|
|
350
|
+
if (behaviors.length === 0) return definition;
|
|
351
|
+
const mergedDataEntries = behaviors.map((item) => item.data).filter(Boolean);
|
|
352
|
+
const mergedDefinition = {
|
|
353
|
+
...mergeRecord(...behaviors, definition),
|
|
354
|
+
methods: mergeRecord(...behaviors.map((item) => item.methods), definition.methods),
|
|
355
|
+
observers: mergeRecord(...behaviors.map((item) => item.observers), definition.observers),
|
|
356
|
+
pageLifetimes: mergeRecord(...behaviors.map((item) => item.pageLifetimes), definition.pageLifetimes),
|
|
357
|
+
properties: mergeRecord(...behaviors.map((item) => item.properties), definition.properties),
|
|
358
|
+
lifetimes: mergeRecord(...behaviors.map((item) => item.lifetimes), definition.lifetimes)
|
|
359
|
+
};
|
|
360
|
+
if (mergedDataEntries.length > 0 || definition.data) mergedDefinition.data = function mergedComponentData() {
|
|
361
|
+
return mergeRecord(mergeRecord(...mergedDataEntries.map((entry) => {
|
|
362
|
+
if (typeof entry === "function") return entry.call(this);
|
|
363
|
+
return entry;
|
|
364
|
+
})), typeof definition.data === "function" ? definition.data.call(this) : definition.data);
|
|
365
|
+
};
|
|
366
|
+
return mergedDefinition;
|
|
367
|
+
}
|
|
368
|
+
function normalizePropertyType(option) {
|
|
369
|
+
if (option === null) return null;
|
|
370
|
+
if (option === String || option === Number || option === Boolean || option === Array || option === Object) return option;
|
|
371
|
+
if (!option || typeof option !== "object" || Array.isArray(option)) return;
|
|
372
|
+
return option.type;
|
|
373
|
+
}
|
|
374
|
+
function resolvePropertyTypeCandidates(option) {
|
|
375
|
+
const candidates = [];
|
|
376
|
+
const primaryType = normalizePropertyType(option);
|
|
377
|
+
if (primaryType) candidates.push(primaryType);
|
|
378
|
+
if (option && typeof option === "object" && !Array.isArray(option)) {
|
|
379
|
+
const optionalTypes = option.optionalTypes;
|
|
380
|
+
if (Array.isArray(optionalTypes)) candidates.push(...optionalTypes);
|
|
381
|
+
}
|
|
382
|
+
return candidates;
|
|
383
|
+
}
|
|
384
|
+
function resolveDefaultValueByType(type) {
|
|
385
|
+
if (type === Number) return 0;
|
|
386
|
+
if (type === Boolean) return false;
|
|
387
|
+
if (type === String) return "";
|
|
388
|
+
if (type === Array) return [];
|
|
389
|
+
if (type === Object) return {};
|
|
390
|
+
if (type === null) return null;
|
|
391
|
+
}
|
|
392
|
+
function matchesRuntimeType(rawValue, type) {
|
|
393
|
+
if (type === null) return true;
|
|
394
|
+
if (type === Number) return typeof rawValue === "number";
|
|
395
|
+
if (type === Boolean) return typeof rawValue === "boolean";
|
|
396
|
+
if (type === String) return typeof rawValue === "string";
|
|
397
|
+
if (type === Array) return Array.isArray(rawValue);
|
|
398
|
+
if (type === Object) return !!rawValue && typeof rawValue === "object" && !Array.isArray(rawValue);
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
function coerceComponentPropertyValue(rawValue, option) {
|
|
402
|
+
const candidates = resolvePropertyTypeCandidates(option);
|
|
403
|
+
const primaryType = candidates[0];
|
|
404
|
+
if (primaryType && matchesRuntimeType(rawValue, primaryType)) return rawValue;
|
|
405
|
+
const fallbackCandidates = primaryType ? candidates.slice(1) : candidates;
|
|
406
|
+
for (const type of fallbackCandidates) {
|
|
407
|
+
if (type === Number) {
|
|
408
|
+
const nextValue = typeof rawValue === "number" ? rawValue : Number(rawValue);
|
|
409
|
+
if (!Number.isNaN(nextValue)) return nextValue;
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
if (type === Boolean) {
|
|
413
|
+
if (typeof rawValue === "boolean") return rawValue;
|
|
414
|
+
if (rawValue === "" || rawValue === "true") return true;
|
|
415
|
+
if (rawValue === "false") return false;
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (type === String) return rawValue == null ? "" : String(rawValue);
|
|
419
|
+
if (type === Array && Array.isArray(rawValue)) return rawValue;
|
|
420
|
+
if (type === Object && rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) return rawValue;
|
|
421
|
+
if (type === null) return rawValue;
|
|
422
|
+
}
|
|
423
|
+
if (primaryType === Number) {
|
|
424
|
+
const nextValue = typeof rawValue === "number" ? rawValue : Number(rawValue);
|
|
425
|
+
return Number.isNaN(nextValue) ? rawValue : nextValue;
|
|
426
|
+
}
|
|
427
|
+
if (primaryType === Boolean) {
|
|
428
|
+
if (typeof rawValue === "boolean") return rawValue;
|
|
429
|
+
if (rawValue === "" || rawValue === "true") return true;
|
|
430
|
+
if (rawValue === "false") return false;
|
|
431
|
+
return Boolean(rawValue);
|
|
432
|
+
}
|
|
433
|
+
if (primaryType === String) return rawValue == null ? "" : String(rawValue);
|
|
434
|
+
return rawValue;
|
|
435
|
+
}
|
|
436
|
+
function resolveInitialProperties(definition, properties) {
|
|
437
|
+
const resolved = {};
|
|
438
|
+
const propOptions = definition.properties;
|
|
439
|
+
if (propOptions && typeof propOptions === "object" && !Array.isArray(propOptions)) for (const [key, option] of Object.entries(propOptions)) {
|
|
440
|
+
if (Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
441
|
+
resolved[key] = coerceComponentPropertyValue(properties[key], option);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) resolved[key] = cloneValue(typeof option.value === "function" ? option.value.call(definition) : option.value);
|
|
445
|
+
else resolved[key] = cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
|
|
446
|
+
}
|
|
447
|
+
for (const [key, value] of Object.entries(properties)) if (!(key in resolved)) resolved[key] = value;
|
|
448
|
+
return resolved;
|
|
449
|
+
}
|
|
450
|
+
function resolvePropertyDefaultValue(option) {
|
|
451
|
+
if (!option || typeof option !== "object" || Array.isArray(option) || !("value" in option)) return;
|
|
452
|
+
return cloneValue(option.value);
|
|
453
|
+
}
|
|
454
|
+
function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
|
|
455
|
+
const propOptions = definition.properties;
|
|
456
|
+
if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
|
|
457
|
+
for (const changedKey of changedKeys) {
|
|
458
|
+
const option = propOptions[changedKey];
|
|
459
|
+
if (!option || typeof option !== "object" || Array.isArray(option)) continue;
|
|
460
|
+
const observer = option.observer;
|
|
461
|
+
if (typeof observer !== "function") continue;
|
|
462
|
+
observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function normalizeObserverPattern(pattern) {
|
|
466
|
+
return pattern.split(",").map((item) => item.trim()).filter(Boolean);
|
|
467
|
+
}
|
|
468
|
+
function resolveObservedValue(instance, pattern) {
|
|
469
|
+
if (pattern === "**") return {
|
|
470
|
+
...instance.properties,
|
|
471
|
+
...instance.data
|
|
472
|
+
};
|
|
473
|
+
const segments = parseDataPath$1(pattern);
|
|
474
|
+
if (segments.length === 0) return;
|
|
475
|
+
const [rootSegment, ...restSegments] = segments;
|
|
476
|
+
let current = (Object.prototype.hasOwnProperty.call(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
|
|
477
|
+
for (const segment of restSegments) {
|
|
478
|
+
const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
|
|
479
|
+
current = current?.[normalizedSegment];
|
|
480
|
+
}
|
|
481
|
+
return current;
|
|
482
|
+
}
|
|
483
|
+
function matchObserverPattern(pattern, changedKeys) {
|
|
484
|
+
if (pattern === "**") return changedKeys.length > 0;
|
|
485
|
+
const patterns = normalizeObserverPattern(pattern);
|
|
486
|
+
return changedKeys.some((changedKey) => {
|
|
487
|
+
return patterns.some((item) => {
|
|
488
|
+
if (item === "**") return true;
|
|
489
|
+
if (changedKey === item) return true;
|
|
490
|
+
return changedKey.startsWith(`${item}.`) || changedKey.startsWith(`${item}[`);
|
|
491
|
+
});
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
|
|
495
|
+
if (changedKeys.length === 0) return;
|
|
496
|
+
runPropertyObservers(definition, instance, changedKeys, previousProperties);
|
|
497
|
+
const observers = definition.observers;
|
|
498
|
+
if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
|
|
499
|
+
if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
|
|
500
|
+
const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
|
|
501
|
+
handler.call(instance, ...args);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function normalizeComponentPropertyValue(definition, key, rawValue) {
|
|
505
|
+
const option = definition.properties?.[key];
|
|
506
|
+
if (rawValue == null) return resolvePropertyDefaultValue(option);
|
|
507
|
+
return coerceComponentPropertyValue(rawValue, option);
|
|
508
|
+
}
|
|
509
|
+
function createComponentInstance(options) {
|
|
510
|
+
const definition = normalizeComponentDefinition(options.definition);
|
|
511
|
+
const instance = {
|
|
512
|
+
__definition__: definition,
|
|
513
|
+
data: resolveInitialData$2(definition),
|
|
514
|
+
__propertySnapshots__: {},
|
|
515
|
+
properties: resolveInitialProperties(definition, options.properties ?? {}),
|
|
516
|
+
setData(patch, callback) {
|
|
517
|
+
const changedKeys = Object.keys(patch);
|
|
518
|
+
for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
|
|
519
|
+
runComponentObservers(definition, instance, changedKeys);
|
|
520
|
+
callback?.();
|
|
521
|
+
},
|
|
522
|
+
triggerEvent(eventName, detail, triggerOptions) {
|
|
523
|
+
options.triggerEvent?.(instance, eventName, detail, triggerOptions);
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
for (const [key, value] of Object.entries(definition)) {
|
|
527
|
+
if (key === "data" || key === "methods" || key === "properties" || key === "observers" || key === "lifetimes") continue;
|
|
528
|
+
bindFunction$2(instance, key, value);
|
|
529
|
+
}
|
|
530
|
+
for (const [key, value] of Object.entries(definition.methods ?? {})) bindFunction$2(instance, key, value);
|
|
531
|
+
return instance;
|
|
532
|
+
}
|
|
533
|
+
function runComponentLifecycle(instance, lifecycleName) {
|
|
534
|
+
const definition = instance.__definition__;
|
|
535
|
+
const fromLifetimes = definition?.lifetimes?.[lifecycleName];
|
|
536
|
+
if (typeof fromLifetimes === "function") {
|
|
537
|
+
fromLifetimes.call(instance);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
const topLevel = definition?.[lifecycleName];
|
|
541
|
+
if (typeof topLevel === "function") topLevel.call(instance);
|
|
542
|
+
}
|
|
543
|
+
function runComponentPageLifetime(instance, lifetimeName, payload) {
|
|
544
|
+
const handler = (instance.__definition__?.pageLifetimes)?.[lifetimeName];
|
|
545
|
+
if (typeof handler !== "function") return;
|
|
546
|
+
handler.call(instance, payload);
|
|
547
|
+
}
|
|
548
|
+
//#endregion
|
|
549
|
+
//#region src/browser/render.ts
|
|
550
|
+
const LEADING_SLASH_RE$3 = /^\/+/;
|
|
551
|
+
const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
|
|
552
|
+
const EVENT_BINDING_ATTRS = [
|
|
553
|
+
"bindtap",
|
|
554
|
+
"bind:tap",
|
|
555
|
+
"catchtap",
|
|
556
|
+
"catch:tap"
|
|
557
|
+
];
|
|
558
|
+
const COMPONENT_EVENT_PREFIXES = [
|
|
559
|
+
"bind:",
|
|
560
|
+
"bind",
|
|
561
|
+
"catch:",
|
|
562
|
+
"catch"
|
|
563
|
+
];
|
|
564
|
+
const STRUCTURAL_ATTRS = [
|
|
565
|
+
"wx:if",
|
|
566
|
+
"wx:elif",
|
|
567
|
+
"wx:else",
|
|
568
|
+
"wx:for",
|
|
569
|
+
"wx:for-item",
|
|
570
|
+
"wx:for-index",
|
|
571
|
+
"wx:key"
|
|
572
|
+
];
|
|
573
|
+
const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
|
|
574
|
+
const DATASET_NAME_RE = /-([a-z])/g;
|
|
575
|
+
const BRACKET_INDEX_RE = /\[(\d+)\]/g;
|
|
576
|
+
const CLASS_SPLIT_RE = /\s+/;
|
|
577
|
+
const JS_FILE_RE = /\.js$/;
|
|
578
|
+
function isMustacheOnly(value) {
|
|
579
|
+
const trimmed = value.trim();
|
|
580
|
+
return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
|
|
581
|
+
}
|
|
582
|
+
function toDatasetKey(attributeName) {
|
|
583
|
+
return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
|
|
584
|
+
}
|
|
585
|
+
function collectDataset(node) {
|
|
586
|
+
const dataset = {};
|
|
587
|
+
for (const [key, value] of Object.entries(node.attribs ?? {})) {
|
|
588
|
+
if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
|
|
589
|
+
dataset[toDatasetKey(key)] = String(value);
|
|
590
|
+
}
|
|
591
|
+
return dataset;
|
|
592
|
+
}
|
|
593
|
+
function escapeText$2(text) {
|
|
594
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
595
|
+
}
|
|
596
|
+
function escapeAttribute$2(value) {
|
|
597
|
+
return escapeText$2(value).replaceAll("\"", """);
|
|
598
|
+
}
|
|
599
|
+
function cloneNode(node) {
|
|
600
|
+
return {
|
|
601
|
+
...node,
|
|
602
|
+
attribs: node.attribs ? { ...node.attribs } : void 0,
|
|
603
|
+
children: node.children?.map((child) => cloneNode(child))
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function parseExpressionSegments(expression) {
|
|
607
|
+
return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
|
|
608
|
+
}
|
|
609
|
+
function unwrapMustacheExpression(expression) {
|
|
610
|
+
const normalized = expression.trim();
|
|
611
|
+
if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
|
|
612
|
+
return normalized;
|
|
613
|
+
}
|
|
614
|
+
function resolveLiteralValue(expression) {
|
|
615
|
+
if (expression === "true") return true;
|
|
616
|
+
if (expression === "false") return false;
|
|
617
|
+
if (expression === "null") return null;
|
|
618
|
+
if (expression === "undefined") return;
|
|
619
|
+
if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
|
|
620
|
+
const numericValue = Number(expression);
|
|
621
|
+
if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
|
|
622
|
+
}
|
|
623
|
+
function resolveValueByExpression(source, expression) {
|
|
624
|
+
const normalized = unwrapMustacheExpression(expression);
|
|
625
|
+
if (!normalized) return;
|
|
626
|
+
if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
|
|
627
|
+
const literalValue = resolveLiteralValue(normalized);
|
|
628
|
+
if (literalValue !== void 0 || normalized === "undefined") return literalValue;
|
|
629
|
+
const segments = parseExpressionSegments(normalized);
|
|
630
|
+
let current = source;
|
|
631
|
+
for (const segment of segments) current = current?.[segment];
|
|
632
|
+
return current;
|
|
633
|
+
}
|
|
634
|
+
function resolveValueByPath$1(source, expression) {
|
|
635
|
+
return resolveValueByExpression(source, expression) ?? "";
|
|
636
|
+
}
|
|
637
|
+
function resolveRawValueByPath(source, expression) {
|
|
638
|
+
return resolveValueByExpression(source, expression);
|
|
639
|
+
}
|
|
640
|
+
function interpolateTemplate$1(input, data) {
|
|
641
|
+
return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
|
|
642
|
+
const value = resolveValueByPath$1(data, expression);
|
|
643
|
+
return typeof value === "string" ? value : String(value);
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
function readTemplateSource(files, filePath) {
|
|
647
|
+
const templateSource = readBrowserVirtualFile(files, filePath);
|
|
648
|
+
if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
|
|
649
|
+
return templateSource;
|
|
650
|
+
}
|
|
651
|
+
function parseTemplateDocument(templateSource) {
|
|
652
|
+
return parseDocument(`<page>${templateSource}</page>`, {
|
|
653
|
+
xmlMode: false,
|
|
654
|
+
decodeEntities: false,
|
|
655
|
+
recognizeSelfClosing: true
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
function serializeDomNode$1(node) {
|
|
659
|
+
if (node.type === "text") return escapeText$2(node.data ?? "");
|
|
660
|
+
if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
|
|
661
|
+
const tagName = node.name ?? "";
|
|
662
|
+
if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
|
|
663
|
+
return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
|
|
664
|
+
}
|
|
665
|
+
function isTagNode(node) {
|
|
666
|
+
return node.type === "tag" && typeof node.name === "string";
|
|
667
|
+
}
|
|
668
|
+
function isIgnorableTextNode(node) {
|
|
669
|
+
return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
|
|
670
|
+
}
|
|
671
|
+
function resolveAttributeValue(value, scope) {
|
|
672
|
+
if (isMustacheOnly(value)) {
|
|
673
|
+
const expression = value.trim().slice(2, -2);
|
|
674
|
+
return resolveValueByPath$1(scope.data, expression);
|
|
675
|
+
}
|
|
676
|
+
return interpolateTemplate$1(value, scope.data);
|
|
677
|
+
}
|
|
678
|
+
function resolveComponentAttributeValue(value, scope) {
|
|
679
|
+
if (isMustacheOnly(value)) {
|
|
680
|
+
const expression = value.trim().slice(2, -2);
|
|
681
|
+
return resolveRawValueByPath(scope.data, expression);
|
|
682
|
+
}
|
|
683
|
+
return interpolateTemplate$1(value, scope.data);
|
|
684
|
+
}
|
|
685
|
+
function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
|
|
686
|
+
const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
|
|
687
|
+
if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
|
|
688
|
+
try {
|
|
689
|
+
const usingComponents = JSON.parse(ownerJson).usingComponents;
|
|
690
|
+
if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
|
|
691
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
692
|
+
for (const [alias, rawPath] of Object.entries(usingComponents)) {
|
|
693
|
+
if (typeof rawPath !== "string") continue;
|
|
694
|
+
const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$3, "") : normalize(join(dirname(ownerFilePath), rawPath));
|
|
695
|
+
resolved.set(alias, basePath.replace(LEADING_SLASH_RE$3, ""));
|
|
696
|
+
}
|
|
697
|
+
return resolved;
|
|
698
|
+
} catch {
|
|
699
|
+
return /* @__PURE__ */ new Map();
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
|
|
703
|
+
const componentBasePath = resolveUsingComponents(context.files, ownerJsonPath, ownerFilePath).get(alias);
|
|
704
|
+
if (!componentBasePath) return null;
|
|
705
|
+
const filePath = `${componentBasePath}.js`;
|
|
706
|
+
const templatePath = `${componentBasePath}.wxml`;
|
|
707
|
+
return {
|
|
708
|
+
definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
|
|
709
|
+
filePath,
|
|
710
|
+
templatePath
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
function collectComponentEventBindings(hostNode) {
|
|
714
|
+
const eventBindings = /* @__PURE__ */ new Map();
|
|
715
|
+
for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
|
|
716
|
+
const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
|
|
717
|
+
if (!matchedPrefix) continue;
|
|
718
|
+
const eventName = key.slice(matchedPrefix.length);
|
|
719
|
+
if (!eventName) continue;
|
|
720
|
+
eventBindings.set(eventName, {
|
|
721
|
+
method: value,
|
|
722
|
+
stopAfter: matchedPrefix.startsWith("catch")
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
return eventBindings;
|
|
726
|
+
}
|
|
727
|
+
function buildComponentTrigger(componentScopeId, context, hostNode) {
|
|
728
|
+
const hostDataset = collectDataset(hostNode);
|
|
729
|
+
const hostId = hostNode.attribs?.id ?? "";
|
|
730
|
+
return (instance, eventName, detail, triggerOptions) => {
|
|
731
|
+
const interactionTarget = instance.__lastInteractionEvent__?.target;
|
|
732
|
+
const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
|
|
733
|
+
const target = {
|
|
734
|
+
dataset: interactionTarget?.dataset ?? hostDataset,
|
|
735
|
+
id: interactionTarget?.id ?? hostId
|
|
736
|
+
};
|
|
737
|
+
let currentScopeId = componentScopeId;
|
|
738
|
+
while (currentScopeId) {
|
|
739
|
+
const currentScope = context.componentScopes.get(currentScopeId);
|
|
740
|
+
const binding = currentScope?.eventBindings?.get(eventName);
|
|
741
|
+
const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
|
|
742
|
+
const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
|
|
743
|
+
if (handler) handler({
|
|
744
|
+
bubbles: triggerOptions?.bubbles ?? false,
|
|
745
|
+
capturePhase: false,
|
|
746
|
+
composed: triggerOptions?.composed ?? false,
|
|
747
|
+
detail,
|
|
748
|
+
mark: void 0,
|
|
749
|
+
target,
|
|
750
|
+
type: eventName,
|
|
751
|
+
currentTarget: {
|
|
752
|
+
dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
|
|
753
|
+
id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
if (binding?.stopAfter) break;
|
|
757
|
+
if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
|
|
758
|
+
currentScopeId = currentScope?.ownerScopeId;
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
function applyNodeBindings(node, scope) {
|
|
763
|
+
if (!isTagNode(node)) {
|
|
764
|
+
if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$1(node.data, scope.data);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
node.attribs ??= {};
|
|
768
|
+
node.attribs["data-sim-scope"] = scope.getScopeId();
|
|
769
|
+
for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
|
|
770
|
+
for (const [key, value] of Object.entries({ ...node.attribs })) {
|
|
771
|
+
if (EVENT_BINDING_ATTRS.includes(key)) {
|
|
772
|
+
node.attribs["data-sim-tap"] = value;
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
|
|
779
|
+
const changedRootKeys = [];
|
|
780
|
+
const previousProperties = {};
|
|
781
|
+
for (const [key, value] of Object.entries(nextProperties)) {
|
|
782
|
+
const nextValue = normalizeComponentPropertyValue(definition, key, value);
|
|
783
|
+
const bindingExpression = bindingExpressions[key];
|
|
784
|
+
const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
|
|
785
|
+
return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
|
|
786
|
+
});
|
|
787
|
+
const previousSnapshot = instance.__propertySnapshots?.[key];
|
|
788
|
+
const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
|
|
789
|
+
if (instance.properties[key] !== nextValue || deepChanged) {
|
|
790
|
+
previousProperties[key] = instance.properties[key];
|
|
791
|
+
instance.properties[key] = nextValue;
|
|
792
|
+
changedRootKeys.push(key);
|
|
793
|
+
}
|
|
794
|
+
instance.__propertySnapshots ??= {};
|
|
795
|
+
instance.__propertySnapshots[key] = cloneValue(nextValue);
|
|
796
|
+
}
|
|
797
|
+
if (changedRootKeys.length === 0) return;
|
|
798
|
+
runComponentObservers(definition, instance, changedRootKeys, previousProperties);
|
|
799
|
+
}
|
|
800
|
+
function createMergedScopeData(pageData, componentProperties, componentData) {
|
|
801
|
+
return {
|
|
802
|
+
...pageData,
|
|
803
|
+
...componentProperties,
|
|
804
|
+
...componentData
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
function isTruthy(value) {
|
|
808
|
+
return Boolean(value);
|
|
809
|
+
}
|
|
810
|
+
function createLoopScope(scope, itemName, indexName, item, index) {
|
|
811
|
+
return {
|
|
812
|
+
...scope,
|
|
813
|
+
data: {
|
|
814
|
+
...scope.data,
|
|
815
|
+
[indexName]: index,
|
|
816
|
+
[itemName]: item
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
function evaluateConditionalBranch(node, scope) {
|
|
821
|
+
const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
|
|
822
|
+
if (condition == null) return true;
|
|
823
|
+
return isTruthy(resolveRawValueByPath(scope.data, condition));
|
|
824
|
+
}
|
|
825
|
+
function expandNodeByFor(node, scope) {
|
|
826
|
+
const forExpression = node.attribs?.["wx:for"];
|
|
827
|
+
if (!forExpression) return [{
|
|
828
|
+
node,
|
|
829
|
+
scope,
|
|
830
|
+
instanceSuffix: ""
|
|
831
|
+
}];
|
|
832
|
+
const list = resolveRawValueByPath(scope.data, forExpression);
|
|
833
|
+
const items = Array.isArray(list) ? list : [];
|
|
834
|
+
const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
|
|
835
|
+
const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
|
|
836
|
+
return items.map((item, index) => ({
|
|
837
|
+
node: cloneNode(node),
|
|
838
|
+
scope: createLoopScope(scope, itemName, indexName, item, index),
|
|
839
|
+
instanceSuffix: `:for-${index}`
|
|
840
|
+
}));
|
|
841
|
+
}
|
|
842
|
+
function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
|
|
843
|
+
return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
|
|
844
|
+
}
|
|
845
|
+
function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
|
|
846
|
+
const renderedChildren = [];
|
|
847
|
+
for (let index = 0; index < children.length; index += 1) {
|
|
848
|
+
const child = children[index];
|
|
849
|
+
if (!isTagNode(child)) {
|
|
850
|
+
renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
853
|
+
const hasConditional = child.attribs?.["wx:if"] != null;
|
|
854
|
+
const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
|
|
855
|
+
if (hasConditional) {
|
|
856
|
+
let branchMatched = false;
|
|
857
|
+
let cursor = index;
|
|
858
|
+
while (cursor < children.length) {
|
|
859
|
+
const branch = children[cursor];
|
|
860
|
+
if (cursor !== index && isIgnorableTextNode(branch)) {
|
|
861
|
+
cursor += 1;
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
if (!isTagNode(branch)) break;
|
|
865
|
+
if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
|
|
866
|
+
if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
|
|
867
|
+
renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
|
|
868
|
+
branchMatched = true;
|
|
869
|
+
}
|
|
870
|
+
let nextBranchIndex = cursor + 1;
|
|
871
|
+
while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
|
|
872
|
+
const nextBranch = children[nextBranchIndex];
|
|
873
|
+
if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
|
|
874
|
+
cursor = nextBranchIndex;
|
|
875
|
+
}
|
|
876
|
+
index = cursor;
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
if (isElseBranch) continue;
|
|
880
|
+
renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
|
|
881
|
+
}
|
|
882
|
+
return renderedChildren;
|
|
883
|
+
}
|
|
884
|
+
function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
|
|
885
|
+
const clonedNode = cloneNode(node);
|
|
886
|
+
if (!isTagNode(clonedNode)) {
|
|
887
|
+
applyNodeBindings(clonedNode, scope);
|
|
888
|
+
return clonedNode;
|
|
889
|
+
}
|
|
890
|
+
const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
|
|
891
|
+
if (componentEntry) {
|
|
892
|
+
const componentScopeId = `${instancePath}/${clonedNode.name}`;
|
|
893
|
+
const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
|
|
894
|
+
const nextProperties = {};
|
|
895
|
+
const bindingExpressions = {};
|
|
896
|
+
for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
|
|
897
|
+
if (key.startsWith("bind")) continue;
|
|
898
|
+
if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
|
|
899
|
+
nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
|
|
900
|
+
}
|
|
901
|
+
let componentInstance = context.componentCache.get(componentScopeId);
|
|
902
|
+
if (!componentInstance) {
|
|
903
|
+
componentInstance = createComponentInstance({
|
|
904
|
+
definition: componentEntry.definition,
|
|
905
|
+
properties: nextProperties,
|
|
906
|
+
triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
|
|
907
|
+
});
|
|
908
|
+
componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
|
|
909
|
+
componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
|
|
910
|
+
componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
|
|
911
|
+
runComponentLifecycle(componentInstance, "created");
|
|
912
|
+
runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
|
|
913
|
+
componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
|
|
914
|
+
runComponentLifecycle(componentInstance, "attached");
|
|
915
|
+
runComponentPageLifetime(componentInstance, "show");
|
|
916
|
+
context.componentCache.set(componentScopeId, componentInstance);
|
|
917
|
+
} else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
|
|
918
|
+
seenComponentScopes.add(componentScopeId);
|
|
919
|
+
const componentScope = {
|
|
920
|
+
alias: clonedNode.name,
|
|
921
|
+
classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
|
|
922
|
+
data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
|
|
923
|
+
dataset: collectDataset(clonedNode),
|
|
924
|
+
eventBindings: collectComponentEventBindings(clonedNode),
|
|
925
|
+
getMethod: (methodName) => {
|
|
926
|
+
const method = componentInstance?.[methodName];
|
|
927
|
+
return typeof method === "function" ? method : void 0;
|
|
928
|
+
},
|
|
929
|
+
getScopeId: () => componentScopeId,
|
|
930
|
+
hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
|
|
931
|
+
id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
|
|
932
|
+
listenerScopeId: scope.getScopeId(),
|
|
933
|
+
ownerScopeId
|
|
934
|
+
};
|
|
935
|
+
context.componentScopes.set(componentScopeId, componentScope);
|
|
936
|
+
const componentDocument = parseTemplateDocument(readTemplateSource(context.files, componentEntry.templatePath));
|
|
937
|
+
const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
|
|
938
|
+
if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
|
|
939
|
+
if (!componentInstance.__ready__) {
|
|
940
|
+
runComponentLifecycle(componentInstance, "ready");
|
|
941
|
+
componentInstance.__ready__ = true;
|
|
942
|
+
}
|
|
943
|
+
return renderedComponentRoot;
|
|
944
|
+
}
|
|
945
|
+
applyNodeBindings(clonedNode, scope);
|
|
946
|
+
clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
|
|
947
|
+
return clonedNode;
|
|
948
|
+
}
|
|
949
|
+
function renderBrowserPageTree(context, page) {
|
|
950
|
+
const route = page.route.replace(LEADING_SLASH_RE$3, "");
|
|
951
|
+
const templatePath = join(context.project.miniprogramRootPath, `${route}.wxml`);
|
|
952
|
+
const document = parseTemplateDocument(readTemplateSource(context.files, templatePath));
|
|
953
|
+
const pageScopeId = `page:${route}`;
|
|
954
|
+
const pageScope = {
|
|
955
|
+
data: page.data,
|
|
956
|
+
getMethod: (methodName) => {
|
|
957
|
+
const method = page[methodName];
|
|
958
|
+
return typeof method === "function" ? method : void 0;
|
|
959
|
+
},
|
|
960
|
+
getScopeId: () => pageScopeId,
|
|
961
|
+
id: "page-root"
|
|
962
|
+
};
|
|
963
|
+
context.componentScopes.clear();
|
|
964
|
+
context.componentScopes.set(pageScopeId, pageScope);
|
|
965
|
+
const seenComponentScopes = /* @__PURE__ */ new Set();
|
|
966
|
+
const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
|
|
967
|
+
for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
|
|
968
|
+
runComponentLifecycle(instance, "detached");
|
|
969
|
+
context.componentCache.delete(scopeId);
|
|
970
|
+
context.componentScopes.delete(scopeId);
|
|
971
|
+
}
|
|
972
|
+
return {
|
|
973
|
+
root: renderedRoot,
|
|
974
|
+
wxml: serializeDomNode$1(renderedRoot)
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
//#endregion
|
|
978
|
+
//#region src/runtime/appInstance.ts
|
|
979
|
+
function bindFunction$1(target, key, value) {
|
|
980
|
+
if (typeof value !== "function") {
|
|
981
|
+
target[key] = value;
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
target[key] = (...args) => value.apply(target, args);
|
|
985
|
+
}
|
|
986
|
+
function resolveInitialData$1(definition) {
|
|
987
|
+
const rawData = definition.globalData ?? definition.data;
|
|
988
|
+
if (typeof rawData === "function") {
|
|
989
|
+
const next = rawData.call(definition);
|
|
990
|
+
return next && typeof next === "object" && !Array.isArray(next) ? { ...next } : {};
|
|
991
|
+
}
|
|
992
|
+
return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? { ...rawData } : {};
|
|
993
|
+
}
|
|
994
|
+
function createAppInstance(definition) {
|
|
995
|
+
const instance = { globalData: resolveInitialData$1(definition) };
|
|
996
|
+
for (const [key, value] of Object.entries(definition)) {
|
|
997
|
+
if (key === "data") continue;
|
|
998
|
+
bindFunction$1(instance, key, value);
|
|
999
|
+
}
|
|
1000
|
+
return instance;
|
|
1001
|
+
}
|
|
1002
|
+
//#endregion
|
|
1003
|
+
//#region src/runtime/pageInstance.ts
|
|
1004
|
+
function bindFunction(target, key, value) {
|
|
1005
|
+
if (typeof value !== "function") {
|
|
1006
|
+
target[key] = value;
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
target[key] = (...args) => value.apply(target, args);
|
|
1010
|
+
}
|
|
1011
|
+
function cloneObject(value) {
|
|
1012
|
+
return JSON.parse(JSON.stringify(value));
|
|
1013
|
+
}
|
|
1014
|
+
function resolveInitialData(definition) {
|
|
1015
|
+
const rawData = definition.data;
|
|
1016
|
+
if (typeof rawData === "function") {
|
|
1017
|
+
const next = rawData.call(definition);
|
|
1018
|
+
return next && typeof next === "object" && !Array.isArray(next) ? cloneObject(next) : {};
|
|
1019
|
+
}
|
|
1020
|
+
return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject(rawData) : {};
|
|
1021
|
+
}
|
|
1022
|
+
function parseDataPath(path) {
|
|
1023
|
+
return path.replace(/\[(\d+)\]/g, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
|
|
1024
|
+
}
|
|
1025
|
+
function isArrayIndexSegment(segment) {
|
|
1026
|
+
return /^\d+$/.test(segment);
|
|
1027
|
+
}
|
|
1028
|
+
function createContainerByNextSegment(nextSegment) {
|
|
1029
|
+
return isArrayIndexSegment(nextSegment ?? "") ? [] : {};
|
|
1030
|
+
}
|
|
1031
|
+
function assignByPath(target, path, value) {
|
|
1032
|
+
const segments = parseDataPath(path);
|
|
1033
|
+
if (segments.length === 0) return;
|
|
1034
|
+
let current = target;
|
|
1035
|
+
for (let index = 0; index < segments.length - 1; index += 1) {
|
|
1036
|
+
const segment = segments[index];
|
|
1037
|
+
const nextSegment = segments[index + 1];
|
|
1038
|
+
const normalizedSegment = isArrayIndexSegment(segment) ? Number(segment) : segment;
|
|
1039
|
+
const next = current?.[normalizedSegment];
|
|
1040
|
+
if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment(nextSegment);
|
|
1041
|
+
current = current[normalizedSegment];
|
|
1042
|
+
}
|
|
1043
|
+
const leafSegment = segments[segments.length - 1];
|
|
1044
|
+
const normalizedLeafSegment = isArrayIndexSegment(leafSegment) ? Number(leafSegment) : leafSegment;
|
|
1045
|
+
current[normalizedLeafSegment] = value;
|
|
1046
|
+
}
|
|
1047
|
+
function normalizeRoute(route) {
|
|
1048
|
+
return route.replace(/^\/+/, "");
|
|
1049
|
+
}
|
|
1050
|
+
function createPageInstance(route, definition, options = {}) {
|
|
1051
|
+
const normalizedRoute = normalizeRoute(route);
|
|
1052
|
+
const instance = {
|
|
1053
|
+
__route__: normalizedRoute,
|
|
1054
|
+
data: resolveInitialData(definition),
|
|
1055
|
+
options: { ...options },
|
|
1056
|
+
route: normalizedRoute,
|
|
1057
|
+
setData(patch, callback) {
|
|
1058
|
+
instance.__lastChangedKeys__ = Object.keys(patch);
|
|
1059
|
+
for (const [key, value] of Object.entries(patch)) assignByPath(instance.data, key, value);
|
|
1060
|
+
callback?.();
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
for (const [key, value] of Object.entries(definition)) {
|
|
1064
|
+
if (key === "data") continue;
|
|
1065
|
+
bindFunction(instance, key, value);
|
|
1066
|
+
}
|
|
1067
|
+
return instance;
|
|
1068
|
+
}
|
|
1069
|
+
//#endregion
|
|
1070
|
+
//#region src/runtime/wxState.ts
|
|
1071
|
+
function cloneValue$1(value) {
|
|
1072
|
+
if (value == null || typeof value !== "object") return value;
|
|
1073
|
+
return JSON.parse(JSON.stringify(value));
|
|
1074
|
+
}
|
|
1075
|
+
function normalizeMethod(method) {
|
|
1076
|
+
return (method || "GET").trim().toUpperCase();
|
|
1077
|
+
}
|
|
1078
|
+
function isRequestSuccessResult(value) {
|
|
1079
|
+
return !!value && typeof value === "object" && "data" in value;
|
|
1080
|
+
}
|
|
1081
|
+
function matchesRequestMock(mock, option) {
|
|
1082
|
+
const requestMethod = normalizeMethod(option.method);
|
|
1083
|
+
const mockMethod = normalizeMethod(mock.method);
|
|
1084
|
+
if (mock.method && requestMethod !== mockMethod) return false;
|
|
1085
|
+
if (typeof mock.url === "string") return mock.url === option.url;
|
|
1086
|
+
mock.url.lastIndex = 0;
|
|
1087
|
+
return mock.url.test(option.url);
|
|
1088
|
+
}
|
|
1089
|
+
function resolveRequestResponse(mock, option) {
|
|
1090
|
+
const rawResponse = typeof mock.response === "function" ? mock.response(option) : mock.response;
|
|
1091
|
+
if (isRequestSuccessResult(rawResponse)) return {
|
|
1092
|
+
cookies: Array.isArray(rawResponse.cookies) ? [...rawResponse.cookies] : [],
|
|
1093
|
+
data: cloneValue$1(rawResponse.data),
|
|
1094
|
+
errMsg: rawResponse.errMsg ?? "request:ok",
|
|
1095
|
+
header: { ...rawResponse.header },
|
|
1096
|
+
statusCode: rawResponse.statusCode ?? mock.statusCode ?? 200
|
|
1097
|
+
};
|
|
1098
|
+
return {
|
|
1099
|
+
cookies: [],
|
|
1100
|
+
data: cloneValue$1(rawResponse),
|
|
1101
|
+
errMsg: "request:ok",
|
|
1102
|
+
header: { ...mock.header ?? {} },
|
|
1103
|
+
statusCode: mock.statusCode ?? 200
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
function createHeadlessWxState() {
|
|
1107
|
+
const requestLogs = [];
|
|
1108
|
+
const requestMocks = [];
|
|
1109
|
+
const storage = /* @__PURE__ */ new Map();
|
|
1110
|
+
let toast = null;
|
|
1111
|
+
return {
|
|
1112
|
+
clearStorageSync() {
|
|
1113
|
+
storage.clear();
|
|
1114
|
+
},
|
|
1115
|
+
getRequestLogs() {
|
|
1116
|
+
return requestLogs.map((entry) => ({
|
|
1117
|
+
...entry,
|
|
1118
|
+
data: cloneValue$1(entry.data),
|
|
1119
|
+
header: { ...entry.header },
|
|
1120
|
+
response: entry.response ? {
|
|
1121
|
+
...entry.response,
|
|
1122
|
+
cookies: [...entry.response.cookies],
|
|
1123
|
+
data: cloneValue$1(entry.response.data),
|
|
1124
|
+
header: { ...entry.response.header }
|
|
1125
|
+
} : void 0
|
|
1126
|
+
}));
|
|
1127
|
+
},
|
|
1128
|
+
getStorageSnapshot() {
|
|
1129
|
+
return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
|
|
1130
|
+
},
|
|
1131
|
+
getStorageSync(key) {
|
|
1132
|
+
return cloneValue$1(storage.get(key));
|
|
1133
|
+
},
|
|
1134
|
+
getToast() {
|
|
1135
|
+
return toast ? { ...toast } : null;
|
|
1136
|
+
},
|
|
1137
|
+
hideToast() {
|
|
1138
|
+
toast = null;
|
|
1139
|
+
return { errMsg: "hideToast:ok" };
|
|
1140
|
+
},
|
|
1141
|
+
mockRequest(definition) {
|
|
1142
|
+
requestMocks.push({
|
|
1143
|
+
...definition,
|
|
1144
|
+
header: definition.header ? { ...definition.header } : void 0
|
|
1145
|
+
});
|
|
1146
|
+
},
|
|
1147
|
+
removeStorageSync(key) {
|
|
1148
|
+
storage.delete(key);
|
|
1149
|
+
},
|
|
1150
|
+
request(option) {
|
|
1151
|
+
const matchedMock = requestMocks.find((mock) => matchesRequestMock(mock, option));
|
|
1152
|
+
if (!matchedMock) {
|
|
1153
|
+
const logEntry = {
|
|
1154
|
+
data: cloneValue$1(option.data),
|
|
1155
|
+
header: { ...option.header ?? {} },
|
|
1156
|
+
matched: false,
|
|
1157
|
+
method: normalizeMethod(option.method),
|
|
1158
|
+
url: option.url
|
|
1159
|
+
};
|
|
1160
|
+
requestLogs.push(logEntry);
|
|
1161
|
+
throw new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
|
|
1162
|
+
}
|
|
1163
|
+
const response = resolveRequestResponse(matchedMock, option);
|
|
1164
|
+
requestLogs.push({
|
|
1165
|
+
data: cloneValue$1(option.data),
|
|
1166
|
+
header: { ...option.header ?? {} },
|
|
1167
|
+
matched: true,
|
|
1168
|
+
method: normalizeMethod(option.method),
|
|
1169
|
+
response,
|
|
1170
|
+
url: option.url
|
|
1171
|
+
});
|
|
1172
|
+
return response;
|
|
1173
|
+
},
|
|
1174
|
+
setStorageSync(key, value) {
|
|
1175
|
+
storage.set(key, cloneValue$1(value));
|
|
1176
|
+
},
|
|
1177
|
+
showToast(option) {
|
|
1178
|
+
toast = {
|
|
1179
|
+
duration: Number(option.duration ?? 1500),
|
|
1180
|
+
icon: option.icon ?? "success",
|
|
1181
|
+
mask: Boolean(option.mask),
|
|
1182
|
+
title: option.title
|
|
1183
|
+
};
|
|
1184
|
+
return { errMsg: "showToast:ok" };
|
|
1185
|
+
}
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
//#endregion
|
|
1189
|
+
//#region src/browser/session.ts
|
|
1190
|
+
const LEADING_SLASH_RE$2 = /^\/+/;
|
|
1191
|
+
const PAGE_STACK_LIMIT$1 = 10;
|
|
1192
|
+
const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
|
|
1193
|
+
const DATASET_KEY_RE = /-([a-z])/g;
|
|
1194
|
+
function stripLeadingSlash$1(route) {
|
|
1195
|
+
return route.replace(LEADING_SLASH_RE$2, "");
|
|
1196
|
+
}
|
|
1197
|
+
function normalizeQuery$1(queryString) {
|
|
1198
|
+
const query = new URLSearchParams(queryString);
|
|
1199
|
+
const result = {};
|
|
1200
|
+
for (const [key, value] of query.entries()) result[key] = value;
|
|
1201
|
+
return result;
|
|
1202
|
+
}
|
|
1203
|
+
function parseNavigationUrl$1(url) {
|
|
1204
|
+
const trimmedUrl = url.trim();
|
|
1205
|
+
if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
|
|
1206
|
+
const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
|
|
1207
|
+
const [pathname] = pathWithHash.split("#");
|
|
1208
|
+
return {
|
|
1209
|
+
pathname: pathname || "",
|
|
1210
|
+
query: normalizeQuery$1(queryString)
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
function createAppLaunchOptions$1(pathname, query) {
|
|
1214
|
+
return {
|
|
1215
|
+
path: stripLeadingSlash$1(pathname),
|
|
1216
|
+
query: { ...query },
|
|
1217
|
+
referrerInfo: {
|
|
1218
|
+
appId: "",
|
|
1219
|
+
extraData: {}
|
|
1220
|
+
},
|
|
1221
|
+
scene: 1001
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
function resolveNavigationPath$1(targetPath, baseRoute) {
|
|
1225
|
+
if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
|
|
1226
|
+
if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$2, "");
|
|
1227
|
+
if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
|
|
1228
|
+
return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$2, "");
|
|
1229
|
+
}
|
|
1230
|
+
var BrowserHeadlessSession = class {
|
|
1231
|
+
files;
|
|
1232
|
+
project;
|
|
1233
|
+
appDefinition = null;
|
|
1234
|
+
appInstance = null;
|
|
1235
|
+
moduleLoader;
|
|
1236
|
+
registries;
|
|
1237
|
+
currentPageInstance = null;
|
|
1238
|
+
pages = [];
|
|
1239
|
+
componentCache = /* @__PURE__ */ new Map();
|
|
1240
|
+
componentScopes = /* @__PURE__ */ new Map();
|
|
1241
|
+
tabBarRoutes;
|
|
1242
|
+
tabPages = /* @__PURE__ */ new Map();
|
|
1243
|
+
tabBarItems = /* @__PURE__ */ new Map();
|
|
1244
|
+
wxState = createHeadlessWxState();
|
|
1245
|
+
constructor(options) {
|
|
1246
|
+
this.files = options.files;
|
|
1247
|
+
this.project = options.project ?? createBrowserProject(options.files);
|
|
1248
|
+
this.registries = createHostRegistries();
|
|
1249
|
+
const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
|
|
1250
|
+
this.tabBarRoutes = /* @__PURE__ */ new Set();
|
|
1251
|
+
rawTabBarList.forEach((item, index) => {
|
|
1252
|
+
if (typeof item?.pagePath !== "string") return;
|
|
1253
|
+
const pagePath = stripLeadingSlash$1(item.pagePath);
|
|
1254
|
+
if (!pagePath) return;
|
|
1255
|
+
this.tabBarRoutes.add(pagePath);
|
|
1256
|
+
this.tabBarItems.set(pagePath, {
|
|
1257
|
+
index,
|
|
1258
|
+
pagePath,
|
|
1259
|
+
text: typeof item.text === "string" ? item.text : void 0
|
|
1260
|
+
});
|
|
1261
|
+
});
|
|
1262
|
+
this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
|
|
1263
|
+
navigateBack: (option) => this.navigateBack(option?.delta),
|
|
1264
|
+
navigateTo: (option) => this.navigateTo(option.url),
|
|
1265
|
+
pageScrollTo: (option) => this.pageScrollTo(option),
|
|
1266
|
+
clearStorageSync: () => this.wxState.clearStorageSync(),
|
|
1267
|
+
getStorageSync: (key) => this.wxState.getStorageSync(key),
|
|
1268
|
+
hideToast: () => this.wxState.hideToast(),
|
|
1269
|
+
reLaunch: (option) => this.reLaunch(option.url),
|
|
1270
|
+
redirectTo: (option) => this.redirectTo(option.url),
|
|
1271
|
+
removeStorageSync: (key) => this.wxState.removeStorageSync(key),
|
|
1272
|
+
request: (option) => this.wxState.request(option),
|
|
1273
|
+
setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
|
|
1274
|
+
showToast: (option) => this.wxState.showToast(option),
|
|
1275
|
+
stopPullDownRefresh: () => this.stopPullDownRefresh(),
|
|
1276
|
+
switchTab: (option) => this.switchTab(option.url)
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
getApp() {
|
|
1280
|
+
return this.appInstance;
|
|
1281
|
+
}
|
|
1282
|
+
getCurrentPages() {
|
|
1283
|
+
return this.pages.slice();
|
|
1284
|
+
}
|
|
1285
|
+
getRequestLogs() {
|
|
1286
|
+
return this.wxState.getRequestLogs();
|
|
1287
|
+
}
|
|
1288
|
+
getStorageSnapshot() {
|
|
1289
|
+
return this.wxState.getStorageSnapshot();
|
|
1290
|
+
}
|
|
1291
|
+
getToast() {
|
|
1292
|
+
return this.wxState.getToast();
|
|
1293
|
+
}
|
|
1294
|
+
mockRequest(definition) {
|
|
1295
|
+
this.wxState.mockRequest(definition);
|
|
1296
|
+
}
|
|
1297
|
+
getScopeSnapshot(scopeId) {
|
|
1298
|
+
const scope = this.componentScopes.get(scopeId);
|
|
1299
|
+
if (!scope) return null;
|
|
1300
|
+
const instance = this.componentCache.get(scopeId);
|
|
1301
|
+
if (instance) return {
|
|
1302
|
+
data: instance.data ?? {},
|
|
1303
|
+
methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
|
|
1304
|
+
properties: instance.properties ?? {},
|
|
1305
|
+
scopeId,
|
|
1306
|
+
type: "component"
|
|
1307
|
+
};
|
|
1308
|
+
const currentPage = this.currentPageInstance;
|
|
1309
|
+
if (currentPage && scopeId === `page:${currentPage.route}`) return {
|
|
1310
|
+
data: currentPage.data ?? {},
|
|
1311
|
+
methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
|
|
1312
|
+
properties: currentPage.options ?? {},
|
|
1313
|
+
scopeId,
|
|
1314
|
+
type: "page"
|
|
1315
|
+
};
|
|
1316
|
+
return {
|
|
1317
|
+
data: scope.data ?? {},
|
|
1318
|
+
methods: [],
|
|
1319
|
+
properties: {},
|
|
1320
|
+
scopeId,
|
|
1321
|
+
type: "scope"
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
selectComponent(selector) {
|
|
1325
|
+
return this.selectComponentsWithin(null, selector)[0] ?? null;
|
|
1326
|
+
}
|
|
1327
|
+
selectAllComponents(selector) {
|
|
1328
|
+
return this.selectComponentsWithin(null, selector);
|
|
1329
|
+
}
|
|
1330
|
+
selectComponentWithin(scopeId, selector) {
|
|
1331
|
+
return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
|
|
1332
|
+
}
|
|
1333
|
+
selectAllComponentsWithin(scopeId, selector) {
|
|
1334
|
+
return this.selectComponentsWithin(scopeId, selector);
|
|
1335
|
+
}
|
|
1336
|
+
selectOwnerComponent(scopeId) {
|
|
1337
|
+
const scope = this.componentScopes.get(scopeId);
|
|
1338
|
+
if (!scope?.ownerScopeId) return null;
|
|
1339
|
+
return this.componentCache.get(scope.ownerScopeId) ?? null;
|
|
1340
|
+
}
|
|
1341
|
+
selectComponentsWithin(rootScopeId, selector) {
|
|
1342
|
+
const normalizedSelector = selector.trim();
|
|
1343
|
+
if (!normalizedSelector) return [];
|
|
1344
|
+
return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
|
|
1345
|
+
if (!candidateScopeId.includes("/")) return false;
|
|
1346
|
+
if (rootScopeId && candidateScopeId === rootScopeId) return false;
|
|
1347
|
+
if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
|
|
1348
|
+
if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
|
|
1349
|
+
if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
|
|
1350
|
+
const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
|
|
1351
|
+
if (dataAttrMatch) {
|
|
1352
|
+
const [, key, value] = dataAttrMatch;
|
|
1353
|
+
const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
|
|
1354
|
+
return scope.dataset?.[datasetKey] === value;
|
|
1355
|
+
}
|
|
1356
|
+
return scope.alias === normalizedSelector;
|
|
1357
|
+
}).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
|
|
1358
|
+
}
|
|
1359
|
+
renderCurrentPage() {
|
|
1360
|
+
const current = this.requireCurrentPage("renderCurrentPage()");
|
|
1361
|
+
const rendered = renderBrowserPageTree({
|
|
1362
|
+
changedPageKeys: current.__lastChangedKeys__ ?? [],
|
|
1363
|
+
componentCache: this.componentCache,
|
|
1364
|
+
componentScopes: this.componentScopes,
|
|
1365
|
+
files: this.files,
|
|
1366
|
+
moduleLoader: this.moduleLoader,
|
|
1367
|
+
project: this.project,
|
|
1368
|
+
session: {
|
|
1369
|
+
selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
|
|
1370
|
+
selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
|
|
1371
|
+
selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
|
|
1372
|
+
}
|
|
1373
|
+
}, current);
|
|
1374
|
+
current.__lastChangedKeys__ = [];
|
|
1375
|
+
return rendered;
|
|
1376
|
+
}
|
|
1377
|
+
callTapBinding(scopeId, methodName) {
|
|
1378
|
+
const scope = this.componentScopes.get(scopeId);
|
|
1379
|
+
if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
|
|
1380
|
+
const method = scope.getMethod(methodName);
|
|
1381
|
+
if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
|
|
1382
|
+
return method();
|
|
1383
|
+
}
|
|
1384
|
+
callTapBindingWithEvent(scopeId, methodName, event = {}) {
|
|
1385
|
+
const scope = this.componentScopes.get(scopeId);
|
|
1386
|
+
if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
|
|
1387
|
+
const method = scope.getMethod(methodName);
|
|
1388
|
+
if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
|
|
1389
|
+
const instance = this.componentCache.get(scopeId);
|
|
1390
|
+
if (instance) instance.__lastInteractionEvent__ = {
|
|
1391
|
+
currentTarget: {
|
|
1392
|
+
dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
|
|
1393
|
+
id: event.currentTarget?.id ?? event.id ?? ""
|
|
1394
|
+
},
|
|
1395
|
+
target: {
|
|
1396
|
+
dataset: event.target?.dataset ?? event.dataset ?? {},
|
|
1397
|
+
id: event.target?.id ?? event.id ?? ""
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
return method({
|
|
1401
|
+
bubbles: false,
|
|
1402
|
+
capturePhase: false,
|
|
1403
|
+
composed: false,
|
|
1404
|
+
currentTarget: {
|
|
1405
|
+
dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
|
|
1406
|
+
id: event.currentTarget?.id ?? event.id ?? ""
|
|
1407
|
+
},
|
|
1408
|
+
detail: void 0,
|
|
1409
|
+
mark: void 0,
|
|
1410
|
+
target: {
|
|
1411
|
+
dataset: event.target?.dataset ?? event.dataset ?? {},
|
|
1412
|
+
id: event.target?.id ?? event.id ?? ""
|
|
1413
|
+
},
|
|
1414
|
+
type: "tap"
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
|
|
1418
|
+
if (this.appInstance) return this.appInstance;
|
|
1419
|
+
const appModulePath = join(this.project.miniprogramRootPath, "app.js");
|
|
1420
|
+
this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
|
|
1421
|
+
this.appInstance = createAppInstance(this.appDefinition);
|
|
1422
|
+
this.appInstance.onLaunch?.(launchOptions);
|
|
1423
|
+
this.appInstance.onShow?.(launchOptions);
|
|
1424
|
+
return this.appInstance;
|
|
1425
|
+
}
|
|
1426
|
+
reLaunch(url) {
|
|
1427
|
+
const target = this.resolveNavigationTarget(url);
|
|
1428
|
+
this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
|
|
1429
|
+
this.unloadAllPages();
|
|
1430
|
+
const pageInstance = this.createFreshPage(target);
|
|
1431
|
+
this.pages.push(pageInstance);
|
|
1432
|
+
this.currentPageInstance = pageInstance;
|
|
1433
|
+
return pageInstance;
|
|
1434
|
+
}
|
|
1435
|
+
navigateTo(url) {
|
|
1436
|
+
const target = this.resolveNavigationTarget(url);
|
|
1437
|
+
this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
|
|
1438
|
+
if (this.pages.length >= PAGE_STACK_LIMIT$1) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT$1}-page stack in browser simulator runtime.`);
|
|
1439
|
+
if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
|
|
1440
|
+
this.currentPageInstance?.onHide?.();
|
|
1441
|
+
if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
|
|
1442
|
+
const pageInstance = this.createFreshPage(target);
|
|
1443
|
+
this.pages.push(pageInstance);
|
|
1444
|
+
this.currentPageInstance = pageInstance;
|
|
1445
|
+
return pageInstance;
|
|
1446
|
+
}
|
|
1447
|
+
redirectTo(url) {
|
|
1448
|
+
const target = this.resolveNavigationTarget(url);
|
|
1449
|
+
this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
|
|
1450
|
+
if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
|
|
1451
|
+
const current = this.currentPageInstance;
|
|
1452
|
+
if (current) {
|
|
1453
|
+
this.pages.pop();
|
|
1454
|
+
this.unloadPage(current);
|
|
47
1455
|
}
|
|
1456
|
+
const pageInstance = this.createFreshPage(target);
|
|
1457
|
+
this.pages.push(pageInstance);
|
|
1458
|
+
this.currentPageInstance = pageInstance;
|
|
1459
|
+
return pageInstance;
|
|
48
1460
|
}
|
|
49
|
-
|
|
1461
|
+
navigateBack(delta = 1) {
|
|
1462
|
+
this.bootstrap();
|
|
1463
|
+
if (this.pages.length <= 1) return this.currentPageInstance;
|
|
1464
|
+
const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
|
|
1465
|
+
const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
|
|
1466
|
+
for (const page of removedPages.reverse()) this.unloadPage(page);
|
|
1467
|
+
const nextPage = this.pages.at(-1) ?? null;
|
|
1468
|
+
this.currentPageInstance = nextPage;
|
|
1469
|
+
nextPage?.onShow?.();
|
|
1470
|
+
if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
|
|
1471
|
+
return nextPage;
|
|
1472
|
+
}
|
|
1473
|
+
switchTab(url) {
|
|
1474
|
+
const target = this.resolveNavigationTarget(url);
|
|
1475
|
+
this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
|
|
1476
|
+
if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in browser simulator runtime: ${url}`);
|
|
1477
|
+
if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
|
|
1478
|
+
const current = this.currentPageInstance;
|
|
1479
|
+
const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
|
|
1480
|
+
const tabItem = this.resolveTabBarItem(target.routeRecord.route);
|
|
1481
|
+
if (current === cachedTarget && current) {
|
|
1482
|
+
current.onTabItemTap?.(tabItem);
|
|
1483
|
+
return current;
|
|
1484
|
+
}
|
|
1485
|
+
if (current && current !== cachedTarget) {
|
|
1486
|
+
current.onHide?.();
|
|
1487
|
+
this.runPageComponentLifetime(current.route, "hide");
|
|
1488
|
+
}
|
|
1489
|
+
for (const page of [...this.pages].reverse()) {
|
|
1490
|
+
if (this.isTabBarRoute(stripLeadingSlash$1(page.route))) continue;
|
|
1491
|
+
this.removePageInstance(page);
|
|
1492
|
+
this.unloadPage(page);
|
|
1493
|
+
}
|
|
1494
|
+
let nextPage = cachedTarget;
|
|
1495
|
+
if (!nextPage) {
|
|
1496
|
+
nextPage = this.createFreshPage(target);
|
|
1497
|
+
this.tabPages.set(target.routeRecord.route, nextPage);
|
|
1498
|
+
} else if (current !== nextPage) {
|
|
1499
|
+
nextPage.onShow?.();
|
|
1500
|
+
this.runPageComponentLifetime(nextPage.route, "show");
|
|
1501
|
+
}
|
|
1502
|
+
nextPage.onTabItemTap?.(tabItem);
|
|
1503
|
+
this.pages.length = 0;
|
|
1504
|
+
this.pages.push(nextPage);
|
|
1505
|
+
this.currentPageInstance = nextPage;
|
|
1506
|
+
return nextPage;
|
|
1507
|
+
}
|
|
1508
|
+
pageScrollTo(option) {
|
|
1509
|
+
this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
|
|
1510
|
+
}
|
|
1511
|
+
triggerPullDownRefresh() {
|
|
1512
|
+
const current = this.requireCurrentPage("triggerPullDownRefresh()");
|
|
1513
|
+
current.onPullDownRefresh?.();
|
|
1514
|
+
return current;
|
|
1515
|
+
}
|
|
1516
|
+
triggerReachBottom() {
|
|
1517
|
+
const current = this.requireCurrentPage("triggerReachBottom()");
|
|
1518
|
+
current.onReachBottom?.();
|
|
1519
|
+
return current;
|
|
1520
|
+
}
|
|
1521
|
+
triggerResize(options) {
|
|
1522
|
+
const current = this.requireCurrentPage("triggerResize()");
|
|
1523
|
+
current.onResize?.(options);
|
|
1524
|
+
this.runPageComponentLifetime(current.route, "resize", options);
|
|
1525
|
+
return current;
|
|
1526
|
+
}
|
|
1527
|
+
triggerRouteDone(options = {}) {
|
|
1528
|
+
const current = this.requireCurrentPage("triggerRouteDone()");
|
|
1529
|
+
current.onRouteDone?.(options);
|
|
1530
|
+
return current;
|
|
1531
|
+
}
|
|
1532
|
+
stopPullDownRefresh() {}
|
|
1533
|
+
createFreshPage(target) {
|
|
1534
|
+
const pageModulePath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
|
|
1535
|
+
const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
|
|
1536
|
+
const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query);
|
|
1537
|
+
pageInstance.selectComponent = (selector) => this.selectComponent(selector);
|
|
1538
|
+
pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
|
|
1539
|
+
pageInstance.onLoad?.(target.query);
|
|
1540
|
+
pageInstance.onShow?.();
|
|
1541
|
+
pageInstance.onReady?.();
|
|
1542
|
+
if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
|
|
1543
|
+
return pageInstance;
|
|
1544
|
+
}
|
|
1545
|
+
isTabBarRoute(route) {
|
|
1546
|
+
return this.tabBarRoutes.has(stripLeadingSlash$1(route));
|
|
1547
|
+
}
|
|
1548
|
+
removePageInstance(page) {
|
|
1549
|
+
const index = this.pages.indexOf(page);
|
|
1550
|
+
if (index >= 0) this.pages.splice(index, 1);
|
|
1551
|
+
}
|
|
1552
|
+
resolveNavigationTarget(url) {
|
|
1553
|
+
const { pathname, query } = parseNavigationUrl$1(url);
|
|
1554
|
+
const normalizedRoute = resolveNavigationPath$1(pathname, this.currentPageInstance ? stripLeadingSlash$1(this.currentPageInstance.route) : void 0);
|
|
1555
|
+
const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
|
|
1556
|
+
if (!routeRecord) {
|
|
1557
|
+
this.bootstrap(createAppLaunchOptions$1(normalizedRoute, query));
|
|
1558
|
+
this.appInstance?.onPageNotFound?.(createAppLaunchOptions$1(normalizedRoute, query));
|
|
1559
|
+
throw new Error(`Unknown route for browser simulator navigation: ${url}`);
|
|
1560
|
+
}
|
|
1561
|
+
return {
|
|
1562
|
+
normalizedRoute,
|
|
1563
|
+
query,
|
|
1564
|
+
routeRecord
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
resolveTabBarItem(route) {
|
|
1568
|
+
const pagePath = stripLeadingSlash$1(route);
|
|
1569
|
+
const item = this.tabBarItems.get(pagePath);
|
|
1570
|
+
if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
|
|
1571
|
+
return { ...item };
|
|
1572
|
+
}
|
|
1573
|
+
unloadAllPages() {
|
|
1574
|
+
const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
|
|
1575
|
+
for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
|
|
1576
|
+
this.pages.length = 0;
|
|
1577
|
+
this.tabPages.clear();
|
|
1578
|
+
this.componentCache.clear();
|
|
1579
|
+
this.componentScopes.clear();
|
|
1580
|
+
this.currentPageInstance = null;
|
|
1581
|
+
}
|
|
1582
|
+
unloadPage(page) {
|
|
1583
|
+
page.onUnload?.();
|
|
1584
|
+
this.detachPageComponents(page.route);
|
|
1585
|
+
this.tabPages.delete(stripLeadingSlash$1(page.route));
|
|
1586
|
+
}
|
|
1587
|
+
requireCurrentPage(action) {
|
|
1588
|
+
this.bootstrap();
|
|
1589
|
+
const current = this.currentPageInstance;
|
|
1590
|
+
if (!current) throw new Error(`Cannot call ${action} without an active page in browser simulator runtime.`);
|
|
1591
|
+
return current;
|
|
1592
|
+
}
|
|
1593
|
+
detachPageComponents(route) {
|
|
1594
|
+
const prefix = `page:${stripLeadingSlash$1(route)}`;
|
|
1595
|
+
for (const [scopeId, instance] of [...this.componentCache.entries()]) {
|
|
1596
|
+
if (!scopeId.startsWith(prefix)) continue;
|
|
1597
|
+
instance.__definition__?.lifetimes?.detached?.call(instance);
|
|
1598
|
+
this.componentCache.delete(scopeId);
|
|
1599
|
+
this.componentScopes.delete(scopeId);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
runPageComponentLifetime(route, lifetimeName, payload) {
|
|
1603
|
+
const prefix = `page:${stripLeadingSlash$1(route)}`;
|
|
1604
|
+
for (const [scopeId, instance] of this.componentCache.entries()) {
|
|
1605
|
+
if (!scopeId.startsWith(prefix)) continue;
|
|
1606
|
+
runComponentPageLifetime(instance, lifetimeName, payload);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
};
|
|
1610
|
+
function createBrowserHeadlessSession(options) {
|
|
1611
|
+
return new BrowserHeadlessSession(options);
|
|
50
1612
|
}
|
|
51
1613
|
//#endregion
|
|
52
1614
|
//#region src/project/loadProject.ts
|
|
@@ -98,135 +1660,14 @@ function loadProject(projectPath) {
|
|
|
98
1660
|
ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
|
|
99
1661
|
const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
|
|
100
1662
|
ensureFileExists(appConfigPath, "built app.json");
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
appConfig,
|
|
1663
|
+
return createProjectDescriptor({
|
|
1664
|
+
appConfig: loadAppConfig(appConfigPath),
|
|
104
1665
|
appConfigPath,
|
|
105
1666
|
miniprogramRoot,
|
|
106
1667
|
miniprogramRootPath,
|
|
107
1668
|
projectPath: normalizedProjectPath,
|
|
108
|
-
projectConfigFiles
|
|
109
|
-
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
//#endregion
|
|
113
|
-
//#region src/host/globals.ts
|
|
114
|
-
function createDuplicateRegistrationError(kind, id) {
|
|
115
|
-
return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
|
|
116
|
-
}
|
|
117
|
-
function createHostRegistries() {
|
|
118
|
-
return {
|
|
119
|
-
appDefinition: null,
|
|
120
|
-
components: /* @__PURE__ */ new Map(),
|
|
121
|
-
currentLoadContext: null,
|
|
122
|
-
pages: /* @__PURE__ */ new Map()
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
function registerAppDefinition(registries, definition) {
|
|
126
|
-
if (registries.appDefinition) throw createDuplicateRegistrationError("app", "app");
|
|
127
|
-
registries.appDefinition = definition;
|
|
128
|
-
return definition;
|
|
129
|
-
}
|
|
130
|
-
function registerPageDefinition(registries, definition) {
|
|
131
|
-
const route = registries.currentLoadContext?.route;
|
|
132
|
-
if (!route) throw new Error("Cannot register Page() without an active page load context in headless runtime.");
|
|
133
|
-
if (registries.pages.has(route)) throw createDuplicateRegistrationError("page", route);
|
|
134
|
-
registries.pages.set(route, definition);
|
|
135
|
-
return definition;
|
|
136
|
-
}
|
|
137
|
-
function registerComponentDefinition(registries, definition) {
|
|
138
|
-
const id = registries.currentLoadContext?.route ?? `anonymous:${registries.components.size}`;
|
|
139
|
-
if (registries.components.has(id)) throw createDuplicateRegistrationError("component", id);
|
|
140
|
-
registries.components.set(id, definition);
|
|
141
|
-
return definition;
|
|
142
|
-
}
|
|
143
|
-
//#endregion
|
|
144
|
-
//#region src/host/wx.ts
|
|
145
|
-
function createUnsupportedWxApi(name) {
|
|
146
|
-
return () => {
|
|
147
|
-
throw new Error(`wx.${name} is not implemented in headless runtime yet.`);
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
function createHeadlessWx() {
|
|
151
|
-
return {
|
|
152
|
-
navigateBack: createUnsupportedWxApi("navigateBack"),
|
|
153
|
-
navigateTo: createUnsupportedWxApi("navigateTo"),
|
|
154
|
-
pageScrollTo: createUnsupportedWxApi("pageScrollTo"),
|
|
155
|
-
reLaunch: createUnsupportedWxApi("reLaunch"),
|
|
156
|
-
redirectTo: createUnsupportedWxApi("redirectTo"),
|
|
157
|
-
switchTab: createUnsupportedWxApi("switchTab")
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
//#endregion
|
|
161
|
-
//#region src/runtime/appInstance.ts
|
|
162
|
-
function bindFunction$1(target, key, value) {
|
|
163
|
-
if (typeof value !== "function") {
|
|
164
|
-
target[key] = value;
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
target[key] = (...args) => value.apply(target, args);
|
|
168
|
-
}
|
|
169
|
-
function resolveInitialData$1(definition) {
|
|
170
|
-
const rawData = definition.data;
|
|
171
|
-
if (typeof rawData === "function") {
|
|
172
|
-
const next = rawData.call(definition);
|
|
173
|
-
return next && typeof next === "object" && !Array.isArray(next) ? { ...next } : {};
|
|
174
|
-
}
|
|
175
|
-
return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? { ...rawData } : {};
|
|
176
|
-
}
|
|
177
|
-
function createAppInstance(definition) {
|
|
178
|
-
const instance = { globalData: resolveInitialData$1(definition) };
|
|
179
|
-
for (const [key, value] of Object.entries(definition)) {
|
|
180
|
-
if (key === "data") continue;
|
|
181
|
-
bindFunction$1(instance, key, value);
|
|
182
|
-
}
|
|
183
|
-
return instance;
|
|
184
|
-
}
|
|
185
|
-
//#endregion
|
|
186
|
-
//#region src/runtime/pageInstance.ts
|
|
187
|
-
function bindFunction(target, key, value) {
|
|
188
|
-
if (typeof value !== "function") {
|
|
189
|
-
target[key] = value;
|
|
190
|
-
return;
|
|
191
|
-
}
|
|
192
|
-
target[key] = (...args) => value.apply(target, args);
|
|
193
|
-
}
|
|
194
|
-
function cloneObject(value) {
|
|
195
|
-
return JSON.parse(JSON.stringify(value));
|
|
196
|
-
}
|
|
197
|
-
function resolveInitialData(definition) {
|
|
198
|
-
const rawData = definition.data;
|
|
199
|
-
if (typeof rawData === "function") {
|
|
200
|
-
const next = rawData.call(definition);
|
|
201
|
-
return next && typeof next === "object" && !Array.isArray(next) ? cloneObject(next) : {};
|
|
202
|
-
}
|
|
203
|
-
return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject(rawData) : {};
|
|
204
|
-
}
|
|
205
|
-
function assignByPath(target, path, value) {
|
|
206
|
-
const segments = path.split(".").filter(Boolean);
|
|
207
|
-
if (segments.length === 0) return;
|
|
208
|
-
let current = target;
|
|
209
|
-
for (let index = 0; index < segments.length - 1; index += 1) {
|
|
210
|
-
const segment = segments[index];
|
|
211
|
-
const next = current[segment];
|
|
212
|
-
if (!next || typeof next !== "object" || Array.isArray(next)) current[segment] = {};
|
|
213
|
-
current = current[segment];
|
|
214
|
-
}
|
|
215
|
-
current[segments[segments.length - 1]] = value;
|
|
216
|
-
}
|
|
217
|
-
function createPageInstance(route, definition) {
|
|
218
|
-
const instance = {
|
|
219
|
-
data: resolveInitialData(definition),
|
|
220
|
-
route,
|
|
221
|
-
setData(patch) {
|
|
222
|
-
for (const [key, value] of Object.entries(patch)) assignByPath(instance.data, key, value);
|
|
223
|
-
}
|
|
224
|
-
};
|
|
225
|
-
for (const [key, value] of Object.entries(definition)) {
|
|
226
|
-
if (key === "data") continue;
|
|
227
|
-
bindFunction(instance, key, value);
|
|
228
|
-
}
|
|
229
|
-
return instance;
|
|
1669
|
+
projectConfigFiles
|
|
1670
|
+
});
|
|
230
1671
|
}
|
|
231
1672
|
//#endregion
|
|
232
1673
|
//#region src/runtime/moduleLoader.ts
|
|
@@ -245,12 +1686,18 @@ function resolveRequiredModulePath(importer, request) {
|
|
|
245
1686
|
for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
|
|
246
1687
|
throw createRequireNotFoundError(request, importer);
|
|
247
1688
|
}
|
|
248
|
-
function createExecutionContext(registries, getCurrentPages, getApp) {
|
|
249
|
-
const wx = createHeadlessWx();
|
|
1689
|
+
function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
|
|
1690
|
+
const wx = createHeadlessWx(wxDriver);
|
|
250
1691
|
return {
|
|
251
1692
|
App(definition) {
|
|
252
1693
|
return registerAppDefinition(registries, definition);
|
|
253
1694
|
},
|
|
1695
|
+
Behavior(definition) {
|
|
1696
|
+
return {
|
|
1697
|
+
...definition,
|
|
1698
|
+
__isHeadlessBehavior__: true
|
|
1699
|
+
};
|
|
1700
|
+
},
|
|
254
1701
|
Component(definition) {
|
|
255
1702
|
return registerComponentDefinition(registries, definition);
|
|
256
1703
|
},
|
|
@@ -269,9 +1716,9 @@ function createExecutionContext(registries, getCurrentPages, getApp) {
|
|
|
269
1716
|
wx
|
|
270
1717
|
};
|
|
271
1718
|
}
|
|
272
|
-
function createModuleLoader(registries, getCurrentPages, getApp) {
|
|
1719
|
+
function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
|
|
273
1720
|
const moduleCache = /* @__PURE__ */ new Map();
|
|
274
|
-
const executionContext = createExecutionContext(registries, getCurrentPages, getApp);
|
|
1721
|
+
const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver);
|
|
275
1722
|
executionContext.globalThis = executionContext;
|
|
276
1723
|
function executeModule(filePath, loadContext) {
|
|
277
1724
|
const resolvedPath = path.resolve(filePath);
|
|
@@ -317,6 +1764,43 @@ function createModuleLoader(registries, getCurrentPages, getApp) {
|
|
|
317
1764
|
//#endregion
|
|
318
1765
|
//#region src/runtime/session.ts
|
|
319
1766
|
const LEADING_SLASH_RE$1 = /^\/+/;
|
|
1767
|
+
const PAGE_STACK_LIMIT = 10;
|
|
1768
|
+
function stripLeadingSlash(route) {
|
|
1769
|
+
return route.replace(LEADING_SLASH_RE$1, "");
|
|
1770
|
+
}
|
|
1771
|
+
function normalizeQuery(queryString) {
|
|
1772
|
+
const query = new URLSearchParams(queryString);
|
|
1773
|
+
const result = {};
|
|
1774
|
+
for (const [key, value] of query.entries()) result[key] = value;
|
|
1775
|
+
return result;
|
|
1776
|
+
}
|
|
1777
|
+
function parseNavigationUrl(url) {
|
|
1778
|
+
const trimmedUrl = url.trim();
|
|
1779
|
+
if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in headless runtime.");
|
|
1780
|
+
const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
|
|
1781
|
+
const [pathname] = pathWithHash.split("#");
|
|
1782
|
+
return {
|
|
1783
|
+
pathname: pathname || "",
|
|
1784
|
+
query: normalizeQuery(queryString)
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
function createAppLaunchOptions(pathname, query) {
|
|
1788
|
+
return {
|
|
1789
|
+
path: stripLeadingSlash(pathname),
|
|
1790
|
+
query: { ...query },
|
|
1791
|
+
referrerInfo: {
|
|
1792
|
+
appId: "",
|
|
1793
|
+
extraData: {}
|
|
1794
|
+
},
|
|
1795
|
+
scene: 1001
|
|
1796
|
+
};
|
|
1797
|
+
}
|
|
1798
|
+
function resolveNavigationPath(targetPath, baseRoute) {
|
|
1799
|
+
if (!targetPath) throw new Error("Navigation url must include a pathname in headless runtime.");
|
|
1800
|
+
if (targetPath.startsWith("/")) return path.posix.normalize(targetPath).replace(LEADING_SLASH_RE$1, "");
|
|
1801
|
+
if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
|
|
1802
|
+
return path.posix.resolve(`/${path.posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$1, "");
|
|
1803
|
+
}
|
|
320
1804
|
var HeadlessSession = class {
|
|
321
1805
|
project;
|
|
322
1806
|
appDefinition = null;
|
|
@@ -325,10 +1809,42 @@ var HeadlessSession = class {
|
|
|
325
1809
|
registries;
|
|
326
1810
|
currentPageInstance = null;
|
|
327
1811
|
pages = [];
|
|
1812
|
+
tabBarRoutes;
|
|
1813
|
+
tabPages = /* @__PURE__ */ new Map();
|
|
1814
|
+
tabBarItems = /* @__PURE__ */ new Map();
|
|
1815
|
+
wxState = createHeadlessWxState();
|
|
328
1816
|
constructor(options) {
|
|
329
1817
|
this.project = loadProject(options.projectPath);
|
|
330
1818
|
this.registries = createHostRegistries();
|
|
331
|
-
|
|
1819
|
+
const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
|
|
1820
|
+
this.tabBarRoutes = /* @__PURE__ */ new Set();
|
|
1821
|
+
rawTabBarList.forEach((item, index) => {
|
|
1822
|
+
if (typeof item?.pagePath !== "string") return;
|
|
1823
|
+
const pagePath = stripLeadingSlash(item.pagePath);
|
|
1824
|
+
if (!pagePath) return;
|
|
1825
|
+
this.tabBarRoutes.add(pagePath);
|
|
1826
|
+
this.tabBarItems.set(pagePath, {
|
|
1827
|
+
index,
|
|
1828
|
+
pagePath,
|
|
1829
|
+
text: typeof item.text === "string" ? item.text : void 0
|
|
1830
|
+
});
|
|
1831
|
+
});
|
|
1832
|
+
this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
|
|
1833
|
+
navigateBack: (option) => this.navigateBack(option?.delta),
|
|
1834
|
+
navigateTo: (option) => this.navigateTo(option.url),
|
|
1835
|
+
pageScrollTo: (option) => this.pageScrollTo(option),
|
|
1836
|
+
clearStorageSync: () => this.wxState.clearStorageSync(),
|
|
1837
|
+
getStorageSync: (key) => this.wxState.getStorageSync(key),
|
|
1838
|
+
hideToast: () => this.wxState.hideToast(),
|
|
1839
|
+
reLaunch: (option) => this.reLaunch(option.url),
|
|
1840
|
+
redirectTo: (option) => this.redirectTo(option.url),
|
|
1841
|
+
removeStorageSync: (key) => this.wxState.removeStorageSync(key),
|
|
1842
|
+
request: (option) => this.wxState.request(option),
|
|
1843
|
+
setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
|
|
1844
|
+
showToast: (option) => this.wxState.showToast(option),
|
|
1845
|
+
stopPullDownRefresh: () => this.stopPullDownRefresh(),
|
|
1846
|
+
switchTab: (option) => this.switchTab(option.url)
|
|
1847
|
+
});
|
|
332
1848
|
}
|
|
333
1849
|
getApp() {
|
|
334
1850
|
return this.appInstance;
|
|
@@ -336,36 +1852,180 @@ var HeadlessSession = class {
|
|
|
336
1852
|
getCurrentPages() {
|
|
337
1853
|
return this.pages.slice();
|
|
338
1854
|
}
|
|
339
|
-
|
|
1855
|
+
getRequestLogs() {
|
|
1856
|
+
return this.wxState.getRequestLogs();
|
|
1857
|
+
}
|
|
1858
|
+
getStorageSnapshot() {
|
|
1859
|
+
return this.wxState.getStorageSnapshot();
|
|
1860
|
+
}
|
|
1861
|
+
getToast() {
|
|
1862
|
+
return this.wxState.getToast();
|
|
1863
|
+
}
|
|
1864
|
+
mockRequest(definition) {
|
|
1865
|
+
this.wxState.mockRequest(definition);
|
|
1866
|
+
}
|
|
1867
|
+
bootstrap(launchOptions = createAppLaunchOptions("", {})) {
|
|
340
1868
|
if (this.appInstance) return this.appInstance;
|
|
341
1869
|
const appModulePath = path.resolve(this.project.miniprogramRootPath, "app.js");
|
|
342
1870
|
this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
|
|
343
1871
|
this.appInstance = createAppInstance(this.appDefinition);
|
|
344
|
-
this.appInstance.onLaunch?.();
|
|
345
|
-
this.appInstance.onShow?.();
|
|
1872
|
+
this.appInstance.onLaunch?.(launchOptions);
|
|
1873
|
+
this.appInstance.onShow?.(launchOptions);
|
|
346
1874
|
return this.appInstance;
|
|
347
1875
|
}
|
|
348
|
-
reLaunch(
|
|
349
|
-
this.
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
1876
|
+
reLaunch(url) {
|
|
1877
|
+
const target = this.resolveNavigationTarget(url);
|
|
1878
|
+
this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
|
|
1879
|
+
this.unloadAllPages();
|
|
1880
|
+
const pageInstance = this.createFreshPage(target);
|
|
1881
|
+
this.pages.push(pageInstance);
|
|
1882
|
+
this.currentPageInstance = pageInstance;
|
|
1883
|
+
return pageInstance;
|
|
1884
|
+
}
|
|
1885
|
+
navigateTo(url) {
|
|
1886
|
+
const target = this.resolveNavigationTarget(url);
|
|
1887
|
+
this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
|
|
1888
|
+
if (this.pages.length >= PAGE_STACK_LIMIT) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT}-page stack in headless runtime.`);
|
|
1889
|
+
if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in headless runtime: ${url}`);
|
|
1890
|
+
this.currentPageInstance?.onHide?.();
|
|
1891
|
+
const pageInstance = this.createFreshPage(target);
|
|
1892
|
+
this.pages.push(pageInstance);
|
|
1893
|
+
this.currentPageInstance = pageInstance;
|
|
1894
|
+
return pageInstance;
|
|
1895
|
+
}
|
|
1896
|
+
redirectTo(url) {
|
|
1897
|
+
const target = this.resolveNavigationTarget(url);
|
|
1898
|
+
this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
|
|
1899
|
+
if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in headless runtime: ${url}`);
|
|
1900
|
+
const current = this.currentPageInstance;
|
|
1901
|
+
if (current) {
|
|
1902
|
+
this.pages.pop();
|
|
1903
|
+
this.unloadPage(current);
|
|
1904
|
+
}
|
|
1905
|
+
const pageInstance = this.createFreshPage(target);
|
|
362
1906
|
this.pages.push(pageInstance);
|
|
363
1907
|
this.currentPageInstance = pageInstance;
|
|
364
|
-
pageInstance
|
|
1908
|
+
return pageInstance;
|
|
1909
|
+
}
|
|
1910
|
+
navigateBack(delta = 1) {
|
|
1911
|
+
this.bootstrap();
|
|
1912
|
+
if (this.pages.length <= 1) return this.currentPageInstance;
|
|
1913
|
+
const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
|
|
1914
|
+
const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
|
|
1915
|
+
for (const page of removedPages.reverse()) this.unloadPage(page);
|
|
1916
|
+
const nextPage = this.pages.at(-1) ?? null;
|
|
1917
|
+
this.currentPageInstance = nextPage;
|
|
1918
|
+
nextPage?.onShow?.();
|
|
1919
|
+
return nextPage;
|
|
1920
|
+
}
|
|
1921
|
+
switchTab(url) {
|
|
1922
|
+
const target = this.resolveNavigationTarget(url);
|
|
1923
|
+
this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
|
|
1924
|
+
if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in headless runtime: ${url}`);
|
|
1925
|
+
if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in headless runtime: ${url}`);
|
|
1926
|
+
const current = this.currentPageInstance;
|
|
1927
|
+
const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
|
|
1928
|
+
const tabItem = this.resolveTabBarItem(target.routeRecord.route);
|
|
1929
|
+
if (current === cachedTarget && current) {
|
|
1930
|
+
current.onTabItemTap?.(tabItem);
|
|
1931
|
+
return current;
|
|
1932
|
+
}
|
|
1933
|
+
if (current && current !== cachedTarget) current.onHide?.();
|
|
1934
|
+
for (const page of [...this.pages].reverse()) {
|
|
1935
|
+
if (this.isTabBarRoute(stripLeadingSlash(page.route))) continue;
|
|
1936
|
+
this.removePageInstance(page);
|
|
1937
|
+
this.unloadPage(page);
|
|
1938
|
+
}
|
|
1939
|
+
let nextPage = cachedTarget;
|
|
1940
|
+
if (!nextPage) {
|
|
1941
|
+
nextPage = this.createFreshPage(target);
|
|
1942
|
+
this.tabPages.set(target.routeRecord.route, nextPage);
|
|
1943
|
+
} else if (current !== nextPage) nextPage.onShow?.();
|
|
1944
|
+
nextPage.onTabItemTap?.(tabItem);
|
|
1945
|
+
this.pages.length = 0;
|
|
1946
|
+
this.pages.push(nextPage);
|
|
1947
|
+
this.currentPageInstance = nextPage;
|
|
1948
|
+
return nextPage;
|
|
1949
|
+
}
|
|
1950
|
+
pageScrollTo(option) {
|
|
1951
|
+
this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
|
|
1952
|
+
}
|
|
1953
|
+
triggerPullDownRefresh() {
|
|
1954
|
+
const current = this.requireCurrentPage("triggerPullDownRefresh()");
|
|
1955
|
+
current.onPullDownRefresh?.();
|
|
1956
|
+
return current;
|
|
1957
|
+
}
|
|
1958
|
+
triggerReachBottom() {
|
|
1959
|
+
const current = this.requireCurrentPage("triggerReachBottom()");
|
|
1960
|
+
current.onReachBottom?.();
|
|
1961
|
+
return current;
|
|
1962
|
+
}
|
|
1963
|
+
triggerResize(options) {
|
|
1964
|
+
const current = this.requireCurrentPage("triggerResize()");
|
|
1965
|
+
current.onResize?.(options);
|
|
1966
|
+
return current;
|
|
1967
|
+
}
|
|
1968
|
+
triggerRouteDone(options = {}) {
|
|
1969
|
+
const current = this.requireCurrentPage("triggerRouteDone()");
|
|
1970
|
+
current.onRouteDone?.(options);
|
|
1971
|
+
return current;
|
|
1972
|
+
}
|
|
1973
|
+
stopPullDownRefresh() {}
|
|
1974
|
+
createFreshPage(target) {
|
|
1975
|
+
const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
|
|
1976
|
+
const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
|
|
1977
|
+
const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query);
|
|
1978
|
+
pageInstance.onLoad?.(target.query);
|
|
365
1979
|
pageInstance.onShow?.();
|
|
366
1980
|
pageInstance.onReady?.();
|
|
1981
|
+
if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
|
|
367
1982
|
return pageInstance;
|
|
368
1983
|
}
|
|
1984
|
+
isTabBarRoute(route) {
|
|
1985
|
+
return this.tabBarRoutes.has(stripLeadingSlash(route));
|
|
1986
|
+
}
|
|
1987
|
+
resolveTabBarItem(route) {
|
|
1988
|
+
const pagePath = stripLeadingSlash(route);
|
|
1989
|
+
const item = this.tabBarItems.get(pagePath);
|
|
1990
|
+
if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
|
|
1991
|
+
return { ...item };
|
|
1992
|
+
}
|
|
1993
|
+
removePageInstance(page) {
|
|
1994
|
+
const index = this.pages.indexOf(page);
|
|
1995
|
+
if (index >= 0) this.pages.splice(index, 1);
|
|
1996
|
+
}
|
|
1997
|
+
resolveNavigationTarget(url) {
|
|
1998
|
+
const { pathname, query } = parseNavigationUrl(url);
|
|
1999
|
+
const normalizedRoute = resolveNavigationPath(pathname, this.currentPageInstance ? stripLeadingSlash(this.currentPageInstance.route) : void 0);
|
|
2000
|
+
const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
|
|
2001
|
+
if (!routeRecord) {
|
|
2002
|
+
this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
|
|
2003
|
+
this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
|
|
2004
|
+
throw new Error(`Unknown route for headless runtime navigation: ${url}`);
|
|
2005
|
+
}
|
|
2006
|
+
return {
|
|
2007
|
+
normalizedRoute,
|
|
2008
|
+
query,
|
|
2009
|
+
routeRecord
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
unloadAllPages() {
|
|
2013
|
+
const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
|
|
2014
|
+
for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
|
|
2015
|
+
this.pages.length = 0;
|
|
2016
|
+
this.tabPages.clear();
|
|
2017
|
+
this.currentPageInstance = null;
|
|
2018
|
+
}
|
|
2019
|
+
unloadPage(page) {
|
|
2020
|
+
page.onUnload?.();
|
|
2021
|
+
this.tabPages.delete(stripLeadingSlash(page.route));
|
|
2022
|
+
}
|
|
2023
|
+
requireCurrentPage(action) {
|
|
2024
|
+
this.bootstrap();
|
|
2025
|
+
const current = this.currentPageInstance;
|
|
2026
|
+
if (!current) throw new Error(`Cannot call ${action} without an active page in headless runtime.`);
|
|
2027
|
+
return current;
|
|
2028
|
+
}
|
|
369
2029
|
};
|
|
370
2030
|
function createHeadlessSession(options) {
|
|
371
2031
|
return new HeadlessSession(options);
|
|
@@ -570,6 +2230,21 @@ var HeadlessTestingSessionHandle = class {
|
|
|
570
2230
|
const page = this.session.reLaunch(route);
|
|
571
2231
|
return new HeadlessTestingPageHandle(this.project, page);
|
|
572
2232
|
}
|
|
2233
|
+
async pageScrollTo(scrollTop) {
|
|
2234
|
+
this.session.pageScrollTo({ scrollTop });
|
|
2235
|
+
}
|
|
2236
|
+
async triggerPullDownRefresh() {
|
|
2237
|
+
this.session.triggerPullDownRefresh();
|
|
2238
|
+
}
|
|
2239
|
+
async triggerReachBottom() {
|
|
2240
|
+
this.session.triggerReachBottom();
|
|
2241
|
+
}
|
|
2242
|
+
async triggerResize(options) {
|
|
2243
|
+
this.session.triggerResize(options);
|
|
2244
|
+
}
|
|
2245
|
+
async triggerRouteDone(options) {
|
|
2246
|
+
this.session.triggerRouteDone(options);
|
|
2247
|
+
}
|
|
573
2248
|
};
|
|
574
2249
|
//#endregion
|
|
575
2250
|
//#region src/testing/launch.ts
|
|
@@ -579,4 +2254,4 @@ async function launch(options) {
|
|
|
579
2254
|
return new HeadlessTestingSessionHandle(session.project, session);
|
|
580
2255
|
}
|
|
581
2256
|
//#endregion
|
|
582
|
-
export { HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, createAppInstance, createHeadlessSession, createHeadlessWx, createHostRegistries, createPageInstance, launch, loadProject, querySelectorAll, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderPageTree, resolveRoutesFromAppConfig };
|
|
2257
|
+
export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, resolveRoutesFromAppConfig, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };
|