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

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 +230 -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
@@ -91,7 +91,34 @@ export class DeclarationReader {
91
91
  const type = this.#checker.getTypeOfSymbol(symbol);
92
92
  const signatures = type.getCallSignatures();
93
93
  if (signatures.length === 0) throw new Error(`${name} is not callable`);
94
- return signatures.map((signature) => `${name}${this.#checker.signatureToString(signature, undefined, typeFlags)}`);
94
+ const statics = this.#checker.getPropertiesOfType(type).flatMap((property) => {
95
+ const [declaration] = property.declarations ?? [];
96
+ if (!declaration || DeclarationReader.#isInternalName(property.name)) return [];
97
+ return this.#checker
98
+ .getTypeOfSymbolAtLocation(property, declaration)
99
+ .getCallSignatures()
100
+ .map((each) => `${name}.${property.name}${this.#checker.signatureToString(each, undefined, typeFlags)}`);
101
+ });
102
+ return [
103
+ ...signatures.map((signature) => `${name}${this.#checker.signatureToString(signature, undefined, typeFlags)}`),
104
+ ...statics,
105
+ ];
106
+ }
107
+
108
+ foreignBases(symbol: ts.Symbol): string[] {
109
+ const [declaration] = symbol.declarations ?? [];
110
+ const nodes =
111
+ declaration && ts.isTypeAliasDeclaration(declaration) && ts.isIntersectionTypeNode(declaration.type)
112
+ ? declaration.type.types.filter((each) => !ts.isTypeLiteralNode(each))
113
+ : declaration && ts.isInterfaceDeclaration(declaration)
114
+ ? (declaration.heritageClauses ?? []).flatMap((clause) => [...clause.types])
115
+ : [];
116
+ return nodes
117
+ .filter((node) => {
118
+ const properties = this.#checker.getPropertiesOfType(this.#checker.getTypeFromTypeNode(node));
119
+ return properties.length > 0 && properties.every((each) => !each.declarations?.some((d) => this.#isOwn(d)));
120
+ })
121
+ .map((node) => DeclarationReader.#print(node, node.getSourceFile()));
95
122
  }
96
123
 
97
124
  props(type: ts.Type, omit: string[] = []): string[] {
@@ -1,4 +1,4 @@
1
- import { cp as cpEntry, lstat, mkdir, readdir as readDirEntries, realpath, symlink } from "node:fs/promises";
1
+ import { cp as cpEntry, lstat, mkdir, readdir as readDirEntries, realpath, rm, stat, symlink } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import type { AkanPlugin, AkanSyncContext } from "akanjs";
@@ -44,8 +44,14 @@ export class AppExecutor extends SysExecutor {
44
44
  static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
45
45
  return new AppExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
46
46
  }
47
- //* Not dev output: the downloaded `bin` sources.
48
- static readonly #keptOnStart = [path.join(".akan", "cache", "bin")];
47
+ #verifyBuild: boolean = false;
48
+ //? `akan verify` builds apart: dist/apps/<app> may hold the full build someone is about to start or deploy.
49
+ useVerifyDist() {
50
+ this.dist = new Executor(`dist/verify/${this.name}`, `${this.workspace.workspaceRoot}/dist/verify/${this.name}`);
51
+ this.#verifyBuild = true;
52
+ }
53
+ //* Not dev output: the downloaded `bin` sources, and caches whose entries name the akanjs and Bun that wrote them.
54
+ static readonly #keptOnStart = [path.join(".akan", "cache")];
49
55
  //* Native builds moved to dist/native/<app>; the old folder may hold a signed release nobody uploaded yet.
50
56
  static readonly #legacyNative = path.join(".akan", "native");
51
57
  async #removeDevOutput(dir = ".akan") {
@@ -59,13 +65,28 @@ export class AppExecutor extends SysExecutor {
59
65
  );
60
66
  return;
61
67
  }
62
- if (AppExecutor.#keptOnStart.includes(entry)) return;
68
+ if (AppExecutor.#keptOnStart.includes(entry)) return await this.#removeStaleTemps(entry);
63
69
  if (AppExecutor.#keptOnStart.some((kept) => kept.startsWith(`${entry}${path.sep}`)))
64
70
  return await this.#removeDevOutput(entry);
65
71
  await this.removeDir(entry);
66
72
  }),
67
73
  );
68
74
  }
75
+ //* A start killed between an atomic write and its rename leaves the `.tmp`; a younger one may be another start's.
76
+ static readonly #staleTempMs = 60_000;
77
+ async #removeStaleTemps(dir: string) {
78
+ const root = this.getPath(dir);
79
+ const names = await readDirEntries(root, { recursive: true }).catch(() => [] as string[]);
80
+ await Promise.all(
81
+ names
82
+ .filter((name) => name.endsWith(".tmp"))
83
+ .map(async (name) => {
84
+ const file = path.join(root, name);
85
+ const stats = await stat(file).catch(() => null);
86
+ if (stats?.isFile() && Date.now() - stats.mtimeMs > AppExecutor.#staleTempMs) await rm(file, { force: true });
87
+ }),
88
+ );
89
+ }
69
90
  getEnv() {
70
91
  return WorkspaceExecutor.getBaseDevEnv().env;
71
92
  }
@@ -116,13 +137,16 @@ export class AppExecutor extends SysExecutor {
116
137
  this.#excludeDevOnlyPages = true;
117
138
  this.#pageKeys = null;
118
139
  await this.dist.removeDir(this.dist.cwdPath);
119
- await Promise.all([this.dist.mkdir("private"), this.dist.mkdir("public")]);
120
- //* Lib assets are symlinks, which neither the docker context nor the release tarball follows out of dist.
121
- //* Only the web router reads `public/`, so an api-only build leaves it out.
122
- await Promise.all([
123
- this.cp("private", `${this.dist.cwdPath}/private`, { dereference: true }),
124
- ...(akanConfig.web.ssr ? [this.cp("public", `${this.dist.cwdPath}/public`, { dereference: true })] : []),
125
- ]);
140
+ //? A verify build stops before anything reads these copies; the font optimizer falls back to the app's `public/`.
141
+ if (!this.#verifyBuild) {
142
+ await Promise.all([this.dist.mkdir("private"), this.dist.mkdir("public")]);
143
+ //* Lib assets are symlinks, which neither the docker context nor the release tarball follows out of dist.
144
+ //* Only the web router reads `public/`, so an api-only build leaves it out.
145
+ await Promise.all([
146
+ this.cp("private", `${this.dist.cwdPath}/private`, { dereference: true }),
147
+ ...(akanConfig.web.ssr ? [this.cp("public", `${this.dist.cwdPath}/public`, { dereference: true })] : []),
148
+ ]);
149
+ }
126
150
  } else {
127
151
  await this.#removeDevOutput();
128
152
  //? `akan start` keeps the full dev surface: the incremental builder is also the file watcher.
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, spyOn, test } from "bun:test";
2
2
  import { existsSync } from "node:fs";
3
- import { lstat, mkdir, readFile, readlink, rm, stat, writeFile } from "node:fs/promises";
3
+ import { lstat, mkdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { AkanAppConfig } from "../akanConfig";
6
6
  import { DevGeneratedIndexSync } from "../frontendBuild/devGeneratedIndexSync";
@@ -612,7 +612,7 @@ describe("Workspace and app executor environment contracts", () => {
612
612
  expect(app.getCommandEnv().AKAN_PUBLIC_SERVE_DOMAIN).toBe("example.com");
613
613
  });
614
614
 
615
- test("akan start clears the dev output and keeps the bin downloads and a native folder from before dist/native", async () => {
615
+ test("akan start clears the dev output and keeps the caches and a native folder from before dist/native", async () => {
616
616
  const root = await makeTempRoot();
617
617
  process.env.AKAN_PUBLIC_REPO_NAME = "repo";
618
618
  process.env.AKAN_PUBLIC_SERVE_DOMAIN = "example.com";
@@ -626,11 +626,14 @@ describe("Workspace and app executor environment contracts", () => {
626
626
  "native/desktop/updates/macos-arm64/main.json",
627
627
  "native/desktop/build/macos/App.app",
628
628
  "cache/bin/ffmpeg",
629
+ "cache/cssCandidates.json",
630
+ "cache/fontCache.json",
631
+ "cache/fonts/Assistant-400-normal-abc.woff2",
629
632
  ];
630
633
  const removed = [
631
634
  "artifact/client/app.js",
635
+ "artifact/fontCache.json",
632
636
  "generated/dict/index.ts",
633
- "cache/cssCandidates.json",
634
637
  "desktop/server/main.js",
635
638
  "mobile/desktop/native/macos/App.app",
636
639
  ];
@@ -644,6 +647,30 @@ describe("Workspace and app executor environment contracts", () => {
644
647
  expect(existsSync(path.join(akan, file))).toBe(false);
645
648
  });
646
649
 
650
+ test("akan start removes a cache temp file a killed start left, and keeps one a running start is writing", async () => {
651
+ const root = await makeTempRoot();
652
+ process.env.AKAN_PUBLIC_REPO_NAME = "repo";
653
+ process.env.AKAN_PUBLIC_SERVE_DOMAIN = "example.com";
654
+ process.env.AKAN_PUBLIC_ENV = "local";
655
+ process.env.PORT_OFFSET = "0";
656
+ await writeJson(path.join(root, "package.json"), rootPackageJson());
657
+ await mkdir(path.join(root, "apps/starttemps/page"), { recursive: true });
658
+ await writeFile(path.join(root, "apps/starttemps/akan.config.ts"), "export default {};\n");
659
+ const cache = path.join(root, "apps/starttemps/.akan/cache");
660
+ const stale = ["cssCandidates.json.1.a.tmp", "fonts/x.woff2.1.b.tmp"];
661
+ const fresh = ["fontCache.json.2.c.tmp", "fonts/x.woff2.2.d.tmp"];
662
+ const kept = [...fresh, "cssCandidates.json", "fonts/x.woff2"];
663
+ for (const file of [...stale, ...kept]) await writeText(path.join(cache, file), "x");
664
+ const twoMinutesAgo = new Date(Date.now() - 120_000);
665
+ for (const file of stale) await utimes(path.join(cache, file), twoMinutesAgo, twoMinutesAgo);
666
+
667
+ const app = AppExecutor.from(new WorkspaceExecutor({ workspaceRoot: root, repoName: "repo" }), "starttemps");
668
+ await app.prepareCommand("start");
669
+
670
+ for (const file of stale) expect(existsSync(path.join(cache, file))).toBe(false);
671
+ for (const file of kept) expect(existsSync(path.join(cache, file))).toBe(true);
672
+ });
673
+
647
674
  describe("syncPages", () => {
648
675
  // `AppExecutor.from` memoises by name, so each test needs a name no other test has used.
649
676
  const makeAppWithLibPages = async (
@@ -0,0 +1,42 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { appendFile, utimes, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { tempDirs } from "../test/testHelpers";
5
+ import { buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
6
+
7
+ const tempRoot = tempDirs("akan-devkit-stamp-");
8
+
9
+ const makeProducer = async () => {
10
+ const file = path.join(await tempRoot(), "producer.ts");
11
+ await writeFile(file, "export const regex = /x/;\n");
12
+ await utimes(file, new Date(1_700_000_000_000), new Date(1_700_000_000_000));
13
+ return file;
14
+ };
15
+
16
+ describe("buildCacheStamp", () => {
17
+ test("matches a stamp taken from the same producing file", async () => {
18
+ const file = await makeProducer();
19
+ expect(isBuildCacheStamp(buildCacheStamp([file]), buildCacheStamp([file]))).toBe(true);
20
+ });
21
+
22
+ test("misses when the producing file's mtime moves", async () => {
23
+ const file = await makeProducer();
24
+ const before = buildCacheStamp([file]);
25
+ await utimes(file, new Date(1_700_000_001_000), new Date(1_700_000_001_000));
26
+ expect(isBuildCacheStamp(before, buildCacheStamp([file]))).toBe(false);
27
+ });
28
+
29
+ test("misses when the producing file's size changes under the same mtime", async () => {
30
+ const file = await makeProducer();
31
+ const before = buildCacheStamp([file]);
32
+ await appendFile(file, "export const more = 1;\n");
33
+ await utimes(file, new Date(1_700_000_000_000), new Date(1_700_000_000_000));
34
+ expect(isBuildCacheStamp(before, buildCacheStamp([file]))).toBe(false);
35
+ });
36
+
37
+ test("misses an entry written before the stamp named its producing files", async () => {
38
+ const file = await makeProducer();
39
+ const { code: _, ...older } = buildCacheStamp([file]);
40
+ expect(isBuildCacheStamp(older, buildCacheStamp([file]))).toBe(false);
41
+ });
42
+ });
@@ -0,0 +1,23 @@
1
+ import { statSync } from "node:fs";
2
+ import { AkanAppConfig } from "../akanConfig/akanConfig";
3
+
4
+ export interface BuildCacheStamp {
5
+ akanjs: string;
6
+ bun: string;
7
+ code: string;
8
+ }
9
+
10
+ //? Kept across starts, so another akanjs, Bun or edit of the producing module (run from source) must read as a miss.
11
+ export const buildCacheStamp = (producers: string[]): BuildCacheStamp => ({
12
+ akanjs: AkanAppConfig.akanVersion,
13
+ bun: `${Bun.version}+${Bun.revision}`,
14
+ code: producers
15
+ .map((file) => {
16
+ const stats = statSync(file, { throwIfNoEntry: false });
17
+ return stats ? `${stats.mtimeMs}:${stats.size}` : "missing";
18
+ })
19
+ .join(","),
20
+ });
21
+
22
+ export const isBuildCacheStamp = (value: Partial<BuildCacheStamp> | null | undefined, stamp: BuildCacheStamp) =>
23
+ value?.akanjs === stamp.akanjs && value.bun === stamp.bun && value.code === stamp.code;
@@ -428,14 +428,9 @@ describe("route client store bootstrap", () => {
428
428
  await write(uiEntry, 'export { ClientPathWrapper } from "./System/Client";\n');
429
429
  await write(clientEntry, '"use client";\nexport const ClientPathWrapper = () => null;\n');
430
430
 
431
- const entryFiles = new Map([
432
- ["akanjs/ui", uiEntry],
433
- ["akanjs/ui/System/Client.tsx", clientEntry],
434
- ]);
435
431
  const discovery = new GraphClientEntryDiscovery({ barrelImports: ["akanjs/ui"] }, async (specifier) => {
436
- const entryFile = entryFiles.get(specifier);
437
- if (!entryFile) return null;
438
- return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true };
432
+ if (specifier !== "akanjs/ui") return null;
433
+ return { pkgName: specifier, entryFile: uiEntry, pkgDir: path.dirname(uiEntry), preserveFilePath: true };
439
434
  });
440
435
 
441
436
  expect(await discovery.discover([seed])).toEqual([clientEntry]);
@@ -226,8 +226,8 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
226
226
  this.#resolvedSpecifierCache,
227
227
  cacheKey,
228
228
  async () => {
229
- if (spec.startsWith(".") || spec.startsWith("/")) {
230
- const abs = spec.startsWith("/") ? spec : path.resolve(importerDir, spec);
229
+ if (spec.startsWith(".") || path.isAbsolute(spec)) {
230
+ const abs = path.resolve(importerDir, spec);
231
231
  return await this.#resolveFileCandidate(abs);
232
232
  }
233
233
  const pkg = await this.#resolvePackage(spec);
@@ -1,7 +1,8 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { mkdtemp, writeFile } from "node:fs/promises";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
+ import type { BuildCacheStamp } from "./buildCacheStamp";
5
6
  import { CssCandidateCache } from "./cssCandidateCache";
6
7
 
7
8
  const scan = async (source: string) => {
@@ -56,3 +57,71 @@ describe("CssCandidateCache token extraction", () => {
56
57
  expect(candidates.filter((candidate) => candidate.startsWith("["))).toEqual([]);
57
58
  });
58
59
  });
60
+
61
+ describe("CssCandidateCache persistence", () => {
62
+ const writeCache = async (stamp: BuildCacheStamp) => {
63
+ const dir = await mkdtemp(path.join(tmpdir(), "css-candidate-"));
64
+ const file = path.join(dir, "probe.tsx");
65
+ const cachePath = path.join(dir, "cache.json");
66
+ await writeFile(file, `const c = "w-full";`);
67
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
68
+ await cache.candidatesFor(file);
69
+ await cache.save(new Set([file]));
70
+ return { file, cachePath };
71
+ };
72
+
73
+ test("reuses an entry the same akanjs and Bun wrote", async () => {
74
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
75
+ const cache = await new CssCandidateCache(cachePath, { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" }).load();
76
+ expect(await cache.candidatesFor(file)).toContain("w-full");
77
+ expect([cache.reused, cache.rescanned]).toEqual([1, 0]);
78
+ });
79
+
80
+ test.each([
81
+ ["akanjs", { akanjs: "1.0.1", bun: "1.0.0+a", code: "1:1" }],
82
+ ["Bun", { akanjs: "1.0.0", bun: "1.0.0+b", code: "1:1" }],
83
+ ["scanner build", { akanjs: "1.0.0", bun: "1.0.0+a", code: "2:1" }],
84
+ ])("rescans an entry another %s wrote", async (_, stamp) => {
85
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
86
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
87
+ expect(await cache.candidatesFor(file)).toContain("w-full");
88
+ expect([cache.reused, cache.rescanned]).toEqual([0, 1]);
89
+ });
90
+
91
+ test("keeps another base path's entries, so each base path reuses its scan on the next start", async () => {
92
+ const stamp = { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" };
93
+ const dir = await mkdtemp(path.join(tmpdir(), "css-candidate-"));
94
+ const cachePath = path.join(dir, "cache.json");
95
+ const [rootFile, adminFile] = [path.join(dir, "root.tsx"), path.join(dir, "admin.tsx")];
96
+ await writeFile(rootFile, `const c = "w-full";`);
97
+ await writeFile(adminFile, `const c = "h-full";`);
98
+ const scanBasePath = async (file: string) => {
99
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
100
+ await cache.candidatesFor(file);
101
+ await cache.save(new Set([file]));
102
+ return cache;
103
+ };
104
+ await scanBasePath(rootFile);
105
+ await scanBasePath(adminFile);
106
+
107
+ const [root, admin] = [await scanBasePath(rootFile), await scanBasePath(adminFile)];
108
+ expect([root.reused, admin.reused]).toEqual([1, 1]);
109
+ });
110
+
111
+ test("drops the entry of a source file that was deleted", async () => {
112
+ const stamp = { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" };
113
+ const { file, cachePath } = await writeCache(stamp);
114
+ await rm(file);
115
+ await new CssCandidateCache(cachePath, stamp).load().then((cache) => cache.save(new Set()));
116
+ expect(Object.keys((await Bun.file(cachePath).json()).files)).toEqual([]);
117
+ });
118
+
119
+ test("rescans when the cache file was cut short", async () => {
120
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
121
+ const text = await Bun.file(cachePath).text();
122
+ await writeFile(cachePath, text.slice(0, text.length / 2));
123
+ const cache = await new CssCandidateCache(cachePath, { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" }).load();
124
+ expect(await cache.candidatesFor(file)).toContain("w-full");
125
+ expect([cache.reused, cache.rescanned]).toEqual([0, 1]);
126
+ });
127
+ });
@@ -1,4 +1,6 @@
1
1
  import { stat } from "node:fs/promises";
2
+ import { FileSys } from "../util/fileSys";
3
+ import { type BuildCacheStamp, buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
2
4
 
3
5
  // The leading `[` alternation keeps arbitrary variants (`[&_td]:px-3`) whole, and a bracket may hold one nested
4
6
  // bracket (`[&_[data-slot=x]]:p-2`, `has-[[aria-expanded=true]]:x`), or the candidate is cut at the inner `]` and the
@@ -14,7 +16,7 @@ interface CachedFile {
14
16
  candidates: string[];
15
17
  }
16
18
 
17
- interface CacheFile {
19
+ interface CacheFile extends BuildCacheStamp {
18
20
  version: number;
19
21
  files: Record<string, CachedFile>;
20
22
  }
@@ -22,15 +24,17 @@ interface CacheFile {
22
24
  /** Tailwind candidates per source file, on disk: the batch worker that compiles CSS exits before the next save. */
23
25
  export class CssCandidateCache {
24
26
  // Bump when the token regex or the entry shape changes, so stale extractions are not reused.
25
- static readonly #version = 5;
27
+ static readonly #version = 6;
26
28
  readonly #path: string;
29
+ readonly #stamp: BuildCacheStamp;
27
30
  readonly #entries = new Map<string, CachedFile>();
28
31
  #dirty = false;
29
32
  #reused = 0;
30
33
  #rescanned = 0;
31
34
 
32
- constructor(cachePath: string) {
35
+ constructor(cachePath: string, stamp = buildCacheStamp([import.meta.path])) {
33
36
  this.#path = cachePath;
37
+ this.#stamp = stamp;
34
38
  }
35
39
 
36
40
  get reused(): number {
@@ -44,8 +48,8 @@ export class CssCandidateCache {
44
48
  async load(): Promise<this> {
45
49
  const raw = (await Bun.file(this.#path)
46
50
  .json()
47
- .catch(() => null)) as CacheFile | null;
48
- if (!raw || raw.version !== CssCandidateCache.#version || typeof raw.files !== "object") return this;
51
+ .catch(() => null)) as Partial<CacheFile> | null;
52
+ if (raw?.version !== CssCandidateCache.#version || !isBuildCacheStamp(raw, this.#stamp) || !raw.files) return this;
49
53
  for (const [file, entry] of Object.entries(raw.files)) {
50
54
  if (typeof entry?.mtimeMs !== "number" || !Array.isArray(entry.candidates)) continue;
51
55
  this.#entries.set(file, entry);
@@ -71,20 +75,23 @@ export class CssCandidateCache {
71
75
  return candidates;
72
76
  }
73
77
 
78
+ // Each base path scans its own files into the same cache, so only an entry whose file is gone is dropped.
74
79
  async save(present: Set<string>): Promise<void> {
75
- for (const file of [...this.#entries.keys()]) {
76
- if (present.has(file)) continue;
80
+ const absent = [...this.#entries.keys()].filter((file) => !present.has(file));
81
+ const exists = await Promise.all(absent.map((file) => Bun.file(file).exists()));
82
+ absent.forEach((file, index) => {
83
+ if (exists[index]) return;
77
84
  this.#entries.delete(file);
78
85
  this.#dirty = true;
79
- }
86
+ });
80
87
  if (!this.#dirty) return;
81
88
  this.#dirty = false;
82
89
  const files: Record<string, CachedFile> = {};
83
90
  for (const [file, entry] of this.#entries) files[file] = entry;
84
91
  // An unwritable cache is a slow build, not a failed one: a read-only checkout must still compile.
85
- await Bun.write(
92
+ await FileSys.writeTextAtomic(
86
93
  this.#path,
87
- JSON.stringify({ version: CssCandidateCache.#version, files } satisfies CacheFile),
94
+ JSON.stringify({ version: CssCandidateCache.#version, ...this.#stamp, files } satisfies CacheFile),
88
95
  ).catch(() => undefined);
89
96
  }
90
97
  }
@@ -2,8 +2,120 @@ import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
3
  import { tempDirs, writeText as write } from "../test/testHelpers";
4
4
  import { CssCompiler, declaredCustomProperties } from "./cssCompiler";
5
+ import { prepareCssAsset } from "./ssrBaseArtifactBuilder";
5
6
 
6
7
  const makeTempRoot = tempDirs("akan-css-compiler-");
8
+ const TAILWIND_BANNER = "/*! tailwindcss v";
9
+
10
+ const cssCompilerFor = (root: string, cwdPath: string, app: object = {}) =>
11
+ new CssCompiler({
12
+ workspace: { workspaceRoot: root },
13
+ cwdPath,
14
+ getTsConfig: async () => ({ compilerOptions: { paths: {} } }),
15
+ getPageKeys: async () => ["./_index.tsx"],
16
+ getConfig: async () => ({ barrelImports: [], basePaths: [] }),
17
+ ...app,
18
+ } as never);
19
+
20
+ describe("CssCompiler on a stylesheet that uses no Tailwind", () => {
21
+ test("passes it through as written, with no banner, before and after the build's optimizer", async () => {
22
+ const root = await makeTempRoot();
23
+ const css = "/* brand */\n:root {\n --brand: #111111;\n}\n\n.card { color: var(--brand); padding: 1rem; }\n";
24
+ await write(path.join(root, "styles.css"), css);
25
+
26
+ const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "styles.css")], []);
27
+
28
+ expect(compiled).toBe(css);
29
+ const built = prepareCssAsset("build", "", compiled);
30
+ expect(built).toBe(":root{--brand:#111}.card{color:var(--brand);padding:1rem}");
31
+ });
32
+
33
+ test("inlines its imports through the resolver alone, where Tailwind stamped its banner", async () => {
34
+ const root = await makeTempRoot();
35
+ await write(path.join(root, "page/styles.css"), '@import "../ui/reset.css" layer(reset);\n.page { margin: 0; }\n');
36
+ await write(path.join(root, "ui/reset.css"), "* { box-sizing: border-box; }\n");
37
+
38
+ const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "page/styles.css")], []);
39
+
40
+ expect(compiled).toBe("@layer reset {\n* { box-sizing: border-box; }\n\n}\n.page { margin: 0; }\n");
41
+ expect(prepareCssAsset("build", "", compiled)).not.toContain("tailwind");
42
+ });
43
+
44
+ test("reports its imports like a compiled stylesheet's", async () => {
45
+ const root = await makeTempRoot();
46
+ const appDir = path.join(root, "apps/demo");
47
+ await write(path.join(appDir, "page/_index.tsx"), 'import "./styles.css";\nexport default () => null;\n');
48
+ await write(path.join(appDir, "page/styles.css"), '@import "../../../libs/shared/ui/brand.css";\n');
49
+ await write(path.join(root, "libs/shared/ui/brand.css"), ":root { --kakao : #fee500; }\n");
50
+
51
+ const compiler = cssCompilerFor(root, appDir);
52
+ const cssByBasePath = await compiler.getCssByBasePath();
53
+
54
+ expect(cssByBasePath[""]).toBe(":root { --kakao : #fee500; }\n\n");
55
+ expect(compiler.importedStylesheetsByBasePath[""]).toEqual([
56
+ { cssPath: path.join(root, "libs/shared/ui/brand.css"), declaredNames: ["--kakao"] },
57
+ ]);
58
+ });
59
+
60
+ test.each([
61
+ ["@theme", "@theme { --color-brand: red; }"],
62
+ ["@utility", "@utility tab-4 { tab-size: 4; }"],
63
+ ["@variant", ".a { @variant hover { color: red; } }"],
64
+ ["@custom-variant", "@custom-variant pointer-coarse (@media (pointer: coarse));"],
65
+ ["@source", '@source "./src";'],
66
+ ["@tailwind", "@tailwind utilities;"],
67
+ ["@apply", ".a { @apply flex; }"],
68
+ ["@plugin", '@plugin "./plugin.js";'],
69
+ ["@config", '@config "./tailwind.config.js";'],
70
+ ["@reference", '@reference "./plain.css";'],
71
+ ["--alpha()", ".a { color: --alpha(red / 50%); }"],
72
+ ["--theme()", ".a { color: --theme(--color-brand, red); }"],
73
+ ["an import's source()", '@import "./plain.css" source(none);'],
74
+ ])("compiles with Tailwind when only an imported stylesheet uses %s", async (_, directive) => {
75
+ const root = await makeTempRoot();
76
+ await write(path.join(root, "styles.css"), '@import "./part.css";\n.app { margin: 0; }\n');
77
+ await write(path.join(root, "part.css"), `${directive}\n`);
78
+ await write(path.join(root, "plain.css"), ".plain { color: red; }\n");
79
+ await write(path.join(root, "plugin.js"), "export default function () {}\n");
80
+ await write(path.join(root, "tailwind.config.js"), "export default {};\n");
81
+
82
+ const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "styles.css")], []);
83
+
84
+ expect(compiled.startsWith(TAILWIND_BANNER)).toBe(true);
85
+ });
86
+
87
+ test('compiles `@import "tailwindcss"` and the utilities the sources use', async () => {
88
+ const root = await makeTempRoot();
89
+ await write(path.join(root, "styles.css"), '@import "tailwindcss";\n');
90
+ await write(path.join(root, "Page.tsx"), 'export const Page = () => <main className="flex" />;\n');
91
+
92
+ const compiled = await cssCompilerFor(root, root).compileCss(
93
+ [path.join(root, "styles.css")],
94
+ [path.join(root, "Page.tsx")],
95
+ );
96
+
97
+ expect(compiled.startsWith(TAILWIND_BANNER)).toBe(true);
98
+ expect(compiled).toContain(".flex {");
99
+ });
100
+
101
+ test("switches to Tailwind on the next rebuild once a stylesheet gains a directive, and back", async () => {
102
+ const root = await makeTempRoot();
103
+ const stylesPath = path.join(root, "page/styles.css");
104
+ await write(path.join(root, "page/_index.tsx"), 'import "./styles.css";\nexport default () => null;\n');
105
+ await write(stylesPath, '@import "./tokens.css";\n');
106
+ await write(path.join(root, "page/tokens.css"), ":root { --brand: #111; }\n");
107
+ const compiler = cssCompilerFor(root, root);
108
+
109
+ expect((await compiler.getCssByBasePath({ refresh: true }))[""]).toBe(":root { --brand: #111; }\n\n");
110
+ await write(
111
+ path.join(root, "page/tokens.css"),
112
+ ":root { --brand: #111; }\n@theme { --color-brand: var(--brand); }\n",
113
+ );
114
+ expect((await compiler.getCssByBasePath({ refresh: true }))[""]?.startsWith(TAILWIND_BANNER)).toBe(true);
115
+ await write(path.join(root, "page/tokens.css"), ":root { --brand: #222; }\n");
116
+ expect((await compiler.getCssByBasePath({ refresh: true }))[""]).toBe(":root { --brand: #222; }\n\n");
117
+ });
118
+ });
7
119
 
8
120
  describe("declaredCustomProperties", () => {
9
121
  test("names what the regex-based version named", () => {
@@ -9,6 +9,7 @@ import { CsrEntryFiles } from "./csrEntryFiles";
9
9
  import { CssBlockParser } from "./cssBlockParser";
10
10
  import { CssCandidateCache } from "./cssCandidateCache";
11
11
  import { CssImportResolver } from "./cssImportResolver";
12
+ import { PlainStylesheet } from "./plainStylesheet";
12
13
 
13
14
  const NON_SOURCE_EXT_RE = /\.(json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav)$/i;
14
15
  const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
@@ -24,6 +25,13 @@ export interface ImportedStylesheet {
24
25
  declaredNames: string[];
25
26
  }
26
27
 
28
+ interface CompiledStylesheet {
29
+ cssPath: string;
30
+ compiler: Awaited<ReturnType<typeof compile>> | null;
31
+ plainCss: string;
32
+ imported: Map<string, string>;
33
+ }
34
+
27
35
  export class CssCompiler {
28
36
  #logger = new Logger("CssCompiler");
29
37
  #transpiler = new Bun.Transpiler({ loader: "tsx" });
@@ -233,38 +241,30 @@ export class CssCompiler {
233
241
  if (cssPaths.length === 0) return { css: "", imported: [] };
234
242
 
235
243
  const compileStarted = Date.now();
236
- const compilers = await Promise.all(
237
- cssPaths.map(async (cssPath) => {
238
- const css = await Bun.file(cssPath).text();
239
- const base = path.dirname(cssPath);
240
- const imported = new Map<string, string>();
241
- const compiler = await compile(css, {
242
- base,
243
- loadStylesheet: (id, fromBase) => this.#loadStylesheet(id, fromBase, imported),
244
- loadModule: (id, fromBase) => this.#loadModule(id, fromBase),
245
- });
246
- return { cssPath, compiler, imported };
247
- }),
248
- );
244
+ const compilers = await Promise.all(cssPaths.map((cssPath) => this.#compileStylesheet(cssPath)));
249
245
 
250
246
  const sourceDirs = new Set<string>();
251
247
  for (const entry of compilers) {
252
- for (const s of entry.compiler.sources as { base: string }[]) sourceDirs.add(s.base);
248
+ for (const s of (entry.compiler?.sources ?? []) as { base: string }[]) sourceDirs.add(s.base);
249
+ }
250
+ let candidates: string[] = [];
251
+ if (compilers.some((entry) => entry.compiler)) {
252
+ const scanStarted = Date.now();
253
+ candidates = await this.#scanCandidates(sourcePaths, [...sourceDirs]);
254
+ this.#logger.verbose(
255
+ `css candidates scanned count=${candidates.length} sources=${sourcePaths.length} dirs=${sourceDirs.size} in ${Date.now() - scanStarted}ms`,
256
+ );
253
257
  }
254
- const scanStarted = Date.now();
255
- const candidates = await this.#scanCandidates(sourcePaths, [...sourceDirs]);
256
- this.#logger.verbose(
257
- `css candidates scanned count=${candidates.length} sources=${sourcePaths.length} dirs=${sourceDirs.size} in ${Date.now() - scanStarted}ms`,
258
- );
259
258
  const parts: string[] = [];
260
259
  const imported: ImportedStylesheet[] = [];
261
260
  for (const entry of compilers) {
262
- const part = entry.compiler.build(candidates);
261
+ const part = entry.compiler ? entry.compiler.build(candidates) : entry.plainCss;
263
262
  parts.push(part);
264
263
  for (const [cssPath, content] of entry.imported) {
265
264
  const declaredNames = declaredCustomProperties(content);
266
265
  imported.push({ cssPath, declaredNames });
267
- if (declaredNames.length === 0 || declaredNames.some((name) => part.includes(`${name}:`))) continue;
266
+ if (!entry.compiler || declaredNames.length === 0 || declaredNames.some((name) => part.includes(`${name}:`)))
267
+ continue;
268
268
  this.#logger.warn(
269
269
  `css @import ${cssPath} was loaded by ${entry.cssPath} but none of its ${declaredNames.length} declaration(s) reached the compiled CSS`,
270
270
  );
@@ -276,6 +276,26 @@ export class CssCompiler {
276
276
  return { css: parts.join("\n"), imported };
277
277
  }
278
278
 
279
+ // `compile()` stamps its banner on any stylesheet with an `@import`, so one that needs no Tailwind never reaches it.
280
+ async #compileStylesheet(cssPath: string): Promise<CompiledStylesheet> {
281
+ const css = await Bun.file(cssPath).text();
282
+ const base = path.dirname(cssPath);
283
+ const imported = new Map<string, string>();
284
+ const loadStylesheet = (id: string, fromBase: string) => this.#loadStylesheet(id, fromBase, imported);
285
+ const plainCss = await PlainStylesheet.bundle(css, base, loadStylesheet);
286
+ if (plainCss !== null) {
287
+ this.#logger.verbose(`css ${cssPath} uses no Tailwind; passed through with ${imported.size} import(s) inlined`);
288
+ return { cssPath, compiler: null, plainCss, imported };
289
+ }
290
+ imported.clear();
291
+ const compiler = await compile(css, {
292
+ base,
293
+ loadStylesheet,
294
+ loadModule: (id, fromBase) => this.#loadModule(id, fromBase),
295
+ });
296
+ return { cssPath, compiler, plainCss: "", imported };
297
+ }
298
+
279
299
  async #loadStylesheet(id: string, fromBase: string, imported?: Map<string, string>) {
280
300
  const p = await this.#resolveCssImport(id, fromBase);
281
301
  this.#discoveredCssPaths.add(p);