@akanjs/devkit 3.3.0-rc.3 → 3.3.0-rc.30

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 (229) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +126 -5
  22. package/app/dictionarySizes.ts +94 -0
  23. package/artifact/implicitRootLayout.test.ts +19 -0
  24. package/artifact/implicitRootLayout.ts +16 -2
  25. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  26. package/artifact/storeBootstrap.test.ts +28 -0
  27. package/artifact/storeBootstrap.ts +60 -8
  28. package/biome.base.json +5 -1
  29. package/codeAgent/agent/CodeAgent.ts +36 -16
  30. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  31. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  32. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  33. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  34. package/codeAgent/agent/codeAgent.test.ts +62 -0
  35. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  36. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  37. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  38. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  39. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  40. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  41. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  42. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  43. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  44. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  45. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  46. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  47. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  48. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  49. package/context/akanContext.ts +2 -0
  50. package/docs/apiReference.test.ts +9 -0
  51. package/docs/apiReference.ts +14 -0
  52. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  53. package/executors/clientRuntimeKeys.fixture.json +393 -0
  54. package/executors/clientRuntimeKeys.test.ts +1591 -0
  55. package/executors/executors.test.ts +2 -0
  56. package/executors/sysExecutor.ts +66 -3
  57. package/executors/workspaceExecutor.ts +7 -4
  58. package/frontendBuild/allRoutesBuilder.ts +72 -3
  59. package/frontendBuild/autoImportSync.ts +3 -2
  60. package/frontendBuild/buildRouteClient.test.ts +515 -12
  61. package/frontendBuild/clientBuildTypes.ts +15 -0
  62. package/frontendBuild/clientEntriesBundler.ts +38 -0
  63. package/frontendBuild/clientEntryDiscovery.test.ts +95 -1
  64. package/frontendBuild/clientEntryDiscovery.ts +88 -7
  65. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  66. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  67. package/frontendBuild/csrDevPatcher.ts +33 -7
  68. package/frontendBuild/csrDevTypes.ts +9 -0
  69. package/frontendBuild/devBarrelImports.test.ts +100 -0
  70. package/frontendBuild/devBarrelImports.ts +82 -23
  71. package/frontendBuild/devRegistryBundler.ts +4 -2
  72. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  73. package/frontendBuild/devRouteRuntime.ts +167 -0
  74. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  75. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  76. package/frontendBuild/dictionaryConstants.ts +82 -0
  77. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  78. package/frontendBuild/dictionaryPacking.ts +92 -0
  79. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  80. package/frontendBuild/dictionaryRoutes.ts +225 -0
  81. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  82. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  83. package/frontendBuild/precompressArtifacts.ts +7 -0
  84. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  85. package/frontendBuild/routeClientBuilder.ts +288 -15
  86. package/frontendBuild/routeHandoffs.test.ts +145 -0
  87. package/frontendBuild/routeHandoffs.ts +115 -0
  88. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  89. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  90. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  91. package/frontendBuild/routeRuntimePays.ts +117 -0
  92. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  93. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  94. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  95. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  96. package/frontendBuild/ssrDevBundler.ts +66 -11
  97. package/frontendBuild/vendorFileImports.test.ts +254 -0
  98. package/frontendBuild/vendorFileImports.ts +163 -0
  99. package/frontendBuild/vendorNarrowing.ts +28 -0
  100. package/frontendBuild/vendorSpecifiers.ts +2 -0
  101. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  102. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  103. package/incrementalBuilder/builderBoot.ts +5 -5
  104. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  105. package/incrementalBuilder/builderLanes.ts +2 -2
  106. package/incrementalBuilder/builderWatch.ts +8 -8
  107. package/incrementalBuilder/csrRegistry.ts +4 -4
  108. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  109. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  110. package/incrementalBuilder/ssrRegistry.ts +6 -6
  111. package/index.ts +1 -1
  112. package/integration/renderAdmissionSoak.test.ts +99 -0
  113. package/integration/renderAdmissionSoak.ts +609 -0
  114. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  115. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  116. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  117. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  118. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  119. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  120. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  121. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  122. package/lint/biomeCheck.test.ts +145 -0
  123. package/lint/biomeCheck.ts +131 -0
  124. package/lint/no-arbitrary-color.grit +5 -0
  125. package/lint/no-conditional-st-hook.grit +5 -1
  126. package/lint/no-daisyui-legacy-class.grit +8 -0
  127. package/lint/no-document-cookie.grit +3 -0
  128. package/lint/no-inline-color.grit +10 -2
  129. package/lint/no-oversized-list-limit.grit +2 -0
  130. package/lint/no-raw-palette-class.grit +7 -0
  131. package/lint/no-unpublished-form-setter.grit +2 -0
  132. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  133. package/lint/no-web-storage.grit +3 -0
  134. package/lint/withheldEnvFile.ts +17 -0
  135. package/mobile/desktopBin.ts +2 -2
  136. package/mobile/desktopServerStage.ts +1 -0
  137. package/mobile/nativeApp.test.ts +7 -5
  138. package/mobile/nativeApp.ts +2 -2
  139. package/mobile/nativeConfig.test.ts +96 -1
  140. package/mobile/nativeConfig.ts +46 -12
  141. package/mobile/serverBundleSecrets.ts +43 -0
  142. package/package.json +15 -169
  143. package/packageExports.test.ts +38 -24
  144. package/quality/dictionaryKeys.test.ts +173 -0
  145. package/quality/dictionaryKeys.ts +415 -0
  146. package/quality/objectImportReport.test.ts +36 -0
  147. package/quality/objectImportReport.ts +102 -0
  148. package/quality/qualityScanner.ts +1 -1
  149. package/quality/routeRuntimeReport.test.ts +91 -0
  150. package/quality/routeRuntimeReport.ts +121 -0
  151. package/quality/runtimeConstantFacts.ts +71 -0
  152. package/quality/runtimeConstantGraph.ts +123 -0
  153. package/quality/runtimeConstantReads.ts +116 -0
  154. package/quality/runtimeImports.test.ts +190 -0
  155. package/quality/runtimeImports.ts +233 -0
  156. package/quality/runtimeKeyNames.ts +46 -0
  157. package/quality/runtimeLexicalScope.ts +132 -0
  158. package/quality/runtimeMarkerReach.test.ts +84 -0
  159. package/quality/runtimeMarkerReach.ts +255 -0
  160. package/quality/runtimeModuleFacts.ts +290 -0
  161. package/quality/runtimeNameTable.test.ts +172 -0
  162. package/quality/runtimeNameTable.ts +477 -0
  163. package/quality/runtimeScopeReport.test.ts +123 -0
  164. package/quality/runtimeScopeReport.ts +167 -0
  165. package/quality/runtimeSliceKey.ts +269 -0
  166. package/quality/runtimeSyntax.ts +133 -0
  167. package/quality/runtimeTable.fixture.ts +189 -0
  168. package/quality/runtimeUse.test.ts +737 -0
  169. package/quality/runtimeUse.ts +696 -0
  170. package/quality/runtimeUseReadable.test.ts +393 -0
  171. package/quality/ssrScanner.test.ts +13 -0
  172. package/quality/ssrScanner.ts +1 -1
  173. package/test/secretEnvFixture.ts +134 -0
  174. package/test/testHelpers.ts +11 -0
  175. package/transforms/barrelAnalyzer.ts +26 -4
  176. package/transforms/barrelImportsPlugin.ts +82 -14
  177. package/transforms/frameworkObjects.fixture.tsx +58 -0
  178. package/transforms/frameworkObjects.test.ts +54 -0
  179. package/transforms/modelReference.test.ts +196 -0
  180. package/transforms/modelReference.ts +39 -0
  181. package/transforms/objectImportEdits.ts +150 -0
  182. package/transforms/objectMemberImports.test.ts +347 -0
  183. package/transforms/objectMemberImports.ts +537 -0
  184. package/transforms/objectModule.test.ts +237 -0
  185. package/transforms/objectModule.ts +458 -0
  186. package/transforms/objectModuleAnalyzer.ts +104 -0
  187. package/transforms/reactIconImports.test.ts +231 -0
  188. package/transforms/reactIconImports.ts +325 -0
  189. package/transforms/routeConstants.ts +122 -0
  190. package/transforms/routeRuntime.test.ts +835 -0
  191. package/transforms/routeRuntime.ts +703 -0
  192. package/transforms/routeRuntimeEdits.ts +92 -0
  193. package/transforms/routeRuntimeGraph.ts +66 -0
  194. package/transforms/routeRuntimePlan.ts +244 -0
  195. package/transforms/secretEnvDeclaration.test.ts +208 -0
  196. package/transforms/secretEnvDeclaration.ts +213 -0
  197. package/transforms/secretEnvFile.test.ts +117 -0
  198. package/transforms/secretEnvFile.ts +113 -0
  199. package/transforms/secretEnvName.test.ts +54 -0
  200. package/transforms/secretEnvName.ts +29 -0
  201. package/transforms/secretEnvSource.test.ts +148 -0
  202. package/transforms/secretEnvSource.ts +166 -0
  203. package/transforms/serverEnvEvaluationError.ts +11 -0
  204. package/transforms/serverEnvPlugin.test.ts +2 -1
  205. package/transforms/serverEnvPlugin.ts +13 -0
  206. package/transforms/serverEnvProfile.test.ts +115 -2
  207. package/transforms/serverEnvProfile.ts +117 -40
  208. package/transforms/serverEnvSecrets.test.ts +292 -0
  209. package/transforms/signalDescriptors.test.ts +280 -0
  210. package/transforms/signalDescriptors.ts +227 -0
  211. package/transforms/thisFreeExports.ts +87 -0
  212. package/transforms/transforms.test.ts +180 -3
  213. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  214. package/tunnel/createTunnel.test.ts +29 -8
  215. package/tunnel/createTunnel.ts +18 -11
  216. package/typecheck/projectTypecheck.test.ts +29 -0
  217. package/typecheck/typeChecker.test.ts +49 -0
  218. package/typecheck/typeChecker.ts +9 -7
  219. package/typecheck/withheldDiagnostics.ts +41 -0
  220. package/util/fileEditor.ts +1 -0
  221. package/util/selectModel.ts +1 -0
  222. package/workflow/executor.ts +6 -2
  223. package/workflow/index.ts +1 -0
  224. package/workflow/plan.ts +36 -7
  225. package/workflow/types.ts +1 -1
  226. package/workflow/uiTarget.ts +50 -0
  227. package/workspace/getRelatedCnsts.ts +7 -0
  228. package/workspace/scanInfo.ts +1 -1
  229. package/workspace/workspaceLayout.ts +1 -0
