@akanjs/devkit 3.1.0-rc.1 → 3.1.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 (138) hide show
  1. package/abstractDoc.ts +1 -1
  2. package/agentsIndex.test.ts +4 -1
  3. package/akanConfig/akanConfig.test.ts +51 -5
  4. package/akanConfig/akanConfig.ts +33 -14
  5. package/akanConfig/akanWorkspaceConfig.test.ts +6 -6
  6. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  7. package/akanContext.ts +4 -4
  8. package/akanMcpContract.ts +1 -1
  9. package/applicationBuildRunner.test.ts +57 -2
  10. package/applicationBuildRunner.ts +15 -6
  11. package/artifact/implicitRootLayout.test.ts +2 -0
  12. package/artifact/implicitRootLayout.ts +1 -0
  13. package/biome.base.json +1 -11
  14. package/biomeBase.ts +1 -1
  15. package/cloud/cloudApi.ts +22 -15
  16. package/cloud/cloudHttpError.test.ts +32 -0
  17. package/cloud/cloudHttpError.ts +54 -0
  18. package/cloud/cloudUpdates.ts +138 -0
  19. package/cloud/configLock.ts +2 -1
  20. package/cloud/globalConfig.test.ts +17 -0
  21. package/cloud/globalConfig.ts +9 -2
  22. package/cloud/index.ts +3 -0
  23. package/cloud/pipelineSecrets.ts +114 -0
  24. package/cloud/updatePackUpload.test.ts +100 -45
  25. package/cloud/updatePackUpload.ts +38 -18
  26. package/codeAgent/agent/CodeAgentProxy.ts +2 -2
  27. package/codeAgent/agent/akanCodeModel.ts +1 -1
  28. package/codeAgent/agent/akanContextFiles.test.ts +3 -1
  29. package/codeAgent/tools/WebToolPack.ts +4 -4
  30. package/codeAgent/tools/akanCodePlugins.test.ts +20 -16
  31. package/commandDecorators/argMeta.ts +11 -2
  32. package/commandDecorators/command.ts +45 -10
  33. package/commandDecorators/commandBuilder.ts +6 -1
  34. package/commandDecorators/commandDecorators.test.ts +205 -4
  35. package/commandDecorators/exitCodeError.ts +15 -0
  36. package/commandDecorators/index.ts +1 -0
  37. package/createTunnel.test.ts +14 -0
  38. package/createTunnel.ts +3 -1
  39. package/dependencyScanner.ts +1 -1
  40. package/devkitUtils.test.ts +1 -1
  41. package/executors.test.ts +131 -3
  42. package/executors.ts +56 -36
  43. package/frontendBuild/autoImportSync.test.ts +3 -1
  44. package/frontendBuild/clientEntryDiscovery.ts +1 -1
  45. package/frontendBuild/csrArtifactBuilder.test.ts +30 -0
  46. package/frontendBuild/csrArtifactBuilder.ts +23 -4
  47. package/frontendBuild/csrDevPatcher.test.ts +4 -1
  48. package/frontendBuild/cssBlockParser.test.ts +123 -0
  49. package/frontendBuild/cssBlockParser.ts +132 -0
  50. package/frontendBuild/cssCompiler.test.ts +53 -0
  51. package/frontendBuild/cssCompiler.ts +8 -4
  52. package/frontendBuild/fontOptimizer.ts +2 -1
  53. package/frontendBuild/frontendBuild.test.ts +14 -0
  54. package/frontendBuild/hmrWatcher.ts +1 -1
  55. package/frontendBuild/pagesBundleBuilder.test.ts +98 -0
  56. package/frontendBuild/pagesBundleBuilder.ts +64 -9
  57. package/frontendBuild/routeClientBuilder.ts +1 -1
  58. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  59. package/frontendBuild/themeValidator.test.ts +83 -2
  60. package/frontendBuild/themeValidator.ts +37 -15
  61. package/getRelatedCnsts.ts +2 -1
  62. package/incrementalBuilder/buildBatch.proc.ts +12 -7
  63. package/incrementalBuilder/incrementalBuilder.proc.test.ts +63 -0
  64. package/incrementalBuilder/incrementalBuilder.proc.ts +7 -5
  65. package/integration/devStabilityHarness.ts +5 -3
  66. package/lint/__fixtures__/no-deep-internal-import/bad.tsx +1 -0
  67. package/lint/__fixtures__/no-deep-internal-import/good.tsx +1 -0
  68. package/lint/__fixtures__/no-import-client-functions/bad.tsx +1 -0
  69. package/lint/__fixtures__/no-import-client-functions/good.tsx +1 -0
  70. package/lint/__fixtures__/no-import-client-in-server/bad.tsx +1 -0
  71. package/lint/__fixtures__/no-import-client-in-server/good.tsx +1 -0
  72. package/lint/__fixtures__/no-import-external-library/bad.tsx +1 -0
  73. package/lint/__fixtures__/no-import-external-library/good.tsx +1 -0
  74. package/lint/__fixtures__/no-import-external-library-in-test/bad.tsx +1 -0
  75. package/lint/__fixtures__/no-import-external-library-in-test/good.tsx +1 -0
  76. package/lint/__fixtures__/no-import-server-in-client/bad.tsx +1 -0
  77. package/lint/__fixtures__/no-import-server-in-client/good.tsx +1 -0
  78. package/lint/__fixtures__/no-init-fetch-in-client/store-file/bad.ts +1 -1
  79. package/lint/__fixtures__/no-static-in-object-light-model/bad.ts +2 -2
  80. package/mobile/desktopServerStage.test.ts +13 -0
  81. package/mobile/desktopServerStage.ts +5 -7
  82. package/mobile/index.ts +2 -0
  83. package/mobile/mobileTarget.ts +1 -2
  84. package/mobile/nativeApi.test.ts +26 -0
  85. package/mobile/nativeApi.ts +5 -2
  86. package/mobile/nativeApp.test.ts +135 -33
  87. package/mobile/nativeApp.ts +109 -73
  88. package/mobile/nativeConfig.test.ts +3 -0
  89. package/mobile/nativeConfig.ts +5 -3
  90. package/mobile/nativePublicEnv.test.ts +131 -0
  91. package/mobile/nativePublicEnv.ts +116 -0
  92. package/mobile/nativeWebDir.ts +3 -2
  93. package/mobile/serverBundleSecrets.test.ts +79 -0
  94. package/mobile/serverBundleSecrets.ts +60 -16
  95. package/mobile/updatePackFolder.test.ts +98 -0
  96. package/mobile/updatePackFolder.ts +131 -0
  97. package/mobile/updateUploader.test.ts +115 -22
  98. package/mobile/updateUploader.ts +77 -10
  99. package/package.json +20 -20
  100. package/piDependencyPins.test.ts +18 -19
  101. package/pipeline/PipelineCompiler.test.ts +157 -1
  102. package/pipeline/PipelineCompiler.ts +80 -46
  103. package/pipeline/PipelineDefinition.test.ts +9 -0
  104. package/pipeline/PipelineDefinition.ts +4 -3
  105. package/pipeline/PipelineDryRun.test.ts +27 -0
  106. package/pipeline/PipelineDryRun.ts +2 -2
  107. package/pipeline/PipelineInputReader.ts +157 -253
  108. package/pipeline/PipelineRules.ts +92 -0
  109. package/pipeline/index.ts +1 -0
  110. package/platformTest/LinuxDockerTarget.ts +2 -1
  111. package/platformTest/PlatformTestTarget.ts +7 -5
  112. package/platformTest/WindowsSshTarget.ts +2 -1
  113. package/qualityScanner.test.ts +5 -3
  114. package/qualityScanner.ts +1 -1
  115. package/recipeScanner.test.ts +9 -3
  116. package/scanInfo.ts +1 -1
  117. package/slicePlanner.ts +5 -3
  118. package/subspace.test.ts +90 -19
  119. package/subspace.ts +52 -500
  120. package/subspaceClone.ts +362 -0
  121. package/subspaceConfig.ts +1 -2
  122. package/subspaceReport.ts +162 -0
  123. package/testHelpers.ts +2 -0
  124. package/transforms/barrelImportsPlugin.ts +1 -1
  125. package/transforms/browserDirnamePlugin.test.ts +88 -0
  126. package/transforms/browserDirnamePlugin.ts +25 -0
  127. package/transforms/rscUseClientTransform.ts +2 -2
  128. package/transforms/serverEnvPlugin.test.ts +76 -0
  129. package/transforms/serverEnvPlugin.ts +9 -25
  130. package/transforms/serverEnvProfile.test.ts +189 -0
  131. package/transforms/serverEnvProfile.ts +324 -60
  132. package/transforms/transforms.test.ts +18 -2
  133. package/transforms/tsconfigPackageResolver.test.ts +9 -0
  134. package/typecheck/projectTypecheck.ts +6 -5
  135. package/types.ts +1 -0
  136. package/workflow/artifacts.ts +1 -1
  137. package/workflow/rolloutGate.test.ts +5 -1
  138. package/workflow/source.ts +2 -2
