@akanjs/devkit 3.3.0-rc.1 → 3.3.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -2
- package/akanApp/akanApp.host.test.ts +21 -4
- package/akanApp/akanApp.host.ts +46 -9
- package/akanApp/akanApp.host.wiring.test.ts +206 -2
- package/akanApp/devBackend.ts +3 -1
- package/akanApp/devBuilder.ts +5 -1
- package/akanApp/devStartTimeline.test.ts +115 -0
- package/akanApp/devStartTimeline.ts +69 -0
- package/akanConfig/akanConfig.test.ts +2 -1
- package/akanConfig/akanConfig.ts +1 -1
- package/app/applicationBuildRunner.test.ts +49 -1
- package/app/applicationBuildRunner.ts +3 -1
- package/codeAgent/skills/akan-page/SKILL.md +18 -13
- package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
- package/codeAgent/skills/akan-service/SKILL.md +2 -2
- package/docs/apiReference.test.ts +5 -0
- package/docs/apiReference.ts +7 -3
- package/docs/declarationReader.ts +28 -1
- package/executors/appExecutor.ts +35 -11
- package/executors/executors.test.ts +30 -3
- package/frontendBuild/buildCacheStamp.test.ts +42 -0
- package/frontendBuild/buildCacheStamp.ts +23 -0
- package/frontendBuild/cssCandidateCache.test.ts +70 -1
- package/frontendBuild/cssCandidateCache.ts +17 -10
- package/frontendBuild/cssCompiler.test.ts +112 -0
- package/frontendBuild/cssCompiler.ts +41 -21
- package/frontendBuild/fontOptimizer.test.ts +144 -3
- package/frontendBuild/fontOptimizer.ts +103 -18
- package/frontendBuild/plainStylesheet.test.ts +155 -0
- package/frontendBuild/plainStylesheet.ts +197 -0
- package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
- package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
- package/guideline/agentAssets.test.ts +10 -0
- package/guideline/agentAssets.ts +52 -11
- package/incrementalBuilder/buildBatch.proc.ts +2 -1
- package/incrementalBuilder/buildBatchProtocol.ts +1 -0
- package/incrementalBuilder/builderBoot.ts +9 -2
- package/incrementalBuilder/builderChannel.ts +8 -2
- package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
- package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +41 -0
- package/incrementalBuilder/incrementalBuilder.proc.ts +1 -0
- package/mobile/nativeConfig.test.ts +21 -0
- package/mobile/nativeConfig.ts +20 -10
- package/mobile/nativePublicEnv.ts +2 -1
- package/package.json +3 -3
- package/util/fileSys.test.ts +13 -0
- package/util/fileSys.ts +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, stat } from "node:fs/promises";
|
|
1
|
+
import { mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import type {
|
|
4
4
|
ReactFont,
|
|
@@ -11,6 +11,8 @@ import type {
|
|
|
11
11
|
import type { FontCategory } from "fontaine";
|
|
12
12
|
import ts from "typescript";
|
|
13
13
|
import type { App } from "../commandDecorators";
|
|
14
|
+
import { FileSys } from "../util/fileSys";
|
|
15
|
+
import { type BuildCacheStamp, buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
|
|
14
16
|
|
|
15
17
|
const FONT_URL_PREFIX = "/_akan/fonts";
|
|
16
18
|
const DEFAULT_FONT_SUBSETS: ReactFontSubset[] = ["latin"];
|
|
@@ -21,11 +23,17 @@ export interface OptimizeAppFontsResult {
|
|
|
21
23
|
files: string[];
|
|
22
24
|
}
|
|
23
25
|
|
|
24
|
-
interface
|
|
26
|
+
interface FontCacheFile {
|
|
27
|
+
path: string;
|
|
28
|
+
size: number;
|
|
29
|
+
sha256: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface FontOptimizerCache extends BuildCacheStamp {
|
|
25
33
|
version: number;
|
|
26
34
|
key: string;
|
|
27
35
|
css: string;
|
|
28
|
-
files:
|
|
36
|
+
files: FontCacheFile[];
|
|
29
37
|
}
|
|
30
38
|
|
|
31
39
|
export type FontOptimizerCommand = "build" | "start";
|
|
@@ -34,17 +42,21 @@ export class FontOptimizer {
|
|
|
34
42
|
#app: App;
|
|
35
43
|
#command: FontOptimizerCommand;
|
|
36
44
|
#artifactRoot: string;
|
|
45
|
+
#cacheRoot: string;
|
|
46
|
+
#stamp = buildCacheStamp([import.meta.path]);
|
|
37
47
|
#files: string[] = [];
|
|
38
48
|
#cssParts: string[] = [];
|
|
39
49
|
#woff2Ready: Promise<void> | null = null;
|
|
40
50
|
|
|
41
51
|
static #ksX1001Text: string | null = null;
|
|
42
|
-
static readonly #cacheVersion =
|
|
52
|
+
static readonly #cacheVersion = 4;
|
|
43
53
|
|
|
44
54
|
constructor(app: App, command: FontOptimizerCommand = "start") {
|
|
45
55
|
this.#app = app;
|
|
46
56
|
this.#command = command;
|
|
47
57
|
this.#artifactRoot = path.join(command === "build" ? app.dist.cwdPath : app.cwdPath, ".akan/artifact");
|
|
58
|
+
//? A build reads fonts from fresh `dist/public` copies, whose stamps never match, so it caches beside its output.
|
|
59
|
+
this.#cacheRoot = command === "build" ? this.#artifactRoot : path.join(app.cwdPath, ".akan/cache");
|
|
48
60
|
}
|
|
49
61
|
|
|
50
62
|
async optimize(): Promise<OptimizeAppFontsResult> {
|
|
@@ -62,24 +74,25 @@ export class FontOptimizer {
|
|
|
62
74
|
const fontUtilityCss = this.#buildFontUtilityRules(fonts);
|
|
63
75
|
if (fontUtilityCss) this.#cssParts.push(fontUtilityCss);
|
|
64
76
|
const result = { css: this.#cssParts.join("\n"), fonts, files: this.#files };
|
|
65
|
-
|
|
77
|
+
// An unwritable cache is a slower start, never a failed one.
|
|
78
|
+
if (cacheKey) await this.#writeCache(cacheKey, result).catch(() => undefined);
|
|
66
79
|
return result;
|
|
67
80
|
}
|
|
68
81
|
|
|
69
82
|
get #cachePath() {
|
|
70
|
-
return path.join(this.#
|
|
83
|
+
return path.join(this.#cacheRoot, "fontCache.json");
|
|
71
84
|
}
|
|
72
85
|
|
|
73
|
-
// null skips the cache: an
|
|
86
|
+
// null skips the cache: an unreadable source's staleness is undetectable, and the uncached path warns about it.
|
|
74
87
|
async #buildCacheKey(fonts: ReactFont[]): Promise<string | null> {
|
|
75
88
|
const sources: unknown[] = [];
|
|
76
89
|
for (const font of fonts) {
|
|
77
90
|
if (!this.#isFontOptimizationEnabled(font)) continue;
|
|
78
91
|
for (const face of this.#getFontFaces(font)) {
|
|
79
92
|
const sourcePath = await this.#resolveFontSourcePath(face.src);
|
|
80
|
-
const
|
|
81
|
-
if (!
|
|
82
|
-
sources.push({ optimizedSrc: face.optimizedSrc, ...
|
|
93
|
+
const digest = sourcePath ? await this.#fileDigest(sourcePath) : null;
|
|
94
|
+
if (!digest) return null;
|
|
95
|
+
sources.push({ optimizedSrc: face.optimizedSrc, sourcePath, ...digest });
|
|
83
96
|
}
|
|
84
97
|
for (const filePath of font.subsetFiles ?? []) {
|
|
85
98
|
const abs = path.isAbsolute(filePath) ? filePath : path.join(this.#app.cwdPath, filePath);
|
|
@@ -90,7 +103,31 @@ export class FontOptimizer {
|
|
|
90
103
|
if (this.#getFontSubsets(font).includes("auto"))
|
|
91
104
|
sources.push({ autoSubsetText: this.#cacheDigest(await this.#collectAutoSubsetText()) });
|
|
92
105
|
}
|
|
93
|
-
|
|
106
|
+
const lockfile = await this.#lockfileDigest();
|
|
107
|
+
return this.#cacheDigest({
|
|
108
|
+
version: FontOptimizer.#cacheVersion,
|
|
109
|
+
command: this.#command,
|
|
110
|
+
lockfile,
|
|
111
|
+
fonts,
|
|
112
|
+
sources,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
//? Only the lockfile moves when the subsetter, the woff2 encoder or fontaine's metrics change version.
|
|
117
|
+
async #lockfileDigest() {
|
|
118
|
+
const root = this.#app.workspace.workspaceRoot;
|
|
119
|
+
const lockfiles = await Promise.all(
|
|
120
|
+
["bun.lock", "bun.lockb"].map((name) =>
|
|
121
|
+
Bun.file(path.join(root, name))
|
|
122
|
+
.bytes()
|
|
123
|
+
.catch(() => null),
|
|
124
|
+
),
|
|
125
|
+
);
|
|
126
|
+
return lockfiles.map((bytes) => (bytes ? this.#sha256(bytes) : null));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#sha256(bytes: Uint8Array) {
|
|
130
|
+
return new Bun.CryptoHasher("sha256").update(bytes).digest("hex");
|
|
94
131
|
}
|
|
95
132
|
|
|
96
133
|
// sha256, not #hashFontConfig's 32-bit FNV: a key collision would serve a stale subset as current.
|
|
@@ -98,6 +135,13 @@ export class FontOptimizer {
|
|
|
98
135
|
return new Bun.CryptoHasher("sha256").update(this.#stableStringify(value)).digest("hex");
|
|
99
136
|
}
|
|
100
137
|
|
|
138
|
+
async #fileDigest(filePath: string): Promise<{ size: number; sha256: string } | null> {
|
|
139
|
+
const bytes = await Bun.file(filePath)
|
|
140
|
+
.bytes()
|
|
141
|
+
.catch(() => null);
|
|
142
|
+
return bytes ? { size: bytes.byteLength, sha256: this.#sha256(bytes) } : null;
|
|
143
|
+
}
|
|
144
|
+
|
|
101
145
|
async #fileStamp(filePath: string): Promise<{ mtimeMs: number; size: number } | null> {
|
|
102
146
|
try {
|
|
103
147
|
const stats = await stat(filePath);
|
|
@@ -110,23 +154,64 @@ export class FontOptimizer {
|
|
|
110
154
|
async #readCache(key: string): Promise<{ css: string; files: string[] } | null> {
|
|
111
155
|
const cache = (await Bun.file(this.#cachePath)
|
|
112
156
|
.json()
|
|
113
|
-
.catch(() => null)) as FontOptimizerCache | null;
|
|
114
|
-
if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
157
|
+
.catch(() => null)) as Partial<FontOptimizerCache> | null;
|
|
158
|
+
if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key || typeof cache.css !== "string")
|
|
159
|
+
return null;
|
|
160
|
+
if (!isBuildCacheStamp(cache, this.#stamp) || !Array.isArray(cache.files)) return null;
|
|
161
|
+
const files: string[] = [];
|
|
162
|
+
for (const file of cache.files) {
|
|
163
|
+
const bytes = await this.#readIntact(this.#cacheRoot, file);
|
|
164
|
+
if (!bytes) return null;
|
|
165
|
+
if (this.#cacheRoot !== this.#artifactRoot && !(await this.#readIntact(this.#artifactRoot, file)))
|
|
166
|
+
await Bun.write(path.join(this.#artifactRoot, file.path), bytes);
|
|
167
|
+
files.push(path.join(this.#artifactRoot, file.path));
|
|
118
168
|
}
|
|
119
169
|
return { css: cache.css, files };
|
|
120
170
|
}
|
|
121
171
|
|
|
172
|
+
// A start killed mid-write leaves a short or stale file under the name the entry lists, so the bytes must match.
|
|
173
|
+
async #readIntact(root: string, file: Partial<FontCacheFile> | null): Promise<Uint8Array | null> {
|
|
174
|
+
if (typeof file?.path !== "string" || typeof file.size !== "number") return null;
|
|
175
|
+
const bytes = await Bun.file(path.join(root, file.path))
|
|
176
|
+
.bytes()
|
|
177
|
+
.catch(() => null);
|
|
178
|
+
if (!bytes || bytes.byteLength !== file.size || this.#sha256(bytes) !== file.sha256) return null;
|
|
179
|
+
return bytes;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// The entry is written last, so a start killed before it keeps the previous entry, which its checksums then refuse.
|
|
122
183
|
async #writeCache(key: string, result: OptimizeAppFontsResult): Promise<void> {
|
|
184
|
+
const files: FontCacheFile[] = [];
|
|
185
|
+
for (const filePath of result.files) {
|
|
186
|
+
const bytes = await Bun.file(filePath).bytes();
|
|
187
|
+
const relativePath = path.relative(this.#artifactRoot, filePath);
|
|
188
|
+
const cachedPath = path.join(this.#cacheRoot, relativePath);
|
|
189
|
+
if (cachedPath !== filePath) await FileSys.writeTextAtomic(cachedPath, bytes);
|
|
190
|
+
files.push({ path: relativePath, size: bytes.byteLength, sha256: this.#sha256(bytes) });
|
|
191
|
+
}
|
|
123
192
|
const cache: FontOptimizerCache = {
|
|
124
193
|
version: FontOptimizer.#cacheVersion,
|
|
194
|
+
...this.#stamp,
|
|
125
195
|
key,
|
|
126
196
|
css: result.css,
|
|
127
|
-
files
|
|
197
|
+
files,
|
|
128
198
|
};
|
|
129
|
-
await
|
|
199
|
+
await FileSys.writeTextAtomic(this.#cachePath, JSON.stringify(cache));
|
|
200
|
+
await this.#pruneCachedFonts(files);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async #pruneCachedFonts(kept: FontCacheFile[]) {
|
|
204
|
+
if (this.#cacheRoot === this.#artifactRoot) return;
|
|
205
|
+
const dir = path.join(this.#cacheRoot, FONT_URL_PREFIX.replace(/^\/_akan\//, ""));
|
|
206
|
+
const keep = new Set(kept.map((file) => path.join(this.#cacheRoot, file.path)));
|
|
207
|
+
const names = await readdir(dir).catch(() => [] as string[]);
|
|
208
|
+
await Promise.all(
|
|
209
|
+
names
|
|
210
|
+
.filter((name) => !name.endsWith(".tmp"))
|
|
211
|
+
.map((name) => path.join(dir, name))
|
|
212
|
+
.filter((filePath) => !keep.has(filePath))
|
|
213
|
+
.map((filePath) => rm(filePath, { force: true })),
|
|
214
|
+
);
|
|
130
215
|
}
|
|
131
216
|
|
|
132
217
|
async discoverFonts(): Promise<ReactFont[]> {
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { PlainStylesheet, type StylesheetLoader } from "./plainStylesheet";
|
|
4
|
+
|
|
5
|
+
const loaderOf = (files: Record<string, string>): StylesheetLoader => {
|
|
6
|
+
return async (id, fromBase) => {
|
|
7
|
+
const filePath = path.resolve(fromBase, id);
|
|
8
|
+
const content = files[filePath];
|
|
9
|
+
if (content === undefined) throw new Error(`no stylesheet at ${filePath}`);
|
|
10
|
+
return { path: filePath, base: path.dirname(filePath), content };
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
const refuseLoad: StylesheetLoader = async (id) => {
|
|
14
|
+
throw new Error(`loaded ${id}`);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
describe("PlainStylesheet.scan", () => {
|
|
18
|
+
test("finds nothing Tailwind in plain CSS", () => {
|
|
19
|
+
const css = [
|
|
20
|
+
'@charset "utf-8";',
|
|
21
|
+
"@layer reset, app;",
|
|
22
|
+
":root { --brand: #111; }",
|
|
23
|
+
"@media (prefers-reduced-motion: reduce) { .a { animation: none; } }",
|
|
24
|
+
"@supports (display: grid) { .grid { display: grid; } }",
|
|
25
|
+
"@container card (min-width: 20rem) { .b { color: color-mix(in oklab, var(--brand) 50%, transparent); } }",
|
|
26
|
+
"@font-face { font-family: X; src: url(data:font/woff2;base64,AAAA) format('woff2'); }",
|
|
27
|
+
"@keyframes spin { to { transform: rotate(1turn); } }",
|
|
28
|
+
'.c::before { content: "@apply theme(x)"; }',
|
|
29
|
+
"/* @theme { --color-x: red; } and --spacing(4) */",
|
|
30
|
+
".icon { background: url(icon@2x.png); }",
|
|
31
|
+
].join("\n");
|
|
32
|
+
expect(PlainStylesheet.scan(css)).toEqual([]);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test.each([
|
|
36
|
+
"@tailwind utilities;",
|
|
37
|
+
"@TAILWIND utilities;",
|
|
38
|
+
".a { @apply flex; }",
|
|
39
|
+
'@plugin "tailwind-scrollbar";',
|
|
40
|
+
'@config "./tailwind.config.js";',
|
|
41
|
+
"@theme { --color-brand: red; }",
|
|
42
|
+
"@theme inline { --color-brand: var(--brand); }",
|
|
43
|
+
"@utility tab-4 { tab-size: 4; }",
|
|
44
|
+
".a { @variant hover { color: red; } }",
|
|
45
|
+
"@custom-variant dark (&:where([data-theme=dark] *));",
|
|
46
|
+
"@custom-variant any-hover { @media (any-hover: hover) { &:hover { @slot; } } }",
|
|
47
|
+
'@source "../node_modules/x";',
|
|
48
|
+
'@source not "./legacy";',
|
|
49
|
+
'@source inline("underline");',
|
|
50
|
+
'@reference "./app.css";',
|
|
51
|
+
".a { color: theme(colors.red.500); }",
|
|
52
|
+
".a { color: --theme(--color-red-500); }",
|
|
53
|
+
".a { color: --alpha(var(--brand) / 50%); }",
|
|
54
|
+
".a { margin: --spacing(4); }",
|
|
55
|
+
"@media (width >= theme(--breakpoint-md)) { .a { color: red; } }",
|
|
56
|
+
"@media source(none) { .a { color: red; } }",
|
|
57
|
+
'@import "tailwindcss";',
|
|
58
|
+
"@import 'tailwindcss';",
|
|
59
|
+
'@import "tailwindcss/theme.css" layer(theme);',
|
|
60
|
+
'@import "tailwindcss/utilities";',
|
|
61
|
+
'@import "./theme.css" theme(reference);',
|
|
62
|
+
'@import "./app.css" source(none);',
|
|
63
|
+
'@import "./app.css" prefix(tw);',
|
|
64
|
+
'@import "./app.css" important;',
|
|
65
|
+
'@import "./app.css" reference;',
|
|
66
|
+
])("needs Tailwind: %s", (css) => {
|
|
67
|
+
expect(PlainStylesheet.scan(css)).toBeNull();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("reads the conditions of an import Tailwind would inline", () => {
|
|
71
|
+
const css = [
|
|
72
|
+
'@import "./a.css";',
|
|
73
|
+
"@import './b.css' layer;",
|
|
74
|
+
'@import "./c.css" layer(base) supports(display: grid) screen and (min-width: 40rem);',
|
|
75
|
+
'@import "./d.css" supports((display: flex) and (gap: 1rem)) print;',
|
|
76
|
+
].join("\n");
|
|
77
|
+
expect(
|
|
78
|
+
PlainStylesheet.scan(css)?.map(({ uri, layer, supports, media }) => ({ uri, layer, supports, media })),
|
|
79
|
+
).toEqual([
|
|
80
|
+
{ uri: "./a.css", layer: null, supports: null, media: null },
|
|
81
|
+
{ uri: "./b.css", layer: "", supports: null, media: null },
|
|
82
|
+
{ uri: "./c.css", layer: "base", supports: "display: grid", media: "screen and (min-width: 40rem)" },
|
|
83
|
+
{ uri: "./d.css", layer: null, supports: "(display: flex) and (gap: 1rem)", media: "print" },
|
|
84
|
+
]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("leaves url(), data: and remote imports where they stand, as Tailwind does", () => {
|
|
88
|
+
const css = [
|
|
89
|
+
'@import url("./a.css");',
|
|
90
|
+
"@import url(./b.css) screen;",
|
|
91
|
+
'@import "https://fonts.example.com/x.css";',
|
|
92
|
+
'@import "data:text/css,.a{color:red}";',
|
|
93
|
+
].join("\n");
|
|
94
|
+
expect(PlainStylesheet.scan(css)).toEqual([]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("defers to Tailwind on CSS it cannot read with certainty", () => {
|
|
98
|
+
expect(PlainStylesheet.scan("/* never closed")).toBeNull();
|
|
99
|
+
expect(PlainStylesheet.scan(".a { color: red;")).toBeNull();
|
|
100
|
+
expect(PlainStylesheet.scan(".a { color: red; } }")).toBeNull();
|
|
101
|
+
expect(PlainStylesheet.scan('@import "./a.css" layer(x) layer(y);')).toBeNull();
|
|
102
|
+
expect(PlainStylesheet.scan('@import "./a.css" supports(display: grid;')).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe("PlainStylesheet.bundle", () => {
|
|
107
|
+
test("returns a stylesheet without imports byte for byte", async () => {
|
|
108
|
+
const css = "/* brand */\n:root {\n --brand: #111;\n}\n.a { color: var(--brand) }";
|
|
109
|
+
expect(await PlainStylesheet.bundle(css, "/app", refuseLoad)).toBe(css);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("inlines imports, nested ones too, wrapped in their layer, supports and media conditions", async () => {
|
|
113
|
+
const load = loaderOf({
|
|
114
|
+
"/app/a.css": '@import "./nested/b.css";\n.a { color: red; }\n',
|
|
115
|
+
"/app/nested/b.css": ".b { color: blue; }",
|
|
116
|
+
"/app/c.css": ".c { color: green; }",
|
|
117
|
+
});
|
|
118
|
+
const css =
|
|
119
|
+
'@import "./a.css";\n@import "./c.css" layer(base) supports(display: grid) print;\n.app { margin: 0; }\n';
|
|
120
|
+
|
|
121
|
+
expect(await PlainStylesheet.bundle(css, "/app", load)).toBe(
|
|
122
|
+
[
|
|
123
|
+
".b { color: blue; }",
|
|
124
|
+
".a { color: red; }",
|
|
125
|
+
"",
|
|
126
|
+
"@supports (display: grid) {",
|
|
127
|
+
"@media print {",
|
|
128
|
+
"@layer base {",
|
|
129
|
+
".c { color: green; }",
|
|
130
|
+
"}",
|
|
131
|
+
"}",
|
|
132
|
+
"}",
|
|
133
|
+
".app { margin: 0; }",
|
|
134
|
+
"",
|
|
135
|
+
].join("\n"),
|
|
136
|
+
);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("needs Tailwind when only an imported stylesheet uses it", async () => {
|
|
140
|
+
const load = loaderOf({
|
|
141
|
+
"/app/a.css": '@import "./b.css";\n',
|
|
142
|
+
"/app/b.css": ".b { color: red; }\n@custom-variant dark (&:where(.dark *));\n",
|
|
143
|
+
});
|
|
144
|
+
expect(await PlainStylesheet.bundle('@import "./a.css";\n.app { margin: 0; }\n', "/app", load)).toBeNull();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('decides on `@import "tailwindcss"` without resolving it', async () => {
|
|
148
|
+
expect(await PlainStylesheet.bundle('@import "tailwindcss";\n.a { color: red; }\n', "/app", refuseLoad)).toBeNull();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("hands an import cycle to Tailwind instead of following it forever", async () => {
|
|
152
|
+
const load = loaderOf({ "/app/a.css": '@import "./b.css";', "/app/b.css": '@import "./a.css";' });
|
|
153
|
+
expect(await PlainStylesheet.bundle('@import "./a.css";', "/app", load)).toBeNull();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
export interface LoadedStylesheet {
|
|
2
|
+
path: string;
|
|
3
|
+
base: string;
|
|
4
|
+
content: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export type StylesheetLoader = (id: string, fromBase: string) => Promise<LoadedStylesheet>;
|
|
8
|
+
|
|
9
|
+
interface ImportConditions {
|
|
10
|
+
layer: string | null;
|
|
11
|
+
supports: string | null;
|
|
12
|
+
media: string | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface PlainImport extends ImportConditions {
|
|
16
|
+
start: number;
|
|
17
|
+
end: number;
|
|
18
|
+
uri: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Every at-rule Tailwind v4's `compile()` acts on (`parseCss`, `substituteAtImports`, `registerPlugins`, `@apply`).
|
|
22
|
+
const TAILWIND_AT_RULES = new Set([
|
|
23
|
+
"@tailwind",
|
|
24
|
+
"@apply",
|
|
25
|
+
"@plugin",
|
|
26
|
+
"@config",
|
|
27
|
+
"@theme",
|
|
28
|
+
"@utility",
|
|
29
|
+
"@variant",
|
|
30
|
+
"@custom-variant",
|
|
31
|
+
"@slot",
|
|
32
|
+
"@source",
|
|
33
|
+
"@reference",
|
|
34
|
+
]);
|
|
35
|
+
// Tailwind's own test (`theme\(` also covers `--theme(`), run over declaration values and media/supports params.
|
|
36
|
+
const TAILWIND_FUNCTION_RE = /(?:--alpha|--spacing|theme)\(/;
|
|
37
|
+
// `@import "x" theme(…)`, `source(…)`, `prefix(…)`, `important` and `reference` become Tailwind-only `@media` params.
|
|
38
|
+
const TAILWIND_CONDITION_RE = /\b(?:source|prefix|theme)\(|(?:^|\s)(?:important|reference)(?=\s|$)/i;
|
|
39
|
+
const TAILWIND_PACKAGE_RE = /^tailwindcss(?:\/|$)/;
|
|
40
|
+
const REMOTE_URI_RE = /^(?:data:|https?:\/\/)/i;
|
|
41
|
+
const COMMENT_RE = /\/\*[\s\S]*?\*\//g;
|
|
42
|
+
const AT_KEYWORD_RE = /@[\w-]+/y;
|
|
43
|
+
const QUOTED_IMPORT_RE = /^\s*(["'])((?:\\[\s\S]|(?!\1)[^\\\n])*)\1([\s\S]*)$/;
|
|
44
|
+
const LAYER_RE = /^layer(?:\(\s*([^()]*?)\s*\))?(?![\w(-])/i;
|
|
45
|
+
const MAX_IMPORT_DEPTH = 100;
|
|
46
|
+
|
|
47
|
+
interface OpenAtRule {
|
|
48
|
+
name: string;
|
|
49
|
+
start: number;
|
|
50
|
+
preludeStart: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type AtRuleVerdict = (ImportConditions & { uri: string }) | "tailwind" | "plain";
|
|
54
|
+
|
|
55
|
+
export class PlainStylesheet {
|
|
56
|
+
static async bundle(css: string, base: string, load: StylesheetLoader, depth = 0): Promise<string | null> {
|
|
57
|
+
//? Past Tailwind's own depth limit (an import cycle), `compile()` runs instead and reports it.
|
|
58
|
+
if (depth > MAX_IMPORT_DEPTH) return null;
|
|
59
|
+
const imports = PlainStylesheet.scan(css);
|
|
60
|
+
if (!imports) return null;
|
|
61
|
+
const parts: string[] = [];
|
|
62
|
+
let cursor = 0;
|
|
63
|
+
for (const rule of imports) {
|
|
64
|
+
const loaded = await load(rule.uri, base);
|
|
65
|
+
const inner = await PlainStylesheet.bundle(loaded.content, loaded.base, load, depth + 1);
|
|
66
|
+
if (inner === null) return null;
|
|
67
|
+
parts.push(css.slice(cursor, rule.start), PlainStylesheet.#wrap(inner, rule));
|
|
68
|
+
cursor = rule.end;
|
|
69
|
+
}
|
|
70
|
+
parts.push(css.slice(cursor));
|
|
71
|
+
return parts.join("");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
static scan(css: string): PlainImport[] | null {
|
|
75
|
+
const imports: PlainImport[] = [];
|
|
76
|
+
const code: string[] = [];
|
|
77
|
+
let segmentStart = 0;
|
|
78
|
+
let parenDepth = 0;
|
|
79
|
+
let braceDepth = 0;
|
|
80
|
+
let atRule: OpenAtRule | null = null;
|
|
81
|
+
let idx = 0;
|
|
82
|
+
while (idx < css.length) {
|
|
83
|
+
const char = css[idx];
|
|
84
|
+
if (char === "/" && css[idx + 1] === "*") {
|
|
85
|
+
const end = css.indexOf("*/", idx + 2);
|
|
86
|
+
if (end === -1) return null;
|
|
87
|
+
code.push(css.slice(segmentStart, idx));
|
|
88
|
+
idx = segmentStart = end + 2;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (char === "\\") {
|
|
92
|
+
idx += 2;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (char === '"' || char === "'") {
|
|
96
|
+
code.push(css.slice(segmentStart, idx));
|
|
97
|
+
idx = segmentStart = PlainStylesheet.#skipString(css, idx);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (char === "@" && !atRule && parenDepth === 0) {
|
|
101
|
+
AT_KEYWORD_RE.lastIndex = idx;
|
|
102
|
+
const keyword = AT_KEYWORD_RE.exec(css);
|
|
103
|
+
if (keyword) {
|
|
104
|
+
const name = keyword[0].toLowerCase();
|
|
105
|
+
if (TAILWIND_AT_RULES.has(name)) return null;
|
|
106
|
+
atRule = { name, start: idx, preludeStart: idx + keyword[0].length };
|
|
107
|
+
idx += keyword[0].length;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (char === "(") parenDepth += 1;
|
|
112
|
+
else if (char === ")") parenDepth = Math.max(0, parenDepth - 1);
|
|
113
|
+
else if (parenDepth === 0 && (char === ";" || char === "{" || char === "}")) {
|
|
114
|
+
if (atRule && !PlainStylesheet.#closeAtRule(css, atRule, idx, char, imports)) return null;
|
|
115
|
+
atRule = null;
|
|
116
|
+
braceDepth += char === "{" ? 1 : char === "}" ? -1 : 0;
|
|
117
|
+
if (braceDepth < 0) return null;
|
|
118
|
+
}
|
|
119
|
+
idx += 1;
|
|
120
|
+
}
|
|
121
|
+
if (atRule && !PlainStylesheet.#closeAtRule(css, atRule, css.length, "", imports)) return null;
|
|
122
|
+
if (braceDepth !== 0 || parenDepth !== 0) return null;
|
|
123
|
+
code.push(css.slice(segmentStart));
|
|
124
|
+
return TAILWIND_FUNCTION_RE.test(code.join(" ")) ? null : imports;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
static #closeAtRule(css: string, atRule: OpenAtRule, end: number, terminator: string, imports: PlainImport[]) {
|
|
128
|
+
const prelude = css.slice(atRule.preludeStart, end).replace(COMMENT_RE, " ");
|
|
129
|
+
const verdict = PlainStylesheet.#readAtRule(atRule.name, prelude, terminator === "{");
|
|
130
|
+
if (verdict === "tailwind") return false;
|
|
131
|
+
if (verdict !== "plain") imports.push({ ...verdict, start: atRule.start, end: terminator === ";" ? end + 1 : end });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
static #readAtRule(name: string, prelude: string, opensBlock: boolean): AtRuleVerdict {
|
|
136
|
+
if (name === "@media") return TAILWIND_CONDITION_RE.test(prelude) ? "tailwind" : "plain";
|
|
137
|
+
if (name !== "@import") return "plain";
|
|
138
|
+
const match = QUOTED_IMPORT_RE.exec(prelude);
|
|
139
|
+
//? Tailwind leaves an `@import url(…)` where it stands, so this does too.
|
|
140
|
+
if (!match) return "plain";
|
|
141
|
+
const [, , uri = "", rest = ""] = match;
|
|
142
|
+
if (TAILWIND_PACKAGE_RE.test(uri) || TAILWIND_CONDITION_RE.test(rest) || opensBlock) return "tailwind";
|
|
143
|
+
if (REMOTE_URI_RE.test(uri)) return "plain";
|
|
144
|
+
const conditions = PlainStylesheet.#parseConditions(rest.trim());
|
|
145
|
+
return conditions ? { uri, ...conditions } : "tailwind";
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
static #parseConditions(text: string): ImportConditions | null {
|
|
149
|
+
let rest = text;
|
|
150
|
+
let layer: string | null = null;
|
|
151
|
+
let supports: string | null = null;
|
|
152
|
+
const layerMatch = LAYER_RE.exec(rest);
|
|
153
|
+
if (layerMatch) {
|
|
154
|
+
layer = layerMatch[1] ?? "";
|
|
155
|
+
rest = rest.slice(layerMatch[0].length).trim();
|
|
156
|
+
}
|
|
157
|
+
if (/^supports\(/i.test(rest)) {
|
|
158
|
+
const close = PlainStylesheet.#closingParen(rest, "supports".length);
|
|
159
|
+
if (close === -1) return null;
|
|
160
|
+
supports = rest.slice("supports(".length, close).trim();
|
|
161
|
+
rest = rest.slice(close + 1).trim();
|
|
162
|
+
}
|
|
163
|
+
if (/["']|\burl\(|\blayer\b|\bsupports\(/i.test(rest)) return null;
|
|
164
|
+
return { layer, supports, media: rest || null };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
static #closingParen(text: string, open: number): number {
|
|
168
|
+
let depth = 0;
|
|
169
|
+
for (let idx = open; idx < text.length; idx++) {
|
|
170
|
+
if (text[idx] === "(") depth += 1;
|
|
171
|
+
else if (text[idx] === ")" && --depth === 0) return idx;
|
|
172
|
+
}
|
|
173
|
+
return -1;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
static #wrap(css: string, { layer, media, supports }: PlainImport): string {
|
|
177
|
+
let wrapped = css;
|
|
178
|
+
if (layer !== null) wrapped = `@layer${layer ? ` ${layer}` : ""} {\n${wrapped}\n}`;
|
|
179
|
+
if (media !== null) wrapped = `@media ${media} {\n${wrapped}\n}`;
|
|
180
|
+
if (supports !== null)
|
|
181
|
+
wrapped = `@supports ${supports.startsWith("(") ? supports : `(${supports})`} {\n${wrapped}\n}`;
|
|
182
|
+
return wrapped;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
static #skipString(css: string, start: number): number {
|
|
186
|
+
const quote = css[start];
|
|
187
|
+
let idx = start + 1;
|
|
188
|
+
while (idx < css.length) {
|
|
189
|
+
const char = css[idx];
|
|
190
|
+
if (char === "\\") idx += 2;
|
|
191
|
+
else if (char === quote) return idx + 1;
|
|
192
|
+
else if (char === "\n") return idx;
|
|
193
|
+
else idx += 1;
|
|
194
|
+
}
|
|
195
|
+
return css.length;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -1,6 +1,35 @@
|
|
|
1
|
-
import { describe, expect, test } from "bun:test";
|
|
1
|
+
import { describe, expect, spyOn, test } from "bun:test";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdtemp, readdir, rm } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import type { BaseBuildArtifact } from "akanjs/server";
|
|
2
7
|
import { SsrBaseArtifactBuilder } from "./ssrBaseArtifactBuilder";
|
|
3
8
|
|
|
9
|
+
describe("SsrBaseArtifactBuilder.writeArtifact", () => {
|
|
10
|
+
test("writes beside the final path and renames into it, so a reader never finds a half-written artifact", async () => {
|
|
11
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), "akan-base-artifact-"));
|
|
12
|
+
const finalPath = path.join(dir, "base-artifact.json");
|
|
13
|
+
const artifact = { domains: ["a.example.com"], pagesBundlePath: "/app/pages.js" } as unknown as BaseBuildArtifact;
|
|
14
|
+
const write = Bun.write;
|
|
15
|
+
const seen: { target: string; finalExisted: boolean }[] = [];
|
|
16
|
+
const written = spyOn(Bun, "write").mockImplementation(((target: string, data: string) => {
|
|
17
|
+
seen.push({ target: String(target), finalExisted: existsSync(finalPath) });
|
|
18
|
+
return write(target, data);
|
|
19
|
+
}) as typeof Bun.write);
|
|
20
|
+
try {
|
|
21
|
+
await SsrBaseArtifactBuilder.writeArtifact(dir, artifact);
|
|
22
|
+
} finally {
|
|
23
|
+
written.mockRestore();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
expect(seen).toEqual([{ target: `${finalPath}.tmp`, finalExisted: false }]);
|
|
27
|
+
expect(await Bun.file(finalPath).json()).toEqual(artifact);
|
|
28
|
+
expect(await readdir(dir)).toEqual(["base-artifact.json"]);
|
|
29
|
+
await rm(dir, { recursive: true, force: true });
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
4
33
|
describe("SsrBaseArtifactBuilder.outletModuleMap", () => {
|
|
5
34
|
const outlet = "pkgs/akanjs/server/rscSegmentOutlet.tsx";
|
|
6
35
|
const ssrOutput = "/dist/client-ssr/rscSegmentOutlet.js";
|