@@ -5,6 +5,8 @@ import { StoreBootstrap } from "../artifact/storeBootstrap";
5
5
  import type { App } from "../commandDecorators";
6
6
  import { BarrelAnalyzer, type BarrelExportMap, type PackageEntry } from "./barrelAnalyzer";
7
7
  import { loaderFor, type NamedItem } from "./moduleSyntax";
8
+ import { ObjectMemberImports } from "./objectMemberImports";
9
+ import type { RouteRuntime } from "./routeRuntime";
8
10
 
9
11
  export interface BarrelImportsPluginOptions {
10
12
  /** Absolute paths whose content is returned unchanged (e.g. node_modules). */
@@ -13,20 +15,35 @@ export interface BarrelImportsPluginOptions {
13
15
  pipeAfter?: (source: string, args: { path: string }) => string | Promise<string | null> | null;
14
16
  /** Barrels the bundle leaves external: a rewritten import would inline the modules the import map already serves. */
15
17
  external?: readonly string[];
16
- /** The barrels to rewrite, instead of the app config's `barrelImports`. */
18
+ /** The barrels to rewrite, instead of the app config's `barrelImports`: a CSR bundle's, which narrows no object or package barrel by member. */
17
19
  barrels?: readonly string[];
20
+ /** What `akanjs/ui/modelRuntime` holds instead of its empty source, in a build loading only the page runtime. */
21
+ modelRuntime?: string;
22
+ /** Gives each client module the runtime pieces of the modules it names, in a build loading only the page runtime. */
23
+ routeRuntime?: RouteRuntime | null;
18
24
  }
19
25
 
20
26
  export const createBarrelImportsPlugin = async (
21
27
  app: App,
22
- { skipPath = defaultSkipPath, pipeAfter, external = [], barrels: only }: BarrelImportsPluginOptions = {},
28
+ {
29
+ skipPath = defaultSkipPath,
30
+ pipeAfter,
31
+ external = [],
32
+ barrels: only,
33
+ modelRuntime,
34
+ routeRuntime,
35
+ }: BarrelImportsPluginOptions = {},
23
36
  ): Promise<BunPlugin> => {
24
37
  const barrels = [...new Set(only ?? (await app.getConfig()).barrelImports)].filter(
25
38
  (barrel) => barrel && !external.includes(barrel),
26
39
  );
40
+ const route = !only;
41
+ const resolvePackage = await createTsconfigPackageResolver(app);
27
42
  const analyzer = new BarrelAnalyzer({
28
- resolvePackage: await createTsconfigPackageResolver(app),
43
+ resolvePackage,
44
+ ...(route ? { packageRoot: app.workspace.workspaceRoot } : {}),
29
45
  });
46
+ const objects = route ? new ObjectMemberImports({ resolve: ObjectMemberImports.resolverOf(resolvePackage) }) : null;
30
47
 
31
48
  return {
32
49
  name: "barrel-imports",
@@ -44,14 +61,28 @@ export const createBarrelImportsPlugin = async (
44
61
  const file = Bun.file(realPath);
45
62
  //? A build's `files` entry has no copy on disk: Bun loads it itself.
46
63
  if (!(await file.exists())) return undefined;
64
+ if (modelRuntime !== undefined && StoreBootstrap.modelRuntimeFilter.test(realPath))
65
+ return { contents: modelRuntime, loader };
66
+ const whole = routeRuntime?.redirectOf(realPath);
67
+ if (whole) return { contents: whole, loader };
47
68
  let source = await file.text();
48
69
  if (skipPath(realPath)) return { contents: source, loader };
49
70
 
50
71
  // Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
51
72
  // macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
52
- if (!MACRO_ATTR_RE.test(source) && barrels.length > 0) {
53
- const rewritten = await rewriteBarrelImports(source, barrels, analyzer);
73
+ if (!MACRO_ATTR_RE.test(source)) {
74
+ const routed = routeRuntime?.transform(source, realPath);
75
+ if (routed) source = routed.source;
76
+ const rewritten =
77
+ barrels.length > 0
78
+ ? await rewriteBarrelImports(source, barrels, analyzer, {
79
+ perModule: routed?.perModule,
80
+ reexports: route,
81
+ })
82
+ : null;
54
83
  if (rewritten !== null) source = rewritten;
84
+ const narrowed = await objects?.rewrite(source, realPath);
85
+ if (narrowed?.contents) source = narrowed.contents;
55
86
  }
56
87
 
57
88
  if (pipeAfter) {
@@ -169,7 +200,7 @@ const resolveNodePackageExport = async (workspaceRoot: string, specifier: string
169
200
  if (!rel?.startsWith(".")) return null;
170
201
  const entryFile = await resolveFileCandidate(path.resolve(pkgDir, rel));
171
202
  if (!entryFile) return null;
172
- return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true };
203
+ return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true, rootDir: pkgDir };
173
204
  } catch {
174
205
  return null;
175
206
  }
@@ -240,6 +271,10 @@ export interface RewriteBarrelImportsOptions {
240
271
  specifierOf?: (subpath: string) => string;
241
272
  /** Called for each import of a listed barrel with the value names whose rewrite reads its export map. */
242
273
  onImport?: (barrel: string, names: string[]) => void;
274
+ /** The file names its runtime per module, so a client barrel stands for the page runtime alone. */
275
+ perModule?: boolean;
276
+ /** Rewrites `export { a, b as c } from "<barrel>"` as it rewrites an import of the same names. */
277
+ reexports?: boolean;
243
278
  }
244
279
 
245
280
  export const workspaceBarrels = (barrels: readonly string[]): string[] =>
@@ -249,11 +284,17 @@ export const rewriteBarrelImports = async (
249
284
  source: string,
250
285
  barrels: string[],
251
286
  analyzer: BarrelAnalyzer,
252
- { keepLines = false, specifierOf = (subpath: string) => subpath, onImport }: RewriteBarrelImportsOptions = {},
287
+ {
288
+ keepLines = false,
289
+ specifierOf = (subpath: string) => subpath,
290
+ onImport,
291
+ perModule = false,
292
+ reexports = false,
293
+ }: RewriteBarrelImportsOptions = {},
253
294
  ): Promise<string | null> => {
254
295
  // Sound pre-filter before the costly parse: a static import cannot name a specifier absent from the text.
255
296
  if (!barrels.some((barrel) => source.includes(barrel))) return null;
256
- const statements = findImportStatements(source);
297
+ const statements = findImportStatements(source, reexports);
257
298
  if (statements.length === 0) return null;
258
299
 
259
300
  // Walk import statements in reverse so replacements don't shift earlier ranges.
@@ -267,7 +308,7 @@ export const rewriteBarrelImports = async (
267
308
  if (names.length > 0) onImport?.(stmt.specifier, names);
268
309
  const map = await analyzer.analyze(stmt.specifier);
269
310
  if (!map || map.size === 0) continue;
270
- const lines = rewriteSingleStatement(stmt, map, specifierOf);
311
+ const lines = rewriteSingleStatement(stmt, map, specifierOf, perModule);
271
312
  if (lines === null) continue;
272
313
  const replacement = keepLines
273
314
  ? `${lines.join(" ")}${"\n".repeat(source.slice(stmt.start, stmt.end).split("\n").length - 1)}`
@@ -286,13 +327,14 @@ interface ParsedClause {
286
327
  }
287
328
 
288
329
  interface ImportStatement {
330
+ kind: "import" | "export";
289
331
  start: number;
290
332
  end: number;
291
333
  clause: ParsedClause | null;
292
334
  specifier: string;
293
335
  }
294
336
 
295
- const findImportStatements = (source: string): ImportStatement[] => {
337
+ const findImportStatements = (source: string, reexports: boolean): ImportStatement[] => {
296
338
  const statements: ImportStatement[] = [];
297
339
  // `setParentNodes: false` holds only while nothing reads `node.parent` and positions use `getStart(sourceFile)`.
298
340
  const sourceFile = ts.createSourceFile(
@@ -303,11 +345,25 @@ const findImportStatements = (source: string): ImportStatement[] => {
303
345
  ts.ScriptKind.TSX,
304
346
  );
305
347
  for (const statement of sourceFile.statements) {
348
+ if (reexports && ts.isExportDeclaration(statement)) {
349
+ const exportClause = statement.exportClause;
350
+ if (!statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
351
+ if (!exportClause || !ts.isNamedExports(exportClause)) continue;
352
+ statements.push({
353
+ kind: "export",
354
+ start: statement.getStart(sourceFile),
355
+ end: statement.end,
356
+ clause: exportClauseOf(statement.isTypeOnly, exportClause),
357
+ specifier: statement.moduleSpecifier.text,
358
+ });
359
+ continue;
360
+ }
306
361
  if (!ts.isImportDeclaration(statement)) continue;
307
362
  if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
308
363
  const importClause = statement.importClause;
309
364
  if (!importClause) continue;
310
365
  statements.push({
366
+ kind: "import",
311
367
  start: statement.getStart(sourceFile),
312
368
  end: statement.end,
313
369
  clause: clauseOf(importClause),
@@ -317,6 +373,16 @@ const findImportStatements = (source: string): ImportStatement[] => {
317
373
  return statements;
318
374
  };
319
375
 
376
+ const exportClauseOf = (typeOnly: boolean, exportClause: ts.NamedExports): ParsedClause | null => {
377
+ const named: NamedItem[] = [];
378
+ for (const element of exportClause.elements) {
379
+ const imported = element.propertyName ?? element.name;
380
+ if (!ts.isIdentifier(imported) || !ts.isIdentifier(element.name)) return null;
381
+ named.push({ imported: imported.text, local: element.name.text, isType: element.isTypeOnly });
382
+ }
383
+ return { named, typeOnly };
384
+ };
385
+
320
386
  const clauseOf = (importClause: ts.ImportClause): ParsedClause | null => {
321
387
  const parsed: ParsedClause = { typeOnly: importClause.phaseModifier === ts.SyntaxKind.TypeKeyword };
322
388
  if (importClause.name) parsed.defaultImport = importClause.name.text;
@@ -344,6 +410,7 @@ const rewriteSingleStatement = (
344
410
  stmt: ImportStatement,
345
411
  map: BarrelExportMap,
346
412
  specifierOf: (subpath: string) => string,
413
+ perModule: boolean,
347
414
  ): string[] | null => {
348
415
  const { clause } = stmt;
349
416
  if (!clause) return null;
@@ -353,6 +420,7 @@ const rewriteSingleStatement = (
353
420
  if (clause.typeOnly && !clause.defaultImport) return null;
354
421
  if (!clause.named?.length) return null;
355
422
 
423
+ const { kind } = stmt;
356
424
  const remaining: NamedItem[] = [];
357
425
  const rewrites = new Map<string, NamedItem[]>();
358
426
  const namespaceLines: string[] = [];
@@ -367,7 +435,7 @@ const rewriteSingleStatement = (
367
435
  continue;
368
436
  }
369
437
  if (target.namespace) {
370
- namespaceLines.push(`import * as ${item.local} from ${JSON.stringify(specifierOf(target.subpath))};`);
438
+ namespaceLines.push(`${kind} * as ${item.local} from ${JSON.stringify(specifierOf(target.subpath))};`);
371
439
  continue;
372
440
  }
373
441
  const list = rewrites.get(target.subpath) ?? [];
@@ -378,7 +446,7 @@ const rewriteSingleStatement = (
378
446
  if (rewrites.size === 0 && namespaceLines.length === 0) return null;
379
447
 
380
448
  //? An app or lib client barrel's import-time side effects are its client runtime and store, not its module UI.
381
- const lines = (StoreBootstrap.ofClientBarrel(stmt.specifier, map) ?? []).map(
449
+ const lines = (StoreBootstrap.ofClientBarrel(stmt.specifier, map, valueNamesOf(clause), { perModule }) ?? []).map(
382
450
  (specifier) => `import ${JSON.stringify(specifierOf(specifier))};`,
383
451
  );
384
452
 
@@ -386,11 +454,11 @@ const rewriteSingleStatement = (
386
454
  const parts: string[] = [];
387
455
  if (clause.defaultImport) parts.push(clause.defaultImport);
388
456
  if (remaining.length > 0) parts.push(`{ ${remaining.map(serializeNamedItem).join(", ")} }`);
389
- lines.push(`import ${parts.join(", ")} from "${stmt.specifier}";`);
457
+ lines.push(`${kind} ${parts.join(", ")} from "${stmt.specifier}";`);
390
458
  }
391
459
 
392
460
  for (const [subpath, items] of rewrites) {
393
- lines.push(`import { ${items.map(serializeNamedItem).join(", ")} } from ${JSON.stringify(specifierOf(subpath))};`);
461
+ lines.push(`${kind} { ${items.map(serializeNamedItem).join(", ")} } from ${JSON.stringify(specifierOf(subpath))};`);
394
462
  }
395
463
  lines.push(...namespaceLines);
396
464
 
@@ -0,0 +1,58 @@
1
+ import path from "node:path";
2
+ import { plugin } from "bun";
3
+ import { transformUseClient } from "./rscUseClientTransform";
4
+
5
+ const workspaceRoot = path.resolve(import.meta.dir, "../../../..");
6
+ const ui = path.join(workspaceRoot, "pkgs/akanjs/ui");
7
+ //? The build narrows these barrel imports to one file; each facet index loads react-dom/client, which react-server refuses.
8
+ const narrowed: Record<string, string> = {
9
+ "akanjs/client": path.join(workspaceRoot, "pkgs/akanjs/client/cn.ts"),
10
+ "akanjs/webkit": path.join(workspaceRoot, "pkgs/akanjs/webkit/lazy.tsx"),
11
+ };
12
+ plugin({
13
+ name: "framework-objects-use-client",
14
+ setup(build) {
15
+ build.onLoad({ filter: /[\\/]pkgs[\\/]akanjs[\\/]ui[\\/].*\.tsx?$/ }, async (args) => {
16
+ let source = await Bun.file(args.path).text();
17
+ for (const [specifier, file] of Object.entries(narrowed))
18
+ source = source.replaceAll(`from "${specifier}"`, `from ${JSON.stringify(file)}`);
19
+ return {
20
+ contents: transformUseClient(source, { path: args.path, workspaceRoot }) ?? source,
21
+ loader: args.path.endsWith(".tsx") ? "tsx" : "ts",
22
+ };
23
+ });
24
+ },
25
+ });
26
+
27
+ const { renderToReadableStream } = await import("react-server-dom-webpack/server.node");
28
+ const { Field } = await import(path.join(ui, "Field/index.tsx"));
29
+ const { Layout } = await import(path.join(ui, "Layout/index.ts"));
30
+ const { Model } = await import(path.join(ui, "Model/index.ts"));
31
+ const { Dialog } = await import(path.join(ui, "Dialog/index.tsx"));
32
+
33
+ const references = new Set<string>();
34
+ const clientManifest = new Proxy(
35
+ {},
36
+ {
37
+ get: (_, key) => {
38
+ const [id = "", name = ""] = String(key).split("#");
39
+ references.add(String(key));
40
+ return { id, chunks: [], name };
41
+ },
42
+ },
43
+ );
44
+ const errors: string[] = [];
45
+ const stream = await renderToReadableStream(
46
+ <main>
47
+ <Field label="Name" />
48
+ <Layout.Header>Head</Layout.Header>
49
+ <Model.View>Body</Model.View>
50
+ <Dialog open>
51
+ <Dialog.LegacyModal>Legacy</Dialog.LegacyModal>
52
+ </Dialog>
53
+ </main>,
54
+ clientManifest,
55
+ { onError: (error: unknown) => void errors.push(String(error)) },
56
+ );
57
+ await new Response(stream).text();
58
+ process.stdout.write(JSON.stringify({ references: [...references].sort(), errors }));
@@ -0,0 +1,54 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { ObjectMemberImports } from "./objectMemberImports";
4
+ import { hasUseClientDirective } from "./rscUseClientTransform";
5
+
6
+ const ui = path.resolve(import.meta.dir, "../../../akanjs/ui");
7
+
8
+ describe("framework objects on the server", () => {
9
+ test("a server component renders Field, Layout.Header, Model.View and Dialog.LegacyModal, each a client reference", async () => {
10
+ const proc = Bun.spawn(
11
+ [process.execPath, "--conditions", "react-server", `${import.meta.dir}/frameworkObjects.fixture.tsx`],
12
+ { cwd: import.meta.dir, env: { ...process.env, NODE_ENV: "production" }, stdout: "pipe", stderr: "pipe" },
13
+ );
14
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
15
+ expect({ exit: await proc.exited, stderr }).toEqual({ exit: 0, stderr: "" });
16
+
17
+ expect(JSON.parse(stdout)).toEqual({
18
+ references: [
19
+ "pkgs/akanjs/ui/Dialog/LegacyModal.tsx#LegacyModal",
20
+ "pkgs/akanjs/ui/Dialog/Provider.tsx#Provider",
21
+ "pkgs/akanjs/ui/Field/index.tsx#Field",
22
+ "pkgs/akanjs/ui/Layout/Header.tsx#Header",
23
+ "pkgs/akanjs/ui/Model/View.tsx#default",
24
+ ],
25
+ errors: [],
26
+ });
27
+ }, 60_000);
28
+
29
+ test("a server file naming Field.Text and Field.Switch imports each from its own client file", async () => {
30
+ const objects = new ObjectMemberImports({ resolve: ObjectMemberImports.resolverOf(async () => null) });
31
+ const result = await objects.rewrite(
32
+ [
33
+ `import { Field } from ${JSON.stringify(path.join(ui, "Field/index.tsx"))};`,
34
+ `export const Page = () => <><Field.Text value="Ada" /><Field.Switch value /></>;`,
35
+ ].join("\n"),
36
+ path.join(import.meta.dir, "page.tsx"),
37
+ );
38
+
39
+ const imported = await Promise.all(
40
+ [...(result?.contents ?? "").matchAll(/import \{ (\w+) as [\w$]+ \} from "([^"]+)";/g)].map(
41
+ async ([, name, file]) => [
42
+ name,
43
+ path.relative(ui, file as string),
44
+ hasUseClientDirective(await Bun.file(file as string).text()),
45
+ ],
46
+ ),
47
+ );
48
+ expect(imported).toEqual([
49
+ ["Text", "Field/Text.tsx", true],
50
+ ["Switch", "Field/Choice.tsx", true],
51
+ ]);
52
+ expect(result?.kept).toEqual([]);
53
+ });
54
+ });
@@ -0,0 +1,196 @@
1
+ import { beforeAll, describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import type { RuntimeNameTable } from "../quality/runtimeNameTable";
4
+ import { runtimeFixtureTables } from "../quality/runtimeTable.fixture";
5
+ import { tempDirs, writeText as write } from "../test/testHelpers";
6
+ import { ModelReference } from "./modelReference";
7
+ import { RouteRuntime } from "./routeRuntime";
8
+
9
+ const makeTempRoot = tempDirs("akan-model-reference-");
10
+ const root = "/ws";
11
+ const onDisk = (model: string) => `\n"use client";\n\nexport const reference = "${model}";\n`;
12
+ const referenceOf = (model: string) => `${root}/apps/demo/lib/__client/${model}.ref.ts`;
13
+ const uiFile = (name: string) => `${root}/apps/demo/ui/${name}.tsx`;
14
+ const naming = (model: string) =>
15
+ `"use client";\nimport { st } from "@apps/demo/client";\nexport const read = () => st.use.${model}();\n`;
16
+ const pickingRun = 'import { st } from "@apps/demo/client";\nexport const run = (name: string) => st.do[name]();\n';
17
+ const pickingStore = `import { store } from "akanjs/store";
18
+
19
+ import { st } from "../st";
20
+ import { fetch, sig } from "../useClient";
21
+
22
+ export class MemoStore extends store(sig.memo, () => ({ draft: "" })) {
23
+ run(name: string) {
24
+ return [fetch[name](), st.get().draft];
25
+ }
26
+ }
27
+ `;
28
+ const appPieces = ["_useClient", "_st", "_base.fetch", "memo.fetch", "memo.st", "note.fetch", "note.st", "tag.fetch"];
29
+ const kitPieces = ["_useClient", "_st", "note.fetch", "note.st", "tag.fetch", "tag.st", "util.st"];
30
+ const pieces = new Set([
31
+ ...appPieces.map((piece) => `apps/demo/lib/__client/${piece}`),
32
+ ...kitPieces.map((piece) => `libs/kit/lib/__client/${piece}`),
33
+ ]);
34
+ const memoPieces = ["apps/demo/lib/__client/memo.fetch", "apps/demo/lib/__client/memo.st"];
35
+ const wholeLoads =
36
+ 'import { loadedAfter as __akanLoadedAfter } from "akanjs/base"; import * as __akanLoaded0 from "/ws/apps/demo/lib/cnst.ts"; import { sig as __akanLoaded1 } from "/ws/apps/demo/lib/__client/_useClient.ts"; import { st as __akanLoaded2 } from "/ws/apps/demo/lib/__client/_st.ts"; __akanLoadedAfter(__akanLoaded0, __akanLoaded1, __akanLoaded2);';
37
+
38
+ let demo: RuntimeNameTable;
39
+ const runtimeOf = (files: Record<string, string> = {}) =>
40
+ new RouteRuntime(root, demo, pieces, (absPath) => files[absPath] ?? null);
41
+ const transformed = (model: string, files?: Record<string, string>) =>
42
+ runtimeOf(files).transform(onDisk(model), referenceOf(model));
43
+
44
+ beforeAll(async () => {
45
+ demo = (await runtimeFixtureTables()).demo;
46
+ });
47
+
48
+ describe("a model's reference file in the per-route build", () => {
49
+ test("imports the model's fetch piece as `loaded` and its store piece by the model's name, and passes both to `loadedAfter`", () => {
50
+ expect(transformed("memo")).toEqual({
51
+ source: `
52
+ "use client";
53
+ import { loadedAfter as __akanLoadedAfter } from "akanjs/base";
54
+ import { loaded as __akanLoaded0 } from "@apps/demo/lib/__client/memo.fetch";
55
+ import { memo as __akanLoaded1 } from "@apps/demo/lib/__client/memo.st";
56
+ __akanLoadedAfter(__akanLoaded0, __akanLoaded1);
57
+
58
+ export const reference = "memo";
59
+ `,
60
+ perModule: true,
61
+ pieces: memoPieces,
62
+ });
63
+ });
64
+
65
+ test("loads the pieces a client file reading the model's store loads, for a model of the app, of a lib, and one the app extends", () => {
66
+ for (const model of ["memo", "tag", "note"]) {
67
+ const named = runtimeOf().transform(naming(model), uiFile("Card"));
68
+ expect(named?.pieces.some((piece) => piece.endsWith(`/${model}.st`))).toBe(true);
69
+ expect(transformed(model)?.pieces).toEqual(named?.pieces ?? []);
70
+ }
71
+ expect(transformed("tag")?.pieces).toEqual(["apps/demo/lib/__client/tag.fetch", "libs/kit/lib/__client/tag.st"]);
72
+ });
73
+
74
+ test("loads the stores the model's own store names too, as a file reading that store does", () => {
75
+ const files = {
76
+ [`${root}/apps/demo/lib/memo/memo.store.ts`]: `import { store } from "akanjs/store";
77
+
78
+ import { st } from "../st";
79
+ import { sig } from "../useClient";
80
+
81
+ export class MemoStore extends store(sig.memo, () => ({ draft: "" })) {
82
+ relabel() {
83
+ st.do.pickLabel(st.get().tagFilter);
84
+ }
85
+ }
86
+ `,
87
+ };
88
+ expect(transformed("memo", files)?.pieces).toEqual([
89
+ ...memoPieces,
90
+ "libs/kit/lib/__client/tag.st",
91
+ "libs/kit/lib/__client/util.st",
92
+ ]);
93
+ });
94
+
95
+ test("loads the whole runtime where the model's store picks a name at run time", () => {
96
+ const whole = transformed("memo", { [`${root}/apps/demo/lib/memo/memo.store.ts`]: pickingStore });
97
+ expect(whole).toEqual({
98
+ source: `\n"use client";\n${wholeLoads.split("; ").join(";\n")}\n\nexport const reference = "memo";\n`,
99
+ perModule: false,
100
+ pieces: [],
101
+ });
102
+ });
103
+
104
+ test("holds no import made only for its effect, which a split bundle would move away from it", () => {
105
+ for (const model of ["memo", "tag", "note"]) expect(transformed(model)?.source).not.toMatch(/import\s*"/);
106
+ });
107
+
108
+ test("stays as written for a model the app does not have, and is no reference file anywhere else", () => {
109
+ expect(transformed("ghost")).toEqual({ source: onDisk("ghost"), perModule: true, pieces: [] });
110
+ expect(ModelReference.modelOf("apps/demo/lib/__client/note.ref.ts")).toBe("note");
111
+ expect(ModelReference.modelOf(referenceOf("note"))).toBe("note");
112
+ for (const file of ["apps/demo/lib/__client/note.st.ts", "apps/demo/ui/note.ref.ts", "apps/demo/lib/refs.ts"]) {
113
+ expect(ModelReference.modelOf(file)).toBeNull();
114
+ expect(ModelReference.isFile(file)).toBe(false);
115
+ }
116
+ expect(ModelReference.sourceOf(onDisk("note"), [])).toBe(onDisk("note"));
117
+ });
118
+ });
119
+
120
+ describe("a model's reference file in a build planned over the whole-runtime bundle", () => {
121
+ const plan = (routes: Record<string, string[]>, files: Record<string, string>) => {
122
+ const target = runtimeOf(files);
123
+ const kept = target.plan({
124
+ importsByModule: new Map(Object.keys(files).map((file) => [file, []])),
125
+ entries: Object.keys(files),
126
+ entriesByRoute: new Map(Object.entries(routes)),
127
+ });
128
+ const piecesOf = (file: string) => target.transform(files[file] ?? "", file)?.pieces ?? "as written";
129
+ return { kept: [...kept].sort(), piecesOf };
130
+ };
131
+ const files = {
132
+ [referenceOf("memo")]: onDisk("memo"),
133
+ [uiFile("Plain")]: "export const Plain = 1;\n",
134
+ [uiFile("Run")]: pickingRun,
135
+ };
136
+
137
+ test("is an entry narrowed to the model's pieces on a route that loads no whole runtime", () => {
138
+ const { kept, piecesOf } = plan(
139
+ { "/list": [uiFile("Plain"), referenceOf("memo")], "/run": [uiFile("Run")] },
140
+ files,
141
+ );
142
+ expect(kept).toEqual([uiFile("Run")]);
143
+ expect(piecesOf(referenceOf("memo"))).toEqual(memoPieces);
144
+ });
145
+
146
+ test("keeps its pieces beside the whole runtime of a page, where more routes without one hold it", () => {
147
+ const routes = {
148
+ "/list": [uiFile("Plain"), referenceOf("memo")],
149
+ "/view": [uiFile("Plain"), referenceOf("memo")],
150
+ "/run": [uiFile("Run"), referenceOf("memo")],
151
+ };
152
+ const { kept, piecesOf } = plan(routes, files);
153
+ expect(kept).toEqual([uiFile("Run")]);
154
+ expect(piecesOf(referenceOf("memo"))).toEqual(memoPieces);
155
+ });
156
+
157
+ test("stays as written where only whole-runtime routes hold it, whose pages already load every model", () => {
158
+ const { kept, piecesOf } = plan(
159
+ { "/run": [uiFile("Run"), referenceOf("memo")], "/plain": [uiFile("Plain")] },
160
+ files,
161
+ );
162
+ expect(kept).toEqual([referenceOf("memo"), uiFile("Run")].sort());
163
+ expect(piecesOf(referenceOf("memo"))).toBe("as written");
164
+ });
165
+
166
+ test("keeps the whole runtime as an entry where its model's store picks a name at run time", () => {
167
+ const picking = { ...files, [`${root}/apps/demo/lib/memo/memo.store.ts`]: pickingStore };
168
+ const target = runtimeOf(picking);
169
+ const kept = target.plan({
170
+ importsByModule: new Map([referenceOf("memo"), uiFile("Plain")].map((file) => [file, []])),
171
+ entries: [referenceOf("memo"), uiFile("Plain")],
172
+ entriesByRoute: new Map([["/list", [uiFile("Plain"), referenceOf("memo")]]]),
173
+ });
174
+ expect([...kept].sort()).toEqual([referenceOf("memo"), uiFile("Plain")]);
175
+ expect(target.transform(onDisk("memo"), referenceOf("memo"))).toBeNull();
176
+ });
177
+ });
178
+
179
+ describe("the reference files of an app", () => {
180
+ test("are listed by model from the app's own folder, and are none before a sync wrote them", async () => {
181
+ const tempRoot = await makeTempRoot();
182
+ const dir = path.join(tempRoot, "apps/demo/lib/__client");
183
+ for (const file of ["note.ref.ts", "memo.ref.ts", "memo.st.ts", "refs.ts"]) await write(path.join(dir, file), "");
184
+ await write(path.join(tempRoot, "libs/kit/lib/__client/tag.ref.ts"), "");
185
+
186
+ expect([...(await ModelReference.filesOf(tempRoot, "apps/demo"))]).toEqual([
187
+ ["memo", path.join(dir, "memo.ref.ts")],
188
+ ["note", path.join(dir, "note.ref.ts")],
189
+ ]);
190
+ expect([...(await ModelReference.filesOf(tempRoot, "apps/other"))]).toEqual([]);
191
+ });
192
+
193
+ test("are registered by the file the root layout imports", () => {
194
+ expect(ModelReference.registrySpecifier("demo")).toBe("@apps/demo/lib/__client/refs");
195
+ });
196
+ });
@@ -0,0 +1,39 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ const referenceFile = /(?:^|[\\/])lib[\\/]__client[\\/]([^\\/]+)\.ref\.ts$/;
5
+ const directive = /^"use client";$/m;
6
+ const suffix = ".ref.ts";
7
+
8
+ //? On disk a reference file names no piece: a bundle holding the whole runtime reads it too and would load each twice.
9
+ export class ModelReference {
10
+ static readonly registry = "__client/refs";
11
+
12
+ static registrySpecifier(appName: string): string {
13
+ return `@apps/${appName}/lib/${ModelReference.registry}`;
14
+ }
15
+
16
+ static async filesOf(workspaceRoot: string, appScope: string): Promise<Map<string, string>> {
17
+ const dir = path.join(workspaceRoot, appScope, "lib/__client");
18
+ const files = await readdir(dir).catch(() => []);
19
+ return new Map(
20
+ files
21
+ .filter((file) => file.endsWith(suffix))
22
+ .sort()
23
+ .map((file) => [file.slice(0, -suffix.length), path.join(dir, file)]),
24
+ );
25
+ }
26
+
27
+ static modelOf(file: string): string | null {
28
+ return file.match(referenceFile)?.[1] ?? null;
29
+ }
30
+
31
+ static isFile(file: string): boolean {
32
+ return referenceFile.test(file);
33
+ }
34
+
35
+ //? `loads` imports each piece by name for `loadedAfter`: Bun's chunk splitting moves an effect-only import away.
36
+ static sourceOf(source: string, loads: string[]): string {
37
+ return loads.length ? source.replace(directive, (line) => [line, ...loads].join("\n")) : source;
38
+ }
39
+ }