@@ -0,0 +1,53 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { declaredCustomProperties } from "./cssCompiler";
3
+
4
+ describe("declaredCustomProperties", () => {
5
+ test("names what the regex-based version named", () => {
6
+ expect(declaredCustomProperties(":root { --kakao: #fee500; --naver: #1ec800; }")).toEqual(["--kakao", "--naver"]);
7
+ expect(declaredCustomProperties("@theme inline {\n --color-brand: var(--brand);\n}\n")).toEqual([]);
8
+ expect(declaredCustomProperties("@theme { --color-x: initial; }\n:root { --brand: #111; }")).toEqual(["--brand"]);
9
+ expect(declaredCustomProperties(".a { color: var(--kakao); }")).toEqual([]);
10
+ expect(declaredCustomProperties(":root{--a:#111}\n@media (min-width:1px){:root{--a:#222;--b:#333}}")).toEqual([
11
+ "--a",
12
+ "--b",
13
+ ]);
14
+ expect(declaredCustomProperties(":root { --a : 1; --b:2 }")).toEqual(["--a", "--b"]);
15
+ expect(declaredCustomProperties(".a{--x:1}.b{--y:2}.c{--z:3}")).toEqual(["--x", "--y", "--z"]);
16
+ expect(declaredCustomProperties("--top: 1;")).toEqual(["--top"]);
17
+ expect(declaredCustomProperties("@property --percentage { syntax: '<number>'; inherits: false; }")).toEqual([]);
18
+ });
19
+
20
+ test("keeps source order across nested rules", () => {
21
+ expect(declaredCustomProperties(".x { --a: 1; .y { --b: 2; } --c: 3; }")).toEqual(["--a", "--b", "--c"]);
22
+ });
23
+
24
+ test("skips a whole @theme block, nested blocks included", () => {
25
+ const css = `@theme { --animate-spin: spin 1s; @keyframes spin { to { --inner: 1; } } --color-after: red; } :root { --kept: 1; }`;
26
+ expect(declaredCustomProperties(css)).toEqual(["--kept"]);
27
+ });
28
+
29
+ test("ignores comments and strings, so a comment mentioning @theme hides nothing", () => {
30
+ const css = [
31
+ "/* `@theme` extension does not work from a lib, so these are plain variables. */",
32
+ ":root { --kakao: #fee500; }",
33
+ "/* :root { --commented: 1; } */",
34
+ `.a::before { content: "--quoted: 1"; }`,
35
+ ].join("\n");
36
+ expect(declaredCustomProperties(css)).toEqual(["--kakao"]);
37
+ });
38
+
39
+ test("adversarial input finishes well under a second", () => {
40
+ for (const css of [
41
+ "@theme".repeat(100_000),
42
+ "@theme{".repeat(100_000),
43
+ `@theme ${"x".repeat(100_000)}`,
44
+ `:root{${"--".repeat(100_000)}`,
45
+ " --a".repeat(100_000),
46
+ "@media x{".repeat(100_000),
47
+ ]) {
48
+ const started = performance.now();
49
+ declaredCustomProperties(css);
50
+ expect(performance.now() - started).toBeLessThan(1000);
51
+ }
52
+ });
53
+ });
@@ -6,6 +6,7 @@ import type { App } from "../commandDecorators";
6
6
  import { BarrelAnalyzer } from "../transforms/barrelAnalyzer";
