@mpcore/simulator 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/index.d.mts +166 -0
- package/dist/index.mjs +582 -0
- package/package.json +55 -0
package/README.md
ADDED
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
//#region src/project/resolveRoutes.d.ts
|
|
2
|
+
interface HeadlessRouteRecord {
|
|
3
|
+
kind: 'page';
|
|
4
|
+
route: string;
|
|
5
|
+
source: 'pages' | 'subPackages';
|
|
6
|
+
subpackageRoot?: string;
|
|
7
|
+
}
|
|
8
|
+
declare function resolveRoutesFromAppConfig(config: Record<string, any>): HeadlessRouteRecord[];
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/project/loadProject.d.ts
|
|
11
|
+
interface HeadlessProjectConfigFile {
|
|
12
|
+
filePath: string;
|
|
13
|
+
value: Record<string, any>;
|
|
14
|
+
}
|
|
15
|
+
interface HeadlessProjectDescriptor {
|
|
16
|
+
appConfig: Record<string, any>;
|
|
17
|
+
appConfigPath: string;
|
|
18
|
+
miniprogramRoot: string;
|
|
19
|
+
miniprogramRootPath: string;
|
|
20
|
+
projectPath: string;
|
|
21
|
+
projectConfigFiles: HeadlessProjectConfigFile[];
|
|
22
|
+
routes: HeadlessRouteRecord[];
|
|
23
|
+
}
|
|
24
|
+
declare function loadProject(projectPath: string): HeadlessProjectDescriptor;
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/host/globals.d.ts
|
|
27
|
+
interface HeadlessAppDefinition extends Record<string, any> {}
|
|
28
|
+
interface HeadlessPageDefinition extends Record<string, any> {}
|
|
29
|
+
interface HeadlessComponentDefinition extends Record<string, any> {}
|
|
30
|
+
interface HeadlessHostLoadContext {
|
|
31
|
+
kind: 'app' | 'page' | 'component';
|
|
32
|
+
route?: string;
|
|
33
|
+
}
|
|
34
|
+
interface HeadlessHostRegistries {
|
|
35
|
+
appDefinition: HeadlessAppDefinition | null;
|
|
36
|
+
components: Map<string, HeadlessComponentDefinition>;
|
|
37
|
+
currentLoadContext: HeadlessHostLoadContext | null;
|
|
38
|
+
pages: Map<string, HeadlessPageDefinition>;
|
|
39
|
+
}
|
|
40
|
+
declare function createHostRegistries(): HeadlessHostRegistries;
|
|
41
|
+
declare function registerAppDefinition(registries: HeadlessHostRegistries, definition: HeadlessAppDefinition): HeadlessAppDefinition;
|
|
42
|
+
declare function registerPageDefinition(registries: HeadlessHostRegistries, definition: HeadlessPageDefinition): HeadlessPageDefinition;
|
|
43
|
+
declare function registerComponentDefinition(registries: HeadlessHostRegistries, definition: HeadlessComponentDefinition): HeadlessComponentDefinition;
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/host/wx.d.ts
|
|
46
|
+
interface HeadlessWx {
|
|
47
|
+
navigateBack: () => never;
|
|
48
|
+
navigateTo: () => never;
|
|
49
|
+
pageScrollTo: () => never;
|
|
50
|
+
reLaunch: () => never;
|
|
51
|
+
redirectTo: () => never;
|
|
52
|
+
switchTab: () => never;
|
|
53
|
+
}
|
|
54
|
+
declare function createHeadlessWx(): HeadlessWx;
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region src/runtime/appInstance.d.ts
|
|
57
|
+
interface HeadlessAppInstance extends Record<string, any> {
|
|
58
|
+
globalData: Record<string, any>;
|
|
59
|
+
}
|
|
60
|
+
declare function createAppInstance(definition: HeadlessAppDefinition): HeadlessAppInstance;
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/runtime/pageInstance.d.ts
|
|
63
|
+
interface HeadlessPageInstance extends Record<string, any> {
|
|
64
|
+
data: Record<string, any>;
|
|
65
|
+
route: string;
|
|
66
|
+
setData: (patch: Record<string, any>) => void;
|
|
67
|
+
}
|
|
68
|
+
declare function createPageInstance(route: string, definition: HeadlessPageDefinition): HeadlessPageInstance;
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/runtime/session.d.ts
|
|
71
|
+
interface HeadlessSessionOptions {
|
|
72
|
+
projectPath: string;
|
|
73
|
+
}
|
|
74
|
+
declare class HeadlessSession {
|
|
75
|
+
readonly project: HeadlessProjectDescriptor;
|
|
76
|
+
private appDefinition;
|
|
77
|
+
private appInstance;
|
|
78
|
+
private readonly moduleLoader;
|
|
79
|
+
private readonly registries;
|
|
80
|
+
private currentPageInstance;
|
|
81
|
+
private readonly pages;
|
|
82
|
+
constructor(options: HeadlessSessionOptions);
|
|
83
|
+
getApp(): HeadlessAppInstance | null;
|
|
84
|
+
getCurrentPages(): HeadlessPageInstance[];
|
|
85
|
+
bootstrap(): HeadlessAppInstance;
|
|
86
|
+
reLaunch(route: string): HeadlessPageInstance;
|
|
87
|
+
}
|
|
88
|
+
declare function createHeadlessSession(options: HeadlessSessionOptions): HeadlessSession;
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region src/view/nodeHandle.d.ts
|
|
91
|
+
interface DomNodeLike$2 {
|
|
92
|
+
attribs?: Record<string, string>;
|
|
93
|
+
children?: DomNodeLike$2[];
|
|
94
|
+
data?: string;
|
|
95
|
+
name?: string;
|
|
96
|
+
parent?: DomNodeLike$2 | null;
|
|
97
|
+
type?: string;
|
|
98
|
+
}
|
|
99
|
+
declare class HeadlessTestingNodeHandle {
|
|
100
|
+
private readonly node;
|
|
101
|
+
constructor(node: DomNodeLike$2);
|
|
102
|
+
$(selector: string): Promise<HeadlessTestingNodeHandle | null>;
|
|
103
|
+
$$(selector: string): Promise<HeadlessTestingNodeHandle[]>;
|
|
104
|
+
attr(name: string): Promise<string | undefined>;
|
|
105
|
+
dataset(): Promise<Record<string, any>>;
|
|
106
|
+
text(): Promise<string>;
|
|
107
|
+
wxml(): Promise<string>;
|
|
108
|
+
}
|
|
109
|
+
//#endregion
|
|
110
|
+
//#region src/view/render.d.ts
|
|
111
|
+
interface DomNodeLike$1 {
|
|
112
|
+
attribs?: Record<string, string>;
|
|
113
|
+
children?: DomNodeLike$1[];
|
|
114
|
+
data?: string;
|
|
115
|
+
name?: string;
|
|
116
|
+
parent?: DomNodeLike$1 | null;
|
|
117
|
+
type?: string;
|
|
118
|
+
}
|
|
119
|
+
interface RenderedPageTree {
|
|
120
|
+
root: DomNodeLike$1;
|
|
121
|
+
wxml: string;
|
|
122
|
+
}
|
|
123
|
+
declare function renderPageTree(project: HeadlessProjectDescriptor, page: HeadlessPageInstance): RenderedPageTree;
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/view/selectors.d.ts
|
|
126
|
+
interface DomNodeLike {
|
|
127
|
+
attribs?: Record<string, string>;
|
|
128
|
+
children?: DomNodeLike[];
|
|
129
|
+
data?: string;
|
|
130
|
+
name?: string;
|
|
131
|
+
parent?: DomNodeLike | null;
|
|
132
|
+
type?: string;
|
|
133
|
+
}
|
|
134
|
+
declare function querySelectorAll(root: DomNodeLike, selector: string): DomNodeLike[];
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region src/testing/pageHandle.d.ts
|
|
137
|
+
declare class HeadlessTestingPageHandle {
|
|
138
|
+
private readonly project;
|
|
139
|
+
private readonly page;
|
|
140
|
+
constructor(project: HeadlessProjectDescriptor, page: HeadlessPageInstance);
|
|
141
|
+
callMethod(methodName: string, ...args: any[]): Promise<any>;
|
|
142
|
+
data(path?: string): Promise<any>;
|
|
143
|
+
waitFor(ms?: number): Promise<void>;
|
|
144
|
+
$(selector: string): Promise<HeadlessTestingNodeHandle | null>;
|
|
145
|
+
$$(selector: string): Promise<HeadlessTestingNodeHandle[]>;
|
|
146
|
+
wxml(): Promise<string>;
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region src/testing/sessionHandle.d.ts
|
|
150
|
+
declare class HeadlessTestingSessionHandle {
|
|
151
|
+
private readonly project;
|
|
152
|
+
private readonly session;
|
|
153
|
+
constructor(project: HeadlessProjectDescriptor, session: HeadlessSession);
|
|
154
|
+
close(): Promise<void>;
|
|
155
|
+
currentPage(): Promise<HeadlessTestingPageHandle | null>;
|
|
156
|
+
getCurrentPages(): Promise<HeadlessTestingPageHandle[]>;
|
|
157
|
+
reLaunch(route: string): Promise<HeadlessTestingPageHandle>;
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/testing/launch.d.ts
|
|
161
|
+
interface HeadlessTestingLaunchOptions {
|
|
162
|
+
projectPath: string;
|
|
163
|
+
}
|
|
164
|
+
declare function launch(options: HeadlessTestingLaunchOptions): Promise<HeadlessTestingSessionHandle>;
|
|
165
|
+
//#endregion
|
|
166
|
+
export { HeadlessAppDefinition, HeadlessAppInstance, HeadlessComponentDefinition, HeadlessHostLoadContext, HeadlessHostRegistries, HeadlessPageDefinition, HeadlessPageInstance, HeadlessProjectConfigFile, HeadlessProjectDescriptor, HeadlessRouteRecord, HeadlessSession, HeadlessSessionOptions, HeadlessTestingLaunchOptions, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, HeadlessWx, RenderedPageTree, createAppInstance, createHeadlessSession, createHeadlessWx, createHostRegistries, createPageInstance, launch, loadProject, querySelectorAll, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderPageTree, resolveRoutesFromAppConfig };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { normalize } from "pathe";
|
|
4
|
+
import process from "node:process";
|
|
5
|
+
import vm from "node:vm";
|
|
6
|
+
import { parseDocument } from "htmlparser2";
|
|
7
|
+
//#region src/project/resolveRoutes.ts
|
|
8
|
+
const LEADING_SLASH_RE$2 = /^\/+/;
|
|
9
|
+
const TRAILING_SLASH_RE = /\/+$/;
|
|
10
|
+
const DUPLICATE_SLASH_RE = /\/{2,}/g;
|
|
11
|
+
function normalizeSegment(value) {
|
|
12
|
+
return value.replace(LEADING_SLASH_RE$2, "").replace(TRAILING_SLASH_RE, "");
|
|
13
|
+
}
|
|
14
|
+
function pushRoute(records, seen, record) {
|
|
15
|
+
if (!record.route || seen.has(record.route)) return;
|
|
16
|
+
seen.add(record.route);
|
|
17
|
+
records.push(record);
|
|
18
|
+
}
|
|
19
|
+
function resolveRoutesFromAppConfig(config) {
|
|
20
|
+
const records = [];
|
|
21
|
+
const seen = /* @__PURE__ */ new Set();
|
|
22
|
+
if (Array.isArray(config.pages)) for (const page of config.pages) {
|
|
23
|
+
if (typeof page !== "string") continue;
|
|
24
|
+
const route = normalizeSegment(page);
|
|
25
|
+
if (!route) continue;
|
|
26
|
+
pushRoute(records, seen, {
|
|
27
|
+
kind: "page",
|
|
28
|
+
route,
|
|
29
|
+
source: "pages"
|
|
30
|
+
});
|
|
31
|
+
}
|
|
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
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return records;
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/project/loadProject.ts
|
|
53
|
+
function readJsonObject(filePath) {
|
|
54
|
+
try {
|
|
55
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
56
|
+
const value = JSON.parse(content);
|
|
57
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
58
|
+
} catch {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function resolveProjectConfigFiles(projectPath) {
|
|
63
|
+
const entries = [];
|
|
64
|
+
for (const fileName of ["project.config.json", "project.private.config.json"]) {
|
|
65
|
+
const filePath = path.resolve(projectPath, fileName);
|
|
66
|
+
const value = readJsonObject(filePath);
|
|
67
|
+
if (!value) continue;
|
|
68
|
+
entries.push({
|
|
69
|
+
filePath,
|
|
70
|
+
value
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return entries;
|
|
74
|
+
}
|
|
75
|
+
function resolveMiniprogramRoot(projectPath, configFiles) {
|
|
76
|
+
for (const configFile of [...configFiles].reverse()) {
|
|
77
|
+
const rawRoot = configFile.value.miniprogramRoot;
|
|
78
|
+
if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
|
|
79
|
+
return rawRoot.trim();
|
|
80
|
+
}
|
|
81
|
+
throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
|
|
82
|
+
}
|
|
83
|
+
function ensureFileExists(filePath, label) {
|
|
84
|
+
if (fs.existsSync(filePath)) return;
|
|
85
|
+
throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
|
|
86
|
+
}
|
|
87
|
+
function loadAppConfig(appConfigPath) {
|
|
88
|
+
const appConfig = readJsonObject(appConfigPath);
|
|
89
|
+
if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
|
|
90
|
+
return appConfig;
|
|
91
|
+
}
|
|
92
|
+
function loadProject(projectPath) {
|
|
93
|
+
const normalizedProjectPath = path.resolve(projectPath);
|
|
94
|
+
const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
|
|
95
|
+
if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
|
|
96
|
+
const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
|
|
97
|
+
const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
|
|
98
|
+
ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
|
|
99
|
+
const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
|
|
100
|
+
ensureFileExists(appConfigPath, "built app.json");
|
|
101
|
+
const appConfig = loadAppConfig(appConfigPath);
|
|
102
|
+
return {
|
|
103
|
+
appConfig,
|
|
104
|
+
appConfigPath,
|
|
105
|
+
miniprogramRoot,
|
|
106
|
+
miniprogramRootPath,
|
|
107
|
+
projectPath: normalizedProjectPath,
|
|
108
|
+
projectConfigFiles,
|
|
109
|
+
routes: resolveRoutesFromAppConfig(appConfig)
|
|
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;
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
//#region src/runtime/moduleLoader.ts
|
|
233
|
+
function createRequireNotFoundError(request, importer) {
|
|
234
|
+
return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
|
|
235
|
+
}
|
|
236
|
+
function resolveRequiredModulePath(importer, request) {
|
|
237
|
+
if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
|
|
238
|
+
const basePath = path.resolve(path.dirname(importer), request);
|
|
239
|
+
const candidates = [
|
|
240
|
+
basePath,
|
|
241
|
+
`${basePath}.js`,
|
|
242
|
+
`${basePath}.json`,
|
|
243
|
+
path.join(basePath, "index.js")
|
|
244
|
+
];
|
|
245
|
+
for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
|
|
246
|
+
throw createRequireNotFoundError(request, importer);
|
|
247
|
+
}
|
|
248
|
+
function createExecutionContext(registries, getCurrentPages, getApp) {
|
|
249
|
+
const wx = createHeadlessWx();
|
|
250
|
+
return {
|
|
251
|
+
App(definition) {
|
|
252
|
+
return registerAppDefinition(registries, definition);
|
|
253
|
+
},
|
|
254
|
+
Component(definition) {
|
|
255
|
+
return registerComponentDefinition(registries, definition);
|
|
256
|
+
},
|
|
257
|
+
Page(definition) {
|
|
258
|
+
return registerPageDefinition(registries, definition);
|
|
259
|
+
},
|
|
260
|
+
console,
|
|
261
|
+
clearTimeout,
|
|
262
|
+
getApp,
|
|
263
|
+
getCurrentPages,
|
|
264
|
+
globalThis: void 0,
|
|
265
|
+
process,
|
|
266
|
+
require: void 0,
|
|
267
|
+
setInterval,
|
|
268
|
+
setTimeout,
|
|
269
|
+
wx
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
function createModuleLoader(registries, getCurrentPages, getApp) {
|
|
273
|
+
const moduleCache = /* @__PURE__ */ new Map();
|
|
274
|
+
const executionContext = createExecutionContext(registries, getCurrentPages, getApp);
|
|
275
|
+
executionContext.globalThis = executionContext;
|
|
276
|
+
function executeModule(filePath, loadContext) {
|
|
277
|
+
const resolvedPath = path.resolve(filePath);
|
|
278
|
+
const cached = moduleCache.get(resolvedPath);
|
|
279
|
+
if (cached) return cached.exports;
|
|
280
|
+
const source = fs.readFileSync(resolvedPath, "utf8");
|
|
281
|
+
const module = { exports: {} };
|
|
282
|
+
moduleCache.set(resolvedPath, module);
|
|
283
|
+
const previousLoadContext = registries.currentLoadContext;
|
|
284
|
+
registries.currentLoadContext = loadContext;
|
|
285
|
+
const localRequire = (request) => {
|
|
286
|
+
const requiredPath = resolveRequiredModulePath(resolvedPath, request);
|
|
287
|
+
if (requiredPath.endsWith(".json")) {
|
|
288
|
+
const content = fs.readFileSync(requiredPath, "utf8");
|
|
289
|
+
return JSON.parse(content);
|
|
290
|
+
}
|
|
291
|
+
return executeModule(requiredPath, null);
|
|
292
|
+
};
|
|
293
|
+
try {
|
|
294
|
+
new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${source}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
|
|
295
|
+
return module.exports;
|
|
296
|
+
} finally {
|
|
297
|
+
registries.currentLoadContext = previousLoadContext;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
executeAppModule(filePath) {
|
|
302
|
+
executeModule(filePath, { kind: "app" });
|
|
303
|
+
if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
|
|
304
|
+
return registries.appDefinition;
|
|
305
|
+
},
|
|
306
|
+
executePageModule(filePath, route) {
|
|
307
|
+
executeModule(filePath, {
|
|
308
|
+
kind: "page",
|
|
309
|
+
route
|
|
310
|
+
});
|
|
311
|
+
const definition = registries.pages.get(route);
|
|
312
|
+
if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
|
|
313
|
+
return definition;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/runtime/session.ts
|
|
319
|
+
const LEADING_SLASH_RE$1 = /^\/+/;
|
|
320
|
+
var HeadlessSession = class {
|
|
321
|
+
project;
|
|
322
|
+
appDefinition = null;
|
|
323
|
+
appInstance = null;
|
|
324
|
+
moduleLoader;
|
|
325
|
+
registries;
|
|
326
|
+
currentPageInstance = null;
|
|
327
|
+
pages = [];
|
|
328
|
+
constructor(options) {
|
|
329
|
+
this.project = loadProject(options.projectPath);
|
|
330
|
+
this.registries = createHostRegistries();
|
|
331
|
+
this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp());
|
|
332
|
+
}
|
|
333
|
+
getApp() {
|
|
334
|
+
return this.appInstance;
|
|
335
|
+
}
|
|
336
|
+
getCurrentPages() {
|
|
337
|
+
return this.pages.slice();
|
|
338
|
+
}
|
|
339
|
+
bootstrap() {
|
|
340
|
+
if (this.appInstance) return this.appInstance;
|
|
341
|
+
const appModulePath = path.resolve(this.project.miniprogramRootPath, "app.js");
|
|
342
|
+
this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
|
|
343
|
+
this.appInstance = createAppInstance(this.appDefinition);
|
|
344
|
+
this.appInstance.onLaunch?.();
|
|
345
|
+
this.appInstance.onShow?.();
|
|
346
|
+
return this.appInstance;
|
|
347
|
+
}
|
|
348
|
+
reLaunch(route) {
|
|
349
|
+
this.bootstrap();
|
|
350
|
+
const normalizedRoute = route.replace(LEADING_SLASH_RE$1, "");
|
|
351
|
+
const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
|
|
352
|
+
if (!routeRecord) throw new Error(`Unknown route for headless runtime reLaunch(): ${route}`);
|
|
353
|
+
if (this.currentPageInstance) {
|
|
354
|
+
this.currentPageInstance.onHide?.();
|
|
355
|
+
this.currentPageInstance.onUnload?.();
|
|
356
|
+
this.pages.length = 0;
|
|
357
|
+
this.currentPageInstance = null;
|
|
358
|
+
}
|
|
359
|
+
const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${routeRecord.route}.js`);
|
|
360
|
+
const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, routeRecord.route);
|
|
361
|
+
const pageInstance = createPageInstance(`/${routeRecord.route}`, pageDefinition);
|
|
362
|
+
this.pages.push(pageInstance);
|
|
363
|
+
this.currentPageInstance = pageInstance;
|
|
364
|
+
pageInstance.onLoad?.();
|
|
365
|
+
pageInstance.onShow?.();
|
|
366
|
+
pageInstance.onReady?.();
|
|
367
|
+
return pageInstance;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
function createHeadlessSession(options) {
|
|
371
|
+
return new HeadlessSession(options);
|
|
372
|
+
}
|
|
373
|
+
//#endregion
|
|
374
|
+
//#region src/view/selectors.ts
|
|
375
|
+
const WHITESPACE_RE = /\s+/;
|
|
376
|
+
const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
|
|
377
|
+
function getClassList(node) {
|
|
378
|
+
return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
|
|
379
|
+
}
|
|
380
|
+
function matchesSimpleSelector(node, selector) {
|
|
381
|
+
if (node.type !== "tag") return false;
|
|
382
|
+
if (selector === "page") return node.name === "page";
|
|
383
|
+
if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
|
|
384
|
+
if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
|
|
385
|
+
const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE);
|
|
386
|
+
if (dataAttrMatch) {
|
|
387
|
+
const [, key, value] = dataAttrMatch;
|
|
388
|
+
return node.attribs?.[`data-${key}`] === value;
|
|
389
|
+
}
|
|
390
|
+
return node.name === selector;
|
|
391
|
+
}
|
|
392
|
+
function collectDescendants(node, into) {
|
|
393
|
+
for (const child of node.children ?? []) {
|
|
394
|
+
into.push(child);
|
|
395
|
+
collectDescendants(child, into);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function querySelectorAll(root, selector) {
|
|
399
|
+
const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
|
|
400
|
+
if (parts.length === 0) return [];
|
|
401
|
+
let current = [root];
|
|
402
|
+
for (const part of parts) {
|
|
403
|
+
const next = [];
|
|
404
|
+
for (const node of current) {
|
|
405
|
+
const candidates = [];
|
|
406
|
+
if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
|
|
407
|
+
collectDescendants(node, candidates);
|
|
408
|
+
for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
|
|
409
|
+
}
|
|
410
|
+
current = next;
|
|
411
|
+
}
|
|
412
|
+
return current;
|
|
413
|
+
}
|
|
414
|
+
//#endregion
|
|
415
|
+
//#region src/view/nodeHandle.ts
|
|
416
|
+
function escapeText$1(text) {
|
|
417
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
418
|
+
}
|
|
419
|
+
function escapeAttribute$1(value) {
|
|
420
|
+
return escapeText$1(value).replaceAll("\"", """);
|
|
421
|
+
}
|
|
422
|
+
function serializeNode(node) {
|
|
423
|
+
if (node.type === "text") return escapeText$1(node.data ?? "");
|
|
424
|
+
if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
|
|
425
|
+
if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
|
|
426
|
+
const attrs = Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$1(value)}"`).join("");
|
|
427
|
+
const children = (node.children ?? []).map(serializeNode).join("");
|
|
428
|
+
return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
|
|
429
|
+
}
|
|
430
|
+
function collectText(node) {
|
|
431
|
+
if (node.type === "text") return node.data ?? "";
|
|
432
|
+
return (node.children ?? []).map(collectText).join("");
|
|
433
|
+
}
|
|
434
|
+
var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
|
|
435
|
+
constructor(node) {
|
|
436
|
+
this.node = node;
|
|
437
|
+
}
|
|
438
|
+
async $(selector) {
|
|
439
|
+
const match = querySelectorAll(this.node, selector)[0];
|
|
440
|
+
return match ? new HeadlessTestingNodeHandle(match) : null;
|
|
441
|
+
}
|
|
442
|
+
async $$(selector) {
|
|
443
|
+
return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node));
|
|
444
|
+
}
|
|
445
|
+
async attr(name) {
|
|
446
|
+
return this.node.attribs?.[name];
|
|
447
|
+
}
|
|
448
|
+
async dataset() {
|
|
449
|
+
const dataset = {};
|
|
450
|
+
for (const [key, value] of Object.entries(this.node.attribs ?? {})) if (key.startsWith("data-")) dataset[key.slice(5)] = value;
|
|
451
|
+
return dataset;
|
|
452
|
+
}
|
|
453
|
+
async text() {
|
|
454
|
+
return collectText(this.node);
|
|
455
|
+
}
|
|
456
|
+
async wxml() {
|
|
457
|
+
return serializeNode(this.node);
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
//#endregion
|
|
461
|
+
//#region src/view/render.ts
|
|
462
|
+
const LEADING_SLASH_RE = /^\/+/;
|
|
463
|
+
const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
|
|
464
|
+
function resolveValueByPath(source, expression) {
|
|
465
|
+
const normalized = expression.trim();
|
|
466
|
+
if (!normalized) return "";
|
|
467
|
+
const segments = normalized.split(".").filter(Boolean);
|
|
468
|
+
let current = source;
|
|
469
|
+
for (const segment of segments) current = current?.[segment];
|
|
470
|
+
return current ?? "";
|
|
471
|
+
}
|
|
472
|
+
function interpolateTemplate(input, data) {
|
|
473
|
+
return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
|
|
474
|
+
const value = resolveValueByPath(data, expression);
|
|
475
|
+
return typeof value === "string" ? value : String(value);
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
function visitDom(node, visitor) {
|
|
479
|
+
visitor(node);
|
|
480
|
+
for (const child of node.children ?? []) visitDom(child, visitor);
|
|
481
|
+
}
|
|
482
|
+
function interpolateDomTree(root, data) {
|
|
483
|
+
visitDom(root, (node) => {
|
|
484
|
+
if (typeof node.data === "string") node.data = interpolateTemplate(node.data, data);
|
|
485
|
+
if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate(value, data);
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
function escapeText(text) {
|
|
489
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
490
|
+
}
|
|
491
|
+
function escapeAttribute(value) {
|
|
492
|
+
return escapeText(value).replaceAll("\"", """);
|
|
493
|
+
}
|
|
494
|
+
function serializeDomNode(node) {
|
|
495
|
+
if (node.type === "text") return escapeText(node.data ?? "");
|
|
496
|
+
if (node.type === "root") return (node.children ?? []).map(serializeDomNode).join("");
|
|
497
|
+
const tagName = node.name ?? "";
|
|
498
|
+
if (!tagName) return (node.children ?? []).map(serializeDomNode).join("");
|
|
499
|
+
return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
|
|
500
|
+
}
|
|
501
|
+
function renderPageTree(project, page) {
|
|
502
|
+
const route = page.route.replace(LEADING_SLASH_RE, "");
|
|
503
|
+
const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
|
|
504
|
+
const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
|
|
505
|
+
xmlMode: false,
|
|
506
|
+
decodeEntities: false,
|
|
507
|
+
recognizeSelfClosing: true
|
|
508
|
+
});
|
|
509
|
+
interpolateDomTree(document, page.data);
|
|
510
|
+
return {
|
|
511
|
+
root: document,
|
|
512
|
+
wxml: serializeDomNode((document.children ?? [])[0] ?? document)
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
//#endregion
|
|
516
|
+
//#region src/testing/pageHandle.ts
|
|
517
|
+
var HeadlessTestingPageHandle = class {
|
|
518
|
+
constructor(project, page) {
|
|
519
|
+
this.project = project;
|
|
520
|
+
this.page = page;
|
|
521
|
+
}
|
|
522
|
+
async callMethod(methodName, ...args) {
|
|
523
|
+
const method = this.page[methodName];
|
|
524
|
+
if (typeof method !== "function") throw new Error(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
|
|
525
|
+
return await method.apply(this.page, args);
|
|
526
|
+
}
|
|
527
|
+
async data(path) {
|
|
528
|
+
if (!path) return this.page.data;
|
|
529
|
+
const segments = path.split(".").filter(Boolean);
|
|
530
|
+
let current = this.page.data;
|
|
531
|
+
for (const segment of segments) current = current?.[segment];
|
|
532
|
+
return current;
|
|
533
|
+
}
|
|
534
|
+
async waitFor(ms = 0) {
|
|
535
|
+
if (ms <= 0) return;
|
|
536
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
537
|
+
}
|
|
538
|
+
async $(selector) {
|
|
539
|
+
const tree = renderPageTree(this.project, this.page);
|
|
540
|
+
const root = new HeadlessTestingNodeHandle(tree.root.children?.[0] ?? tree.root);
|
|
541
|
+
if (selector === "page") return root;
|
|
542
|
+
return await root.$(selector);
|
|
543
|
+
}
|
|
544
|
+
async $$(selector) {
|
|
545
|
+
const root = await this.$("page");
|
|
546
|
+
if (!root) return [];
|
|
547
|
+
if (selector === "page") return [root];
|
|
548
|
+
return await root.$$(selector);
|
|
549
|
+
}
|
|
550
|
+
async wxml() {
|
|
551
|
+
return renderPageTree(this.project, this.page).wxml;
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
//#endregion
|
|
555
|
+
//#region src/testing/sessionHandle.ts
|
|
556
|
+
var HeadlessTestingSessionHandle = class {
|
|
557
|
+
constructor(project, session) {
|
|
558
|
+
this.project = project;
|
|
559
|
+
this.session = session;
|
|
560
|
+
}
|
|
561
|
+
async close() {}
|
|
562
|
+
async currentPage() {
|
|
563
|
+
const current = this.session.getCurrentPages().at(-1);
|
|
564
|
+
return current ? new HeadlessTestingPageHandle(this.project, current) : null;
|
|
565
|
+
}
|
|
566
|
+
async getCurrentPages() {
|
|
567
|
+
return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page));
|
|
568
|
+
}
|
|
569
|
+
async reLaunch(route) {
|
|
570
|
+
const page = this.session.reLaunch(route);
|
|
571
|
+
return new HeadlessTestingPageHandle(this.project, page);
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
//#endregion
|
|
575
|
+
//#region src/testing/launch.ts
|
|
576
|
+
async function launch(options) {
|
|
577
|
+
const session = createHeadlessSession({ projectPath: options.projectPath });
|
|
578
|
+
session.bootstrap();
|
|
579
|
+
return new HeadlessTestingSessionHandle(session.project, session);
|
|
580
|
+
}
|
|
581
|
+
//#endregion
|
|
582
|
+
export { HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, createAppInstance, createHeadlessSession, createHeadlessWx, createHostRegistries, createPageInstance, launch, loadProject, querySelectorAll, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderPageTree, resolveRoutesFromAppConfig };
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mpcore/simulator",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.0",
|
|
5
|
+
"description": "Headless mini-program runtime and testing kernel for the weapp-vite ecosystem",
|
|
6
|
+
"author": "ice breaker <1324318532@qq.com>",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/weapp-vite/weapp-vite.git",
|
|
11
|
+
"directory": "mpcore/packages/simulator"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/weapp-vite/weapp-vite/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"weapp",
|
|
18
|
+
"mini-program",
|
|
19
|
+
"runtime",
|
|
20
|
+
"headless",
|
|
21
|
+
"testing"
|
|
22
|
+
],
|
|
23
|
+
"sideEffects": false,
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.mjs"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.mjs",
|
|
31
|
+
"module": "./dist/index.mjs",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"files": [
|
|
34
|
+
"README.md",
|
|
35
|
+
"dist"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"dev": "tsdown -w",
|
|
42
|
+
"build": "tsdown",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:dev": "vitest",
|
|
45
|
+
"typecheck": "tsc --noEmit"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"htmlparser2": "catalog:",
|
|
49
|
+
"pathe": "catalog:"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public",
|
|
53
|
+
"registry": "https://registry.npmjs.org"
|
|
54
|
+
}
|
|
55
|
+
}
|