@akanjs/devkit 3.3.0-rc.36 → 3.3.0-rc.38

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 (44) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/app/applicationBuildRunner.ts +7 -1
  3. package/app/dictionarySizes.ts +2 -5
  4. package/app/routeFilesReport.test.ts +59 -0
  5. package/app/routeFilesReport.ts +46 -0
  6. package/app/routeJsBudget.ts +18 -4
  7. package/artifact/storeBootstrap.ts +5 -1
  8. package/biome.base.json +1 -3
  9. package/codeAgent/skills/akan-page/SKILL.md +28 -7
  10. package/executors/clientRuntimeKeys.test.ts +72 -1
  11. package/executors/sysExecutor.ts +10 -8
  12. package/frontendBuild/allRoutesBuilder.ts +14 -7
  13. package/frontendBuild/clientEntryDiscovery.test.ts +193 -0
  14. package/frontendBuild/clientEntryDiscovery.ts +41 -8
  15. package/frontendBuild/devBarrelImports.test.ts +54 -0
  16. package/frontendBuild/devBarrelImports.ts +1 -0
  17. package/frontendBuild/dictionaryAssetBuilder.test.ts +12 -4
  18. package/frontendBuild/dictionaryAssetBuilder.ts +20 -7
  19. package/frontendBuild/dictionaryConstants.ts +55 -1
  20. package/frontendBuild/dictionaryPacking.test.ts +58 -0
  21. package/frontendBuild/dictionaryPacking.ts +43 -0
  22. package/frontendBuild/dictionaryRoutes.test.ts +65 -0
  23. package/frontendBuild/dictionaryRoutes.ts +3 -1
  24. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  25. package/frontendBuild/precompressArtifacts.ts +18 -11
  26. package/frontendBuild/renderedEntries.ts +129 -0
  27. package/frontendBuild/routeHandoffs.test.ts +10 -0
  28. package/frontendBuild/routeHandoffs.ts +3 -1
  29. package/frontendBuild/routeRuntimePays.test.ts +7 -1
  30. package/lint/biomeBase.test.ts +23 -3
  31. package/package.json +3 -3
  32. package/quality/dictionaryKeys.test.ts +185 -2
  33. package/quality/dictionaryKeys.ts +82 -9
  34. package/quality/objectImportReport.ts +6 -3
  35. package/quality/translatorBindings.ts +187 -0
  36. package/transforms/barrelImportsPlugin.ts +6 -1
  37. package/transforms/exportReach.test.ts +162 -0
  38. package/transforms/exportReach.ts +304 -0
  39. package/transforms/objectMemberImports.test.ts +289 -7
  40. package/transforms/objectMemberImports.ts +92 -58
  41. package/transforms/objectMemberLookup.ts +150 -0
  42. package/transforms/objectModule.test.ts +72 -2
  43. package/transforms/objectModule.ts +31 -7
  44. package/workspace/scanInfo.ts +24 -0
@@ -35,6 +35,22 @@ export class User extends via(UserInput, (field) => ({})) {}
35
35
  "apps/demo/lib/__scalar/address/address.constant.ts",
36
36
  `export class Address extends via((field) => ({ city: field(String) })) {}`,
37
37
  );
38
+ constants.add(
39
+ "apps/demo/lib/runnerBot/runnerBot.constant.ts",
40
+ `export class RunnerBot extends via((field) => ({ name: field(String) })) {
41
+ static readonly labelKeyOf = { reviewer: "runnerBot.reviewer", fixer: "task.fixer" } as const;
42
+ static stageKeys = ["project.stage.open", "project.stage.done"] as const satisfies readonly string[];
43
+ static loose = { reviewer: "runnerBot.reviewer" };
44
+ static typed: Record<string, string> = { reviewer: "runnerBot.reviewer" } as const;
45
+ static called = { reviewer: "runnerBot.reviewer", fixer: keyOf("fixer") } as const;
46
+ static computed = { reviewer: "runnerBot.reviewer", [fixer]: "runnerBot.fixer" } as const;
47
+ static spread = [...RunnerBotRole.values, "runnerBot.fixer"] as const;
48
+ static nested = { reviewer: { label: "runnerBot.reviewer" } } as const;
49
+ static get made() { return { reviewer: "runnerBot.reviewer" } as const; }
50
+ held = { reviewer: "runnerBot.reviewer" } as const;
51
+ }
52
+ `,
53
+ );
38
54
  return constants;
39
55
  };
40
56
 
@@ -153,6 +169,55 @@ describe("DictionaryRoutes", () => {
153
169
  });
154
170
  });
155
171
 
