@dimina-kit/compiler 0.0.1-dev.20260702173719

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.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/compile-core.browser.js +281945 -0
  4. package/dist/compile-core.node.js +3702 -0
  5. package/dist/pool.browser.js +99 -0
  6. package/dist/pool.node.js +3743 -0
  7. package/dist/stage-worker.browser.js +291085 -0
  8. package/dist/stage-worker.node.js +3097 -0
  9. package/dist/toolchain.browser.js +30 -0
  10. package/package.json +87 -0
  11. package/scripts/build-compiler.js +207 -0
  12. package/scripts/gen-bench-fixture.js +24 -0
  13. package/scripts/kit-resolve-hook.js +35 -0
  14. package/scripts/register-kit.js +2 -0
  15. package/scripts/test-appid-fallback.js +114 -0
  16. package/scripts/test-decompose.js +90 -0
  17. package/scripts/test-hardening.js +78 -0
  18. package/scripts/test-node.js +69 -0
  19. package/scripts/test-npm-scan.js +164 -0
  20. package/scripts/test-pool-hardening.js +65 -0
  21. package/scripts/test-pool-node.js +117 -0
  22. package/scripts/test-realm-reuse.js +77 -0
  23. package/src/browser-entry.js +25 -0
  24. package/src/compile-core.js +428 -0
  25. package/src/pool-node.js +170 -0
  26. package/src/pool.js +122 -0
  27. package/src/shims/esbuild-wasm.js +19 -0
  28. package/src/shims/fs-promises.js +20 -0
  29. package/src/shims/fs.js +59 -0
  30. package/src/shims/less.js +9 -0
  31. package/src/shims/os.js +11 -0
  32. package/src/shims/oxc-parser.js +21 -0
  33. package/src/shims/oxc-walker.js +29 -0
  34. package/src/shims/postcss-noop-plugin.js +9 -0
  35. package/src/shims/process.js +20 -0
  36. package/src/shims/url.js +4 -0
  37. package/src/shims/worker_threads.js +10 -0
  38. package/src/stage-worker-node.js +41 -0
  39. package/src/stage-worker.js +88 -0
  40. package/src/toolchain.js +49 -0
