@akanjs/devkit 3.3.0-rc.24 → 3.3.0-rc.26

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 (144) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/akanApp/akanApp.host.ts +11 -0
  3. package/akanConfig/akanBin.ts +4 -0
  4. package/akanConfig/akanConfig.test.ts +11 -0
  5. package/akanConfig/akanConfig.ts +39 -137
  6. package/akanConfig/akanWorkers.test.ts +39 -0
  7. package/akanConfig/akanWorkers.ts +32 -0
  8. package/akanConfig/desktopServerConfig.ts +96 -0
  9. package/akanConfig/dockerImage.ts +20 -0
  10. package/akanConfig/types.ts +1 -0
  11. package/app/appBin.test.ts +63 -0
  12. package/app/appBin.ts +50 -0
  13. package/app/applicationBuildReporter.test.ts +32 -0
  14. package/app/applicationBuildReporter.ts +4 -0
  15. package/app/applicationBuildRunner.test.ts +3 -0
  16. package/app/applicationBuildRunner.ts +40 -4
  17. package/app/dictionarySizes.ts +94 -0
  18. package/artifact/implicitRootLayout.test.ts +19 -0
  19. package/artifact/implicitRootLayout.ts +16 -2
  20. package/artifact/storeBootstrap.test.ts +28 -0
  21. package/artifact/storeBootstrap.ts +60 -8
  22. package/biome.base.json +5 -1
  23. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  24. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  25. package/codeAgent/skills/akan-err/SKILL.md +2 -6
  26. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  27. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  28. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  29. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  30. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  31. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  32. package/context/akanContext.ts +2 -0
  33. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  34. package/executors/clientRuntimeKeys.fixture.json +393 -0
  35. package/executors/clientRuntimeKeys.test.ts +1591 -0
  36. package/executors/executors.test.ts +2 -0
  37. package/executors/sysExecutor.ts +66 -3
  38. package/frontendBuild/allRoutesBuilder.ts +72 -3
  39. package/frontendBuild/autoImportSync.ts +3 -2
  40. package/frontendBuild/buildRouteClient.test.ts +513 -5
  41. package/frontendBuild/clientBuildTypes.ts +15 -0
  42. package/frontendBuild/clientEntriesBundler.ts +38 -0
  43. package/frontendBuild/clientEntryDiscovery.test.ts +60 -1
  44. package/frontendBuild/clientEntryDiscovery.ts +72 -4
  45. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  46. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  47. package/frontendBuild/csrDevPatcher.ts +33 -7
  48. package/frontendBuild/csrDevTypes.ts +9 -0
  49. package/frontendBuild/devBarrelImports.test.ts +70 -0
  50. package/frontendBuild/devBarrelImports.ts +80 -21
  51. package/frontendBuild/devRegistryBundler.ts +4 -2
  52. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  53. package/frontendBuild/devRouteRuntime.ts +167 -0
  54. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  55. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  56. package/frontendBuild/dictionaryConstants.ts +82 -0
  57. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  58. package/frontendBuild/dictionaryPacking.ts +92 -0
  59. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  60. package/frontendBuild/dictionaryRoutes.ts +225 -0
  61. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  62. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  63. package/frontendBuild/precompressArtifacts.ts +7 -0
  64. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  65. package/frontendBuild/routeClientBuilder.ts +288 -15
  66. package/frontendBuild/routeHandoffs.test.ts +119 -0
  67. package/frontendBuild/routeHandoffs.ts +94 -0
  68. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  69. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  70. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  71. package/frontendBuild/routeRuntimePays.ts +117 -0
  72. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  73. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  74. package/frontendBuild/ssrDevBundler.ts +66 -11
  75. package/frontendBuild/vendorFileImports.test.ts +254 -0
  76. package/frontendBuild/vendorFileImports.ts +163 -0
  77. package/frontendBuild/vendorNarrowing.ts +28 -0
  78. package/frontendBuild/vendorSpecifiers.ts +2 -0
  79. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  80. package/incrementalBuilder/incrementalBuilder.proc.ts +20 -1
  81. package/mobile/desktopBin.ts +2 -2
  82. package/mobile/desktopServerStage.ts +1 -0
  83. package/package.json +4 -3
  84. package/quality/dictionaryKeys.test.ts +173 -0
  85. package/quality/dictionaryKeys.ts +415 -0
  86. package/quality/objectImportReport.test.ts +36 -0
  87. package/quality/objectImportReport.ts +102 -0
  88. package/quality/qualityScanner.ts +1 -1
  89. package/quality/routeRuntimeReport.test.ts +91 -0
  90. package/quality/routeRuntimeReport.ts +121 -0
  91. package/quality/runtimeConstantFacts.ts +71 -0
  92. package/quality/runtimeConstantGraph.ts +123 -0
  93. package/quality/runtimeConstantReads.ts +116 -0
  94. package/quality/runtimeImports.test.ts +190 -0
  95. package/quality/runtimeImports.ts +233 -0
  96. package/quality/runtimeKeyNames.ts +46 -0
  97. package/quality/runtimeLexicalScope.ts +132 -0
  98. package/quality/runtimeMarkerReach.test.ts +84 -0
  99. package/quality/runtimeMarkerReach.ts +255 -0
  100. package/quality/runtimeModuleFacts.ts +290 -0
  101. package/quality/runtimeNameTable.test.ts +172 -0
  102. package/quality/runtimeNameTable.ts +477 -0
  103. package/quality/runtimeScopeReport.test.ts +123 -0
  104. package/quality/runtimeScopeReport.ts +167 -0
  105. package/quality/runtimeSliceKey.ts +269 -0
  106. package/quality/runtimeSyntax.ts +133 -0
  107. package/quality/runtimeTable.fixture.ts +189 -0
  108. package/quality/runtimeUse.test.ts +737 -0
  109. package/quality/runtimeUse.ts +696 -0
  110. package/quality/runtimeUseReadable.test.ts +393 -0
  111. package/quality/ssrScanner.test.ts +13 -0
  112. package/quality/ssrScanner.ts +1 -1
  113. package/test/testHelpers.ts +11 -0
  114. package/transforms/barrelAnalyzer.ts +17 -1
  115. package/transforms/barrelImportsPlugin.ts +81 -13
  116. package/transforms/frameworkObjects.fixture.tsx +58 -0
  117. package/transforms/frameworkObjects.test.ts +54 -0
  118. package/transforms/modelReference.test.ts +196 -0
  119. package/transforms/modelReference.ts +39 -0
  120. package/transforms/objectImportEdits.ts +150 -0
  121. package/transforms/objectMemberImports.test.ts +347 -0
  122. package/transforms/objectMemberImports.ts +537 -0
  123. package/transforms/objectModule.test.ts +237 -0
  124. package/transforms/objectModule.ts +458 -0
  125. package/transforms/objectModuleAnalyzer.ts +104 -0
  126. package/transforms/reactIconImports.test.ts +231 -0
  127. package/transforms/reactIconImports.ts +325 -0
  128. package/transforms/routeConstants.ts +122 -0
  129. package/transforms/routeRuntime.test.ts +835 -0
  130. package/transforms/routeRuntime.ts +703 -0
  131. package/transforms/routeRuntimeEdits.ts +92 -0
  132. package/transforms/routeRuntimeGraph.ts +66 -0
  133. package/transforms/routeRuntimePlan.ts +244 -0
  134. package/transforms/signalDescriptors.test.ts +280 -0
  135. package/transforms/signalDescriptors.ts +227 -0
  136. package/transforms/thisFreeExports.ts +87 -0
  137. package/transforms/transforms.test.ts +139 -0
  138. package/workflow/executor.ts +6 -2
  139. package/workflow/index.ts +1 -0
  140. package/workflow/plan.ts +36 -7
  141. package/workflow/types.ts +1 -1
  142. package/workflow/uiTarget.ts +50 -0
  143. package/workspace/scanInfo.ts +1 -1
  144. package/workspace/workspaceLayout.ts +1 -0