172
+ test("a constant class's static table gives its written keys only when every entry is one", () => {
173
+ const constants = constantsOf();
174
+ expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toEqual(["runnerBot.reviewer", "task.fixer"]);
175
+ expect(constants.staticKeysOf("RunnerBot", "stageKeys")).toEqual(["project.stage.open", "project.stage.done"]);
176
+ for (const member of ["loose", "typed", "called", "computed", "spread", "nested", "made", "held", "missing"])
177
+ expect(constants.staticKeysOf("RunnerBot", member), member).toBeNull();
178
+ expect(constants.staticKeysOf("Missing", "labelKeyOf")).toBeNull();
179
+
180
+ constants.add(
181
+ "libs/shared/lib/runnerBot/runnerBot.constant.ts",
182
+ `export class RunnerBot {
183
+ static readonly labelKeyOf = { planner: "runnerBot.planner", fixer: "task.fixer" } as const;
184
+ static stageKeys = load();
185
+ }
186
+ `,
187
+ );
188
+ expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toEqual([
189
+ "runnerBot.reviewer",
190
+ "task.fixer",
191
+ "runnerBot.planner",
192
+ ]);
193
+ expect(constants.staticKeysOf("RunnerBot", "stageKeys")).toBeNull();
194
+
195
+ constants.add("libs/util/lib/runnerBot/runnerBot.constant.ts", `export class RunnerBot extends BaseBot {}`);
196
+ expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toBeNull();
197
+ });
198
+
199
+ test("a route picking a key from a constant class's static table shows the groups its keys name", async () => {
200
+ const page = (table: string) =>
201
+ [
202
+ `import { cnst } from "@apps/demo/client";`,
203
+ `export const Page = ({ role }: { role: string }) => <>{l(cnst.RunnerBot.${table}[role])}</>;`,
204
+ ].join("\n");
205
+ const { root, abs } = await workspace({
206
+ "apps/demo/page/Bots.tsx": page("labelKeyOf"),
207
+ "apps/demo/page/Loose.tsx": page("loose"),
208
+ });
209
+ const routes = reader(root, {});
210
+
211
+ const read = routes.read({ entries: [abs("apps/demo/page/Bots.tsx")] });
212
+ expect(read.whole).toBeNull();
213
+ expect(read.groups).toEqual(["base", "runnerBot", "task"]);
214
+ expect(routes.read({ entries: [abs("apps/demo/page/Loose.tsx")] }).whole).toEqual({
215
+ file: "apps/demo/page/Loose.tsx",
216
+ line: 2,
217
+ why: "cnst.RunnerBot.loose[role] is read from data at run time",
218
+ });
219
+ });
220
+
156
221
  test("a route naming an API description key says so, for the API description file", async () => {
157
222
  const { root, abs } = await workspace({
158
223
  "apps/demo/page/Api.tsx": `export const Page = () => <>{l("memo.signal.getMemo.desc")}</>;`,
@@ -214,7 +214,9 @@ export class DictionaryRoutes {
214
214
  }
215
215
  const known = this.#reads.get(file);
216
216
  if (known?.source === source) return known;
217
- const next = { source, read: DictionaryKeys.read(source, fileName) };
217
+ const { constants } = this.#options;
218
+ const staticKeys = (className: string, member: string) => constants.staticKeysOf(className, member);
219
+ const next = { source, read: DictionaryKeys.read(source, fileName, staticKeys) };
218
220
  this.#reads.set(file, next);
219
221
  return next;
220
222
  }
@@ -39,4 +39,26 @@ describe("precompressArtifacts", () => {
39
39
  expect(await readFile(`${chunkPath}.br`)).toEqual(brotliAt(await readFile(chunkPath), 9));
40
40
  expect(await Bun.file(`${dictPath}.gz`).exists()).toBe(true);
41
41
  });
42
+
43
+ test("compresses a chunk under 1 KB too, and writes no sidecar that would be larger than its file", async () => {
44
+ const distPath = await tempRoot();
45
+ const artifactDir = path.join(distPath, ".akan/artifact");
46
+ const stubPath = path.join(artifactDir, "client/stub.js");
47
+ const tinyPath = path.join(artifactDir, "client/tiny.js");
48
+ await mkdir(path.dirname(stubPath), { recursive: true });
49
+ await writeFile(
50
+ stubPath,
51
+ 'import{a as memoStore,b as memoList}from"./chunks/abc.js";export{memoStore,memoList};\n'.repeat(4),
52
+ );
53
+ await writeFile(tinyPath, "x");
54
+ const app = { dist: { cwdPath: distPath }, verbose: () => undefined } as unknown as App;
55
+
56
+ expect((await precompressArtifacts(app)).files).toBe(1);
57
+ const stubBytes = await readFile(stubPath);
58
+ expect(stubBytes.byteLength).toBeLessThan(1024);
59
+ expect(await readFile(`${stubPath}.br`)).toEqual(brotliAt(stubBytes, 9));
60
+ expect((await readFile(`${stubPath}.gz`)).byteLength).toBeLessThan(stubBytes.byteLength);
61
+ expect(await Bun.file(`${tinyPath}.br`).exists()).toBe(false);
62
+ expect(await Bun.file(`${tinyPath}.gz`).exists()).toBe(false);
63
+ });
42
64
  });
@@ -5,7 +5,6 @@ import type { App } from "../commandDecorators";
5
5
  import { FontPruner } from "./fontPruner";
6
6
 
7
7
  const COMPRESSIBLE_EXTS = new Set([".css", ".html", ".js", ".json", ".svg"]);
8
- const MIN_COMPRESS_BYTES = 1024;
9
8
  // Brotli 11 is ~100x slower than gzip: worth it for the one CSS asset per basePath and one dictionary per locale, not
10
9
  // for hundreds of JS chunks.
11
10
  const MAX_BROTLI_QUALITY = 11;
@@ -59,11 +58,17 @@ async function precompressRoot(
59
58
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
60
59
  const gz = Bun.gzipSync(buffer, { level: GZIP_LEVEL });
61
60
  const br = brotliCompress(buffer, brotliQuality ?? brotliQualityOf(path.extname(filePath).toLowerCase()));
62
- await Promise.all([Bun.write(`${filePath}.gz`, gz), Bun.write(`${filePath}.br`, br)]);
61
+ //? No 1 KB floor, unlike a response compressed as it is sent: serving a sidecar costs nothing per request.
62
+ const smaller = [
63
+ { ext: ".gz", encoded: gz },
64
+ { ext: ".br", encoded: br },
65
+ ].filter(({ encoded }) => encoded.byteLength < bytes.byteLength);
66
+ if (smaller.length === 0) continue;
67
+ await Promise.all(smaller.map(({ ext, encoded }) => Bun.write(`${filePath}${ext}`, encoded)));
63
68
  result.files += 1;
64
69
  result.inputBytes += bytes.byteLength;
65
- result.outputBytes += gz.byteLength;
66
- result.brotliBytes += br.byteLength;
70
+ result.outputBytes += Math.min(gz.byteLength, bytes.byteLength);
71
+ result.brotliBytes += Math.min(br.byteLength, bytes.byteLength);
67
72
  }
68
73
  }
