@akanjs/devkit 3.3.0-rc.37 → 3.3.0-rc.39

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 (59) hide show
  1. package/CHANGELOG.md +65 -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 +20 -8
  13. package/frontendBuild/buildRouteClient.test.ts +65 -0
  14. package/frontendBuild/clientBuildTypes.ts +11 -0
  15. package/frontendBuild/clientEntriesBundler.ts +21 -11
  16. package/frontendBuild/clientEntryDiscovery.test.ts +213 -0
  17. package/frontendBuild/clientEntryDiscovery.ts +49 -8
  18. package/frontendBuild/devBarrelImports.test.ts +54 -0
  19. package/frontendBuild/devBarrelImports.ts +1 -0
  20. package/frontendBuild/dictionaryAssetBuilder.test.ts +12 -4
  21. package/frontendBuild/dictionaryAssetBuilder.ts +20 -7
  22. package/frontendBuild/dictionaryConstants.ts +55 -1
  23. package/frontendBuild/dictionaryPacking.test.ts +58 -0
  24. package/frontendBuild/dictionaryPacking.ts +43 -0
  25. package/frontendBuild/dictionaryRoutes.test.ts +65 -0
  26. package/frontendBuild/dictionaryRoutes.ts +3 -1
  27. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  28. package/frontendBuild/precompressArtifacts.ts +18 -11
  29. package/frontendBuild/renderedEntries.ts +144 -0
  30. package/frontendBuild/routeClientBuilder.ts +65 -27
  31. package/frontendBuild/routeHandoffs.test.ts +10 -0
  32. package/frontendBuild/routeHandoffs.ts +3 -1
  33. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  34. package/frontendBuild/routeModulePreloads.ts +20 -11
  35. package/frontendBuild/routeRuntimeCheck.test.ts +23 -0
  36. package/frontendBuild/routeRuntimeCheck.ts +10 -3
  37. package/frontendBuild/routeRuntimePays.test.ts +7 -1
  38. package/lint/biomeBase.test.ts +23 -3
  39. package/package.json +3 -3
  40. package/quality/dictionaryKeys.test.ts +185 -2
  41. package/quality/dictionaryKeys.ts +82 -9
  42. package/quality/objectImportReport.ts +6 -3
  43. package/quality/translatorBindings.ts +187 -0
  44. package/transforms/barrelImportsPlugin.ts +56 -35
  45. package/transforms/exportReach.test.ts +162 -0
  46. package/transforms/exportReach.ts +308 -0
  47. package/transforms/moduleParts.test.ts +225 -0
  48. package/transforms/moduleParts.ts +418 -0
  49. package/transforms/objectMemberImports.test.ts +289 -7
  50. package/transforms/objectMemberImports.ts +92 -58
  51. package/transforms/objectMemberLookup.ts +150 -0
  52. package/transforms/objectModule.test.ts +72 -2
  53. package/transforms/objectModule.ts +31 -7
  54. package/transforms/partImports.test.ts +76 -0
  55. package/transforms/partImports.ts +110 -0
  56. package/transforms/partModules.test.ts +187 -0
  57. package/transforms/partModules.ts +90 -0
  58. package/transforms/partPurity.ts +124 -0
  59. package/workspace/scanInfo.ts +24 -0
@@ -12,7 +12,7 @@ import type { App } from "../commandDecorators";
12
12
  import { type RouteRuntimeDictionaryFallback, RouteRuntimeReport } from "../quality/routeRuntimeReport";
13
13
  import { ModelReference } from "../transforms/modelReference";
14
14
  import { RouteRuntime } from "../transforms/routeRuntime";
15
- import type { ClientEntryDiscovery } from "./clientBuildTypes";
15
+ import type { AskedExports, ClientEntryDiscovery } from "./clientBuildTypes";
16
16
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
17
17
  import { DictionaryRoutes } from "./dictionaryRoutes";
18
18
  import { type BuildRouteClientResult, RouteClientBuilder } from "./routeClientBuilder";
