@akanjs/devkit 3.2.0 → 3.2.1-rc.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.
- package/CHANGELOG.md +94 -0
- 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/executors/appExecutor.ts +19 -4
- 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/fontOptimizer.test.ts +144 -3
- package/frontendBuild/fontOptimizer.ts +103 -18
- package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
- package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
- 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/nativePublicEnv.ts +2 -1
- package/package.json +3 -3
- package/util/fileSys.test.ts +13 -0
- package/util/fileSys.ts +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
|
-
import { mkdir, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { chmod, mkdir, rm, stat, utimes, writeFile } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import type { App } from "../commandDecorators";
|
|
5
5
|
import { tempDirs } from "../test/testHelpers";
|
|
@@ -17,15 +17,17 @@ const makeApp = async (layoutSource: string) => {
|
|
|
17
17
|
await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutSource);
|
|
18
18
|
await Bun.write(path.join(cwdPath, "public/fonts/Assistant-Regular.woff2"), Bun.file(SOURCE_FONT));
|
|
19
19
|
const warnings: string[] = [];
|
|
20
|
+
const verboses: string[] = [];
|
|
20
21
|
const app = {
|
|
21
22
|
cwdPath,
|
|
22
23
|
dist: { cwdPath: path.join(root, "dist/apps/demo") },
|
|
23
24
|
workspace: { workspaceRoot: root },
|
|
24
25
|
getPageKeys: async () => ["./_layout.tsx"],
|
|
25
|
-
verbose: () =>
|
|
26
|
+
verbose: (message: string) => verboses.push(message),
|
|
26
27
|
logger: { warn: (message: string) => warnings.push(message) },
|
|
27
28
|
} as unknown as App;
|
|
28
|
-
|
|
29
|
+
const reusedCount = () => verboses.filter((message) => message.startsWith("[font] reused")).length;
|
|
30
|
+
return { app, cwdPath, root, warnings, reusedCount };
|
|
29
31
|
};
|
|
30
32
|
|
|
31
33
|
const layoutWith = (extra = "") => `
|
|
@@ -125,6 +127,145 @@ describe("FontOptimizer cache", () => {
|
|
|
125
127
|
expect(await Bun.file(second.files[0]).exists()).toBe(true);
|
|
126
128
|
});
|
|
127
129
|
|
|
130
|
+
test("reuses the subset on the next akan start, which wipes the artifact folder", async () => {
|
|
131
|
+
const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
|
|
132
|
+
const first = await optimize(app);
|
|
133
|
+
const firstBytes = await Bun.file(first.files[0]).bytes();
|
|
134
|
+
await rm(path.join(cwdPath, ".akan/artifact"), { recursive: true, force: true });
|
|
135
|
+
|
|
136
|
+
const second = await optimize(app);
|
|
137
|
+
expect(reusedCount()).toBe(1);
|
|
138
|
+
expect(second.files).toEqual(first.files);
|
|
139
|
+
expect(second.css).toBe(first.css);
|
|
140
|
+
expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test.each(["akanjs", "bun", "code"])("resubsets when the cache was written by another %s version", async (field) => {
|
|
144
|
+
const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
|
|
145
|
+
await optimize(app);
|
|
146
|
+
const indexPath = path.join(cwdPath, ".akan/cache/fontCache.json");
|
|
147
|
+
const index = await Bun.file(indexPath).json();
|
|
148
|
+
await Bun.write(indexPath, JSON.stringify({ ...index, [field]: "0.0.1-other" }));
|
|
149
|
+
|
|
150
|
+
await optimize(app);
|
|
151
|
+
expect(reusedCount()).toBe(0);
|
|
152
|
+
expect((await Bun.file(indexPath).json())[field]).toBe(index[field]);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test("resubsets when the lockfile changes, since a font tool version may have moved", async () => {
|
|
156
|
+
const { app, root, reusedCount } = await makeApp(layoutWith());
|
|
157
|
+
await writeFile(path.join(root, "bun.lock"), '{ "lockfileVersion": 1 }\n');
|
|
158
|
+
await optimize(app);
|
|
159
|
+
await optimize(app);
|
|
160
|
+
expect(reusedCount()).toBe(1);
|
|
161
|
+
|
|
162
|
+
await writeFile(path.join(root, "bun.lock"), '{ "lockfileVersion": 1, "packages": {} }\n');
|
|
163
|
+
await optimize(app);
|
|
164
|
+
expect(reusedCount()).toBe(1);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("rebuilds a cached font file that was cut short", async () => {
|
|
168
|
+
const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
|
|
169
|
+
const first = await optimize(app);
|
|
170
|
+
const firstBytes = await Bun.file(first.files[0]).bytes();
|
|
171
|
+
const cachedPath = path.join(
|
|
172
|
+
cwdPath,
|
|
173
|
+
".akan/cache",
|
|
174
|
+
path.relative(path.join(cwdPath, ".akan/artifact"), first.files[0]),
|
|
175
|
+
);
|
|
176
|
+
await Bun.write(cachedPath, firstBytes.subarray(0, firstBytes.byteLength / 2));
|
|
177
|
+
await rm(path.join(cwdPath, ".akan/artifact"), { recursive: true, force: true });
|
|
178
|
+
|
|
179
|
+
const second = await optimize(app);
|
|
180
|
+
expect(reusedCount()).toBe(0);
|
|
181
|
+
expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
|
|
182
|
+
expect(await Bun.file(cachedPath).bytes()).toEqual(firstBytes);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test("replaces an artifact copy that was cut short with the cached font", async () => {
|
|
186
|
+
const { app, reusedCount } = await makeApp(layoutWith());
|
|
187
|
+
const first = await optimize(app);
|
|
188
|
+
const firstBytes = await Bun.file(first.files[0]).bytes();
|
|
189
|
+
await Bun.write(first.files[0], firstBytes.subarray(0, 16));
|
|
190
|
+
|
|
191
|
+
const second = await optimize(app);
|
|
192
|
+
expect(reusedCount()).toBe(1);
|
|
193
|
+
expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("rebuilds when the cache index was cut short", async () => {
|
|
197
|
+
const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
|
|
198
|
+
const first = await optimize(app);
|
|
199
|
+
const indexPath = path.join(cwdPath, ".akan/cache/fontCache.json");
|
|
200
|
+
const index = await Bun.file(indexPath).text();
|
|
201
|
+
await Bun.write(indexPath, index.slice(0, index.length / 2));
|
|
202
|
+
|
|
203
|
+
const second = await optimize(app);
|
|
204
|
+
expect(reusedCount()).toBe(0);
|
|
205
|
+
expect(second.css).toBe(first.css);
|
|
206
|
+
expect(await Bun.file(indexPath).text()).toBe(index);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("drops cached font files the current entry no longer lists", async () => {
|
|
210
|
+
const { app, cwdPath } = await makeApp(layoutWith());
|
|
211
|
+
const first = await optimize(app);
|
|
212
|
+
const stalePath = path.join(cwdPath, ".akan/cache/fonts/Assistant-400-normal-stale.woff2");
|
|
213
|
+
await Bun.write(stalePath, "stale");
|
|
214
|
+
|
|
215
|
+
await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutWith(`\n className: "font-brand",`));
|
|
216
|
+
await optimize(app);
|
|
217
|
+
expect(await Bun.file(stalePath).exists()).toBe(false);
|
|
218
|
+
expect(
|
|
219
|
+
await Bun.file(
|
|
220
|
+
path.join(cwdPath, ".akan/cache", path.relative(path.join(cwdPath, ".akan/artifact"), first.files[0])),
|
|
221
|
+
).exists(),
|
|
222
|
+
).toBe(true);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
test("still writes the fonts when the cache folder cannot be written", async () => {
|
|
226
|
+
const { app, cwdPath } = await makeApp(layoutWith());
|
|
227
|
+
const cacheDir = path.join(cwdPath, ".akan/cache");
|
|
228
|
+
await mkdir(cacheDir, { recursive: true });
|
|
229
|
+
await chmod(cacheDir, 0o500);
|
|
230
|
+
try {
|
|
231
|
+
const result = await optimize(app);
|
|
232
|
+
expect(result.files).toHaveLength(1);
|
|
233
|
+
expect(await Bun.file(result.files[0]).exists()).toBe(true);
|
|
234
|
+
} finally {
|
|
235
|
+
await chmod(cacheDir, 0o700);
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test("resubsets when the source font is replaced by one of the same size and mtime", async () => {
|
|
240
|
+
const { app, cwdPath, reusedCount } = await makeApp(`
|
|
241
|
+
export const fonts = [{ name: "Gilda", paths: [{ src: "/fonts/Gilda.ttf", weight: 400 }] }];
|
|
242
|
+
export default function Layout() {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
`);
|
|
246
|
+
const sourcePath = path.join(cwdPath, "public/fonts/Gilda.ttf");
|
|
247
|
+
const source = await Bun.file(path.resolve(path.dirname(SOURCE_FONT), "GildaDisplay-Regular.ttf")).bytes();
|
|
248
|
+
await Bun.write(sourcePath, source);
|
|
249
|
+
await optimize(app);
|
|
250
|
+
const { mtime } = await stat(sourcePath);
|
|
251
|
+
|
|
252
|
+
await Bun.write(sourcePath, renameSfntTable(source.slice(), "OS/2", "XS/2"));
|
|
253
|
+
await utimes(sourcePath, mtime, mtime);
|
|
254
|
+
await optimize(app);
|
|
255
|
+
expect(reusedCount()).toBe(0);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test("leaves a temporary file another start is still writing in the cache folder", async () => {
|
|
259
|
+
const { app, cwdPath } = await makeApp(layoutWith());
|
|
260
|
+
await optimize(app);
|
|
261
|
+
const tempPath = path.join(cwdPath, ".akan/cache/fonts/Assistant-400-normal-abc.woff2.123.abc.tmp");
|
|
262
|
+
await Bun.write(tempPath, "in progress");
|
|
263
|
+
|
|
264
|
+
await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutWith(`\n className: "font-brand",`));
|
|
265
|
+
await optimize(app);
|
|
266
|
+
expect(await Bun.file(tempPath).exists()).toBe(true);
|
|
267
|
+
});
|
|
268
|
+
|
|
128
269
|
test("skips route files that never mention fonts", async () => {
|
|
129
270
|
const { app } = await makeApp("export default function Layout() {\n return null;\n}\n");
|
|
130
271
|
const result = await optimize(app);
|
|
@@ -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[]> {
|
|
@@ -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";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rename } from "node:fs/promises";
|
|
1
2
|
import path from "node:path";
|
|
2
3
|
import { optimize } from "@tailwindcss/node";
|
|
3
4
|
import type { AkanNativeAppId, AkanWebConfig } from "akanjs";
|
|
@@ -16,12 +17,15 @@ import type { RuntimeChunks } from "./routeModulePreloads";
|
|
|
16
17
|
import { VendorNarrowing } from "./vendorNarrowing";
|
|
17
18
|
import type { VendorSpecifier } from "./vendorSpecifiers";
|
|
18
19
|
|
|
20
|
+
export type BaseBuildPhase = "runtime" | "routes" | "styles" | "dictionary" | "pages" | "total";
|
|
21
|
+
|
|
19
22
|
export interface BuildSsrBaseArtifactResult {
|
|
20
23
|
artifact: BaseBuildArtifact;
|
|
21
24
|
seedIndex: RouteSeedIndex;
|
|
22
25
|
cssCompiler: CssCompiler;
|
|
23
26
|
optimizedFonts: Awaited<ReturnType<FontOptimizer["optimize"]>>;
|
|
24
27
|
runtimeChunks: RuntimeChunks;
|
|
28
|
+
phaseMs: Record<BaseBuildPhase, number>;
|
|
25
29
|
}
|
|
26
30
|
|
|
27
31
|
export function prepareCssAsset(command: "build" | "start", basePath: string, cssText: string): string {
|
|
@@ -65,15 +69,31 @@ export class SsrBaseArtifactBuilder {
|
|
|
65
69
|
|
|
66
70
|
async build(): Promise<BuildSsrBaseArtifactResult> {
|
|
67
71
|
const akanConfig = await this.#app.getConfig();
|
|
68
|
-
const {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
72
|
+
const phaseMs = { runtime: 0, routes: 0, styles: 0, dictionary: 0, pages: 0, total: 0 };
|
|
73
|
+
const timed = async <T>(phase: BaseBuildPhase, run: () => Promise<T>): Promise<T> => {
|
|
74
|
+
const started = performance.now();
|
|
75
|
+
try {
|
|
76
|
+
return await run();
|
|
77
|
+
} finally {
|
|
78
|
+
phaseMs[phase] = Math.round(performance.now() - started);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap, runtimeChunks } = await timed(
|
|
82
|
+
"runtime",
|
|
83
|
+
() => this.#buildRuntimeClientEntries(),
|
|
84
|
+
);
|
|
85
|
+
const pageEntries = await timed("routes", async () => {
|
|
86
|
+
const pageKeys = await this.#app.getPageKeys();
|
|
87
|
+
this.#app.verbose(`[base-artifact] discovered ${pageKeys.length} route files under ${this.#app.cwdPath}/page`);
|
|
88
|
+
return await resolveSsrPageEntriesForApp(this.#app, pageKeys);
|
|
89
|
+
});
|
|
90
|
+
const { cssCompiler, optimizedFonts, cssAssets } = await timed("styles", () => this.#buildStyleAssets());
|
|
91
|
+
const dictAssets = await timed("dictionary", () =>
|
|
92
|
+
new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).build(akanConfig.i18n),
|
|
93
|
+
);
|
|
94
|
+
const pagesBundle = await timed("pages", () =>
|
|
95
|
+
new PagesBundleBuilder(this.#app, this.#command, pageEntries, this.#serverEnv).build(),
|
|
96
|
+
);
|
|
77
97
|
this.#app.verbose(
|
|
78
98
|
`[base-artifact] pages bundle -> ${pagesBundle.bundlePath} (buildId=${pagesBundle.buildId}, splitting=${pagesBundle.splitting}, entry=${pagesBundle.entryBytes} bytes, outputs=${pagesBundle.outputCount}, chunks=${pagesBundle.chunkCount}, total=${pagesBundle.outputBytes} bytes)`,
|
|
79
99
|
);
|
|
@@ -118,10 +138,18 @@ export class SsrBaseArtifactBuilder {
|
|
|
118
138
|
androidSha256CertFingerprints: target.android?.sha256CertFingerprints,
|
|
119
139
|
})),
|
|
120
140
|
};
|
|
121
|
-
await
|
|
122
|
-
|
|
141
|
+
await SsrBaseArtifactBuilder.writeArtifact(this.#absArtifactDir, artifact);
|
|
142
|
+
phaseMs.total = Date.now() - this.#started;
|
|
143
|
+
this.#app.verbose(`[base-artifact] complete in ${phaseMs.total}ms`);
|
|
144
|
+
|
|
145
|
+
return { artifact, seedIndex, cssCompiler, optimizedFonts, runtimeChunks, phaseMs };
|
|
146
|
+
}
|
|
123
147
|
|
|
124
|
-
|
|
148
|
+
//? Renamed into place, last: a dev backend booted beside this build starts on the file the moment it exists.
|
|
149
|
+
static async writeArtifact(absArtifactDir: string, artifact: BaseBuildArtifact): Promise<void> {
|
|
150
|
+
const artifactPath = path.join(absArtifactDir, "base-artifact.json");
|
|
151
|
+
await Bun.write(`${artifactPath}.tmp`, `${JSON.stringify(artifact, null, 2)}\n`);
|
|
152
|
+
await rename(`${artifactPath}.tmp`, artifactPath);
|
|
125
153
|
}
|
|
126
154
|
|
|
127
155
|
async #buildRuntimeClientEntries(): Promise<
|
|
@@ -84,9 +84,10 @@ class BuildBatch {
|
|
|
84
84
|
async #buildBase(): Promise<void> {
|
|
85
85
|
const started = Date.now();
|
|
86
86
|
try {
|
|
87
|
-
const { artifact, optimizedFonts } = await new SsrBaseArtifactBuilder(this.#app).build();
|
|
87
|
+
const { artifact, optimizedFonts, phaseMs } = await new SsrBaseArtifactBuilder(this.#app).build();
|
|
88
88
|
this.#result.artifact = artifact;
|
|
89
89
|
this.#result.optimizedFonts = optimizedFonts;
|
|
90
|
+
this.#result.basePhaseMs = phaseMs;
|
|
90
91
|
this.#logger.verbose(`base-artifact ok buildId=${artifact.pagesBundleBuildId} (${Date.now() - started}ms)`);
|
|
91
92
|
} catch (err) {
|
|
92
93
|
this.#fail("base", "base-artifact", err);
|
|
@@ -32,6 +32,7 @@ export interface BuildBatchResult {
|
|
|
32
32
|
cssAssets?: PagesBatchCssAssets;
|
|
33
33
|
optimizedFonts?: OptimizedFonts;
|
|
34
34
|
artifact?: BaseBuildArtifact; // `base` batches only
|
|
35
|
+
basePhaseMs?: Record<string, number>;
|
|
35
36
|
errors: Partial<Record<BuildBatchNeed, string>>;
|
|
36
37
|
crashed?: boolean; // died before reporting its result
|
|
37
38
|
/** Of a crashed batch, the needs it died before reporting: the others streamed their build-status first. */
|
|
@@ -19,7 +19,9 @@ export interface IncrementalBuilderOptions {
|
|
|
19
19
|
initialGeneration?: number;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
type IncrementalBuilderBootDeps = Pick<IncrementalBuilderOptions, "artifact" | "optimizedFonts" | "discovery"
|
|
22
|
+
type IncrementalBuilderBootDeps = Pick<IncrementalBuilderOptions, "artifact" | "optimizedFonts" | "discovery"> & {
|
|
23
|
+
basePhaseMs: Record<string, number>;
|
|
24
|
+
};
|
|
23
25
|
|
|
24
26
|
export class BuilderBoot {
|
|
25
27
|
// Discovery stays in-process because route builds need it live; it is free at boot, building its graph lazily.
|
|
@@ -41,7 +43,12 @@ export class BuilderBoot {
|
|
|
41
43
|
if (!result.artifact || !result.optimizedFonts)
|
|
42
44
|
throw new Error("boot build reported success without an artifact; the build worker likely died");
|
|
43
45
|
const discovery = await GraphClientEntryDiscovery.create(app);
|
|
44
|
-
return {
|
|
46
|
+
return {
|
|
47
|
+
artifact: result.artifact,
|
|
48
|
+
optimizedFonts: result.optimizedFonts,
|
|
49
|
+
discovery,
|
|
50
|
+
basePhaseMs: result.basePhaseMs ?? {},
|
|
51
|
+
};
|
|
45
52
|
}
|
|
46
53
|
|
|
47
54
|
// A boot compile error must not kill the builder, the dev server's only file watcher: report it, emit builder-ready
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import type { Logger } from "akanjs/common";
|
|
2
2
|
import type { BuilderMessage } from "akanjs/server";
|
|
3
3
|
|
|
4
|
+
//? For the host alone, never relayed: the boot artifact is on disk, and `builder-ready` follows once the watcher is up.
|
|
5
|
+
export interface BaseBuiltMessage {
|
|
6
|
+
type: "base-built";
|
|
7
|
+
phaseMs: Record<string, number>;
|
|
8
|
+
}
|
|
9
|
+
|
|
4
10
|
// `process.exit` drops an ipc write that has not flushed (a natural exit does not), and whether one survives
|
|
5
11
|
// depends on the message's shape as well as its size — so every send reports its flush and `shutdown` drains.
|
|
6
12
|
export class BuilderChannel {
|
|
@@ -8,7 +14,7 @@ export class BuilderChannel {
|
|
|
8
14
|
static readonly #flushTimeoutMs = 5_000;
|
|
9
15
|
static readonly #flushing = new Set<Promise<void>>();
|
|
10
16
|
|
|
11
|
-
static send(message: BuilderMessage): Promise<void> {
|
|
17
|
+
static send(message: BuilderMessage | BaseBuiltMessage): Promise<void> {
|
|
12
18
|
const send = process.send;
|
|
13
19
|
if (!send) return Promise.resolve();
|
|
14
20
|
const flushed = new Promise<void>((resolve) => {
|
|
@@ -25,7 +31,7 @@ export class BuilderChannel {
|
|
|
25
31
|
}
|
|
26
32
|
|
|
27
33
|
// Tracked like `send`: for an event nobody awaits, `drain` is all that stands between it and the exit.
|
|
28
|
-
static emit(message: BuilderMessage): void {
|
|
34
|
+
static emit(message: BuilderMessage | BaseBuiltMessage): void {
|
|
29
35
|
void BuilderChannel.send(message);
|
|
30
36
|
}
|
|
31
37
|
|
|
@@ -43,6 +43,22 @@ const startRecordingHost = () => {
|
|
|
43
43
|
};
|
|
44
44
|
|
|
45
45
|
describe("IncrementalBuilderHost", () => {
|
|
46
|
+
test("tells its starter the boot artifact is built, ahead of ready, and relays nothing for it", () => {
|
|
47
|
+
const spawns = mockSpawns();
|
|
48
|
+
const messages: unknown[] = [];
|
|
49
|
+
const onBaseBuilt = mock();
|
|
50
|
+
const host = createHost((message) => messages.push(message));
|
|
51
|
+
|
|
52
|
+
host.start({ onBaseBuilt });
|
|
53
|
+
spawns[0]?.options.ipc?.({ type: "base-built", phaseMs: { pages: 5, total: 9 } });
|
|
54
|
+
|
|
55
|
+
expect(onBaseBuilt).toHaveBeenCalledWith({ pages: 5, total: 9 });
|
|
56
|
+
expect(host.status).toBe("starting");
|
|
57
|
+
expect(messages).toEqual([]);
|
|
58
|
+
|
|
59
|
+
host.stop();
|
|
60
|
+
});
|
|
61
|
+
|
|
46
62
|
test("restarts after a ready builder exits", async () => {
|
|
47
63
|
const spawns = mockSpawns();
|
|
48
64
|
|
|
@@ -5,6 +5,7 @@ import type { BuilderMessage, BuilderRequest } from "akanjs/server";
|
|
|
5
5
|
import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
|
|
6
6
|
import { MemoryLimit } from "akanjs/server/memoryLimit";
|
|
7
7
|
import type { App } from "../commandDecorators";
|
|
8
|
+
import type { BaseBuiltMessage } from "./builderChannel";
|
|
8
9
|
|
|
9
10
|
const builderMsgTypeSet = new Set<BuilderMessage["type"]>([
|
|
10
11
|
"build-route-res",
|
|
@@ -41,6 +42,7 @@ export type IncrementalBuilderStatus = "starting" | "ready" | "recycling" | "res
|
|
|
41
42
|
interface IncrementalBuilderStartOptions {
|
|
42
43
|
onExit?: () => void;
|
|
43
44
|
onReady?: () => void;
|
|
45
|
+
onBaseBuilt?: (phaseMs: Record<string, number>) => void;
|
|
44
46
|
onRestartReady?: () => void;
|
|
45
47
|
/** The builder is gone and a replacement is coming (unwatched until then); `onExit` means it gave up. */
|
|
46
48
|
onAway?: () => void;
|
|
@@ -124,9 +126,13 @@ export class IncrementalBuilderHost {
|
|
|
124
126
|
...(this.#patcherOff ? { AKAN_DEV_CSR_PATCHER: "off" } : {}),
|
|
125
127
|
},
|
|
126
128
|
stdio: ["ignore", this.#stdio, this.#stdio],
|
|
127
|
-
ipc: (msg: BuilderMessage) => {
|
|
129
|
+
ipc: (msg: BuilderMessage | BaseBuiltMessage) => {
|
|
128
130
|
if (this.#proc !== proc) return;
|
|
129
131
|
if (!msg || typeof msg !== "object") return;
|
|
132
|
+
if (msg.type === "base-built") {
|
|
133
|
+
this.#startOptions.onBaseBuilt?.(msg.phaseMs);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
130
136
|
if (msg.type === "build-route-res" || msg.type === "build-csr-res" || msg.type === "build-graph-res")
|
|
131
137
|
this.#inFlight.delete(msg.id);
|
|
132
138
|
if (builderMsgTypeSet.has(msg.type)) this.#onMessage(msg);
|