@akanjs/devkit 3.2.0-rc.31 → 3.2.0-rc.32

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.
@@ -143,6 +143,32 @@ const givenOptionsOf = (argMetas: (ArgMeta | InternalArgMeta)[], opt: Record<str
143
143
  return given;
144
144
  };
145
145
 
146
+ const argValuesOf = (argMetas: (ArgMeta | InternalArgMeta)[], cmdArgs: unknown[], opt: Record<string, unknown>) => {
147
+ const values = givenOptionsOf(argMetas, opt);
148
+ for (const argMeta of argMetas) {
149
+ if (argMeta.type === "Argument") values[argMeta.name] = cmdArgs[argMeta.idx] ?? argMeta.argsOption.default;
150
+ else if (argMeta.type === "Option") values[argMeta.name] ??= argMeta.argsOption.default;
151
+ }
152
+ return values;
153
+ };
154
+
155
+ const resolvedValuesOf = (argMetas: (ArgMeta | InternalArgMeta)[], commandArgs: unknown[]) =>
156
+ Object.fromEntries(
157
+ argMetas.flatMap((argMeta) =>
158
+ argMeta.type === "Option" || argMeta.type === "Argument" ? [[argMeta.name, commandArgs[argMeta.idx]]] : [],
159
+ ),
160
+ );
161
+
162
+ const versionGateOf = (cliVersion: string | undefined) => {
163
+ let warning = WorkspaceVersionCheck.warning(cliVersion, process.argv, process.cwd());
164
+ const refusal = WorkspaceVersionCheck.refusal(cliVersion, process.argv, process.cwd());
165
+ return (targetOption: TargetOption, values: { [name: string]: unknown }) => {
166
+ if (refusal && !WorkspaceVersionCheck.readsOnly(targetOption, values)) throw new CliError("refused", refusal);
167
+ if (warning) Logger.rawLog(chalk.yellow(`\n${warning}`), undefined, "error");
168
+ warning = null;
169
+ };
170
+ };
171
+
146
172
  const normalizeEnumChoices = (enumChoices: EnumChoices) =>
