@akanjs/devkit 3.3.0-rc.1 → 3.3.0-rc.10

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 (85) hide show
  1. package/CHANGELOG.md +229 -2
  2. package/README.ko.md +3 -2
  3. package/README.md +3 -3
  4. package/akanApp/akanApp.host.test.ts +22 -5
  5. package/akanApp/akanApp.host.ts +46 -9
  6. package/akanApp/akanApp.host.wiring.test.ts +206 -2
  7. package/akanApp/devBackend.ts +3 -1
  8. package/akanApp/devBuilder.ts +5 -1
  9. package/akanApp/devStartTimeline.test.ts +115 -0
  10. package/akanApp/devStartTimeline.ts +69 -0
  11. package/akanConfig/akanConfig.test.ts +57 -8
  12. package/akanConfig/akanConfig.ts +12 -65
  13. package/akanConfig/dockerImage.ts +17 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/app/applicationBuildRunner.test.ts +49 -1
  16. package/app/applicationBuildRunner.ts +3 -1
  17. package/codeAgent/agent/CodeAgent.ts +36 -16
  18. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  19. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  20. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  21. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  22. package/codeAgent/agent/codeAgent.test.ts +62 -0
  23. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  24. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  25. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  26. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  27. package/codeAgent/skills/akan-page/SKILL.md +18 -13
  28. package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
  29. package/codeAgent/skills/akan-service/SKILL.md +2 -2
  30. package/docs/apiReference.test.ts +5 -0
  31. package/docs/apiReference.ts +7 -3
  32. package/docs/declarationReader.ts +28 -1
  33. package/executors/appExecutor.ts +35 -11
  34. package/executors/executors.test.ts +30 -3
  35. package/frontendBuild/buildCacheStamp.test.ts +42 -0
  36. package/frontendBuild/buildCacheStamp.ts +23 -0
  37. package/frontendBuild/buildRouteClient.test.ts +2 -7
  38. package/frontendBuild/clientEntryDiscovery.ts +2 -2
  39. package/frontendBuild/cssCandidateCache.test.ts +70 -1
  40. package/frontendBuild/cssCandidateCache.ts +17 -10
  41. package/frontendBuild/cssCompiler.test.ts +112 -0
  42. package/frontendBuild/cssCompiler.ts +41 -21
  43. package/frontendBuild/devBarrelImports.test.ts +30 -0
  44. package/frontendBuild/devBarrelImports.ts +2 -2
  45. package/frontendBuild/fontOptimizer.test.ts +144 -3
  46. package/frontendBuild/fontOptimizer.ts +103 -18
  47. package/frontendBuild/pagesBundleBuilder.ts +3 -1
  48. package/frontendBuild/plainStylesheet.test.ts +155 -0
  49. package/frontendBuild/plainStylesheet.ts +197 -0
  50. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  51. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  52. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
  53. package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
  54. package/guideline/agentAssets.test.ts +10 -0
  55. package/guideline/agentAssets.ts +52 -11
  56. package/incrementalBuilder/buildBatch.proc.ts +11 -10
  57. package/incrementalBuilder/buildBatchProtocol.ts +2 -1
  58. package/incrementalBuilder/builderBoot.ts +14 -7
  59. package/incrementalBuilder/builderChannel.ts +8 -2
  60. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  61. package/incrementalBuilder/builderLanes.ts +2 -2
  62. package/incrementalBuilder/builderWatch.ts +8 -8
  63. package/incrementalBuilder/csrRegistry.ts +4 -4
  64. package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
  65. package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
  66. package/incrementalBuilder/incrementalBuilder.proc.test.ts +41 -0
  67. package/incrementalBuilder/incrementalBuilder.proc.ts +9 -8
  68. package/incrementalBuilder/ssrRegistry.ts +6 -6
  69. package/index.ts +1 -1
  70. package/integration/renderAdmissionSoak.test.ts +99 -0
  71. package/integration/renderAdmissionSoak.ts +609 -0
  72. package/mobile/nativeConfig.test.ts +100 -0
  73. package/mobile/nativeConfig.ts +55 -16
  74. package/mobile/nativePublicEnv.ts +2 -1
  75. package/package.json +14 -169
  76. package/packageExports.test.ts +38 -24
  77. package/transforms/barrelAnalyzer.ts +2 -2
  78. package/transforms/transforms.test.ts +3 -3
  79. package/tunnel/createTunnel.test.ts +29 -8
  80. package/tunnel/createTunnel.ts +18 -11
  81. package/util/fileEditor.ts +1 -0
  82. package/util/fileSys.test.ts +13 -0
  83. package/util/fileSys.ts +2 -2
  84. package/util/selectModel.ts +1 -0
  85. package/workspace/getRelatedCnsts.ts +7 -0
