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