@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,227 @@
1
+ import path from "node:path";
2
+ import type { BunPlugin } from "bun";
3
+
4
+ type ScopeDescriptors = Record<string, string>;
5
+
6
+ interface ScopeSignals {
7
+ //? Every name the scope's signal holds, with or without a literal.
8
+ names: string[];
9
+ literals: ScopeDescriptors;
10
+ }
11
+
12
+ interface ScopeRead {
13
+ file: string;
14
+ names?: string[];
15
+ read?: ScopeDescriptors;
16
+ failure?: string;
17
+ }
18
+
19
+ export interface SignalDescriptorsOptions {
20
+ onUnread?: (reason: string) => void;
21
+ timeoutMs?: number;
22
+ //? The pieces a scope's `lib/useClient.ts` takes descriptors from, so it holds none of theirs again.
23
+ takenFromPieces?: (absPath: string) => string[] | null;
24
+ }
25
+
26
+ //* Bun runs a macro module again on each bundler thread, so a build of many pieces reads each scope's signal once here.
27
+ export class SignalDescriptors {
28
+ static readonly readTimeoutMs = 60_000;
29
+ static readonly #pieceFile = /[\\/]lib[\\/]__client[\\/][^\\/]+\.fetch\.ts$/;
30
+ static readonly #wholeFile = /[\\/]lib[\\/]useClient\.ts$/;
31
+ static readonly #macroImport = 'import { getSerializedSignalOf } from "../sig" with { type: "macro" };';
32
+ static readonly #macroCall = /\bgetSerializedSignalOf\("([^"\\]+)"\)/g;
33
+ static readonly #wholeImport = 'import { getSerializedSignal } from "./sig" with { type: "macro" };';
34
+ static readonly #wholeCall = "getSerializedSignal()";
35
+ readonly #workspaceRoot: string;
36
+ readonly #sigFiles: string[];
37
+ readonly #onUnread: (reason: string) => void;
38
+ readonly #timeoutMs: number;
39
+ readonly #takenFromPieces: (absPath: string) => string[] | null;
40
+ readonly #reads = new Map<string, Promise<ScopeSignals | null>>();
41
+ #env: Record<string, string> = {};
42
+
43
+ //? In a process of its own: a module imported into this one stays cached after its file changes.
44
+ //? JSON drops undefined, -0, NaN and holes, and a `"__proto__"` key sets a prototype: such a name keeps its macro.
45
+ static #readScript(sigFiles: string[]) {
46
+ return `
47
+ process.on("disconnect", () => process.exit(1));
48
+ const send = (message) => new Promise((resolve) => process.send(message, undefined, undefined, resolve));
49
+ const literalOf = (value) => {
50
+ try {
51
+ const text = JSON.stringify(value);
52
+ return Bun.deepEquals(JSON.parse(text), value, true) && !text.includes('"__proto__":') ? text : undefined;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ };
57
+ for (const file of ${JSON.stringify(sigFiles)}) {
58
+ try {
59
+ const { fetch, getSerializedSignalOf } = await import(file);
60
+ const names = ["base", ...Object.keys(fetch.ownSerializedSignal)];
61
+ const literals = names.map((name) => [name, literalOf(getSerializedSignalOf(name))]);
62
+ await send({ file, names, read: Object.fromEntries(literals.filter(([, literal]) => literal !== undefined)) });
63
+ } catch (error) {
64
+ await send({ file, failure: String(error?.message ?? error) });
65
+ }
66
+ }
67
+ process.exit(0);
68
+ `;
69
+ }
70
+
71
+ //? A macro module sees the build's `define`, so the process reading the signals gets each `process.env.<KEY>` of it.
72
+ static #envOf(define: Record<string, string> = {}): Record<string, string> {
73
+ return Object.fromEntries(
74
+ Object.entries(define).flatMap(([key, value]) => {
75
+ if (!key.startsWith("process.env.")) return [];
76
+ try {
77
+ const parsed: unknown = JSON.parse(value);
78
+ return typeof parsed === "string" ? [[key.slice("process.env.".length), parsed]] : [];
79
+ } catch {
80
+ return [];
81
+ }
82
+ }),
83
+ );
84
+ }
85
+
86
+ constructor(
87
+ workspaceRoot: string,
88
+ scopes: readonly string[],
89
+ {
90
+ onUnread = () => undefined,
91
+ timeoutMs = SignalDescriptors.readTimeoutMs,
92
+ takenFromPieces = () => null,
93
+ }: SignalDescriptorsOptions = {},
94
+ ) {
95
+ this.#takenFromPieces = takenFromPieces;
96
+ this.#workspaceRoot = workspaceRoot;
97
+ this.#sigFiles = scopes.map((scope) => path.join(workspaceRoot, scope, "lib/sig.ts"));
98
+ this.#onUnread = onUnread;
99
+ this.#timeoutMs = timeoutMs;
100
+ }
101
+
102
+ get plugin(): BunPlugin {
103
+ return {
104
+ name: "signal-descriptors",
105
+ setup: (build) => {
106
+ this.#env = SignalDescriptors.#envOf(build.config.define);
107
+ build.onLoad({ filter: SignalDescriptors.#pieceFile }, async (args) => {
108
+ const contents = await this.inline(await Bun.file(args.path).text(), args.path);
109
+ return contents === null ? undefined : { contents, loader: "ts" };
110
+ });
111
+ build.onLoad({ filter: SignalDescriptors.#wholeFile }, async (args) => {
112
+ const pieces = this.#takenFromPieces(args.path);
113
+ const contents = pieces && (await this.withoutPieces(await Bun.file(args.path).text(), args.path, pieces));
114
+ return contents ? { contents, loader: "ts" } : undefined;
115
+ });
116
+ },
117
+ };
118
+ }
119
+
120
+ async inline(source: string, absPath: string): Promise<string | null> {
121
+ const macroImport = SignalDescriptors.#macroImport;
122
+ const calls = [...source.matchAll(SignalDescriptors.#macroCall)];
123
+ const [call] = calls;
124
+ const name = call?.[1];
125
+ if (!SignalDescriptors.#pieceFile.test(absPath) || !call || !name || calls.length !== 1) return null;
126
+ if (source.split(macroImport).length !== 2) return null;
127
+ const descriptors = (await this.#descriptorsOf(path.resolve(path.dirname(absPath), "../sig.ts")))?.literals;
128
+ const literal = descriptors && Object.hasOwn(descriptors, name) ? descriptors[name] : undefined;
129
+ if (literal === undefined) return null;
130
+ const end = call.index + call[0].length;
131
+ return `${source.slice(0, call.index)}${literal}${source.slice(end)}`.replace(macroImport, "");
132
+ }
133
+
134
+ //* A scope's `lib/useClient.ts` with the descriptors of these pieces left out and the pieces imported in their place.
135
+ //* Null where a name cannot be accounted for, so the file keeps its macro and every descriptor.
136
+ async withoutPieces(source: string, absPath: string, pieces: readonly string[]): Promise<string | null> {
137
+ const [macroImport, macroCall] = [SignalDescriptors.#wholeImport, SignalDescriptors.#wholeCall];
138
+ if (source.split(macroImport).length !== 2 || source.split(macroCall).length !== 2) return null;
139
+ const signals = await this.#descriptorsOf(path.resolve(path.dirname(absPath), "sig.ts"));
140
+ if (!signals) return null;
141
+ const { names, literals } = signals;
142
+ if (!names.length || names.some((name) => !Object.hasOwn(literals, name))) return null;
143
+ //? The first name stands for what the scope takes from its base, and a signal of the base may itself be named `base`.
144
+ const [, ...own] = names;
145
+ const fromBase = JSON.parse(literals.base ?? "{}") as Record<string, unknown>;
146
+ const taken = new Set<string>();
147
+ for (const piece of pieces) {
148
+ const calls = [...(await Bun.file(piece).text()).matchAll(SignalDescriptors.#macroCall)];
149
+ const name = calls[0]?.[1];
150
+ if (!name || calls.length !== 1) return null;
151
+ if (name === "base") for (const held of Object.keys(fromBase)) taken.add(held);
152
+ else taken.add(name);
153
+ }
154
+ const kept = [...new Set(own)].filter((name) => !taken.has(name));
155
+ if (kept.includes("base") && !Object.hasOwn(fromBase, "base")) return null;
156
+ const literalOf = (name: string) =>
157
+ name === "base" ? JSON.stringify({ base: fromBase.base }) : (literals[name] ?? "{}");
158
+ const literal = `{${kept
159
+ .map((name) => literalOf(name).slice(1, -1))
160
+ .filter(Boolean)
161
+ .join(",")}}`;
162
+ const loaded = pieces.map((_, index) => `__akanPiece${index}`);
163
+ const imports = [
164
+ 'import { loadedAfter as __akanPiecesFirst } from "akanjs/base";',
165
+ ...pieces.map((piece, index) => `import { loaded as ${loaded[index]} } from ${JSON.stringify(piece)};`),
166
+ `__akanPiecesFirst(${loaded.join(", ")});`,
167
+ ];
168
+ return `${imports.join("\n")}\n${source.replace(macroImport, "").replace(macroCall, () => literal)}`;
169
+ }
170
+
171
+ #descriptorsOf(sigFile: string): Promise<ScopeSignals | null> {
172
+ const known = this.#reads.get(sigFile);
173
+ if (known) return known;
174
+ const batch = [...new Set([sigFile, ...this.#sigFiles])].filter((file) => !this.#reads.has(file));
175
+ const read = this.#read(batch);
176
+ for (const file of batch)
177
+ this.#reads.set(
178
+ file,
179
+ read.then((byFile) => byFile.get(file) ?? null),
180
+ );
181
+ return this.#reads.get(sigFile) ?? Promise.resolve(null);
182
+ }
183
+
184
+ //? `--no-env-file`: the build's `NODE_ENV` define would make Bun load `.env.production` files the build never loaded.
185
+ async #read(sigFiles: string[]): Promise<Map<string, ScopeSignals>> {
186
+ const read = new Map<string, ScopeSignals>();
187
+ const failures = new Map<string, string>();
188
+ const child = Bun.spawn([process.execPath, "--no-env-file", "--eval", SignalDescriptors.#readScript(sigFiles)], {
189
+ cwd: this.#workspaceRoot,
190
+ env: { ...process.env, ...this.#env },
191
+ stdout: "ignore",
192
+ stderr: "ignore",
193
+ serialization: "json",
194
+ ipc: (message: ScopeRead) => {
195
+ if (message.read) read.set(message.file, { names: message.names ?? [], literals: message.read });
196
+ else failures.set(message.file, message.failure ?? "");
197
+ },
198
+ });
199
+ let timedOut = false;
200
+ const kill = () => child.kill("SIGKILL");
201
+ const timer = setTimeout(() => {
202
+ timedOut = true;
203
+ kill();
204
+ }, this.#timeoutMs);
205
+ process.on("exit", kill);
206
+ const code = await child.exited.finally(() => {
207
+ clearTimeout(timer);
208
+ process.off("exit", kill);
209
+ });
210
+ for (const [file, failure] of failures)
211
+ this.#onUnread(`the signals of ${this.#scopeOf(file)} could not be read (${failure})`);
212
+ const unsent = sigFiles.filter((file) => !read.has(file) && !failures.has(file));
213
+ if (unsent.length > 0) {
214
+ const why = timedOut
215
+ ? `they did not load within ${this.#timeoutMs / 1000}s, so the process reading them was stopped`
216
+ : `its process exited with code ${code}`;
217
+ this.#onUnread(
218
+ `the signals of ${unsent.map((file) => this.#scopeOf(file)).join(", ")} could not be read (${why})`,
219
+ );
220
+ }
221
+ return read;
222
+ }
223
+
224
+ #scopeOf(sigFile: string) {
225
+ return path.relative(this.#workspaceRoot, path.dirname(path.dirname(sigFile)));
226
+ }
227
+ }
@@ -0,0 +1,87 @@
1
+ import ts from "typescript";
2
+ import { ObjectModule } from "./objectModule";
3
+
4
+ const OWN_THIS = new Set([
5
+ ts.SyntaxKind.FunctionDeclaration,
6
+ ts.SyntaxKind.FunctionExpression,
7
+ ts.SyntaxKind.MethodDeclaration,
8
+ ts.SyntaxKind.GetAccessor,
9
+ ts.SyntaxKind.SetAccessor,
10
+ ts.SyntaxKind.Constructor,
11
+ ]);
12
+
13
+ //* The exports a caller may call without the object it reached them through: an arrow function, or a function whose
14
+ //* parameters and body read no `this` outside a nested function that binds its own. Any other export (a call's result,
15
+ //* a re-export, a class, a `let`) may read `this`, so it is never one of them.
16
+ export class ThisFreeExports {
17
+ static read(source: string, file: string): Set<string> {
18
+ const sourceFile = ts.createSourceFile(
19
+ file,
20
+ source,
21
+ ts.ScriptTarget.Latest,
22
+ false,
23
+ ObjectModule.scriptKindOf(file),
24
+ );
25
+ const free = new Map<string, boolean>();
26
+ const exported = new Map<string, string>();
27
+ const names = new Set<string>();
28
+ for (const statement of sourceFile.statements) {
29
+ if (ts.isFunctionDeclaration(statement) && statement.body) {
30
+ const name = statement.name?.text ?? "default";
31
+ free.set(name, !ThisFreeExports.#readsThis(statement));
32
+ if (ThisFreeExports.#hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) exported.set("default", name);
33
+ else if (ThisFreeExports.#hasModifier(statement, ts.SyntaxKind.ExportKeyword)) exported.set(name, name);
34
+ } else if (ts.isVariableStatement(statement)) {
35
+ const constant = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;
36
+ const isExported = ThisFreeExports.#hasModifier(statement, ts.SyntaxKind.ExportKeyword);
37
+ for (const declaration of statement.declarationList.declarations) {
38
+ if (!ts.isIdentifier(declaration.name)) continue;
39
+ const name = declaration.name.text;
40
+ free.set(name, constant && !!declaration.initializer && ThisFreeExports.#isFree(declaration.initializer));
41
+ if (isExported) exported.set(name, name);
42
+ }
43
+ } else if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause) {
44
+ if (!ts.isNamedExports(statement.exportClause)) continue;
45
+ for (const element of statement.exportClause.elements)
46
+ exported.set(element.name.text, (element.propertyName ?? element.name).text);
47
+ } else if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
48
+ const value = ThisFreeExports.#unwrap(statement.expression);
49
+ if (ts.isIdentifier(value)) exported.set("default", value.text);
50
+ else if (ThisFreeExports.#isFree(value)) names.add("default");
51
+ }
52
+ }
53
+ for (const [name, local] of exported) if (free.get(local)) names.add(name);
54
+ return names;
55
+ }
56
+
57
+ static #isFree(node: ts.Expression) {
58
+ const value = ThisFreeExports.#unwrap(node);
59
+ if (ts.isArrowFunction(value)) return true;
60
+ return ts.isFunctionExpression(value) && !ThisFreeExports.#readsThis(value);
61
+ }
62
+
63
+ static #readsThis(fn: ts.FunctionLikeDeclaration) {
64
+ const visit = (node: ts.Node): boolean => {
65
+ if (node.kind === ts.SyntaxKind.ThisKeyword) return true;
66
+ if (OWN_THIS.has(node.kind)) return false;
67
+ return ts.forEachChild(node, visit) ?? false;
68
+ };
69
+ return [...fn.parameters, ...(fn.body ? [fn.body] : [])].some(visit);
70
+ }
71
+
72
+ static #unwrap(node: ts.Expression): ts.Expression {
73
+ let current = node;
74
+ while (
75
+ ts.isParenthesizedExpression(current) ||
76
+ ts.isAsExpression(current) ||
77
+ ts.isSatisfiesExpression(current) ||
78
+ ts.isTypeAssertionExpression(current)
79
+ )
80
+ current = current.expression;
81
+ return current;
82
+ }
83
+
84
+ static #hasModifier(node: ts.Node, kind: ts.SyntaxKind) {
85
+ return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind);
86
+ }
87
+ }
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import fs from "node:fs";
3
+ import { realpath } from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { ApplicationBuildReporter } from "../app/applicationBuildReporter";
5
6
  import { tempDirs, writeText as write } from "../test/testHelpers";
@@ -448,6 +449,81 @@ describe("BarrelAnalyzer and rewriteBarrelImports", () => {
448
449
  );
449
450
  });
450
451
 
452
+ test("gives a module importing only usePage, msg or Err from a client barrel lib/usePage, not the descriptors and stores", async () => {
453
+ const root = await makeTempRoot();
454
+ await write(
455
+ path.join(root, "apps/demo/client.ts"),
456
+ [
457
+ 'export * as cnst from "./lib/cnst";',
458
+ 'export { msg, Err, usePage } from "./lib/usePage";',
459
+ 'export { fetch, sig } from "./lib/useClient";',
460
+ 'export { st, RootStore } from "./lib/st";',
461
+ 'export { Memo } from "./lib/memo";',
462
+ "",
463
+ ].join("\n"),
464
+ );
465
+ await write(path.join(root, "apps/demo/lib/cnst.ts"), "export const Sample = 1;\n");
466
+ await write(path.join(root, "apps/demo/lib/usePage.ts"), "export const { msg, Err, usePage, fetch, sig } = {};\n");
467
+ await write(
468
+ path.join(root, "apps/demo/lib/useClient.ts"),
469
+ [
470
+ 'import { fetch as pageFetch, sig as pageSig } from "./usePage";',
471
+ "export const fetch = pageFetch;",
472
+ "export const sig = pageSig;",
473
+ 'export { Err, msg, usePage } from "./usePage";',
474
+ "",
475
+ ].join("\n"),
476
+ );
477
+ await write(path.join(root, "apps/demo/lib/st.ts"), "export class RootStore {}\nexport const st = {};\n");
478
+ await write(path.join(root, "apps/demo/lib/memo/index.ts"), "export const Memo = {};\n");
479
+ const analyzer = new BarrelAnalyzer({
480
+ resolvePackage: await createTsconfigPackageResolver({
481
+ workspace: { workspaceRoot: root },
482
+ getTsConfig: async () => ({ compilerOptions: { paths: { "@apps/*": ["./apps/*"] } } }),
483
+ } as never),
484
+ });
485
+ const rewrite = async (source: string) => await rewriteBarrelImports(source, ["@apps/demo/client"], analyzer);
486
+
487
+ expect(await rewrite('import { usePage, msg as toast, Err, type cnst } from "@apps/demo/client";\n')).toBe(
488
+ [
489
+ 'import "@apps/demo/lib/usePage";',
490
+ 'import { type cnst } from "@apps/demo/client";',
491
+ 'import { usePage, msg as toast, Err } from "@apps/demo/lib/usePage";',
492
+ "",
493
+ ].join("\n"),
494
+ );
495
+ expect(await rewrite('import { fetch, usePage } from "@apps/demo/client";\n')).toBe(
496
+ [
497
+ 'import "@apps/demo/lib/useClient";',
498
+ 'import "@apps/demo/lib/st";',
499
+ 'import { fetch } from "@apps/demo/lib/useClient";',
500
+ 'import { usePage } from "@apps/demo/lib/usePage";',
501
+ "",
502
+ ].join("\n"),
503
+ );
504
+ expect(await rewrite('import { Memo, usePage } from "@apps/demo/client";\n')).toBe(
505
+ [
506
+ 'import "@apps/demo/lib/useClient";',
507
+ 'import "@apps/demo/lib/st";',
508
+ 'import { Memo } from "@apps/demo/lib/memo";',
509
+ 'import { usePage } from "@apps/demo/lib/usePage";',
510
+ "",
511
+ ].join("\n"),
512
+ );
513
+ expect(
514
+ await rewriteBarrelImports('import { cnst, Memo } from "@apps/demo/client";\n', ["@apps/demo/client"], analyzer, {
515
+ perModule: true,
516
+ }),
517
+ ).toBe(
518
+ [
519
+ 'import "@apps/demo/lib/usePage";',
520
+ 'import { Memo } from "@apps/demo/lib/memo";',
521
+ 'import * as cnst from "@apps/demo/lib/cnst";',
522
+ "",
523
+ ].join("\n"),
524
+ );
525
+ });
526
+
451
527
  test("keeps each statement's line count and writes the specifier specifierOf gives a target", async () => {
452
528
  const analyzer = fakeAnalyzer([
453
529
  ["A", { subpath: "@scope/pkg/leaf", originalName: "A" }],
@@ -548,4 +624,67 @@ describe("BarrelAnalyzer and rewriteBarrelImports", () => {
548
624
  ].join("\n")}\n`,
549
625
  );
550
626
  });
627
+
628
+ test("narrows a re-export of barrel names like an import when asked, and leaves a namespace of the barrel whole", async () => {
629
+ const analyzer = fakeAnalyzer([
630
+ ["buttonRecipe", { subpath: "akanjs/ui/Recipe/button", originalName: "buttonRecipe" }],
631
+ ["inputRecipe", { subpath: "akanjs/ui/Recipe/input", originalName: "inputRecipe" }],
632
+ ["icons", { subpath: "akanjs/ui/Icon/icons", originalName: "icons", namespace: true }],
633
+ ]);
634
+ const source = [
635
+ 'export { buttonRecipe, inputRecipe as input, icons, type Recipe } from "akanjs/ui";',
636
+ 'export * as ui from "akanjs/ui";',
637
+ 'export type { Theme } from "akanjs/ui";',
638
+ "",
639
+ ].join("\n");
640
+
641
+ expect(await rewriteBarrelImports(source, ["akanjs/ui"], analyzer)).toBeNull();
642
+ expect(await rewriteBarrelImports(source, ["akanjs/ui"], analyzer, { reexports: true })).toBe(
643
+ [
644
+ 'export { type Recipe } from "akanjs/ui";',
645
+ 'export { buttonRecipe } from "akanjs/ui/Recipe/button";',
646
+ 'export { inputRecipe as input } from "akanjs/ui/Recipe/input";',
647
+ 'export * as icons from "akanjs/ui/Icon/icons";',
648
+ 'export * as ui from "akanjs/ui";',
649
+ 'export type { Theme } from "akanjs/ui";',
650
+ "",
651
+ ].join("\n"),
652
+ );
653
+ });
654
+
655
+ test("maps a name the barrel re-exports from a package to the package, when it resolves the same from the workspace", async () => {
656
+ const root = await realpath(await makeTempRoot());
657
+ const pkgDir = path.join(root, "pkgs/ui");
658
+ await write(
659
+ path.join(root, "node_modules/use-agentic/package.json"),
660
+ '{ "name": "use-agentic", "main": "index.js" }',
661
+ );
662
+ await write(path.join(root, "node_modules/use-agentic/index.js"), "export const useAgent = () => null;\n");
663
+ await write(path.join(root, "node_modules/use-agentic/other.js"), "export const other = 1;\n");
664
+ await write(path.join(pkgDir, "node_modules/pinned/package.json"), '{ "name": "pinned", "main": "index.js" }');
665
+ await write(path.join(pkgDir, "node_modules/pinned/index.js"), "export const usePinned = () => null;\n");
666
+ await write(
667
+ path.join(pkgDir, "index.ts"),
668
+ [
669
+ 'export { useAgent, useAgent as useAgentReference } from "use-agentic";',
670
+ 'export { usePinned } from "pinned";',
671
+ 'export * from "./Link";',
672
+ "",
673
+ ].join("\n"),
674
+ );
675
+ await write(
676
+ path.join(pkgDir, "Link.ts"),
677
+ 'export { other } from "use-agentic";\nexport const Link = () => null;\n',
678
+ );
679
+ const resolvePackage = async () => ({ pkgName: "akanjs/ui", entryFile: path.join(pkgDir, "index.ts"), pkgDir });
680
+
681
+ const narrowed = await new BarrelAnalyzer({ resolvePackage, packageRoot: root }).analyze("akanjs/ui");
682
+ const whole = await new BarrelAnalyzer({ resolvePackage }).analyze("akanjs/ui");
683
+
684
+ expect(narrowed?.get("useAgent")).toEqual({ subpath: "use-agentic", originalName: "useAgent" });
685
+ expect(narrowed?.get("useAgentReference")).toEqual({ subpath: "use-agentic", originalName: "useAgent" });
686
+ expect(narrowed?.get("usePinned")).toEqual({ subpath: "akanjs/ui", originalName: "usePinned" });
687
+ expect(narrowed?.get("other")).toEqual({ subpath: "akanjs/ui/Link", originalName: "other" });
688
+ expect(whole?.get("useAgent")).toEqual({ subpath: "akanjs/ui", originalName: "useAgent" });
689
+ });
551
690
  });
@@ -27,6 +27,7 @@ import type {
27
27
  WorkflowStepResult,
28
28
  } from "./types";
29
29
  import { addFieldUiPolicyForType } from "./uiPolicy";
30
+ import { isUiSurface } from "./uiTarget";
30
31
 
31
32
  export const workflowStepKey = (workflow: string, stepId: string) => `${workflow}:${stepId}`;
32
33
 
@@ -428,10 +429,13 @@ export const createWorkflowStepRegistry = ({
428
429
  },
429
430
  [workflowStepKey("create-ui", "create-ui")]: async (_step, plan) => {
430
431
  const surface = workflowStringInput(plan.inputs.surface);
431
- if (surface !== "view" && surface !== "unit" && surface !== "template") {
432
+ if (!isUiSurface(surface)) {
432
433
  return {
433
434
  diagnostics: [
434
- unsupportedInput("surface", "Workflow apply currently supports create-ui surfaces: view, unit, template."),
435
+ unsupportedInput(
436
+ "surface",
437
+ "Workflow apply supports create-ui surfaces: view, unit, template, zone, util.",
438
+ ),
435
439
  ],
436
440
  };
437
441
  }
package/workflow/index.ts CHANGED
@@ -14,4 +14,5 @@ export * from "./rolloutGate";
14
14
  export * from "./source";
15
15
  export * from "./types";
16
16
  export * from "./uiPolicy";
17
+ export * from "./uiTarget";
17
18
  export * from "./utils";
package/workflow/plan.ts CHANGED
@@ -20,6 +20,7 @@ import type {
20
20
  WorkflowSurfaceMode,
21
21
  } from "./types";
22
22
  import { addFieldUiPolicyForType } from "./uiPolicy";
23
+ import { isUiSurface, resolveUiTarget, uiFileExists } from "./uiTarget";
23
24
  import { workflowStatus } from "./utils";
24
25
 
25
26
  const surfaceModes = new Set<WorkflowSurfaceMode>(["infer", "include", "skip"]);
@@ -355,19 +356,25 @@ const createWorkflowPlanRecommendations = (
355
356
  ...(spec.name === "add-field" ? createAddFieldRecommendations(inputs) : []),
356
357
  ];
357
358
 
359
+ const isBlankInput = (value: unknown) => value === undefined || value === null || value === "";
360
+
358
361
  export const createWorkflowPlan = (spec: WorkflowSpec, rawInputs: Record<string, unknown>): WorkflowPlan => {
359
362
  const inputs: Record<string, WorkflowInputValue> = {};
360
363
  const diagnostics: WorkflowDiagnostic[] = [];
364
+ const untaken = Object.keys(rawInputs).filter((name) => !(name in spec.inputs) && !isBlankInput(rawInputs[name]));
365
+ const untakenNote = untaken.length
366
+ ? ` It does not take ${untaken.map((name) => `"${name}"`).join(", ")}, which ${untaken.length === 1 ? "was" : "were"} passed.`
367
+ : "";
361
368
 
362
369
  for (const [name, inputSpec] of Object.entries(spec.inputs)) {
363
370
  const rawValue = rawInputs[name];
364
- if (rawValue === undefined || rawValue === null || rawValue === "") {
371
+ if (isBlankInput(rawValue)) {
365
372
  if (inputSpec.required) {
366
373
  diagnostics.push({
367
374
  severity: "error",
368
375
  code: "workflow-input-missing",
369
376
  input: name,
370
- message: `Workflow ${spec.name} requires input "${name}".`,
377
+ message: `Workflow ${spec.name} requires input "${name}" (--${name} on the command line).${untakenNote}`,
371
378
  });
372
379
  }
373
380
  continue;
@@ -572,11 +579,32 @@ export const workflowTargetDiagnostics = async (
572
579
  const module = planString(inputs, "module");
573
580
  const moduleSpec: WorkflowInputSpec | undefined = spec.inputs.module;
574
581
  if (!module || !moduleSpec?.mustExist) return [];
575
- const refused =
576
- (await moduleMissing(workspace, sys, module)) ??
577
- (await moduleNotDatabase(sys, spec, module)) ??
578
- (await fieldTypeUnknown(sys, spec, module, planString(inputs, "type")));
579
- return refused ? [refused] : [];
582
+ const surface = planString(inputs, "surface");
583
+ const ui = spec.name === "create-ui" ? await resolveUiTarget(sys, module, surface) : null;
584
+ if (ui?.diagnostic) return [ui.diagnostic];
585
+ const refused = ui?.module
586
+ ? null
587
+ : ((await moduleMissing(workspace, sys, module)) ??
588
+ (await moduleNotDatabase(sys, spec, module)) ??
589
+ (await fieldTypeUnknown(sys, spec, module, planString(inputs, "type"))));
590
+ if (refused) return [refused];
591
+ const exists = ui && isUiSurface(surface) ? await uiFileExists(sys, ui.module ?? module, surface) : null;
592
+ return exists ? [exists] : [];
593
+ };
594
+
595
+ const inspectCreateUiPlan = async (workspace: Workspace, plan: WorkflowPlan): Promise<WorkflowPlan> => {
596
+ const sys = await resolveWorkflowSys(workspace, planString(plan.inputs, "app")).catch(() => null);
597
+ const module = planString(plan.inputs, "module");
598
+ const surface = planString(plan.inputs, "surface");
599
+ if (!sys || !module || !isUiSurface(surface)) return plan;
600
+ const resolved = (await resolveUiTarget(sys, module, surface)).module ?? module;
601
+ const target = `${getSysRoot(sys)}/${moduleSourcePaths(resolved)[surface]}`;
602
+ return {
603
+ ...plan,
604
+ predictedChanges: plan.predictedChanges.map((change) =>
605
+ change.target.endsWith(".<Surface>.tsx") ? { ...change, target } : change,
606
+ ),
607
+ };
580
608
  };
581
609
 
582
610
  const inspectPlanTarget = async (
@@ -593,6 +621,7 @@ const inspectPlanTarget = async (
593
621
  recommendations: [],
594
622
  };
595
623
  if (plan.workflow === "rename-key") return await inspectRenameKeyPlan(workspace, plan);
624
+ if (plan.workflow === "create-ui") return await inspectCreateUiPlan(workspace, plan);
596
625
  if (plan.workflow !== "add-mutation" && plan.workflow !== "create-interaction") return plan;
597
626
  const sys = await resolveWorkflowSys(workspace, planString(plan.inputs, "app")).catch(() => null);
598
627
  if (!sys) return plan;
package/workflow/types.ts CHANGED
@@ -7,7 +7,7 @@ export type WorkflowInputValue = string | string[] | boolean | WorkflowSurfaceMo
7
7
  export type WorkflowFormat = "markdown" | "json";
8
8
  export type WorkflowPlanInputs = Record<string, string | null>;
9
9
  export type PrimitiveFormat = "markdown" | "json";
10
- export type UiSurface = "view" | "unit" | "template";
10
+ export type UiSurface = "view" | "unit" | "template" | "zone" | "util";
11
11
  export type WorkflowValidationKind = "verify" | "sync" | "lint" | "typecheck" | "doctor" | "custom";
12
12
  export type WorkflowFailureScope = "workspace-config" | "environment" | "source-change" | "unknown";
13
13
  export type WorkflowValidationStatus = "passed" | "failed" | "unknown";
@@ -0,0 +1,50 @@
1
+ import type { Sys } from "../commandDecorators";
2
+ import { getSysRoot, moduleSourcePaths } from "./modulePaths";
3
+ import type { UiSurface, WorkflowDiagnostic } from "./types";
4
+
5
+ const uiSurfaces: readonly string[] = ["view", "unit", "template", "zone", "util"];
6
+ const serviceSurfaces: readonly string[] = ["zone", "util"];
7
+
8
+ export const isUiSurface = (value: unknown): value is UiSurface =>
9
+ typeof value === "string" && uiSurfaces.includes(value);
10
+
11
+ export interface UiTarget {
12
+ module: string | null;
13
+ diagnostic: WorkflowDiagnostic | null;
14
+ }
15
+
16
+ const bareName = (name: string) => name.replace(/^_/, "").toLowerCase();
17
+
18
+ export const resolveUiTarget = async (sys: Sys, module: string, surface: string | null): Promise<UiTarget> => {
19
+ if (!isUiSurface(surface) || (await sys.getDatabaseModules()).includes(module))
20
+ return { module: null, diagnostic: null };
21
+ const service = (await sys.getServiceModules()).find((name) => bareName(name) === bareName(module));
22
+ if (!service) return { module: null, diagnostic: null };
23
+ const root = getSysRoot(sys);
24
+ if (!serviceSurfaces.includes(surface))
25
+ return {
26
+ module: null,
27
+ diagnostic: {
28
+ severity: "error",
29
+ code: "workflow-module-not-database",
30
+ input: "module",
31
+ message: `${root}/lib/${service} is a service module, which stores no model, so create-ui takes only zone or util there; a ${surface} needs a database module.`,
32
+ },
33
+ };
34
+ return { module: service, diagnostic: null };
35
+ };
36
+
37
+ export const uiFileExists = async (
38
+ sys: Sys,
39
+ module: string,
40
+ surface: UiSurface,
41
+ ): Promise<WorkflowDiagnostic | null> => {
42
+ const path = moduleSourcePaths(module)[surface];
43
+ if (!(await sys.exists(path))) return null;
44
+ return {
45
+ severity: "error",
46
+ code: "workflow-ui-file-exists",
47
+ input: "surface",
48
+ message: `${getSysRoot(sys)}/${path} already exists, and create-ui does not overwrite it; edit that file, or remove it first to scaffold it again.`,
49
+ };
50
+ };
@@ -51,7 +51,7 @@ const fileTypeOf = (filename: string) =>
51
51
 
52
52
  type ModuleKind = "database" | "service" | "scalar";
53
53
 
54
- const internalLibDirs = new Set(["__lib", "__scalar"]);
54
+ const internalLibDirs = new Set(["__lib", "__scalar", "__client"]);
55
55
  const moduleNonUiFileTypes = {
56
56
  database: new Set(["constant", "dictionary", "document", "service", "signal", "store"]),
57
57
  service: new Set(["dictionary", "service", "signal", "store"]),
@@ -80,6 +80,7 @@ export const libFacetRootAllowedFiles = new Set([
80
80
  "srv.ts",
81
81
  "st.ts",
82
82
  "useClient.ts",
83
+ "usePage.ts",
83
84
  "useServer.ts",
84
85
  ]);
85
86