69
74
 
@@ -73,20 +78,24 @@ export async function servedBrotliBytesOf(artifactDir: string, filePath: string)
73
78
  const bytes = await Bun.file(filePath).bytes();
74
79
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
75
80
  const quality = ROOT_BROTLI_QUALITY[root] ?? brotliQualityOf(path.extname(filePath).toLowerCase());
76
- return brotliCompress(buffer, quality).byteLength;
81
+ return Math.min(bytes.byteLength, brotliCompress(buffer, quality).byteLength);
77
82
  }
78
83
 
79
84
  export function chunkBrotliBytesOf(bytes: Uint8Array): number {
80
85
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
81
- return bytes.byteLength < MIN_COMPRESS_BYTES
82
- ? bytes.byteLength
83
- : brotliCompress(buffer, brotliQualityOf(".js")).byteLength;
86
+ return Math.min(bytes.byteLength, brotliCompress(buffer, brotliQualityOf(".js")).byteLength);
84
87
  }
85
88
 
86
89
  function brotliQualityOf(ext: string): number {
87
90
  return BROTLI_QUALITY_BY_EXT[ext as keyof typeof BROTLI_QUALITY_BY_EXT] ?? DEFAULT_BROTLI_QUALITY;
88
91
  }
89
92
 
93
+ export function dictionaryBrotliBytesOf(source: string): number {
94
+ const bytes = new TextEncoder().encode(source);
95
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
96
+ return brotliCompress(buffer, ROOT_BROTLI_QUALITY.dict ?? MAX_BROTLI_QUALITY).byteLength;
97
+ }
98
+
90
99
  function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
