@dimina/compiler 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const node_worker_threads = require("node:worker_threads");
5
+ const postcss = require("postcss");
6
+ const autoprefixer = require("autoprefixer");
7
+ const selectorParser = require("postcss-selector-parser");
8
+ const cssnano = require("cssnano");
9
+ const compilerSfc = require("@vue/compiler-sfc");
10
+ const env = require("../env-Chow6VXH.cjs");
11
+ const fileType = [".wxss", ".ddss"];
12
+ const compileRes = /* @__PURE__ */ new Map();
13
+ const processedModules = /* @__PURE__ */ new Set();
14
+ if (!node_worker_threads.isMainThread) {
15
+ node_worker_threads.parentPort.on("message", async ({ pages, storeInfo }) => {
16
+ try {
17
+ env.resetStoreInfo(storeInfo);
18
+ const progress = {
19
+ _completedTasks: 0,
20
+ get completedTasks() {
21
+ return this._completedTasks;
22
+ },
23
+ set completedTasks(value) {
24
+ this._completedTasks = value;
25
+ node_worker_threads.parentPort.postMessage({ completedTasks: this._completedTasks });
26
+ }
27
+ };
28
+ await compileSS(pages.mainPages, null, progress);
29
+ for (const [root, subPages] of Object.entries(pages.subPages)) {
30
+ await compileSS(subPages.info, root, progress);
31
+ }
32
+ node_worker_threads.parentPort.postMessage({ success: true });
33
+ } catch (error) {
34
+ node_worker_threads.parentPort.postMessage({ success: false, error: error.message });
35
+ }
36
+ });
37
+ }
38
+ async function compileSS(pages, root, progress) {
39
+ for (const page of pages) {
40
+ const code = await buildCompileCss(page, []) || "";
41
+ const filename = `${page.path.replace(/\//g, "_")}`;
42
+ if (root) {
43
+ const subDir = `${env.getTargetPath()}/${root}`;
44
+ if (!fs.existsSync(subDir)) {
45
+ fs.mkdirSync(subDir);
46
+ }
47
+ fs.writeFileSync(`${subDir}/${filename}.css`, code);
48
+ } else {
49
+ const mainDir = `${env.getTargetPath()}/main`;
50
+ if (!fs.existsSync(mainDir)) {
51
+ fs.mkdirSync(mainDir);
52
+ }
53
+ fs.writeFileSync(`${mainDir}/${filename}.css`, code);
54
+ }
55
+ progress.completedTasks++;
56
+ }
57
+ }
58
+ async function buildCompileCss(module2, depthChain = []) {
59
+ const currentPath = module2.path;
60
+ if (depthChain.includes(currentPath)) {
61
+ console.warn(`检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
62
+ }
63
+ if (depthChain.length > 100) {
64
+ console.warn(`检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
65
+ }
66
+ depthChain = [...depthChain, currentPath];
67
+ let result = await enhanceCSS(module2) || "";
68
+ if (module2.usingComponents) {
69
+ for (const componentInfo of Object.values(module2.usingComponents)) {
70
+ const componentModule = env.getComponent(componentInfo);
71
+ if (!componentModule) {
72
+ continue;
73
+ }
74
+ result += await buildCompileCss(componentModule, depthChain);
75
+ }
76
+ }
77
+ processedModules.add(currentPath);
78
+ return result;
79
+ }
80
+ async function enhanceCSS(module2) {
81
+ const absolutePath = module2.absolutePath ? module2.absolutePath : getAbsolutePath(module2.path);
82
+ if (!absolutePath) {
83
+ return;
84
+ }
85
+ const inputCSS = env.getContentByPath(absolutePath);
86
+ if (!inputCSS) {
87
+ return;
88
+ }
89
+ if (compileRes.has(absolutePath)) {
90
+ return compileRes.get(absolutePath);
91
+ }
92
+ const fixedCSS = inputCSS.replace(/@import.*?(?<!;)\s*$/gm, "$&;");
93
+ const ast = postcss.parse(fixedCSS);
94
+ const promises = [];
95
+ ast.walk(async (node) => {
96
+ if (node.type === "atrule" && node.name === "import") {
97
+ const str = node.params.replace(/^['"]|['"]$/g, "");
98
+ const importFullPath = path.resolve(absolutePath, `../${str}`);
99
+ node.remove();
100
+ promises.push(buildCompileCss({ absolutePath: importFullPath, id: module2.id }));
101
+ } else if (node.type === "rule") {
102
+ if (node.selector.includes("::v-deep")) {
103
+ node.selector = node.selector.replace(/::v-deep\s+(\S[^{]*)/g, ":deep($1)");
104
+ }
105
+ node.selector = selectorParser((selectors) => {
106
+ selectors.walkTags((tag) => {
107
+ if (env.tagWhiteList.includes(tag.value)) {
108
+ tag.value = `.dd-${tag.value}`;
109
+ }
110
+ });
111
+ }).processSync(node.selector);
112
+ node.walkDecls((decl) => {
113
+ const match = decl.value.match(/url\("([^"]*)"\)/);
114
+ if (match) {
115
+ const imgSrc = match[1].trim();
116
+ if (imgSrc.startsWith("data:image")) {
117
+ return;
118
+ }
119
+ const realSrc = env.collectAssets(env.getWorkPath(), absolutePath, imgSrc, env.getTargetPath(), env.getAppId());
120
+ decl.value = `url(${realSrc})`;
121
+ } else {
122
+ decl.value = env.transformRpx(decl.value);
123
+ }
124
+ });
125
+ } else if (node.type === "comment") {
126
+ node.remove();
127
+ }
128
+ });
129
+ const cssCode = ast.toResult().css;
130
+ const code = compilerSfc.compileStyle({
131
+ source: cssCode,
132
+ id: module2.id,
133
+ scoped: !!module2.id
134
+ }).code;
135
+ const res = await postcss([autoprefixer({ overrideBrowserslist: ["cover 99.5%"] }), cssnano()]).process(code, {
136
+ from: void 0
137
+ // 未指定输入源文件路径
138
+ });
139
+ const importCss = (await Promise.all(promises)).filter(Boolean).join("");
140
+ const result = importCss ? importCss + res.css : res.css;
141
+ compileRes.set(module2.path, result);
142
+ return result;
143
+ }
144
+ function getAbsolutePath(modulePath) {
145
+ const workPath = env.getWorkPath();
146
+ const src = modulePath.startsWith("/") ? modulePath : `/${modulePath}`;
147
+ for (const ssType of fileType) {
148
+ const ssFullPath = `${workPath}${src}${ssType}`;
149
+ if (fs.existsSync(ssFullPath)) {
150
+ return ssFullPath;
151
+ }
152
+ }
153
+ }
154
+ module.exports = compileSS;
@@ -0,0 +1,155 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isMainThread, parentPort } from "node:worker_threads";
4
+ import postcss from "postcss";
5
+ import autoprefixer from "autoprefixer";
6
+ import selectorParser from "postcss-selector-parser";
7
+ import cssnano from "cssnano";
8
+ import { compileStyle } from "@vue/compiler-sfc";
9
+ import { r as resetStoreInfo, g as getTargetPath, a as getComponent, b as getContentByPath, h as tagWhiteList, d as collectAssets, e as getAppId, f as getWorkPath, t as transformRpx } from "../env-CezfCSQz.js";
10
+ const fileType = [".wxss", ".ddss"];
11
+ const compileRes = /* @__PURE__ */ new Map();
12
+ const processedModules = /* @__PURE__ */ new Set();
13
+ if (!isMainThread) {
14
+ parentPort.on("message", async ({ pages, storeInfo }) => {
15
+ try {
16
+ resetStoreInfo(storeInfo);
17
+ const progress = {
18
+ _completedTasks: 0,
19
+ get completedTasks() {
20
+ return this._completedTasks;
21
+ },
22
+ set completedTasks(value) {
23
+ this._completedTasks = value;
24
+ parentPort.postMessage({ completedTasks: this._completedTasks });
25
+ }
26
+ };
27
+ await compileSS(pages.mainPages, null, progress);
28
+ for (const [root, subPages] of Object.entries(pages.subPages)) {
29
+ await compileSS(subPages.info, root, progress);
30
+ }
31
+ parentPort.postMessage({ success: true });
32
+ } catch (error) {
33
+ parentPort.postMessage({ success: false, error: error.message });
34
+ }
35
+ });
36
+ }
37
+ async function compileSS(pages, root, progress) {
38
+ for (const page of pages) {
39
+ const code = await buildCompileCss(page, []) || "";
40
+ const filename = `${page.path.replace(/\//g, "_")}`;
41
+ if (root) {
42
+ const subDir = `${getTargetPath()}/${root}`;
43
+ if (!fs.existsSync(subDir)) {
44
+ fs.mkdirSync(subDir);
45
+ }
46
+ fs.writeFileSync(`${subDir}/${filename}.css`, code);
47
+ } else {
48
+ const mainDir = `${getTargetPath()}/main`;
49
+ if (!fs.existsSync(mainDir)) {
50
+ fs.mkdirSync(mainDir);
51
+ }
52
+ fs.writeFileSync(`${mainDir}/${filename}.css`, code);
53
+ }
54
+ progress.completedTasks++;
55
+ }
56
+ }
57
+ async function buildCompileCss(module, depthChain = []) {
58
+ const currentPath = module.path;
59
+ if (depthChain.includes(currentPath)) {
60
+ console.warn(`检测到循环依赖: ${[...depthChain, currentPath].join(" -> ")}`);
61
+ }
62
+ if (depthChain.length > 100) {
63
+ console.warn(`检测到深度依赖: ${[...depthChain, currentPath].join(" -> ")}`);
64
+ }
65
+ depthChain = [...depthChain, currentPath];
66
+ let result = await enhanceCSS(module) || "";
67
+ if (module.usingComponents) {
68
+ for (const componentInfo of Object.values(module.usingComponents)) {
69
+ const componentModule = getComponent(componentInfo);
70
+ if (!componentModule) {
71
+ continue;
72
+ }
73
+ result += await buildCompileCss(componentModule, depthChain);
74
+ }
75
+ }
76
+ processedModules.add(currentPath);
77
+ return result;
78
+ }
79
+ async function enhanceCSS(module) {
80
+ const absolutePath = module.absolutePath ? module.absolutePath : getAbsolutePath(module.path);
81
+ if (!absolutePath) {
82
+ return;
83
+ }
84
+ const inputCSS = getContentByPath(absolutePath);
85
+ if (!inputCSS) {
86
+ return;
87
+ }
88
+ if (compileRes.has(absolutePath)) {
89
+ return compileRes.get(absolutePath);
90
+ }
91
+ const fixedCSS = inputCSS.replace(/@import.*?(?<!;)\s*$/gm, "$&;");
92
+ const ast = postcss.parse(fixedCSS);
93
+ const promises = [];
94
+ ast.walk(async (node) => {
95
+ if (node.type === "atrule" && node.name === "import") {
96
+ const str = node.params.replace(/^['"]|['"]$/g, "");
97
+ const importFullPath = path.resolve(absolutePath, `../${str}`);
98
+ node.remove();
99
+ promises.push(buildCompileCss({ absolutePath: importFullPath, id: module.id }));
100
+ } else if (node.type === "rule") {
101
+ if (node.selector.includes("::v-deep")) {
102
+ node.selector = node.selector.replace(/::v-deep\s+(\S[^{]*)/g, ":deep($1)");
103
+ }
104
+ node.selector = selectorParser((selectors) => {
105
+ selectors.walkTags((tag) => {
106
+ if (tagWhiteList.includes(tag.value)) {
107
+ tag.value = `.dd-${tag.value}`;
108
+ }
109
+ });
110
+ }).processSync(node.selector);
111
+ node.walkDecls((decl) => {
112
+ const match = decl.value.match(/url\("([^"]*)"\)/);
113
+ if (match) {
114
+ const imgSrc = match[1].trim();
115
+ if (imgSrc.startsWith("data:image")) {
116
+ return;
117
+ }
118
+ const realSrc = collectAssets(getWorkPath(), absolutePath, imgSrc, getTargetPath(), getAppId());
119
+ decl.value = `url(${realSrc})`;
120
+ } else {
121
+ decl.value = transformRpx(decl.value);
122
+ }
123
+ });
124
+ } else if (node.type === "comment") {
125
+ node.remove();
126
+ }
127
+ });
128
+ const cssCode = ast.toResult().css;
129
+ const code = compileStyle({
130
+ source: cssCode,
131
+ id: module.id,
132
+ scoped: !!module.id
133
+ }).code;
134
+ const res = await postcss([autoprefixer({ overrideBrowserslist: ["cover 99.5%"] }), cssnano()]).process(code, {
135
+ from: void 0
136
+ // 未指定输入源文件路径
137
+ });
138
+ const importCss = (await Promise.all(promises)).filter(Boolean).join("");
139
+ const result = importCss ? importCss + res.css : res.css;
140
+ compileRes.set(module.path, result);
141
+ return result;
142
+ }
143
+ function getAbsolutePath(modulePath) {
144
+ const workPath = getWorkPath();
145
+ const src = modulePath.startsWith("/") ? modulePath : `/${modulePath}`;
146
+ for (const ssType of fileType) {
147
+ const ssFullPath = `${workPath}${src}${ssType}`;
148
+ if (fs.existsSync(ssFullPath)) {
149
+ return ssFullPath;
150
+ }
151
+ }
152
+ }
153
+ export {
154
+ compileSS as default
155
+ };