@@ -1,5 +1,5 @@
1
1
  import { afterAll, describe, expect, test } from "bun:test";
2
- import { mkdtemp, rm } from "node:fs/promises";
2
+ import { mkdtemp, realpath, rm } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { createTsconfigPackageResolver } from "../transforms/barrelImportsPlugin";
@@ -190,6 +190,33 @@ describe("GraphClientEntryDiscovery", () => {
190
190
  expect(await fresh.discover([file("Page.tsx")], { importsAs })).toEqual([]);
191
191
  });
192
192
 
193
+ test("the server modules of a walk are every file it reads before a client entry, with the same imports swapped or dropped", async () => {
194
+ const file = await tempDir();
195
+ await Bun.write(file("Page.tsx"), 'import "./Layout";\nimport "./Card";\n');
196
+ await Bun.write(file("Layout.tsx"), 'import "./Registry";\nimport "./Helper";\n');
197
+ await Bun.write(file("Helper.ts"), 'import "./Page";\nexport const helper = 1;\n');
198
+ await Bun.write(file("Registry.ts"), 'import "./Reference";\n');
199
+ await Bun.write(file("Reference.ts"), '"use client";\nexport const reference = "memo";\n');
200
+ await Bun.write(file("Card.tsx"), '"use client";\nimport "./Inner";\nexport const Card = () => null;\n');
201
+ await Bun.write(file("Inner.ts"), "export const inner = 1;\n");
202
+ const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
203
+ const names = (files: string[]) => files.map((each) => path.basename(each));
204
+
205
+ expect(names(await discovery.serverModules([file("Page.tsx")]))).toEqual([
206
+ "Helper.ts",
207
+ "Layout.tsx",
208
+ "Page.tsx",
209
+ "Registry.ts",
210
+ ]);
211
+ const dropped = new Map([[file("Layout.tsx"), new Map([["./Registry", null]])]]);
212
+ expect(names(await discovery.serverModules([file("Page.tsx")], { importsAs: dropped }))).toEqual([
213
+ "Helper.ts",
214
+ "Layout.tsx",
215
+ "Page.tsx",
216
+ ]);
217
+ expect(names(await discovery.serverModules([file("Card.tsx")]))).toEqual([]);
218
+ });
219
+
193
220
  test("a client file exporting only hooks is no entry of a server graph that imports it, one with a component still is", async () => {
194
221
  const file = await tempDir();
195
222
  await Bun.write(file("Layout.tsx"), 'import "./store";\nimport "./Panel";\n');
@@ -224,4 +251,36 @@ describe("GraphClientEntryDiscovery", () => {
224
251
  const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
225
252
  expect(await discovery.discover([file("S.tsx")])).toEqual([file("A.ts"), file("B.ts"), file("C.ts")]);
226
253
  });
254
+
255
+ test("a page writing out an object's part reaches only that part's file under a route runtime, until the object moves it", async () => {
256
+ const dir = await realpath(await mkdtemp(path.join(os.tmpdir(), "akan-discovery-")));
257
+ dirs.push(dir);
258
+ const file = (name: string) => path.join(dir, name);
259
+ await Bun.write(
260
+ file("lib/memo/index.ts"),
261
+ 'import * as Template from "./Memo.Template";\nimport * as Zone from "./Memo.Zone";\nexport const Memo = { Template, Zone };\n',
262
+ );
263
+ for (const part of ["Template", "Zone", "Panel"])
264
+ await Bun.write(file(`lib/memo/Memo.${part}.tsx`), '"use client";\nexport const View = () => null;\n');
265
+ await Bun.write(
266
+ file("S.tsx"),
267
+ 'import { Memo } from "./lib/memo";\nexport const Page = () => <Memo.Zone.View />;\n',
268
+ );
269
+ const discoveryOf = (options?: { packageRoot: string }) =>
270
+ new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never, options);
271
+ const route = discoveryOf({ packageRoot: dir });
272
+
273
+ expect(await discoveryOf().discover([file("S.tsx")])).toEqual([
274
+ file("lib/memo/Memo.Template.tsx"),
275
+ file("lib/memo/Memo.Zone.tsx"),
276
+ ]);
277
+ expect(await route.discover([file("S.tsx")])).toEqual([file("lib/memo/Memo.Zone.tsx")]);
278
+
279
+ await Bun.write(
280
+ file("lib/memo/index.ts"),
281
+ 'import * as Template from "./Memo.Template";\nimport * as Zone from "./Memo.Panel";\nexport const Memo = { Template, Zone };\n',
282
+ );
283
+ route.invalidate([file("lib/memo/index.ts")]);
284
+ expect(await route.discover([file("S.tsx")])).toEqual([file("lib/memo/Memo.Panel.tsx")]);
285
+ });
227
286
  });
