Repository navigation
Expand file tree
/
Copy pathbuild-css.ts
More file actions
258 lines (227 loc) · 7.07 KB
/
Copy pathbuild-css.ts
File metadata and controls
258 lines (227 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// @depends-on css/**
import { createHash } from "node:crypto";
import { watch } from "node:fs";
import { access, mkdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { Glob } from "bun";
import { transform } from "lightningcss";
import { initAsyncCompiler } from "sass-embedded";
import { targets } from "./lib/css-targets";
const PARTIAL_FILE_REGEX = /^_/;
const CACHE_DIR = ".cache/build-css";
const WATCH = process.argv.includes("--watch");
const FULL_THEMES = process.argv.includes("--themes");
// Built by default alongside `all`: small, and the docs site loads them.
const DEFAULT_ENTRIES = ["all", "fonts", "prose", "syntax", "syntax-tokens"];
// `BUILD_CSS_MINIFY=0` keeps the output readable for debugging.
const MINIFY = process.env.BUILD_CSS_MINIFY !== "0";
/**
* Lowers the CSS to the browser targets (vendor prefixes such as
* `-webkit-user-select`) and minifies it. It runs locally as in CI, so
* local and e2e builds style pages the way the published CSS does; it
* costs ~15ms against the Sass compile's seconds.
*/
function postprocessCss(css: string, outFile: string): Uint8Array {
const { code } = transform({
filename: outFile,
code: Buffer.from(css, "utf8"),
targets,
minify: MINIFY,
});
return code;
}
const SASS_OPTIONS = {
style: "compressed" as const,
sourceMap: false,
// Resolves `@import "carbon-components/..."` to the vendored tree in
// css/vendor (inlined from carbon-components@10.58.15).
loadPaths: ["css/vendor"],
quietDeps: true,
silenceDeprecations: [
"import",
"global-builtin",
"color-functions",
"if-function",
],
};
function themeEntries() {
return Array.from(new Glob("*.scss").scanSync({ cwd: "css" }))
.filter((file) => !PARTIAL_FILE_REGEX.test(file))
.sort()
.map((file) => path.parse(file));
}
function compileEntries() {
const entries = themeEntries();
if (FULL_THEMES) return entries;
if (!entries.some((entry) => entry.name === "all")) {
throw new Error("css/all.scss is required for the default CSS build");
}
return entries.filter((entry) => DEFAULT_ENTRIES.includes(entry.name));
}
async function hashPathStats(files: string[], cwd: string): Promise<string> {
const hash = createHash("sha256");
const stats = await Promise.all(
files.map((file) => stat(path.join(cwd, file))),
);
files.forEach((file, i) => {
hash.update(file);
hash.update("\0");
hash.update(String(stats[i].mtimeMs));
hash.update("\0");
hash.update(String(stats[i].size));
hash.update("\0");
});
return hash.digest("hex");
}
async function hashGlob(pattern: string, cwd: string): Promise<string> {
const files = Array.from(new Glob(pattern).scanSync({ cwd })).sort();
return await hashPathStats(files, cwd);
}
async function sharedInputs(): Promise<string> {
const packageJson = JSON.parse(await readFile("package.json", "utf8")) as {
devDependencies?: {
lightningcss?: string;
};
};
return [
await hashGlob("_*.scss", "css"),
await hashGlob("syntax/**/*.scss", "css"),
await hashGlob("vendor/**/*.scss", "css"),
packageJson.devDependencies?.lightningcss ?? "",
JSON.stringify(targets),
MINIFY ? "lightningcss-minify" : "lightningcss-targets",
"stat-cache-v1",
].join("\0");
}
function inputHash(entryMtimeSize: string, shared: string): string {
const hash = createHash("sha256");
hash.update(entryMtimeSize);
hash.update(shared);
return hash.digest("hex");
}
async function isCached(name: string, hash: string): Promise<boolean> {
try {
const cachedHash = (
await readFile(`${CACHE_DIR}/${name}.hash`, "utf8")
).trim();
if (cachedHash !== hash) return false;
await access(`css/${name}.css`);
return true;
} catch {
return false;
}
}
function ms(started: number): string {
return `${Math.round(performance.now() - started)}ms`;
}
type Compiler = Awaited<ReturnType<typeof initAsyncCompiler>>;
async function build(compiler: Compiler): Promise<void> {
const started = performance.now();
await mkdir(CACHE_DIR, { recursive: true });
const keyStarted = performance.now();
const shared = await sharedInputs();
const scss = compileEntries();
const entryStats = await Promise.all(
scss.map(async ({ base }) => ({
base,
stamp: await hashPathStats([base], "css"),
})),
);
console.log("[build-css] cache keys", ms(keyStarted));
let compiled = 0;
let cached = 0;
const workStarted = performance.now();
await Promise.all(
scss.map(async ({ name, base }) => {
const file = `css/${base}`;
const outFile = `css/${name}.css`;
const stamp =
entryStats.find((entry) => entry.base === base)?.stamp ?? "";
const hash = inputHash(stamp, shared);
if (await isCached(name, hash)) {
cached += 1;
console.log("[build-css]", file, "-->", outFile, "(cached)");
return;
}
console.log("[build-css]", file, "-->", outFile);
compiled += 1;
const { css } = await compiler.compileAsync(file, SASS_OPTIONS);
const code = postprocessCss(css, outFile);
await Bun.write(outFile, code);
await writeFile(`${CACHE_DIR}/${name}.hash`, `${hash}\n`);
}),
);
const cssTypes = `${themeEntries()
.map(
({ name }) =>
`declare module "carbon-components-svelte/css/${name}.css";`,
)
.join("\n")}\n`;
const previousTypes = await readFile("css/css.d.ts", "utf8").catch(() => "");
if (previousTypes !== cssTypes) {
await Bun.write("css/css.d.ts", cssTypes);
}
console.log(
[
"[build-css]",
`${compiled} compiled`,
`${cached} cached`,
FULL_THEMES ? "all themes" : `${DEFAULT_ENTRIES.join(", ")} only`,
MINIFY ? "minify on" : "minify off",
compiled ? `compile ${ms(workStarted)}` : "",
`total ${ms(started)}`,
]
.filter(Boolean)
.join(" "),
);
}
function isScssChange(filename: string | null): boolean {
if (!filename) return true;
return filename.endsWith(".scss");
}
const compiler = await initAsyncCompiler();
let keepAlive = false;
try {
await build(compiler);
if (WATCH) {
keepAlive = true;
console.log("[build-css] watching css/**/*.scss");
let pending: ReturnType<typeof setTimeout> | undefined;
let running = false;
let rerun = false;
const kick = () => {
if (running) {
rerun = true;
return;
}
running = true;
build(compiler)
.catch((error: unknown) => {
console.error(error);
})
.finally(() => {
running = false;
if (rerun) {
rerun = false;
kick();
}
});
};
watch("css", { recursive: true }, (_event, filename) => {
if (!isScssChange(filename)) return;
clearTimeout(pending);
pending = setTimeout(kick, 150);
});
await new Promise<void>((resolve) => {
const stop = () => {
compiler.dispose().finally(() => resolve());
};
process.once("SIGINT", stop);
process.once("SIGTERM", stop);
});
}
} finally {
if (!keepAlive) {
await compiler.dispose();
}
}