@@ -0,0 +1,30 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, realpath, symlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { tempDirs, writeText as write } from "../test/testHelpers";
5
+ import { DevBarrelImports } from "./devBarrelImports";
6
+
7
+ const makeTempRoot = tempDirs("akan-dev-barrel-imports-");
8
+
9
+ describe("DevBarrelImports", () => {
10
+ test("points an installed package's import at the real file behind its link, relative to the importer", async () => {
11
+ const root = await realpath(await makeTempRoot());
12
+ const installed = path.join(root, "store/akanjs");
13
+ await write(path.join(installed, "ui/index.ts"), 'export { Link } from "./Link";\n');
14
+ await write(path.join(installed, "ui/Link/index.tsx"), "export const Link = () => null;\n");
15
+ await mkdir(path.join(root, "node_modules"), { recursive: true });
16
+ await symlink(installed, path.join(root, "node_modules/akanjs"));
17
+ const uiEntry = path.join(root, "node_modules/akanjs/ui/index.ts");
18
+ const importer = path.join(root, "apps/demo/page/_index.tsx");
19
+ await write(importer, "");
20
+
21
+ const barrels = new DevBarrelImports(["akanjs/ui"], async (specifier) =>
22
+ specifier === "akanjs/ui"
23
+ ? { pkgName: specifier, entryFile: uiEntry, pkgDir: path.dirname(uiEntry), preserveFilePath: true }
24
+ : null,
25
+ );
26
+ const rewrite = await barrels.rewrite('import { Link } from "akanjs/ui";\n', importer);
27
+
28
+ expect(rewrite?.contents).toBe('import { Link } from "../../../store/akanjs/ui/Link/index.tsx";\n');
29
+ });
30
+ });
@@ -115,8 +115,8 @@ export class DevBarrelImports {
115
115
 
116
116
  static #fileOf(subpath: string, packages: PackageEntry[]): string | null {
117
117
  const pkg = packages.find(({ pkgName }) => subpath === pkgName || subpath.startsWith(`${pkgName}/`));
118
- if (!pkg) return null;
119
- const file = CsrDevPaths.resolveOnDisk(path.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)));
118
+ if (!pkg && !path.isAbsolute(subpath)) return null;
119
+ const file = CsrDevPaths.resolveOnDisk(pkg ? path.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)) : subpath);
120
120
  return file ? CsrDevPaths.realpath(file) : null;
121
121
  }
122
122
 
@@ -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: () => undefined,
26
+ verbose: (message: string) => verboses.push(message),
26
27
  logger: { warn: (message: string) => warnings.push(message) },
27
28
  } as unknown as App;
28
- return { app, cwdPath, warnings };
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 FontOptimizerCache {
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: string[];
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 = 3;
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
- if (cacheKey) await this.#writeCache(cacheKey, result);
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.#artifactRoot, "fontCache.json");
83
+ return path.join(this.#cacheRoot, "fontCache.json");
71
84
  }
72
85
 
73
- // null skips the cache: an unstat-able source's staleness is undetectable, and the uncached path warns about it.
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 stamp = sourcePath ? await this.#fileStamp(sourcePath) : null;
81
- if (!stamp) return null;
82
- sources.push({ optimizedSrc: face.optimizedSrc, ...stamp });
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
- return this.#cacheDigest({ version: FontOptimizer.#cacheVersion, fonts, sources });
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) return null;
115
- const files = cache.files.map((relativePath) => path.join(this.#artifactRoot, relativePath));
116
- for (const filePath of files) {
117
- if (!(await Bun.file(filePath).exists())) return null;
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: result.files.map((filePath) => path.relative(this.#artifactRoot, filePath)),
197
+ files,
128
198
  };
129
- await Bun.write(this.#cachePath, JSON.stringify(cache));
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[]> {
@@ -13,6 +13,7 @@ import { createUseClientBundlePlugin } from "../transforms/useClientBundlePlugin
13
13
  import { bundleDefine } from "./bundleDefine";
14
14
  import { CsrDevPaths } from "./csrDevPaths";
15
15
  import { PagesEntrySourceGenerator } from "./pagesEntrySourceGenerator";
16
+ import { RscServerRendererGuard } from "./rscServerRendererGuard";
16
17
  import { ServerGraphFile } from "./serverGraphFile";
17
18
 
18
19
  export interface BuildPagesBundleResult {
@@ -74,7 +75,7 @@ export class PagesBundleBuilder {
74
75
  asset: "assets/[name]-[hash].[ext]",
75
76
  },
76
77
  define: bundleDefine(this.#app, this.#command, "ssr"),
77
- metafile: dev,
78
+ metafile: true,
78
79
  plugins: [
79
80
  //? First: the use-client plugins below load every module, and an env file must be swapped before they do.
80
81
  ...(this.#serverEnv ? [this.#serverEnv] : []),
@@ -96,6 +97,7 @@ export class PagesBundleBuilder {
96
97
  });
97
98
 
98
99
  if (!result.success) throw new AggregateError(result.logs, "[PagesBundleBuilder] Bun.build failed");
100
+ RscServerRendererGuard.assert(result.metafile, workspaceRoot);
99
101
 
100
102
  const entryArtifact = result.outputs.find((a) => a.kind === "entry-point");
101
103
  if (!entryArtifact) throw new Error("[PagesBundleBuilder] Bun.build emitted no entry-point artifact");
@@ -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
+ });