7
7
  import { createTsconfigPackageResolver, rewriteBarrelImports } from "../transforms/barrelImportsPlugin";
8
8
  import { CsrEntryFiles } from "./csrEntryFiles";
9
+ import { CssBlockParser } from "./cssBlockParser";
9
10
  import { CssCandidateCache } from "./cssCandidateCache";
10
11
  import { CssImportResolver } from "./cssImportResolver";
11
12
 
@@ -387,10 +388,13 @@ export function isIgnoredNodeModuleSource(filePath: string): boolean {
387
388
 
388
389
  /** Skips `@theme` blocks: Tailwind emits those variables only when a utility uses one. */
389
390
  export function declaredCustomProperties(css: string): string[] {
390
- const withoutThemeBlocks = css.replace(/@theme[^{]*\{[^}]*\}/g, "");
391
- return [...new Set([...withoutThemeBlocks.matchAll(/(?:^|[\s;{])(--[\w-]+)\s*:/g)].map(([, name]) => name))].filter(
392
- (name): name is string => !!name,
393
- );
391
+ const names = new Set<string>();
392
+ CssBlockParser.walk(CssBlockParser.parse(css), true, (node) => {
393
+ if (node.kind === "block") return node.atRule === "@theme" ? null : true;
394
+ if (node.property.startsWith("--")) names.add(node.property);
395
+ return null;
396
+ });
397
+ return [...names];
394
398
  }
395
399
 
396
400
  export function getPageKeyBasePath(pageKey: string, basePaths: string[]): string | null {
@@ -425,7 +425,8 @@ export class FontOptimizer {
425
425
  if (!isDir) continue;
426
426
  const filePaths: string[] = [];
427
427
  for await (const filePath of glob.scan({ cwd: root, absolute: true })) filePaths.push(filePath);
428
- for (const filePath of filePaths.sort()) parts.push(await Bun.file(filePath).text());
428
+ for (const filePath of filePaths.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)))
429
+ parts.push(await Bun.file(filePath).text());
429
430
  }
430
431
  return parts.join("");
431
432
  }
@@ -195,6 +195,20 @@ describe("CsrArtifactBuilder", () => {
195
195
  );
196
196
  });
197
197
 
