@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
@@ -0,0 +1,121 @@
1
+ import path from "node:path";
2
+ import type { RouteRuntimeCause } from "../transforms/routeRuntimePlan";
3
+
4
+ export interface RouteRuntimeBuildReport {
5
+ app: string;
6
+ routes: number;
7
+ perModule: string[];
8
+ //? Routes the analysis could load per module, kept whole because the build measured them no smaller that way.
9
+ notSmaller: string[];
10
+ //? Routes no smaller per module than where every page keeps the whole runtime, which came out larger still when the
11
+ //? build kept it for them among this app's other pages: they load per module.
12
+ refused?: string[];
13
+ causes: RouteRuntimeCause[];
14
+ dictionary?: RouteRuntimeDictionaryFallback[];
15
+ }
16
+
17
+ export interface RouteRuntimeDictionaryFallback {
18
+ file: string;
19
+ line?: number;
20
+ why: string;
21
+ routes: string[];
22
+ }
23
+
24
+ const count = (items: readonly unknown[], one: string, many = `${one}s`) =>
25
+ `${items.length} ${items.length === 1 ? one : many}`;
26
+
27
+ export class RouteRuntimeReport {
28
+ //? Under `.akan/cache`: the development server clears the rest of `.akan` when it starts.
29
+ static readonly file = ".akan/cache/route-runtime.json";
30
+ static readonly shown = 6;
31
+
32
+ static summary({ perModule, notSmaller, routes }: RouteRuntimeBuildReport): string {
33
+ const named = routes - perModule.length - notSmaller.length;
34
+ const verb = (many: number, word: string) => (many === 1 ? `${word}s` : word);
35
+ return [
36
+ `${count(perModule, "route")} ${verb(perModule.length, "load")} per module`,
37
+ `${notSmaller.length} ${verb(notSmaller.length, "keep")} the whole runtime because per module would not be smaller`,
38
+ ...(named > 0 ? [`${named} ${verb(named, "keep")} it for a reason \`akan quality runtime\` names`] : []),
39
+ ].join(", ");
40
+ }
41
+
42
+ static format(reports: readonly RouteRuntimeBuildReport[]): string {
43
+ return reports
44
+ .map((report) =>
45
+ [
46
+ `Last build of apps/${report.app}: ${RouteRuntimeReport.summary(report)}.`,
47
+ ...RouteRuntimeReport.#perModuleLines(report.perModule),
48
+ ...report.causes.flatMap((cause) => RouteRuntimeReport.#causeLines(cause)),
49
+ ...RouteRuntimeReport.#refusedLines(report.refused ?? []),
50
+ ...(report.dictionary ?? []).flatMap((fallback) => RouteRuntimeReport.#dictionaryLines(fallback)),
51
+ ].join("\n"),
52
+ )
53
+ .join("\n\n");
54
+ }
55
+
56
+ static #perModuleLines(routes: readonly string[]): string[] {
57
+ if (routes.length === 0) return [];
58
+ const more =
59
+ routes.length > RouteRuntimeReport.shown ? `, and ${routes.length - RouteRuntimeReport.shown} more` : "";
60
+ return [` per module: ${routes.slice(0, RouteRuntimeReport.shown).join(", ")}${more}`];
61
+ }
62
+
63
+ static #causeLines({ rule, file, line, message, entries, routes, chains }: RouteRuntimeCause): string[] {
64
+ const where = file ? `${file}${line ? `:${line}` : ""} ` : "";
65
+ const listed = routes.slice(0, RouteRuntimeReport.shown).join(", ");
66
+ const more =
67
+ routes.length > RouteRuntimeReport.shown ? `, and ${routes.length - RouteRuntimeReport.shown} more` : "";
68
+ return [
69
+ ` [${rule}] ${where}${message}`,
70
+ ` ${count(entries, "entry", "entries")} on ${count(routes, "route")}${routes.length ? `: ${listed}${more}` : ""}`,
71
+ ...chains.map((chain) => ` reached as ${RouteRuntimeReport.#chain(chain)}`),
72
+ ];
73
+ }
74
+
75
+ static #refusedLines(routes: readonly string[]): string[] {
76
+ if (routes.length === 0) return [];
77
+ const more =
78
+ routes.length > RouteRuntimeReport.shown ? `, and ${routes.length - RouteRuntimeReport.shown} more` : "";
79
+ return [
80
+ ` ${count(routes, "route")} measured no smaller per module than where every page keeps the whole runtime, and larger still keeping it here, so ${routes.length === 1 ? "it loads" : "they load"} per module: ${routes.slice(0, RouteRuntimeReport.shown).join(", ")}${more}`,
81
+ ];
82
+ }
83
+
84
+ static #dictionaryLines({ file, line, why, routes }: RouteRuntimeDictionaryFallback): string[] {
85
+ const more =
86
+ routes.length > RouteRuntimeReport.shown ? `, and ${routes.length - RouteRuntimeReport.shown} more` : "";
87
+ return [
88
+ ` [dictionary] ${file}${line ? `:${line}` : ""} ${why}`,
89
+ ` ${count(routes, "route")} ${routes.length === 1 ? "loads" : "load"} every text of the page dictionary: ${routes.slice(0, RouteRuntimeReport.shown).join(", ")}${more}`,
90
+ ];
91
+ }
92
+
93
+ static #chain(chain: readonly string[]) {
94
+ return chain.length > 6
95
+ ? `${chain.slice(0, 2).join(" → ")} → … → ${chain.slice(-3).join(" → ")}`
96
+ : chain.join(" → ");
97
+ }
98
+
99
+ static async write(appDir: string, report: RouteRuntimeBuildReport) {
100
+ await Bun.write(path.join(appDir, RouteRuntimeReport.file), `${JSON.stringify(report, null, 1)}\n`);
101
+ }
102
+
103
+ static async addDictionary(appDir: string, dictionary: RouteRuntimeDictionaryFallback[]) {
104
+ const report: RouteRuntimeBuildReport | null = await Bun.file(path.join(appDir, RouteRuntimeReport.file))
105
+ .json()
106
+ .catch(() => null);
107
+ if (report) await RouteRuntimeReport.write(appDir, { ...report, dictionary });
108
+ }
109
+
110
+ static async read(workspaceRoot: string): Promise<RouteRuntimeBuildReport[]> {
111
+ const files = [...new Bun.Glob(`apps/*/${RouteRuntimeReport.file}`).scanSync({ cwd: workspaceRoot, dot: true })];
112
+ const reports = await Promise.all(
113
+ files.sort().map((file) =>
114
+ Bun.file(path.join(workspaceRoot, file))
115
+ .json()
116
+ .catch(() => null),
117
+ ),
118
+ );
119
+ return reports.filter((report): report is RouteRuntimeBuildReport => !!report && Array.isArray(report.causes));
120
+ }
121
+ }
@@ -0,0 +1,71 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import type { RuntimeSourceFile } from "./runtimeModuleFacts";
4
+
5
+ export interface RuntimeConstantFact {
6
+ scope: string;
7
+ module: string;
8
+ kind: "database" | "scalar";
9
+ file: string;
10
+ exports: string[];
11
+ }
12
+
13
+ export type RuntimeConstantEntry =
14
+ | { type: "model" | "export"; fact: RuntimeConstantFact }
15
+ | { type: "namespace"; scope: string };
16
+
17
+ const constantPath = /^((?:apps|libs)\/[^/]+)\/lib\/(__scalar\/)?([^/_][^/]*)\/\3\.constant$/;
18
+
19
+ export class RuntimeConstantFacts {
20
+ static of({ file, sourceFile }: RuntimeSourceFile): RuntimeConstantFact | null {
21
+ const [, scope, scalar, module] = file.replace(/\.ts$/, "").match(constantPath) ?? [];
22
+ if (!scope || !module) return null;
23
+ const exports = new Set<string>();
24
+ for (const statement of sourceFile.statements) {
25
+ if (ts.isExportDeclaration(statement)) {
26
+ if (statement.isTypeOnly) continue;
27
+ const clause = statement.exportClause;
28
+ if (clause && ts.isNamedExports(clause))
29
+ for (const element of clause.elements) if (!element.isTypeOnly) exports.add(element.name.text);
30
+ } else for (const name of RuntimeConstantFacts.#declaredExports(statement)) exports.add(name);
31
+ }
32
+ return {
33
+ scope,
34
+ module,
35
+ kind: scalar ? "scalar" : "database",
36
+ file: file.replace(/\.ts$/, ""),
37
+ exports: [...exports].sort(),
38
+ };
39
+ }
40
+
41
+ static ownerOf(specifier: string, fileName: string): { scope: string; module: string } | null {
42
+ const aliased = specifier.match(/^@((?:apps|libs)\/[\s\S]+)$/)?.[1];
43
+ const joined =
44
+ aliased ?? (specifier.startsWith(".") ? path.posix.join(path.posix.dirname(fileName), specifier) : null);
45
+ const [, scope, , module] = joined
46
+ ? (path.posix.normalize(joined).replace(/\.ts$/, "").match(constantPath) ?? [])
47
+ : [];
48
+ return scope && module ? { scope, module } : null;
49
+ }
50
+
51
+ static #declaredExports(statement: ts.Statement): string[] {
52
+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
53
+ const exported = modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
54
+ if (!exported || modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword)) return [];
55
+ if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)) return [];
56
+ if (ts.isVariableStatement(statement))
57
+ return statement.declarationList.declarations.flatMap((declaration) =>
58
+ RuntimeConstantFacts.#bindingNames(declaration.name),
59
+ );
60
+ if (ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement) || ts.isEnumDeclaration(statement))
61
+ return statement.name ? [statement.name.text] : [];
62
+ return [];
63
+ }
64
+
65
+ static #bindingNames(name: ts.BindingName): string[] {
66
+ if (ts.isIdentifier(name)) return [name.text];
67
+ return name.elements.flatMap((element) =>
68
+ ts.isOmittedExpression(element) ? [] : RuntimeConstantFacts.#bindingNames(element.name),
69
+ );
70
+ }
71
+ }
@@ -0,0 +1,123 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import type { RuntimeConstantFact } from "./runtimeConstantFacts";
4
+ import type { RuntimeNameTable, RuntimeOwner } from "./runtimeNameTable";
5
+ import { RuntimeUse, type RuntimeUseProblem } from "./runtimeUse";
6
+
7
+ export interface RuntimeConstantNeeds {
8
+ owners: RuntimeOwner[];
9
+ problems: RuntimeUseProblem[];
10
+ }
11
+
12
+ const keyOf = ({ scope, module }: RuntimeOwner) => `${scope}/${module}`;
13
+
14
+ export class RuntimeConstantGraph {
15
+ readonly #table: RuntimeNameTable;
16
+ readonly #read: (file: string) => string | null;
17
+ readonly #needs = new Map<string, RuntimeConstantNeeds>();
18
+
19
+ constructor(table: RuntimeNameTable, read: (file: string) => string | null) {
20
+ this.#table = table;
21
+ this.#read = read;
22
+ }
23
+
24
+ static ofDisk(workspaceRoot: string, table: RuntimeNameTable) {
25
+ return new RuntimeConstantGraph(table, (file) => {
26
+ try {
27
+ return readFileSync(path.join(workspaceRoot, file), "utf8");
28
+ } catch {
29
+ return null;
30
+ }
31
+ });
32
+ }
33
+
34
+ get table() {
35
+ return this.#table;
36
+ }
37
+
38
+ factOf({ scope, module }: RuntimeOwner): RuntimeConstantFact | null {
39
+ return this.#table.constantsOf(scope).find((fact) => fact.module === module) ?? null;
40
+ }
41
+
42
+ declarationsOf(owner: RuntimeOwner): RuntimeOwner[] {
43
+ const kind = this.factOf(owner)?.kind;
44
+ return kind ? this.#declarationsOf(owner.module, kind) : [];
45
+ }
46
+
47
+ #declarationsOf(module: string, kind: RuntimeConstantFact["kind"]): RuntimeOwner[] {
48
+ return this.#table.layers
49
+ .filter(({ constants }) => constants?.some((fact) => fact.module === module && fact.kind === kind))
50
+ .map(({ scope }) => ({ scope, module }));
51
+ }
52
+
53
+ modelOf(module: string): RuntimeOwner | null {
54
+ return this.#declarationsOf(module, "database").at(-1) ?? null;
55
+ }
56
+
57
+ //? The outermost scope: an app model extends the lib model of its name, so the app's piece registers both, lib first.
58
+ registrationOf(owner: RuntimeOwner): RuntimeOwner | null {
59
+ return this.declarationsOf(owner).at(-1) ?? null;
60
+ }
61
+
62
+ needsOf(owner: RuntimeOwner): RuntimeConstantNeeds {
63
+ const key = keyOf(owner);
64
+ const known = this.#needs.get(key);
65
+ if (known) return known;
66
+ const file = this.factOf(owner)?.file;
67
+ const needs = file ? this.needsOfFile(`${file}.ts`) : { owners: [], problems: [] };
68
+ const result = { ...needs, owners: needs.owners.filter((named) => keyOf(named) !== key) };
69
+ this.#needs.set(key, result);
70
+ return result;
71
+ }
72
+
73
+ needsOfFile(fileName: string): RuntimeConstantNeeds {
74
+ const text = this.#read(fileName);
75
+ if (text === null) return { owners: [], problems: [] };
76
+ const { constants } = RuntimeUse.analyze({ fileName, text }, this.#table);
77
+ const owners = new Map<string, RuntimeOwner>();
78
+ for (const owner of constants.imports) owners.set(keyOf(owner), owner);
79
+ for (const read of constants.reads)
80
+ for (const { owner } of read.kind === "member" ? [read] : read.keys) owners.set(keyOf(owner), owner);
81
+ return { owners: [...owners.values()], problems: constants.problems };
82
+ }
83
+
84
+ fetchNeedsOf(module: string): RuntimeOwner[] | null {
85
+ const model = this.modelOf(module);
86
+ const owners = model ? [model] : [];
87
+ for (const { scope, modules } of this.#table.layers)
88
+ for (const fact of modules)
89
+ if (fact.module === module && fact.signal) {
90
+ const dir = fact.kind === "service" ? `_${module}` : module;
91
+ const needs = this.needsOfFile(`${scope}/lib/${dir}/${module}.signal.ts`);
92
+ if (needs.problems.length) return null;
93
+ owners.push(...needs.owners);
94
+ }
95
+ return this.closureOf(owners);
96
+ }
97
+
98
+ closureOf(owners: RuntimeOwner[]): RuntimeOwner[] {
99
+ const found = new Map<string, RuntimeOwner>();
100
+ const visit = (owner: RuntimeOwner) => {
101
+ const registration = this.registrationOf(owner);
102
+ if (!registration || found.has(keyOf(registration))) return;
103
+ found.set(keyOf(registration), registration);
104
+ for (const declaration of this.declarationsOf(registration))
105
+ for (const named of this.needsOf(declaration).owners) visit(named);
106
+ };
107
+ owners.forEach(visit);
108
+ return [...found.values()];
109
+ }
110
+
111
+ //? An edge closing a cycle is left out: a piece imported back by one it imports reads an unset binding at load.
112
+ piecesBefore(owner: RuntimeOwner): { libs: RuntimeOwner[]; named: RuntimeOwner[] } {
113
+ const libs = this.declarationsOf(owner).filter(({ scope }) => scope !== owner.scope);
114
+ const named = new Map<string, RuntimeOwner>();
115
+ for (const need of this.needsOf(owner).owners) {
116
+ const registration = this.registrationOf(need);
117
+ if (!registration || keyOf(registration) === keyOf(owner)) continue;
118
+ if (this.closureOf([registration]).some((reached) => keyOf(reached) === keyOf(owner))) continue;
119
+ named.set(keyOf(registration), registration);
120
+ }
121
+ return { libs, named: [...named.values()] };
122
+ }
123
+ }
@@ -0,0 +1,116 @@
1
+ import ts from "typescript";
2
+ import { type RuntimeConstantEntry, RuntimeConstantFacts } from "./runtimeConstantFacts";
3
+ import type { RuntimeNameTable, RuntimeOwner } from "./runtimeNameTable";
4
+ import { climb, memberName, type PositionedProblem, problemAt, sortedProblems, staticName } from "./runtimeSyntax";
5
+ import type { RuntimeUseProblem, RuntimeUseReason } from "./runtimeUse";
6
+
7
+ export interface RuntimeConstantName {
8
+ name: string;
9
+ owner: RuntimeOwner;
10
+ file: string;
11
+ //? The object `ConstantRegistry.buildModel` returns, which only the model's registration piece exports.
12
+ model: boolean;
13
+ }
14
+
15
+ export type RuntimeConstantRead =
16
+ | ({ kind: "member"; start: number; end: number } & RuntimeConstantName)
17
+ | { kind: "destructure"; start: number; end: number; keys: ({ key: string } & RuntimeConstantName)[] };
18
+
19
+ export interface RuntimeConstantUse {
20
+ reads: RuntimeConstantRead[];
21
+ imports: RuntimeOwner[];
22
+ problems: RuntimeUseProblem[];
23
+ }
24
+
25
+ export class RuntimeConstantReads {
26
+ readonly #source: ts.SourceFile;
27
+ readonly #fileName: string;
28
+ readonly #consumer: RuntimeNameTable | null;
29
+ readonly #recording: () => boolean;
30
+ readonly #reads = new Map<number, RuntimeConstantRead>();
31
+ readonly #imports = new Map<string, RuntimeOwner>();
32
+ readonly #problems: PositionedProblem[] = [];
33
+
34
+ constructor(source: ts.SourceFile, fileName: string, consumer: RuntimeNameTable | null, recording: () => boolean) {
35
+ this.#source = source;
36
+ this.#fileName = fileName;
37
+ this.#consumer = consumer;
38
+ this.#recording = recording;
39
+ }
40
+
41
+ get use(): RuntimeConstantUse {
42
+ return {
43
+ reads: [...this.#reads.values()].sort((a, b) => a.start - b.start),
44
+ imports: [...this.#imports.values()],
45
+ problems: sortedProblems([...this.#problems]),
46
+ };
47
+ }
48
+
49
+ imported(specifier: string) {
50
+ const owner = RuntimeConstantFacts.ownerOf(specifier, this.#fileName);
51
+ if (owner) this.#imports.set(`${owner.scope}/${owner.module}`, owner);
52
+ }
53
+
54
+ follow(node: ts.Expression, scope: string) {
55
+ const { current, parent } = climb(node);
56
+ const access =
57
+ (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === current
58
+ ? parent
59
+ : null;
60
+ if (access) this.#member(access, scope);
61
+ else if (ts.isVariableDeclaration(parent) && parent.initializer === current)
62
+ this.#destructure(parent, current, scope);
63
+ else this.problem("passed-on", current, "the constants are handed on whole");
64
+ }
65
+
66
+ #member(access: ts.PropertyAccessExpression | ts.ElementAccessExpression, scope: string) {
67
+ const name = memberName(access);
68
+ const entry = name === null ? null : this.#consumer?.constantOf(scope, name);
69
+ if (name === null) this.problem("computed-access", access, "the constant is picked at run time");
70
+ else if (!entry) this.problem("unknown-name", access, `${name} is not a constant ${scope} hands out`);
71
+ else if (entry.type === "namespace") this.follow(access, entry.scope);
72
+ else {
73
+ const [start, end] = [access.getStart(this.#source), access.end];
74
+ this.#read({ kind: "member", start, end, ...RuntimeConstantReads.#nameOf(name, entry) });
75
+ }
76
+ }
77
+
78
+ problem(reason: RuntimeUseReason, node: ts.Node, why: string) {
79
+ if (!this.#recording()) return;
80
+ const found = problemAt(this.#source, reason, node, why);
81
+ if (!this.#problems.some(({ position }) => position === found.position)) this.#problems.push(found);
82
+ }
83
+
84
+ #destructure(declaration: ts.VariableDeclaration, initializer: ts.Expression, scope: string) {
85
+ const list = declaration.parent;
86
+ const statement = list.parent;
87
+ const exported =
88
+ ts.isVariableStatement(statement) &&
89
+ !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
90
+ const pattern = declaration.name;
91
+ if (exported || !(list.flags & ts.NodeFlags.Const) || !ts.isObjectBindingPattern(pattern))
92
+ return this.problem("passed-on", declaration, "the constants are held whole under another name");
93
+ const keys: ({ key: string } & RuntimeConstantName)[] = [];
94
+ for (const element of pattern.elements) {
95
+ const key = element.propertyName ?? element.name;
96
+ const name = ts.isIdentifier(key) ? key.text : staticName(key);
97
+ const entry = name === null ? null : this.#consumer?.constantOf(scope, name);
98
+ if (element.dotDotDotToken || name === null || !ts.isIdentifier(element.name))
99
+ return this.problem("hidden-by-destructuring", element, "a rest, computed or nested key hides names");
100
+ if (!entry) return this.problem("unknown-name", element, `${name} is not a constant ${scope} hands out`);
101
+ if (entry.type === "namespace")
102
+ return this.problem("passed-on", element, `${name} holds ${entry.scope}'s constants whole`);
103
+ keys.push({ key: name, ...RuntimeConstantReads.#nameOf(name, entry) });
104
+ }
105
+ this.#read({ kind: "destructure", start: initializer.getStart(this.#source), end: initializer.end, keys });
106
+ }
107
+
108
+ #read(read: RuntimeConstantRead) {
109
+ if (this.#recording()) this.#reads.set(read.start, read);
110
+ }
111
+
112
+ static #nameOf(name: string, entry: Exclude<RuntimeConstantEntry, { type: "namespace" }>): RuntimeConstantName {
113
+ const { scope, module, file } = entry.fact;
114
+ return { name, owner: { scope, module }, file, model: entry.type === "model" };
115
+ }
116
+ }
@@ -0,0 +1,190 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import ts from "typescript";
4
+ import { RuntimeImports } from "./runtimeImports";
5
+
6
+ const files = [
7
+ "apps/demo/ui/Card.tsx",
8
+ "apps/demo/lib/memo/Memo.Zone.tsx",
9
+ "apps/demo/lib/st/inner.ts",
10
+ "libs/kit/ui/deep/inner/Panel.tsx",
11
+ ];
12
+ const targets = [
13
+ "apps/demo/client",
14
+ "apps/demo/lib/useClient",
15
+ "apps/demo/lib/usePage",
16
+ "apps/demo/lib/st",
17
+ "apps/demo/lib/sig",
18
+ "apps/demo/lib/__client/memo.st",
19
+ "libs/kit/client",
20
+ "libs/kit/lib/useClient",
21
+ ];
22
+ const tails = ["", ".ts", ".tsx", ".js", ".jsx", "/index", "/index.ts", "/index.js"];
23
+ const frameworks = ["akanjs/store", "akanjs/client", "akanjs/./store", "akanjs/client/index", "akanjs/store/baseSt"];
24
+
25
+ const spellingsOf = (file: string, target: string) => {
26
+ const [root = "", scope = "", ...rest] = target.split("/");
27
+ const relative = path.posix.relative(path.posix.dirname(file), target);
28
+ const dotted = relative.startsWith(".") ? relative : `./${relative}`;
29
+ return [
30
+ ...tails.flatMap((tail) => [
31
+ `@${target}${tail}`,
32
+ `@${root}/${scope}//${rest.join("/")}${tail}`,
33
+ `@${root}/${scope}/./${rest.join("/")}${tail}`,
34
+ `${dotted}${tail}`,
35
+ `${dotted.replace(/\//g, "//")}${tail}`,
36
+ `${dotted}/../${path.posix.basename(target)}${tail}`,
37
+ `./ /..${dotted.slice(1)}${tail}`,
38
+ ]),
39
+ ".",
40
+ "..",
41
+ "./",
42
+ "../.",
43
+ ];
44
+ };
45
+
46
+ const escapedOf = (spelling: string) => {
47
+ const at = spelling.search(/[a-z](?=[^/]*$)/);
48
+ if (at < 0) return [spelling];
49
+ const code = spelling.charCodeAt(at);
50
+ const swap = (escape: string) => `${spelling.slice(0, at)}${escape}${spelling.slice(at + 1)}`;
51
+ return [
52
+ spelling,
53
+ swap(`\\u${code.toString(16).padStart(4, "0")}`),
54
+ swap(`\\u{${code.toString(16)}}`),
55
+ swap(`\\x${code.toString(16)}`),
56
+ swap(`\\\n${spelling[at]}`),
57
+ swap(`\\\r\n${spelling[at]}`),
58
+ ];
59
+ };
60
+
61
+ const statementsOf = (literal: string) => [
62
+ `import { st } from ${literal};\n`,
63
+ `export * from ${literal};\n`,
64
+ `import client = require(${literal});\n`,
65
+ `const client = require(${literal});\n`,
66
+ `export const load = () => import(${literal});\n`,
67
+ `import ${literal};\n`,
68
+ ];
69
+
70
+ const specifierOf = (file: string, text: string) => {
71
+ let found: string | null = null;
72
+ const visit = (node: ts.Node) => {
73
+ if (found === null && ts.isStringLiteralLike(node)) found = node.text;
74
+ ts.forEachChild(node, visit);
75
+ };
76
+ visit(ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX));
77
+ return found as string | null;
78
+ };
79
+
80
+ describe("RuntimeImports", () => {
81
+ test("never skips a file whose specifier, in any spelling, the specifier reader resolves", () => {
82
+ let resolved = 0;
83
+ const skipped: string[] = [];
84
+ for (const file of files)
85
+ for (const spelling of [...targets.flatMap((target) => spellingsOf(file, target)), ...frameworks])
86
+ for (const escaped of escapedOf(spelling))
87
+ for (const quote of ['"', "'", "`"])
88
+ for (const text of statementsOf(`${quote}${escaped}${quote}`)) {
89
+ const specifier = specifierOf(file, `// a \`note\`, it's\n${text}`);
90
+ if (specifier === null || !RuntimeImports.targetOf(specifier, file)) continue;
91
+ resolved++;
92
+ if (!RuntimeImports.mayUseRuntime(`// a \`note\`, it's\n${text}`, file)) skipped.push(`${file}: ${text}`);
93
+ }
94
+ expect(skipped).toEqual([]);
95
+ expect(resolved).toBeGreaterThan(20000);
96
+ });
97
+
98
+ test("reads a specifier through its extension, index, doubled slashes and dot segments", () => {
99
+ const file = "apps/demo/lib/memo/Memo.Zone.tsx";
100
+ expect(
101
+ [
102
+ "@apps/demo/client.js",
103
+ "@apps/demo//client",
104
+ "@apps/demo/./lib/../client/index.tsx",
105
+ "../useClient.js",
106
+ "../__client/memo.st",
107
+ "../__client/_base.fetch",
108
+ "../__client/_st",
109
+ "../__client/_useClient.ts",
110
+ "akanjs/./store",
111
+ "akanjs/store/baseSt",
112
+ "akanjs/client/native/haptics",
113
+ "akanjs/fetch",
114
+ "@apps/demo/lib/cnst",
115
+ ].map((specifier) => RuntimeImports.targetOf(specifier, file)?.kind ?? null),
116
+ ).toEqual([
117
+ "client",
118
+ "client",
119
+ "client",
120
+ "useClient",
121
+ "piece",
122
+ "piece",
123
+ "_st",
124
+ "_useClient",
125
+ "framework-store",
126
+ "framework-deep",
127
+ null,
128
+ "framework-fetch",
129
+ null,
130
+ ]);
131
+ });
132
+
133
+ test("names the agent entry apart, and lists as its screen exports the files that import no store or fetch", async () => {
134
+ const kindOf = (specifier: string) => RuntimeImports.targetOf(specifier, "apps/demo/ui/Card.tsx")?.kind ?? null;
135
+ expect(
136
+ [
137
+ "akanjs/store/agent",
138
+ "akanjs/store/agent/index.ts",
139
+ "akanjs/store/agent/ScreenSettle",
140
+ "akanjs/client/agent",
141
+ ].map(kindOf),
142
+ ).toEqual(["framework-agent", "framework-agent", "framework-deep", "framework-deep"]);
143
+ const use = (name: string) => RuntimeImports.useOf({ scope: "apps/demo", kind: "framework-agent" }, name, false);
144
+ expect([use("ScreenSettle"), use("AgentBridge"), use("somethingNew")]).toEqual([
145
+ null,
146
+ { reason: "whole-runtime-import", why: "a framework internal may hand out the whole runtime" },
147
+ { reason: "whole-runtime-import", why: "a framework internal may hand out the whole runtime" },
148
+ ]);
149
+
150
+ const dir = path.join(import.meta.dir, "../../../akanjs/store/agent");
151
+ const index = await Bun.file(path.join(dir, "index.ts")).text();
152
+ const files = new Map<string, { imports: string[]; exports: string[]; text: string }>();
153
+ for (const [, name = ""] of index.matchAll(/export \* from "\.\/(\w+)";/g)) {
154
+ const text = await Bun.file(path.join(dir, `${name}.ts`)).text();
155
+ const source = ts.createSourceFile(name, text, ts.ScriptTarget.Latest);
156
+ const imports = source.statements.flatMap((statement) => {
157
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) return [];
158
+ const clause = statement.importClause;
159
+ const named =
160
+ clause?.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : [];
161
+ const values = named.filter((element) => !element.isTypeOnly).map((element) => element.name.text);
162
+ if (clause?.isTypeOnly || (clause && !clause.name && named.length && !values.length)) return [];
163
+ const specifier = statement.moduleSpecifier.text;
164
+ return specifier === "akanjs/client" && values.join() === "router" ? [] : [specifier];
165
+ });
166
+ const exports = source.statements.flatMap((statement) => {
167
+ const exported =
168
+ ts.canHaveModifiers(statement) &&
169
+ ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
170
+ if (!exported) return [];
171
+ if (ts.isVariableStatement(statement))
172
+ return statement.declarationList.declarations.map((declaration) => declaration.name.getText(source));
173
+ return [(statement as ts.DeclarationStatement).name?.text ?? "default"];
174
+ });
175
+ files.set(name, { imports, exports, text });
176
+ }
177
+ expect(files.size).toBe(12);
178
+ const outside = new Set(["akanjs/base", "use-agentic"]);
179
+ for (let size = -1; size !== files.size; ) {
180
+ size = files.size;
181
+ for (const [name, { imports }] of files)
182
+ if (!imports.every((specifier) => outside.has(specifier) || files.has(specifier.replace(/^\.\//, ""))))
183
+ files.delete(name);
184
+ }
185
+ expect([...files.values()].filter(({ text }) => /globalThis|Symbol\.for\(|import\(/.test(text))).toEqual([]);
186
+ expect([...files.values()].flatMap(({ exports }) => exports).sort()).toEqual(
187
+ [...RuntimeImports.agentScreenNames].sort(),
188
+ );
189
+ });
190
+ });