147
173
  enumChoices.map((choice: EnumChoice) =>
148
174
  typeof choice === "object"
@@ -509,8 +535,7 @@ export const runCommands = async (...commands: CommandCls[]) => {
509
535
  program.version(process.env.AKAN_VERSION).description("Akan CLI").configureHelp({
510
536
  helpWidth: 100,
511
537
  });
512
- const versionWarning = WorkspaceVersionCheck.warning(cliPackageJson?.version, process.argv, process.cwd());
513
- if (versionWarning) Logger.rawLog(chalk.yellow(`\n${versionWarning}`), undefined, "error");
538
+ const checkVersion = versionGateOf(cliPackageJson?.version);
514
539
 
515
540
  for (const command of commands) {
516
541
  const targetMetas = getTargetMetas(command);
@@ -569,6 +594,7 @@ export const runCommands = async (...commands: CommandCls[]) => {
569
594
  usage: false,
570
595
  given: givenOptionsOf(allArgMetas, opt),
571
596
  });
597
+ checkVersion(targetMeta.targetOption, argValuesOf(allArgMetas, cmdArgs, opt));
572
598
  const commandArgs = [] as unknown[];
573
599
  if (targetMeta.targetOption.runsOnWorkspaceRoot) {
574
600
  await assertCurrentDirectoryIsWorkspaceRoot();
@@ -606,6 +632,8 @@ export const runCommands = async (...commands: CommandCls[]) => {
606
632
  assignCommandContext(commandContext, argMeta, commandArgs[argMeta.idx]);
607
633
  if ((opt as { verbose?: boolean }).verbose) Executor.setVerbose(true);
608
634
  }
635
+ //? Again on the answers: a left-out argument reads as read-only above, then may be answered `apply`.
636
+ checkVersion(targetMeta.targetOption, resolvedValuesOf(allArgMetas, commandArgs));
609
637
  const cmd = CommandContainer.get(command);
610
638
 
611
639
  try {
@@ -763,6 +763,83 @@ describe("a target left out where no terminal can ask for it", () => {
763
763
  }, 30_000);
764
764
  });
765
765
 
766
+ describe("a CLI of another major.minor than the workspace's akanjs", () => {
767
+ const track = tempRoots();
768
+ const run = async (args: string[], env: { [name: string]: string } = {}) => {
769
+ const { root } = track(await makeCliTempWorkspace());
770
+ await writeText(path.join(root, "package.json"), '{ "name": "repo", "version": "1.0.0" }\n');
771
+ await writeText(path.join(root, "tsconfig.json"), "{}\n");
772
+ await writeText(path.join(root, "node_modules/akanjs/package.json"), '{ "name": "akanjs", "version": "1.0.0" }\n');
773
+ const entry = path.join(root, "cli.ts");
774
+ await writeText(
775
+ entry,
776
+ [
777
+ `import { command, runCommands } from ${JSON.stringify(path.join(import.meta.dir, "index.ts"))};`,
778
+ 'class ThingCommand extends command("thing", ({ public: target }) => ({',
779
+ ' makeThing: target({ desc: "writes a thing" }).exec(async function () {',
780
+ ' process.stdout.write("made\\n");',
781
+ " }),",
782
+ ' showThing: target({ desc: "reads a thing", readOnly: true }).exec(async function () {',
783
+ ' process.stdout.write("shown\\n");',
784
+ " }),",
785
+ ' fixThing: target({ desc: "fixes a thing", readOnly: ({ fix }) => fix === false })',
786
+ ' .option("fix", Boolean, { default: true })',
787
+ " .exec(async function (fix) {",
788
+ ' process.stdout.write("fix " + fix + "\\n");',
789
+ " }),",
790
+ ' actThing: target({ desc: "acts on a thing", readOnly: ({ action }) => action !== "apply" })',
791
+ ' .option("action", String, { enum: () => ["apply"] })',
792
+ " .exec(async function (action) {",
793
+ ' process.stdout.write("acted " + action + "\\n");',
794
+ " }),",
795
+ "})) {}",
796
+ "await runCommands(ThingCommand);",
797
+ "",
798
+ ].join("\n"),
799
+ );
800
+ const proc = Bun.spawn(["bun", entry, ...args], {
801
+ cwd: root,
802
+ env: { ...process.env, AKAN_ALLOW_VERSION_MISMATCH: "", ...env },
803
+ stdin: "ignore",
804
+ stdout: "pipe",
805
+ stderr: "pipe",
806
+ });
807
+ const [stdout, stderr, code] = await Promise.all([
808
+ new Response(proc.stdout).text(),
809
+ new Response(proc.stderr).text(),
810
+ proc.exited,
811
+ ]);
812
+ return { stdout, stderr, code };
813
+ };
814
+
815
+ test("refuses a command that writes, before it runs, naming akan update and the override", async () => {
816
+ const refused = await run(["make-thing"]);
817
+ expect(refused.code).toBe(2);
818
+ expect(refused.stdout).toContain("but this workspace has akanjs 1.0.0, another major.minor");
819
+ expect(refused.stdout).toContain("akan update");
820
+ expect(refused.stdout).toContain("AKAN_ALLOW_VERSION_MISMATCH=1");
821
+ expect(refused.stdout).not.toContain("made");
822
+ expect((await run(["fix-thing"])).code).toBe(2);
823
+ }, 30_000);
824
+
825
+ test("decides on the values the left-out arguments resolve to, so one answered later cannot slip through", async () => {
826
+ const acted = await run(["act-thing"]);
827
+ expect(acted.code).toBe(2);
828
+ expect(acted.stdout).toContain("AKAN_ALLOW_VERSION_MISMATCH=1");
829
+ expect(acted.stdout).not.toContain("acted");
830
+ expect((await run(["act-thing"], { AKAN_ALLOW_VERSION_MISMATCH: "1" })).stdout).toContain("acted apply\n");
831
+ }, 30_000);
832
+
833
+ test("only warns for a read-only command, and runs a writing one with the override set", async () => {
834
+ const shown = await run(["show-thing"]);
835
+ expect([shown.code, shown.stdout.trim()]).toEqual([0, "shown"]);
836
+ expect(shown.stderr).toContain("but this workspace has akanjs 1.0.0");
837
+ expect((await run(["fix-thing", "--fix", "false"])).stdout).toContain("fix false\n");
838
+ const overridden = await run(["make-thing"], { AKAN_ALLOW_VERSION_MISMATCH: "1" });
839
+ expect([overridden.code, overridden.stdout.trim()]).toEqual([0, "made"]);
840
+ }, 30_000);
841
+ });
842
+
766
843
  describe("the exit code of a command that failed", () => {
767
844
  const track = tempRoots();
768
845
  const run = async (
@@ -1055,7 +1132,7 @@ describe("a workspace whose akanjs is not the CLI's version", () => {
1055
1132
  'class PlanRunner extends runner("plan") {}',
1056
1133
  'class PlanScript extends script("plan", [PlanRunner]) {}',
1057
1134
  'class PlanCommand extends command("plan", [PlanScript], ({ public: target }) => ({',
1058
- ' plan: target({ desc: "plans", stdio: true }).exec(async function () {',
1135
+ ' plan: target({ desc: "plans", stdio: true, readOnly: true }).exec(async function () {',
1059
1136
  " process.stdout.write(JSON.stringify({ phases: 1 }));",
1060
1137
  " }),",
1061
1138
  "})) {}",
@@ -48,6 +48,8 @@ export interface TargetOption {
48
48
  usageExitCode?: number;
49
49
  /** It deletes files in its app, lib, pkg or module, so one left out or unknown is refused, never picked or asked. */
50
50
  destructive?: boolean;
51
+ /** Writes nothing akanjs's version shapes, so another major.minor CLI only warns; left out, it is refused. */
52
+ readOnly?: boolean | ((values: { [name: string]: unknown }) => boolean);
51
53
  /** Runs after the CLI printed a failure and before it exits, so what it writes ends the output. */
52
54
  onFailure?: (error: unknown, failure: TargetFailure) => void | Promise<void>;
53
55
  }
@@ -77,4 +77,73 @@ describe("WorkspaceVersionCheck", () => {
77
77
  expect(WorkspaceVersionCheck.installedAkanVersion(root)).toBeNull();
78
78
  expect(WorkspaceVersionCheck.warning("3.1.0", argv("sync", "demo"), root)).toBeNull();
79
79
  });
80
+
81
+ describe("refusal", () => {
82
+ test("refuses another major.minor, naming both versions, akan update and the variable that overrides it", async () => {
83
+ const root = await makeWorkspace({ akanjs: "3.1.4" });
84
+
85
+ const refusal = WorkspaceVersionCheck.refusal("3.2.0", argv("sync", "demo"), root, {});
86
+
87
+ expect(refusal).toContain("@akanjs/cli 3.2.0, but this workspace has akanjs 3.1.4, another major.minor");
88
+ expect(refusal).toContain("`akan sync` is refused");
89
+ expect(refusal).toContain("Move the workspace and this CLI to one release together: akan update\n");
90
+ expect(refusal).toContain("Or run the matching CLI once: bunx -p @akanjs/cli@3.1.4 akan sync demo");
91
+ expect(refusal).toEndWith("Or set AKAN_ALLOW_VERSION_MISMATCH=1 to run it anyway.");
92
+ expect(WorkspaceVersionCheck.refusal("4.0.0-rc.1", argv("sync"), root, {})).toContain("akan update --tag rc");
93
+ });
94
+
95
+ test("tells a CLI older than the workspace to install the matching one, not to run akan update", async () => {
96
+ const refusal = WorkspaceVersionCheck.refusal(
97
+ "3.1.4",
98
+ argv("sync", "demo"),
99
+ await makeWorkspace({ akanjs: "3.2.0" }),
100
+ {},
101
+ );
102
+
103
+ expect(refusal).toContain("Install the CLI this workspace was moved to: bun add -g @akanjs/cli@3.2.0");
104
+ expect(refusal).not.toContain("akan update");
105
+ });
106
+
107
+ test("passes the same major.minor, prereleases of it included, leaving the warning", async () => {
108
+ for (const [cli, akanjs] of [
109
+ ["3.2.0-rc.5", "3.2.0-rc.3"],
110
+ ["3.2.1", "3.2.0"],
111
+ ["3.2.0", "3.2.0-rc.9"],
112
+ ] as const) {
113
+ const root = await makeWorkspace({ akanjs });
114
+ expect(WorkspaceVersionCheck.refusal(cli, argv("sync"), root, {})).toBeNull();
115
+ expect(WorkspaceVersionCheck.warning(cli, argv("sync"), root)).toContain(`akanjs ${akanjs}`);
116
+ }
117
+ });
118
+
119
+ test("never refuses update, create-workspace, help or version, nor with the override set", async () => {
120
+ const root = await makeWorkspace({ akanjs: "3.1.4" });
121
+ for (const args of [["update"], ["create-workspace", "next"], ["--version"], ["sync", "--help"]])
122
+ expect(WorkspaceVersionCheck.refusal("3.2.0", argv(...args), root, {})).toBeNull();
123
+ for (const value of ["1", "true"])
124
+ expect(
125
+ WorkspaceVersionCheck.refusal("3.2.0", argv("sync"), root, { AKAN_ALLOW_VERSION_MISMATCH: value }),
126
+ ).toBeNull();
127
+ expect(
128
+ WorkspaceVersionCheck.refusal("3.2.0", argv("sync"), root, { AKAN_ALLOW_VERSION_MISMATCH: "0" }),
129
+ ).not.toBeNull();
130
+ });
131
+
132
+ test("never refuses a workspace that links akanjs from its own source", async () => {
133
+ const root = await makeWorkspace({});
134
+ await writeJson(path.join(root, "pkgs/akanjs/package.json"), { name: "akanjs", version: "2.0.0" });
135
+ await mkdir(path.join(root, "node_modules"), { recursive: true });
136
+ await symlink(path.join(root, "pkgs/akanjs"), path.join(root, "node_modules/akanjs"), "dir");
137
+
138
+ expect(WorkspaceVersionCheck.refusal("3.2.0", argv("sync", "demo"), root, {})).toBeNull();
139
+ });
140
+
141
+ test("counts a command as writing unless it is marked read-only, for the values it was given", () => {
142
+ expect(WorkspaceVersionCheck.readsOnly({ type: "public" }, {})).toBe(false);
143
+ expect(WorkspaceVersionCheck.readsOnly({ type: "public", readOnly: true }, {})).toBe(true);
144
+ const lint = { type: "public", readOnly: ({ fix }: { [name: string]: unknown }) => fix === false } as const;
145
+ expect(WorkspaceVersionCheck.readsOnly(lint, { fix: true })).toBe(false);
146
+ expect(WorkspaceVersionCheck.readsOnly(lint, { fix: false })).toBe(true);
147
+ });
148
+ });
80
149
  });
@@ -1,35 +1,66 @@
1
1
  import { existsSync, readFileSync, realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { PackageJson } from "../workspace/types";
4
+ import type { TargetOption } from "./targetMeta";
5
+
6
+ interface Mismatch {
7
+ args: string[];
8
+ cliVersion: string;
9
+ installed: string;
10
+ pinnedCli: string | null;
11
+ rerun: string;
12
+ update: string;
13
+ }
4
14
 
5
15
  export class WorkspaceVersionCheck {
16
+ static readonly overrideEnv = "AKAN_ALLOW_VERSION_MISMATCH";
6
17
  static readonly #exemptCommands = new Set(["update", "create-workspace"]);
7
18
  static readonly #infoFlags = new Set(["--help", "-h", "--version", "-V"]);
8
19
  static readonly #updateTags = new Set(["dev", "canary", "beta", "rc", "alpha"]);
9
20
 
10
21
  static warning(cliVersion: string | undefined, argv: string[], workspaceRoot: string) {
11
- const args = argv.slice(2);
12
- if (!cliVersion || WorkspaceVersionCheck.#exemptCommands.has(args[0] ?? "")) return null;
13
- if (args.some((arg) => WorkspaceVersionCheck.#infoFlags.has(arg))) return null;
14
- const installed = WorkspaceVersionCheck.installedAkanVersion(workspaceRoot);
15
- if (!installed || installed === cliVersion) return null;
16
- const pinnedCli = WorkspaceVersionCheck.#versionAt(path.join(workspaceRoot, "node_modules/@akanjs/cli"));
17
- const runner = pinnedCli === installed ? ["bunx"] : ["bunx", "-p", `@akanjs/cli@${installed}`];
18
- const rerun = [...runner, "akan", ...args].map(WorkspaceVersionCheck.#quote).join(" ");
19
- const [, prerelease = ""] = cliVersion.split("-");
20
- const tag = prerelease.split(".")[0];
21
- const update = `akan update${WorkspaceVersionCheck.#updateTags.has(tag) ? ` --tag ${tag}` : ""}`;
22
+ const mismatch = WorkspaceVersionCheck.#mismatchOf(cliVersion, argv, workspaceRoot);
23
+ if (!mismatch) return null;
24
+ const { cliVersion: cli, installed, pinnedCli, rerun, update } = mismatch;
22
25
  const lines = [
23
- `This akan is @akanjs/cli ${cliVersion}, but this workspace has akanjs ${installed}: what it generates may not match the installed framework.`,
26
+ `This akan is @akanjs/cli ${cli}, but this workspace has akanjs ${installed}: what it generates may not match the installed framework.`,
24
27
  `Run the matching CLI: ${rerun}`,
25
28
  ];
26
- if (Bun.semver.order(cliVersion, installed) > 0)
29
+ if (Bun.semver.order(cli, installed) > 0)
27
30
  lines.push(`Or move the workspace and this CLI to the newest release of the line together: ${update}`);
28
31
  else if (pinnedCli !== installed)
29
32
  lines.push(`Pin it so \`bunx akan\` runs it: bun add -d @akanjs/cli@${installed}`);
30
33
  return lines.join("\n");
31
34
  }
32
35
 
36
+ static refusal(
37
+ cliVersion: string | undefined,
38
+ argv: string[],
39
+ workspaceRoot: string,
40
+ env: { [name: string]: string | undefined } = process.env,
41
+ ) {
42
+ const mismatch = WorkspaceVersionCheck.#mismatchOf(cliVersion, argv, workspaceRoot);
43
+ if (!mismatch || ["1", "true"].includes(env[WorkspaceVersionCheck.overrideEnv] ?? "")) return null;
44
+ const { args, cliVersion: cli, installed, rerun, update } = mismatch;
45
+ if (WorkspaceVersionCheck.#lineOf(cli) === WorkspaceVersionCheck.#lineOf(installed)) return null;
46
+ //? An older CLI is not told `akan update`: it resolves the tag this CLI came from and could move akanjs back.
47
+ const realign =
48
+ Bun.semver.order(cli, installed) > 0
49
+ ? `Move the workspace and this CLI to one release together: ${update}`
50
+ : `Install the CLI this workspace was moved to: bun add -g @akanjs/cli@${installed}`;
51
+ return [
52
+ `This akan is @akanjs/cli ${cli}, but this workspace has akanjs ${installed}, another major.minor, so \`akan ${args[0]}\` is refused: it writes to the workspace, and what it writes would not match the installed framework.`,
53
+ realign,
54
+ `Or run the matching CLI once: ${rerun}`,
55
+ `Or set ${WorkspaceVersionCheck.overrideEnv}=1 to run it anyway.`,
56
+ ].join("\n");
57
+ }
58
+
59
+ static readsOnly(targetOption: TargetOption, values: { [name: string]: unknown }) {
60
+ const { readOnly = false } = targetOption;
61
+ return typeof readOnly === "function" ? readOnly(values) : readOnly;
62
+ }
63
+
33
64
  static installedAkanVersion(workspaceRoot: string) {
34
65
  const packageDir = path.join(workspaceRoot, "node_modules", "akanjs");
35
66
  if (!existsSync(packageDir)) return null;
@@ -38,6 +69,25 @@ export class WorkspaceVersionCheck {
38
69
  return WorkspaceVersionCheck.#versionAt(packageDir);
39
70
  }
40
71
 
72
+ static #mismatchOf(cliVersion: string | undefined, argv: string[], workspaceRoot: string): Mismatch | null {
73
+ const args = argv.slice(2);
74
+ if (!cliVersion || WorkspaceVersionCheck.#exemptCommands.has(args[0] ?? "")) return null;
75
+ if (args.some((arg) => WorkspaceVersionCheck.#infoFlags.has(arg))) return null;
76
+ const installed = WorkspaceVersionCheck.installedAkanVersion(workspaceRoot);
77
+ if (!installed || installed === cliVersion) return null;
78
+ const pinnedCli = WorkspaceVersionCheck.#versionAt(path.join(workspaceRoot, "node_modules/@akanjs/cli"));
79
+ const runner = pinnedCli === installed ? ["bunx"] : ["bunx", "-p", `@akanjs/cli@${installed}`];
80
+ const rerun = [...runner, "akan", ...args].map(WorkspaceVersionCheck.#quote).join(" ");
81
+ const [, prerelease = ""] = cliVersion.split("-");
82
+ const tag = prerelease.split(".")[0];
83
+ const update = `akan update${WorkspaceVersionCheck.#updateTags.has(tag) ? ` --tag ${tag}` : ""}`;
84
+ return { args, cliVersion, installed, pinnedCli, rerun, update };
85
+ }
86
+
87
+ static #lineOf(version: string) {
88
+ return version.split("-")[0]?.split(".").slice(0, 2).join(".");
89
+ }
90
+
41
91
  static #versionAt(packageDir: string) {
42
92
  const packageJsonPath = path.join(packageDir, "package.json");
43
93
  if (!existsSync(packageJsonPath)) return null;
@@ -12,6 +12,11 @@ const MAX_BROTLI_QUALITY = 11;
12
12
  const BROTLI_QUALITY_BY_EXT = { ".css": MAX_BROTLI_QUALITY } as const;
13
13
  const DEFAULT_BROTLI_QUALITY = 9;
14
14
  const GZIP_LEVEL = 9;
15
+ const ROOT_BROTLI_QUALITY: Record<string, number | undefined> = {
16
+ client: undefined,
17
+ styles: undefined,
18
+ dict: MAX_BROTLI_QUALITY,
19
+ };
15
20
  const { formatBytes } = FontPruner;
16
21
 
17
22
  export interface PrecompressArtifactsResult {
@@ -24,11 +29,10 @@ export interface PrecompressArtifactsResult {
24
29
  export async function precompressArtifacts(app: App): Promise<PrecompressArtifactsResult> {
25
30
  //* WebRouter serves client/, styles/ and dict/ through the same sidecar-aware WebRouteContext.fileResponse.
26
31
  const artifactDir = path.join(app.dist.cwdPath, ".akan/artifact");
27
- const roots = [
28
- { root: path.join(artifactDir, "client") },
29
- { root: path.join(artifactDir, "styles") },
30
- { root: path.join(artifactDir, "dict"), brotliQuality: MAX_BROTLI_QUALITY },
31
- ];
32
+ const roots = Object.entries(ROOT_BROTLI_QUALITY).map(([dir, brotliQuality]) => ({
33
+ root: path.join(artifactDir, dir),
34
+ brotliQuality,
35
+ }));
32
36
  const result: PrecompressArtifactsResult = { files: 0, inputBytes: 0, outputBytes: 0, brotliBytes: 0 };
33
37
 
34
38
  await Promise.all(roots.map(({ root, brotliQuality }) => precompressRoot(root, result, brotliQuality)));
@@ -63,6 +67,15 @@ async function precompressRoot(
63
67
  }
64
68
  }
65
69
 
70
+ export async function servedBrotliBytesOf(artifactDir: string, filePath: string): Promise<number> {
71
+ const root = path.relative(artifactDir, filePath).split(path.sep)[0] ?? "";
72
+ if (!Object.hasOwn(ROOT_BROTLI_QUALITY, root) || !(await shouldPrecompress(filePath))) return Bun.file(filePath).size;
73
+ const bytes = await Bun.file(filePath).bytes();
74
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
75
+ const quality = ROOT_BROTLI_QUALITY[root] ?? brotliQualityOf(path.extname(filePath).toLowerCase());
76
+ return brotliCompress(buffer, quality).byteLength;
77
+ }
78
+
66
79
  function brotliQualityOf(ext: string): number {
67
80
  return BROTLI_QUALITY_BY_EXT[ext as keyof typeof BROTLI_QUALITY_BY_EXT] ?? DEFAULT_BROTLI_QUALITY;
68
81
  }
@@ -7,6 +7,8 @@ const track = tempRoots();
7
7
 
8
8
  const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
9
9
 
10
+ const crashWindowMs = 2_000;
11
+
10
12
  const until = async (proc: Bun.Subprocess, what: string, condition: () => boolean, timeoutMs = 20_000) => {
11
13
  const deadline = Date.now() + timeoutMs;
12
14
  while (!condition()) {
@@ -443,6 +445,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
443
445
  AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
444
446
  AKAN_PUBLIC_ENV: "local",
445
447
  AKAN_WATCH: "0",
448
+ AKAN_DEV_SSR_CRASH_RETRY_MS: String(crashWindowMs),
446
449
  },
447
450
  stdio: ["ignore", "ignore", "ignore"],
448
451
  serialization: "advanced",
@@ -453,11 +456,10 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
453
456
  const ssrRuns = async () =>
454
457
  (await Bun.file(runs).exists()) ? (await Bun.file(runs).text()).trim().split("\n").map(Number) : [];
455
458
  try {
456
- //? boot-armed waits out the 10s crash window first, so 20s left a loaded machine too little for the rest.
457
- await until(proc, "boot-armed", () => messages.some((message) => message.type === "boot-armed"), 30_000);
459
+ await until(proc, "boot-armed", () => messages.some((message) => message.type === "boot-armed"));
458
460
  const [first = 0, second = 0] = await ssrRuns();
459
461
  expect(await ssrRuns()).toHaveLength(2);
460
- expect(second - first).toBeGreaterThanOrEqual(9_500);
462
+ expect(second - first).toBeGreaterThanOrEqual(crashWindowMs - 500);
461
463
  proc.send({
462
464
  type: "build-route",
463
465
  id: 1,
@@ -471,7 +473,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
471
473
  const deadline = Date.now() + 15_000;
472
474
  while ((await ssrRuns()).length < 3 && Date.now() < deadline) await wait(100);
473
475
  const [, retried = 0, third = 0] = await ssrRuns();
474
- expect(third - retried).toBeGreaterThanOrEqual(9_500);
476
+ expect(third - retried).toBeGreaterThanOrEqual(crashWindowMs - 500);
475
477
  } finally {
476
478
  proc.kill();
477
479
  await proc.exited;
@@ -510,6 +512,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
510
512
  AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
511
513
  AKAN_PUBLIC_ENV: "local",
512
514
  AKAN_WATCH: "0",
515
+ AKAN_DEV_SSR_CRASH_RETRY_MS: String(crashWindowMs),
513
516
  },
514
517
  stdio: ["ignore", "ignore", "ignore"],
515
518
  serialization: "advanced",
@@ -533,7 +536,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
533
536
  const deadline = Date.now() + 20_000;
534
537
  while ((await ssrRuns()).length < 3 && Date.now() < deadline) await wait(100);
535
538
  const [, killed = 0, retried = 0] = await ssrRuns();
536
- expect(retried - killed).toBeGreaterThanOrEqual(9_500);
539
+ expect(retried - killed).toBeGreaterThanOrEqual(crashWindowMs - 500);
537
540
  } finally {
538
541
  proc.kill();
539
542
  await proc.exited;
@@ -43,7 +43,11 @@ export class SsrRegistry {
43
43
  //* before reporting (an OOM kill) route builds do retry, at most every `#crashRetryMs`.
44
44
  #ssrBroken = false;
45
45
  #ssrCrashedAt: number | null = null;
46
- static readonly #crashRetryMs = 10_000;
46
+ static get #crashRetryMs(): number {
47
+ //? `AKAN_DEV_SSR_CRASH_RETRY_MS` is a test hook: a builder test waits out a shorter window than a developer's.
48
+ const ms = Number(process.env.AKAN_DEV_SSR_CRASH_RETRY_MS);
49
+ return Number.isInteger(ms) && ms > 0 ? ms : 10_000;
50
+ }
47
51
 
48
52
  constructor(
49
53
  app: App,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.2.0-rc.31",
3
+ "version": "3.2.0-rc.32",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -205,16 +205,16 @@
205
205
  "./*": "./*.ts"
206
206
  },
207
207
  "dependencies": {
208
- "@akanjs/language": "3.2.0-rc.31",
209
- "@earendil-works/pi-agent-core": "1.3.0",
210
- "@earendil-works/pi-ai": "1.3.0",
211
- "@earendil-works/pi-codemode": "1.3.0",
212
- "@earendil-works/pi-coding-agent": "1.3.0",
213
- "@earendil-works/pi-mcp": "1.3.0",
214
- "@earendil-works/pi-tui": "1.3.0",
208
+ "@akanjs/language": "3.2.0-rc.32",
209
+ "@earendil-works/pi-agent-core": "1.5.2",
210
+ "@earendil-works/pi-ai": "1.5.2",
211
+ "@earendil-works/pi-codemode": "1.5.2",
212
+ "@earendil-works/pi-coding-agent": "1.5.2",
213
+ "@earendil-works/pi-mcp": "1.5.2",
214
+ "@earendil-works/pi-tui": "1.5.2",
215
215
  "@inquirer/prompts": "^8.7.3",
216
216
  "@tailwindcss/node": "^4.3.3",
217
- "akanjs": "3.2.0-rc.31",
217
+ "akanjs": "3.2.0-rc.32",
218
218
  "chalk": "^6.0.1",
219
219
  "commander": "^15.0.0",
220
220
  "dayjs": "^1.11.23",
@@ -1,4 +1,4 @@
1
- import { describe, expect, test } from "bun:test";
1
+ import { beforeAll, describe, expect, test } from "bun:test";
2
2
  import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
@@ -9,6 +9,21 @@ const serve = (html: string, status = 200) =>
9
9
  Bun.serve({ port: 0, fetch: () => new Response(html, { status, headers: { "content-type": "text/html" } }) });
10
10
 
11
11
  const browserTestMs = PreviewView.startTimeoutMs + 30_000;
12
+ //? Chrome starts once per process and took ~35 s on a cold CI runner: one stuck past this is killed and started again.
13
+ const browserStartDeadlineMs = 45_000;
14
+
15
+ const startBrowser = async () => {
16
+ const open = () =>
17
+ PreviewView.probe("about:blank", { startTimeoutMs: browserStartDeadlineMs, timeoutMs: browserStartDeadlineMs });
18
+ try {
19
+ await open();
20
+ } catch (error) {
21
+ if (!(error instanceof Error) || !error.message.startsWith("Timed out starting")) throw error;
22
+ Bun.WebView.closeAll();
23
+ await Bun.sleep(100);
24
+ await open();
25
+ }
26
+ };
12
27
  const slowChromeRuns = PreviewView.isAvailable("chrome") && process.platform !== "win32";
13
28
 
14
29
  const withSlowChrome = async (body: string, startSeconds = 3) => {
@@ -46,6 +61,13 @@ const withSlowChrome = async (body: string, startSeconds = 3) => {
46
61
  };
47
62
 
48
63
  describe("PreviewView", () => {
64
+ beforeAll(
65
+ async () => {
66
+ if (PreviewView.available) await startBrowser();
67
+ },
68
+ browserStartDeadlineMs * 2 + 5_000,
69
+ );
70
+
49
71
  test("reports whether this Bun build can drive a headless page at all", () => {
50
72
  expect(typeof PreviewView.available).toBe("boolean");
51
73
  });
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
+ import { chmod } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { tempDirs, writeText } from "../test/testHelpers";
4
5
  import { AbstractDoc } from "./abstractDoc";
@@ -174,6 +175,45 @@ describe("AkanQualityScanner ssr rules", () => {
174
175
  expect(ssrBalance[1]).toMatchObject({ serverMass: 0, clientMass: 1 });
175
176
  expect(ssrBalance[2]).toMatchObject({ scope: "workspace", serverMass: 3, clientMass: 1 });
176
177
  });
178
+
179
+ test("an SSR scan of some folders reads only them and the libs' signals, and warns there as the full scan does", async () => {
180
+ const root = await makeWorkspace({
181
+ "libs/shared/lib/item/item.signal.ts": [
182
+ "export class ItemEndpoint extends endpoint(srv.item, ({ mutation }) => ({",
183
+ ' approveItem: mutation(cnst.Item, { guards: [User] }).param("itemId", ID).exec(async function (itemId) {',
184
+ " return await this.itemService.approve(itemId);",
185
+ " }),",
186
+ "})) {}",
187
+ "",
188
+ ].join("\n"),
189
+ "apps/demo/page/item/[itemId].tsx": [
190
+ 'import { fetch } from "@apps/demo/client";',
191
+ 'import { ID } from "akanjs/base";',
192
+ 'import { page } from "akanjs/client";',
193
+ "",
194
+ 'export default page().param("itemId", ID).render(async ({ itemId }) => {',
195
+ " await fetch.approveItem(itemId);",
196
+ " return <p>{itemId}</p>;",
197
+ "});",
198
+ "",
199
+ ].join("\n"),
200
+ "apps/demo/ui/Plain.tsx": `"use client";\nexport const Plain = () => <div>plain</div>;\n`,
201
+ "apps/other/ui/Plain.tsx": `"use client";\nexport const Plain = () => <div>plain</div>;\n`,
202
+ });
203
+ const scanner = new AkanQualityScanner();
204
+ const full = (await scanner.scan(root)).warnings.filter(
205
+ (warning) => warning.scope === "ssr" && warning.file?.startsWith("apps/demo/"),
206
+ );
207
+ await chmod(path.join(root, "apps/other/ui/Plain.tsx"), 0);
208
+
209
+ const scoped = await scanner.scanSsr(root, ["apps/demo"]);
210
+
211
+ expect(scoped.map(({ rule, file }) => [rule, file])).toEqual([
212
+ ["akan.ssr.render-mutation", "apps/demo/page/item/[itemId].tsx"],
213
+ ["akan.ssr.unnecessary-use-client", "apps/demo/ui/Plain.tsx"],
214
+ ]);
215
+ expect(scoped).toEqual(full);
216
+ });
177
217
  });
178
218
 
179
219
  describe("AkanQualityScanner layout rules", () => {