198
+ test("blanks embedded bodies the way the HTML tokenizer closes them", () => {
199
+ const blank = (html: string) => CsrArtifactBuilder.blankEmbeddedContent(html).trim();
200
+
201
+ expect(blank("<script>a</script >")).toBe("");
202
+ expect(blank("<script>a</script\t\n bar>")).toBe("");
203
+ expect(blank("<SCRIPT>a</SCRIPT>")).toBe("");
204
+ expect(blank("<style>a</style foo>")).toBe("");
205
+ expect(blank("<!-- a --!></head>")).toBe("</head>");
206
+ expect(blank("<script>a</scripts></head>")).toBe("");
207
+ expect(blank("<!-- a </head>")).toBe("");
208
+ expect(CsrArtifactBuilder.blankEmbeddedContent(`<!--${"<!--".repeat(50_000)}`)).toHaveLength(200_004);
209
+ expect(CsrArtifactBuilder.blankEmbeddedContent(`<script>${"</script\t".repeat(50_000)}`)).toHaveLength(450_008);
210
+ });
211
+
198
212
  test("gives each basePath its own routes plus the routes outside every basePath", () => {
199
213
  const entries = [
200
214
  { key: "./_layout.tsx", moduleAbsPath: "/repo/page/_layout.tsx" },
@@ -197,7 +197,7 @@ export class HmrWatcher {
197
197
  const gaps = this.#index.coverageGaps;
198
198
  const key = gaps
199
199
  .map((gap) => `${gap.code}:${gap.path}`)
200
- .sort()
200
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
201
201
  .join("|");
202
202
  if (key === this.#reportedGaps) return;
203
203
  this.#reportedGaps = key;
@@ -0,0 +1,98 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { PagesBundleBuilder } from "./pagesBundleBuilder";
3
+
4
+ const macroImport = `import { getSerializedSignal } from "./sig" with { type: "macro" };`;
5
+ const macroFetchProto =
6
+ "const fetchProto = FetchClient.build<typeof signal>(cnst, getSerializedSignal(), { Err: pageProto.Err });";
7
+ const serverImport = `import { fetch as serverFetch } from "./sig";`;
8
+ const serverFetchProto =
9
+ "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { Err: pageProto.Err, base: serverFetch });";
10
+
11
+ const generatedUseClient = (lines: { importLine?: string; fetchProtoLine?: string } = {}) =>
12
+ [
13
+ 'import { makePageProto, registerClientRuntime } from "akanjs/client";',
14
+ 'import { FetchClient } from "akanjs/fetch";',
15
+ 'import * as cnst from "./cnst";',
16
+ 'import type * as dict from "./dict";',
17
+ lines.importLine ?? macroImport,
18
+ 'import type * as signal from "./sig";',
19
+ "",
20
+ "// dict.ts is cumulative, so a lib dictionary is a subset of the mounting app's. Translator state is global,",
21
+ "const dictionary = {};",
22
+ "const pageProto = makePageProto<typeof dict>(dictionary);",
23
+ lines.fetchProtoLine ?? macroFetchProto,
24
+ 'export const runtime = registerClientRuntime({ ...pageProto, ...fetchProto }, { scope: "lib" });',
25
+ "",
26
+ "export const { msg, Err, usePage, sig, fetch } = runtime;",
27
+ "",
28
+ ].join("\n");
29
+
30
+ const transform = (source: string) => PagesBundleBuilder.transformServerUseClientFetchSource(source);
31
+
32
+ describe("PagesBundleBuilder.transformServerUseClientFetchSource", () => {
33
+ test("swaps the signal macro for the live server fetch in the generated useClient.ts", () => {
34
+ expect(transform(generatedUseClient())).toBe(
35
+ generatedUseClient({ importLine: serverImport, fetchProtoLine: serverFetchProto }),
36
+ );
37
+ });
38
+
39
+ test("accepts the spacing and quoting variants the regex-based version accepted", () => {
40
+ const source = generatedUseClient({
41
+ importLine: `import {getSerializedSignal} from './sig' with {type : 'macro'};`,
42
+ fetchProtoLine: [
43
+ "const fetchProto=FetchClient.build<typeof signal>(",
44
+ " cnst,",
45
+ " getSerializedSignal(),",
46
+ " { Err: pageProto.Err },",
47
+ ");",
48
+ ].join("\n"),
49
+ }).replace("import type * as dict", `import { x } from "./x" with { type: "macro" };\nimport type * as dict`);
50
+ const transformed = transform(source);
51
+ expect(transformed).toContain(`\n${serverImport}\n`);
52
+ expect(transformed).toContain(`\n${serverFetchProto}\nexport const runtime`);
53
+ expect(transformed).not.toContain("getSerializedSignal");
54
+ });
55
+
56
+ test("keeps an export modifier in front of the rewritten declaration", () => {
57
+ const transformed = transform(generatedUseClient({ fetchProtoLine: `export ${macroFetchProto}` }));
58
+ expect(transformed).toContain(`\nexport ${serverFetchProto}\n`);
59
+ });
60
+
61
+ test("leaves comments and strings that spell the statements alone", () => {
62
+ const source = generatedUseClient().replace(
63
+ "const dictionary = {};",
64
+ `// ${macroFetchProto}\nconst note = "${macroImport.replaceAll('"', "'")}";\nconst dictionary = {};`,
65
+ );
66
+ const transformed = transform(source);
67
+ expect(transformed).toContain(`// ${macroFetchProto}\n`);
68
+ expect(transformed).toContain(`const note = "${macroImport.replaceAll('"', "'")}";`);
69
+ expect(transformed).toContain(`\n${serverImport}\n`);
70
+ expect(transformed).toContain(`\n${serverFetchProto}\n`);
71
+ });
72
+
73
+ test("returns sources it does not recognise unchanged", () => {
74
+ const transformed = generatedUseClient({ importLine: serverImport, fetchProtoLine: serverFetchProto });
75
+ expect(transform(transformed)).toBe(transformed);
76
+ const typeOnly = generatedUseClient({ importLine: macroImport.replace("import {", "import type {") });
77
+ expect(transform(typeOnly)).toContain(`import type { getSerializedSignal } from "./sig" with { type: "macro" };`);
78
+ const aliased = generatedUseClient({
79
+ importLine: macroImport.replace("getSerializedSignal", "getSerializedSignal as g"),
80
+ });
81
+ expect(transform(aliased)).toContain(`import { getSerializedSignal as g } from "./sig" with { type: "macro" };`);
82
+ const withoutMacro = 'import { x } from "./y";\n';
83
+ expect(transform(withoutMacro)).toBe(withoutMacro);
84
+ });
85
+
86
+ test("adversarial input finishes well under a second", () => {
87
+ const marker = `${macroImport}\nFetchClient.build\n`;
88
+ for (const source of [
89
+ marker + "const fetchProto=FetchClient.build<".repeat(100_000),
90
+ marker + `import { getSerializedSignal } from "./sig" with { type: `.repeat(100_000),
91
+ marker + "{".repeat(100_000),
92
+ ]) {
93
+ const started = performance.now();
94
+ transform(source);
95
+ expect(performance.now() - started).toBeLessThan(1000);
96
+ }
97
+ });
98
+ });
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { BunPlugin } from "bun";
4
+ import ts from "typescript";
4
5
  import type { PageEntry } from "../artifact/implicitRootLayout";
5
6
  import { resolveSsrPageEntriesForApp } from "../artifact/implicitRootLayout";
6
7
  import type { App } from "../commandDecorators";
@@ -25,6 +26,12 @@ export interface BuildPagesBundleResult {
25
26
  chunkCount: number;
26
27
  }
27
28
 
29
+ interface TextSpan {
30
+ start: number;
31
+ end: number;
32
+ text: string;
33
+ }
34
+
28
35
  const VIRTUAL_PAGES_ENTRY = "akan-pages-entry";
29
36
 
30
37
  export class PagesBundleBuilder {
@@ -174,14 +181,62 @@ export class PagesBundleBuilder {
174
181
 
175
182
  static transformServerUseClientFetchSource(source: string): string {
176
183
  if (!source.includes(`with { type: "macro" }`) || !source.includes("FetchClient.build")) return source;
177
- return source
178
- .replace(
179
- /import\s+\{\s*getSerializedSignal\s*\}\s+from\s+["']\.\/sig["']\s+with\s+\{\s*type\s*:\s*["']macro["']\s*\};/,
180
- `import { fetch as serverFetch } from "./sig";`,
181
- )
182
- .replace(
183
- /const\s+fetchProto\s*=\s*FetchClient\.build<[^;]+;/,
184
- "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { Err: pageProto.Err, base: serverFetch });",
185
- );
184
+ const tokens = PagesBundleBuilder.#tokenize(source);
185
+ const edits: TextSpan[] = [];
186
+ const importAt = PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#macroImportTokens);
187
+ if (importAt !== -1)
188
+ edits.push({
189
+ start: tokens[importAt].start,
190
+ end: tokens[importAt + PagesBundleBuilder.#macroImportTokens.length - 1].end,
191
+ text: `import { fetch as serverFetch } from "./sig";`,
192
+ });
193
+ const fetchProtoAt = PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#fetchProtoTokens);
194
+ const fetchProtoEnd = fetchProtoAt === -1 ? undefined : tokens.slice(fetchProtoAt).find(({ text }) => text === ";");
195
+ if (fetchProtoEnd)
196
+ edits.push({
197
+ start: tokens[fetchProtoAt].start,
198
+ end: fetchProtoEnd.end,
199
+ text: "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { Err: pageProto.Err, base: serverFetch });",
200
+ });
201
+ let transformed = source;
202
+ for (const { start, end, text } of edits.sort((a, b) => b.start - a.start))
203
+ transformed = transformed.slice(0, start) + text + transformed.slice(end);
204
+ return transformed;
205
+ }
206
+
207
+ static readonly #macroImportTokens = [
208
+ "import",
209
+ "{",
210
+ "getSerializedSignal",
211
+ "}",
212
+ "from",
213
+ '"./sig"',
214
+ "with",
215
+ "{",
216
+ "type",
217
+ ":",
218
+ '"macro"',
219
+ "}",
220
+ ";",
221
+ ] as const;
222
+ static readonly #fetchProtoTokens = ["const", "fetchProto", "=", "FetchClient", ".", "build", "<"] as const;
223
+
224
+ //? The scanner, not the parser: parsing recurses per nesting level and overflows the stack on a deep `{` run.
225
+ static #tokenize(source: string): TextSpan[] {
226
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, source);
227
+ const tokens: TextSpan[] = [];
228
+ for (let kind = scanner.scan(); kind !== ts.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
229
+ const text =
230
+ kind === ts.SyntaxKind.StringLiteral ? JSON.stringify(scanner.getTokenValue()) : scanner.getTokenText();
231
+ tokens.push({ text, start: scanner.getTokenStart(), end: scanner.getTokenEnd() });
232
+ }
233
+ return tokens;
234
+ }
235
+
236
+ static #indexOfTokens(tokens: TextSpan[], pattern: readonly string[]): number {
237
+ for (let idx = 0; idx + pattern.length <= tokens.length; idx += 1) {
238
+ if (pattern.every((text, offset) => tokens[idx + offset].text === text)) return idx;
239
+ }
240
+ return -1;
186
241
  }
187
242
  }
@@ -244,7 +244,7 @@ export class RouteClientBuilder {
244
244
  //? a probe export and only the ones the parser reports as exports are declarations.
245
245
  static #declaredNamedDefaultFunctions(source: string, filePath?: string) {
246
246
  const candidates = [
247
- ...source.matchAll(/(^|\n)(\s*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g),
247
+ ...source.matchAll(/(^|\n)([^\S\n]*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g),
248
248
  ].map((match) => ({
249
249
  index: match.index,
250
250
  text: match[0],
@@ -50,7 +50,7 @@ describe("SourceMtimeIndex", () => {
50
50
 
51
51
  for (const [i, abs] of files.entries()) await rewrite(abs, `${i}00`);
52
52
 
53
- expect((await index.collectChanges()).sort()).toEqual([...files].sort());
53
+ expect((await index.collectChanges()).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))).toEqual([...files].sort());
54
54
  });
55
55
 
56
56
  test("reports a change once, then stops reporting it", async () => {
@@ -37,6 +37,67 @@ describe("ThemeValidator.parseThemeTokens", () => {
37
37
  const tokens = ThemeValidator.parseThemeTokens(css);
38
38
  expect(Object.keys(tokens)).toEqual([":root"]);
39
39
  });
40
+
41
+ test("reads every block, not every other one", () => {
42
+ const css = `.a {} :root { --background: #fff; } .b {} [data-theme='light'] { --background: #eee; } [data-theme="dark"] { --background: #111; }`;
43
+ expect(ThemeValidator.parseThemeTokens(css)).toEqual({
44
+ ":root": { background: "#fff" },
45
+ '[data-theme="light"]': { background: "#eee" },
46
+ '[data-theme="dark"]': { background: "#111" },
47
+ });
48
+ });
49
+
50
+ test("reads the first block after @source and @import lines", () => {
51
+ const css = [
52
+ `@source "./**/*";`,
53
+ `@import "tailwindcss";`,
54
+ `@plugin "tailwind-scrollbar";`,
55
+ `:root { --background: #ffffff; --foreground: #0a0a0a; }`,
56
+ `[data-theme="dark"] { --background: #0a0a0a; --foreground: #fafafa; }`,
57
+ `[data-theme="light"] { --background: #fafafa; --foreground: #171717; }`,
58
+ ].join("\n");
59
+ expect(Object.keys(ThemeValidator.parseThemeTokens(css))).toEqual([
60
+ ":root",
61
+ '[data-theme="dark"]',
62
+ '[data-theme="light"]',
63
+ ]);
64
+ });
65
+
66
+ test("keeps a block's own declarations, skipping comments and nested rules", () => {
67
+ const css = `:root { /* --background: #000; */ --background: #fff; .x { --foreground: #000; } --foreground: #111 }`;
68
+ expect(ThemeValidator.parseThemeTokens(css)).toEqual({ ":root": { background: "#fff", foreground: "#111" } });
69
+ });
70
+
71
+ test("merges a scope declared twice, the later value winning", () => {
72
+ const css = `:root { --background: #fff; --foreground: #000; } :root { --foreground: #111; }`;
73
+ expect(ThemeValidator.parseThemeTokens(css)).toEqual({ ":root": { background: "#fff", foreground: "#111" } });
74
+ });
75
+
76
+ test("reads through @layer and keys a conditional scope by its condition", () => {
77
+ const css = [
78
+ `@layer base { :root { --background: #fff; --foreground: #000; } }`,
79
+ `@media (prefers-color-scheme: dark) { :root { --background: #000; } }`,
80
+ ].join("\n");
81
+ expect(ThemeValidator.parseThemeTokens(css)).toEqual({
82
+ ":root": { background: "#fff", foreground: "#000" },
83
+ "@media (prefers-color-scheme: dark) :root": { background: "#000" },
84
+ });
85
+ });
86
+
87
+ test("adversarial input finishes well under a second", () => {
88
+ for (const css of [
89
+ " ".repeat(100_000),
90
+ `}${" ".repeat(100_000)}`,
91
+ `:root{${"--".repeat(100_000)}`,
92
+ `:root{---:${" ".repeat(100_000)}`,
93
+ ":root{--background:#fff}".repeat(100_000),
94
+ `${"@media x{".repeat(100_000)}:root{--background:#fff}`,
95
+ ]) {
96
+ const started = performance.now();
97
+ ThemeValidator.parseThemeTokens(css);
98
+ expect(performance.now() - started).toBeLessThan(1000);
99
+ }
100
+ });
40
101
  });
41
102
 
42
103
  describe("ThemeValidator.validate", () => {
@@ -58,12 +119,32 @@ describe("ThemeValidator.validate", () => {
58
119
  const css = `:root { --primary: var(--brand); --primary-foreground: #000000; }`;
59
120
  expect(validator.validate(css)).toHaveLength(0);
60
121
  });
122
+
123
+ test("checks a conditional scope over the scope it overrides", () => {
124
+ const css = [
125
+ `:root { --background: #ffffff; --foreground: #000000; }`,
126
+ `@media (prefers-color-scheme: dark) { :root { --background: #111111; } }`,
127
+ ].join("\n");
128
+ const violations = validator.validate(css);
129
+ expect(violations.map(({ scope, pair }) => [scope, pair])).toEqual([
130
+ ["@media (prefers-color-scheme: dark) :root", "background / foreground"],
131
+ ]);
132
+ });
61
133
  });
62
134
 
63
135
  describe("shipped framework palette", () => {
136
+ const css = readFileSync(path.resolve(import.meta.dir, "../../../akanjs/ui/styles.css"), "utf8");
137
+
138
+ test("pkgs/akanjs/ui/styles.css parses :root, dark and light", () => {
139
+ const tokens = ThemeValidator.parseThemeTokens(css);
140
+ expect(Object.keys(tokens)).toEqual([":root", '[data-theme="dark"]', '[data-theme="light"]']);
141
+ expect(tokens[":root"].background).toBe("#0a0a0a");
142
+ expect(tokens['[data-theme="dark"]'].background).toBe("#0a0a0a");
143
+ expect(tokens['[data-theme="light"]'].background).toBe("#ffffff");
144
+ for (const scopeTokens of Object.values(tokens)) expect(Object.keys(scopeTokens).length).toBeGreaterThanOrEqual(26);
145
+ });
146
+
64
147
  test("pkgs/akanjs/ui/styles.css passes WCAG contrast for all scopes", () => {
65
- const stylesPath = path.resolve(import.meta.dir, "../../../akanjs/ui/styles.css");
66
- const css = readFileSync(stylesPath, "utf8");
67
148
  const violations = validator.validate(css);
68
149
  expect(violations).toEqual([]);
69
150
  });
@@ -1,4 +1,5 @@
1
1
  // No akanjs runtime import: this runs inside the lint path.
2
+ import { type CssBlock, CssBlockParser } from "./cssBlockParser";
2
3
 
3
4
  export interface ThemeContrastViolation {
4
5
  scope: string;
@@ -34,6 +35,7 @@ const PAIRS: PairDef[] = [
34
35
  ];
35
36
 
36
37
  const THEME_SCOPES = new Set([":root", '[data-theme="dark"]', '[data-theme="light"]']);
38
+ const CONDITIONAL_AT_RULES = new Set(["@media", "@supports", "@container"]);
37
39
 
38
40
  export type ThemeTokensByScope = Record<string, Record<string, string>>;
39
41
 
@@ -42,8 +44,9 @@ export class ThemeValidator {
42
44
  const tokensByScope = ThemeValidator.parseThemeTokens(css);
43
45
  const violations: ThemeContrastViolation[] = [];
44
46
  for (const [scope, tokens] of Object.entries(tokensByScope)) {
45
- if (!THEME_SCOPES.has(scope)) continue;
46
- violations.push(...this.validateScope(tokens, scope));
47
+ const underlying = THEME_SCOPES.has(scope) ? null : [...THEME_SCOPES].find((name) => scope.endsWith(` ${name}`));
48
+ const effective = underlying ? ThemeValidator.#overlayPairs(tokensByScope[underlying] ?? {}, tokens) : tokens;
49
+ violations.push(...this.validateScope(effective, scope));
47
50
  }
48
51
  return violations;
49
52
  }
@@ -75,23 +78,42 @@ export class ThemeValidator {
75
78
  /** A scope declared twice keeps the later value, so pass the framework css before the app's. */
76
79
  static parseThemeTokens(css: string): ThemeTokensByScope {
77
80
  const result: ThemeTokensByScope = {};
78
- const blockRe = /(?:^|})\s*([^{}@]+?)\s*\{([^{}]*)\}/g;
79
- for (const block of css.matchAll(blockRe)) {
80
- const selectors = block[1].split(",").map((s) => s.trim());
81
- const relevant = selectors.filter((s) => THEME_SCOPES.has(ThemeValidator.#normalizeScope(s)));
82
- if (relevant.length === 0) continue;
83
- const decls: Record<string, string> = {};
84
- for (const decl of block[2].matchAll(/--([\w-]+)\s*:\s*([^;]+?)\s*(?:;|$)/g)) {
85
- decls[decl[1]] = decl[2].trim();
81
+ CssBlockParser.walk(CssBlockParser.parse(css), "", (node, condition) => {
82
+ if (node.kind !== "block") return null;
83
+ if (node.atRule === "@layer") return condition;
84
+ if (node.atRule) return CONDITIONAL_AT_RULES.has(node.atRule) ? node.prelude.replace(/\s+/g, " ") : null;
85
+ const scopes = node.prelude
86
+ .split(",")
87
+ .map((selector) => ThemeValidator.#normalizeScope(selector))
88
+ .filter((scope) => THEME_SCOPES.has(scope));
89
+ if (scopes.length === 0) return null;
90
+ const tokens = ThemeValidator.#customProperties(node);
91
+ for (const scope of scopes) {
92
+ const key = condition ? `${condition} ${scope}` : scope;
93
+ result[key] = Object.assign(result[key] ?? {}, tokens);
86
94
  }
87
- for (const selector of relevant) {
88
- const scope = ThemeValidator.#normalizeScope(selector);
89
- result[scope] = { ...(result[scope] ?? {}), ...decls };
90
- }
91
- }
95
+ return null;
96
+ });
92
97
  return result;
93
98
  }
94
99
 
100
+ static #customProperties(block: CssBlock): Record<string, string> {
101
+ const tokens: Record<string, string> = {};
102
+ for (const node of block.nodes) {
103
+ if (node.kind === "declaration" && node.property.startsWith("--")) tokens[node.property.slice(2)] = node.value;
104
+ }
105
+ return tokens;
106
+ }
107
+
108
+ static #overlayPairs(underlying: Record<string, string>, tokens: Record<string, string>): Record<string, string> {
109
+ const effective: Record<string, string> = {};
110
+ for (const name of PAIRS.flatMap(({ base, fg }) => [base, fg])) {
111
+ const value = tokens[name] ?? underlying[name];
112
+ if (value) effective[name] = value;
113
+ }
114
+ return effective;
115
+ }
116
+
95
117
  static #normalizeScope(selector: string): string {
96
118
  return selector.replace(/\[data-theme=['"]?([\w-]+)['"]?\]/g, '[data-theme="$1"]').trim();
97
119
  }
@@ -1,4 +1,5 @@
1
1
  import { readFileSync, realpathSync } from "node:fs";
2
+ import { dirname } from "node:path";
2
3
  import ora from "ora";
3
4
  import * as ts from "typescript";
4
5
 
@@ -45,7 +46,7 @@ export const parseTsConfig = (tsConfigPath: string = "./tsconfig.json") => {
45
46
  return ts.sys.readFile(path);
46
47
  });
47
48
 
48
- return ts.parseJsonConfigFileContent(configFile.config, ts.sys, realpathSync(tsConfigPath).replace(/[^/\\]+$/, ""));
49
+ return ts.parseJsonConfigFileContent(configFile.config, ts.sys, dirname(realpathSync(tsConfigPath)));
49
50
  };
50
51
 
51
52
  const collectFiles = (constantFilePath: string, parsedConfig: ts.ParsedCommandLine, includeExports: boolean) => {
@@ -33,13 +33,17 @@ class BuildBatch {
33
33
  }
34
34
 
35
35
  async run(): Promise<BuildBatchResult> {
36
- if (this.#request.needs.includes("base")) await this.#buildBase();
37
- if (this.#request.needs.includes("csr")) await this.#buildCsr();
38
- if (this.#request.needs.includes("shell")) await this.#buildShell();
39
- if (this.#request.needs.includes("ssr")) await this.#buildSsrRegistry();
36
+ const { needs } = this.#request;
37
+ //? A CSR artifact inlines the stylesheets, so it waits for this batch's compile of them; the registry reads none.
38
+ const cssFirst = needs.includes("css") && needs.includes("csr") && resolveDevCsrMode() === "artifact";
39
+ if (needs.includes("base")) await this.#buildBase();
40
+ if (cssFirst) await this.#buildCss();
41
+ if (needs.includes("csr")) await this.#buildCsr();
42
+ if (needs.includes("shell")) await this.#buildShell();
43
+ if (needs.includes("ssr")) await this.#buildSsrRegistry();
40
44
  // Css before pages: it scans the sources and reads nothing pages produces, so a class edit need not wait for pages.
41
- if (this.#request.needs.includes("css")) await this.#buildCss();
42
- if (this.#request.needs.includes("pages")) await this.#buildPages();
45
+ if (needs.includes("css") && !cssFirst) await this.#buildCss();
46
+ if (needs.includes("pages")) await this.#buildPages();
43
47
  return this.#result;
44
48
  }
45
49
 
@@ -112,7 +116,8 @@ class BuildBatch {
112
116
  }
113
117
 
114
118
  async #rebuildCsrArtifact(started: number): Promise<void> {
115
- await new CsrArtifactBuilder(this.#app, "start", "en", { cssAssets: this.#request.cssAssets }).build();
119
+ const cssAssets = this.#result.cssAssets ?? this.#request.cssAssets;
120
+ await new CsrArtifactBuilder(this.#app, "start", "en", { cssAssets }).build();
116
121
  this.#logger.verbose(`csr-rebundle ok (${Date.now() - started}ms)`);
117
122
  // A CSR tab takes none of the SSR refresh messages, so a rebuilt artifact reaches it only as this reload.
118
123
  if (this.#request.changedFiles.length === 0) return;
@@ -178,6 +178,69 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
178
178
  expect(batches.filter((needs) => needs === "shell")).toHaveLength(1);
179
179
  }, 30_000);
180
180
 
181
+ test("builds the shell again once the css it inlined is replaced, though the generation has not moved", async () => {
182
+ const { root } = track(await createTempApp("demo"));
183
+ const appDir = path.join(root, "apps/demo");
184
+ const ledger = path.join(root, "batches.log");
185
+ const gate = path.join(root, "css-lands");
186
+ const landed = { "": { cssUrl: "/_akan/styles/root-next.css", cssRelPath: "styles/root-next.css" } };
187
+ // The registry's boot build stands in for a save's css compile, held until the first shell is built.
188
+ await writeText(
189
+ path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
190
+ `import fs from "node:fs";
191
+ const { generation, needs, cssAssets } = JSON.parse(process.argv[2]);
192
+ fs.appendFileSync(${JSON.stringify(ledger)}, needs.join(",") + " " + JSON.stringify(cssAssets) + "\\n");
193
+ const orphaned = () => process.exit(1);
194
+ process.on("disconnect", orphaned);
195
+ const deadline = Date.now() + 15_000;
196
+ if (needs.includes("ssr")) while (!fs.existsSync(${JSON.stringify(gate)}) && Date.now() < deadline) await Bun.sleep(20);
197
+ const css = needs.includes("ssr") ? { cssAssets: ${JSON.stringify(landed)} } : {};
198
+ process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] }, ...css } });
199
+ process.off("disconnect", orphaned);
200
+ `,
201
+ );
202
+ await writeText(path.join(appDir, "page/_index.tsx"), "export default () => null;\n");
203
+ const messages: BuilderMessage[] = [];
204
+ const proc = Bun.spawn(["bun", path.join(import.meta.dir, "incrementalBuilder.proc.ts")], {
205
+ cwd: appDir,
206
+ env: {
207
+ ...process.env,
208
+ AKAN_WORKSPACE_ROOT: root,
209
+ AKAN_PUBLIC_APP_NAME: "demo",
210
+ AKAN_PUBLIC_REPO_NAME: "repo",
211
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
212
+ AKAN_PUBLIC_ENV: "local",
213
+ AKAN_WATCH: "0",
214
+ AKAN_DEV_CSR_PATCHER: "off",
215
+ },
216
+ stdio: ["ignore", "ignore", "pipe"],
217
+ serialization: "advanced",
218
+ ipc: (message: BuilderMessage) => {
219
+ messages.push(message);
220
+ },
221
+ });
222
+ const answers = () => messages.filter((message) => message.type === "build-csr-res");
223
+ try {
224
+ await until(proc, "builder-ready", () => messages.some((message) => message.type === "builder-ready"));
225
+ proc.send({ type: "build-csr", id: 7, reason: "mcp app view", shell: true } satisfies BuilderMessage);
226
+ await until(proc, "the first build-csr-res", () => answers().length === 1);
227
+ await writeText(gate, "");
228
+ await until(proc, "boot-armed", () => messages.some((message) => message.type === "boot-armed"));
229
+ proc.send({ type: "build-csr", id: 8, reason: "mcp app view", shell: true } satisfies BuilderMessage);
230
+ await until(proc, "the second build-csr-res", () => answers().length === 2);
231
+ } finally {
232
+ await writeText(gate, "");
233
+ proc.kill();
234
+ await proc.exited;
235
+ }
236
+ expect(answers()).toEqual([
237
+ { type: "build-csr-res", id: 7, ok: true },
238
+ { type: "build-csr-res", id: 8, ok: true },
239
+ ]);
240
+ const shells = (await Bun.file(ledger).text()).split("\n").filter((line) => line.startsWith("shell "));
241
+ expect(shells).toEqual(["shell null", `shell ${JSON.stringify(landed)}`]);
242
+ }, 30_000);
243
+
181
244
  test("a killed boot build is tried again after the crash window, before boot-armed; a route build's check waits likewise", async () => {
182
245
  // Inside the checkout so the route's client bundle resolves the framework from its source.
183
246
  const { root } = track(await createTempApp("demo", path.join(import.meta.dir, "..", "local")));