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

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
@@ -0,0 +1,537 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import type { PackageEntry } from "./barrelAnalyzer";
4
+ import {
5
+ type ObjectImportCandidate as Candidate,
6
+ type ObjectMemberTarget as MemberTarget,
7
+ ObjectImportEdits,
8
+ type ObjectMemberUse,
9
+ } from "./objectImportEdits";
10
+ import { ObjectModule, type ObjectModuleClause, type ObjectModuleFacts, type ObjectShape } from "./objectModule";
11
+ import { ObjectModuleAnalyzer, resolveModuleFile } from "./objectModuleAnalyzer";
12
+ import { hasUseClientDirective } from "./rscUseClientTransform";
13
+
14
+ export type ObjectKeepReason =
15
+ | ObjectModuleClause
16
+ | "passed-on"
17
+ | "computed-member"
18
+ | "spread"
19
+ | "rendered-or-called"
20
+ | "method-call"
21
+ | "written"
22
+ | "shadowed"
23
+ | "unresolved-member"
24
+ | "server-boundary";
25
+
26
+ export interface ObjectImportKept {
27
+ object: string;
28
+ file: string;
29
+ line: number;
30
+ reason: ObjectKeepReason;
31
+ }
32
+
33
+ export interface ObjectImportNarrowed {
34
+ object: string;
35
+ file: string;
36
+ /** Each member path the importer reached, `Zone.View` or `Util`. */
37
+ members: string[];
38
+ }
39
+
40
+ export interface ObjectMemberRewrite {
41
+ contents: string | null;
42
+ clientImporter: boolean;
43
+ narrowed: ObjectImportNarrowed[];
44
+ kept: ObjectImportKept[];
45
+ /** The object modules the answer read and the member files whose exports it consulted. */
46
+ read: string[];
47
+ }
48
+
49
+ export interface ObjectMemberImportsOptions {
50
+ resolve: (specifier: string, importer: string) => Promise<string | null>;
51
+ specifierOf?: (file: string, importer: string) => string;
52
+ keepLines?: boolean;
53
+ }
54
+
55
+ const ASSIGN_OPERATOR_FIRST = ts.SyntaxKind.FirstAssignment;
56
+ const ASSIGN_OPERATOR_LAST = ts.SyntaxKind.LastAssignment;
57
+ const NAMED_IMPORT_RE = /\bimport\s+(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*["'][^"']+["']/g;
58
+ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
59
+ const AKANJS_NODE_MODULE_RE = /[\\/]node_modules[\\/]akanjs[\\/]/;
60
+ const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
61
+
62
+ const escapeRe = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
63
+
64
+ //* Rewrites an import of an object module's object to imports of the members the importer writes out
65
+ //* (`Memo.Zone.View`, `<Field.Text />`, `const { Util } = Memo`); any other use keeps the whole object for that file.
66
+ export class ObjectMemberImports {
67
+ static readonly keyPrefix = "object:";
68
+ readonly #modules: ObjectModuleAnalyzer;
69
+ readonly #resolve: ObjectMemberImportsOptions["resolve"];
70
+ readonly #specifierOf: NonNullable<ObjectMemberImportsOptions["specifierOf"]>;
71
+ readonly #keepLines: boolean;
72
+
73
+ constructor(
74
+ { resolve, specifierOf = ObjectMemberImports.absoluteSpecifier, keepLines = false }: ObjectMemberImportsOptions,
75
+ modules = new ObjectModuleAnalyzer(),
76
+ ) {
77
+ this.#resolve = resolve;
78
+ this.#specifierOf = specifierOf;
79
+ this.#keepLines = keepLines;
80
+ this.#modules = modules;
81
+ }
82
+
83
+ get modules() {
84
+ return this.#modules;
85
+ }
86
+
87
+ static absoluteSpecifier(file: string) {
88
+ return file.split(path.sep).join("/");
89
+ }
90
+
91
+ static resolverOf(
92
+ resolvePackage: (pkgName: string) => Promise<PackageEntry | null>,
93
+ ): ObjectMemberImportsOptions["resolve"] {
94
+ const packages = new Map<string, Promise<string | null>>();
95
+ return async (specifier, importer) => {
96
+ let resolved: Promise<string | null> | undefined;
97
+ if (ObjectMemberImports.#isPathSpecifier(specifier)) resolved = resolveModuleFile(importer, specifier);
98
+ else {
99
+ resolved = packages.get(specifier);
100
+ if (!resolved) {
101
+ resolved = resolvePackage(specifier).then((pkg) => pkg?.entryFile ?? null);
102
+ packages.set(specifier, resolved);
103
+ }
104
+ }
105
+ const file = await resolved;
106
+ return file && (!NODE_MODULES_RE.test(file) || AKANJS_NODE_MODULE_RE.test(file)) ? file : null;
107
+ };
108
+ }
109
+
110
+ static keyOf(file: string, object: string) {
111
+ return `${ObjectMemberImports.keyPrefix}${file}#${object}`;
112
+ }
113
+
114
+ static parseKey(key: string): { file: string; object: string } | null {
115
+ if (!key.startsWith(ObjectMemberImports.keyPrefix)) return null;
116
+ const hash = key.lastIndexOf("#");
117
+ return { file: key.slice(ObjectMemberImports.keyPrefix.length, hash), object: key.slice(hash + 1) };
118
+ }
119
+
120
+ async rewrite(source: string, importer: string): Promise<ObjectMemberRewrite | null> {
121
+ const locals = ObjectMemberImports.#candidateLocals(source);
122
+ if (locals.size === 0) return null;
123
+ const sourceFile = ts.createSourceFile(
124
+ importer,
125
+ source,
126
+ ts.ScriptTarget.Latest,
127
+ true,
128
+ ObjectModule.scriptKindOf(importer),
129
+ );
130
+ const candidates = ObjectMemberImports.#importsOf(sourceFile, locals);
131
+ if (candidates.size === 0) return null;
132
+ const read = new Set<string>();
133
+ const facts = new Map<Candidate, { facts: ObjectModuleFacts; shape: ObjectShape }>();
134
+ for (const candidate of candidates.values()) {
135
+ const specifier = (candidate.declaration.moduleSpecifier as ts.StringLiteral).text;
136
+ const file = await this.#resolve(specifier, importer);
137
+ if (!file) continue;
138
+ const moduleFacts = await this.#modules.facts(file);
139
+ const shape = moduleFacts?.objects.get(candidate.imported);
140
+ if (!moduleFacts || !shape || ![...shape.members.values()].some(Boolean)) continue;
141
+ candidate.file = file;
142
+ read.add(file);
143
+ facts.set(candidate, { facts: moduleFacts, shape });
144
+ }
145
+ if (facts.size === 0) return null;
146
+ ObjectMemberImports.#classifyUses(sourceFile, new Map([...facts.keys()].map((c) => [c.local, c])));
147
+ const clientImporter = hasUseClientDirective(source);
148
+ const result: ObjectMemberRewrite = { contents: null, clientImporter, narrowed: [], kept: [], read: [] };
149
+ const plan = new ObjectImportEdits(source, sourceFile, this.#keepLines);
150
+ for (const [candidate, { facts: moduleFacts, shape }] of facts) {
151
+ const file = candidate.file ?? "";
152
+ const lineOf = (node: ts.Node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
153
+ const keep = (reason: ObjectKeepReason, node: ts.Node) =>
154
+ result.kept.push({ object: candidate.imported, file, line: lineOf(node), reason });
155
+ if (moduleFacts.failed) {
156
+ keep(moduleFacts.failed.clause, candidate.element);
157
+ continue;
158
+ }
159
+ if (candidate.shadowed) {
160
+ keep("shadowed", candidate.element);
161
+ continue;
162
+ }
163
+ if (candidate.keep) {
164
+ keep(candidate.keep.reason, candidate.keep.node);
165
+ continue;
166
+ }
167
+ const targets = await this.#targetsOf(candidate, moduleFacts, shape, importer, clientImporter, read);
168
+ if ("reason" in targets) {
169
+ keep(targets.reason, targets.node);
170
+ continue;
171
+ }
172
+ plan.narrow(candidate, targets, (target) => target.bare ?? this.#specifierOf(target.file, importer));
173
+ result.narrowed.push({
174
+ object: candidate.imported,
175
+ file,
176
+ members: [...new Set(targets.map(({ written }) => written))].sort(),
177
+ });
178
+ }
179
+ result.read = [...read];
180
+ result.contents = plan.apply();
181
+ return result;
182
+ }
183
+
184
+ async fingerprint(file: string, object: string, members: string[], clientImporter: boolean): Promise<string> {
185
+ const moduleFacts = await this.#modules.facts(file);
186
+ const shape = moduleFacts?.objects.get(object);
187
+ const targets = await Promise.all(
188
+ members.map(async (member) => {
189
+ if (!moduleFacts || !shape) return null;
190
+ const called = member.endsWith("()");
191
+ const memberPath = (called ? member.slice(0, -2) : member).split(".");
192
+ const target = await this.#targetOf(file, moduleFacts, shape, memberPath, file, clientImporter, new Set());
193
+ return await this.#calledTargetOf(target, memberPath, called);
194
+ }),
195
+ );
196
+ return Bun.hash(JSON.stringify([moduleFacts?.failed ?? null, targets])).toString(36);
197
+ }
198
+
199
+ async filesOf(file: string): Promise<string[]> {
200
+ const moduleFacts = await this.#modules.facts(file);
201
+ const files = new Set([file]);
202
+ for (const shape of moduleFacts?.objects.values() ?? [])
203
+ for (const member of shape.members.values()) {
204
+ if (!member || !ObjectMemberImports.#isPathSpecifier(member.specifier)) continue;
205
+ const resolved = await resolveModuleFile(file, member.specifier);
206
+ if (resolved) files.add(resolved);
207
+ }
208
+ return [...files];
209
+ }
210
+
211
+ async digest(file: string): Promise<string> {
212
+ const moduleFacts = await this.#modules.facts(file);
213
+ const objects = [...(moduleFacts?.objects ?? [])].map(([name, shape]) => [
214
+ name,
215
+ shape.open,
216
+ [...shape.members].map(([key, member]) => [key, member?.specifier ?? null, member?.imported ?? null]),
217
+ ]);
218
+ const exports = await Promise.all(
219
+ (await this.filesOf(file)).map(async (member) => {
220
+ const scanned = await this.#modules.exportsOf(member);
221
+ const thisFree = [...(await this.#modules.thisFreeOf(member))].sort();
222
+ return [member, scanned ? [[...scanned.names].sort(), scanned.star, scanned.useClient, thisFree] : null];
223
+ }),
224
+ );
225
+ return Bun.hash(JSON.stringify([moduleFacts?.useClient, moduleFacts?.failed, objects, exports])).toString(36);
226
+ }
227
+
228
+ async #targetsOf(
229
+ candidate: Candidate,
230
+ moduleFacts: ObjectModuleFacts,
231
+ shape: ObjectShape,
232
+ importer: string,
233
+ clientImporter: boolean,
234
+ read: Set<string>,
235
+ ): Promise<ObjectMemberUse[] | { reason: ObjectKeepReason; node: ts.Node }> {
236
+ const file = candidate.file ?? "";
237
+ const targets: ObjectMemberUse[] = [];
238
+ const uses = [
239
+ ...candidate.paths,
240
+ ...candidate.destructures.flatMap(({ keys, node }) =>
241
+ keys.map((key) => ({ path: [key], nodes: [node], called: false })),
242
+ ),
243
+ ];
244
+ for (const use of uses) {
245
+ const found = await this.#targetOf(file, moduleFacts, shape, use.path, importer, clientImporter, read);
246
+ const target = await this.#calledTargetOf(found, use.path, use.called);
247
+ const node = use.nodes[0] ?? candidate.element;
248
+ if (typeof target === "string") return { reason: target, node };
249
+ targets.push({
250
+ member: use.path.slice(0, target.depth).join("."),
251
+ written: `${use.path.join(".")}${use.called ? "()" : ""}`,
252
+ target,
253
+ nodes: use.nodes,
254
+ });
255
+ }
256
+ return targets;
257
+ }
258
+
259
+ //? Called through the object, a member gets the object as `this`; imported alone it would get none.
260
+ async #calledTargetOf(
261
+ target: MemberTarget | ObjectKeepReason,
262
+ memberPath: string[],
263
+ called: boolean,
264
+ ): Promise<MemberTarget | ObjectKeepReason> {
265
+ if (typeof target === "string" || !called || target.depth !== memberPath.length) return target;
266
+ if (target.imported !== "*" && (await this.#modules.thisFreeOf(target.file)).has(target.imported)) return target;
267
+ return "method-call";
268
+ }
269
+
270
+ async #targetOf(
271
+ file: string,
272
+ moduleFacts: ObjectModuleFacts,
273
+ shape: ObjectShape,
274
+ memberPath: string[],
275
+ importer: string,
276
+ clientImporter: boolean,
277
+ read: Set<string>,
278
+ ): Promise<MemberTarget | ObjectKeepReason> {
279
+ const [name, inner] = memberPath;
280
+ const nested = inner === undefined ? undefined : shape.members.get(`${name}.${inner}`);
281
+ const member = nested ?? (name === undefined ? undefined : shape.members.get(name));
282
+ if (!member) return "unresolved-member";
283
+ const bare = ObjectMemberImports.#isPathSpecifier(member.specifier) ? null : member.specifier;
284
+ const target = bare
285
+ ? ObjectMemberImports.#sameBareTarget(bare, file, importer)
286
+ : await resolveModuleFile(file, member.specifier);
287
+ if (!target) return "unresolved-member";
288
+ const exports = await this.#modules.exportsOf(target);
289
+ if (!exports) return "unresolved-member";
290
+ read.add(target);
291
+ if (moduleFacts.useClient && !clientImporter && !exports.useClient) return "server-boundary";
292
+ if (nested) return { file: target, bare, imported: member.imported, depth: 2 };
293
+ if (member.imported !== "*") return { file: target, bare, imported: member.imported, depth: 1 };
294
+ if (inner !== undefined && exports.names.has(inner)) return { file: target, bare, imported: inner, depth: 2 };
295
+ return { file: target, bare, imported: "*", depth: 1 };
296
+ }
297
+
298
+ //? A bare member is written as the object module wrote it only when the importer resolves it to the same file.
299
+ static #sameBareTarget(specifier: string, objectFile: string, importer: string): string | null {
300
+ try {
301
+ const fromObject = Bun.resolveSync(specifier, path.dirname(objectFile));
302
+ const fromImporter = Bun.resolveSync(specifier, path.dirname(importer));
303
+ return fromObject === fromImporter ? fromObject : null;
304
+ } catch {
305
+ return null;
306
+ }
307
+ }
308
+
309
+ static #isPathSpecifier(specifier: string) {
310
+ return specifier.startsWith(".") || path.isAbsolute(specifier);
311
+ }
312
+
313
+ static #candidateLocals(source: string): Set<string> {
314
+ const locals = new Set<string>();
315
+ for (const match of source.matchAll(NAMED_IMPORT_RE)) {
316
+ for (const raw of (match[1] ?? "").split(",")) {
317
+ const item = raw.trim();
318
+ if (!item || item.startsWith("type ")) continue;
319
+ const local =
320
+ item
321
+ .split(/\sas\s/)
322
+ .pop()
323
+ ?.trim() ?? "";
324
+ if (!IDENTIFIER_RE.test(local)) continue;
325
+ const name = escapeRe(local);
326
+ if (new RegExp(`(?<![\\w$.])${name}\\s*\\??\\.\\s*[A-Za-z_$]|=\\s*${name}(?![\\w$])`).test(source))
327
+ locals.add(local);
328
+ }
329
+ }
330
+ return locals;
331
+ }
332
+
333
+ static #importsOf(sourceFile: ts.SourceFile, locals: Set<string>): Map<string, Candidate> {
334
+ const candidates = new Map<string, Candidate>();
335
+ for (const statement of sourceFile.statements) {
336
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
337
+ if (statement.attributes) continue;
338
+ const clause = statement.importClause;
339
+ if (!clause || clause.phaseModifier === ts.SyntaxKind.TypeKeyword) continue;
340
+ const bindings = clause.namedBindings;
341
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
342
+ for (const element of bindings.elements) {
343
+ const local = element.name.text;
344
+ if (element.isTypeOnly || !locals.has(local)) continue;
345
+ if (element.propertyName && !ts.isIdentifier(element.propertyName)) continue;
346
+ candidates.set(local, {
347
+ declaration: statement,
348
+ element,
349
+ local,
350
+ imported: (element.propertyName ?? element.name).text,
351
+ shadowed: candidates.has(local),
352
+ typeUse: false,
353
+ keep: null,
354
+ paths: [],
355
+ destructures: [],
356
+ });
357
+ }
358
+ }
359
+ return candidates;
360
+ }
361
+
362
+ static #classifyUses(sourceFile: ts.SourceFile, candidates: Map<string, Candidate>) {
363
+ const visit = (node: ts.Node) => {
364
+ if (ts.isIdentifier(node)) {
365
+ const candidate = candidates.get(node.text);
366
+ if (candidate) ObjectMemberImports.#classify(node, candidate);
367
+ }
368
+ ts.forEachChild(node, visit);
369
+ };
370
+ visit(sourceFile);
371
+ }
372
+
373
+ static #classify(id: ts.Identifier, candidate: Candidate) {
374
+ if (id === candidate.element.name || ObjectMemberImports.#isPropertyName(id)) return;
375
+ if (ObjectMemberImports.#isDeclarationName(id)) {
376
+ candidate.shadowed = true;
377
+ return;
378
+ }
379
+ if (ObjectMemberImports.#isType(id)) {
380
+ candidate.typeUse = true;
381
+ return;
382
+ }
383
+ const keep = (reason: ObjectKeepReason, node: ts.Node = id) => {
384
+ candidate.keep ??= { reason, node };
385
+ };
386
+ const nodes: ts.Expression[] = [];
387
+ let current: ts.Expression = id;
388
+ while (nodes.length < 2) {
389
+ const parent: ts.Node = current.parent;
390
+ if (!ts.isPropertyAccessExpression(parent) || parent.expression !== current || parent.questionDotToken) break;
391
+ if (!ts.isIdentifier(parent.name)) break;
392
+ nodes.push(parent);
393
+ current = parent;
394
+ }
395
+ const last = nodes.at(-1);
396
+ if (last) {
397
+ if (nodes.some((node) => ObjectMemberImports.#isWritten(node))) return keep("written");
398
+ candidate.paths.push({
399
+ path: nodes.map((node) => ((node as ts.PropertyAccessExpression).name as ts.Identifier).text),
400
+ nodes,
401
+ called: ObjectMemberImports.#isCallee(last),
402
+ });
403
+ return;
404
+ }
405
+ const parent = id.parent;
406
+ if (ts.isVariableDeclaration(parent) && parent.initializer === id && ts.isObjectBindingPattern(parent.name)) {
407
+ const keys: string[] = [];
408
+ for (const element of parent.name.elements) {
409
+ if (element.dotDotDotToken) return keep("spread");
410
+ const name = element.propertyName ?? element.name;
411
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) return keep("computed-member");
412
+ keys.push(name.text);
413
+ }
414
+ if (keys.length === 0) return keep("passed-on");
415
+ candidate.destructures.push({ node: id, keys });
416
+ return;
417
+ }
418
+ if (ts.isElementAccessExpression(parent) && parent.expression === id) return keep("computed-member");
419
+ if (ts.isSpreadElement(parent) || ts.isSpreadAssignment(parent) || ts.isJsxSpreadAttribute(parent))
420
+ return keep("spread");
421
+ if (ObjectMemberImports.#isRenderedOrCalled(id)) return keep("rendered-or-called");
422
+ if (ObjectMemberImports.#isWritten(id)) return keep("written");
423
+ keep("passed-on");
424
+ }
425
+
426
+ static #isRenderedOrCalled(id: ts.Identifier) {
427
+ const parent = id.parent;
428
+ if (ts.isJsxOpeningElement(parent) || ts.isJsxSelfClosingElement(parent) || ts.isJsxClosingElement(parent))
429
+ return parent.tagName === id;
430
+ if (ts.isCallExpression(parent) || ts.isNewExpression(parent)) return parent.expression === id;
431
+ return ts.isTaggedTemplateExpression(parent) && parent.tag === id;
432
+ }
433
+
434
+ static #isCallee(node: ts.Node) {
435
+ let current = node;
436
+ while (ObjectMemberImports.#isTransparent(current.parent)) current = current.parent;
437
+ const parent = current.parent;
438
+ if (ts.isCallExpression(parent)) return parent.expression === current;
439
+ return ts.isTaggedTemplateExpression(parent) && parent.tag === current;
440
+ }
441
+
442
+ //? A node inside an array or object literal is written when that literal is a destructuring target.
443
+ static #isWritten(node: ts.Node): boolean {
444
+ const parent = node.parent;
445
+ if (ObjectMemberImports.#isTransparent(parent)) return ObjectMemberImports.#isWritten(parent);
446
+ if (ts.isBinaryExpression(parent))
447
+ return (
448
+ parent.left === node &&
449
+ parent.operatorToken.kind >= ASSIGN_OPERATOR_FIRST &&
450
+ parent.operatorToken.kind <= ASSIGN_OPERATOR_LAST
451
+ );
452
+ if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent))
453
+ return [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(parent.operator);
454
+ if (ts.isForInStatement(parent) || ts.isForOfStatement(parent)) return parent.initializer === node;
455
+ if (ts.isPropertyAssignment(parent))
456
+ return parent.initializer === node && ObjectMemberImports.#isWritten(parent.parent);
457
+ if (ts.isSpreadAssignment(parent)) return ObjectMemberImports.#isWritten(parent.parent);
458
+ if (ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent))
459
+ return ObjectMemberImports.#isWritten(parent);
460
+ return ts.isDeleteExpression(parent);
461
+ }
462
+
463
+ static #isTransparent(node: ts.Node) {
464
+ return (
465
+ ts.isParenthesizedExpression(node) ||
466
+ ts.isNonNullExpression(node) ||
467
+ ts.isAsExpression(node) ||
468
+ ts.isSatisfiesExpression(node) ||
469
+ ts.isTypeAssertionExpression(node)
470
+ );
471
+ }
472
+
473
+ static #isPropertyName(id: ts.Identifier) {
474
+ const parent = id.parent;
475
+ if (ts.isPropertyAccessExpression(parent)) return parent.name === id;
476
+ if (ts.isQualifiedName(parent)) return parent.right === id;
477
+ if (ts.isBindingElement(parent)) return parent.propertyName === id;
478
+ if (ts.isImportSpecifier(parent)) return parent.propertyName === id;
479
+ if (ts.isExportSpecifier(parent)) return !!parent.propertyName && parent.name === id;
480
+ if (ts.isLabeledStatement(parent) || ts.isBreakOrContinueStatement(parent)) return true;
481
+ if (
482
+ ts.isPropertyAssignment(parent) ||
483
+ ts.isMethodDeclaration(parent) ||
484
+ ts.isPropertyDeclaration(parent) ||
485
+ ts.isPropertySignature(parent) ||
486
+ ts.isMethodSignature(parent) ||
487
+ ts.isGetAccessorDeclaration(parent) ||
488
+ ts.isSetAccessorDeclaration(parent) ||
489
+ ts.isEnumMember(parent) ||
490
+ ts.isJsxAttribute(parent)
491
+ )
492
+ return parent.name === id;
493
+ return false;
494
+ }
495
+
496
+ static #isDeclarationName(id: ts.Identifier) {
497
+ const parent = id.parent;
498
+ if (
499
+ ts.isVariableDeclaration(parent) ||
500
+ ts.isParameter(parent) ||
501
+ ts.isFunctionDeclaration(parent) ||
502
+ ts.isFunctionExpression(parent) ||
503
+ ts.isClassDeclaration(parent) ||
504
+ ts.isClassExpression(parent) ||
505
+ ts.isInterfaceDeclaration(parent) ||
506
+ ts.isTypeAliasDeclaration(parent) ||
507
+ ts.isEnumDeclaration(parent) ||
508
+ ts.isModuleDeclaration(parent) ||
509
+ ts.isTypeParameterDeclaration(parent) ||
510
+ ts.isImportClause(parent) ||
511
+ ts.isNamespaceImport(parent) ||
512
+ ts.isImportSpecifier(parent) ||
513
+ ts.isImportEqualsDeclaration(parent) ||
514
+ ts.isBindingElement(parent)
515
+ )
516
+ return parent.name === id;
517
+ return false;
518
+ }
519
+
520
+ static #isType(id: ts.Identifier) {
521
+ for (let node: ts.Node = id; node.parent; node = node.parent) {
522
+ const parent: ts.Node = node.parent;
523
+ if (ts.isExpressionWithTypeArguments(parent)) {
524
+ const heritage = parent.parent;
525
+ if (!ts.isHeritageClause(heritage)) return false;
526
+ const owner = heritage.parent;
527
+ return !(
528
+ heritage.token === ts.SyntaxKind.ExtendsKeyword &&
529
+ (ts.isClassDeclaration(owner) || ts.isClassExpression(owner))
530
+ );
531
+ }
532
+ if (ts.isTypeNode(parent)) return true;
533
+ if (ts.isStatement(parent) || ts.isSourceFile(parent)) return false;
534
+ }
535
+ return false;
536
+ }
537
+ }