@@ -0,0 +1,3702 @@
1
+ // src/shims/fs.js
2
+ var current = null;
3
+ function setFs(impl) {
4
+ current = impl;
5
+ }
6
+ function resetFs() {
7
+ current = null;
8
+ }
9
+ var call = (name) => (...args) => {
10
+ if (!current) throw new Error("[compiler] no fs backend injected \u2014 call compileMiniApp({ fs })");
11
+ const fn = current[name];
12
+ if (typeof fn === "function") return fn.apply(current, args);
13
+ throw new Error(`[compiler] injected fs is missing ${name}()`);
14
+ };
15
+ var existsSync = call("existsSync");
16
+ var readFileSync = call("readFileSync");
17
+ var writeFileSync = call("writeFileSync");
18
+ var mkdirSync = call("mkdirSync");
19
+ var rmSync = call("rmSync");
20
+ var rmdirSync = call("rmdirSync");
21
+ var readdirSync = call("readdirSync");
22
+ var copyFileSync = call("copyFileSync");
23
+ var statSync = call("statSync");
24
+ var lstatSync = call("lstatSync");
25
+ var unlinkSync = call("unlinkSync");
26
+ var renameSync = call("renameSync");
27
+ var appendFileSync = call("appendFileSync");
28
+ var realpathSync = call("realpathSync");
29
+ var accessSync = call("accessSync");
30
+ var readlinkSync = call("readlinkSync");
31
+ var watch = call("watch");
32
+ var promises = new Proxy({}, {
33
+ get: (_t, prop) => (...args) => {
34
+ if (!current || !current.promises || typeof current.promises[prop] !== "function") {
35
+ throw new Error(`[compiler] injected fs has no promises.${String(prop)}()`);
36
+ }
37
+ return current.promises[prop](...args);
38
+ }
39
+ });
40
+ var fs = {
41
+ existsSync,
42
+ readFileSync,
43
+ writeFileSync,
44
+ mkdirSync,
45
+ rmSync,
46
+ rmdirSync,
47
+ readdirSync,
48
+ copyFileSync,
49
+ statSync,
50
+ lstatSync,
51
+ unlinkSync,
52
+ renameSync,
53
+ appendFileSync,
54
+ realpathSync,
55
+ accessSync,
56
+ readlinkSync,
57
+ watch,
58
+ promises
59
+ };
60
+ var fs_default = fs;
61
+
62
+ // ../../dimina/fe/packages/compiler/src/env.js
63
+ import os from "node:os";
64
+ import path4 from "node:path";
65
+ import process2 from "node:process";
66
+
67
+ // ../../dimina/fe/packages/compiler/src/common/path-utils.js
68
+ import path from "node:path";
69
+ var WINDOWS_FS_PATH_RE = /^(?:[a-zA-Z]:[\\/]|\\\\)/;
70
+ function isWindowsFsPath(targetPath) {
71
+ return typeof targetPath === "string" && (WINDOWS_FS_PATH_RE.test(targetPath) || targetPath.includes("\\"));
72
+ }
73
+ function getFsPathApi(targetPath) {
74
+ return isWindowsFsPath(targetPath) ? path.win32 : path.posix;
75
+ }
76
+ function normalizeToPosixPath(targetPath) {
77
+ return targetPath.replace(/\\/g, "/");
78
+ }
79
+ function resolveMiniProgramPath(workPath, importerPath, sourcePath) {
80
+ const pathApi = getFsPathApi(importerPath || workPath);
81
+ return sourcePath.startsWith("/") ? pathApi.join(workPath, sourcePath) : pathApi.resolve(pathApi.dirname(importerPath), sourcePath);
82
+ }
83
+ function toMiniProgramModuleId(resolvedPath, workPath) {
84
+ const normalizedResolvedPath = normalizeToPosixPath(resolvedPath);
85
+ const normalizedWorkPath = normalizeToPosixPath(workPath);
86
+ let moduleId = normalizedResolvedPath.startsWith(normalizedWorkPath) ? normalizedResolvedPath.slice(normalizedWorkPath.length) : normalizedResolvedPath;
87
+ moduleId = moduleId.replace(/\/+/g, "/");
88
+ if (!moduleId.startsWith("/")) {
89
+ moduleId = `/${moduleId}`;
90
+ }
91
+ return moduleId;
92
+ }
93
+ function getRelativePosixPath(targetPath, rootPath) {
94
+ return normalizeToPosixPath(targetPath).replace(normalizeToPosixPath(rootPath), "").replace(/^\//, "");
95
+ }
96
+
97
+ // ../../dimina/fe/packages/compiler/src/common/utils.js
98
+ import path2 from "node:path";
99
+ import process from "node:process";
100
+ function hasCompileInfo(modulePath, list, preList) {
101
+ const mergeList = Array.isArray(preList) ? [...preList, ...list] : list;
102
+ for (const element of mergeList) {
103
+ if (element.path === modulePath) {
104
+ return true;
105
+ }
106
+ }
107
+ return false;
108
+ }
109
+ function getAbsolutePath(workPath, pagePath, src) {
110
+ if (src.startsWith("/")) {
111
+ return path2.join(workPath, src);
112
+ }
113
+ if (pagePath.includes("/miniprogram_npm/")) {
114
+ const componentDir = pagePath.split("/").slice(0, -1).join("/");
115
+ const componentFullPath = workPath + componentDir;
116
+ return path2.resolve(componentFullPath, src);
117
+ }
118
+ const relativePath = pagePath.split("/").filter((part) => part !== "").slice(0, -1).join("/");
119
+ return path2.resolve(workPath, relativePath, src);
120
+ }
121
+ var assetsMap = {};
122
+ function collectAssets(workPath, pagePath, src, targetPath, appId) {
123
+ if (src.startsWith("http") || src.startsWith("//")) {
124
+ return src;
125
+ }
126
+ if (!/\.(?:png|jpe?g|gif|svg)(?:\?.*)?$/.test(src)) {
127
+ return src;
128
+ }
129
+ const relativePath = pagePath.split("/").slice(0, -1).join("/");
130
+ const absolutePath = src.startsWith("/") ? workPath + src : path2.resolve(workPath, relativePath, src);
131
+ if (assetsMap[absolutePath]) {
132
+ return assetsMap[absolutePath];
133
+ }
134
+ try {
135
+ const ext = `.${src.split(".").pop()}`;
136
+ const dirPath = absolutePath.split(path2.sep).slice(0, -1).join("/");
137
+ const prefix = uuid();
138
+ const targetStatic = `${targetPath}/main/static`;
139
+ if (!fs_default.existsSync(targetStatic)) {
140
+ fs_default.mkdirSync(targetStatic, { recursive: true });
141
+ }
142
+ getFilesWithExtension(dirPath, ext).forEach((file) => {
143
+ fs_default.copyFileSync(path2.resolve(dirPath, file), `${targetStatic}/${prefix}_${file}`);
144
+ });
145
+ const filename = src.split("/").pop();
146
+ const pathPrefix = process.env.ASSETS_PATH_PREFIX ? "" : "/";
147
+ assetsMap[absolutePath] = `${pathPrefix}${appId}/main/static/${prefix}_${filename}`;
148
+ } catch (error) {
149
+ console.log(error);
150
+ }
151
+ return assetsMap[absolutePath] || src;
152
+ }
153
+ function getFilesWithExtension(directory, extension) {
154
+ const files = fs_default.readdirSync(directory);
155
+ const filteredFiles = files.filter((file) => path2.extname(file) === extension);
156
+ return filteredFiles;
157
+ }
158
+ function isObjectEmpty(objectName) {
159
+ if (!objectName) {
160
+ return true;
161
+ }
162
+ return Object.keys(objectName).length === 0 && objectName.constructor === Object;
163
+ }
164
+ function isString(o) {
165
+ return Object.prototype.toString.call(o) === "[object String]";
166
+ }
167
+ function transformRpx(styleText) {
168
+ if (!isString(styleText)) {
169
+ return styleText;
170
+ }
171
+ return styleText.replace(/([+-]?\d+(?:\.\d+)?)rpx/g, (_, pixel) => {
172
+ return `${Number(pixel)}rem`;
173
+ });
174
+ }
175
+ function uuid() {
176
+ return Math.random().toString(36).slice(2, 7);
177
+ }
178
+ var tagWhiteList = [
179
+ "page",
180
+ "wrapper",
181
+ "block",
182
+ "button",
183
+ "camera",
184
+ "checkbox-group",
185
+ "checkbox",
186
+ "cover-image",
187
+ "cover-view",
188
+ "form",
189
+ "icon",
190
+ "image",
191
+ "input",
192
+ "keyboard-accessory",
193
+ "label",
194
+ "map",
195
+ "movable-area",
196
+ "movable-view",
197
+ "navigation-bar",
198
+ "navigator",
199
+ "open-data",
200
+ "page-meta",
201
+ "picker-view-column",
202
+ "picker-view",
203
+ "picker",
204
+ "progress",
205
+ "radio-group",
206
+ "radio",
207
+ "rich-text",
208
+ "root-portal",
209
+ "scroll-view",
210
+ "slider",
211
+ "swiper-item",
212
+ "swiper",
213
+ "switch",
214
+ "template",
215
+ "text",
216
+ "textarea",
217
+ "video",
218
+ "view",
219
+ "web-view"
220
+ ];
221
+ function __resetAssets() {
222
+ for (const k of Object.keys(assetsMap)) delete assetsMap[k];
223
+ }
224
+
225
+ // ../../dimina/fe/packages/compiler/src/common/npm-resolver.js
226
+ import path3 from "node:path";
227
+ var NpmResolver = class {
228
+ constructor(workPath) {
229
+ this.workPath = workPath;
230
+ this.miniprogramNpmCache = /* @__PURE__ */ new Map();
231
+ this.packageCache = /* @__PURE__ */ new Map();
232
+ }
233
+ /**
234
+ * 解析组件路径,支持 npm 包组件
235
+ * @param {string} componentPath 组件路径
236
+ * @param {string} pageFilePath 页面文件路径
237
+ * @returns {string} 解析后的组件路径
238
+ */
239
+ resolveComponentPath(componentPath, pageFilePath) {
240
+ if (componentPath.startsWith("./") || componentPath.startsWith("../") || componentPath.startsWith("/")) {
241
+ return this.resolveRelativePath(componentPath, pageFilePath);
242
+ }
243
+ const npmPath = this.resolveNpmComponent(componentPath, pageFilePath);
244
+ if (npmPath) {
245
+ return npmPath;
246
+ }
247
+ return this.resolveRelativePath(componentPath, pageFilePath);
248
+ }
249
+ /**
250
+ * 解析相对路径组件
251
+ * @param {string} componentPath 组件路径
252
+ * @param {string} pageFilePath 页面文件路径
253
+ * @returns {string} 解析后的路径
254
+ */
255
+ resolveRelativePath(componentPath, pageFilePath) {
256
+ return toMiniProgramModuleId(
257
+ resolveMiniProgramPath(this.workPath, pageFilePath, componentPath),
258
+ this.workPath
259
+ );
260
+ }
261
+ /**
262
+ * 解析 npm 组件
263
+ * @param {string} componentName 组件名称
264
+ * @param {string} pageFilePath 页面文件路径
265
+ * @returns {string|null} 解析后的组件路径,如果找不到返回 null
266
+ */
267
+ resolveNpmComponent(componentName, pageFilePath) {
268
+ const searchPaths = this.generateSearchPaths(pageFilePath);
269
+ for (const searchPath of searchPaths) {
270
+ const componentPath = this.findComponentInMiniprogramNpm(componentName, searchPath);
271
+ if (componentPath) {
272
+ return componentPath;
273
+ }
274
+ }
275
+ return null;
276
+ }
277
+ /**
278
+ * 解析脚本模块路径,支持微信小程序 npm 逐级寻址和 package.json 入口
279
+ * @param {string} specifier 模块导入路径
280
+ * @param {string} modulePath 当前模块绝对文件路径
281
+ * @param {(moduleId: string) => string | null} resolveExistingModuleId 解析真实存在模块的回调
282
+ * @returns {string|null} 解析后的模块 id
283
+ */
284
+ resolveScriptModule(specifier, modulePath, resolveExistingModuleId) {
285
+ if (!specifier || !resolveExistingModuleId) {
286
+ return null;
287
+ }
288
+ for (const searchPath of this.generateSearchPaths(modulePath)) {
289
+ const moduleId = this.normalizeModuleId(`/${searchPath}/${specifier}`);
290
+ const resolvedModuleId = resolveExistingModuleId(moduleId);
291
+ if (resolvedModuleId) {
292
+ return resolvedModuleId;
293
+ }
294
+ }
295
+ return null;
296
+ }
297
+ /**
298
+ * 生成 miniprogram_npm 搜索路径
299
+ * 按照微信小程序的寻址顺序生成搜索路径
300
+ * @param {string} pageFilePath 页面文件路径
301
+ * @returns {string[]} 搜索路径数组
302
+ */
303
+ generateSearchPaths(pageFilePath) {
304
+ const relativePath = getRelativePosixPath(pageFilePath, this.workPath);
305
+ const pathParts = relativePath.split("/").slice(0, -1);
306
+ const searchPaths = [];
307
+ for (let i = pathParts.length; i >= 0; i--) {
308
+ const currentPath = pathParts.slice(0, i).join("/");
309
+ const miniprogramNpmPath = currentPath ? `${currentPath}/miniprogram_npm` : "miniprogram_npm";
310
+ searchPaths.push(miniprogramNpmPath);
311
+ }
312
+ return searchPaths;
313
+ }
314
+ /**
315
+ * 在指定的 miniprogram_npm 目录中查找组件
316
+ * @param {string} componentName 组件名称
317
+ * @param {string} miniprogramNpmPath miniprogram_npm 路径
318
+ * @returns {string|null} 组件路径,如果找不到返回 null
319
+ */
320
+ findComponentInMiniprogramNpm(componentName, miniprogramNpmPath) {
321
+ const fullMiniprogramNpmPath = path3.join(this.workPath, miniprogramNpmPath);
322
+ if (!fs_default.existsSync(fullMiniprogramNpmPath)) {
323
+ return null;
324
+ }
325
+ const cacheKey = `${miniprogramNpmPath}/${componentName}`;
326
+ if (this.miniprogramNpmCache.has(cacheKey)) {
327
+ return this.miniprogramNpmCache.get(cacheKey);
328
+ }
329
+ const candidatePaths = [
330
+ componentName,
331
+ `${componentName}/index`
332
+ ];
333
+ for (const candidatePath of candidatePaths) {
334
+ const componentDir = path3.join(fullMiniprogramNpmPath, candidatePath);
335
+ if (this.isValidComponent(componentDir)) {
336
+ const resolvedPath = `/${miniprogramNpmPath}/${candidatePath}`.replace(/\/+/g, "/");
337
+ this.miniprogramNpmCache.set(cacheKey, resolvedPath);
338
+ return resolvedPath;
339
+ }
340
+ }
341
+ this.miniprogramNpmCache.set(cacheKey, null);
342
+ return null;
343
+ }
344
+ normalizeModuleId(moduleId) {
345
+ let normalized = moduleId.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
346
+ if (!normalized.startsWith("/")) {
347
+ normalized = `/${normalized}`;
348
+ }
349
+ return normalized;
350
+ }
351
+ /**
352
+ * 检查是否为有效的组件
353
+ * @param {string} componentPath 组件路径
354
+ * @returns {boolean} 是否为有效组件
355
+ */
356
+ isValidComponent(componentPath) {
357
+ const requiredFiles = [".json", ".js"];
358
+ const hasRequiredFiles = requiredFiles.some((ext) => {
359
+ return fs_default.existsSync(`${componentPath}${ext}`);
360
+ });
361
+ if (!hasRequiredFiles) {
362
+ const indexFiles = requiredFiles.some((ext) => {
363
+ return fs_default.existsSync(path3.join(componentPath, `index${ext}`));
364
+ });
365
+ if (!indexFiles) {
366
+ return false;
367
+ }
368
+ const indexJsonFile = path3.join(componentPath, "index.json");
369
+ if (fs_default.existsSync(indexJsonFile)) {
370
+ try {
371
+ const config = JSON.parse(fs_default.readFileSync(indexJsonFile, "utf-8"));
372
+ return config.component === true;
373
+ } catch (e) {
374
+ return false;
375
+ }
376
+ }
377
+ return true;
378
+ }
379
+ const jsonFile = `${componentPath}.json`;
380
+ if (fs_default.existsSync(jsonFile)) {
381
+ try {
382
+ const config = JSON.parse(fs_default.readFileSync(jsonFile, "utf-8"));
383
+ return config.component === true;
384
+ } catch (e) {
385
+ return false;
386
+ }
387
+ }
388
+ return true;
389
+ }
390
+ /**
391
+ * 获取 npm 包信息
392
+ * @param {string} packageName 包名
393
+ * @param {string} searchPath 搜索路径
394
+ * @returns {object|null} 包信息,如果找不到返回 null
395
+ */
396
+ getPackageInfo(packageName, searchPath) {
397
+ const cacheKey = `${searchPath}/${packageName}`;
398
+ if (this.packageCache.has(cacheKey)) {
399
+ return this.packageCache.get(cacheKey);
400
+ }
401
+ const packageJsonPath = path3.join(this.workPath, searchPath, packageName, "package.json");
402
+ if (!fs_default.existsSync(packageJsonPath)) {
403
+ this.packageCache.set(cacheKey, null);
404
+ return null;
405
+ }
406
+ try {
407
+ const packageInfo = JSON.parse(fs_default.readFileSync(packageJsonPath, "utf-8"));
408
+ this.packageCache.set(cacheKey, packageInfo);
409
+ return packageInfo;
410
+ } catch (e) {
411
+ this.packageCache.set(cacheKey, null);
412
+ return null;
413
+ }
414
+ }
415
+ /**
416
+ * 清除缓存
417
+ */
418
+ clearCache() {
419
+ this.miniprogramNpmCache.clear();
420
+ this.packageCache.clear();
421
+ }
422
+ };
423
+
424
+ // ../../dimina/fe/packages/compiler/src/env.js
425
+ var pathInfo = {};
426
+ var configInfo = {};
427
+ var npmResolver = null;
428
+ var DEFAULT_TEMPLATE_EXTS = [".wxml", ".ddml"];
429
+ var DEFAULT_STYLE_EXTS = [".wxss", ".ddss", ".less", ".scss", ".sass"];
430
+ var DEFAULT_VIEW_SCRIPT_EXTS = [".wxs"];
431
+ var DEFAULT_VIEW_SCRIPT_TAGS = ["wxs", "dds"];
432
+ var RESERVED_EXTS = /* @__PURE__ */ new Set([
433
+ ...DEFAULT_TEMPLATE_EXTS,
434
+ ...DEFAULT_STYLE_EXTS,
435
+ ...DEFAULT_VIEW_SCRIPT_EXTS,
436
+ ".js",
437
+ ".ts",
438
+ ".json"
439
+ ]);
440
+ var compilerOptions = normalizeFileTypes();
441
+ function normalizeExt(raw) {
442
+ if (typeof raw !== "string") {
443
+ return null;
444
+ }
445
+ const v = raw.trim().toLowerCase().replace(/^\.+/, "");
446
+ if (!/^[a-z0-9_-]+$/.test(v)) {
447
+ return null;
448
+ }
449
+ return `.${v}`;
450
+ }
451
+ function normalizeTag(raw) {
452
+ if (typeof raw !== "string") {
453
+ return null;
454
+ }
455
+ const v = raw.trim().toLowerCase().replace(/^\.+/, "");
456
+ if (!/^[a-z][a-z0-9_-]*$/.test(v)) {
457
+ return null;
458
+ }
459
+ return v;
460
+ }
461
+ function mergeUnique(builtins, custom, normalizer, reserved) {
462
+ const out = [...builtins];
463
+ const seen = new Set(builtins);
464
+ if (Array.isArray(custom)) {
465
+ for (const raw of custom) {
466
+ const n = normalizer(raw);
467
+ if (n && !seen.has(n) && !reserved?.has(n)) {
468
+ seen.add(n);
469
+ out.push(n);
470
+ }
471
+ }
472
+ }
473
+ return out;
474
+ }
475
+ function normalizeFileTypes(fileTypes = {}) {
476
+ const ft = fileTypes || {};
477
+ return {
478
+ templateExts: mergeUnique(DEFAULT_TEMPLATE_EXTS, ft.template, normalizeExt, RESERVED_EXTS),
479
+ styleExts: mergeUnique(DEFAULT_STYLE_EXTS, ft.style, normalizeExt, RESERVED_EXTS),
480
+ viewScriptExts: mergeUnique(DEFAULT_VIEW_SCRIPT_EXTS, ft.viewScript, normalizeExt, RESERVED_EXTS),
481
+ viewScriptTags: mergeUnique(DEFAULT_VIEW_SCRIPT_TAGS, ft.viewScript, normalizeTag)
482
+ };
483
+ }
484
+ function storeInfo(workPath, options = {}) {
485
+ storePathInfo(workPath);
486
+ storeProjectConfig();
487
+ storeAppConfig();
488
+ storePageConfig();
489
+ compilerOptions = normalizeFileTypes(options.fileTypes);
490
+ return {
491
+ pathInfo,
492
+ configInfo,
493
+ compilerOptions
494
+ };
495
+ }
496
+ function resetStoreInfo(opts) {
497
+ pathInfo = opts.pathInfo;
498
+ configInfo = opts.configInfo;
499
+ compilerOptions = opts.compilerOptions || normalizeFileTypes();
500
+ if (pathInfo.workPath) {
501
+ npmResolver = new NpmResolver(pathInfo.workPath);
502
+ }
503
+ }
504
+ function getTemplateExts() {
505
+ return compilerOptions.templateExts;
506
+ }
507
+ function getStyleExts() {
508
+ return compilerOptions.styleExts;
509
+ }
510
+ function getViewScriptExts() {
511
+ return compilerOptions.viewScriptExts;
512
+ }
513
+ function getViewScriptTags() {
514
+ return compilerOptions.viewScriptTags;
515
+ }
516
+ function storePathInfo(workPath) {
517
+ pathInfo.workPath = workPath;
518
+ if (process2.env.TARGET_PATH) {
519
+ pathInfo.targetPath = process2.env.TARGET_PATH;
520
+ } else {
521
+ const tempDir = process2.env.GITHUB_WORKSPACE || os.tmpdir();
522
+ const targetDir = path4.join(tempDir, `dimina-fe-dist-${Date.now()}`);
523
+ if (!fs_default.existsSync(targetDir)) {
524
+ fs_default.mkdirSync(targetDir, { recursive: true });
525
+ }
526
+ pathInfo.targetPath = targetDir;
527
+ }
528
+ npmResolver = new NpmResolver(workPath);
529
+ }
530
+ function storeProjectConfig() {
531
+ const privateConfigPath = `${pathInfo.workPath}/project.private.config.json`;
532
+ const defaultConfigPath = `${pathInfo.workPath}/project.config.json`;
533
+ let privateConfig = {};
534
+ let defaultConfig = {};
535
+ if (fs_default.existsSync(defaultConfigPath)) {
536
+ try {
537
+ defaultConfig = parseContentByPath(defaultConfigPath);
538
+ } catch (e) {
539
+ console.warn("Failed to parse project.config.json:", e.message);
540
+ }
541
+ }
542
+ if (fs_default.existsSync(privateConfigPath)) {
543
+ try {
544
+ privateConfig = parseContentByPath(privateConfigPath);
545
+ } catch (e) {
546
+ console.warn("Failed to parse project.private.config.json:", e.message);
547
+ }
548
+ }
549
+ configInfo.projectInfo = { ...defaultConfig, ...privateConfig };
550
+ }
551
+ function storeAppConfig() {
552
+ const filePath = `${pathInfo.workPath}/app.json`;
553
+ const content = parseContentByPath(filePath);
554
+ const newObj = {};
555
+ for (const key in content) {
556
+ if (Object.prototype.hasOwnProperty.call(content, key)) {
557
+ if (key === "subpackages") {
558
+ newObj.subPackages = content[key];
559
+ } else {
560
+ newObj[key] = content[key];
561
+ }
562
+ }
563
+ }
564
+ configInfo.appInfo = newObj;
565
+ }
566
+ function getContentByPath(path8) {
567
+ return fs_default.readFileSync(path8, { encoding: "utf-8" });
568
+ }
569
+ function parseContentByPath(path8) {
570
+ return JSON.parse(getContentByPath(path8));
571
+ }
572
+ function storePageConfig() {
573
+ const { pages, subPackages } = configInfo.appInfo;
574
+ configInfo.pageInfo = {};
575
+ configInfo.componentInfo = {};
576
+ if (configInfo.appInfo.usingComponents) {
577
+ const appFilePath = `${pathInfo.workPath}/app.json`;
578
+ storeComponentConfig(configInfo.appInfo, appFilePath);
579
+ }
580
+ collectionPageJson(pages);
581
+ if (subPackages) {
582
+ subPackages.forEach((subPkg) => {
583
+ collectionPageJson(subPkg.pages, subPkg.root);
584
+ });
585
+ }
586
+ }
587
+ function collectionPageJson(pages, root) {
588
+ pages.forEach((pagePath) => {
589
+ let np = pagePath;
590
+ if (root) {
591
+ if (!root.endsWith("/")) {
592
+ root += "/";
593
+ }
594
+ np = root + np;
595
+ }
596
+ const pageFilePath = `${pathInfo.workPath}/${np}.json`;
597
+ if (fs_default.existsSync(pageFilePath)) {
598
+ const pageJsonContent = parseContentByPath(pageFilePath);
599
+ if (root) {
600
+ pageJsonContent.root = transSubDir(root);
601
+ }
602
+ configInfo.pageInfo[np] = pageJsonContent;
603
+ storeComponentConfig(pageJsonContent, pageFilePath);
604
+ }
605
+ });
606
+ }
607
+ function storeComponentConfig(pageJsonContent, pageFilePath) {
608
+ if (isObjectEmpty(pageJsonContent.usingComponents)) {
609
+ return;
610
+ }
611
+ for (const [componentName, componentPath] of Object.entries(pageJsonContent.usingComponents)) {
612
+ const moduleId = getModuleId(componentPath, pageFilePath);
613
+ pageJsonContent.usingComponents[componentName] = moduleId;
614
+ if (configInfo.componentInfo[moduleId]) {
615
+ continue;
616
+ }
617
+ let componentFilePath = path4.resolve(getWorkPath(), `./${moduleId}.json`);
618
+ let cContent = null;
619
+ if (fs_default.existsSync(componentFilePath)) {
620
+ cContent = parseContentByPath(componentFilePath);
621
+ } else {
622
+ const indexJsonPath = path4.resolve(getWorkPath(), `./${moduleId}/index.json`);
623
+ if (fs_default.existsSync(indexJsonPath)) {
624
+ componentFilePath = indexJsonPath;
625
+ cContent = parseContentByPath(componentFilePath);
626
+ } else {
627
+ if (moduleId.includes("/miniprogram_npm/")) {
628
+ console.log(`[env] \u4E3A npm \u7EC4\u4EF6\u521B\u5EFA\u9ED8\u8BA4\u914D\u7F6E: ${moduleId}`);
629
+ cContent = {
630
+ component: true,
631
+ usingComponents: {}
632
+ };
633
+ } else {
634
+ console.warn(`[env] \u7EC4\u4EF6\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728: ${componentFilePath}`);
635
+ continue;
636
+ }
637
+ }
638
+ }
639
+ const cUsing = cContent.usingComponents || {};
640
+ const isComponent = cContent.component || false;
641
+ const cComponents = Object.keys(cUsing).reduce((acc, key) => {
642
+ acc[key] = getModuleId(cUsing[key], componentFilePath);
643
+ return acc;
644
+ }, {});
645
+ configInfo.componentInfo[moduleId] = {
646
+ id: uuid(),
647
+ path: moduleId,
648
+ component: isComponent,
649
+ usingComponents: cComponents
650
+ };
651
+ if (cContent.usingComponents && Object.keys(cContent.usingComponents).length > 0) {
652
+ storeComponentConfig(configInfo.componentInfo[moduleId], componentFilePath);
653
+ }
654
+ }
655
+ }
656
+ function getModuleId(src, pageFilePath) {
657
+ const resolvedAlias = resolveAppAlias(src);
658
+ if (resolvedAlias) {
659
+ return resolvedAlias;
660
+ }
661
+ if (!npmResolver) {
662
+ const workPath = getWorkPath();
663
+ return toMiniProgramModuleId(
664
+ resolveMiniProgramPath(workPath, pageFilePath, src),
665
+ workPath
666
+ );
667
+ }
668
+ return npmResolver.resolveComponentPath(src, pageFilePath);
669
+ }
670
+ function resolveAppAlias(src) {
671
+ const resolveAlias = configInfo.appInfo?.resolveAlias;
672
+ if (!resolveAlias || typeof src !== "string") {
673
+ return null;
674
+ }
675
+ for (const [alias, target] of Object.entries(resolveAlias)) {
676
+ if (alias.endsWith("/*") && target.endsWith("/*")) {
677
+ const aliasPrefix = alias.slice(0, -1);
678
+ const targetPrefix = target.slice(0, -1);
679
+ if (src.startsWith(aliasPrefix)) {
680
+ return src.replace(aliasPrefix, targetPrefix);
681
+ }
682
+ } else if (src === alias) {
683
+ return target;
684
+ }
685
+ }
686
+ return null;
687
+ }
688
+ function getTargetPath() {
689
+ return pathInfo.targetPath;
690
+ }
691
+ function getComponent(src) {
692
+ return configInfo.componentInfo[src];
693
+ }
694
+ function getPageConfigInfo() {
695
+ return configInfo.pageInfo;
696
+ }
697
+ function getAppConfigInfo() {
698
+ return configInfo.appInfo;
699
+ }
700
+ function getWorkPath() {
701
+ return pathInfo.workPath;
702
+ }
703
+ function getNpmResolver() {
704
+ return npmResolver;
705
+ }
706
+ function getAppId() {
707
+ return configInfo.projectInfo.appid;
708
+ }
709
+ function getAppName() {
710
+ if (configInfo.projectInfo.projectname) {
711
+ return decodeURIComponent(configInfo.projectInfo.projectname);
712
+ }
713
+ return getAppId();
714
+ }
715
+ function transSubDir(name) {
716
+ return `sub_${name.replace(/\/$/, "")}`;
717
+ }
718
+ function getPages() {
719
+ const { pages, subPackages = [], usingComponents: globalComponents = {} } = getAppConfigInfo();
720
+ const pageInfo = getPageConfigInfo();
721
+ const mainPages = pages.map((path8) => {
722
+ const pageComponents = pageInfo[path8]?.usingComponents || {};
723
+ const mergedComponents = { ...globalComponents, ...pageComponents };
724
+ return {
725
+ id: uuid(),
726
+ path: path8,
727
+ usingComponents: mergedComponents
728
+ };
729
+ });
730
+ const subPages = {};
731
+ subPackages.forEach((subPkg) => {
732
+ const rootPath = subPkg.root.endsWith("/") ? subPkg.root : `${subPkg.root}/`;
733
+ const independent = subPkg.independent ? subPkg.independent : false;
734
+ subPages[transSubDir(rootPath)] = {
735
+ independent,
736
+ info: subPkg.pages.map((path8) => {
737
+ const fullPath = rootPath + path8;
738
+ const pageComponents = pageInfo[fullPath]?.usingComponents || {};
739
+ const mergedComponents = { ...globalComponents, ...pageComponents };
740
+ return {
741
+ id: uuid(),
742
+ path: fullPath,
743
+ usingComponents: mergedComponents
744
+ };
745
+ })
746
+ };
747
+ });
748
+ return {
749
+ mainPages,
750
+ subPages
751
+ };
752
+ }
753
+
754
+ // ../../dimina/fe/packages/compiler/src/common/publish.js
755
+ function createDist() {
756
+ const distPath = getTargetPath();
757
+ if (fs_default.existsSync(distPath)) {
758
+ fs_default.rmSync(distPath, { recursive: true, force: true });
759
+ }
760
+ fs_default.mkdirSync(distPath, { recursive: true });
761
+ }
762
+
763
+ // ../../dimina/fe/packages/compiler/src/core/config-compiler.js
764
+ function processTabBarIcons(app) {
765
+ const list = app?.tabBar?.list;
766
+ if (!Array.isArray(list) || list.length === 0) {
767
+ return;
768
+ }
769
+ const workPath = getWorkPath();
770
+ const targetPath = getTargetPath();
771
+ const appId = getAppId();
772
+ for (const item of list) {
773
+ if (item.iconPath) {
774
+ item.iconPath = collectAssets(workPath, "", item.iconPath, targetPath, appId);
775
+ }
776
+ if (item.selectedIconPath) {
777
+ item.selectedIconPath = collectAssets(workPath, "", item.selectedIconPath, targetPath, appId);
778
+ }
779
+ }
780
+ }
781
+ function compileConfig() {
782
+ const app = getAppConfigInfo();
783
+ processTabBarIcons(app);
784
+ const compileResInfo = {
785
+ app,
786
+ modules: getPageConfigInfo(),
787
+ projectName: getAppName()
788
+ };
789
+ const json = JSON.stringify(compileResInfo, null, 4);
790
+ const mainDir = `${getTargetPath()}/main`;
791
+ if (!fs_default.existsSync(mainDir)) {
792
+ fs_default.mkdirSync(mainDir, { recursive: true });
793
+ }
794
+ fs_default.writeFileSync(`${mainDir}/app-config.json`, json);
795
+ }
796
+ var config_compiler_default = compileConfig;
797
+
798
+ // ../../dimina/fe/packages/compiler/src/common/npm-builder.js
799
+ import path5 from "node:path";
800
+ var NpmBuilder = class {
801
+ constructor(workPath, targetPath) {
802
+ this.workPath = workPath;
803
+ this.targetPath = targetPath;
804
+ this.builtPackages = /* @__PURE__ */ new Set();
805
+ this.packageDependencies = /* @__PURE__ */ new Map();
806
+ }
807
+ /**
808
+ * 构建 npm 包
809
+ * 扫描 miniprogram_npm 目录并构建相关包
810
+ */
811
+ async buildNpmPackages() {
812
+ const miniprogramNpmPaths = this.findMiniprogramNpmDirs();
813
+ for (const npmPath of miniprogramNpmPaths) {
814
+ await this.buildNpmDir(npmPath);
815
+ }
816
+ }
817
+ /**
818
+ * 查找所有 miniprogram_npm 目录
819
+ * @returns {string[]} miniprogram_npm 目录路径数组
820
+ */
821
+ findMiniprogramNpmDirs() {
822
+ const npmDirs = [];
823
+ const scanDir = (dir, relativePath = "") => {
824
+ if (!fs_default.existsSync(dir)) {
825
+ return;
826
+ }
827
+ const items = fs_default.readdirSync(dir, { withFileTypes: true });
828
+ for (const item of items) {
829
+ if (item.isDirectory()) {
830
+ const itemPath = path5.join(dir, item.name);
831
+ const itemRelativePath = relativePath ? `${relativePath}/${item.name}` : item.name;
832
+ if (item.name === "miniprogram_npm") {
833
+ npmDirs.push(itemRelativePath);
834
+ } else {
835
+ scanDir(itemPath, itemRelativePath);
836
+ }
837
+ }
838
+ }
839
+ };
840
+ scanDir(this.workPath);
841
+ return npmDirs;
842
+ }
843
+ /**
844
+ * 构建指定的 miniprogram_npm 目录
845
+ * @param {string} npmDirPath miniprogram_npm 目录路径
846
+ */
847
+ async buildNpmDir(npmDirPath) {
848
+ const fullNpmPath = path5.join(this.workPath, npmDirPath);
849
+ if (!fs_default.existsSync(fullNpmPath)) {
850
+ return;
851
+ }
852
+ const packages = fs_default.readdirSync(fullNpmPath, { withFileTypes: true }).filter((item) => item.isDirectory()).map((item) => item.name);
853
+ for (const packageName of packages) {
854
+ await this.buildPackage(packageName, npmDirPath);
855
+ }
856
+ }
857
+ /**
858
+ * 构建单个 npm 包
859
+ * @param {string} packageName 包名
860
+ * @param {string} npmDirPath miniprogram_npm 目录路径
861
+ */
862
+ async buildPackage(packageName, npmDirPath) {
863
+ const packageKey = `${npmDirPath}/${packageName}`;
864
+ if (this.builtPackages.has(packageKey)) {
865
+ return;
866
+ }
867
+ const packagePath = path5.join(this.workPath, npmDirPath, packageName);
868
+ const targetPackagePath = path5.join(this.targetPath, npmDirPath, packageName);
869
+ if (!fs_default.existsSync(path5.dirname(targetPackagePath))) {
870
+ fs_default.mkdirSync(path5.dirname(targetPackagePath), { recursive: true });
871
+ }
872
+ await this.copyPackageFiles(packagePath, targetPackagePath);
873
+ await this.processDependencies(packageName, packagePath, npmDirPath);
874
+ this.builtPackages.add(packageKey);
875
+ }
876
+ /**
877
+ * 复制包文件
878
+ * @param {string} sourcePath 源路径
879
+ * @param {string} targetPath 目标路径
880
+ */
881
+ async copyPackageFiles(sourcePath, targetPath) {
882
+ if (!fs_default.existsSync(sourcePath)) {
883
+ return;
884
+ }
885
+ if (!fs_default.existsSync(targetPath)) {
886
+ fs_default.mkdirSync(targetPath, { recursive: true });
887
+ }
888
+ const items = fs_default.readdirSync(sourcePath, { withFileTypes: true });
889
+ for (const item of items) {
890
+ const sourceItemPath = path5.join(sourcePath, item.name);
891
+ const targetItemPath = path5.join(targetPath, item.name);
892
+ if (item.isDirectory()) {
893
+ await this.copyPackageFiles(sourceItemPath, targetItemPath);
894
+ } else {
895
+ if (this.isMiniprogramFile(item.name)) {
896
+ fs_default.copyFileSync(sourceItemPath, targetItemPath);
897
+ }
898
+ }
899
+ }
900
+ }
901
+ /**
902
+ * 检查是否为小程序相关文件
903
+ * @param {string} filename 文件名
904
+ * @returns {boolean} 是否为小程序文件
905
+ */
906
+ isMiniprogramFile(filename) {
907
+ const miniprogramExts = [".js", ".json", ".ts", ...getTemplateExts(), ...getStyleExts(), ...getViewScriptExts()];
908
+ const ext = path5.extname(filename).toLowerCase();
909
+ return miniprogramExts.includes(ext) || filename === "package.json" || filename === "README.md" || filename.startsWith(".");
910
+ }
911
+ /**
912
+ * 处理包依赖
913
+ * @param {string} packageName 包名
914
+ * @param {string} packagePath 包路径
915
+ * @param {string} npmDirPath npm 目录路径
916
+ */
917
+ async processDependencies(packageName, packagePath, npmDirPath) {
918
+ const packageJsonPath = path5.join(packagePath, "package.json");
919
+ if (!fs_default.existsSync(packageJsonPath)) {
920
+ return;
921
+ }
922
+ try {
923
+ const packageJson = JSON.parse(fs_default.readFileSync(packageJsonPath, "utf-8"));
924
+ const dependencies = {
925
+ ...packageJson.dependencies,
926
+ ...packageJson.peerDependencies
927
+ };
928
+ if (dependencies && Object.keys(dependencies).length > 0) {
929
+ this.packageDependencies.set(packageName, dependencies);
930
+ for (const depName of Object.keys(dependencies)) {
931
+ await this.buildPackage(depName, npmDirPath);
932
+ }
933
+ }
934
+ } catch (e) {
935
+ console.warn(`[npm-builder] \u89E3\u6790 package.json \u5931\u8D25: ${packageJsonPath}`, e.message);
936
+ }
937
+ }
938
+ /**
939
+ * 验证 npm 包的完整性
940
+ * @param {string} packageName 包名
941
+ * @param {string} packagePath 包路径
942
+ * @returns {boolean} 是否有效
943
+ */
944
+ validatePackage(packageName, packagePath) {
945
+ const requiredFiles = ["package.json"];
946
+ for (const file of requiredFiles) {
947
+ if (!fs_default.existsSync(path5.join(packagePath, file))) {
948
+ console.warn(`[npm-builder] \u5305 ${packageName} \u7F3A\u5C11\u5FC5\u8981\u6587\u4EF6: ${file}`);
949
+ return false;
950
+ }
951
+ }
952
+ try {
953
+ const packageJsonPath = path5.join(packagePath, "package.json");
954
+ const packageJson = JSON.parse(fs_default.readFileSync(packageJsonPath, "utf-8"));
955
+ if (!packageJson.name || !packageJson.version) {
956
+ console.warn(`[npm-builder] \u5305 ${packageName} \u7684 package.json \u683C\u5F0F\u4E0D\u6B63\u786E`);
957
+ return false;
958
+ }
959
+ } catch (e) {
960
+ console.warn(`[npm-builder] \u5305 ${packageName} \u7684 package.json \u89E3\u6790\u5931\u8D25:`, e.message);
961
+ return false;
962
+ }
963
+ return true;
964
+ }
965
+ /**
966
+ * 获取已构建的包列表
967
+ * @returns {string[]} 已构建的包列表
968
+ */
969
+ getBuiltPackages() {
970
+ return Array.from(this.builtPackages);
971
+ }
972
+ /**
973
+ * 获取包依赖关系
974
+ * @returns {Map} 包依赖关系映射
975
+ */
976
+ getPackageDependencies() {
977
+ return this.packageDependencies;
978
+ }
979
+ /**
980
+ * 清理构建缓存
981
+ */
982
+ clearCache() {
983
+ this.builtPackages.clear();
984
+ this.packageDependencies.clear();
985
+ }
986
+ };
987
+
988
+ // ../../dimina/fe/packages/compiler/src/core/logic-compiler.js
989
+ import { resolve, sep } from "node:path";
990
+
991
+ // src/shims/worker_threads.js
992
+ var isMainThread = true;
993
+ var parentPort = null;
994
+
995
+ // ../../dimina/fe/packages/compiler/src/core/logic-compiler.js
996
+ import { parseSync } from "oxc-parser";
997
+ import { walk } from "oxc-walker";
998
+ import MagicString from "magic-string";
999
+ import { transform } from "esbuild";
1000
+
1001
+ // ../../dimina/fe/packages/compiler/src/common/compatibility.js
1002
+ import { Parser } from "htmlparser2";
1003
+
1004
+ // ../../dimina/fe/packages/compiler/src/common/compatibility-reference.js
1005
+ var supportedBuiltinComponents = [
1006
+ "block",
1007
+ "button",
1008
+ "canvas",
1009
+ "checkbox",
1010
+ "checkbox-group",
1011
+ "cover-image",
1012
+ "cover-view",
1013
+ "form",
1014
+ "icon",
1015
+ "image",
1016
+ "input",
1017
+ "label",
1018
+ "movable-area",
1019
+ "movable-view",
1020
+ "navigation-bar",
1021
+ "navigator",
1022
+ "picker",
1023
+ "picker-view",
1024
+ "picker-view-column",
1025
+ "progress",
1026
+ "radio",
1027
+ "radio-group",
1028
+ "rich-text",
1029
+ "scroll-view",
1030
+ "slider",
1031
+ "slot",
1032
+ "swiper",
1033
+ "swiper-item",
1034
+ "switch",
1035
+ "template",
1036
+ "text",
1037
+ "textarea",
1038
+ "video",
1039
+ "view",
1040
+ "web-view",
1041
+ "wxs",
1042
+ "include",
1043
+ "import"
1044
+ ];
1045
+ var supportedWxApis = [
1046
+ "env",
1047
+ "canIUse",
1048
+ "getUpdateManager",
1049
+ "openSystemBluetoothSetting",
1050
+ "getWindowInfo",
1051
+ "getSystemSetting",
1052
+ "getSystemInfoSync",
1053
+ "getSystemInfoAsync",
1054
+ "getSystemInfo",
1055
+ "reLaunch",
1056
+ "redirectTo",
1057
+ "navigateTo",
1058
+ "navigateBack",
1059
+ "showToast",
1060
+ "showModal",
1061
+ "showLoading",
1062
+ "showActionSheet",
1063
+ "hideToast",
1064
+ "hideLoading",
1065
+ "setNavigationBarTitle",
1066
+ "setNavigationBarColor",
1067
+ "pageScrollTo",
1068
+ "getMenuButtonBoundingClientRect",
1069
+ "createAnimation",
1070
+ "createCanvasContext",
1071
+ "createOffscreenCanvas",
1072
+ "canvasToTempFilePath",
1073
+ "createSelectorQuery",
1074
+ "createIntersectionObserver",
1075
+ "request",
1076
+ "downloadFile",
1077
+ "uploadFile",
1078
+ "setStorageSync",
1079
+ "getStorageSync",
1080
+ "removeStorageSync",
1081
+ "clearStorageSync",
1082
+ "setStorage",
1083
+ "getStorage",
1084
+ "removeStorage",
1085
+ "clearStorage",
1086
+ "getStorageInfoSync",
1087
+ "getStorageInfo",
1088
+ "saveImageToPhotosAlbum",
1089
+ "previewImage",
1090
+ "compressImage",
1091
+ "chooseImage",
1092
+ "chooseMedia",
1093
+ "chooseContact",
1094
+ "addPhoneContact",
1095
+ "setClipboardData",
1096
+ "getClipboardData",
1097
+ "vibrateShort",
1098
+ "vibrateLong",
1099
+ "hideKeyboard",
1100
+ "getNetworkType",
1101
+ "makePhoneCall",
1102
+ "extBridge",
1103
+ "extOnBridge",
1104
+ "extOffBridge"
1105
+ ];
1106
+
1107
+ // ../../dimina/fe/packages/compiler/src/common/compatibility.js
1108
+ var cachedReference = null;
1109
+ var warnedItems = /* @__PURE__ */ new Set();
1110
+ function loadReference() {
1111
+ if (cachedReference) {
1112
+ return cachedReference;
1113
+ }
1114
+ cachedReference = {
1115
+ supportedBuiltinComponents: new Set(supportedBuiltinComponents),
1116
+ supportedWxApis: new Set(supportedWxApis)
1117
+ };
1118
+ return cachedReference;
1119
+ }
1120
+ function getWxMemberName(node) {
1121
+ if (node?.type !== "MemberExpression") {
1122
+ return null;
1123
+ }
1124
+ if (node.object?.type !== "Identifier" || node.object.name !== "wx") {
1125
+ return null;
1126
+ }
1127
+ if (!node.computed && node.property?.type === "Identifier") {
1128
+ return node.property.name;
1129
+ }
1130
+ if (node.computed && (node.property?.type === "StringLiteral" || node.property?.type === "Literal") && typeof node.property.value === "string") {
1131
+ return node.property.value;
1132
+ }
1133
+ return null;
1134
+ }
1135
+ function warnUnsupportedWxApi(apiName, filePath, line) {
1136
+ const { supportedWxApis: supportedWxApis2 } = loadReference();
1137
+ if (!apiName || supportedWxApis2.has(apiName)) {
1138
+ return;
1139
+ }
1140
+ const location = formatLocation(filePath, line);
1141
+ warnOnce("api", apiName, location, `[compat] Unsupported wx API: wx.${apiName}${location}`);
1142
+ }
1143
+ function warnUnsupportedComponent(tagName, filePath, line) {
1144
+ const { supportedBuiltinComponents: supportedBuiltinComponents2 } = loadReference();
1145
+ if (!tagName || supportedBuiltinComponents2.has(tagName) || getViewScriptTags().includes(tagName)) {
1146
+ return;
1147
+ }
1148
+ const location = formatLocation(filePath, line);
1149
+ warnOnce("component", tagName, location, `[compat] Unsupported or undeclared component: <${tagName}>${location}`);
1150
+ }
1151
+ function checkTemplateCompatibility(content, filePath, components = {}) {
1152
+ let parser;
1153
+ parser = new Parser(
1154
+ {
1155
+ onopentag(tagName) {
1156
+ if (components?.[tagName]) {
1157
+ return;
1158
+ }
1159
+ const line = getLineByIndex(content, parser.startIndex);
1160
+ warnUnsupportedComponent(tagName, filePath, line);
1161
+ },
1162
+ onerror(error) {
1163
+ console.warn("[compat]", `Failed to parse template for compatibility diagnostics: ${filePath}`, error.message);
1164
+ }
1165
+ },
1166
+ {
1167
+ xmlMode: true,
1168
+ lowerCaseTags: false,
1169
+ lowerCaseAttributeNames: false,
1170
+ withStartIndices: true
1171
+ }
1172
+ );
1173
+ parser.write(content);
1174
+ parser.end();
1175
+ }
1176
+ function getLineByIndex(content, index) {
1177
+ if (typeof index !== "number" || index < 0) {
1178
+ return null;
1179
+ }
1180
+ let line = 1;
1181
+ for (let i = 0; i < index; i++) {
1182
+ if (content.charCodeAt(i) === 10) {
1183
+ line++;
1184
+ }
1185
+ }
1186
+ return line;
1187
+ }
1188
+ function formatLocation(filePath, line) {
1189
+ if (!filePath) {
1190
+ return "";
1191
+ }
1192
+ return line ? ` (${filePath}:${line})` : ` (${filePath})`;
1193
+ }
1194
+ function warnOnce(type, name, location, message) {
1195
+ const key = `${type}:${name}:${location}`;
1196
+ if (warnedItems.has(key)) {
1197
+ return;
1198
+ }
1199
+ warnedItems.add(key);
1200
+ console.warn(message);
1201
+ }
1202
+
1203
+ // ../../dimina/fe/packages/compiler/src/core/sourcemap.js
1204
+ import { SourceMapConsumer, SourceMapGenerator } from "source-map-js";
1205
+ function wrapModDefine(module) {
1206
+ const code = module.code.endsWith("\n") ? module.code : module.code + "\n";
1207
+ const extraLine = module.extraInfoCode || "";
1208
+ const header = `modDefine('${module.path}', function(require, module, exports) {
1209
+ ${extraLine}`;
1210
+ const footer = "});\n";
1211
+ return { header, code, footer };
1212
+ }
1213
+ function mergeSourcemap(compileRes2) {
1214
+ const smg = new SourceMapGenerator({ file: "logic.js" });
1215
+ let bundleCode = "";
1216
+ let lineOffset = 0;
1217
+ for (const module of compileRes2) {
1218
+ const { header, code, footer } = wrapModDefine(module);
1219
+ bundleCode += header;
1220
+ const headerLineCount = header.split("\n").length - 1;
1221
+ lineOffset += headerLineCount;
1222
+ if (module.map) {
1223
+ const moduleMap = JSON.parse(module.map);
1224
+ const smc = new SourceMapConsumer(moduleMap);
1225
+ smc.eachMapping((mapping) => {
1226
+ if (mapping.source == null) return;
1227
+ smg.addMapping({
1228
+ generated: {
1229
+ line: mapping.generatedLine + lineOffset,
1230
+ column: mapping.generatedColumn
1231
+ },
1232
+ original: {
1233
+ line: mapping.originalLine,
1234
+ column: mapping.originalColumn
1235
+ },
1236
+ source: mapping.source,
1237
+ name: mapping.name
1238
+ });
1239
+ });
1240
+ if (moduleMap.sourcesContent) {
1241
+ moduleMap.sources.forEach((src, i) => {
1242
+ smg.setSourceContent(src, moduleMap.sourcesContent[i]);
1243
+ });
1244
+ }
1245
+ }
1246
+ bundleCode += code;
1247
+ lineOffset += code.split("\n").length - 1;
1248
+ bundleCode += footer;
1249
+ lineOffset += footer.split("\n").length - 1;
1250
+ }
1251
+ return { bundleCode, sourcemap: smg.toString() };
1252
+ }
1253
+ function remapSourcemap(nextMap, prevMap) {
1254
+ if (!nextMap) {
1255
+ return prevMap;
1256
+ }
1257
+ if (!prevMap) {
1258
+ return nextMap;
1259
+ }
1260
+ const nextMapObj = typeof nextMap === "string" ? JSON.parse(nextMap) : nextMap;
1261
+ const prevMapObj = typeof prevMap === "string" ? JSON.parse(prevMap) : prevMap;
1262
+ const smg = new SourceMapGenerator({ file: nextMapObj.file || prevMapObj.file || "" });
1263
+ const prevSmc = new SourceMapConsumer(prevMapObj);
1264
+ const nextSmc = new SourceMapConsumer(nextMapObj);
1265
+ nextSmc.eachMapping((mapping) => {
1266
+ if (mapping.source == null || mapping.originalLine == null || mapping.originalColumn == null) {
1267
+ return;
1268
+ }
1269
+ const original = prevSmc.originalPositionFor({
1270
+ line: mapping.originalLine,
1271
+ column: mapping.originalColumn
1272
+ });
1273
+ if (original.source == null || original.line == null || original.column == null) {
1274
+ return;
1275
+ }
1276
+ smg.addMapping({
1277
+ generated: {
1278
+ line: mapping.generatedLine,
1279
+ column: mapping.generatedColumn
1280
+ },
1281
+ original: {
1282
+ line: original.line,
1283
+ column: original.column
1284
+ },
1285
+ source: original.source,
1286
+ name: original.name || mapping.name
1287
+ });
1288
+ });
1289
+ if (prevMapObj.sourcesContent) {
1290
+ prevMapObj.sources.forEach((src, i) => {
1291
+ smg.setSourceContent(src, prevMapObj.sourcesContent[i]);
1292
+ });
1293
+ }
1294
+ return smg.toString();
1295
+ }
1296
+
1297
+ // ../../dimina/fe/packages/compiler/src/core/logic-compiler.js
1298
+ var processedModules = /* @__PURE__ */ new Set();
1299
+ var enableSourcemap = false;
1300
+ if (!isMainThread) {
1301
+ parentPort.on("message", async ({ pages, storeInfo: storeInfo2, sourcemap }) => {
1302
+ try {
1303
+ resetStoreInfo(storeInfo2);
1304
+ enableSourcemap = !!sourcemap;
1305
+ const progress = {
1306
+ _completedTasks: 0,
1307
+ get completedTasks() {
1308
+ return this._completedTasks;
1309
+ },
1310
+ set completedTasks(value) {
1311
+ this._completedTasks = value;
1312
+ parentPort.postMessage({ completedTasks: this.completedTasks });
1313
+ }
1314
+ };
1315
+ const mainCompileRes = await compileJS(pages.mainPages, null, null, progress);
1316
+ for (const [root, subPages] of Object.entries(pages.subPages)) {
1317
+ try {
1318
+ const subCompileRes = await compileJS(
1319
+ subPages.info,
1320
+ root,
1321
+ subPages.independent ? [] : mainCompileRes,
1322
+ progress
1323
+ );
1324
+ await writeCompileRes(subCompileRes, root);
1325
+ } catch (error) {
1326
+ throw new Error(`Error processing subpackage ${root}: ${error.message}
1327
+ ${error.stack}`);
1328
+ }
1329
+ }
1330
+ await writeCompileRes(mainCompileRes, null);
1331
+ processedModules.clear();
1332
+ parentPort.postMessage({ success: true });
1333
+ } catch (error) {
1334
+ processedModules.clear();
1335
+ parentPort.postMessage({
1336
+ success: false,
1337
+ error: {
1338
+ message: error.message,
1339
+ stack: error.stack,
1340
+ name: error.name
1341
+ }
1342
+ });
1343
+ }
1344
+ });
1345
+ }
1346
+ async function writeCompileRes(compileRes2, root) {
1347
+ const outputDir = root ? `${getTargetPath()}/${root}` : `${getTargetPath()}/main`;
1348
+ if (!fs_default.existsSync(outputDir)) {
1349
+ fs_default.mkdirSync(outputDir, { recursive: true });
1350
+ }
1351
+ if (enableSourcemap) {
1352
+ const { bundleCode, sourcemap } = mergeSourcemap(compileRes2);
1353
+ const sourcemapFileName = "logic.js.map";
1354
+ fs_default.writeFileSync(`${outputDir}/logic.js`, `${bundleCode}//# sourceMappingURL=${sourcemapFileName}
1355
+ `);
1356
+ fs_default.writeFileSync(`${outputDir}/${sourcemapFileName}`, sourcemap);
1357
+ } else {
1358
+ let mergeCode = "";
1359
+ for (const module of compileRes2) {
1360
+ const amdFormat = `modDefine('${module.path}', function(require, module, exports) {
1361
+ ${module.code}
1362
+ });`;
1363
+ const { code: minifiedCode } = await transform(amdFormat, {
1364
+ minify: true,
1365
+ target: ["es2023"],
1366
+ // quickjs 支持版本
1367
+ platform: "neutral"
1368
+ });
1369
+ mergeCode += minifiedCode;
1370
+ }
1371
+ fs_default.writeFileSync(`${outputDir}/logic.js`, mergeCode);
1372
+ }
1373
+ }
1374
+ async function compileJS(pages, root, mainCompileRes, progress) {
1375
+ const compileRes2 = [];
1376
+ if (!root) {
1377
+ await buildJSByPath(root, { path: "app" }, compileRes2, mainCompileRes, false);
1378
+ }
1379
+ for (const page of pages) {
1380
+ await buildJSByPath(root, page, compileRes2, mainCompileRes, true);
1381
+ progress.completedTasks++;
1382
+ }
1383
+ return compileRes2;
1384
+ }
1385
+ async function buildJSByPath(packageName, module, compileRes2, mainCompileRes, addExtra, depthChain = [], putMain = false) {
1386
+ const currentPath = module.path;
1387
+ if (depthChain.includes(currentPath)) {
1388
+ console.warn("[logic]", `\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56: ${[...depthChain, currentPath].join(" -> ")}`);
1389
+ return;
1390
+ }
1391
+ if (depthChain.length > 20) {
1392
+ console.warn("[logic]", `\u68C0\u6D4B\u5230\u6DF1\u5EA6\u4F9D\u8D56: ${[...depthChain, currentPath].join(" -> ")}`);
1393
+ return;
1394
+ }
1395
+ depthChain = [...depthChain, currentPath];
1396
+ if (!module.path) {
1397
+ return;
1398
+ }
1399
+ if (hasCompileInfo(module.path, compileRes2, mainCompileRes)) {
1400
+ return;
1401
+ }
1402
+ const compileInfo = {
1403
+ path: module.path,
1404
+ code: "",
1405
+ sourceFile: null
1406
+ };
1407
+ const src = module.path.startsWith("/") ? module.path : `/${module.path}`;
1408
+ const modulePath = getJSAbsolutePath(src);
1409
+ if (!modulePath) {
1410
+ console.warn("[logic]", `\u627E\u4E0D\u5230\u6A21\u5757\u6587\u4EF6: ${src}`);
1411
+ return;
1412
+ }
1413
+ const diagnosticSource = modulePath.startsWith(getWorkPath()) ? modulePath.slice(getWorkPath().length) : src;
1414
+ const sourceCode = getContentByPath(modulePath);
1415
+ if (!sourceCode) {
1416
+ console.warn("[logic]", `\u65E0\u6CD5\u8BFB\u53D6\u6A21\u5757\u6587\u4EF6: ${modulePath}`);
1417
+ return;
1418
+ }
1419
+ const isTypeScript = modulePath.endsWith(".ts");
1420
+ if (enableSourcemap) {
1421
+ const workPath = getWorkPath();
1422
+ compileInfo.sourceFile = modulePath.startsWith(workPath) ? modulePath.slice(workPath.length) : src;
1423
+ }
1424
+ const parseResult = parseSync(modulePath, sourceCode, {
1425
+ sourceType: "module",
1426
+ lang: isTypeScript ? "ts" : "js"
1427
+ });
1428
+ const ast = parseResult.program;
1429
+ const s = new MagicString(sourceCode);
1430
+ const extraInfo = {
1431
+ path: module.path
1432
+ };
1433
+ if (module.component) {
1434
+ extraInfo.component = true;
1435
+ }
1436
+ if (module.usingComponents) {
1437
+ const componentsObj = {};
1438
+ const allSubPackages = getAppConfigInfo().subPackages;
1439
+ for (const [name, path8] of Object.entries(module.usingComponents)) {
1440
+ let toMainSubPackage = true;
1441
+ if (packageName) {
1442
+ const normalizedPath = path8.startsWith("/") ? path8.substring(1) : path8;
1443
+ for (const subPackage of allSubPackages) {
1444
+ if (normalizedPath.startsWith(`${subPackage.root}/`)) {
1445
+ toMainSubPackage = false;
1446
+ break;
1447
+ }
1448
+ }
1449
+ } else {
1450
+ toMainSubPackage = false;
1451
+ }
1452
+ const componentModule = getComponent(path8);
1453
+ if (!componentModule) {
1454
+ continue;
1455
+ }
1456
+ await buildJSByPath(packageName, componentModule, compileRes2, mainCompileRes, true, depthChain, putMain || toMainSubPackage);
1457
+ componentsObj[name] = path8;
1458
+ }
1459
+ extraInfo.usingComponents = componentsObj;
1460
+ }
1461
+ if (addExtra) {
1462
+ const extraInfoCode = `globalThis.__extraInfo = ${JSON.stringify(extraInfo)};
1463
+ `;
1464
+ if (enableSourcemap) {
1465
+ compileInfo.extraInfoCode = extraInfoCode;
1466
+ } else {
1467
+ s.prepend(extraInfoCode);
1468
+ }
1469
+ }
1470
+ if (putMain) {
1471
+ mainCompileRes.push(compileInfo);
1472
+ } else {
1473
+ compileRes2.push(compileInfo);
1474
+ }
1475
+ const pathReplacements = [];
1476
+ const dependenciesToProcess = [];
1477
+ walk(ast, {
1478
+ enter(node, parent) {
1479
+ const wxMemberName = getWxMemberName(node);
1480
+ if (wxMemberName) {
1481
+ warnUnsupportedWxApi(
1482
+ wxMemberName,
1483
+ compileInfo.sourceFile || diagnosticSource,
1484
+ node.loc?.start?.line || getLineByIndex2(sourceCode, node.start)
1485
+ );
1486
+ }
1487
+ if ((node.type === "StringLiteral" || node.type === "Literal") && isLocalAssetString(node.value)) {
1488
+ pathReplacements.push({
1489
+ start: node.start,
1490
+ end: node.end,
1491
+ newValue: collectAssets(getWorkPath(), modulePath, node.value, getTargetPath(), getAppId())
1492
+ });
1493
+ }
1494
+ if (node.type === "CallExpression") {
1495
+ const isRequire = node.callee.type === "Identifier" && node.callee.name === "require";
1496
+ const isRequireProperty = node.callee.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object?.name === "require";
1497
+ if ((isRequire || isRequireProperty) && node.arguments.length > 0 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "Literal")) {
1498
+ const arg = node.arguments[0];
1499
+ const requirePath = arg.value;
1500
+ if (requirePath) {
1501
+ const { id, shouldProcess } = resolveDependencyId(requirePath, modulePath, false);
1502
+ if (shouldProcess) {
1503
+ pathReplacements.push({
1504
+ start: arg.start,
1505
+ end: arg.end,
1506
+ newValue: id
1507
+ });
1508
+ if (!processedModules.has(packageName + id)) {
1509
+ dependenciesToProcess.push(id);
1510
+ }
1511
+ }
1512
+ }
1513
+ }
1514
+ }
1515
+ if (node.type === "ImportDeclaration") {
1516
+ const importPath = node.source.value;
1517
+ if (importPath) {
1518
+ const { id, shouldProcess } = resolveDependencyId(importPath, modulePath, true);
1519
+ if (shouldProcess) {
1520
+ pathReplacements.push({
1521
+ start: node.source.start,
1522
+ end: node.source.end,
1523
+ newValue: id
1524
+ });
1525
+ if (!processedModules.has(packageName + id)) {
1526
+ dependenciesToProcess.push(id);
1527
+ }
1528
+ }
1529
+ }
1530
+ }
1531
+ if (node.type === "TSImportEqualsDeclaration" && node.moduleReference?.type === "TSExternalModuleReference") {
1532
+ const importPathNode = node.moduleReference.expression;
1533
+ const importPath = importPathNode?.value;
1534
+ if (importPath) {
1535
+ const { id, shouldProcess } = resolveDependencyId(importPath, modulePath, false);
1536
+ if (shouldProcess) {
1537
+ pathReplacements.push({
1538
+ start: importPathNode.start,
1539
+ end: importPathNode.end,
1540
+ newValue: id
1541
+ });
1542
+ if (!processedModules.has(packageName + id)) {
1543
+ dependenciesToProcess.push(id);
1544
+ }
1545
+ }
1546
+ }
1547
+ }
1548
+ if ((node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && node.source) {
1549
+ const exportPath = node.source.value;
1550
+ if (exportPath) {
1551
+ const { id, shouldProcess } = resolveDependencyId(exportPath, modulePath, true);
1552
+ if (shouldProcess) {
1553
+ pathReplacements.push({
1554
+ start: node.source.start,
1555
+ end: node.source.end,
1556
+ newValue: id
1557
+ });
1558
+ if (!processedModules.has(packageName + id)) {
1559
+ dependenciesToProcess.push(id);
1560
+ }
1561
+ }
1562
+ }
1563
+ }
1564
+ }
1565
+ });
1566
+ for (const depId of dependenciesToProcess) {
1567
+ await buildJSByPath(packageName, { path: depId }, compileRes2, mainCompileRes, false, depthChain, putMain);
1568
+ }
1569
+ for (const replacement of pathReplacements.reverse()) {
1570
+ s.overwrite(replacement.start, replacement.end, `'${replacement.newValue}'`);
1571
+ }
1572
+ const modifiedCode = s.toString();
1573
+ let preEsbuildMap = null;
1574
+ if (enableSourcemap && compileInfo.sourceFile) {
1575
+ const generatedMap = JSON.parse(s.generateMap({
1576
+ file: compileInfo.sourceFile,
1577
+ source: compileInfo.sourceFile,
1578
+ includeContent: true,
1579
+ hires: true
1580
+ }).toString());
1581
+ generatedMap.file = compileInfo.sourceFile;
1582
+ generatedMap.sources = [compileInfo.sourceFile];
1583
+ generatedMap.sourcesContent = [sourceCode];
1584
+ preEsbuildMap = JSON.stringify(generatedMap);
1585
+ }
1586
+ try {
1587
+ const esbuildOpts = {
1588
+ format: "cjs",
1589
+ target: "es2020",
1590
+ platform: "neutral",
1591
+ loader: isTypeScript ? "ts" : "js"
1592
+ };
1593
+ if (enableSourcemap && compileInfo.sourceFile) {
1594
+ esbuildOpts.sourcemap = true;
1595
+ esbuildOpts.sourcefile = compileInfo.sourceFile;
1596
+ esbuildOpts.sourcesContent = true;
1597
+ }
1598
+ const esbuildResult = await transform(modifiedCode, esbuildOpts);
1599
+ if (enableSourcemap && esbuildResult.map) {
1600
+ compileInfo.map = preEsbuildMap ? remapSourcemap(esbuildResult.map, preEsbuildMap) : esbuildResult.map;
1601
+ }
1602
+ compileInfo.code = esbuildResult.code;
1603
+ } catch (error) {
1604
+ console.error(`[logic] esbuild \u8F6C\u6362\u5931\u8D25 ${modulePath}:`, error.message);
1605
+ compileInfo.code = modifiedCode;
1606
+ }
1607
+ processedModules.add(packageName + currentPath);
1608
+ }
1609
+ function isLocalAssetString(value) {
1610
+ return typeof value === "string" && !value.startsWith("http") && !value.startsWith("//") && (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) && /\.(?:png|jpe?g|gif|svg)(?:\?.*)?$/.test(value);
1611
+ }
1612
+ function getLineByIndex2(content, index) {
1613
+ if (typeof index !== "number" || index < 0) {
1614
+ return null;
1615
+ }
1616
+ let line = 1;
1617
+ for (let i = 0; i < index; i++) {
1618
+ if (content.charCodeAt(i) === 10) {
1619
+ line++;
1620
+ }
1621
+ }
1622
+ return line;
1623
+ }
1624
+ function getJSAbsolutePath(modulePath) {
1625
+ const workPath = getWorkPath();
1626
+ const resolvedModuleId = resolveModuleIdToExistingPath(modulePath);
1627
+ if (!resolvedModuleId) {
1628
+ return null;
1629
+ }
1630
+ const fileTypes = [".js", ".ts"];
1631
+ for (const ext of fileTypes) {
1632
+ const fullPath = `${workPath}${resolvedModuleId}${ext}`;
1633
+ if (fs_default.existsSync(fullPath)) {
1634
+ return fullPath;
1635
+ }
1636
+ }
1637
+ return null;
1638
+ }
1639
+ function resolveDependencyId(specifier, modulePath, allowAbsolute) {
1640
+ if (!specifier) {
1641
+ return { id: specifier, shouldProcess: false };
1642
+ }
1643
+ if (specifier.startsWith("miniprogram_npm/")) {
1644
+ const npmModuleId = normalizeModuleId(`/${specifier}`);
1645
+ return {
1646
+ id: resolveModuleIdToExistingPath(npmModuleId) || npmModuleId,
1647
+ shouldProcess: true
1648
+ };
1649
+ }
1650
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
1651
+ return {
1652
+ id: resolveRelativeModuleId(specifier, modulePath),
1653
+ shouldProcess: true
1654
+ };
1655
+ }
1656
+ if (specifier.startsWith("/")) {
1657
+ return {
1658
+ id: allowAbsolute ? normalizeModuleId(specifier) : resolveRelativeModuleId(specifier, modulePath),
1659
+ shouldProcess: true
1660
+ };
1661
+ }
1662
+ const aliasResolved = resolveAppAlias(specifier);
1663
+ if (aliasResolved) {
1664
+ return {
1665
+ id: normalizeModuleId(aliasResolved),
1666
+ shouldProcess: true
1667
+ };
1668
+ }
1669
+ if (specifier.startsWith("@") || isBareModuleSpecifier(specifier)) {
1670
+ const npmModuleId = resolveNpmModuleId(specifier, modulePath);
1671
+ if (npmModuleId) {
1672
+ return {
1673
+ id: npmModuleId,
1674
+ shouldProcess: true
1675
+ };
1676
+ }
1677
+ const siblingModuleId = resolveBareSiblingModuleId(specifier, modulePath);
1678
+ return {
1679
+ id: siblingModuleId || specifier,
1680
+ shouldProcess: Boolean(siblingModuleId)
1681
+ };
1682
+ }
1683
+ return { id: specifier, shouldProcess: false };
1684
+ }
1685
+ function isBareModuleSpecifier(specifier) {
1686
+ return !specifier.startsWith(".") && !specifier.startsWith("/");
1687
+ }
1688
+ function resolveRelativeModuleId(specifier, modulePath) {
1689
+ const requireFullPath = resolve(modulePath, `../${specifier}`);
1690
+ const relativeId = requireFullPath.split(`${getWorkPath()}${sep}`)[1];
1691
+ return normalizeModuleId(relativeId);
1692
+ }
1693
+ function resolveBareSiblingModuleId(specifier, modulePath) {
1694
+ const siblingModuleId = resolveRelativeModuleId(`./${specifier}`, modulePath);
1695
+ return resolveModuleIdToExistingPath(siblingModuleId);
1696
+ }
1697
+ function normalizeModuleId(moduleId) {
1698
+ let normalized = moduleId.replace(/\.(js|ts)$/, "").replace(/\\/g, "/");
1699
+ if (!normalized.startsWith("/")) {
1700
+ normalized = `/${normalized}`;
1701
+ }
1702
+ return normalized;
1703
+ }
1704
+ function resolveNpmModuleId(specifier, modulePath) {
1705
+ const npmResolver2 = getNpmResolver();
1706
+ if (!npmResolver2) {
1707
+ return null;
1708
+ }
1709
+ return npmResolver2.resolveScriptModule(specifier, modulePath, resolveModuleIdToExistingPath);
1710
+ }
1711
+ function resolveModuleIdToExistingPath(moduleId) {
1712
+ const normalizedModuleId = normalizeModuleId(moduleId);
1713
+ const workPath = getWorkPath();
1714
+ for (const ext of [".js", ".ts"]) {
1715
+ if (fs_default.existsSync(`${workPath}${normalizedModuleId}${ext}`)) {
1716
+ return normalizedModuleId;
1717
+ }
1718
+ }
1719
+ for (const ext of [".js", ".ts"]) {
1720
+ if (fs_default.existsSync(`${workPath}${normalizedModuleId}/index${ext}`)) {
1721
+ return `${normalizedModuleId}/index`;
1722
+ }
1723
+ }
1724
+ const packageJsonPath = `${workPath}${normalizedModuleId}/package.json`;
1725
+ if (fs_default.existsSync(packageJsonPath)) {
1726
+ try {
1727
+ const packageInfo = JSON.parse(fs_default.readFileSync(packageJsonPath, "utf-8"));
1728
+ for (const entryField of ["miniprogram", "main"]) {
1729
+ if (typeof packageInfo[entryField] === "string" && packageInfo[entryField]) {
1730
+ const entryModuleId = normalizeModuleId(resolve(normalizedModuleId, packageInfo[entryField]));
1731
+ const resolvedEntry = resolveModuleIdToExistingPath(entryModuleId);
1732
+ if (resolvedEntry) {
1733
+ return resolvedEntry;
1734
+ }
1735
+ }
1736
+ }
1737
+ } catch (error) {
1738
+ console.warn("[logic]", `\u89E3\u6790 package.json \u5931\u8D25: ${packageJsonPath}`, error.message);
1739
+ }
1740
+ }
1741
+ return null;
1742
+ }
1743
+ function __resetLogicState() {
1744
+ processedModules.clear();
1745
+ }
1746
+ function __setEnableSourcemap(v) {
1747
+ enableSourcemap = !!v;
1748
+ }
1749
+
1750
+ // ../../dimina/fe/packages/compiler/src/core/view-compiler.js
1751
+ import path6 from "node:path";
1752
+ import { parseSync as parseSync3 } from "oxc-parser";
1753
+ import { walk as walk2 } from "oxc-walker";
1754
+ import MagicString2 from "magic-string";
1755
+ import { compileTemplate } from "@vue/compiler-sfc";
1756
+ import * as cheerio from "cheerio";
1757
+ import { transform as transform2 } from "esbuild";
1758
+ import * as htmlparser2 from "htmlparser2";
1759
+
1760
+ // ../../dimina/fe/packages/compiler/src/common/expression-parser.js
1761
+ import { parseSync as parseSync2 } from "oxc-parser";
1762
+ var KEYWORDS = /* @__PURE__ */ new Set([
1763
+ "true",
1764
+ "false",
1765
+ "null",
1766
+ "undefined",
1767
+ "NaN",
1768
+ "Infinity",
1769
+ "this",
1770
+ "arguments",
1771
+ "Array",
1772
+ "Object",
1773
+ "String",
1774
+ "Number",
1775
+ "Boolean",
1776
+ "Math",
1777
+ "Date",
1778
+ "RegExp",
1779
+ "Error",
1780
+ "JSON",
1781
+ "console",
1782
+ "window",
1783
+ "document",
1784
+ "parseInt",
1785
+ "parseFloat",
1786
+ "isNaN",
1787
+ "isFinite",
1788
+ "encodeURI",
1789
+ "encodeURIComponent",
1790
+ "decodeURI",
1791
+ "decodeURIComponent"
1792
+ ]);
1793
+ function extractDependencies(expression) {
1794
+ if (!expression || typeof expression !== "string") {
1795
+ return [];
1796
+ }
1797
+ const dependencies = /* @__PURE__ */ new Set();
1798
+ try {
1799
+ const code = `(${expression})`;
1800
+ const ast = parseSync2("expression.js", code, {
1801
+ sourceType: "module",
1802
+ lang: "js"
1803
+ }).program;
1804
+ visitExpressionAst(ast, null, dependencies);
1805
+ } catch (error) {
1806
+ console.warn("[expression-parser] AST \u89E3\u6790\u5931\u8D25\uFF0C\u8868\u8FBE\u5F0F:", expression, "\u9519\u8BEF:", error.message);
1807
+ return [];
1808
+ }
1809
+ return Array.from(dependencies);
1810
+ }
1811
+ function visitExpressionAst(node, parent, dependencies) {
1812
+ if (!node || typeof node !== "object") {
1813
+ return;
1814
+ }
1815
+ if (node.type === "Identifier") {
1816
+ collectIdentifier(node, parent, dependencies);
1817
+ return;
1818
+ }
1819
+ if (node.type === "MemberExpression") {
1820
+ let root = node.object;
1821
+ while (root?.type === "MemberExpression" || root?.type === "ChainExpression") {
1822
+ root = root.type === "ChainExpression" ? root.expression : root.object;
1823
+ }
1824
+ if (root?.type === "Identifier" && !KEYWORDS.has(root.name)) {
1825
+ dependencies.add(root.name);
1826
+ }
1827
+ return;
1828
+ }
1829
+ for (const [key, value] of Object.entries(node)) {
1830
+ if (key === "type" || key === "start" || key === "end" || key === "loc") {
1831
+ continue;
1832
+ }
1833
+ if (Array.isArray(value)) {
1834
+ for (const child of value) {
1835
+ visitExpressionAst(child, node, dependencies);
1836
+ }
1837
+ } else {
1838
+ visitExpressionAst(value, node, dependencies);
1839
+ }
1840
+ }
1841
+ }
1842
+ function collectIdentifier(node, parent, dependencies) {
1843
+ const name = node.name;
1844
+ if (KEYWORDS.has(name)) {
1845
+ return;
1846
+ }
1847
+ if (parent?.type === "MemberExpression" && parent.property === node && !parent.computed) {
1848
+ return;
1849
+ }
1850
+ if (parent?.type === "Property" && parent.key === node && !parent.computed && !parent.shorthand) {
1851
+ return;
1852
+ }
1853
+ dependencies.add(name);
1854
+ }
1855
+ function parseExpression(expression) {
1856
+ if (!expression || typeof expression !== "string") {
1857
+ return {
1858
+ expression: "",
1859
+ dependencies: [],
1860
+ isSimple: true
1861
+ };
1862
+ }
1863
+ const dependencies = extractDependencies(expression);
1864
+ const isSimple = dependencies.length === 1 && expression.trim() === dependencies[0];
1865
+ return {
1866
+ expression: expression.trim(),
1867
+ dependencies,
1868
+ isSimple
1869
+ };
1870
+ }
1871
+ function parseBindings(bindings) {
1872
+ if (!bindings || typeof bindings !== "object") {
1873
+ return {};
1874
+ }
1875
+ const parsed = {};
1876
+ for (const [propName, expression] of Object.entries(bindings)) {
1877
+ parsed[propName] = parseExpression(expression);
1878
+ }
1879
+ return parsed;
1880
+ }
1881
+
1882
+ // ../../dimina/fe/packages/compiler/src/core/view-compiler.js
1883
+ function buildExtStripRegex(exts) {
1884
+ const alt = exts.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
1885
+ return new RegExp(`(${alt})$`);
1886
+ }
1887
+ function stripViewScriptExt(p) {
1888
+ return p.replace(buildExtStripRegex(getViewScriptExts()), "");
1889
+ }
1890
+ function parseJs(code, filename = "view-compiler.js", sourceType = "module") {
1891
+ return parseSync3(filename, code, {
1892
+ sourceType,
1893
+ lang: "js"
1894
+ }).program;
1895
+ }
1896
+ function getProgramCode(code, ast) {
1897
+ const statement = ast.body?.[0];
1898
+ if (ast.body?.length === 1 && statement?.type === "ExpressionStatement") {
1899
+ return code.slice(statement.expression.start, statement.expression.end);
1900
+ }
1901
+ return code;
1902
+ }
1903
+ function isStringLiteral(node) {
1904
+ return node?.type === "StringLiteral" || node?.type === "Literal" && typeof node.value === "string";
1905
+ }
1906
+ function getStringLiteralRawValue(node) {
1907
+ if (!isStringLiteral(node)) {
1908
+ return "";
1909
+ }
1910
+ if (typeof node.raw === "string") {
1911
+ return node.raw.slice(1, -1);
1912
+ }
1913
+ return String(node.value);
1914
+ }
1915
+ function getSource(code, node) {
1916
+ return code.slice(node.start, node.end);
1917
+ }
1918
+ function applyCodeReplacements(source, replacements) {
1919
+ if (replacements.length === 0) {
1920
+ return source;
1921
+ }
1922
+ const selected = [];
1923
+ const byLargestRange = [...replacements].sort((a, b) => {
1924
+ const lengthDiff = b.end - b.start - (a.end - a.start);
1925
+ return lengthDiff || b.start - a.start;
1926
+ });
1927
+ for (const replacement of byLargestRange) {
1928
+ const overlaps = selected.some(
1929
+ (item) => replacement.start < item.end && item.start < replacement.end
1930
+ );
1931
+ if (!overlaps) {
1932
+ selected.push(replacement);
1933
+ }
1934
+ }
1935
+ const s = new MagicString2(source);
1936
+ for (const replacement of selected.sort((a, b) => b.start - a.start)) {
1937
+ if (replacement.type === "insert") {
1938
+ s.appendLeft(replacement.start, replacement.value);
1939
+ } else {
1940
+ s.overwrite(replacement.start, replacement.end, replacement.value);
1941
+ }
1942
+ }
1943
+ return s.toString();
1944
+ }
1945
+ function addOptionalChaining(expression) {
1946
+ if (!expression || typeof expression !== "string") {
1947
+ return expression;
1948
+ }
1949
+ try {
1950
+ const code = `(${expression})`;
1951
+ const ast = parseJs(code);
1952
+ const insertions = [];
1953
+ walk2(ast, {
1954
+ enter(node) {
1955
+ if (node.type !== "MemberExpression" || node.optional) {
1956
+ return;
1957
+ }
1958
+ if (node.computed) {
1959
+ const bracketIndex = code.lastIndexOf("[", node.property.start);
1960
+ if (bracketIndex >= 0) {
1961
+ insertions.push({
1962
+ type: "insert",
1963
+ start: bracketIndex,
1964
+ end: bracketIndex,
1965
+ value: "?."
1966
+ });
1967
+ }
1968
+ } else {
1969
+ const dotIndex = code.lastIndexOf(".", node.property.start);
1970
+ if (dotIndex >= 0) {
1971
+ insertions.push({
1972
+ type: "insert",
1973
+ start: dotIndex,
1974
+ end: dotIndex,
1975
+ value: "?"
1976
+ });
1977
+ }
1978
+ }
1979
+ }
1980
+ });
1981
+ return applyCodeReplacements(code, insertions).slice(1, -1);
1982
+ } catch (error) {
1983
+ return expression;
1984
+ }
1985
+ }
1986
+ function parseSafeBraceExp(exp) {
1987
+ return addOptionalChaining(parseBraceExp(exp));
1988
+ }
1989
+ function transformTextInterpolation(text) {
1990
+ if (!text || typeof text !== "string" || !isWrappedByBraces(text)) {
1991
+ return text;
1992
+ }
1993
+ return text.replace(braceRegex, (match, bracePart) => {
1994
+ if (!bracePart) {
1995
+ return match;
1996
+ }
1997
+ const matchResult = bracePart.match(noBraceRegex);
1998
+ if (!matchResult) {
1999
+ return match;
2000
+ }
2001
+ return `{{${addOptionalChaining(matchResult[1].trim())}}}`;
2002
+ });
2003
+ }
2004
+ var compileResCache = /* @__PURE__ */ new Map();
2005
+ var wxsModuleRegistry = /* @__PURE__ */ new Set();
2006
+ var wxsFilePathMap = /* @__PURE__ */ new Map();
2007
+ if (!isMainThread) {
2008
+ parentPort.on("message", async ({ pages, storeInfo: storeInfo2 }) => {
2009
+ try {
2010
+ resetStoreInfo(storeInfo2);
2011
+ const progress = {
2012
+ _completedTasks: 0,
2013
+ get completedTasks() {
2014
+ return this._completedTasks;
2015
+ },
2016
+ set completedTasks(value) {
2017
+ this._completedTasks = value;
2018
+ parentPort.postMessage({ completedTasks: this._completedTasks });
2019
+ }
2020
+ };
2021
+ await compileML(pages.mainPages, null, progress);
2022
+ for (const [root, subPages] of Object.entries(pages.subPages)) {
2023
+ await compileML(subPages.info, root, progress);
2024
+ }
2025
+ compileResCache.clear();
2026
+ wxsModuleRegistry.clear();
2027
+ wxsFilePathMap.clear();
2028
+ parentPort.postMessage({ success: true });
2029
+ } catch (error) {
2030
+ compileResCache.clear();
2031
+ wxsModuleRegistry.clear();
2032
+ wxsFilePathMap.clear();
2033
+ parentPort.postMessage({
2034
+ success: false,
2035
+ error: {
2036
+ message: error.message,
2037
+ stack: error.stack,
2038
+ name: error.name
2039
+ }
2040
+ });
2041
+ }
2042
+ });
2043
+ }
2044
+ async function compileML(pages, root, progress) {
2045
+ const workPath = getWorkPath();
2046
+ initWxsFilePathMap(workPath);
2047
+ for (const page of pages) {
2048
+ const scriptRes = /* @__PURE__ */ new Map();
2049
+ buildCompileView(page, false, scriptRes, [], /* @__PURE__ */ new Set());
2050
+ let mergeRender = "";
2051
+ for (const [key, value] of scriptRes.entries()) {
2052
+ const amdFormat = `modDefine('${key}', function(require, module, exports) {
2053
+ ${value}
2054
+ });`;
2055
+ const { code: minifiedCode } = await transform2(amdFormat, {
2056
+ minify: true,
2057
+ target: ["es2020"],
2058
+ platform: "browser"
2059
+ });
2060
+ mergeRender += minifiedCode;
2061
+ }
2062
+ scriptRes.clear();
2063
+ const filename = `${page.path.replace(/\//g, "_")}`;
2064
+ if (root) {
2065
+ const subDir = `${getTargetPath()}/${root}`;
2066
+ if (!fs_default.existsSync(subDir)) {
2067
+ fs_default.mkdirSync(subDir, { recursive: true });
2068
+ }
2069
+ fs_default.writeFileSync(`${subDir}/${filename}.js`, mergeRender);
2070
+ } else {
2071
+ const mainDir = `${getTargetPath()}/main`;
2072
+ if (!fs_default.existsSync(mainDir)) {
2073
+ fs_default.mkdirSync(mainDir, { recursive: true });
2074
+ }
2075
+ fs_default.writeFileSync(`${mainDir}/${filename}.js`, mergeRender);
2076
+ }
2077
+ progress.completedTasks++;
2078
+ }
2079
+ }
2080
+ function initWxsFilePathMap(workPath) {
2081
+ wxsFilePathMap.clear();
2082
+ const npmDir = path6.join(workPath, "miniprogram_npm");
2083
+ if (fs_default.existsSync(npmDir)) {
2084
+ scanWxsFiles(npmDir, workPath);
2085
+ }
2086
+ }
2087
+ function scanWxsFiles(dir, workPath) {
2088
+ try {
2089
+ const items = fs_default.readdirSync(dir);
2090
+ for (const item of items) {
2091
+ const fullPath = path6.join(dir, item);
2092
+ const stat = fs_default.statSync(fullPath);
2093
+ if (stat.isDirectory()) {
2094
+ scanWxsFiles(fullPath, workPath);
2095
+ } else if (stat.isFile() && getViewScriptExts().some((ext) => item.endsWith(ext))) {
2096
+ const relativePath = stripViewScriptExt(fullPath.replace(workPath, ""));
2097
+ const moduleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
2098
+ wxsFilePathMap.set(moduleName, fullPath);
2099
+ }
2100
+ }
2101
+ } catch (error) {
2102
+ }
2103
+ }
2104
+ function registerWxsModule(modulePath) {
2105
+ wxsModuleRegistry.add(modulePath);
2106
+ }
2107
+ function isRegisteredWxsModule(modulePath) {
2108
+ return wxsModuleRegistry.has(modulePath);
2109
+ }
2110
+ function buildCompileView(module, isComponent = false, scriptRes, depthChain = [], inheritedTemplatePaths = /* @__PURE__ */ new Set()) {
2111
+ const currentPath = module.path;
2112
+ if (depthChain.includes(currentPath)) {
2113
+ console.warn("[view]", `\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56: ${[...depthChain, currentPath].join(" -> ")}`);
2114
+ return;
2115
+ }
2116
+ if (depthChain.length > 20) {
2117
+ console.warn("[view]", `\u68C0\u6D4B\u5230\u6DF1\u5EA6\u4F9D\u8D56: ${[...depthChain, currentPath].join(" -> ")}`);
2118
+ return;
2119
+ }
2120
+ depthChain = [...depthChain, currentPath];
2121
+ const allScriptModules = [];
2122
+ const currentInstruction = compileModule(module, isComponent, scriptRes, {
2123
+ skipTemplatePaths: isComponent ? inheritedTemplatePaths : /* @__PURE__ */ new Set()
2124
+ });
2125
+ if (currentInstruction && currentInstruction.scriptModule) {
2126
+ allScriptModules.push(...currentInstruction.scriptModule);
2127
+ }
2128
+ const childInheritedTemplatePaths = new Set(inheritedTemplatePaths);
2129
+ for (const tm of currentInstruction?.templateModule || []) {
2130
+ childInheritedTemplatePaths.add(tm.path);
2131
+ }
2132
+ if (module.usingComponents) {
2133
+ for (const componentInfo of Object.values(module.usingComponents)) {
2134
+ const componentModule = getComponent(componentInfo);
2135
+ if (!componentModule) {
2136
+ continue;
2137
+ }
2138
+ if (componentModule.path === module.path) {
2139
+ console.warn("[view]", `\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56\uFF0C\u8DF3\u8FC7\u5904\u7406: ${module.path}`);
2140
+ continue;
2141
+ }
2142
+ const componentInstruction = buildCompileView(componentModule, true, scriptRes, depthChain, childInheritedTemplatePaths);
2143
+ if (componentInstruction && componentInstruction.scriptModule) {
2144
+ for (const sm of componentInstruction.scriptModule) {
2145
+ if (!allScriptModules.find((existing) => existing.path === sm.path)) {
2146
+ allScriptModules.push(sm);
2147
+ }
2148
+ }
2149
+ }
2150
+ }
2151
+ }
2152
+ if (!isComponent && allScriptModules.length > 0) {
2153
+ for (const sm of allScriptModules) {
2154
+ if (!scriptRes.has(sm.path)) {
2155
+ scriptRes.set(sm.path, sm.code);
2156
+ }
2157
+ }
2158
+ compileModuleWithAllWxs(module, scriptRes, allScriptModules);
2159
+ }
2160
+ return { scriptModule: allScriptModules, templateModule: currentInstruction?.templateModule || [] };
2161
+ }
2162
+ function compileModule(module, isComponent, scriptRes, options = {}) {
2163
+ const skipTemplatePaths = options.skipTemplatePaths || /* @__PURE__ */ new Set();
2164
+ const { tpl, instruction } = toCompileTemplate(isComponent, module.path, module.usingComponents, module.componentPlaceholder);
2165
+ if (!tpl) {
2166
+ return null;
2167
+ }
2168
+ const templateModule = instruction.templateModule || [];
2169
+ const templateModuleForCompile = templateModule.filter((tm) => !skipTemplatePaths.has(tm.path));
2170
+ const compileInstruction = {
2171
+ ...instruction,
2172
+ templateModule: templateModuleForCompile
2173
+ };
2174
+ let useCache = false;
2175
+ let cachedCode = null;
2176
+ const canUseCache = skipTemplatePaths.size === 0;
2177
+ if (canUseCache && !scriptRes.has(module.path) && compileResCache.has(module.path)) {
2178
+ const cacheData2 = compileResCache.get(module.path);
2179
+ if (cacheData2 && typeof cacheData2 === "object" && cacheData2.code && cacheData2.instruction) {
2180
+ cachedCode = cacheData2.code;
2181
+ useCache = true;
2182
+ for (const sm of cacheData2.instruction.scriptModule) {
2183
+ if (!scriptRes.has(sm.path)) {
2184
+ scriptRes.set(sm.path, sm.code);
2185
+ }
2186
+ }
2187
+ } else if (typeof cacheData2 === "string") {
2188
+ cachedCode = cacheData2;
2189
+ useCache = true;
2190
+ }
2191
+ }
2192
+ if (useCache && cachedCode) {
2193
+ scriptRes.set(module.path, cachedCode);
2194
+ const allWxsModules2 = collectAllWxsModules(scriptRes, /* @__PURE__ */ new Set(), instruction.scriptModule || []);
2195
+ if (allWxsModules2.length > 0) {
2196
+ const existingModules = instruction.scriptModule || [];
2197
+ const mergedModules = [...existingModules];
2198
+ for (const wxsModule of allWxsModules2) {
2199
+ if (!mergedModules.find((existing) => existing.path === wxsModule.path)) {
2200
+ mergedModules.push(wxsModule);
2201
+ }
2202
+ }
2203
+ instruction.scriptModule = mergedModules;
2204
+ }
2205
+ return {
2206
+ ...instruction,
2207
+ scriptModule: allWxsModules2
2208
+ };
2209
+ }
2210
+ const processedTpl = tpl.replace(/\bthis\./g, "_ctx.");
2211
+ const tplCode = compileTemplate({
2212
+ source: processedTpl,
2213
+ filename: module.path,
2214
+ // 用于错误提示
2215
+ id: `data-v-${module.id}`,
2216
+ scoped: true,
2217
+ compilerOptions: {
2218
+ // https://template-explorer.vuejs.org/
2219
+ prefixIdentifiers: true,
2220
+ hoistStatic: false,
2221
+ cacheHandlers: true,
2222
+ scopeId: `data-v-${module.id}`,
2223
+ mode: "function",
2224
+ inline: true
2225
+ }
2226
+ });
2227
+ let tplComponents = "{";
2228
+ for (const tm of compileInstruction.templateModule) {
2229
+ let { code: code2 } = compileTemplate({
2230
+ source: tm.tpl,
2231
+ filename: tm.path,
2232
+ id: `data-v-${module.id}`,
2233
+ scoped: true,
2234
+ compilerOptions: {
2235
+ prefixIdentifiers: true,
2236
+ hoistStatic: false,
2237
+ cacheHandlers: true,
2238
+ scopeId: `data-v-${module.id}`,
2239
+ mode: "function",
2240
+ inline: true
2241
+ }
2242
+ });
2243
+ code2 = insertWxsToRenderCode(code2, compileInstruction.scriptModule, scriptRes, tm.path);
2244
+ tplComponents += `'${tm.path}':${code2},`;
2245
+ }
2246
+ tplComponents += "}";
2247
+ const transCode = insertWxsToRenderCode(tplCode.code, compileInstruction.scriptModule, scriptRes, module.path);
2248
+ const code = `Module({
2249
+ path: '${module.path}',
2250
+ id: '${module.id}',
2251
+ render: ${transCode},
2252
+ usingComponents: ${JSON.stringify(module.usingComponents)},
2253
+ tplComponents: ${tplComponents},
2254
+ });`;
2255
+ const allWxsModules = collectAllWxsModules(scriptRes, /* @__PURE__ */ new Set(), compileInstruction.scriptModule || []);
2256
+ if (allWxsModules.length > 0) {
2257
+ const existingModules = compileInstruction.scriptModule || [];
2258
+ const mergedModules = [...existingModules];
2259
+ for (const wxsModule of allWxsModules) {
2260
+ if (!mergedModules.find((existing) => existing.path === wxsModule.path)) {
2261
+ mergedModules.push(wxsModule);
2262
+ }
2263
+ }
2264
+ compileInstruction.scriptModule = mergedModules;
2265
+ }
2266
+ const cacheData = {
2267
+ code,
2268
+ instruction: compileInstruction
2269
+ };
2270
+ if (canUseCache) {
2271
+ compileResCache.set(module.path, cacheData);
2272
+ }
2273
+ scriptRes.set(module.path, code);
2274
+ return {
2275
+ ...compileInstruction,
2276
+ templateModule
2277
+ };
2278
+ }
2279
+ function processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath) {
2280
+ let wxsAst;
2281
+ try {
2282
+ wxsAst = parseJs(wxsContent, wxsFilePath || "inline.wxs", "script");
2283
+ } catch (error) {
2284
+ console.error(`[view] \u89E3\u6790 wxs \u6587\u4EF6\u5931\u8D25: ${wxsFilePath}`, error.message);
2285
+ return wxsContent;
2286
+ }
2287
+ const replacements = [];
2288
+ walk2(wxsAst, {
2289
+ enter(node) {
2290
+ if (node.type === "CallExpression") {
2291
+ const calleeName = node.callee?.name;
2292
+ if (calleeName === "getRegExp") {
2293
+ const args = node.arguments;
2294
+ if (args.length > 0) {
2295
+ if (isStringLiteral(args[0]) && (!args[1] || isStringLiteral(args[1]))) {
2296
+ const pattern = getStringLiteralRawValue(args[0]);
2297
+ const flags = args.length > 1 ? getStringLiteralRawValue(args[1]) : "";
2298
+ replacements.push({
2299
+ start: node.start,
2300
+ end: node.end,
2301
+ value: `/${pattern}/${flags}`
2302
+ });
2303
+ } else {
2304
+ const newRegExpArgs = args.map((arg) => getSource(wxsContent, arg)).join(", ");
2305
+ replacements.push({
2306
+ start: node.start,
2307
+ end: node.end,
2308
+ value: `new RegExp(${newRegExpArgs})`
2309
+ });
2310
+ }
2311
+ }
2312
+ } else if (calleeName === "getDate") {
2313
+ const args = node.arguments.map((arg) => getSource(wxsContent, arg)).join(", ");
2314
+ replacements.push({
2315
+ start: node.start,
2316
+ end: node.end,
2317
+ value: `new Date(${args})`
2318
+ });
2319
+ } else if (calleeName === "require" && node.arguments.length > 0 && wxsFilePath) {
2320
+ const requirePath = node.arguments[0].value;
2321
+ if (requirePath && typeof requirePath === "string") {
2322
+ let resolvedWxsPath;
2323
+ if (filePath && filePath.includes("/miniprogram_npm/")) {
2324
+ const currentWxsDir = path6.dirname(wxsFilePath);
2325
+ resolvedWxsPath = path6.resolve(currentWxsDir, requirePath);
2326
+ const relativePath = stripViewScriptExt(resolvedWxsPath.replace(workPath, ""));
2327
+ const moduleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
2328
+ processWxsDependency(resolvedWxsPath, moduleName, scriptModule, workPath, filePath);
2329
+ replacements.push({
2330
+ start: node.arguments[0].start,
2331
+ end: node.arguments[0].end,
2332
+ value: JSON.stringify(moduleName)
2333
+ });
2334
+ } else {
2335
+ const currentWxsDir = path6.dirname(wxsFilePath);
2336
+ resolvedWxsPath = path6.resolve(currentWxsDir, requirePath);
2337
+ const relativePath = stripViewScriptExt(resolvedWxsPath.replace(workPath, ""));
2338
+ const depModuleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
2339
+ processWxsDependency(resolvedWxsPath, depModuleName, scriptModule, workPath, filePath);
2340
+ replacements.push({
2341
+ start: node.arguments[0].start,
2342
+ end: node.arguments[0].end,
2343
+ value: JSON.stringify(depModuleName)
2344
+ });
2345
+ }
2346
+ }
2347
+ }
2348
+ }
2349
+ if (node.type === "MemberExpression") {
2350
+ if (node.property?.name === "constructor" && !node.computed) {
2351
+ const objectCode = getSource(wxsContent, node.object);
2352
+ replacements.push({
2353
+ start: node.start,
2354
+ end: node.end,
2355
+ value: `Object.prototype.toString.call(${objectCode}).slice(8, -1)`
2356
+ });
2357
+ }
2358
+ }
2359
+ }
2360
+ });
2361
+ return applyCodeReplacements(wxsContent, replacements);
2362
+ }
2363
+ function isWxsModuleByContent(moduleCode, modulePath = "") {
2364
+ if (!moduleCode || typeof moduleCode !== "string") {
2365
+ return false;
2366
+ }
2367
+ if (modulePath && isRegisteredWxsModule(modulePath)) {
2368
+ return true;
2369
+ }
2370
+ return false;
2371
+ }
2372
+ function processWxsDependency(wxsFilePath, moduleName, scriptModule, workPath, filePath) {
2373
+ if (!fs_default.existsSync(wxsFilePath)) {
2374
+ console.warn(`[view] wxs \u4F9D\u8D56\u6587\u4EF6\u4E0D\u5B58\u5728: ${wxsFilePath}`);
2375
+ return;
2376
+ }
2377
+ if (scriptModule.find((sm) => sm.path === moduleName)) {
2378
+ return;
2379
+ }
2380
+ const wxsContent = getContentByPath(wxsFilePath).trim();
2381
+ if (!wxsContent) {
2382
+ return;
2383
+ }
2384
+ const wxsCode = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath);
2385
+ registerWxsModule(moduleName);
2386
+ scriptModule.push({
2387
+ path: moduleName,
2388
+ code: wxsCode
2389
+ });
2390
+ }
2391
+ function compileModuleWithAllWxs(module, scriptRes, allScriptModules) {
2392
+ const { tpl, instruction } = toCompileTemplate(false, module.path, module.usingComponents, module.componentPlaceholder);
2393
+ if (!tpl) {
2394
+ return;
2395
+ }
2396
+ const mergedInstruction = {
2397
+ ...instruction,
2398
+ scriptModule: allScriptModules
2399
+ };
2400
+ const processedTpl = tpl.replace(/\bthis\./g, "_ctx.");
2401
+ const tplCode = compileTemplate({
2402
+ source: processedTpl,
2403
+ filename: module.path,
2404
+ id: `data-v-${module.id}`,
2405
+ scoped: true,
2406
+ compilerOptions: {
2407
+ prefixIdentifiers: true,
2408
+ hoistStatic: false,
2409
+ cacheHandlers: true,
2410
+ scopeId: `data-v-${module.id}`,
2411
+ mode: "function",
2412
+ inline: true
2413
+ }
2414
+ });
2415
+ let tplComponents = "{";
2416
+ for (const tm of mergedInstruction.templateModule) {
2417
+ let { code: code2 } = compileTemplate({
2418
+ source: tm.tpl,
2419
+ filename: tm.path,
2420
+ id: `data-v-${module.id}`,
2421
+ scoped: true,
2422
+ compilerOptions: {
2423
+ prefixIdentifiers: true,
2424
+ hoistStatic: false,
2425
+ cacheHandlers: true,
2426
+ scopeId: `data-v-${module.id}`,
2427
+ mode: "function",
2428
+ inline: true
2429
+ }
2430
+ });
2431
+ code2 = insertWxsToRenderCode(code2, allScriptModules, scriptRes, tm.path);
2432
+ tplComponents += `'${tm.path}':${code2},`;
2433
+ }
2434
+ tplComponents += "}";
2435
+ const transCode = insertWxsToRenderCode(tplCode.code, allScriptModules, scriptRes, module.path);
2436
+ const code = `Module({
2437
+ path: '${module.path}',
2438
+ id: '${module.id}',
2439
+ render: ${transCode},
2440
+ usingComponents: ${JSON.stringify(module.usingComponents)},
2441
+ tplComponents: ${tplComponents},
2442
+ });`;
2443
+ const cacheData = {
2444
+ code,
2445
+ instruction: mergedInstruction
2446
+ };
2447
+ compileResCache.set(module.path, cacheData);
2448
+ scriptRes.set(module.path, code);
2449
+ }
2450
+ function processIncludeConditionalAttrs($, elem, includeContent) {
2451
+ const allAttrs = $(elem).attr();
2452
+ const conditionAttrs = {};
2453
+ let hasCondition = false;
2454
+ for (const attrName in allAttrs) {
2455
+ if (attrName.endsWith(":if") || attrName.endsWith(":elif") || attrName.endsWith(":else")) {
2456
+ conditionAttrs[attrName] = allAttrs[attrName];
2457
+ hasCondition = true;
2458
+ }
2459
+ }
2460
+ if (hasCondition) {
2461
+ let blockAttrs = "";
2462
+ for (const attrName in conditionAttrs) {
2463
+ const attrValue = conditionAttrs[attrName];
2464
+ if (attrValue !== void 0 && attrValue !== "") {
2465
+ blockAttrs += ` ${attrName}="${attrValue}"`;
2466
+ } else {
2467
+ blockAttrs += ` ${attrName}`;
2468
+ }
2469
+ }
2470
+ return `<block${blockAttrs}>${includeContent}</block>`;
2471
+ } else {
2472
+ return includeContent;
2473
+ }
2474
+ }
2475
+ function processIncludedFileWxsDependencies(content, includePath, scriptModule, components, processedPaths = /* @__PURE__ */ new Set()) {
2476
+ if (processedPaths.has(includePath)) {
2477
+ return;
2478
+ }
2479
+ processedPaths.add(includePath);
2480
+ const $ = cheerio.load(content, {
2481
+ xmlMode: true,
2482
+ decodeEntities: false,
2483
+ _useHtmlParser2: true,
2484
+ // 减少内存占用的配置
2485
+ lowerCaseTags: false,
2486
+ lowerCaseAttributeNames: false
2487
+ });
2488
+ const componentTags = /* @__PURE__ */ new Set();
2489
+ $("*").each((_, elem) => {
2490
+ const tagName = elem.tagName;
2491
+ if (components && components[tagName]) {
2492
+ componentTags.add(tagName);
2493
+ }
2494
+ });
2495
+ for (const tagName of componentTags) {
2496
+ const componentPath = components[tagName];
2497
+ const componentModule = getComponent(componentPath);
2498
+ if (componentModule) {
2499
+ if (processedPaths.has(componentModule.path)) {
2500
+ continue;
2501
+ }
2502
+ const componentTemplate = toCompileTemplate(true, componentModule.path, componentModule.usingComponents, componentModule.componentPlaceholder, processedPaths);
2503
+ if (componentTemplate && componentTemplate.instruction && componentTemplate.instruction.scriptModule) {
2504
+ for (const sm of componentTemplate.instruction.scriptModule) {
2505
+ if (!scriptModule.find((existing) => existing.path === sm.path)) {
2506
+ scriptModule.push(sm);
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+ }
2512
+ }
2513
+ function toCompileTemplate(isComponent, path8, components, componentPlaceholder, processedPaths = /* @__PURE__ */ new Set()) {
2514
+ const workPath = getWorkPath();
2515
+ const fullPath = getViewPath(workPath, path8);
2516
+ if (!fullPath) {
2517
+ return { tpl: void 0 };
2518
+ }
2519
+ const diagnosticSource = fullPath.startsWith(workPath) ? fullPath.slice(workPath.length) : path8;
2520
+ let content = getContentByPath(fullPath).trim();
2521
+ if (!content) {
2522
+ content = "<block></block>";
2523
+ } else {
2524
+ checkTemplateCompatibility(content, diagnosticSource, components);
2525
+ if (isComponent) {
2526
+ content = `<wrapper name="${path8}">${content}</wrapper>`;
2527
+ } else {
2528
+ const tempRoot = cheerio.load(content, {
2529
+ xmlMode: true,
2530
+ decodeEntities: false
2531
+ });
2532
+ const rootNodes = tempRoot.root().children().toArray().filter((node) => node.type !== "comment");
2533
+ if (rootNodes.length > 1) {
2534
+ content = `<view>${content}</view>`;
2535
+ }
2536
+ }
2537
+ }
2538
+ const templateModule = [];
2539
+ const scriptModule = [];
2540
+ const $ = cheerio.load(content, {
2541
+ xmlMode: true,
2542
+ decodeEntities: false,
2543
+ _useHtmlParser2: true,
2544
+ // 减少内存占用的配置
2545
+ lowerCaseTags: false,
2546
+ lowerCaseAttributeNames: false
2547
+ });
2548
+ const includeNodes = $("include");
2549
+ includeNodes.each((_, elem) => {
2550
+ const src = $(elem).attr("src");
2551
+ if (src) {
2552
+ const includeFullPath = getAbsolutePath(workPath, path8, src);
2553
+ let includePath = includeFullPath.replace(workPath, "").replace(buildExtStripRegex(getTemplateExts()), "");
2554
+ const includeDiagnosticSource = includeFullPath.startsWith(workPath) ? includeFullPath.slice(workPath.length) : includePath;
2555
+ if (!includePath.startsWith("/")) {
2556
+ includePath = "/" + includePath;
2557
+ }
2558
+ const includeContent = getContentByPath(includeFullPath).trim();
2559
+ if (includeContent) {
2560
+ checkTemplateCompatibility(includeContent, includeDiagnosticSource, components);
2561
+ const $includeContent = cheerio.load(includeContent, {
2562
+ xmlMode: true,
2563
+ decodeEntities: false
2564
+ });
2565
+ transTagTemplate(
2566
+ $includeContent,
2567
+ templateModule,
2568
+ includePath,
2569
+ components,
2570
+ componentPlaceholder
2571
+ );
2572
+ transTagWxs(
2573
+ $includeContent,
2574
+ scriptModule,
2575
+ includePath
2576
+ );
2577
+ processIncludedFileWxsDependencies(includeContent, includePath, scriptModule, components, processedPaths);
2578
+ $includeContent("template").remove();
2579
+ $includeContent(getViewScriptTags().join(",")).remove();
2580
+ const processedContent = processIncludeConditionalAttrs($, elem, $includeContent.html());
2581
+ $(elem).replaceWith(processedContent);
2582
+ } else {
2583
+ $(elem).remove();
2584
+ }
2585
+ } else {
2586
+ $(elem).remove();
2587
+ }
2588
+ });
2589
+ transTagTemplate($, templateModule, path8, components, componentPlaceholder);
2590
+ transTagWxs($, scriptModule, path8);
2591
+ const importNodes = $("import");
2592
+ importNodes.each((_, elem) => {
2593
+ const src = $(elem).attr("src");
2594
+ if (src) {
2595
+ const importFullPath = getAbsolutePath(workPath, path8, src);
2596
+ let importPath = importFullPath.replace(workPath, "").replace(buildExtStripRegex(getTemplateExts()), "");
2597
+ const importDiagnosticSource = importFullPath.startsWith(workPath) ? importFullPath.slice(workPath.length) : importPath;
2598
+ if (!importPath.startsWith("/")) {
2599
+ importPath = "/" + importPath;
2600
+ }
2601
+ const importContent = getContentByPath(importFullPath).trim();
2602
+ if (importContent) {
2603
+ checkTemplateCompatibility(importContent, importDiagnosticSource, components);
2604
+ const $$ = cheerio.load(importContent, {
2605
+ xmlMode: true,
2606
+ decodeEntities: false
2607
+ });
2608
+ transTagTemplate(
2609
+ $$,
2610
+ templateModule,
2611
+ path8,
2612
+ components,
2613
+ componentPlaceholder
2614
+ );
2615
+ transTagWxs(
2616
+ $$,
2617
+ scriptModule,
2618
+ importPath
2619
+ );
2620
+ processIncludedFileWxsDependencies(importContent, importPath, scriptModule, components, processedPaths);
2621
+ }
2622
+ }
2623
+ });
2624
+ importNodes.remove();
2625
+ transAsses($, $("image"), path8);
2626
+ const res = [];
2627
+ transHtmlTag($.html(), res, components, componentPlaceholder);
2628
+ return {
2629
+ tpl: res.join(""),
2630
+ instruction: {
2631
+ templateModule,
2632
+ scriptModule
2633
+ }
2634
+ };
2635
+ }
2636
+ function transTagTemplate($, templateModule, path8, components, componentPlaceholder) {
2637
+ const templateNodes = $("template[name]");
2638
+ templateNodes.each((_, elem) => {
2639
+ const name = $(elem).attr("name");
2640
+ const templateContent = $(elem);
2641
+ templateContent.find("import").remove();
2642
+ templateContent.find("include").remove();
2643
+ templateContent.find(getViewScriptTags().join(",")).remove();
2644
+ transAsses($, templateContent.find("image"), path8);
2645
+ const res = [];
2646
+ transHtmlTag(templateContent.html(), res, components, componentPlaceholder);
2647
+ templateModule.push({
2648
+ path: `tpl-${name}`,
2649
+ tpl: res.join("")
2650
+ });
2651
+ });
2652
+ templateNodes.remove();
2653
+ }
2654
+ function transAsses($, imageNodes, path8) {
2655
+ imageNodes.each((_, elem) => {
2656
+ const imgSrc = $(elem).attr("src").trim();
2657
+ if (!imgSrc.startsWith("{{")) {
2658
+ $(elem).attr("src", collectAssets(getWorkPath(), path8, imgSrc, getTargetPath(), getAppId()));
2659
+ }
2660
+ });
2661
+ }
2662
+ function transHtmlTag(html, res, components, componentPlaceholder) {
2663
+ const attrsList = [];
2664
+ const parser = new htmlparser2.Parser(
2665
+ {
2666
+ onopentag(tag, attrs) {
2667
+ attrsList.push(attrs);
2668
+ res.push(transTag({ isStart: true, tag, attrs, components, componentPlaceholder }));
2669
+ },
2670
+ ontext(text) {
2671
+ res.push(transformTextInterpolation(text));
2672
+ },
2673
+ onclosetag(tag) {
2674
+ res.push(transTag({ tag, attrs: attrsList.pop(), components }));
2675
+ },
2676
+ onerror(error) {
2677
+ console.error(error);
2678
+ }
2679
+ },
2680
+ { xmlMode: true }
2681
+ );
2682
+ parser.write(html);
2683
+ parser.end();
2684
+ }
2685
+ function transTag(opts) {
2686
+ const { isStart, tag, attrs, components } = opts;
2687
+ let res;
2688
+ if (tag === "slot") {
2689
+ res = tag;
2690
+ } else if (components && components[tag]) {
2691
+ res = `dd-${tag}`;
2692
+ } else if (tag === "component" || tag === "canvas") {
2693
+ res = tag;
2694
+ } else if (!tagWhiteList.includes(tag)) {
2695
+ res = "dd-text";
2696
+ } else {
2697
+ res = `dd-${tag}`;
2698
+ }
2699
+ let tagRes;
2700
+ const propsAry = isStart ? getProps(attrs, tag, components) : [];
2701
+ const multipleSlots = attrs?.slot;
2702
+ if (attrs?.slot) {
2703
+ const isDynamicSlot = isWrappedByBraces(multipleSlots);
2704
+ if (isStart) {
2705
+ const withVIf = [];
2706
+ const withoutVIf = [];
2707
+ for (let i = 0; i < propsAry.length; i++) {
2708
+ const prop = propsAry[i];
2709
+ if (prop.includes("v-if") || prop.includes("v-else-if") || prop.includes("v-else")) {
2710
+ withVIf.push(prop);
2711
+ } else if (!prop.includes("slot")) {
2712
+ withoutVIf.push(prop);
2713
+ }
2714
+ }
2715
+ const vIfProps = withVIf.length > 0 ? `${withVIf.join(" ")} ` : "";
2716
+ const vOtherProps = withoutVIf.length > 0 ? ` ${withoutVIf.join(" ")}` : "";
2717
+ const templateContent = `<template ${vIfProps}${generateSlotDirective(multipleSlots)}><${res}${vOtherProps}>`;
2718
+ if (isDynamicSlot) {
2719
+ tagRes = `<dd-block>${templateContent}`;
2720
+ } else {
2721
+ tagRes = templateContent;
2722
+ }
2723
+ } else {
2724
+ if (isDynamicSlot) {
2725
+ tagRes = `</${res}></template></dd-block>`;
2726
+ } else {
2727
+ tagRes = `</${res}></template>`;
2728
+ }
2729
+ }
2730
+ } else {
2731
+ if (isStart) {
2732
+ const props = propsAry.join(" ");
2733
+ tagRes = props ? `<${res} ${props}>` : `<${res}>`;
2734
+ } else {
2735
+ tagRes = `</${res}>`;
2736
+ }
2737
+ }
2738
+ return tagRes;
2739
+ }
2740
+ function generateSlotDirective(slotValue) {
2741
+ if (isWrappedByBraces(slotValue)) {
2742
+ const slotExpression = parseBraceExp(slotValue);
2743
+ return `#[${slotExpression}]`;
2744
+ } else {
2745
+ return `#${slotValue}`;
2746
+ }
2747
+ }
2748
+ function getProps(attrs, tag, components) {
2749
+ const attrsList = [];
2750
+ const propBindings = {};
2751
+ Object.entries(attrs).forEach(([name, value]) => {
2752
+ if (name.endsWith(":if")) {
2753
+ attrsList.push({
2754
+ name: "v-if",
2755
+ value: parseSafeBraceExp(value)
2756
+ });
2757
+ } else if (name.endsWith(":elif")) {
2758
+ attrsList.push({
2759
+ name: "v-else-if",
2760
+ value: parseSafeBraceExp(value)
2761
+ });
2762
+ } else if (name.endsWith(":else")) {
2763
+ attrsList.push({
2764
+ name: "v-else",
2765
+ value: ""
2766
+ });
2767
+ } else if (name.endsWith(":for") || name.endsWith(":for-items")) {
2768
+ attrsList.push({
2769
+ name: "v-for",
2770
+ value: parseForExp(value, attrs)
2771
+ });
2772
+ } else if (name.endsWith(":for-item") || name.endsWith(":for-index")) {
2773
+ } else if (name.endsWith(":key")) {
2774
+ const tranValue = parseKeyExpression(value, getForItemName(attrs), getForIndexName(attrs));
2775
+ attrsList.push({
2776
+ name: ":key",
2777
+ value: tranValue
2778
+ });
2779
+ } else if (name === "style") {
2780
+ attrsList.push({
2781
+ name: "v-c-style",
2782
+ value: transformRpx(parseSafeBraceExp(value))
2783
+ });
2784
+ } else if (name === "class") {
2785
+ if (isWrappedByBraces(value)) {
2786
+ attrsList.push({
2787
+ name: ":class",
2788
+ value: parseClassRules(value)
2789
+ });
2790
+ } else {
2791
+ attrsList.push({
2792
+ name: "class",
2793
+ value
2794
+ });
2795
+ }
2796
+ attrsList.push({
2797
+ name: "v-c-class",
2798
+ value: ""
2799
+ });
2800
+ } else if (name === "is" && tag === "component") {
2801
+ attrsList.push({
2802
+ name: ":is",
2803
+ value: `'dd-'+${parseSafeBraceExp(value)}`
2804
+ });
2805
+ } else if (name === "animation" && (tag !== "movable-view" && tagWhiteList.includes(tag))) {
2806
+ attrsList.push({
2807
+ name: "v-c-animation",
2808
+ value: parseSafeBraceExp(value)
2809
+ });
2810
+ } else if (name === "value" && (tag === "input" || tag === "textarea") || (name === "x" || name === "y") && tag === "movable-view") {
2811
+ const parsedValue = parseSafeBraceExp(value);
2812
+ const conditionExp = generateVModelTemplate(parsedValue);
2813
+ if (conditionExp) {
2814
+ attrsList.push({
2815
+ name: `:${name}`,
2816
+ value: parsedValue
2817
+ });
2818
+ attrsList.push({
2819
+ name: `update:${name}`,
2820
+ value: conditionExp
2821
+ });
2822
+ } else {
2823
+ attrsList.push({
2824
+ name: `v-model:${name}`,
2825
+ value: parsedValue
2826
+ });
2827
+ }
2828
+ } else if (name.startsWith("data-")) {
2829
+ if (isWrappedByBraces(value)) {
2830
+ attrsList.push({
2831
+ name: "v-c-data",
2832
+ value: ""
2833
+ });
2834
+ attrsList.push({
2835
+ name: `:${name}`,
2836
+ value: parseSafeBraceExp(value)
2837
+ });
2838
+ } else {
2839
+ attrsList.push({
2840
+ name,
2841
+ value
2842
+ });
2843
+ }
2844
+ } else if (isWrappedByBraces(value)) {
2845
+ const pVal = tag === "template" && name === "data" ? parseTemplateDataExp(value) : parseSafeBraceExp(value);
2846
+ if (components && components[tag]) {
2847
+ if (pVal && typeof pVal === "string") {
2848
+ propBindings[name] = pVal;
2849
+ }
2850
+ }
2851
+ attrsList.push({
2852
+ name: `:${name}`,
2853
+ value: pVal
2854
+ });
2855
+ } else if (name !== "slot") {
2856
+ attrsList.push({
2857
+ name,
2858
+ value
2859
+ });
2860
+ }
2861
+ });
2862
+ const propsRes = [];
2863
+ attrsList.forEach((attr) => {
2864
+ const { name, value } = attr;
2865
+ if (value === "") {
2866
+ propsRes.push(`${name}`);
2867
+ } else if (/\$\{[^}]*\}/.test(value)) {
2868
+ propsRes.push(`:${name}="\`${value}\`"`);
2869
+ } else {
2870
+ propsRes.push(`${name}="${escapeQuotes(value)}"`);
2871
+ }
2872
+ });
2873
+ if (components && components[tag] && Object.keys(propBindings).length > 0) {
2874
+ try {
2875
+ const validBindings = {};
2876
+ for (const [key, value] of Object.entries(propBindings)) {
2877
+ if (value !== void 0 && value !== null && typeof value === "string") {
2878
+ validBindings[key] = value;
2879
+ }
2880
+ }
2881
+ if (Object.keys(validBindings).length > 0) {
2882
+ const parsedBindings = parseBindings(validBindings);
2883
+ const bindingsJson = JSON.stringify(parsedBindings);
2884
+ const escapedJson = bindingsJson.replace(/"/g, "&quot;");
2885
+ propsRes.push(`v-c-prop-bindings="${escapedJson}"`);
2886
+ }
2887
+ } catch (error) {
2888
+ console.warn("[compiler] \u5E8F\u5217\u5316 propBindings \u5931\u8D25:", error.message, "\u6807\u7B7E:", tag, "\u7ED1\u5B9A\u6570\u636E:", propBindings);
2889
+ }
2890
+ }
2891
+ return propsRes;
2892
+ }
2893
+ function generateVModelTemplate(expression) {
2894
+ let var1, var2, updateExpression;
2895
+ if (expression.includes("&&")) {
2896
+ [var1, var2] = expression.split("&&").map((v) => v.trim());
2897
+ updateExpression = `${var1} ? (${var2} = $event) : (${var1} = $event)`;
2898
+ } else if (expression.includes("||")) {
2899
+ [var1, var2] = expression.split("||").map((v) => v.trim());
2900
+ updateExpression = `${var1} ? (${var1} = $event) : (${var2} = $event)`;
2901
+ } else if (expression.includes("?")) {
2902
+ const parts = expression.split(/[?:]/).map((v) => v.trim());
2903
+ var1 = parts[0];
2904
+ var2 = parts[2];
2905
+ updateExpression = `${var1} ? (${var1} = $event) : (${var2} = $event)`;
2906
+ } else {
2907
+ return false;
2908
+ }
2909
+ return updateExpression;
2910
+ }
2911
+ function parseKeyExpression(exp, itemName = "item", indexName = "index") {
2912
+ exp = exp.trim();
2913
+ if (/\*this/.test(exp) || /\*item/.test(exp)) {
2914
+ return `${itemName}.toString()`;
2915
+ }
2916
+ if (!exp.includes("{{")) {
2917
+ if (/^-?\d+(\.\d+)?$/.test(exp)) {
2918
+ return exp;
2919
+ }
2920
+ if (exp === indexName) {
2921
+ return indexName;
2922
+ }
2923
+ return exp.startsWith(itemName) ? `${exp}` : `${itemName}.${exp}`;
2924
+ }
2925
+ if (exp.startsWith("{{") && exp.endsWith("}}")) {
2926
+ const content = exp.slice(2, -2).trim();
2927
+ if (content === "this") {
2928
+ return `${itemName}.toString()`;
2929
+ } else if (content === indexName) {
2930
+ return indexName;
2931
+ } else {
2932
+ return content.startsWith(itemName) ? `${content}` : `${itemName}.${content}`;
2933
+ }
2934
+ }
2935
+ const parts = exp.split(/(\{\{.*?\}\})/);
2936
+ const result = parts.map((part) => {
2937
+ if (part.startsWith("{{") && part.endsWith("}}")) {
2938
+ const content = part.slice(2, -2).trim();
2939
+ if (content === indexName) {
2940
+ return indexName;
2941
+ }
2942
+ return content.startsWith(itemName) ? content : `${itemName}.${content}`;
2943
+ }
2944
+ return `'${part}'`;
2945
+ }).join("+");
2946
+ return result.endsWith("+''") ? result.slice(0, -3) : result;
2947
+ }
2948
+ function getViewPath(workPath, src) {
2949
+ const aSrc = src.startsWith("/") ? src : `/${src}`;
2950
+ for (const mlType of getTemplateExts()) {
2951
+ const mlFullPath = `${workPath}${aSrc}${mlType}`;
2952
+ if (fs_default.existsSync(mlFullPath)) {
2953
+ return mlFullPath;
2954
+ }
2955
+ const indexMlFullPath = `${workPath}${aSrc}/index${mlType}`;
2956
+ if (fs_default.existsSync(indexMlFullPath)) {
2957
+ return indexMlFullPath;
2958
+ }
2959
+ }
2960
+ }
2961
+ function escapeQuotes(input) {
2962
+ return input.replace(/"/g, "'");
2963
+ }
2964
+ function isWrappedByBraces(str) {
2965
+ return /\{\{.*\}\}/.test(str);
2966
+ }
2967
+ function splitWithBraces(str) {
2968
+ const result = [];
2969
+ let temp = "";
2970
+ let inBraces = false;
2971
+ for (let i = 0; i < str.length; i++) {
2972
+ const char = str[i];
2973
+ if (char === "{" && i + 1 < str.length && str[i + 1] === "{") {
2974
+ inBraces = true;
2975
+ temp += "{{";
2976
+ i++;
2977
+ } else if (char === "}" && i + 1 < str.length && str[i + 1] === "}") {
2978
+ inBraces = false;
2979
+ temp += "}}";
2980
+ i++;
2981
+ } else if (!inBraces && char === " ") {
2982
+ if (temp) {
2983
+ result.push(temp);
2984
+ temp = "";
2985
+ }
2986
+ } else {
2987
+ temp += char;
2988
+ }
2989
+ }
2990
+ if (temp) {
2991
+ result.push(temp);
2992
+ }
2993
+ return result;
2994
+ }
2995
+ function parseClassRules(cssRule) {
2996
+ let list = splitWithBraces(cssRule);
2997
+ list = list.map((item) => {
2998
+ return parseBraceExp(item);
2999
+ });
3000
+ if (list.length === 1) {
3001
+ return list.pop();
3002
+ }
3003
+ return `[${list.join(",")}]`;
3004
+ }
3005
+ function getForItemName(attrs) {
3006
+ for (const key in attrs) {
3007
+ if (key.endsWith(":for-item")) {
3008
+ return attrs[key];
3009
+ }
3010
+ }
3011
+ return "item";
3012
+ }
3013
+ function getForIndexName(attrs) {
3014
+ for (const key in attrs) {
3015
+ if (key.endsWith(":for-index")) {
3016
+ return attrs[key];
3017
+ }
3018
+ }
3019
+ return "index";
3020
+ }
3021
+ function parseForExp(exp, attrs) {
3022
+ const item = getForItemName(attrs);
3023
+ const index = getForIndexName(attrs);
3024
+ const listVariableName = parseBraceExp(exp);
3025
+ return `(${item}, ${index}) in ${listVariableName}`;
3026
+ }
3027
+ var braceRegex = /(\{\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}\})|([^{}]+)/g;
3028
+ var noBraceRegex = /\{\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}\}/;
3029
+ var ternaryRegex = /[^?]+\?.+:.+/;
3030
+ function parseBraceExp(exp) {
3031
+ let result;
3032
+ const group = [];
3033
+ while (result = braceRegex.exec(exp)) {
3034
+ if (result[1]) {
3035
+ const matchResult = result[1].match(noBraceRegex);
3036
+ if (matchResult) {
3037
+ const statement = matchResult[1].trim();
3038
+ if (ternaryRegex.test(statement)) {
3039
+ group.push(`(${statement})`);
3040
+ } else {
3041
+ group.push(statement);
3042
+ }
3043
+ }
3044
+ }
3045
+ if (result[2]) {
3046
+ group.push(`+'${result[2].replace(/'/g, "\\'")}'+`);
3047
+ }
3048
+ }
3049
+ return group.join("").replace(/^\+|\+$/g, "");
3050
+ }
3051
+ function parseTemplateDataExp(exp) {
3052
+ const matchResult = exp.trim().match(/^\{\{([\s\S]*)\}\}$/);
3053
+ if (matchResult) {
3054
+ return `{${matchResult[1].trim()}}`;
3055
+ }
3056
+ return `{${parseBraceExp(exp)}}`;
3057
+ }
3058
+ function transTagWxs($, scriptModule, filePath) {
3059
+ const wxsNodes = $(getViewScriptTags().join(","));
3060
+ wxsNodes.each((_, elem) => {
3061
+ const smName = $(elem).attr("module");
3062
+ if (smName) {
3063
+ let wxsContent;
3064
+ let uniqueModuleName = smName;
3065
+ let cacheKey = smName;
3066
+ const src = $(elem).attr("src");
3067
+ let wxsFilePath = null;
3068
+ const workPath = getWorkPath();
3069
+ if (src) {
3070
+ if (filePath.includes("/miniprogram_npm/")) {
3071
+ const componentDir = filePath.split("/").slice(0, -1).join("/");
3072
+ const componentFullPath = workPath + componentDir;
3073
+ wxsFilePath = path6.resolve(componentFullPath, src);
3074
+ } else {
3075
+ wxsFilePath = getAbsolutePath(workPath, filePath, src);
3076
+ }
3077
+ if (wxsFilePath) {
3078
+ const relativePath = stripViewScriptExt(wxsFilePath.replace(workPath, ""));
3079
+ uniqueModuleName = relativePath.replace(/[\/\\@\-]/g, "_").replace(/^_/, "");
3080
+ cacheKey = wxsFilePath;
3081
+ }
3082
+ }
3083
+ if (compileResCache.has(cacheKey)) {
3084
+ wxsContent = compileResCache.get(cacheKey);
3085
+ } else {
3086
+ if (src && wxsFilePath) {
3087
+ if (fs_default.existsSync(wxsFilePath)) {
3088
+ wxsContent = getContentByPath(wxsFilePath).trim();
3089
+ } else {
3090
+ console.warn(`[view] wxs \u6587\u4EF6\u4E0D\u5B58\u5728: ${wxsFilePath}`);
3091
+ return;
3092
+ }
3093
+ } else {
3094
+ wxsContent = $(elem).html();
3095
+ }
3096
+ if (!wxsContent) {
3097
+ return;
3098
+ }
3099
+ wxsContent = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, filePath);
3100
+ compileResCache.set(cacheKey, wxsContent);
3101
+ }
3102
+ if (wxsContent) {
3103
+ registerWxsModule(uniqueModuleName);
3104
+ scriptModule.push({
3105
+ path: uniqueModuleName,
3106
+ code: wxsContent,
3107
+ originalName: smName
3108
+ // 保存原始模块名用于模板中的引用
3109
+ });
3110
+ }
3111
+ }
3112
+ });
3113
+ wxsNodes.remove();
3114
+ }
3115
+ function collectAllWxsModules(scriptRes, collectedPaths = /* @__PURE__ */ new Set(), scriptModule = []) {
3116
+ const allWxsModules = [];
3117
+ const workPath = getWorkPath();
3118
+ for (const [modulePath, moduleCode] of scriptRes.entries()) {
3119
+ if (collectedPaths.has(modulePath)) {
3120
+ continue;
3121
+ }
3122
+ if (isWxsModuleByContent(moduleCode, modulePath)) {
3123
+ collectedPaths.add(modulePath);
3124
+ allWxsModules.push({
3125
+ path: modulePath,
3126
+ code: moduleCode
3127
+ });
3128
+ const dependencies = extractWxsDependencies(moduleCode);
3129
+ for (const depPath of dependencies) {
3130
+ if (!collectedPaths.has(depPath)) {
3131
+ if (scriptRes.has(depPath)) {
3132
+ const depModules = collectAllWxsModules(/* @__PURE__ */ new Map([[depPath, scriptRes.get(depPath)]]), collectedPaths, scriptModule);
3133
+ allWxsModules.push(...depModules);
3134
+ } else {
3135
+ const loaded = loadWxsModule(depPath, workPath, scriptModule);
3136
+ if (loaded) {
3137
+ scriptRes.set(depPath, loaded.code);
3138
+ allWxsModules.push(loaded);
3139
+ collectedPaths.add(depPath);
3140
+ const depModules = collectAllWxsModules(/* @__PURE__ */ new Map([[depPath, loaded.code]]), collectedPaths, scriptModule);
3141
+ allWxsModules.push(...depModules);
3142
+ }
3143
+ }
3144
+ }
3145
+ }
3146
+ }
3147
+ }
3148
+ return allWxsModules;
3149
+ }
3150
+ function loadWxsModule(modulePath, workPath, scriptModule) {
3151
+ const wxsFilePath = wxsFilePathMap.get(modulePath);
3152
+ if (!wxsFilePath) {
3153
+ return null;
3154
+ }
3155
+ try {
3156
+ const wxsContent = getContentByPath(wxsFilePath).trim();
3157
+ if (!wxsContent) {
3158
+ return null;
3159
+ }
3160
+ const processedContent = processWxsContent(wxsContent, wxsFilePath, scriptModule, workPath, "");
3161
+ registerWxsModule(modulePath);
3162
+ return {
3163
+ path: modulePath,
3164
+ code: processedContent
3165
+ };
3166
+ } catch (error) {
3167
+ console.warn(`[view] \u52A0\u8F7D wxs \u6A21\u5757\u5931\u8D25: ${modulePath}`, error.message);
3168
+ return null;
3169
+ }
3170
+ }
3171
+ function extractWxsDependencies(moduleCode) {
3172
+ const dependencies = [];
3173
+ const requirePattern = /(?:require|_)\s*\(\s*["']([^"']+)["']\s*\)/g;
3174
+ let match;
3175
+ while ((match = requirePattern.exec(moduleCode)) !== null) {
3176
+ const depPath = match[1];
3177
+ if (depPath && !dependencies.includes(depPath)) {
3178
+ dependencies.push(depPath);
3179
+ }
3180
+ }
3181
+ return dependencies;
3182
+ }
3183
+ function insertWxsToRenderCode(code, scriptModule, scriptRes, filename = "render.js") {
3184
+ const wxsBindings = [];
3185
+ const codeReplacements = [];
3186
+ const ast = parseJs(code, filename);
3187
+ const statement = ast.body?.[0];
3188
+ const renderExpression = statement?.type === "ExpressionStatement" ? statement.expression : null;
3189
+ const renderBody = renderExpression?.body;
3190
+ const declarations = [];
3191
+ for (const [index, sm] of scriptModule.entries()) {
3192
+ if (!scriptRes.has(sm.path)) {
3193
+ scriptRes.set(sm.path, sm.code);
3194
+ }
3195
+ const templatePropertyName = sm.originalName || sm.path;
3196
+ const requireModuleName = sm.path;
3197
+ const localIdentifier = `__wxs_${index}`;
3198
+ wxsBindings.push({
3199
+ localIdentifier,
3200
+ templatePropertyName
3201
+ });
3202
+ declarations.push(`const ${localIdentifier} = require(${JSON.stringify(requireModuleName)});`);
3203
+ }
3204
+ if (wxsBindings.length === 0) {
3205
+ return getProgramCode(code, ast);
3206
+ }
3207
+ if (renderBody?.type === "BlockStatement") {
3208
+ codeReplacements.push({
3209
+ type: "insert",
3210
+ start: renderBody.start + 1,
3211
+ end: renderBody.start + 1,
3212
+ value: `
3213
+ ${declarations.join("\n")}`
3214
+ });
3215
+ }
3216
+ walk2(ast, {
3217
+ enter(node) {
3218
+ if (node.type === "MemberExpression" && node.object?.type === "Identifier" && node.object.name === "_ctx" && !node.computed && node.property?.type === "Identifier") {
3219
+ const replacement = wxsBindings.find((item) => item.templatePropertyName === node.property.name);
3220
+ if (replacement) {
3221
+ codeReplacements.push({
3222
+ start: node.start,
3223
+ end: node.end,
3224
+ value: replacement.localIdentifier
3225
+ });
3226
+ }
3227
+ }
3228
+ }
3229
+ });
3230
+ const transformed = applyCodeReplacements(code, codeReplacements);
3231
+ const transformedAst = parseJs(transformed, filename);
3232
+ return getProgramCode(transformed, transformedAst);
3233
+ }
3234
+ function __resetViewState() {
3235
+ compileResCache.clear();
3236
+ wxsModuleRegistry.clear();
3237
+ wxsFilePathMap.clear();
3238
+ }
3239
+
3240
+ // ../../dimina/fe/packages/compiler/src/core/style-compiler.js
3241
+ import path7 from "node:path";
3242
+ import { compileStyle } from "@vue/compiler-sfc";
3243
+ import autoprefixer from "autoprefixer";
3244
+ import cssnano from "cssnano";
3245
+ import less from "less";
3246
+ import postcss from "postcss";
3247
+ import selectorParser from "postcss-selector-parser";
3248
+ import * as sass from "sass";
3249
+ var compileRes = /* @__PURE__ */ new Map();
3250
+ if (!isMainThread) {
3251
+ parentPort.on("message", async ({ pages, storeInfo: storeInfo2 }) => {
3252
+ try {
3253
+ resetStoreInfo(storeInfo2);
3254
+ const progress = {
3255
+ _completedTasks: 0,
3256
+ get completedTasks() {
3257
+ return this._completedTasks;
3258
+ },
3259
+ set completedTasks(value) {
3260
+ this._completedTasks = value;
3261
+ parentPort.postMessage({ completedTasks: this._completedTasks });
3262
+ }
3263
+ };
3264
+ await compileSS(pages.mainPages, null, progress);
3265
+ for (const [root, subPages] of Object.entries(pages.subPages)) {
3266
+ await compileSS(subPages.info, root, progress);
3267
+ }
3268
+ compileRes.clear();
3269
+ parentPort.postMessage({ success: true });
3270
+ } catch (error) {
3271
+ compileRes.clear();
3272
+ parentPort.postMessage({
3273
+ success: false,
3274
+ error: {
3275
+ message: error.message,
3276
+ stack: error.stack,
3277
+ name: error.name
3278
+ }
3279
+ });
3280
+ }
3281
+ });
3282
+ }
3283
+ async function compileSS(pages, root, progress) {
3284
+ for (const page of pages) {
3285
+ const code = await buildCompileCss(page, [], /* @__PURE__ */ new Set()) || "";
3286
+ const filename = `${page.path.replace(/\//g, "_")}`;
3287
+ if (root) {
3288
+ const subDir = `${getTargetPath()}/${root}`;
3289
+ if (!fs_default.existsSync(subDir)) {
3290
+ fs_default.mkdirSync(subDir, { recursive: true });
3291
+ }
3292
+ fs_default.writeFileSync(`${subDir}/${filename}.css`, code);
3293
+ } else {
3294
+ const mainDir = `${getTargetPath()}/main`;
3295
+ if (!fs_default.existsSync(mainDir)) {
3296
+ fs_default.mkdirSync(mainDir, { recursive: true });
3297
+ }
3298
+ fs_default.writeFileSync(`${mainDir}/${filename}.css`, code);
3299
+ }
3300
+ progress.completedTasks++;
3301
+ }
3302
+ }
3303
+ async function buildCompileCss(module, depthChain = [], compiledPaths = /* @__PURE__ */ new Set()) {
3304
+ const currentPath = module.path || module.absolutePath;
3305
+ if (depthChain.includes(currentPath)) {
3306
+ console.warn("[style]", `\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F9D\u8D56: ${[...depthChain, currentPath].join(" -> ")}`);
3307
+ return "";
3308
+ }
3309
+ if (depthChain.length > 20) {
3310
+ console.warn("[style]", `\u68C0\u6D4B\u5230\u6DF1\u5EA6\u4F9D\u8D56: ${[...depthChain, currentPath].join(" -> ")}`);
3311
+ return "";
3312
+ }
3313
+ if (compiledPaths.has(currentPath)) {
3314
+ return "";
3315
+ }
3316
+ compiledPaths.add(currentPath);
3317
+ depthChain = [...depthChain, currentPath];
3318
+ let result = await enhanceCSS(module) || "";
3319
+ if (module.usingComponents) {
3320
+ for (const componentInfo of Object.values(module.usingComponents)) {
3321
+ const componentModule = getComponent(componentInfo);
3322
+ if (!componentModule) {
3323
+ continue;
3324
+ }
3325
+ result += await buildCompileCss(componentModule, depthChain, compiledPaths) || "";
3326
+ }
3327
+ }
3328
+ return result;
3329
+ }
3330
+ async function enhanceCSS(module) {
3331
+ const absolutePath = module.absolutePath ? module.absolutePath : getAbsolutePath2(module.path);
3332
+ if (!absolutePath) {
3333
+ return "";
3334
+ }
3335
+ const cacheKey = `${absolutePath}::${module.id || ""}`;
3336
+ const inputCSS = getContentByPath(absolutePath);
3337
+ if (!inputCSS) {
3338
+ return "";
3339
+ }
3340
+ if (compileRes.has(cacheKey)) {
3341
+ return compileRes.get(cacheKey);
3342
+ }
3343
+ let processedCSS = normalizeRootStyleImports(inputCSS);
3344
+ const ext = path7.extname(absolutePath).toLowerCase();
3345
+ try {
3346
+ if (ext === ".less") {
3347
+ const result2 = await less.render(processedCSS, {
3348
+ filename: absolutePath,
3349
+ paths: [path7.dirname(absolutePath), getWorkPath()]
3350
+ });
3351
+ processedCSS = result2.css;
3352
+ } else if (ext === ".scss" || ext === ".sass") {
3353
+ const result2 = sass.compileString(processedCSS, {
3354
+ loadPaths: [path7.dirname(absolutePath), getWorkPath()],
3355
+ syntax: ext === ".sass" ? "indented" : "scss"
3356
+ });
3357
+ processedCSS = result2.css;
3358
+ }
3359
+ } catch (error) {
3360
+ console.error(`[style] \u9884\u5904\u7406\u5668\u7F16\u8BD1\u5931\u8D25 ${absolutePath}:`, error.message);
3361
+ processedCSS = inputCSS;
3362
+ }
3363
+ const fixedCSS = ensureImportSemicolons(processedCSS);
3364
+ let ast;
3365
+ try {
3366
+ ast = postcss.parse(fixedCSS);
3367
+ } catch (error) {
3368
+ console.error(`[style] PostCSS \u89E3\u6790\u5931\u8D25 ${absolutePath}:`, error.message);
3369
+ return "";
3370
+ }
3371
+ const promises2 = [];
3372
+ ast.walk(async (node) => {
3373
+ if (node.type === "atrule" && node.name === "import") {
3374
+ const str = node.params.replace(/^['"]|['"]$/g, "");
3375
+ const importFullPath = resolveStyleImportPath(absolutePath, str);
3376
+ node.remove();
3377
+ promises2.push(buildCompileCss({ absolutePath: importFullPath, id: module.id }, [], /* @__PURE__ */ new Set()));
3378
+ } else if (node.type === "rule") {
3379
+ if (node.selector.includes("::v-deep")) {
3380
+ node.selector = node.selector.replace(/::v-deep\s+(\S[^{]*)/g, ":deep($1)");
3381
+ }
3382
+ if (node.selector.includes(":host")) {
3383
+ node.selector = processHostSelector(node.selector, module.id);
3384
+ }
3385
+ node.selector = selectorParser((selectors) => {
3386
+ selectors.walkTags((tag) => {
3387
+ if (tagWhiteList.includes(tag.value)) {
3388
+ tag.value = `.dd-${tag.value}`;
3389
+ }
3390
+ });
3391
+ }).processSync(node.selector);
3392
+ } else if (node.type === "comment") {
3393
+ node.remove();
3394
+ }
3395
+ });
3396
+ ast.walkDecls((decl) => {
3397
+ decl.value = normalizeCssUrlValue(decl.value, absolutePath);
3398
+ decl.value = transformRpx(decl.value);
3399
+ });
3400
+ const cssCode = ast.toResult().css;
3401
+ const moduleId = module.id;
3402
+ const scopedCode = compileStyle({
3403
+ source: cssCode,
3404
+ id: moduleId,
3405
+ scoped: !!moduleId
3406
+ }).code;
3407
+ const cleanedCode = await removeBaseComponentScope(scopedCode, moduleId);
3408
+ const res = await postcss([
3409
+ autoprefixer({ overrideBrowserslist: ["cover 99.5%"] }),
3410
+ cssnano()
3411
+ ]).process(cleanedCode, { from: void 0 });
3412
+ const importCss = (await Promise.all(promises2)).filter(Boolean).join("");
3413
+ const result = importCss + res.css;
3414
+ compileRes.set(cacheKey, result);
3415
+ return result;
3416
+ }
3417
+ function normalizeCssUrlValue(value, absolutePath) {
3418
+ return value.replace(/url\(([^)]+)\)/g, (fullMatch, rawUrl) => {
3419
+ const cleanedUrl = rawUrl.trim().replace(/^['"]|['"]$/g, "");
3420
+ if (!cleanedUrl || cleanedUrl.startsWith("data:image")) {
3421
+ return fullMatch;
3422
+ }
3423
+ if (cleanedUrl.startsWith("//")) {
3424
+ return `url(https:${cleanedUrl})`;
3425
+ }
3426
+ if (/^(https?:|blob:|data:)/.test(cleanedUrl)) {
3427
+ return fullMatch;
3428
+ }
3429
+ const realSrc = collectAssets(getWorkPath(), absolutePath, cleanedUrl, getTargetPath(), getAppId());
3430
+ return `url(${realSrc})`;
3431
+ });
3432
+ }
3433
+ function getAbsolutePath2(modulePath) {
3434
+ const workPath = getWorkPath();
3435
+ const src = modulePath.startsWith("/") ? modulePath : `/${modulePath}`;
3436
+ for (const ssType of getStyleExts()) {
3437
+ const ssFullPath = `${workPath}${src}${ssType}`;
3438
+ if (fs_default.existsSync(ssFullPath)) {
3439
+ return ssFullPath;
3440
+ }
3441
+ const indexSsFullPath = `${workPath}${src}/index${ssType}`;
3442
+ if (fs_default.existsSync(indexSsFullPath)) {
3443
+ return indexSsFullPath;
3444
+ }
3445
+ }
3446
+ }
3447
+ function resolveStyleImportPath(absolutePath, importPath, workPath = getWorkPath()) {
3448
+ if (importPath.startsWith("/")) {
3449
+ return path7.join(workPath, importPath);
3450
+ }
3451
+ return path7.resolve(path7.dirname(absolutePath), importPath);
3452
+ }
3453
+ function normalizeRootStyleImports(source, workPath = getWorkPath()) {
3454
+ return source.replace(/(@import\s+(?:\(.*?\)\s*)?(?:url\()?['"])(\/[^'")]+)(['"]\)?)/g, (_, prefix, importPath, suffix) => {
3455
+ return `${prefix}${path7.join(workPath, importPath)}${suffix}`;
3456
+ });
3457
+ }
3458
+ async function removeBaseComponentScope(css, moduleId) {
3459
+ if (!moduleId) return css;
3460
+ const ast = postcss.parse(css);
3461
+ const scopeAttrName = `data-v-${moduleId}`;
3462
+ ast.walkRules((rule) => {
3463
+ const hasBaseComponent = tagWhiteList.some(
3464
+ (tag) => rule.selector.includes(`.dd-${tag}`)
3465
+ );
3466
+ if (hasBaseComponent && rule.selector.includes(scopeAttrName)) {
3467
+ rule.selector = selectorParser((selectors) => {
3468
+ selectors.walkAttributes((attr) => {
3469
+ if (attr.attribute === scopeAttrName) {
3470
+ attr.remove();
3471
+ }
3472
+ });
3473
+ }).processSync(rule.selector);
3474
+ }
3475
+ });
3476
+ return ast.toResult().css;
3477
+ }
3478
+ function ensureImportSemicolons(css) {
3479
+ return css.replace(/@import[^;\n]*$/gm, (match) => {
3480
+ return match.endsWith(";") ? match : `${match};`;
3481
+ });
3482
+ }
3483
+ function processHostSelector(selector, moduleId) {
3484
+ return selector.replace(/^:host$/, `[data-v-${moduleId}]`).replace(/:host\(([^)]+)\)/g, `[data-v-${moduleId}]$1`).replace(/:host\s+/g, `[data-v-${moduleId}] `).replace(/:host(?=\.|#|:)/g, `[data-v-${moduleId}]`);
3485
+ }
3486
+ function __resetStyleState() {
3487
+ compileRes.clear();
3488
+ }
3489
+
3490
+ // src/compile-core.js
3491
+ function makeProgress() {
3492
+ let c = 0;
3493
+ return {
3494
+ get completedTasks() {
3495
+ return c;
3496
+ },
3497
+ set completedTasks(v) {
3498
+ c = v;
3499
+ }
3500
+ };
3501
+ }
3502
+ var SYNTHETIC_APPID = "dmlocalpreview";
3503
+ function ensureAppIdFs(fs2, configPath) {
3504
+ let config = {};
3505
+ if (fs2.existsSync(configPath)) {
3506
+ const raw = fs2.readFileSync(configPath, "utf8");
3507
+ try {
3508
+ config = JSON.parse(raw);
3509
+ } catch {
3510
+ throw new Error(`[compiler] ${configPath} is not valid JSON; refusing to overwrite it`);
3511
+ }
3512
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
3513
+ throw new Error(`[compiler] ${configPath} must be a JSON object`);
3514
+ }
3515
+ }
3516
+ const { appid } = config;
3517
+ if (appid !== void 0 && appid !== "" && typeof appid !== "string") {
3518
+ throw new Error(`[compiler] ${configPath} "appid" must be a non-empty string`);
3519
+ }
3520
+ if (!appid) {
3521
+ config.appid = SYNTHETIC_APPID;
3522
+ const slash = configPath.lastIndexOf("/");
3523
+ if (slash > 0) fs2.mkdirSync(configPath.slice(0, slash), { recursive: true });
3524
+ fs2.writeFileSync(configPath, JSON.stringify(config));
3525
+ }
3526
+ }
3527
+ function readOutputs(fs2, target) {
3528
+ const prefix = target.endsWith("/") ? target : `${target}/`;
3529
+ const out = {};
3530
+ const seen = /* @__PURE__ */ new Set();
3531
+ const walk3 = (dir) => {
3532
+ if (seen.has(dir)) return;
3533
+ seen.add(dir);
3534
+ const entries = fs2.readdirSync(dir, { withFileTypes: true });
3535
+ if (!Array.isArray(entries)) {
3536
+ throw new Error(`[compiler] fs.readdirSync(${dir}, { withFileTypes: true }) must return an array`);
3537
+ }
3538
+ for (const e of entries) {
3539
+ if (!e || typeof e.isDirectory !== "function") {
3540
+ throw new Error(`[compiler] fs.readdirSync must return Dirent entries with isDirectory()/isFile() (got ${typeof e} under ${dir})`);
3541
+ }
3542
+ const full = `${dir}/${e.name}`;
3543
+ if (e.isDirectory()) walk3(full);
3544
+ else out[full.slice(prefix.length)] = fs2.readFileSync(full, "utf8");
3545
+ }
3546
+ };
3547
+ walk3(prefix.slice(0, -1));
3548
+ return out;
3549
+ }
3550
+ function findScopedNpmDirs(fs2, workPath, excludeRoots) {
3551
+ const excluded = excludeRoots.filter(Boolean).map((p) => p.endsWith("/") ? p : `${p}/`);
3552
+ const npmDirs = [];
3553
+ const walk3 = (dir, rel) => {
3554
+ if (!fs2.existsSync(dir)) return;
3555
+ for (const item of fs2.readdirSync(dir, { withFileTypes: true })) {
3556
+ if (!item.isDirectory()) continue;
3557
+ const { name } = item;
3558
+ if (name === "node_modules" || name.startsWith(".")) continue;
3559
+ const full = `${dir}/${name}`;
3560
+ if (excluded.some((ex) => `${full}/`.startsWith(ex))) continue;
3561
+ const childRel = rel ? `${rel}/${name}` : name;
3562
+ if (name === "miniprogram_npm") npmDirs.push(childRel);
3563
+ else walk3(full, childRel);
3564
+ }
3565
+ };
3566
+ walk3(workPath.endsWith("/") ? workPath.slice(0, -1) : workPath, "");
3567
+ return npmDirs;
3568
+ }
3569
+ var ScopedNpmBuilder = class extends NpmBuilder {
3570
+ constructor(workPath, targetPath, { fs: fs2, excludeRoots }) {
3571
+ super(workPath, targetPath);
3572
+ this._fs = fs2;
3573
+ this._excludeRoots = excludeRoots;
3574
+ }
3575
+ findMiniprogramNpmDirs() {
3576
+ return findScopedNpmDirs(this._fs, this.workPath, this._excludeRoots);
3577
+ }
3578
+ };
3579
+ var REQUIRED_FS = [
3580
+ "existsSync",
3581
+ "readFileSync",
3582
+ "readdirSync",
3583
+ "statSync",
3584
+ "writeFileSync",
3585
+ "mkdirSync",
3586
+ "copyFileSync",
3587
+ "rmSync"
3588
+ ];
3589
+ function assertFs(fs2) {
3590
+ if (!fs2 || typeof fs2 !== "object") {
3591
+ throw new Error("[compiler] compileMiniApp requires { fs }: inject a node:fs replacement (e.g. createFsFromVolume(memfs Volume)) seeded with the project source under workPath");
3592
+ }
3593
+ const missing = REQUIRED_FS.filter((m) => typeof fs2[m] !== "function");
3594
+ if (missing.length) {
3595
+ throw new Error(`[compiler] injected fs is missing required method(s): ${missing.join(", ")}. Needs the sync subset ${REQUIRED_FS.join("/")}, and readdirSync must support { withFileTypes: true }.`);
3596
+ }
3597
+ }
3598
+ async function runLogicStage(pages, progress) {
3599
+ const mainRes = await compileJS(pages.mainPages, null, null, progress);
3600
+ for (const [root, sub] of Object.entries(pages.subPages)) {
3601
+ const subRes = await compileJS(sub.info, root, sub.independent ? [] : mainRes, progress);
3602
+ await writeCompileRes(subRes, root);
3603
+ }
3604
+ await writeCompileRes(mainRes, null);
3605
+ }
3606
+ async function runViewStage(pages, progress) {
3607
+ await compileML(pages.mainPages, null, progress);
3608
+ for (const [root, sub] of Object.entries(pages.subPages)) {
3609
+ await compileML(sub.info, root, progress);
3610
+ }
3611
+ }
3612
+ async function runStyleStage(pages, progress) {
3613
+ const styleMain = [{ path: "app", id: "" }, ...pages.mainPages];
3614
+ await compileSS(styleMain, null, progress);
3615
+ for (const [root, sub] of Object.entries(pages.subPages)) {
3616
+ await compileSS(sub.info, root, progress);
3617
+ }
3618
+ }
3619
+ var STAGES = {
3620
+ logic: runLogicStage,
3621
+ view: runViewStage,
3622
+ style: runStyleStage
3623
+ };
3624
+ var STAGE_NAMES = Object.keys(STAGES);
3625
+ async function runStage(stage, pages, { sourcemap = false } = {}) {
3626
+ const run = STAGES[stage];
3627
+ if (!run) throw new Error(`[compiler] unknown compile stage "${stage}" (expected ${STAGE_NAMES.join("/")})`);
3628
+ if (stage === "logic") __setEnableSourcemap(!!sourcemap);
3629
+ await run(pages, makeProgress());
3630
+ }
3631
+ async function setupCompile({ fs: fs2, workPath = "/work", options = {}, npmScanExclude = [] } = {}) {
3632
+ assertFs(fs2);
3633
+ ensureAppIdFs(fs2, `${workPath}/project.config.json`);
3634
+ setFs(fs2);
3635
+ try {
3636
+ const store = storeInfo(workPath, options);
3637
+ createDist();
3638
+ config_compiler_default();
3639
+ try {
3640
+ await new ScopedNpmBuilder(getWorkPath(), getTargetPath(), {
3641
+ fs: fs2,
3642
+ excludeRoots: [getTargetPath(), ...npmScanExclude]
3643
+ }).buildNpmPackages();
3644
+ } catch (e) {
3645
+ throw new Error(`[compiler] miniprogram_npm build failed: ${e.message}`);
3646
+ }
3647
+ return {
3648
+ storeInfo: store,
3649
+ pages: getPages(),
3650
+ appId: getAppId(),
3651
+ name: getAppName(),
3652
+ targetPath: getTargetPath(),
3653
+ workPath
3654
+ };
3655
+ } finally {
3656
+ resetFs();
3657
+ }
3658
+ }
3659
+ async function compileStage({ stage, pages, storeInfo: bundle, fs: fs2, sourcemap = false } = {}) {
3660
+ assertFs(fs2);
3661
+ setFs(fs2);
3662
+ try {
3663
+ resetStoreInfo(bundle);
3664
+ await runStage(stage, pages, { sourcemap });
3665
+ } finally {
3666
+ resetFs();
3667
+ }
3668
+ }
3669
+ function collectOutputs({ fs: fs2, targetPath } = {}) {
3670
+ return readOutputs(fs2, targetPath);
3671
+ }
3672
+ function resetCompilerState() {
3673
+ __resetLogicState();
3674
+ __resetStyleState();
3675
+ __resetViewState();
3676
+ __resetAssets();
3677
+ }
3678
+ var compileChain = Promise.resolve();
3679
+ function compileMiniApp(opts = {}) {
3680
+ const result = compileChain.then(() => runCompile(opts));
3681
+ compileChain = result.then(() => {
3682
+ }, () => {
3683
+ });
3684
+ return result;
3685
+ }
3686
+ async function runCompile({ fs: fs2, workPath = "/work" } = {}) {
3687
+ const ctx = await setupCompile({ fs: fs2, workPath });
3688
+ const { storeInfo: bundle, pages, appId, name, targetPath } = ctx;
3689
+ await compileStage({ stage: "logic", pages, storeInfo: bundle, fs: fs2 });
3690
+ await compileStage({ stage: "view", pages, storeInfo: bundle, fs: fs2 });
3691
+ await compileStage({ stage: "style", pages, storeInfo: bundle, fs: fs2 });
3692
+ return { appId, name, files: collectOutputs({ fs: fs2, targetPath }) };
3693
+ }
3694
+ export {
3695
+ STAGE_NAMES,
3696
+ collectOutputs,
3697
+ compileMiniApp,
3698
+ compileStage,
3699
+ resetCompilerState,
3700
+ runStage,
3701
+ setupCompile
3702
+ };