@@ -41,6 +41,7 @@ export class AllRoutesBuilder {
41
41
  #routeIds: string[] = [];
42
42
  #ssrEntriesByRoute = new Map<string, string[]>();
43
43
  #entriesByRoute = new Map<string, string[]>();
44
+ #askedByRoute = new Map<string, AskedExports>();
44
45
  #serverModulesByRoute = new Map<string, string[]>();
45
46
  #externalsByChunkUrl: Record<string, string[]> = {};
46
47
  #discovery: ClientEntryDiscovery | null = null;
@@ -56,9 +57,9 @@ export class AllRoutesBuilder {
56
57
  const pageEntries = await resolveSsrPageEntriesForApp(this.#app, pageKeys);
57
58
  const seedIndex = computeRouteSeedIndex(pageEntries);
58
59
  this.#app.verbose(`[build-all] discovered ${seedIndex.entries.length} routes`);
59
- const discovery = await GraphClientEntryDiscovery.create(this.#app);
60
+ const discovery = await GraphClientEntryDiscovery.create(this.#app, { byExport: this.#command === "build" });
60
61
  this.#discovery = discovery;
61
- const importsAs = await this.#ssrImportsAs(discovery, pageEntries);
62
+ const { importsAs, rendering } = await this.#ssrImportsAs(discovery, pageEntries);
62
63
  const handoffs = await this.#readHandoffs();
63
64
  const dictionary = this.#command === "build";
64
65
  const unread = new Map<string, string[]>();
@@ -69,10 +70,14 @@ export class AllRoutesBuilder {
69
70
  const seeds = Array.from(new Set([...seedIndex.globalLayoutFiles, ...entry.seeds]));
70
71
  const routeEntries = await discovery.discover(seeds);
71
72
  for (const discovered of routeEntries) allEntries.add(discovered);
72
- const ssrEntries = await discovery.discover(seeds, { importsAs });
73
- const serverModules = handoffs || dictionary ? await discovery.serverModules(seeds, { importsAs }) : [];
74
- if (dictionary) this.#serverModulesByRoute.set(entry.routeId, serverModules);
75
- const handed = await handoffs?.read(serverModules);
73
+ const serverModules = dictionary ? await discovery.serverModules(seeds, { importsAs }) : undefined;
74
+ const asked = await discovery.discoverAsked(seeds, { importsAs, serverModules });
75
+ const ssrEntries = [...asked.keys()].sort();
76
+ this.#askedByRoute.set(entry.routeId, asked);
77
+ if (serverModules) this.#serverModulesByRoute.set(entry.routeId, serverModules);
78
+ const handed = handoffs
79
+ ? await handoffs.read(await discovery.serverModules(seeds, { importsAs: rendering }))
80
+ : undefined;
76
81
  const loaded = [...new Set([...ssrEntries, ...(handed?.referenceFiles ?? [])])].sort();
77
82
  this.#ssrEntriesByRoute.set(entry.routeId, loaded);
78
83
  const besidesReferences = handed ? routeEntries.filter((file) => !ModelReference.isFile(file)) : routeEntries;
@@ -144,7 +149,12 @@ export class AllRoutesBuilder {
144
149
  if (isImplicitRootLayoutKey(key)) importsAs.set(path.resolve(moduleAbsPath), toShell);
145
150
  const system = await discovery.resolveImport(specifier, this.#app.cwdPath);
146
151
  if (system) importsAs.set(system, new Map(importsNoSsrPageRenders.map((spec) => [spec, null])));
147
- return importsAs;
152
+ //? The root layout also imports every store so the server holds them; no route's own render runs through one.
153
+ const stores = StoreBootstrap.serverSpecifiers(this.#app.name).map((spec) => [spec, null] as const);
154
+ const rendering = new Map(importsAs);
155
+ for (const { key, moduleAbsPath } of pageEntries)
156
+ if (isImplicitRootLayoutKey(key)) rendering.set(path.resolve(moduleAbsPath), new Map([...toShell, ...stores]));
157
+ return { importsAs, rendering };
148
158
  }
149
159
 
150
160
  async #readHandoffs(): Promise<RouteHandoffs | null> {
@@ -160,6 +170,7 @@ export class AllRoutesBuilder {
160
170
  const preloads = new RouteModulePreloads({
161
171
  runtimeChunks,
162
172
  entriesByRoute: this.#ssrEntriesByRoute,
173
+ askedByRoute: this.#askedByRoute,
163
174
  clientManifest: this.#merged.clientManifest,
164
175
  externalsByChunkUrl: this.#externalsByChunkUrl,
165
176
  workspaceRoot: this.#app.workspace.workspaceRoot,
@@ -202,6 +213,7 @@ export class AllRoutesBuilder {
202
213
  command: this.#command,
203
214
  entriesByRoute: this.#entriesByRoute,
204
215
  sizedEntriesByRoute: this.#ssrEntriesByRoute,
216
+ askedByRoute: this.#askedByRoute,
205
217
  }).build();
206
218
  this.#app.verbose(`[build-all] bundled ${delta.newEntries.length} entries (${Date.now() - started}ms)`);
207
219
  return delta;
@@ -744,6 +744,71 @@ export const getSerializedSignalOf = (name: string) => (name === "base" ? {} : {
744
744
  const report = await Bun.file(path.join(appDir, RouteRuntimeReport.file)).json();
745
745
  expect(report).toMatchObject({ perModule: ["/draft", "/board"], notSmaller: [], refused: ["/board"] });
746
746
  }, 30_000);
747
+
748
+ test("a production build answers each export of a client file from its own entry, so a route asking one loads no import of the other; under start the file is one entry", async () => {
749
+ const { root, appDir, app, file, warnings } = await describedFixture();
750
+ for (const name of ["a", "b"])
751
+ await write(file(`heavy-${name}`), `export const heavy = { mark: "heavy-${name}-marker" };\n`);
752
+ const pair = file("Pair");
753
+ await write(
754
+ pair,
755
+ '"use client";\nimport { heavy as a } from "./heavy-a";\nimport { heavy as b } from "./heavy-b";\nexport const A = () => a.mark;\nexport const B = () => b.mark;\n',
756
+ );
757
+ const entriesByRoute = new Map([
758
+ ["/a", [pair]],
759
+ ["/b", [pair]],
760
+ ]);
761
+ const askedByRoute = new Map([
762
+ ["/a", new Map([[pair, ["A"]]])],
763
+ ["/b", new Map([[pair, ["B"]]])],
764
+ ]);
765
+ const buildAs = async (command: "build" | "start") => {
766
+ const { manifestDelta } = await new RouteClientBuilder({
767
+ app,
768
+ seeds: [],
769
+ entries: [pair],
770
+ artifact: {} as never,
771
+ browser: "chunks",
772
+ command,
773
+ entriesByRoute,
774
+ askedByRoute,
775
+ }).build();
776
+ const artifact = path.join(
777
+ command === "build" ? path.join(root, "dist/apps/demo") : appDir,
778
+ ".akan/artifact",
779
+ );
780
+ const sized = new RouteModulePreloads({
781
+ runtimeChunks: { runtime: [], vendors: {} },
782
+ entriesByRoute,
783
+ askedByRoute,
784
+ clientManifest: manifestDelta,
785
+ externalsByChunkUrl: {},
786
+ workspaceRoot: root,
787
+ }).modulesByRoute();
788
+ const loadedBy = async (route: string) =>
789
+ (
790
+ await Promise.all(
791
+ (sized[route] ?? []).map((url) => Bun.file(path.join(artifact, url.replace(/^\/_akan\//, ""))).text()),
792
+ )
793
+ ).join("\n");
794
+ const idOf = (name: string) => manifestDelta[`apps/demo/ui/Pair.tsx#${name}`]?.id;
795
+ return { rows: Object.keys(manifestDelta).sort(), idOf, a: await loadedBy("/a"), b: await loadedBy("/b") };
796
+ };
797
+
798
+ const built = await buildAs("build");
799
+ expect(built.rows).toEqual(["apps/demo/ui/Pair.tsx#A", "apps/demo/ui/Pair.tsx#B"]);
800
+ expect(built.idOf("A")).not.toBe(built.idOf("B"));
801
+ expect(built.a).toContain("heavy-a-marker");
802
+ expect(built.a).not.toContain("heavy-b-marker");
803
+ expect(built.b).toContain("heavy-b-marker");
804
+ expect(built.b).not.toContain("heavy-a-marker");
805
+
806
+ const started = await buildAs("start");
807
+ expect(started.rows).toEqual(built.rows);
808
+ expect(started.idOf("A")).toBe(started.idOf("B"));
809
+ for (const marker of ["heavy-a-marker", "heavy-b-marker"]) expect(started.a).toContain(marker);
810
+ expect(warnings).toEqual([]);
811
+ }, 30_000);
747
812
  });
748
813
 
749
814
  test("the files a route is sized by hold the store piece of the module its client code names, and no assembled runtime", async () => {
@@ -86,6 +86,17 @@ export interface ClientBundleGraph {
86
86
  chunksByModule: Map<string, string[]>;
87
87
  /** Static imports only: a chunk loaded by `import()` runs after the chunk asking for it. */
88
88
  importsByChunk: Map<string, string[]>;
89
+ /** What the bundler placed on its own: a file taken apart by export is several, held together in the maps above. */
90
+ linked?: ClientLinkedInput[];
91
+ }
92
+
93
+ /** By client entry, the export names asked of it; null for all of them. */
94
+ export type AskedExports = ReadonlyMap<string, readonly string[] | null>;
95
+
96
+ export interface ClientLinkedInput {
97
+ module: string;
98
+ imports: ClientModuleImport[];
99
+ chunks: string[];
89
100
  }
90
101
 
91
102
  export interface ClientModuleImport {
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { SsrManifest, SsrManifestEntry } from "akanjs/server";
4
4
  import type { BunPlugin } from "bun";
5
+ import { ModuleParts } from "../transforms/moduleParts";
5
6
  import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
6
7
  import { bundleConditions, bundleDefine } from "./bundleDefine";
7
8
  import {
@@ -10,6 +11,7 @@ import {
10
11
  CLIENT_BUNDLE_NAMING,
11
12
  type ClientBundleGraph,
12
13
  type ClientBundleTarget,
14
+ type ClientLinkedInput,
13
15
  type ClientManifest,
14
16
  type ClientModuleImport,
15
17
  type MetafileInput,
@@ -118,20 +120,26 @@ export class ClientEntriesBundler {
118
120
  return abs;
119
121
  };
120
122
  const importsByModule = new Map<string, ClientModuleImport[]>();
121
- for (const [input, { imports = [] }] of Object.entries(this.#metafileInputs))
122
- importsByModule.set(
123
- absOf(input),
124
- imports
125
- .filter((imported) => !imported.external)
126
- .map((imported) => ({ path: absOf(imported.path), lazy: imported.kind === "dynamic-import" })),
127
- );
123
+ const linkedByInput = new Map<string, ClientLinkedInput>();
124
+ for (const [input, { imports = [] }] of Object.entries(this.#metafileInputs)) {
125
+ const module = absOf(input);
126
+ const own = imports
127
+ .filter((imported) => !imported.external)
128
+ .map((imported) => ({ path: absOf(imported.path), lazy: imported.kind === "dynamic-import" }))
129
+ .filter((imported) => imported.path !== module);
130
+ linkedByInput.set(input, { module, imports: own, chunks: [] });
131
+ const held = importsByModule.getOrInsert(module, []);
132
+ for (const imported of own)
133
+ if (!held.some((known) => known.path === imported.path && known.lazy === imported.lazy)) held.push(imported);
134
+ }
128
135
  const chunksByModule = new Map<string, string[]>();
129
136
  const importsByChunk = new Map<string, string[]>();
130
137
  for (const [chunk, info] of this.#metafileOutputsByAbs) {
131
138
  if (!chunk.endsWith(".js")) continue;
132
139
  for (const input of Object.keys(info.inputs ?? {})) {
133
- const module = absOf(input);
134
- chunksByModule.set(module, [...(chunksByModule.get(module) ?? []), chunk]);
140
+ const chunks = chunksByModule.getOrInsert(absOf(input), []);
141
+ if (!chunks.includes(chunk)) chunks.push(chunk);
142
+ linkedByInput.get(input)?.chunks.push(chunk);
135
143
  }
136
144
  importsByChunk.set(
137
145
  chunk,
@@ -140,7 +148,7 @@ export class ClientEntriesBundler {
140
148
  .map((imported) => this.#absFromOutdir(imported.path)),
141
149
  );
142
150
  }
143
- return { importsByModule, chunksByModule, importsByChunk };
151
+ return { importsByModule, chunksByModule, importsByChunk, linked: [...linkedByInput.values()] };
144
152
  }
145
153
 
146
154
  async #createOpaqueEntryAliases(): Promise<OpaqueEntryAliases> {
@@ -271,7 +279,9 @@ export class ClientEntriesBundler {
271
279
  return path.isAbsolute(p) ? p : path.resolve(this.#outdir, p);
272
280
  }
273
281
 
274
- #absFromEntryPoint(p: string): string {
282
+ //? A file taken apart by export is linked as several inputs, each named by the file's path and its part.
283
+ #absFromEntryPoint(input: string): string {
284
+ const p = input.replace(ModuleParts.specifier, "");
275
285
  if (path.isAbsolute(p)) return path.resolve(p);
276
286
  const candidates = [path.resolve(process.cwd(), p), path.resolve(this.#app.cwdPath, p)];
277
287
  return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
@@ -283,4 +283,217 @@ describe("GraphClientEntryDiscovery", () => {
283
283
  route.invalidate([file("lib/memo/index.ts")]);
284
284
  expect(await route.discover([file("S.tsx")])).toEqual([file("lib/memo/Memo.Panel.tsx")]);
285
285
  });
286
+
287
+ describe("read by export", () => {
288
+ const byExport = () =>
289
+ new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never, { byExport: true });
290
+ const client = (name: string) => `"use client";\nexport const ${name} = () => null;\n`;
291
+ const writeView = async (file: (name: string) => string) => {
292
+ for (const name of ["Remove", "Chart", "Editor", "Panel", "Badge"])
293
+ await Bun.write(file(`ui/${name}.tsx`), client(name));
294
+ await Bun.write(
295
+ file("Memo.View.tsx"),
296
+ [
297
+ 'import { Badge } from "./ui/Badge";',
298
+ 'import { Chart } from "./ui/Chart";',
299
+ 'import { Remove } from "./ui/Remove";',
300
+ "const Title = () => <Badge />;",
301
+ "export const General = () => [<Title />, <Remove />];",
302
+ "export const Stats = () => <Chart />;",
303
+ 'export const Rich = async () => (await import("./ui/Editor")).Editor;',
304
+ "",
305
+ ].join("\n"),
306
+ );
307
+ };
308
+
309
+ test("a route reaches the client files of the export its page names, not of the whole server file", async () => {
310
+ const file = await tempDir();
311
+ await writeView(file);
312
+ await Bun.write(file("general.tsx"), 'import { General } from "./Memo.View";\nexport default General;\n');
313
+ await Bun.write(file("stats.tsx"), 'import { Stats as S } from "./Memo.View";\nexport default () => <S />;\n');
314
+ await Bun.write(file("rich.tsx"), 'import * as View from "./Memo.View";\nexport default View.Rich;\n');
315
+ await Bun.write(file("all.tsx"), 'import * as View from "./Memo.View";\nexport default () => View;\n');
316
+ const discovery = byExport();
317
+ const whole = ["Badge", "Chart", "Editor", "Remove"].map((name) => file(`ui/${name}.tsx`));
318
+
319
+ expect(await discovery.discover([file("general.tsx")])).toEqual(whole);
320
+ expect(await discovery.discoverRendered([file("general.tsx")])).toEqual([
321
+ file("ui/Badge.tsx"),
322
+ file("ui/Remove.tsx"),
323
+ ]);
324
+ expect(await discovery.discoverRendered([file("stats.tsx")])).toEqual([file("ui/Chart.tsx")]);
325
+ expect(await discovery.discoverRendered([file("rich.tsx")])).toEqual([file("ui/Editor.tsx")]);
326
+ expect(await discovery.discoverRendered([file("all.tsx")])).toEqual(whole);
327
+ });
328
+
329
+ test("each entry comes with the exports the route's server files ask of it, and with none named when one asks for the file", async () => {
330
+ const file = await tempDir();
331
+ const pair = file("ui/Pair.tsx");
332
+ await Bun.write(pair, `${client("A")}export const B = () => null;\nexport const C = () => null;\n`);
333
+ await Bun.write(file("a.tsx"), 'import { A } from "./ui/Pair";\nexport default () => <A />;\n');
334
+ await Bun.write(
335
+ file("ab.tsx"),
336
+ 'import { A } from "./ui/Pair";\nimport { B as Bee } from "./ui/Pair";\nexport default () => [A, Bee];\n',
337
+ );
338
+ await Bun.write(file("all.tsx"), 'import * as Pair from "./ui/Pair";\nexport default () => Pair;\n');
339
+ const discovery = byExport();
340
+
341
+ expect(await discovery.discoverAsked([file("a.tsx")])).toEqual(new Map([[pair, ["A"]]]));
342
+ expect(await discovery.discoverAsked([file("ab.tsx")])).toEqual(new Map([[pair, ["A", "B"]]]));
343
+ expect(await discovery.discoverAsked([file("all.tsx")])).toEqual(new Map([[pair, null]]));
344
+ expect(await discovery.discoverAsked([file("a.tsx"), file("all.tsx")])).toEqual(new Map([[pair, null]]));
345
+ const whole = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
346
+ expect(await whole.discoverAsked([file("a.tsx")])).toEqual(new Map([[pair, null]]));
347
+ });
348
+
349
+ test("a second route asking the same export gets the same answer, and a saved file is read again", async () => {
350
+ const file = await tempDir();
351
+ await writeView(file);
352
+ await Bun.write(file("stats.tsx"), 'import { Stats } from "./Memo.View";\nexport default Stats;\n');
353
+ await Bun.write(file("board.tsx"), 'import { Stats } from "./Memo.View";\nexport default () => <Stats />;\n');
354
+ const discovery = byExport();
355
+
356
+ expect(await discovery.discoverRendered([file("stats.tsx")])).toEqual([file("ui/Chart.tsx")]);
357
+ expect(await discovery.discoverRendered([file("board.tsx")])).toEqual([file("ui/Chart.tsx")]);
358
+
359
+ await Bun.write(
360
+ file("Memo.View.tsx"),
361
+ 'import { Panel } from "./ui/Panel";\nexport const Stats = () => <Panel />;\n',
362
+ );
363
+ discovery.invalidate([file("Memo.View.tsx")]);
364
+ expect(await discovery.discoverRendered([file("board.tsx")])).toEqual([file("ui/Panel.tsx")]);
365
+ });
366
+
367
+ test("without the setting, a route reaches what the whole server file imports", async () => {
368
+ const file = await tempDir();
369
+ await writeView(file);
370
+ await Bun.write(file("stats.tsx"), 'import { Stats } from "./Memo.View";\nexport default Stats;\n');
371
+ const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
372
+
373
+ expect(await discovery.discoverRendered([file("stats.tsx")])).toEqual(
374
+ ["Badge", "Chart", "Editor", "Remove"].map((name) => file(`ui/${name}.tsx`)),
375
+ );
376
+ });
377
+
378
+ test("a client file registered by a top-level statement is reached by every route evaluating the module", async () => {
379
+ const file = await tempDir();
380
+ await writeView(file);
381
+ await Bun.write(file("registry.ts"), "export const parts: unknown[] = [];\n");
382
+ await Bun.write(
383
+ file("Memo.Zone.tsx"),
384
+ [
385
+ 'import { parts } from "./registry";',
386
+ 'import { Chart } from "./ui/Chart";',
387
+ 'import { Panel } from "./ui/Panel";',
388
+ "parts.push(Panel);",
389
+ "export const Stats = () => <Chart />;",
390
+ "export const Plain = () => null;",
391
+ "",
392
+ ].join("\n"),
393
+ );
394
+ await Bun.write(file("plain.tsx"), 'import { Plain } from "./Memo.Zone";\nexport default Plain;\n');
395
+
396
+ expect(await byExport().discoverRendered([file("plain.tsx")])).toEqual([file("ui/Panel.tsx")]);
397
+ });
398
+
399
+ test("a name asked through `export *` is followed into the file that holds it, and an unknown name takes the whole file", async () => {
400
+ const file = await tempDir();
401
+ await writeView(file);
402
+ await Bun.write(file("index.ts"), 'export * from "./Memo.View";\nexport * from "./other";\n');
403
+ await Bun.write(file("other.tsx"), 'import { Panel } from "./ui/Panel";\nexport const Side = () => <Panel />;\n');
404
+ await Bun.write(
405
+ file("legacy.js"),
406
+ 'const { Panel } = require("./ui/Panel");\nmodule.exports = { Old: Panel };\n',
407
+ );
408
+ await Bun.write(file("stats.tsx"), 'import { Stats } from "./index";\nexport default Stats;\n');
409
+ await Bun.write(file("old.tsx"), 'import { Old } from "./legacy";\nexport default Old;\n');
410
+ const discovery = byExport();
411
+
412
+ expect(await discovery.discoverRendered([file("stats.tsx")])).toEqual([file("ui/Chart.tsx")]);
413
+ expect(await discovery.discoverRendered([file("old.tsx")])).toEqual([file("ui/Panel.tsx")]);
414
+ });
415
+
416
+ test("an import swapped or dropped for the walk is swapped or dropped by export too", async () => {
417
+ const file = await tempDir();
418
+ await writeView(file);
419
+ await Bun.write(
420
+ file("Shell.tsx"),
421
+ 'import { Panel } from "./ui/Panel";\nexport const General = () => <Panel />;\n',
422
+ );
423
+ await Bun.write(
424
+ file("page.tsx"),
425
+ 'import { General } from "./Memo.View";\nimport { Chart } from "./ui/Chart";\nexport default () => [<General />, <Chart />];\n',
426
+ );
427
+ const discovery = byExport();
428
+ const importsAs = new Map([
429
+ [
430
+ file("page.tsx"),
431
+ new Map<string, string | null>([
432
+ ["./Memo.View", "./Shell"],
433
+ ["./ui/Chart", null],
434
+ ]),
435
+ ],
436
+ ]);
437
+
438
+ expect(await discovery.discoverRendered([file("page.tsx")], { importsAs })).toEqual([file("ui/Panel.tsx")]);
439
+ expect(await discovery.discoverRendered([file("page.tsx")])).toEqual(
440
+ ["Badge", "Chart", "Remove"].map((name) => file(`ui/${name}.tsx`)),
441
+ );
442
+ });
443
+ });
444
+
445
+ test("a page naming a part of the object a wrapper copies in reaches that part's file and none of the wrapper's own, until the copied object or its barrel moves it", async () => {
446
+ const dir = await realpath(await mkdtemp(path.join(os.tmpdir(), "akan-discovery-")));
447
+ dirs.push(dir);
448
+ const file = (name: string) => path.join(dir, name);
449
+ const client = (name: string) => `"use client";\nexport const ${name} = () => null;\n`;
450
+ const fieldIndex = (text: string) =>
451
+ `import { Text } from "./${text}";\nexport const Field = Object.assign(() => null, { Text });\n`;
452
+ const wrapper = [
453
+ 'import { memo } from "react";',
454
+ 'import { Field as BaseField } from "@demo/ui";',
455
+ 'import { Editor } from "./Editor";',
456
+ "const Rich = memo(() => <Editor />);",
457
+ "export const Field = Object.assign(() => null, BaseField, { Rich });",
458
+ ].join("\n");
459
+ const pageOf = (wrap: string, member: string) =>
460
+ `import { Field } from "./wrap/${wrap}";\nexport const Page = () => <Field.${member} />;\n`;
461
+ await Bun.write(file("ui/index.ts"), 'export * from "./Field";\n');
462
+ await Bun.write(file("ui/Field/index.tsx"), fieldIndex("Text"));
463
+ await Bun.write(file("ui/FieldNext/index.tsx"), fieldIndex("TextLast"));
464
+ for (const text of ["Field/Text", "Field/TextNext", "FieldNext/TextLast"])
465
+ await Bun.write(file(`ui/${text}.tsx`), client("Text"));
466
+ await Bun.write(file("wrap/Field.tsx"), wrapper);
467
+ await Bun.write(file("wrap/ClientField.tsx"), `"use client";\n${wrapper}`);
468
+ await Bun.write(file("wrap/Editor.tsx"), client("Editor"));
469
+ await Bun.write(file("Text.tsx"), pageOf("Field", "Text"));
470
+ await Bun.write(file("Rich.tsx"), pageOf("Field", "Rich"));
471
+ await Bun.write(file("ClientText.tsx"), pageOf("ClientField", "Text"));
472
+ await Bun.write(file("ClientRich.tsx"), pageOf("ClientField", "Rich"));
473
+ const entries: Record<string, string> = {
474
+ "@demo/ui": "ui/index.ts",
475
+ "@demo/ui/Field": "ui/Field/index.tsx",
476
+ "@demo/ui/FieldNext": "ui/FieldNext/index.tsx",
477
+ };
478
+ const resolvePackage = async (pkgName: string) => {
479
+ const entry = entries[pkgName];
480
+ return entry ? { pkgName, entryFile: file(entry), pkgDir: file("ui") } : null;
481
+ };
482
+ const route = new GraphClientEntryDiscovery({ barrelImports: ["@demo/ui"] }, resolvePackage as never, {
483
+ packageRoot: dir,
484
+ });
485
+
486
+ expect(await route.discover([file("Text.tsx")])).toEqual([file("ui/Field/Text.tsx")]);
487
+ expect(await route.discover([file("Rich.tsx")])).toEqual([file("ui/Field/Text.tsx"), file("wrap/Editor.tsx")]);
488
+ expect(await route.discover([file("ClientText.tsx")])).toEqual([file("ui/Field/Text.tsx")]);
489
+ expect(await route.discover([file("ClientRich.tsx")])).toEqual([file("wrap/ClientField.tsx")]);
490
+
491
+ await Bun.write(file("ui/Field/index.tsx"), fieldIndex("TextNext"));
492
+ route.invalidate([file("ui/Field/index.tsx")]);
493
+ expect(await route.discover([file("Text.tsx")])).toEqual([file("ui/Field/TextNext.tsx")]);
494
+
495
+ await Bun.write(file("ui/index.ts"), 'export * from "./FieldNext";\n');
496
+ route.invalidate([file("ui/index.ts")]);
497
+ expect(await route.discover([file("Text.tsx")])).toEqual([file("ui/FieldNext/TextLast.tsx")]);
498
+ });
286
499
  });
@@ -4,8 +4,10 @@ import { SOURCE_EXTS } from "../akanApp/devHostPolicy";
4
4
  import type { App } from "../commandDecorators";
5
5
  import { BarrelAnalyzer, type BarrelExportMap } from "../transforms/barrelAnalyzer";
6
6
  import { createTsconfigPackageResolver, rewriteBarrelImports } from "../transforms/barrelImportsPlugin";
7
+ import { ExportReach } from "../transforms/exportReach";
7
8
  import { ObjectMemberImports } from "../transforms/objectMemberImports";
8
9
  import type { AkanConfig, ClientEntryDiscovery, DiscoverOptions, ScannedImport } from "./clientBuildTypes";
10
+ import { RenderedEntries, type RenderedFile } from "./renderedEntries";
9
11
 
10
12
  const USE_CLIENT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*|\/\/[^\n]*\n\s*)*["']use client["']/;
11
13
  const EXPORT_STAR_RE = /^\s*export\s*\*/m;
@@ -16,10 +18,7 @@ const AKANJS_NODE_MODULE_RE = /[\\/]node_modules[\\/]akanjs[\\/]/;
16
18
  const NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav)$/i;
17
19
  type PackageResolver = Awaited<ReturnType<typeof createTsconfigPackageResolver>>;
18
20
 
19
- interface FileFacts {
20
- isClientEntry: boolean;
21
- imports: ScannedImport[];
22
- }
21
+ type FileFacts = RenderedFile;
23
22
 
24
23
  interface Lookup<T> {
25
24
  epoch: number;
@@ -68,24 +67,37 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
68
67
  //? Bumped by every invalidation: a walk that began before one computed from facts it may have read stale, so it
69
68
  //? answers its caller but caches nothing (a registry check walks this instance beside the slow lane's route builds).
70
69
  #epoch = 0;
70
+ #rendered: RenderedEntries | null;
71
71
 
72
72
  constructor(
73
73
  akanConfig: Pick<AkanConfig, "barrelImports">,
74
74
  resolvePackage: PackageResolver,
75
- { packageRoot }: { packageRoot?: string } = {},
75
+ { packageRoot, byExport = false }: { packageRoot?: string; byExport?: boolean } = {},
76
76
  ) {
77
77
  this.#akanConfig = akanConfig;
78
78
  this.#resolvePackage = resolvePackage;
79
+ this.#rendered = byExport
80
+ ? new RenderedEntries({
81
+ fileOf: async (file) => (shouldSkipNodeModule(file) ? null : await this.#facts(file)),
82
+ resolve: async (spec, fromDir) =>
83
+ NON_SOURCE_EXT_RE.test(spec) ? null : await this.#resolveSpecifier(spec, fromDir),
84
+ epoch: () => this.#epoch,
85
+ })
86
+ : null;
79
87
  this.#analyzer = new BarrelAnalyzer({ resolvePackage, ...(packageRoot ? { packageRoot } : {}) });
80
88
  this.#objects = packageRoot
81
- ? new ObjectMemberImports({ resolve: ObjectMemberImports.resolverOf(resolvePackage) })
89
+ ? new ObjectMemberImports({
90
+ resolve: ObjectMemberImports.resolverOf(resolvePackage),
91
+ barrels: { names: akanConfig.barrelImports, analyzer: this.#analyzer },
92
+ })
82
93
  : null;
83
94
  }
84
95
 
85
96
  //? An app narrows as its bundles do, so discovery reaches the member files they load.
86
- static async create(app: App): Promise<GraphClientEntryDiscovery> {
97
+ static async create(app: App, { byExport = false } = {}): Promise<GraphClientEntryDiscovery> {
87
98
  return new GraphClientEntryDiscovery(await app.getConfig(), await createTsconfigPackageResolver(app), {
88
99
  packageRoot: app.workspace.workspaceRoot,
100
+ byExport,
89
101
  });
90
102
  }
91
103
 
@@ -101,6 +113,28 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
101
113
  return Array.from(entries).sort();
102
114
  }
103
115
 
116
+ //? Without `byExport`, and never beyond it, this is what `discover` answers.
117
+ async discoverRendered(
118
+ seeds: string[],
119
+ { importsAs, serverModules }: DiscoverOptions & { serverModules?: string[] } = {},
120
+ ): Promise<string[]> {
121
+ return [...(await this.discoverAsked(seeds, { importsAs, serverModules })).keys()].sort();
122
+ }
123
+
124
+ //? The same entries, each with the export names asked of it: null for all of them.
125
+ async discoverAsked(
126
+ seeds: string[],
127
+ { importsAs, serverModules }: DiscoverOptions & { serverModules?: string[] } = {},
128
+ ): Promise<Map<string, string[] | null>> {
129
+ const within = await this.discover(seeds, { importsAs });
130
+ if (!this.#rendered) return new Map(within.map((entry) => [entry, null]));
131
+ return await this.#rendered.asked(seeds, {
132
+ serverModules: serverModules ?? (await this.serverModules(seeds, { importsAs })),
133
+ within,
134
+ importsAs,
135
+ });
136
+ }
137
+
104
138
  async serverModules(seeds: string[], { importsAs }: DiscoverOptions = {}): Promise<string[]> {
105
139
  const seen = new Set<string>();
106
140
  const queue = seeds.map((seed) => path.resolve(seed));
@@ -147,6 +181,7 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
147
181
  // Reachable-entry results are transitive, so a changed child invalidates every ancestor.
148
182
  this.#reachableEntriesCache.clear();
149
183
  this.#swappedEntriesCaches = new WeakMap();
184
+ this.#rendered?.forget();
150
185
  for (const [barrel, before] of this.#analyzer.forget(files))
151
186
  if (!this.#reread.has(barrel)) this.#reread.set(barrel, before);
152
187
  this.#forgetObjects(files);
@@ -221,7 +256,11 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
221
256
  if (content === null) return null;
222
257
  this.#readFiles.add(absPath);
223
258
  if (USE_CLIENT_RE.test(content)) return { isClientEntry: !this.#exportsOnlyHooks(content), imports: [] };
224
- return { isClientEntry: false, imports: this.#scanImports(await this.#rewrite(content, absPath)) };
259
+ const rewritten = await this.#rewrite(content, absPath);
260
+ const imports = this.#scanImports(rewritten);
261
+ return this.#rendered
262
+ ? { isClientEntry: false, imports, reach: ExportReach.read(rewritten, absPath) }
263
+ : { isClientEntry: false, imports };
225
264
  })();
226
265
  this.#factsCache.set(absPath, cached);
227
266
  }
@@ -255,6 +294,8 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
255
294
  const absFile = path.resolve(file);
256
295
  this.#objectReaders.set(absFile, (this.#objectReaders.get(absFile) ?? new Set()).add(absPath));
257
296
  }
297
+ for (const barrel of narrowed?.barrels ?? [])
298
+ this.#barrelImporters.set(barrel, (this.#barrelImporters.get(barrel) ?? new Set()).add(absPath));
258
299
  return narrowed?.contents ?? null;
259
300
  } catch {
260
301
  return null;
@@ -75,6 +75,60 @@ describe("DevBarrelImports", () => {
75
75
  expect(await round().fingerprint(key, ["@server", "Zone.View"])).not.toBe(hash ?? "");
76
76
  });
77
77
 
78
+ test("narrows a part of the object a wrapper copies in from a barrel, and stamps the wrapper with that object's files and the barrel's", async () => {
79
+ const root = await realpath(await makeTempRoot());
80
+ const file = (name: string) => path.join(root, name);
81
+ const fieldIndex = (text: string) =>
82
+ `import { Text } from "./${text}";\nexport const Field = Object.assign(() => null, { Text });\n`;
83
+ await write(file("ui/index.ts"), 'export * from "./Field";\n');
84
+ await write(file("ui/Field/index.tsx"), fieldIndex("Text"));
85
+ for (const text of ["Text", "TextNext"])
86
+ await write(file(`ui/Field/${text}.tsx`), '"use client";\nexport const Text = () => null;\n');
87
+ await write(
88
+ file("wrap/Field.tsx"),
89
+ [
90
+ 'import { memo } from "react";',
91
+ 'import { Field as BaseField } from "@demo/ui";',
92
+ "const Rich = memo(() => null);",
93
+ "export const Field = Object.assign(() => null, BaseField, { Rich });",
94
+ ].join("\n"),
95
+ );
96
+ const importer = file("page/_index.tsx");
97
+ const page = 'import { Field } from "../wrap/Field";\nexport const Page = () => <Field.Text />;\n';
98
+ const key = `object:${file("wrap/Field.tsx")}#Field`;
99
+ const round = () =>
100
+ new DevBarrelImports(
101
+ ["@demo/ui"],
102
+ async (pkgName) => {
103
+ const entry = { "@demo/ui": "ui/index.ts", "@demo/ui/Field": "ui/Field/index.tsx" }[pkgName];
104
+ return entry ? { pkgName, entryFile: file(entry), pkgDir: file("ui") } : null;
105
+ },
106
+ { packageRoot: root },
107
+ );
108
+ const stamp = async () => (await round().stamps([key], (id) => path.relative(root, id)))[key];
109
+
110
+ const rewrite = await round().rewrite(page, importer);
111
+ const before = await stamp();
112
+
113
+ expect(rewrite?.contents).toBe(
114
+ 'import { Text as Field$Text } from "../ui/Field/Text.tsx";\nexport const Page = () => <Field$Text />;\n',
115
+ );
116
+ expect(rewrite?.narrowed[key]?.names).toEqual(["@server", "Text"]);
117
+ expect(Object.keys(before?.read ?? {}).sort()).toEqual([
118
+ "ui",
119
+ "ui/Field",
120
+ "ui/Field/Text.tsx",
121
+ "ui/Field/index.tsx",
122
+ "ui/index.ts",
123
+ "wrap",
124
+ "wrap/Field.tsx",
125
+ ]);
126
+
127
+ await write(file("ui/Field/index.tsx"), fieldIndex("TextNext"));
128
+ expect((await stamp())?.digest).not.toBe(before?.digest ?? "");
129
+ expect(await round().fingerprint(key, ["@server", "Text"])).not.toBe(rewrite?.narrowed[key]?.hash ?? "");
130
+ });
131
+
78
132
  test("hashes a part called through the object with whether it reads `this`, so a save that makes it read one moves both", async () => {
79
133
  const root = await realpath(await makeTempRoot());
80
134
  const file = (name: string) => path.join(root, name);
@@ -51,6 +51,7 @@ export class DevBarrelImports {
51
51
  specifierOf: (file, importer) =>
52
52
  DevBarrelImports.#relativeFile(CsrDevPaths.realpath(file), path.dirname(CsrDevPaths.realpath(importer))),
53
53
  keepLines: true,
54
+ barrels: { names: this.#barrels, analyzer: this.#analyzer },
54
55
  })
55
56
  : null;
56
57
  }