91
100
  return zlib.brotliCompressSync(buffer, {
92
101
  params: {
@@ -99,7 +108,5 @@ function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
99
108
  async function shouldPrecompress(filePath: string): Promise<boolean> {
100
109
  if (filePath.endsWith(".gz") || filePath.endsWith(".br")) return false;
101
110
  if (!COMPRESSIBLE_EXTS.has(path.extname(filePath).toLowerCase())) return false;
102
- const file = Bun.file(filePath);
103
- if (!(await file.exists())) return false;
104
- return file.size >= MIN_COMPRESS_BYTES;
111
+ return Bun.file(filePath).exists();
105
112
  }
@@ -0,0 +1,129 @@
1
+ import path from "node:path";
2
+ import type { ExportReach, ReachedImport } from "../transforms/exportReach";
3
+ import type { DiscoverOptions, ScannedImport } from "./clientBuildTypes";
4
+
5
+ export interface RenderedFile {
6
+ isClientEntry: boolean;
7
+ imports: ScannedImport[];
8
+ /** Null for a module whose exports cannot be read. */
9
+ reach?: ExportReach | null;
10
+ }
11
+
12
+ export interface RenderedGraph {
13
+ fileOf(file: string): Promise<RenderedFile | null>;
14
+ resolve(specifier: string, fromDir: string): Promise<string | null>;
15
+ /** Bumped when a file changed: an answer computed across a bump is not kept. */
16
+ epoch(): number;
17
+ }
18
+
19
+ interface ExportAsk {
20
+ file: string;
21
+ name: string;
22
+ how: "whole" | "always" | "named" | "starred";
23
+ key: string;
24
+ }
25
+
26
+ interface AskAnswer {
27
+ isEntry: boolean;
28
+ whole: boolean;
29
+ next: ExportAsk[];
30
+ }
31
+
32
+ type ImportsAs = NonNullable<DiscoverOptions["importsAs"]>;
33
+
34
+ /**
35
+ * The client entries a route can render. A server module asked for one export gives only what that export's
36
+ * declaration reaches, and every server module the route evaluates gives what its top-level statements reach.
37
+ */
38
+ export class RenderedEntries {
39
+ #graph: RenderedGraph;
40
+ #answers = new Map<string, AskAnswer>();
41
+ //? Keyed by a walk's `importsAs`: an ask's answer under swapped imports holds only for walks swapping the same ones.
42
+ #swappedAnswers = new WeakMap<ImportsAs, Map<string, AskAnswer>>();
43
+
44
+ constructor(graph: RenderedGraph) {
45
+ this.#graph = graph;
46
+ }
47
+
48
+ forget(): void {
49
+ this.#answers.clear();
50
+ this.#swappedAnswers = new WeakMap();
51
+ }
52
+
53
+ async of(
54
+ seeds: string[],
55
+ { serverModules, within, importsAs }: { serverModules: string[]; within: string[]; importsAs?: ImportsAs },
56
+ ): Promise<string[]> {
57
+ const answers = importsAs ? this.#answersUnder(importsAs) : this.#answers;
58
+ const reachable = new Set(within);
59
+ const entries = new Set<string>();
60
+ const asked = new Set<string>();
61
+ const whole = new Set<string>();
62
+ const queue = seeds.map((seed) => RenderedEntries.#ask(path.resolve(seed), "whole"));
63
+ for (const file of serverModules) queue.push(RenderedEntries.#ask(file, "always"));
64
+ for (const ask of queue) {
65
+ if (asked.has(ask.key) || whole.has(ask.file)) continue;
66
+ asked.add(ask.key);
67
+ const answer = answers.get(ask.key) ?? (await this.#answer(ask, answers, importsAs));
68
+ if (answer.isEntry) {
69
+ if (ask.how !== "always" && reachable.has(ask.file)) entries.add(ask.file);
70
+ continue;
71
+ }
72
+ if (answer.whole) whole.add(ask.file);
73
+ for (const next of answer.next) if (!asked.has(next.key) && !whole.has(next.file)) queue.push(next);
74
+ }
75
+ return [...entries].sort();
76
+ }
77
+
78
+ #answersUnder(importsAs: ImportsAs): Map<string, AskAnswer> {
79
+ const answers = this.#swappedAnswers.get(importsAs) ?? new Map<string, AskAnswer>();
80
+ this.#swappedAnswers.set(importsAs, answers);
81
+ return answers;
82
+ }
83
+
84
+ async #answer(ask: ExportAsk, answers: Map<string, AskAnswer>, importsAs?: ImportsAs): Promise<AskAnswer> {
85
+ const epoch = this.#graph.epoch();
86
+ const answer = await this.#answerOf(ask, importsAs);
87
+ if (epoch === this.#graph.epoch()) answers.set(ask.key, answer);
88
+ return answer;
89
+ }
90
+
91
+ async #answerOf(ask: ExportAsk, importsAs?: ImportsAs): Promise<AskAnswer> {
92
+ const facts = await this.#graph.fileOf(ask.file);
93
+ if (!facts) return { isEntry: false, whole: false, next: [] };
94
+ if (facts.isClientEntry) return { isEntry: true, whole: false, next: [] };
95
+ const reached = RenderedEntries.#reachedBy(ask, facts);
96
+ const swaps = importsAs?.get(ask.file);
97
+ const next: ExportAsk[] = [];
98
+ for (const { specifier, names } of reached.imports) {
99
+ const swapped = swaps?.get(specifier);
100
+ const spec = swapped === undefined ? specifier : swapped;
101
+ if (!spec) continue;
102
+ const resolved = await this.#graph.resolve(spec, path.dirname(ask.file));
103
+ if (!resolved) continue;
104
+ const file = path.resolve(resolved);
105
+ if (names === null) next.push(RenderedEntries.#ask(file, "whole"));
106
+ else for (const name of names) next.push(RenderedEntries.#ask(file, reached.starred ? "starred" : "named", name));
107
+ }
108
+ return { isEntry: false, whole: reached.whole ?? false, next };
109
+ }
110
+
111
+ //? A name asked through `export *` that the target does not hold is another target's, so it reaches nothing here.
112
+ static #reachedBy(
113
+ { name, how }: ExportAsk,
114
+ { reach, imports }: RenderedFile,
115
+ ): { imports: ReachedImport[]; whole?: boolean; starred?: boolean } {
116
+ if (!reach) return { imports: imports.map((imported) => ({ specifier: imported.path, names: null })), whole: true };
117
+ if (how === "whole") return { imports: reach.whole(), whole: true };
118
+ if (how === "always") return { imports: reach.always() };
119
+ const reached = reach.of(name);
120
+ if (reached.known) return { imports: reached.imports };
121
+ if (reached.stars.length > 0)
122
+ return { imports: reached.stars.map((specifier) => ({ specifier, names: [name] })), starred: true };
123
+ return how === "starred" ? { imports: [] } : { imports: reach.whole(), whole: true };
124
+ }
125
+
126
+ static #ask(file: string, how: ExportAsk["how"], name = ""): ExportAsk {
127
+ return { file, name, how, key: `${file}\0${how}\0${name}` };
128
+ }
129
+ }
@@ -108,6 +108,16 @@ describe("the models a route's server modules hand to client components", () =>
108
108
  expect(read).toEqual({ referenceFiles: [], unread: null });
109
109
  });
110
110
 
111
+ test("do not count a store, whose actions name and pick models only in the browser", async () => {
112
+ const read = await readOf({
113
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
114
+ "apps/demo/lib/note/note.store.ts": `${client}export const open = (id: string) => [fetch.viewNote(id), fetch.slice.tag];\n`,
115
+ "apps/demo/lib/tag/tag.store.ts": `${client}export const any = (name: string) => (fetch as never)[name];\n`,
116
+ });
117
+
118
+ expect(read).toEqual({ referenceFiles: [referenceOf("memo")], unread: null });
119
+ });
120
+
111
121
  test("are every model once the server barrel's `fetch` is indexed, passed on or taken apart", async () => {
112
122
  const taken = 'import { fetch } from "@apps/demo/server";\n';
113
123
  const unreadOf = async (name: string, body: string) =>
@@ -18,6 +18,8 @@ const capitalize = (name: string) => name.charAt(0).toUpperCase() + name.slice(1
18
18
  const serverFetchSource =
19
19
  /^(?:@(?:apps|libs)\/[^/]+\/(?:server|lib\/(?:sig|useServer))|\.{1,2}\/(?:.+\/)?(?:server|sig|useServer))$/;
20
20
  const generatedFile = /^(?:apps|libs)\/[^/]+\/(?:(?:server|client)\.ts$|lib\/[^/]+\.ts$|lib\/__client\/)/;
21
+ //? A store's actions run in the browser, so what one names is never handed over while the server renders.
22
+ const storeFile = /\.store\.ts$/;
21
23
  const handoffName = /\b(?:init|view|edit)[A-Z]|\bget[A-Z]\w*(?:Init|View|Edit)\b|\bslice\b/;
22
24
  const handoffMember = /^(?:(?:init|view|edit)[A-Z]|get[A-Z]\w*(?:Init|View|Edit)$|slice$)/;
23
25
 
@@ -53,7 +55,7 @@ export class RouteHandoffs {
53
55
  if (known) return known;
54
56
  const read = (async (): Promise<FileRead> => {
55
57
  const fileName = this.#runtime.fileNameOf(absPath);
56
- if (!fileName || generatedFile.test(fileName)) return { models: [], unread: null };
58
+ if (!fileName || generatedFile.test(fileName) || storeFile.test(fileName)) return { models: [], unread: null };
57
59
  const text = await Bun.file(absPath).text();
58
60
  const serverFetchLine = RouteHandoffs.#serverFetchLineOf(fileName, text);
59
61
  if (serverFetchLine)
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
3
  import { tempDirs, writeText } from "../test/testHelpers";
4
+ import { chunkBrotliBytesOf } from "./precompressArtifacts";
4
5
  import { RouteRuntimePays } from "./routeRuntimePays";
5
6
 
6
7
  const makeTempRoot = tempDirs("akan-devkit-route-pays-");
@@ -132,6 +133,11 @@ describe("which entries keep the whole runtime because per module made a page no
132
133
  ["/memo", ["Memo"]],
133
134
  ]),
134
135
  );
135
- expect(Object.fromEntries(sizes)).toEqual({ "/both": 700, "/memo": 600 });
136
+ const served = (bytes: number) => chunkBrotliBytesOf(new TextEncoder().encode("x".repeat(bytes)));
137
+ expect(served(100)).toBeLessThan(100);
138
+ expect(Object.fromEntries(sizes)).toEqual({
139
+ "/both": served(100) + served(200) + served(400),
140
+ "/memo": served(200) + served(400),
141
+ });
136
142
  });
137
143
  });
@@ -20,6 +20,13 @@ export const Branch = ({ open }: { open: boolean }) => {
20
20
  };
21
21
  `;
22
22
 
23
+ const execProbe = `export const idOf = (url: string) => {
24
+ const match = /\\/(\\d+)\\/?$/.exec(url);
25
+ return match ? Number(match[1]) : 0;
26
+ };
27
+ export const idOfChained = (url: string) => Number(/\\/(\\d+)\\/?$/.exec(url)?.[1] ?? 0);
28
+ `;
29
+
23
30
  const tempDirs: string[] = [];
24
31
 
25
32
  afterAll(async () => {
@@ -37,17 +44,17 @@ const runBiome = (args: string[], cwd: string) =>
37
44
  proc.on("close", () => resolve(stdout || stderr));
38
45
  });
39
46
 
40
- const lintWorkspace = async (files: string[]) => {
47
+ const lintWorkspace = async (files: string[], probe = hookProbe, config: object = { extends: [biomeBaseConfig] }) => {
41
48
  const dir = await mkdtemp(path.join(os.tmpdir(), "biome-base-"));
42
49
  tempDirs.push(dir);
43
50
  //? The base config names its plugins as `./node_modules/@akanjs/devkit/…`, resolved from the extending config's
44
51
  //? folder. A junction needs no privilege on Windows, and the type is ignored elsewhere.
45
52
  await mkdir(path.join(dir, "node_modules", "@akanjs"), { recursive: true });
46
53
  await symlink(devkitDir, path.join(dir, "node_modules", "@akanjs", "devkit"), "junction");
47
- await writeFile(path.join(dir, "biome.json"), JSON.stringify({ extends: [biomeBaseConfig] }));
54
+ await writeFile(path.join(dir, "biome.json"), JSON.stringify(config));
48
55
  for (const file of files) {
49
56
  await mkdir(path.dirname(path.join(dir, file)), { recursive: true });
50
- await writeFile(path.join(dir, file), hookProbe);
57
+ await writeFile(path.join(dir, file), probe);
51
58
  }
52
59
  const output = await runBiome(["lint", "--reporter=json", "--max-diagnostics=none", ...files], dir);
53
60
  return parseBiomeReport(output).diagnostics ?? [];
@@ -75,4 +82,17 @@ describe("biome.base.json", () => {
75
82
  "libs/demo/ui/Probe.tsx:7 error",
76
83
  ]);
77
84
  });
85
+
86
+ test("leaves a null check on RegExp.exec alone, which Biome reads as never null", async () => {
87
+ const unnecessary = (diagnostics: Awaited<ReturnType<typeof lintWorkspace>>) =>
88
+ diagnostics.filter((diagnostic) => diagnostic.category === "lint/suspicious/noUnnecessaryConditions").length;
89
+
90
+ expect(unnecessary(await lintWorkspace(["apps/demo/common/idOf.ts"], execProbe))).toBe(0);
91
+
92
+ //? Pins the Biome 2.5.14 misreading: once this is 0, the base config can turn the rule back on.
93
+ const ruleOnly = {
94
+ linter: { rules: { recommended: false, suspicious: { noUnnecessaryConditions: "warn" } } },
95
+ };
96
+ expect(unnecessary(await lintWorkspace(["apps/demo/common/idOf.ts"], execProbe, ruleOnly))).toBe(2);
97
+ });
78
98
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.36",
3
+ "version": "3.3.0-rc.38",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.36",
53
+ "@akanjs/language": "3.3.0-rc.38",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.36",
62
+ "akanjs": "3.3.0-rc.38",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",
@@ -1,7 +1,8 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { DictionaryKeys } from "./dictionaryKeys";
2
+ import { DictionaryKeys, type DictionaryStaticKeys } from "./dictionaryKeys";
3
3
 
4
- const read = (source: string, fileName = "apps/demo/lib/memo/Memo.Unit.tsx") => DictionaryKeys.read(source, fileName);
4
+ const read = (source: string, fileName = "apps/demo/lib/memo/Memo.Unit.tsx", staticKeys?: DictionaryStaticKeys) =>
5
+ DictionaryKeys.read(source, fileName, staticKeys);
5
6
 
6
7
  describe("DictionaryKeys", () => {
7
8
  test("follows a literal key, a template whose group is written, and a key chosen from a table the file holds", () => {
@@ -153,6 +154,188 @@ describe("DictionaryKeys", () => {
153
154
  expect(understood.unread).toEqual([]);
154
155
  });
155
156
 
157
+ test("does not take a parameter or a local named l that holds a plain value for the translator", () => {
158
+ const uses = [
159
+ "return values.map((l) => l.trim());",
160
+ "return rows.map((l) => l.id);",
161
+ "return values.map((l) => format(l));",
162
+ "return rows.toSorted((l, r) => l.order - r.order);",
163
+ "return values.reduce((sum, l) => sum + count(l), 0);",
164
+ "return rows.map(([l, r]) => join(l, r));",
165
+ "const l = line.length; return pad(l);",
166
+ "const l = line + ' '; return [l, line];",
167
+ "let l = 0; l += line.length; l = l * 2; return pad(l);",
168
+ "for (const l of values) send(l); return null;",
169
+ "for (const l in rows) send(l); return null;",
170
+ "for (let l = 0; l < 3; l++) send(l); return null;",
171
+ "const pad = (l: number) => fill(l); return pad(2);",
172
+ "setRows((l) => l.filter(Boolean)); return null;",
173
+ "const l = rows.at(0); return l.id ?? l[0];",
174
+ "function width(l) { return l.length; } return width(line);",
175
+ ];
176
+ for (const use of uses) {
177
+ const keys = read(`export const A = ({ values, rows, line }) => { ${use} };`);
178
+ expect(keys.unread, use).toEqual([]);
179
+ }
180
+ });
181
+
182
+ test("reads the translator beside a name that shadows it, and each use by the binding it reaches", () => {
183
+ const keys = read(`
184
+ export const Lines = ({ lines }: { lines: string[] }) => {
185
+ const { l } = usePage();
186
+ const widths = lines.map((l) => l.length);
187
+ return <>{l("memo.title")}{lines.map((l) => <li>{l}</li>)}{widths}</>;
188
+ };
189
+ `);
190
+ expect(keys.unread).toEqual([]);
191
+ expect(keys.names).toContain("memo");
192
+ const handedOn = read(
193
+ [
194
+ `export const Lines = ({ lines }: { lines: string[] }) => {`,
195
+ ` const { l: t } = usePage();`,
196
+ ` const trimmed = lines.map((t) => t.trim());`,
197
+ ` return <>{format(t, trimmed)}</>;`,
198
+ `};`,
199
+ ].join("\n"),
200
+ );
201
+ expect(handedOn.unread).toEqual([{ line: 4, why: "t passes the translator on" }]);
202
+ });
203
+
204
+ test("still takes a parameter or a local for the translator when it may be one", () => {
205
+ const uses = [
206
+ "const labelOf = (l: Translator, name: string) => l(name);",
207
+ "const headOf = (l: Translator) => dictText(l, 'memo.title');",
208
+ "const headOf = (l) => dictText(l, 'memo.title');",
209
+ "function headOf(l) { return dictText(l, 'memo.title'); }",
210
+ "withPage((l) => l(name));",
211
+ "withPage((l) => dictText(l, 'memo.title'));",
212
+ "translators.map((l) => l(name));",
213
+ "translators.forEach((l) => l._(name));",
214
+ "translators.forEach((l) => l['rich'](name));",
215
+ "translators.forEach((l) => l.call(null, name));",
216
+ "wrappers.reduce((l, wrap) => wrap(l), translator);",
217
+ "const l = pick(); helper(l);",
218
+ "const l = page.l; helper(l);",
219
+ "let l = 0; l = pick(); helper(l);",
220
+ "let l = 0; ({ l } = page); helper(l);",
221
+ "let l = 0; [l] = translators; helper(l);",
222
+ "translators.map((l) => { l ??= pick(); return helper(l); });",
223
+ "const { l } = page; helper(l.id);",
224
+ "for (const l of translators) l(name);",
225
+ "setRows((l) => [...l, name]);",
226
+ ];
227
+ for (const use of uses) {
228
+ const keys = read(`export const A = ({ name, page, translators, wrappers }) => { ${use} return null; };`);
229
+ expect(keys.unread.length, use).toBeGreaterThan(0);
230
+ }
231
+ });
232
+
233
+ test("follows a key held in a variable that may be null, undefined or false", () => {
234
+ const note = (declared: string, shown = "noteKey ? <p>{l(noteKey)}</p> : null") =>
235
+ read(`
236
+ export const Note = ({ denied, outside, fallback }: { denied: boolean; outside: boolean; fallback: string }) => {
237
+ const { l } = usePage();
238
+ ${declared}
239
+ return ${shown};
240
+ };
241
+ `);
242
+ const held = [
243
+ `const noteKey = denied ? "weather.locationDenied" : outside ? "weather.locationOutside" : null;`,
244
+ `const noteKey = denied ? "weather.locationDenied" : undefined;`,
245
+ `const noteKey = !outside && (denied ? "weather.locationDenied" : false);`,
246
+ ];
247
+ for (const declared of held) {
248
+ const keys = note(declared);
249
+ expect(keys.unread, declared).toEqual([]);
250
+ expect(keys.names, declared).toContain("weather");
251
+ }
252
+ const unknown = [
253
+ `const noteKey = denied ? "weather.locationDenied" : outside ? fallback : null;`,
254
+ `let noteKey: string | null = null; if (denied) noteKey = "weather.locationDenied"; else if (outside) noteKey = fallback;`,
255
+ `let noteKey: string | null = "weather.locationDenied"; noteKey = fallback;`,
256
+ ];
257
+ for (const declared of unknown) expect(note(declared).unread, declared).toHaveLength(1);
258
+ });
259
+
260
+ test("follows a key read from a table the file maps into another table", () => {
261
+ const stages = (
262
+ mapped: string,
263
+ table = `{ key: "project.stage.open", icon: BiBox }, { key: "task.stage.done", icon: BiCheck }`,
264
+ ) =>
265
+ read(`
266
+ const stages = [${table}] as const;
267
+ export const Stages = ({ counts, decorate }: { counts: number[]; decorate: (stage: object) => { key: string } }) => {
268
+ const { l } = usePage();
269
+ const items = ${mapped};
270
+ return <>{items.map((item) => <Tab key={item.key} title={l(item.key)} />)}</>;
271
+ };
272
+ `);
273
+ const tables = [
274
+ "stages.map((stage) => ({ ...stage, label: l(stage.key) }))",
275
+ "stages.map((stage) => ({ ...stage, label: l._(stage.key), hint: l.trans({ en: 'a', ko: 'b' }), open: true }))",
276
+ "stages.map((stage) => { return { key: stage.key, count: 0 }; })",
277
+ "stages.filter((stage) => stage.icon).map(function (stage) { return { ...stage }; })",
278
+ "stages.map((stage) => ({ ...stage, label: l(stage.key) })).map((stage) => ({ ...stage, on: false }))",
279
+ ];
280
+ for (const mapped of tables) {
281
+ const keys = stages(mapped);
282
+ expect(keys.unread, mapped).toEqual([]);
283
+ expect(keys.names, mapped).toEqual(expect.arrayContaining(["project", "task"]));
284
+ }
285
+ const picked = read(`
286
+ const stages = [{ key: "project.stage.open" }, { key: "task.stage.done" }] as const;
287
+ export const Stages = () => { const { l } = usePage(); return stages.map((stage) => stage.key).map((key) => l(key)); };
288
+ `);
289
+ expect(picked.unread).toEqual([]);
290
+ const unknown = [
291
+ "stages.map((stage) => ({ ...stage, key: rename(stage.key) }))",
292
+ "stages.map((stage, idx) => ({ ...stage, key: counts[idx] }))",
293
+ "stages.map((stage) => { if (stage.icon) return decorate(stage); return { ...stage }; })",
294
+ "stages.map((stage) => ({ ...stage, ...decorate(stage) }))",
295
+ "stages.map(decorate)",
296
+ "counts.map(() => decorate({}))",
297
+ ];
298
+ for (const mapped of unknown) expect(stages(mapped).unread, mapped).toHaveLength(1);
299
+ const computed = [`{ key: "project.stage.open" }, { key: keyOf("done") }`, `{ key: "project.stage.open", hint }`];
300
+ for (const table of computed)
301
+ expect(stages("stages.map((stage) => ({ ...stage, label: l(stage.key) }))", table).unread, table).toHaveLength(2);
302
+ });
303
+
304
+ test("follows a key picked from a static table of a constant class, which the build reads for it", () => {
305
+ const tables: Record<string, string[]> = { "RunnerBot.labelKeyOf": ["runnerBot.reviewer", "task.fixer"] };
306
+ const staticKeys: DictionaryStaticKeys = (name, member) => tables[`${name}.${member}`] ?? null;
307
+ const sourceOf = (imports: string, shown: string) =>
308
+ `${imports}\nexport const Bot = ({ role }: { role: string }) => { const { l } = usePage(); return <>{${shown}}</>; };`;
309
+ const bot = (imports: string, shown: string) => read(sourceOf(imports, shown), undefined, staticKeys);
310
+ const fromBarrel = `import * as cnst from "../cnst";`;
311
+ const followed: [string, string][] = [
312
+ [fromBarrel, "l(cnst.RunnerBot.labelKeyOf[role])"],
313
+ [`import { cnst } from "@apps/demo/client";`, "l(cnst.RunnerBot.labelKeyOf[role])"],
314
+ [`import { cnst } from "@apps/demo/client";`, "l(cnst.shared.RunnerBot.labelKeyOf.reviewer)"],
315
+ [`import { RunnerBot as Bots } from "./runnerBot.constant";`, "l(Bots.labelKeyOf[role])"],
316
+ [fromBarrel, "Object.values(cnst.RunnerBot.labelKeyOf).map((key) => l(key))"],
317
+ ];
318
+ for (const [imports, shown] of followed) {
319
+ const keys = bot(imports, shown);
320
+ expect(keys.unread, shown).toEqual([]);
321
+ expect(keys.names, shown).toEqual(expect.arrayContaining(["runnerBot", "task"]));
322
+ }
323
+ const unread: [string, string][] = [
324
+ [fromBarrel, "l(cnst.RunnerBot.other[role])"],
325
+ [fromBarrel, "l(cnst.Other.labelKeyOf[role])"],
326
+ [fromBarrel, "l(cnst.RunnerBot[role])"],
327
+ [fromBarrel, "Object.keys(cnst.RunnerBot.labelKeyOf).map((name) => l(name))"],
328
+ [`import * as constants from "../cnst";`, "l(constants.RunnerBot.labelKeyOf[role])"],
329
+ [`const cnst = load();`, "l(cnst.RunnerBot.labelKeyOf[role])"],
330
+ [`import { RunnerBot } from "./bots";`, "l(RunnerBot.labelKeyOf[role])"],
331
+ [`const RunnerBot = load();`, "l(RunnerBot.labelKeyOf[role])"],
332
+ ];
333
+ for (const [imports, shown] of unread) expect(bot(imports, shown).unread, `${imports} ${shown}`).toHaveLength(1);
334
+ expect(read(sourceOf(fromBarrel, "l(cnst.RunnerBot.labelKeyOf[role])")).unread).toEqual([
335
+ { line: 2, why: "cnst.RunnerBot.labelKeyOf[role] is read from data at run time" },
336
+ ]);
337
+ });
338
+
156
339
  test("marks a framework surface that shows the texts of any module", () => {
157
340
  expect(read(`import { Signal } from "akanjs/ui";`).anyModule).toContain("Signal from akanjs/ui");
158
341
  expect(read(`import { Field } from "akanjs/ui/Constant";`).anyModule).toContain("Constant from akanjs/ui/Constant");