@@ -4,6 +4,7 @@ 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 { ObjectMemberImports } from "../transforms/objectMemberImports";
7
8
  import type { AkanConfig, ClientEntryDiscovery, DiscoverOptions, ScannedImport } from "./clientBuildTypes";
8
9
 
9
10
  const USE_CLIENT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*|\/\/[^\n]*\n\s*)*["']use client["']/;
@@ -58,6 +59,8 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
58
59
  #swappedEntriesCaches = new WeakMap<object, Map<string, Set<string>>>();
59
60
  #readFiles = new Set<string>();
60
61
  #barrelImporters = new Map<string, Set<string>>();
62
+ #objects: ObjectMemberImports | null;
63
+ #objectReaders = new Map<string, Set<string>>();
61
64
  //? Barrels a save went beside, by the analysis before it: a save of any component re-reads its barrel, and only an
62
65
  //? export that moved sends that barrel's importers back to the disk.
63
66
  #reread = new Map<string, Promise<BarrelExportMap | null>>();
@@ -66,14 +69,24 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
66
69
  //? answers its caller but caches nothing (a registry check walks this instance beside the slow lane's route builds).
67
70
  #epoch = 0;
68
71
 
69
- constructor(akanConfig: Pick<AkanConfig, "barrelImports">, resolvePackage: PackageResolver) {
72
+ constructor(
73
+ akanConfig: Pick<AkanConfig, "barrelImports">,
74
+ resolvePackage: PackageResolver,
75
+ { packageRoot }: { packageRoot?: string } = {},
76
+ ) {
70
77
  this.#akanConfig = akanConfig;
71
78
  this.#resolvePackage = resolvePackage;
72
- this.#analyzer = new BarrelAnalyzer({ resolvePackage });
79
+ this.#analyzer = new BarrelAnalyzer({ resolvePackage, ...(packageRoot ? { packageRoot } : {}) });
80
+ this.#objects = packageRoot
81
+ ? new ObjectMemberImports({ resolve: ObjectMemberImports.resolverOf(resolvePackage) })
82
+ : null;
73
83
  }
74
84
 
85
+ //? An app narrows as its bundles do, so discovery reaches the member files they load.
75
86
  static async create(app: App): Promise<GraphClientEntryDiscovery> {
76
- return new GraphClientEntryDiscovery(await app.getConfig(), await createTsconfigPackageResolver(app));
87
+ return new GraphClientEntryDiscovery(await app.getConfig(), await createTsconfigPackageResolver(app), {
88
+ packageRoot: app.workspace.workspaceRoot,
89
+ });
77
90
  }
78
91
 
79
92
  async discover(seeds: string[], { importsAs }: DiscoverOptions = {}): Promise<string[]> {
@@ -88,6 +101,26 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
88
101
  return Array.from(entries).sort();
89
102
  }
90
103
 
104
+ async serverModules(seeds: string[], { importsAs }: DiscoverOptions = {}): Promise<string[]> {
105
+ const seen = new Set<string>();
106
+ const queue = seeds.map((seed) => path.resolve(seed));
107
+ for (const absPath of queue) {
108
+ if (seen.has(absPath) || shouldSkipNodeModule(absPath)) continue;
109
+ const facts = await this.#facts(absPath);
110
+ if (!facts || facts.isClientEntry) continue;
111
+ seen.add(absPath);
112
+ const swaps = importsAs?.get(absPath);
113
+ for (const imp of facts.imports) {
114
+ const swapped = swaps?.get(imp.path);
115
+ const spec = swapped === undefined ? imp.path : swapped;
116
+ if (!spec || NON_SOURCE_EXT_RE.test(spec)) continue;
117
+ const resolved = await this.#resolveSpecifier(spec, path.dirname(absPath));
118
+ if (resolved) queue.push(path.resolve(resolved));
119
+ }
120
+ }
121
+ return [...seen].sort();
122
+ }
123
+
91
124
  async resolveImport(spec: string, importerDir: string): Promise<string | null> {
92
125
  const resolved = await this.#resolveSpecifier(spec, importerDir);
93
126
  return resolved ? path.resolve(resolved) : null;
@@ -116,6 +149,7 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
116
149
  this.#swappedEntriesCaches = new WeakMap();
117
150
  for (const [barrel, before] of this.#analyzer.forget(files))
118
151
  if (!this.#reread.has(barrel)) this.#reread.set(barrel, before);
152
+ this.#forgetObjects(files);
119
153
  //? A file gone, or one never read, can leave a found resolution on its old target (`Chart.tsx` to
120
154
  //? `Chart/index.tsx`), so a move drops them all; a save of a file already read keeps them (a walk re-resolving
121
155
  //? every package cost 3x). Misses lapse with the epoch on their own (#lookup).
@@ -125,6 +159,18 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
125
159
  this.#resolvedSpecifierCache.clear();
126
160
  }
127
161
 
162
+ //? An importer's facts hold the member files its object imports narrowed to: a save of the object module or of a
163
+ //? member file can move them.
164
+ #forgetObjects(files: string[]) {
165
+ if (!this.#objects) return;
166
+ this.#objects.modules.forget(files);
167
+ for (const file of files) {
168
+ const absPath = path.resolve(file);
169
+ for (const importer of this.#objectReaders.get(absPath) ?? []) this.#factsCache.delete(importer);
170
+ this.#objectReaders.delete(absPath);
171
+ }
172
+ }
173
+
128
174
  //? An importer's facts hold the files its barrel imports narrowed to, which an export moved between them changes.
129
175
  async #dropRenarrowed(): Promise<void> {
130
176
  const reread = [...this.#reread];
@@ -183,16 +229,38 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
183
229
  }
184
230
 
185
231
  async #rewrite(content: string, absPath: string): Promise<string> {
232
+ const rewritten = await this.#rewriteBarrels(content, absPath);
233
+ return (await this.#narrowObjects(rewritten, absPath)) ?? rewritten;
234
+ }
235
+
236
+ async #rewriteBarrels(content: string, absPath: string): Promise<string> {
186
237
  if (this.#akanConfig.barrelImports.length === 0) return content;
187
238
  for (const barrel of this.#akanConfig.barrelImports.filter((barrel) => content.includes(barrel)))
188
239
  this.#barrelImporters.set(barrel, (this.#barrelImporters.get(barrel) ?? new Set()).add(absPath));
189
240
  try {
190
- return (await rewriteBarrelImports(content, this.#akanConfig.barrelImports, this.#analyzer)) ?? content;
241
+ const reexports = this.#objects !== null;
242
+ return (
243
+ (await rewriteBarrelImports(content, this.#akanConfig.barrelImports, this.#analyzer, { reexports })) ?? content
244
+ );
191
245
  } catch {
192
246
  return content;
193
247
  }
194
248
  }
195
249
 
250
+ async #narrowObjects(content: string, absPath: string): Promise<string | null> {
251
+ if (!this.#objects) return null;
252
+ try {
253
+ const narrowed = await this.#objects.rewrite(content, absPath);
254
+ for (const file of narrowed?.read ?? []) {
255
+ const absFile = path.resolve(file);
256
+ this.#objectReaders.set(absFile, (this.#objectReaders.get(absFile) ?? new Set()).add(absPath));
257
+ }
258
+ return narrowed?.contents ?? null;
259
+ } catch {
260
+ return null;
261
+ }
262
+ }
263
+
196
264
  //? A hook is never rendered, so no flight row names its file; `export *` hides names from the scan, so it stays an entry.
197
265
  #exportsOnlyHooks(content: string): boolean {
198
266
  if (EXPORT_STAR_RE.test(content)) return false;
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import type { App } from "../commandDecorators";
6
+ import { printedInOwnProcess, tempDirs } from "../test/testHelpers";
6
7
  import { CsrDevModuleCompiler } from "./csrDevModuleCompiler";
7
8
  import { CsrDevPaths } from "./csrDevPaths";
8
9
  import { CsrDevResolver } from "./csrDevResolver";
@@ -189,6 +190,28 @@ describe("CsrDevModuleCompiler", () => {
189
190
  await rm(root, { recursive: true, force: true });
190
191
  });
191
192
 
193
+ test("answers the model runtime marker with the context's source, in an installed package and in app code", async () => {
194
+ const markers = ["node_modules/akanjs/ui/modelRuntime.ts", "pkgs/akanjs/ui/modelRuntime.ts"].map(file);
195
+ for (const marker of markers) await Bun.write(marker, "export {};\n");
196
+ await Bun.write(file("apps/demo/lib/st.ts"), 'export const st = "store";\n');
197
+ const paths = new CsrDevPaths(root);
198
+ const modelRuntime = `import ${JSON.stringify(file("apps/demo/lib/st.ts"))};\n`;
199
+ const compiler = new CsrDevModuleCompiler({
200
+ app: { verbose: () => undefined, logger: { error: (message: string) => logged.push(message) } } as unknown as App,
201
+ paths,
202
+ resolver: new CsrDevResolver({ paths, context, entryFiles: [] }),
203
+ context: { ...context, modelRuntime },
204
+ outDir: file("out"),
205
+ routePrefix: "/_akan/registry/",
206
+ });
207
+
208
+ const { modules } = await compiler.compile(markers, new Set());
209
+
210
+ for (const marker of markers)
211
+ expect(modules.find((module) => module.file === marker)?.deps).toEqual([file("apps/demo/lib/st.ts")]);
212
+ expect(modules.map((module) => module.file)).toContain(file("apps/demo/lib/st.ts"));
213
+ });
214
+
192
215
  test("a pre-bundled file keeps its own __reExport and __toESM, which Bun leaves in place of its own", async () => {
193
216
  const { modules } = await compile("node_modules/prebundled/chunk.mjs");
194
217
  const [module] = modules;
@@ -388,3 +411,66 @@ describe("CsrDevModuleCompiler barrel narrowing", () => {
388
411
  ]);
389
412
  });
390
413
  });
414
+
415
+ describe("CsrDevModuleCompiler loading per module", () => {
416
+ const makeTempRoot = tempDirs("akan-csr-dev-descriptors-");
417
+
418
+ test("answers a module piece's macro with descriptors read from the signal, in a process of its own", async () => {
419
+ const root = CsrDevPaths.realpath(await makeTempRoot());
420
+ await Bun.write(
421
+ path.join(root, "apps/demo/lib/sig.ts"),
422
+ `const serialized = { draft: { endpoint: { draftOf: { type: "query", args: [], returns: { refName: "draft-descriptor-ref" } } } } };
423
+ export const fetch = { ownSerializedSignal: serialized };
424
+ export const getSerializedSignalOf = (name: string) => (name === "base" ? {} : { [name]: serialized[name as "draft"] });
425
+ `,
426
+ );
427
+ const piece = path.join(root, "apps/demo/lib/__client/draft.fetch.ts");
428
+ await Bun.write(
429
+ piece,
430
+ 'import { getSerializedSignalOf } from "../sig" with { type: "macro" };\nexport const descriptors = getSerializedSignalOf("draft");\n',
431
+ );
432
+ const dir = JSON.stringify(import.meta.dir);
433
+
434
+ const compiled = (await printedInOwnProcess(
435
+ `
436
+ const path = await import("node:path");
437
+ const { CsrDevModuleCompiler } = await import(path.join(${dir}, "csrDevModuleCompiler.ts"));
438
+ const { CsrDevPaths } = await import(path.join(${dir}, "csrDevPaths.ts"));
439
+ const { CsrDevResolver } = await import(path.join(${dir}, "csrDevResolver.ts"));
440
+ const { SignalDescriptors } = await import(path.join(${dir}, "../transforms/signalDescriptors.ts"));
441
+ const [root, piece] = ${JSON.stringify([root, piece])};
442
+ let answered = 0;
443
+ const inline = SignalDescriptors.prototype.inline;
444
+ SignalDescriptors.prototype.inline = async function (...args) {
445
+ const contents = await inline.apply(this, args);
446
+ if (contents !== null) answered += 1;
447
+ return contents;
448
+ };
449
+ const logged = [];
450
+ const context = {
451
+ ...${JSON.stringify(context)},
452
+ routeRuntime: { scopes: ["apps/demo"], redirectOf: () => null, transform: () => null },
453
+ };
454
+ const paths = new CsrDevPaths(root);
455
+ const compiler = new CsrDevModuleCompiler({
456
+ app: {
457
+ verbose: () => undefined,
458
+ logger: { error: (message) => logged.push(message), warn: (message) => logged.push(message) },
459
+ workspace: { workspaceRoot: root },
460
+ },
461
+ paths,
462
+ resolver: new CsrDevResolver({ paths, context, entryFiles: [] }),
463
+ context,
464
+ outDir: path.join(root, "out"),
465
+ routePrefix: "/_akan/registry/",
466
+ });
467
+ const { modules } = await compiler.compile([piece], new Set());
468
+ console.log(JSON.stringify({ answered, logged, factories: modules.map(({ factory }) => factory) }));
469
+ `,
470
+ root,
471
+ )) as { answered: number; logged: string[]; factories: string[] };
472
+
473
+ expect({ answered: compiled.answered, logged: compiled.logged }).toEqual({ answered: 1, logged: [] });
474
+ expect(compiled.factories.join("\n")).toContain("draft-descriptor-ref");
475
+ }, 30_000);
476
+ });
@@ -1,7 +1,10 @@
1
1
  import path from "node:path";
2
+ import { SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
2
3
  import type { BunPlugin } from "bun";
4
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
3
5
  import type { App } from "../commandDecorators";
4
6
  import { loaderFor } from "../transforms/moduleSyntax";
7
+ import { SignalDescriptors } from "../transforms/signalDescriptors";
5
8
  import { CsrDevFactoryCheck } from "./csrDevFactoryCheck";
6
9
  import { CsrDevPaths } from "./csrDevPaths";
7
10
  import { CsrDevResolver } from "./csrDevResolver";
@@ -13,6 +16,7 @@ import type {
13
16
  CsrDevSharedHelpers,
14
17
  } from "./csrDevTypes";
15
18
  import { DevBarrelImports } from "./devBarrelImports";
19
+ import { DevRouteRuntime } from "./devRouteRuntime";
16
20
  import { RouteClientBuilder } from "./routeClientBuilder";
17
21
 
18
22
  interface OutputMetafile {
@@ -52,7 +56,8 @@ export interface CsrDevCompileResult {
52
56
  //* Every module becomes its own CJS factory: one Bun.build with each import external, so a save re-runs only the
53
57
  //* modules it changed instead of reloading one scope-hoisted file.
54
58
  export class CsrDevModuleCompiler {
55
- static readonly #storeRoot = /(?:^|\/)lib\/st\.ts$/;
59
+ static readonly #storeRoot = /(?:^|\/)lib\/(?:st|__client\/(?:_st|[^/]+\.st))\.ts$/;
60
+ static readonly #storeOwners = `/.akan/generated/${SSR_DEV_DIRNAME}/${DevRouteRuntime.ownersModule}.ts`;
56
61
  static readonly #macroImport = /\b(?:with|assert)\s*\{\s*type\s*:\s*["']macro["']/;
57
62
  static readonly #factoryArgument =
58
63
  /(?<![\w$.])(?:require|module|exports|__akanImport|\$RefreshReg\$|\$RefreshSig\$)(?![\w$]|\s*:)/;
@@ -69,6 +74,7 @@ export class CsrDevModuleCompiler {
69
74
  readonly #assets = new Set<string>();
70
75
  #barrels: Promise<DevBarrelImports | null> | null = null;
71
76
  readonly #narrowed = new Map<string, Record<string, CsrDevNarrowedImport>>();
77
+ readonly #routed = new Map<string, string>();
72
78
 
73
79
  constructor({ app, paths, resolver, context, outDir, routePrefix }: CsrDevModuleCompilerOptions) {
74
80
  this.#app = app;
@@ -216,6 +222,7 @@ export class CsrDevModuleCompiler {
216
222
  }
217
223
  const sourceMap = sourceMaps.get(`${artifact.path}.map`);
218
224
  const narrowed = this.#narrowed.get(file);
225
+ const routed = this.#routed.get(file);
219
226
  modules.push({
220
227
  id,
221
228
  file,
@@ -226,6 +233,7 @@ export class CsrDevModuleCompiler {
226
233
  mtimeMs: mtimes.get(file) ?? CsrDevPaths.mtimeOf(file),
227
234
  hash: hashes.get(file) ?? "",
228
235
  ...(narrowed && Object.keys(narrowed).length > 0 ? { narrowed } : {}),
236
+ ...(routed ? { routed } : {}),
229
237
  });
230
238
  }
231
239
  return { modules, misses, tangled };
@@ -279,8 +287,18 @@ export class CsrDevModuleCompiler {
279
287
  //? rewrite leaves a free `__akanMeta` that no factory header declares. So a file importing a macro has its macros run
280
288
  //? first by a build of its own, with every other import left as written, and the module build reads that output.
281
289
  async #evaluateMacros(files: string[]): Promise<Map<string, string>> {
282
- const sources = await Promise.all(files.map(async (file) => [file, await Bun.file(file).text()] as const));
290
+ const { routeRuntime } = this.#context;
291
+ const sources = await Promise.all(
292
+ files
293
+ .filter((file) => !routeRuntime?.redirectOf(file))
294
+ .map(async (file) => [file, await Bun.file(file).text()] as const),
295
+ );
283
296
  const importers = sources.filter(([, source]) => CsrDevModuleCompiler.#macroImport.test(source));
297
+ const descriptors = routeRuntime
298
+ ? new SignalDescriptors(this.#app.workspace.workspaceRoot, routeRuntime.scopes, {
299
+ onUnread: (reason) => this.#app.logger.warn(`[csr-dev] ${reason}, so their pieces run the macro`),
300
+ }).plugin
301
+ : null;
284
302
  const outputs = await Promise.all(
285
303
  importers.map(async ([file]) => {
286
304
  const result = await Bun.build({
@@ -288,6 +306,7 @@ export class CsrDevModuleCompiler {
288
306
  target: "browser",
289
307
  format: "esm",
290
308
  plugins: [
309
+ ...(descriptors ? [descriptors] : []),
291
310
  {
292
311
  name: "akan-csr-macro-pass",
293
312
  setup: (build) =>
@@ -314,6 +333,14 @@ export class CsrDevModuleCompiler {
314
333
  name: "akan-csr-registry",
315
334
  setup: (build) => {
316
335
  build.onLoad({ filter: /\.css$/ }, () => ({ contents: "", loader: "js" }));
336
+ const { modelRuntime, routeRuntime } = this.#context;
337
+ if (modelRuntime !== undefined)
338
+ build.onLoad({ filter: StoreBootstrap.modelRuntimeFilter }, () => ({ contents: modelRuntime, loader: "ts" }));
339
+ if (routeRuntime && !vendor)
340
+ build.onLoad({ filter: /[\\/]lib[\\/](?:useClient|st)\.ts$/ }, (args) => {
341
+ const contents = routeRuntime.redirectOf(args.path);
342
+ return contents === null ? undefined : { contents, loader: "ts" };
343
+ });
317
344
  if (macroOutputs.size > 0) {
318
345
  const exact = [...macroOutputs.keys()].map((file) => file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
319
346
  build.onLoad({ filter: new RegExp(`^(?:${exact.join("|")})$`) }, (args) => {
@@ -325,9 +352,16 @@ export class CsrDevModuleCompiler {
325
352
  build.onLoad({ filter: /\.(?:tsx?|jsx?)$/ }, async (args) => {
326
353
  if (CsrDevPaths.isVendorFile(args.path)) return undefined;
327
354
  const source = await Bun.file(args.path).text();
328
- const rewrite = await (await this.#barrelImports())?.rewrite(source, args.path);
329
- if (rewrite) this.#narrowed.set(CsrDevPaths.realpath(args.path), rewrite.narrowed);
330
- const narrowed = rewrite?.contents ?? source;
355
+ const file = CsrDevPaths.realpath(args.path);
356
+ const routed = routeRuntime?.transform(source, args.path) ?? null;
357
+ if (routed) this.#routed.set(file, routed.stamp);
358
+ else this.#routed.delete(file);
359
+ const input = routed?.contents ?? source;
360
+ const rewrite = await (await this.#barrelImports())?.rewrite(input, args.path, {
361
+ perModule: routed?.perModule,
362
+ });
363
+ if (rewrite) this.#narrowed.set(file, rewrite.narrowed);
364
+ const narrowed = rewrite?.contents ?? input;
331
365
  const normalized = args.path.endsWith(".tsx")
332
366
  ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh(narrowed, { path: args.path })
333
367
  : null;
@@ -359,7 +393,7 @@ export class CsrDevModuleCompiler {
359
393
  }
360
394
 
361
395
  #barrelImports(): Promise<DevBarrelImports | null> {
362
- this.#barrels ??= DevBarrelImports.create(this.#app, this.#context.barrelImports ?? []);
396
+ this.#barrels ??= DevBarrelImports.create(this.#app, this.#context);
363
397
  return this.#barrels;
364
398
  }
365
399
 
@@ -413,8 +447,10 @@ export class CsrDevModuleCompiler {
413
447
  );
414
448
  }
415
449
  // StoreRegistry.build merges into one global store instance, so every importer already holds the updated `st`:
416
- // re-running the store root is the whole update, and bubbling past it would only reach the page modules.
417
- if (CsrDevModuleCompiler.#storeRoot.test(id)) patched += "\nmodule.hot.accept();";
450
+ // re-running the store root, or a module's store piece, is the whole update: bubbling past it would only reach the
451
+ // page modules.
452
+ if (CsrDevModuleCompiler.#storeRoot.test(id) || id.endsWith(CsrDevModuleCompiler.#storeOwners))
453
+ patched += "\nmodule.hot.accept();";
418
454
  const shared = CsrDevModuleCompiler.#shareHelpers(patched);
419
455
  //? What `import.meta` is in a browser module: a `url` and no `env`, so `import.meta.env` checks (jotai, zustand)
420
456
  //? branch as they do in the ESM bundle. On the header line, outside the preamble that modules share.
@@ -75,7 +75,7 @@ export class CsrDevPatcher {
75
75
  if (state.graph.configKey !== context.configKey)
76
76
  return this.#handBack("the dev bundle config changed", generation, context);
77
77
  const metadataFile = changedFiles.find((file) => this.#bundler.isMetadataFile(file));
78
- // `lib/useClient.ts` inlines signal and dictionary metadata through a macro at build time.
78
+ // `lib/useClient.ts` and `lib/usePage.ts` inline signal and dictionary metadata through macros at build time.
79
79
  if (metadataFile) return this.#handBack(`${path.basename(metadataFile)} changed`, generation, context);
80
80
  //? Only a registry read from disk: one held in memory saw every save since, and a metadata save was handed back.
81
81
  if (!resident && state.graph.metadata !== (await this.#bundler.metadataFingerprint()))
@@ -110,6 +110,8 @@ export class CsrDevPatcher {
110
110
  const forgotten = this.#forgetDeletedModules(state, present);
111
111
  const changed = onlyRoots ? new Set<string>() : await this.#changedModules(graph, changedFiles, present);
112
112
  const restamped = onlyRoots ? null : await this.#renarrowed(context, graph, changedFiles, changed);
113
+ const routeTable = onlyRoots ? undefined : await this.#rerouted(context, graph, changed);
114
+ for (const id of CsrDevPatcher.#extendingAppStores(context, graph, changed)) changed.add(id);
113
115
  for (const id of this.#withoutFactory(state, present)) changed.add(id);
114
116
  for (const file of entries.changed) changed.add(paths.idOf(file));
115
117
  const rootFiles = [...Object.values(entries.files), ...roots.filter((file) => fs.existsSync(file))];
@@ -124,6 +126,7 @@ export class CsrDevPatcher {
124
126
  if (changed.size === 0) {
125
127
  //? No importer moved (none compiles), so the restamped barrels already hold.
126
128
  if (restamped) graph.barrels = { ...graph.barrels, ...restamped };
129
+ if (routeTable !== undefined) graph.routeTable = routeTable;
127
130
  if (carried.length === 0) return { kind: "unchanged" };
128
131
  return await this.#retryCarried(context, state, carried, { announce, allowWholeAppBuilds });
129
132
  }
@@ -161,12 +164,7 @@ export class CsrDevPatcher {
161
164
  await writer.writeJson("graph.json", graph);
162
165
  throw error;
163
166
  }
164
- const refusal =
165
- result.refusedVendors.length > 0
166
- ? "an npm module joined the graph"
167
- : result.unresolved.length > 0
168
- ? `a new import needs the resolution build: ${result.unresolved[0]}`
169
- : null;
167
+ const refusal = CsrDevPatcher.#refusalOf(result);
170
168
  if (refusal) {
171
169
  //? The entry files are already rewritten, so the worker would see them unchanged and patch a moved route table:
172
170
  //? a graph whose entries name none makes it reload instead.
@@ -192,6 +190,7 @@ export class CsrDevPatcher {
192
190
  }
193
191
  graph.pending = graph.pending.filter((id) => !orphans.includes(id));
194
192
  this.#bundler.merge(graph, resolver, compiled, { ...restamped, ...result.barrels });
193
+ if (routeTable !== undefined) graph.routeTable = routeTable;
195
194
  if (!this.#resident) delete graph.failed;
196
195
  for (const module of compiled) this.#delegated.delete(module.id);
197
196
  graph.entries = entryIds;
@@ -261,6 +260,11 @@ export class CsrDevPatcher {
261
260
  return retried.kind === "delegate" ? retried : outcome;
262
261
  }
263
262
 
263
+ static #refusalOf(result: CsrDevCompileResult): string | null {
264
+ if (result.refusedVendors.length > 0) return "an npm module joined the graph";
265
+ return result.unresolved.length > 0 ? `a new import needs the resolution build: ${result.unresolved[0]}` : null;
266
+ }
267
+
264
268
  //? Compiled apart from the save: a new root that failed to compile, and that no module imports, must not fail every
265
269
  //? later save's round with it. Its error still reaches the overlay (this throws after the save's patch went out).
266
270
  async #retryCarried(
@@ -540,6 +544,28 @@ export class CsrDevPatcher {
540
544
  return barrels;
541
545
  }
542
546
 
547
+ //? A store, signal or constant save can move a name to another module, or make one known: a module whose own text
548
+ //? did not change may then need other pieces. Each module the route runtime rewrote is rewritten again, and compiles
549
+ //? when it comes out different. The digest is recorded like a barrel stamp, with the compile that follows.
550
+ async #rerouted(context: CsrDevContext, graph: CsrDevGraph, changed: Set<string>): Promise<string | undefined> {
551
+ const { routeRuntime } = context;
552
+ if (!routeRuntime || graph.routeTable === routeRuntime.digest) return undefined;
553
+ const { paths } = this.#bundler;
554
+ for (const [id, module] of Object.entries(graph.modules)) {
555
+ if (!module.routed || changed.has(id)) continue;
556
+ const file = paths.fileOf(id);
557
+ if (!fs.existsSync(file)) continue;
558
+ if (routeRuntime.transform(await Bun.file(file).text(), file)?.stamp !== module.routed) changed.add(id);
559
+ }
560
+ return routeRuntime.digest;
561
+ }
562
+
563
+ static #extendingAppStores(context: CsrDevContext, graph: CsrDevGraph, changed: Set<string>): string[] {
564
+ const { routeRuntime } = context;
565
+ if (!routeRuntime) return [];
566
+ return [...changed].flatMap((id) => routeRuntime.appStoresAfter(id, (module) => graph.modules[module]?.deps));
567
+ }
568
+
543
569
  static #remember(code: CsrDevCode, compiled: CsrDevCompileResult["modules"]) {
544
570
  for (const module of compiled) {
545
571
  if (module.vendor) continue;
@@ -1,4 +1,5 @@
1
1
  import type { PageEntry } from "../artifact/implicitRootLayout";
2
+ import type { DevRouteRuntime } from "./devRouteRuntime";
2
3
 
3
4
  export interface CsrDevNarrowedImport {
4
5
  names: string[];
@@ -19,6 +20,7 @@ export interface CsrDevGraphModule {
19
20
  deps: string[];
20
21
  helpers?: string;
21
22
  narrowed?: Record<string, CsrDevNarrowedImport>;
23
+ routed?: string;
22
24
  }
23
25
 
24
26
  export interface CsrDevGraph {
@@ -36,6 +38,8 @@ export interface CsrDevGraph {
36
38
  /** The stamp of the signal and dictionary sources the last whole build inlined; see `RegistryMetadataFingerprint`. */
37
39
  metadata?: string;
38
40
  barrels?: Record<string, CsrDevBarrelStamp>;
41
+ /** The `DevRouteRuntime` digest every module's `routed` stamp was taken under. */
42
+ routeTable?: string;
39
43
  }
40
44
 
41
45
  export interface CsrDevContext {
@@ -50,6 +54,10 @@ export interface CsrDevContext {
50
54
  /** Bare specifiers the page already loads (an SSR page's import map): required as `vendor:<specifier>`, not compiled. */
51
55
  externals?: readonly string[];
52
56
  barrelImports?: readonly string[];
57
+ /** What `akanjs/ui/modelRuntime` holds instead of its empty source, when the bootstrap loads only the page runtime. */
58
+ modelRuntime?: string;
59
+ /** Where pages load per module: what each client module imports, as the production build decides it. */
60
+ routeRuntime?: DevRouteRuntime;
53
61
  }
54
62
 
55
63
  export interface CsrDevSharedHelpers {
@@ -68,6 +76,7 @@ export interface CsrDevCompiledModule {
68
76
  mtimeMs: number;
69
77
  hash: string;
70
78
  narrowed?: Record<string, CsrDevNarrowedImport>;
79
+ routed?: string;
71
80
  }
72
81
 
73
82
  /** Module factories by id and helper definitions by hash, kept in memory so app.js is written without a pass over the disk. */
@@ -27,4 +27,74 @@ describe("DevBarrelImports", () => {
27
27
 
28
28
  expect(rewrite?.contents).toBe('import { Link } from "../../../store/akanjs/ui/Link/index.tsx";\n');
29
29
  });
30
+
31
+ test("narrows an object's part under a route runtime as a build does, keyed by the object and the importer's side", async () => {
32
+ const root = await realpath(await makeTempRoot());
33
+ const file = (name: string) => path.join(root, name);
34
+ const memoIndex = (zone: string) =>
35
+ `import * as Template from "./Memo.Template";\nimport * as Zone from "./${zone}";\nexport const Memo = { Template, Zone };\n`;
36
+ await write(file("lib/memo/index.ts"), memoIndex("Memo.Zone"));
37
+ for (const part of ["Template", "Zone", "Panel"])
38
+ await write(file(`lib/memo/Memo.${part}.tsx`), '"use client";\nexport const View = () => null;\n');
39
+ const importer = file("page/_index.tsx");
40
+ const page = 'import { Memo } from "../lib/memo";\nexport const Page = () => <Memo.Zone.View />;\n';
41
+ const key = `object:${file("lib/memo/index.ts")}#Memo`;
42
+ const round = () => new DevBarrelImports([], async () => null, { packageRoot: root });
43
+
44
+ const server = await round().rewrite(page, importer);
45
+ const client = await round().rewrite(`"use client";\n${page}`, importer);
46
+ const stamp = async () => (await round().stamps([key], (id) => path.relative(root, id)))[key];
47
+
48
+ expect(await new DevBarrelImports(["akanjs/ui"], async () => null).rewrite(page, importer)).toBeNull();
49
+ expect(server?.contents).toBe(
50
+ 'import { View as Memo$Zone$View } from "../lib/memo/Memo.Zone.tsx";\nexport const Page = () => <Memo$Zone$View />;\n',
51
+ );
52
+ expect(Object.keys(server?.narrowed ?? {})).toEqual([key]);
53
+ expect(server?.narrowed[key]?.names).toEqual(["@server", "Zone.View"]);
54
+ expect(client?.narrowed[key]?.names).toEqual(["@client", "Zone.View"]);
55
+ expect(Object.keys((await stamp())?.read ?? {}).sort()).toEqual([
56
+ "lib/memo",
57
+ "lib/memo/Memo.Template.tsx",
58
+ "lib/memo/Memo.Zone.tsx",
59
+ "lib/memo/index.ts",
60
+ ]);
61
+
62
+ const hash = server?.narrowed[key]?.hash;
63
+ const digest = (await stamp())?.digest;
64
+ await write(file("lib/memo/Memo.Zone.tsx"), '"use client";\nexport const View = () => "saved";\n');
65
+ expect(await round().fingerprint(key, ["@server", "Zone.View"])).toBe(hash ?? "");
66
+ expect((await stamp())?.digest).toBe(digest ?? "");
67
+
68
+ await write(
69
+ file("lib/memo/Memo.Zone.tsx"),
70
+ '"use client";\nexport const View = () => null;\nexport const Added = () => null;\n',
71
+ );
72
+ expect((await stamp())?.digest).not.toBe(digest ?? "");
73
+
74
+ await write(file("lib/memo/index.ts"), memoIndex("Memo.Panel"));
75
+ expect(await round().fingerprint(key, ["@server", "Zone.View"])).not.toBe(hash ?? "");
76
+ });
77
+
78
+ 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
+ const root = await realpath(await makeTempRoot());
80
+ const file = (name: string) => path.join(root, name);
81
+ await write(file("lib/memo/index.ts"), 'import * as Util from "./Memo.Util";\nexport const Memo = { Util };\n');
82
+ await write(file("lib/memo/Memo.Util.ts"), "export function format() {\n return 1;\n}\n");
83
+ const importer = file("page/_index.tsx");
84
+ const key = `object:${file("lib/memo/index.ts")}#Memo`;
85
+ const round = () => new DevBarrelImports([], async () => null, { packageRoot: root });
86
+ const digest = async () => (await round().stamps([key], (id) => path.relative(root, id)))[key]?.digest;
87
+
88
+ const narrowed = (
89
+ await round().rewrite('import { Memo } from "../lib/memo";\nexport const n = Memo.Util.format();\n', importer)
90
+ )?.narrowed[key];
91
+ const before = await digest();
92
+ await write(file("lib/memo/Memo.Util.ts"), "export function format() {\n return 2;\n}\n");
93
+ expect(narrowed?.names).toEqual(["@server", "Util.format()"]);
94
+ expect(await digest()).toBe(before ?? "");
95
+
96
+ await write(file("lib/memo/Memo.Util.ts"), "export function format(this: unknown) {\n return this;\n}\n");
97
+ expect(await digest()).not.toBe(before ?? "");
98
+ expect(await round().fingerprint(key, narrowed?.names ?? [])).not.toBe(narrowed?.hash ?? "");
99
+ });
30
100
  });