@akanjs/devkit 3.3.0-rc.66 โ†’ 3.3.0-rc.67

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.
@@ -8,7 +8,7 @@ import { AkanBin } from "../akanConfig/akanBin";
8
8
  import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX } from "../akanConfig/dockerImage";
9
9
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
10
10
  import type { App } from "../commandDecorators";
11
- import { parseEnvFile, WorkspaceExecutor } from "../executors";
11
+ import { LibExecutor, parseEnvFile, WorkspaceExecutor } from "../executors";
12
12
  import {
13
13
  AllRoutesBuilder,
14
14
  type BuildAllRoutesResult,
@@ -36,6 +36,7 @@ import {
36
36
  ApplicationBuildReporter,
37
37
  type ApplicationBuildResult,
38
38
  } from "./applicationBuildReporter";
39
+ import { ClientServerBoundary } from "./clientServerBoundary";
39
40
  import { RouteFilesReport } from "./routeFilesReport";
40
41
  import { RouteJsBudget, type RouteJsBudgetMode, type RouteJsBudgetStatus, type RouteJsSize } from "./routeJsBudget";
41
42
 
@@ -50,6 +51,7 @@ export interface TypecheckOptions {
50
51
  export type BuildPhaseId =
51
52
  | "prepare"
52
53
  | "typecheck"
54
+ | "boundary"
53
55
  | "backend"
54
56
  | "ssr"
55
57
  | "csr"
@@ -95,6 +97,7 @@ const MAIN_BUNDLE = "main.bundle.js";
95
97
  const BUILD_PHASE_EMOJIS: Record<BuildPhaseId, string> = {
96
98
  prepare: "๐Ÿงน",
97
99
  typecheck: "๐Ÿ”Ž",
100
+ boundary: "๐Ÿšง",
98
101
  backend: "๐Ÿ“ฆ",
99
102
  ssr: "๐Ÿงญ",
100
103
  csr: "๐ŸŽจ",
@@ -201,6 +204,13 @@ export class ApplicationBuildRunner {
201
204
  if (this.#secretEnv) await this.#declareSecrets(environment);
202
205
  await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
203
206
  if (!this.#fast) await this.#runPhase("typecheck", "Typechecking", () => this.typecheck());
207
+ if (!this.#verify)
208
+ await this.#runPhase(
209
+ "boundary",
210
+ "Checking client imports",
211
+ () => this.assertClientBoundary(),
212
+ (files) => `${files} client files`,
213
+ );
204
214
  await this.#runPhase(
205
215
  "backend",
206
216
  "Compiling backend",
@@ -369,6 +379,12 @@ export class ApplicationBuildRunner {
369
379
  );
370
380
  }
371
381
 
382
+ async assertClientBoundary() {
383
+ const scanInfo = this.#app.getScanInfo({ allowEmpty: true }) ?? (await this.#app.scan({ write: false }));
384
+ const libs = scanInfo.getLibs().map((lib) => LibExecutor.from(this.#app, lib).cwdPath);
385
+ return await ClientServerBoundary.assert([this.#app.cwdPath, ...libs], this.#app.workspace.workspaceRoot);
386
+ }
387
+
372
388
  static #ssrSummary({ manifest, runtimeReport }: BuildAllRoutesResult) {
373
389
  const built = `${manifest.routeIds.length} routes, ${manifest.knownEntries.length} entries`;
374
390
  return runtimeReport ? `${built}; ${RouteRuntimeReport.summary(runtimeReport)}` : built;
@@ -0,0 +1,115 @@
1
+ import { afterAll, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { CliError } from "../commandDecorators/cliError";
6
+ import { ClientServerBoundary } from "./clientServerBoundary";
7
+
8
+ const plugin = "no-import-server-in-client.grit";
9
+ const lintDir = path.join(import.meta.dir, "../lint");
10
+
11
+ describe("ClientServerBoundary", () => {
12
+ test("holds the patterns and messages of the lint plugin", async () => {
13
+ const grit = await Bun.file(path.join(lintDir, plugin)).text();
14
+ const patterns = [...grit.matchAll(/r"\\"(.+?)\\""/g)].map(([, inner]) => inner);
15
+ const messages = [...grit.matchAll(/message = "(.+)",$/gm)].map(([, message]) => message);
16
+ expect(ClientServerBoundary.rules.flatMap((rule) => rule.patterns)).toEqual(patterns);
17
+ expect(ClientServerBoundary.rules.map((rule) => rule.hint)).toEqual(messages);
18
+ });
19
+
20
+ test("checks the files the lint plugin covers", async () => {
21
+ const base = (await Bun.file(path.join(import.meta.dir, "../biome.base.json")).json()) as {
22
+ overrides: { includes?: string[]; plugins?: string[] }[];
23
+ };
24
+ const includes = base.overrides.find((each) => each.plugins?.some((file) => file.endsWith(`/${plugin}`)))?.includes;
25
+ if (!includes) throw new Error(`biome.base.json has no override running ${plugin}`);
26
+ const covered = (file: string) =>
27
+ includes.some((glob) => !glob.startsWith("!") && new Bun.Glob(glob).match(file)) &&
28
+ !includes.some((glob) => glob.startsWith("!") && new Bun.Glob(glob.slice(1)).match(file));
29
+ const files = [
30
+ "page/_index.tsx",
31
+ "page/(main)/books/_layout.ts",
32
+ "ui/Card.tsx",
33
+ "ui/Recipe/card.ts",
34
+ "webkit/useThing.ts",
35
+ "common/format.ts",
36
+ "lib/book/book.store.ts",
37
+ "lib/book/book.constant.ts",
38
+ "lib/book/Book.Unit.tsx",
39
+ "lib/book/book.service.ts",
40
+ "lib/book/book.signal.ts",
41
+ "lib/book/book.store.test.ts",
42
+ "page/_index.test.tsx",
43
+ "srvkit/bookApi.ts",
44
+ "env/env.server.ts",
45
+ "main.ts",
46
+ "client.ts",
47
+ ];
48
+ for (const file of files)
49
+ expect([file, ClientServerBoundary.isClientFile(file)]).toEqual([file, covered(`apps/a/${file}`)]);
50
+ });
51
+
52
+ test("names a value import of server code, and lets a type-only import through", () => {
53
+ const found = ClientServerBoundary.serverImportsOf(
54
+ "apps/a/page/_index.tsx",
55
+ [
56
+ 'import type { BookApi } from "../srvkit";',
57
+ 'import { fetch } from "@apps/a/client";',
58
+ 'import { BookApi } from "../srvkit";',
59
+ 'import { cnst, type Book } from "../lib/book/book.service";',
60
+ 'import "akanjs/server";',
61
+ 'import * as srv from "../lib/srv";',
62
+ 'import { useServer } from "../lib/useServer";',
63
+ ].join("\n"),
64
+ );
65
+ expect(found.map(({ line, specifier }) => [line, specifier])).toEqual([
66
+ [3, "../srvkit"],
67
+ [4, "../lib/book/book.service"],
68
+ [5, "akanjs/server"],
69
+ [6, "../lib/srv"],
70
+ [7, "../lib/useServer"],
71
+ ]);
72
+ });
73
+
74
+ test("honours the suppressions the lint plugin honours", () => {
75
+ const silencedImport = [
76
+ 'import { fetch } from "@apps/a/client";',
77
+ "// biome-ignore lint/plugin: reads the build id the server stamps",
78
+ 'import { buildId } from "../srvkit/buildId";',
79
+ 'import { BookApi } from "../srvkit";',
80
+ ].join("\n");
81
+ expect(ClientServerBoundary.serverImportsOf("apps/a/ui/A.tsx", silencedImport).map(({ line }) => line)).toEqual([
82
+ 4,
83
+ ]);
84
+ const silencedFile = ["// biome-ignore-all lint/plugin: quotes banned imports", 'import "../srvkit";'].join("\n");
85
+ expect(ClientServerBoundary.serverImportsOf("apps/a/ui/A.tsx", silencedFile)).toEqual([]);
86
+ });
87
+
88
+ describe("on disk", () => {
89
+ let root = "";
90
+ afterAll(async () => {
91
+ if (root) await rm(root, { recursive: true, force: true });
92
+ });
93
+
94
+ test("fails a build naming each import, and passes one that imports none", async () => {
95
+ root = await mkdtemp(path.join(tmpdir(), "akan-boundary-"));
96
+ const app = path.join(root, "apps", "a");
97
+ await Bun.write(path.join(app, "page", "_index.tsx"), 'import { BookApi } from "../srvkit";\n');
98
+ await Bun.write(path.join(app, "page", "books.test.tsx"), 'import { BookApi } from "../srvkit";\n');
99
+ await Bun.write(path.join(app, "srvkit", "index.ts"), 'export { BookApi } from "./bookApi";\n');
100
+ await Bun.write(path.join(app, "lib", "book", "book.service.ts"), 'import * as db from "../db";\n');
101
+ const lib = path.join(root, "libs", "l");
102
+ await Bun.write(path.join(lib, "webkit", "useThing.ts"), 'import { srv } from "../lib/srv";\n');
103
+ const error = await ClientServerBoundary.assert([app, lib], root).catch((caught: unknown) => caught);
104
+ expect(error).toBeInstanceOf(CliError);
105
+ expect((error as CliError).code).toBe("checkFailed");
106
+ expect((error as CliError).message).toContain('apps/a/page/_index.tsx:1 "../srvkit"');
107
+ expect((error as CliError).message).toContain('libs/l/webkit/useThing.ts:1 "../lib/srv"');
108
+ expect((error as CliError).message).not.toContain("books.test.tsx");
109
+ expect((error as CliError).message).not.toContain("book.service.ts");
110
+ await Bun.write(path.join(app, "page", "_index.tsx"), 'import type { BookApi } from "../srvkit";\n');
111
+ await Bun.write(path.join(lib, "webkit", "useThing.ts"), 'import { st } from "../lib/st";\n');
112
+ expect(await ClientServerBoundary.assert([app, lib], root)).toBe(2);
113
+ });
114
+ });
115
+ });
@@ -0,0 +1,89 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import { CliError } from "../commandDecorators/cliError";
4
+
5
+ export interface ServerImport {
6
+ file: string;
7
+ line: number;
8
+ specifier: string;
9
+ hint: string;
10
+ }
11
+
12
+ export class ClientServerBoundary {
13
+ static readonly rules = [
14
+ {
15
+ patterns: [String.raw`.*\.(?:document|dictionary|service|signal)`],
16
+ hint: "Server module. A client or shared file must not import a *.document, *.dictionary, *.service, or *.signal file โ€” take the model from the package client entrypoint ('@libs/<lib>/client') or from its *.constant instead. Write 'import type' if only the type is needed.",
17
+ },
18
+ {
19
+ patterns: [String.raw`(?:.*/)?srvkit(?:/.*)?`, String.raw`.*/server(?:/.*)?`],
20
+ hint: "Server entrypoint. A client or shared file must not import srvkit/ or a package server entrypoint such as '@apps/<app>/server' or 'akanjs/server' โ€” import the matching client entrypoint instead.",
21
+ },
22
+ {
23
+ patterns: [String.raw`(?:.*/)?(?:db|srv|sig|dict|option|useServer)`],
24
+ hint: "Server barrel. A client or shared file must not import db, srv, sig, dict, option, or useServer โ€” read models from cnst, state from st, and Err from the package client entrypoint.",
25
+ },
26
+ ].map((rule) => ({ ...rule, pattern: new RegExp(`^(?:${rule.patterns.join("|")})$`) }));
27
+ static readonly #sources = new Bun.Glob("**/*.{ts,tsx}");
28
+ static readonly #skippedDir = /(?:^|\/)(?:node_modules|dist|dump|local)\//;
29
+ static readonly #silencedFile = /biome-ignore-all\b[^:\n]*\blint\/plugin\b/;
30
+ static readonly #silencedImport = /biome-ignore\s[^:\n]*\blint\/plugin\b/;
31
+
32
+ static isClientFile(relativePath: string) {
33
+ if (/\.(?:test|spec)\.tsx?$/.test(relativePath)) return false;
34
+ return (
35
+ relativePath.endsWith(".tsx") ||
36
+ relativePath.endsWith(".store.ts") ||
37
+ relativePath.endsWith(".constant.ts") ||
38
+ /(?:^|\/)(?:ui|webkit|page|common)\//.test(relativePath)
39
+ );
40
+ }
41
+
42
+ static serverImportsOf(file: string, text: string): ServerImport[] {
43
+ if (ClientServerBoundary.#silencedFile.test(text)) return [];
44
+ const kind = file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
45
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false, kind);
46
+ return source.statements.flatMap((statement) => {
47
+ if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly) return [];
48
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) return [];
49
+ const specifier = statement.moduleSpecifier.text;
50
+ const found = ClientServerBoundary.rules.find(({ pattern }) => pattern.test(specifier));
51
+ const comments = ts.getLeadingCommentRanges(text, statement.pos) ?? [];
52
+ if (!found || comments.some(({ pos, end }) => ClientServerBoundary.#silencedImport.test(text.slice(pos, end))))
53
+ return [];
54
+ const { line } = source.getLineAndCharacterOfPosition(statement.getStart(source));
55
+ return [{ file, line: line + 1, specifier, hint: found.hint }];
56
+ });
57
+ }
58
+
59
+ static async find(dirs: string[], workspaceRoot: string): Promise<{ files: number; found: ServerImport[] }> {
60
+ let files = 0;
61
+ const found: ServerImport[] = [];
62
+ for (const dir of dirs)
63
+ for await (const relativePath of ClientServerBoundary.#sources.scan({ cwd: dir, followSymlinks: false })) {
64
+ const posix = relativePath.split(path.sep).join("/");
65
+ if (ClientServerBoundary.#skippedDir.test(posix) || !ClientServerBoundary.isClientFile(posix)) continue;
66
+ files++;
67
+ const absolute = path.join(dir, relativePath);
68
+ const file = path.relative(workspaceRoot, absolute).split(path.sep).join("/");
69
+ found.push(...ClientServerBoundary.serverImportsOf(file, await Bun.file(absolute).text()));
70
+ }
71
+ return { files, found };
72
+ }
73
+
74
+ static async assert(dirs: string[], workspaceRoot: string): Promise<number> {
75
+ const { files, found } = await ClientServerBoundary.find(dirs, workspaceRoot);
76
+ if (!found.length) return files;
77
+ const lines = ClientServerBoundary.rules.flatMap(({ hint }) => {
78
+ const each = found.filter((serverImport) => serverImport.hint === hint);
79
+ return each.length ? [hint, ...each.map(({ file, line, specifier }) => ` ${file}:${line} "${specifier}"`)] : [];
80
+ });
81
+ throw new CliError(
82
+ "checkFailed",
83
+ [
84
+ `${found.length} import${found.length === 1 ? "" : "s"} would put server code in the browser bundle (\`akan lint\` reports ${found.length === 1 ? "it" : "them"} as no-import-server-in-client):`,
85
+ ...lines,
86
+ ].join("\n"),
87
+ );
88
+ }
89
+ }
@@ -52,6 +52,12 @@ describe("ApiReference", () => {
52
52
  expect(rendered).toMatch(/^Link\.Back\(.+\): Element$/m);
53
53
  });
54
54
 
55
+ test("defines under a signature the akanjs type alias it names, so no shape has to be grepped from node_modules", () => {
56
+ expect(rendered).toMatch(
57
+ /^usePageLocation\(\): .+ searchParams: BaseSearchParamsState; \}\ntype BaseSearchParamsState = \{ \[key: string\]: string \| string\[\]; \}\n```$/m,
58
+ );
59
+ });
60
+
55
61
  test("lists the keys of akan.config.ts, so the web and i18n shapes have a field to belong to", () => {
56
62
  const appConfig = rendered.slice(rendered.indexOf("### `AppConfigInput`"));
57
63
  expect(appConfig).toMatch(/^web\?: AkanWebOption;$/m);
@@ -138,6 +138,8 @@ const subpathPurposes = [
138
138
 
139
139
  const routeInternals = ["assertPattern", "resolveArgs", "toRouteModule"];
140
140
 
141
+ const documented = new Set(sections.flatMap((section) => section.items.map((item) => item.name)));
142
+
141
143
  export class ApiReference {
142
144
  static readonly guideline = "akanApi";
143
145
 
@@ -205,7 +207,15 @@ export class ApiReference {
205
207
  if (item.show.kind === "declaration")
206
208
  return [heading, "", "```ts", reader.declarationText(symbol), "```", ...note].join("\n");
207
209
  if (item.show.kind === "signature")
208
- return [heading, "", "```ts", ...reader.signatures(symbol, item.name), "```", ...note].join("\n");
210
+ return [
211
+ heading,
212
+ "",
213
+ "```ts",
214
+ ...reader.signatures(symbol, item.name),
215
+ ...reader.aliasesUsedBy(symbol, documented),
216
+ "```",
217
+ ...note,
218
+ ].join("\n");
209
219
  if (item.show.kind === "props") {
210
220
  const bases = reader.foreignBases(symbol).map((base) => `\`${base}\``);
211
221
  const inherits = bases.length ? ["", `Every prop of ${bases.join(" and ")}, and:`] : [];
@@ -105,6 +105,36 @@ export class DeclarationReader {
105
105
  ];
106
106
  }
107
107
 
108
+ aliasesUsedBy(symbol: ts.Symbol, documented: ReadonlySet<string>): string[] {
109
+ const found = new Map<string, string>();
110
+ const seen = new Set<ts.Type>();
111
+ const visit = (type: ts.Type) => {
112
+ if (seen.has(type)) return;
113
+ seen.add(type);
114
+ const alias = type.aliasSymbol;
115
+ if (alias) {
116
+ const [declaration] = alias.declarations ?? [];
117
+ if (
118
+ declaration &&
119
+ ts.isTypeAliasDeclaration(declaration) &&
120
+ !declaration.typeParameters &&
121
+ this.#isOwn(declaration) &&
122
+ !documented.has(alias.name)
123
+ )
124
+ found.set(alias.name, this.declarationText(alias));
125
+ return;
126
+ }
127
+ if (type.isUnionOrIntersection()) for (const each of type.types) visit(each);
128
+ else if (type.flags & ts.TypeFlags.Object && (type as ts.ObjectType).objectFlags & ts.ObjectFlags.Anonymous)
129
+ for (const property of this.#checker.getPropertiesOfType(type)) visit(this.#checker.getTypeOfSymbol(property));
130
+ };
131
+ for (const signature of this.#checker.getTypeOfSymbol(symbol).getCallSignatures()) {
132
+ for (const parameter of signature.getParameters()) visit(this.#checker.getTypeOfSymbol(parameter));
133
+ visit(signature.getReturnType());
134
+ }
135
+ return [...found.values()];
136
+ }
137
+
108
138
  foreignBases(symbol: ts.Symbol): string[] {
109
139
  const [declaration] = symbol.declarations ?? [];
110
140
  const nodes =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.66",
3
+ "version": "3.3.0-rc.67",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.66",
53
+ "@akanjs/language": "3.3.0-rc.67",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.66",
62
+ "akanjs": "3.3.0-rc.67",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",