@akanjs/devkit 3.3.0-rc.40 → 3.3.0-rc.42

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.
package/CHANGELOG.md CHANGED
@@ -211,6 +211,14 @@
211
211
  An app built with the akan-native CLI's own config grants the same in its capabilities: `{ identifier: "external-view:default", allow: [{ origin: "https://board.example" }] }`, `"external-view:allow-evaluate"` and `"external-view:allow-sendKey"`. A grant of `external-view:all` or `external-view:allow-open` opens no origin unless its own `allow` lists them. A page that passed `window` to `open` passes its own window or leaves it out.
212
212
 
213
213
  - 1712cf0: The image carries `bin`. `akan build` fetches each `bin` entry's `linux-x64` and `linux-arm64` file into the build's `bin/amd64/` and `bin/arm64/`, and the generated Dockerfile puts the folder its `TARGETARCH` names first on PATH, so an executable the server spawns is declared once for the image and the desktop app. An entry with no Linux file is still left to `docker.preRuns`; one that has both now runs the carried file, which is ahead on PATH. An app that writes its own Dockerfile adds `ENV PATH=/workspace/bin/$TARGETARCH:$PATH` itself, and the build says so. `akan start` warns when a declared executable is not on the computer's PATH. The byte budget of the `akan-runtime` skill's `runtimeRule-3.md` is raised on purpose for the new text.
214
+ - 612f146: The generated image starts the server under an init, and the runtime guide covers a device on a LAN.
215
+
216
+ The Dockerfile `akan build` writes now installs `tini` and ends in `ENTRYPOINT ["tini","-s","--"]` before its `CMD`. With `bun` as PID 1, a process whose parent died first (the `ffmpeg` of a killed `sh -c '… | ffmpeg'`) was re-parented to it and stayed `<defunct>` for the life of the container, because Bun never waits for a child it did not start. tini reaps them, passes signals on to the server and exits with its code; `-s` keeps that working under `docker run --init` or a shared process namespace. `docker.command` is still the `CMD`, and `docker run <image> bun main.js ops …` runs as before. An app whose `docker` is a whole Dockerfile is not changed and adds an init itself.
217
+
218
+ The runtime guide gains two things. The image section says a device node needs its group as well as `--device` (`--group-add` with the host's numeric gid, or `supplementalGroups` in a pod), since the server is uid 1000 with no other group. A new section, "An Image On A Device", is the recipe for a board reached by IP with no domain: build `--env main` rather than `local`, what the serve domain is for when nothing resolves it, `AKAN_PUBLIC_OPERATION_MODE=edge`, the secrets to hand over, the two directories to put on volumes (`/workspace/sqlite`, `/workspace/local`), and that a browser session needs HTTPS outside operation mode `local`.
219
+
220
+ The guide's `runtimeRule-2.md` reference is 3987 bytes larger, and its budget is raised to match.
221
+
214
222
  - 8d75f2b: The public surface 3.2.0 deprecated is removed. `akanjs` and `@akanjs/devkit` publish only the subpaths their `exports` name, with no wildcard, so a file becomes public only when an entry names it.
215
223
 
216
224
  - **`@akanjs/devkit` has no root aliases and no `./*` or `./*.ts`.** It publishes `@akanjs/devkit` (types only), `biome.base.json`, the facets `akanApp`, `akanConfig`, `artifact`, `cloud`, `codeAgent`, `commandDecorators`, `executors`, `frontendBuild`, `incrementalBuilder`, `mobile`, `pipeline`, `preview`, `transforms` and `workflow`, and the files `app/applicationBuildRunner`, `cloud/cloudApi`, `cloud/cloudUpdates`, `commandDecorators/exitCodeError`, `mobile/desktopRelease`, `mobile/serverBundleSecrets` and `transforms/serverEnvProfile`. `util/fileEditor`, `util/selectModel` and `workspace/getRelatedCnsts` are named too, and deprecated: nothing in akanjs uses them.
@@ -409,6 +417,16 @@
409
417
  - f678e80: The skills no longer repeat the path rule an agent has already loaded for the same files: `akan-query` points at the `module` rule for its musts (500 rows, soft removal, hookless writes, secret projections, cascade direction), `akan-transport` at the `auth` rule for guards and drops what the `server` rule says about body types, the 30-second default deadline and remote errors, `akan-service`, `akan-err` and `akan-mcp` at the `server` rule, and `akan-ui`, `cssRule` and `componentRule` at the `style` rule for class order and the colour vocabulary. The `server` rule drops its in-page agent line, which the `akan-agent` skill already holds and which no service, signal or document file needs. Run `akan agent install` in a workspace to pick up the new files.
410
418
  - ce430ed: A coding agent reads less before its first page: the generated AGENTS.md is about 9% smaller, leaving to the path rules what they already say while still naming every check that breaks the build, and it now says that `i18n: { localePrefix: "as-needed" }` in `akan.config.ts` serves URLs without `/<locale>/`. The `akan-page` skill now holds the guard basics, the first-render `searchParams` snapshot and Link prefetch, so `pageRule` keeps only the deeper contract (12 KB to 7 KB), and the `@akanjs/cli` README tells an agent to read the workspace's `AGENTS.md`, rules and skills rather than the package's `guidelines/` folder. Run `akan agent install` in a workspace to pick up the new files.
411
419
  - c44d068: A coding agent reads less to build its first app: the `akanjs` README keeps the path to a first app and links the rest on akanjs.com (17 KB to 7 KB), the `akan-page` and `akan-service` skills ship the API reference one section at a time with every entry named in the skill's index (`Link` now lists the anchor attributes it takes and `Link.Back`, `Link.Close` and `Link.Lang`), the `akan-page` skill holds what a first page looks up while `pageRule` keeps the deeper contract, and each rule is stated once across AGENTS.md, the path rules and the skills. Run `akan agent install` in a workspace to pick up the new files.
420
+ - 22791e7: A production page loads fewer, larger client files: the client entries exactly the same routes load are built as one.
421
+
422
+ `akan build` gave every `"use client"` file, and every export of one it takes apart, an entry of its own. The bundler puts a module in a chunk of its own for every different set of entries that reach it, so an app with several hundred entries ended with hundreds of small files per page, many under 1 KB, where a file is served uncompressed. Entries that the same set of routes loads are now one entry, so what only they reach is one chunk. Entries any other set of routes loads stay apart, and a route still downloads nothing it did not download before.
423
+
424
+ On a real workspace's largest app (236 routes, brotli as served) every route got smaller, by 3.8 to 60.6 KB: the JS all routes load fell 3.4% in total, the median route went from 764.7 to 748.1 KB, and the routes of its signed-in area from a median of 836.0 to 801.8 KB. A signed-in route loads a median of 354 files against 454. The build writes 1,414 client files against 1,827, 5.7% fewer bytes on disk, and 518 files under 1 KB against 688. This repository's sample apps write 214 files against 232 and 132 against 156.
425
+
426
+ What changes for an app: the files of one group run together, the first time a page uses any of them. A file that does work when it loads — registers something, reads the window — now does it when a file grouped with it is first used, on the same routes as before, and a file that throws while loading takes its group with it. A group's file name changes when any file in it changes, so a returning visitor downloads a group again where one small file changed.
427
+
428
+ `akan start` (development) and the server bundle are unchanged. No upgrade step.
429
+
412
430
  - 56d67dd: A production page loads the exports of a client file it uses, not everything else the file holds.
413
431
 
414
432
  A workspace file with several exports — a `*.Util.tsx`, a `*.Zone.tsx`, a `ui/` or `webkit/` file — was one module to the bundler, so a page rendering `Memo.Util.Remove` also downloaded what `Memo.Util.Edit` imports. `akan build` now hands the browser bundle each such file as one module per export: a top-level declaration that only builds a value (a component, a function, a constant, a class) becomes its own module with the imports it alone reads, and an importer naming `{ Remove }` follows that module only. A `"use client"` file is likewise built as one entry per export, and a route preloads and counts as Route JS the entries of the exports its server files ask for.
@@ -260,7 +260,7 @@ describe("AkanAppConfig", () => {
260
260
  .map(([key, value]) => `ENV ${key}=${value}`)
261
261
  .join("\n");
262
262
  expect(config.dockerfile).toContain(
263
- `COPY . .\n${writeDirsStep}\n${envBlock}\nUSER 1000:1000\nCMD ["bun","main.js"]`,
263
+ `COPY . .\n${writeDirsStep}\n${envBlock}\nUSER 1000:1000\nENTRYPOINT ["tini","-s","--"]\nCMD ["bun","main.js"]`,
264
264
  );
265
265
  });
266
266
 
@@ -276,10 +276,10 @@ describe("AkanAppConfig", () => {
276
276
  });
277
277
 
278
278
  test("writes the Dockerfile instructions it wrote before its env came from getProductionEnv", () => {
279
- //? 9adfb95c's output for this config, less the blank lines its empty interpolations left, its floating tag and root.
279
+ //? 9adfb95c's output for this config, less the blank lines its empty interpolations left, its floating tag and root, plus the init.
280
280
  const before = [
281
281
  `FROM ${DEFAULT_DOCKER_IMAGE}`,
282
- "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*",
282
+ "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*",
283
283
  "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
284
284
  "ARG TARGETARCH",
285
285
  "",
@@ -305,6 +305,7 @@ describe("AkanAppConfig", () => {
305
305
  "ENV AKAN_LOG_TO_FILE=0",
306
306
  "",
307
307
  "USER 1000:1000",
308
+ 'ENTRYPOINT ["tini","-s","--"]',
308
309
  'CMD ["bun","main.js"]',
309
310
  ];
310
311
  const lines = (text: string) => text.split("\n").filter((line) => line !== "");
@@ -318,11 +319,11 @@ describe("AkanAppConfig", () => {
318
319
  ).toThrow("the native apps ship that bundle");
319
320
  });
320
321
 
321
- test("installs only ca-certificates and tzdata in the default image", () => {
322
+ test("installs only ca-certificates, tzdata and the init in the default image", () => {
322
323
  const config = new AkanAppConfig(app, [], packageJson, {}, baseDevEnv);
323
324
 
324
325
  expect(config.dockerfile).toContain(
325
- "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*",
326
+ "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*",
326
327
  );
327
328
  // The Chromium/ffmpeg toolchain moved to per-app `preRuns`; keeping it here paid for it in every image.
328
329
  for (const dropped of ["libnss3", "ffmpeg", "build-essential", "redis", "xdg-utils"])
@@ -348,7 +349,7 @@ describe("AkanAppConfig", () => {
348
349
  const userAt = instructions.indexOf("USER 1000:1000");
349
350
 
350
351
  expect(instructions.filter((line) => line.startsWith("USER "))).toEqual(["USER 1000:1000"]);
351
- expect(instructions.slice(userAt + 1)).toEqual(['CMD ["bun","main.js"]']);
352
+ expect(instructions.slice(userAt + 1)).toEqual(['ENTRYPOINT ["tini","-s","--"]', 'CMD ["bun","main.js"]']);
352
353
  for (const rootStep of ["apt-get update", "apt-get install -y ffmpeg", "bun install", "echo after"])
353
354
  expect(instructions.findIndex((line) => line.includes(rootStep))).toBeLessThan(userAt);
354
355
  expect(instructions.filter((line) => line.includes("--chown"))).toEqual([]);
@@ -13,6 +13,7 @@ import { AkanWorkers } from "./akanWorkers";
13
13
  import { DesktopServerConfig } from "./desktopServerConfig";
14
14
  import {
15
15
  DEFAULT_DOCKER_IMAGE,
16
+ DOCKER_INIT,
16
17
  DOCKER_RUN_USER,
17
18
  DOCKER_WRITE_DIRS,
18
19
  dockerImageScript,
@@ -503,7 +504,7 @@ export class AkanAppConfig implements AppConfigResult {
503
504
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
504
505
  const envLines = Object.entries(env).map(([key, value]) => `ENV ${key}=${value}`);
505
506
  return `${imageScript}${isLocal ? `\n${AkanAppConfig.localImageGuard}` : ""}
506
- RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*
507
+ RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*
507
508
  RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
508
509
  ARG TARGETARCH
509
510
  ${preRunScripts.join("\n")}
@@ -515,7 +516,8 @@ COPY . .
515
516
  RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}
516
517
  ${envLines.join("\n")}
517
518
  USER ${DOCKER_RUN_USER}
518
- CMD [${command.map((c) => `"${c}"`).join(",")}]`;
519
+ ENTRYPOINT ${JSON.stringify(DOCKER_INIT)}
520
+ CMD ${JSON.stringify(command)}`;
519
521
  }
520
522
  static #importGeneration = 0;
521
523
  // Bun caches dynamic imports by path; a fresh query string re-evaluates the config module (its imports stay cached).
@@ -9,6 +9,8 @@ export const BUN_IMAGE_PIN = {
9
9
  export const DEFAULT_DOCKER_IMAGE = `oven/bun:${BUN_IMAGE_PIN.version}-slim@${BUN_IMAGE_PIN.digest}`;
10
10
  //? oven/bun's `bun` user, numeric so a kubelet can check `runAsNonRoot` without reading the image's passwd file.
11
11
  export const DOCKER_RUN_USER = "1000:1000";
12
+ //? Bun as PID 1 never waits for a process re-parented to it, which stays defunct; `-s` reaps under another init too.
13
+ export const DOCKER_INIT = ["tini", "-s", "--"];
12
14
  //? The directories the server writes, its code staying read-only; an empty named volume mounted on one takes its owner.
13
15
  export const DOCKER_WRITE_DIRS = [
14
16
  "/workspace/sqlite",
@@ -141,6 +141,37 @@ describe("route client store bootstrap", () => {
141
141
  });
142
142
  });
143
143
 
144
+ test("remaps a name a build entry holding several entries exports back to the entry and the name behind it", () => {
145
+ const group = "/repo/apps/akan/.akan/generated/client-entry-bootstrap-route/group-1.tsx";
146
+ const reference = "apps/akan/.akan/generated/client-entry-bootstrap-route/group-1.tsx";
147
+ const members = new Map([
148
+ [
149
+ group,
150
+ new Map([
151
+ ["g0", { entry: "/repo/apps/akan/ui/One.tsx", name: "default" }],
152
+ ["g1", { entry: "/repo/apps/akan/ui/Two.tsx", name: "default" }],
153
+ ]),
154
+ ],
155
+ ]);
156
+ const remap = (name: string) =>
157
+ RouteClientBuilder.resolveOriginalManifestEntry(
158
+ `${reference}#${name}`,
159
+ new Map(),
160
+ new Map([[group, reference]]),
161
+ "/repo",
162
+ members,
163
+ );
164
+
165
+ expect(remap("g1")).toEqual({
166
+ buildEntry: group,
167
+ originalEntry: "/repo/apps/akan/ui/Two.tsx",
168
+ name: "default",
169
+ key: "apps/akan/ui/Two.tsx#default",
170
+ });
171
+ expect(remap("g0")?.key).toBe("apps/akan/ui/One.tsx#default");
172
+ expect(remap("g2")).toBeNull();
173
+ });
174
+
144
175
  test("emits browser chunks and assets with hash-only names", () => {
145
176
  expect(CLIENT_BUNDLE_NAMING).toEqual({
146
177
  entry: "[name]-[hash].[ext]",
@@ -809,6 +840,61 @@ export const getSerializedSignalOf = (name: string) => (name === "base" ? {} : {
809
840
  for (const marker of ["heavy-a-marker", "heavy-b-marker"]) expect(started.a).toContain(marker);
810
841
  expect(warnings).toEqual([]);
811
842
  }, 30_000);
843
+
844
+ test("a production build answers the entries the same routes load from one entry, each still found by its own name, and keeps apart an entry other routes load; under start each entry is its own", async () => {
845
+ const { root, appDir, app, file, warnings } = await describedFixture();
846
+ for (const name of ["One", "Two"])
847
+ await write(file(name), `"use client";\nexport default () => "${name.toLowerCase()}-marker";\n`);
848
+ await write(file("Solo"), '"use client";\nexport const Solo = () => "solo-marker";\n');
849
+ const [one, two, solo] = [file("One"), file("Two"), file("Solo")];
850
+ const entriesByRoute = new Map([
851
+ ["/pair", [one, two]],
852
+ ["/all", [two, solo, one]],
853
+ ]);
854
+ const state = globalThis as { $RefreshReg$?: unknown; $RefreshSig$?: unknown };
855
+ state.$RefreshReg$ ??= () => undefined;
856
+ state.$RefreshSig$ ??= () => (type: unknown) => type;
857
+ const buildAs = async (command: "build" | "start") => {
858
+ const { manifestDelta, ssrManifestDelta } = await new RouteClientBuilder({
859
+ app,
860
+ seeds: [],
861
+ entries: [one, two, solo],
862
+ artifact: {} as never,
863
+ browser: "chunks",
864
+ command,
865
+ entriesByRoute,
866
+ }).build();
867
+ const artifact = path.join(
868
+ command === "build" ? path.join(root, "dist/apps/demo") : appDir,
869
+ ".akan/artifact",
870
+ );
871
+ const rowOf = (key: string) => manifestDelta[`apps/demo/ui/${key}`];
872
+ const answered = async (key: string) => {
873
+ const row = rowOf(key);
874
+ const loaded = await import(path.join(artifact, (row?.id ?? "").replace(/^\/_akan\//, "")));
875
+ return (loaded[row?.name ?? ""] as () => string)();
876
+ };
877
+ const onServer = (key: string) => ssrManifestDelta.moduleMap[rowOf(key)?.id ?? ""]?.[rowOf(key)?.name ?? ""];
878
+ return { rows: Object.keys(manifestDelta).sort(), rowOf, answered, onServer };
879
+ };
880
+ const keys = ["One.tsx#default", "Solo.tsx#Solo", "Two.tsx#default"];
881
+
882
+ const built = await buildAs("build");
883
+ expect(built.rows).toEqual(keys.map((key) => `apps/demo/ui/${key}`));
884
+ expect(built.rowOf("One.tsx#default")?.id).toBe(built.rowOf("Two.tsx#default")?.id ?? "");
885
+ expect(built.rowOf("Solo.tsx#Solo")?.id).not.toBe(built.rowOf("One.tsx#default")?.id);
886
+ expect(keys.map((key) => built.rowOf(key)?.name)).toEqual(["g0", "Solo", "g1"]);
887
+ expect(await Promise.all(keys.map(built.answered))).toEqual(["one-marker", "solo-marker", "two-marker"]);
888
+ expect(keys.map((key) => built.onServer(key)?.name)).toEqual(["default", "Solo", "default"]);
889
+ expect(built.onServer("One.tsx#default")?.id).not.toBe(built.onServer("Two.tsx#default")?.id);
890
+
891
+ const started = await buildAs("start");
892
+ expect(started.rows).toEqual(built.rows);
893
+ expect(started.rowOf("One.tsx#default")?.id).not.toBe(started.rowOf("Two.tsx#default")?.id);
894
+ expect(keys.map((key) => started.rowOf(key)?.name)).toEqual(["default", "Solo", "default"]);
895
+ expect(await Promise.all(keys.map(started.answered))).toEqual(["one-marker", "solo-marker", "two-marker"]);
896
+ expect(warnings).toEqual([]);
897
+ }, 30_000);
812
898
  });
813
899
 
814
900
  test("the files a route is sized by hold the store piece of the module its client code names, and no assembled runtime", async () => {
@@ -0,0 +1,77 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
4
+ import type { AskedExports } from "./clientBuildTypes";
5
+ import { ClientEntryGroups } from "./clientEntryGroups";
6
+
7
+ describe("ClientEntryGroups", () => {
8
+ const entry = (name: string) => path.resolve(`/repo/apps/demo/ui/${name}.tsx`);
9
+ const part = (name: string, ...names: string[]) => ({ entry: entry(name), names });
10
+ const entriesOf = (groups: readonly { entry: string }[][]) =>
11
+ groups.map((group) => group.map((held) => path.basename(held.entry, ".tsx")));
12
+
13
+ test("puts together the entries exactly the same routes load, whatever order the routes come in", () => {
14
+ const routes: Record<string, string[]> = {
15
+ Shell: ["/a", "/b"],
16
+ Nav: ["/b", "/a"],
17
+ Board: ["/b"],
18
+ Chart: ["/b"],
19
+ Solo: ["/a"],
20
+ };
21
+
22
+ const groups = ClientEntryGroups.plan(
23
+ Object.keys(routes).map((name) => part(name, name)),
24
+ (held) => routes[path.basename(held.entry, ".tsx")] ?? [],
25
+ );
26
+
27
+ expect(entriesOf(groups)).toEqual([["Shell", "Nav"], ["Board", "Chart"], ["Solo"]]);
28
+ });
29
+
30
+ test("leaves alone an entry no route loads and an entry whose export names are not known", () => {
31
+ const groups = ClientEntryGroups.plan(
32
+ [part("Unused", "Unused"), part("Other", "Other"), part("Star"), part("Bare")],
33
+ (held) => (held.entry === entry("Unused") || held.entry === entry("Other") ? [] : ["/a"]),
34
+ );
35
+
36
+ expect(entriesOf(groups)).toEqual([["Unused"], ["Other"], ["Star"], ["Bare"]]);
37
+ });
38
+
39
+ test("a part of an entry is loaded by the routes asking it for one of its names, and by a route asking for none in particular", () => {
40
+ const loadedBy = ClientEntryGroups.loadedBy(
41
+ new Map([
42
+ ["/a", [entry("Pair"), entry("Pair")]],
43
+ ["/b", [entry("Pair")]],
44
+ ["/c", [entry("Pair")]],
45
+ ["/d", [entry("Else")]],
46
+ ]),
47
+ new Map<string, AskedExports>([
48
+ ["/a", new Map([[entry("Pair"), ["A"]]])],
49
+ ["/b", new Map([[entry("Pair"), ["B"]]])],
50
+ ["/c", new Map([[entry("Pair"), null]])],
51
+ ]),
52
+ );
53
+
54
+ expect(loadedBy(part("Pair", "A"))).toEqual(["/a", "/c"]);
55
+ expect(loadedBy(part("Pair", "B"))).toEqual(["/b", "/c"]);
56
+ expect(loadedBy(part("Else", "Else"))).toEqual(["/d"]);
57
+ expect(loadedBy(part("Never", "Never"))).toEqual([]);
58
+ });
59
+
60
+ test("a group exports every name under a name of its own, so two entries' defaults do not collide", () => {
61
+ const exports = ClientEntryGroups.exportsOf([part("One", "default", "One"), part("Two", "default")]);
62
+
63
+ expect([...exports]).toEqual([
64
+ ["g0", { entry: entry("One"), name: "default" }],
65
+ ["g1", { entry: entry("One"), name: "One" }],
66
+ ["g2", { entry: entry("Two"), name: "default" }],
67
+ ]);
68
+ expect(ClientEntryGroups.source("demo", exports, "page")).toBe(
69
+ [
70
+ ...StoreBootstrap.importLines("demo", "page"),
71
+ `export { default as g0, One as g1 } from ${JSON.stringify(entry("One"))};`,
72
+ `export { default as g2 } from ${JSON.stringify(entry("Two"))};`,
73
+ "",
74
+ ].join("\n"),
75
+ );
76
+ });
77
+ });
@@ -0,0 +1,61 @@
1
+ import path from "node:path";
2
+ import { type ClientRuntimeScope, StoreBootstrap } from "../artifact/storeBootstrap";
3
+ import type { AskedExports } from "./clientBuildTypes";
4
+
5
+ export interface ClientEntryPart {
6
+ entry: string;
7
+ names: readonly string[];
8
+ }
9
+
10
+ export interface GroupedExport {
11
+ entry: string;
12
+ name: string;
13
+ }
14
+
15
+ //? Bun gives a module a chunk per set of entries reaching it, so entries the same routes load are built as one.
16
+ export class ClientEntryGroups {
17
+ static plan<Part extends ClientEntryPart>(
18
+ parts: readonly Part[],
19
+ routesOf: (part: Part) => readonly string[],
20
+ ): Part[][] {
21
+ const groups = new Map<string, Part[]>();
22
+ const alone: Part[][] = [];
23
+ for (const part of parts) {
24
+ const routes = routesOf(part);
25
+ if (routes.length === 0 || part.names.length === 0) alone.push([part]);
26
+ else groups.getOrInsert(routes.toSorted((a, b) => a.localeCompare(b)).join("\n"), []).push(part);
27
+ }
28
+ return [...groups.values(), ...alone];
29
+ }
30
+
31
+ static loadedBy(
32
+ entriesByRoute: ReadonlyMap<string, readonly string[]>,
33
+ askedByRoute?: ReadonlyMap<string, AskedExports>,
34
+ ): (part: ClientEntryPart) => string[] {
35
+ const loads = new Map<string, { route: string; asked: readonly string[] | null }[]>();
36
+ for (const [route, entries] of entriesByRoute)
37
+ for (const entry of new Set(entries.map((held) => path.resolve(held))))
38
+ loads.getOrInsert(entry, []).push({ route, asked: askedByRoute?.get(route)?.get(entry) ?? null });
39
+ return ({ entry, names }) =>
40
+ (loads.get(path.resolve(entry)) ?? [])
41
+ .filter(({ asked }) => !asked || names.some((name) => asked.includes(name)))
42
+ .map(({ route }) => route);
43
+ }
44
+
45
+ static exportsOf(group: readonly ClientEntryPart[]): Map<string, GroupedExport> {
46
+ const exports = new Map<string, GroupedExport>();
47
+ for (const { entry, names } of group)
48
+ for (const name of names) exports.set(`g${exports.size}`, { entry: path.resolve(entry), name });
49
+ return exports;
50
+ }
51
+
52
+ static source(appName: string, exports: ReadonlyMap<string, GroupedExport>, scope: ClientRuntimeScope): string {
53
+ const byEntry = new Map<string, string[]>();
54
+ for (const [alias, { entry, name }] of exports) byEntry.getOrInsert(entry, []).push(`${name} as ${alias}`);
55
+ const lines = [
56
+ ...StoreBootstrap.importLines(appName, scope),
57
+ ...[...byEntry].map(([entry, names]) => `export { ${names.join(", ")} } from ${JSON.stringify(entry)};`),
58
+ ];
59
+ return `${lines.join("\n")}\n`;
60
+ }
61
+ }
@@ -17,6 +17,7 @@ import { SignalDescriptors } from "../transforms/signalDescriptors";
17
17
  import type { AskedExports, ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
18
18
  import { ClientEntriesBundler } from "./clientEntriesBundler";
19
19
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
20
+ import { ClientEntryGroups, type ClientEntryPart, type GroupedExport } from "./clientEntryGroups";
20
21
  import { CsrDevPaths } from "./csrDevPaths";
21
22
  import { RouteRuntimeCheck } from "./routeRuntimeCheck";
22
23
  import { type RoutePaysVerdict, RouteRuntimePays } from "./routeRuntimePays";
@@ -73,6 +74,13 @@ interface BootstrapEntries {
73
74
  originalByBuildEntry: Map<string, string>;
74
75
  //? Only for an entry built as several: the export names each of its build entries holds.
75
76
  namesByBuildEntry?: Map<string, readonly string[]>;
77
+ //? Only for a build entry holding several entries: each name it exports, with the entry and the name behind it.
78
+ membersByBuildEntry?: Map<string, ReadonlyMap<string, GroupedExport>>;
79
+ }
80
+
81
+ interface WrappedPart extends ClientEntryPart {
82
+ file: string;
83
+ split: boolean;
76
84
  }
77
85
 
78
86
  interface NarrowedBuild {
@@ -165,6 +173,7 @@ export class RouteClientBuilder {
165
173
  bootstrapEntries.originalByBuildEntry,
166
174
  referenceBundle.clientReferenceIdByAbsPath,
167
175
  this.#app.workspace.workspaceRoot,
176
+ bootstrapEntries.membersByBuildEntry,
168
177
  );
169
178
  if (!manifestEntry) continue;
170
179
  if (!acceptedEntries.has(manifestEntry.originalEntry)) continue;
@@ -179,17 +188,23 @@ export class RouteClientBuilder {
179
188
  if (!ssrOutput) continue;
180
189
 
181
190
  ssrModuleMap[row.id] ??= {};
182
- ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name: row.name, async: true };
191
+ const { name } = manifestEntry;
192
+ ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name, async: true };
183
193
  }
184
194
  for (const entry of bootstrapEntries.buildEntries) {
185
195
  const buildEntry = path.resolve(entry);
186
- const originalEntry = path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
187
- if (!acceptedEntries.has(originalEntry)) continue;
188
- const deps = new Set<string>(clientDepsByEntry[originalEntry] ?? [originalEntry]);
189
- for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
190
- const sortedDeps = [...deps].sort();
191
- clientDepsByEntry[originalEntry] = sortedDeps;
192
- if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
196
+ const grouped = bootstrapEntries.membersByBuildEntry?.get(buildEntry);
197
+ const originalEntries = grouped
198
+ ? new Set([...grouped.values()].map((member) => member.entry))
199
+ : [path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry)];
200
+ for (const originalEntry of originalEntries) {
201
+ if (!acceptedEntries.has(originalEntry)) continue;
202
+ const deps = new Set<string>(clientDepsByEntry[originalEntry] ?? [originalEntry]);
203
+ for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
204
+ const sortedDeps = [...deps].sort();
205
+ clientDepsByEntry[originalEntry] = sortedDeps;
206
+ if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
207
+ }
193
208
  }
194
209
 
195
210
  return {
@@ -375,24 +390,31 @@ export class RouteClientBuilder {
375
390
  }
376
391
 
377
392
  //? An entry built as several answers with the ones holding a name asked, and with all of them asked for none.
378
- static #buildEntriesOf({ originalByBuildEntry, namesByBuildEntry }: BootstrapEntries) {
379
- const built = new Map<string, string[]>();
380
- for (const [buildEntry, original] of originalByBuildEntry) built.getOrInsert(original, []).push(buildEntry);
393
+ static #buildEntriesOf({ originalByBuildEntry, namesByBuildEntry, membersByBuildEntry }: BootstrapEntries) {
394
+ const built = new Map<string, { buildEntry: string; names?: readonly string[] }[]>();
395
+ for (const [buildEntry, original] of originalByBuildEntry)
396
+ built.getOrInsert(original, []).push({ buildEntry, names: namesByBuildEntry?.get(buildEntry) });
397
+ for (const [buildEntry, exports] of membersByBuildEntry ?? [])
398
+ for (const [original, held] of Map.groupBy(exports.values(), (member) => member.entry))
399
+ built.getOrInsert(original, []).push({ buildEntry, names: held.map((member) => member.name) });
381
400
  return (entry: string, asked?: readonly string[] | null): string[] => {
382
- const buildEntries = built.get(path.resolve(entry)) ?? [path.resolve(entry)];
383
- if (!asked) return buildEntries;
384
- return buildEntries.filter((buildEntry) => {
385
- const names = namesByBuildEntry?.get(buildEntry);
386
- return !names || names.some((name) => asked.includes(name));
387
- });
401
+ const held = built.get(path.resolve(entry));
402
+ if (!held) return [path.resolve(entry)];
403
+ return held
404
+ .filter(({ names }) => !asked || !names || names.some((name) => asked.includes(name)))
405
+ .map(({ buildEntry }) => buildEntry);
388
406
  };
389
407
  }
390
408
 
391
409
  #check({ entries, kept, bundle, runtime: routeRuntime }: NarrowedBuild): boolean {
392
410
  const { workspaceRoot } = this.#app.workspace;
393
411
  const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
412
+ const grouped = [...(entries.membersByBuildEntry ?? [])].flatMap(([buildEntry, exports]) => {
413
+ const [first] = exports.values();
414
+ return first ? [[buildEntry, first.entry] as const] : [];
415
+ });
394
416
  const check = new RouteRuntimeCheck(workspaceRoot, bundle.graph, {
395
- entries: new Map([...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry))),
417
+ entries: new Map([...[...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry)), ...grouped]),
396
418
  wholeReaders: routeRuntime.wholeReaders,
397
419
  wholeConstantReaders: routeRuntime.wholeConstantReaders,
398
420
  routes: new Map(
@@ -491,42 +513,66 @@ export class RouteClientBuilder {
491
513
 
492
514
  const originalByBuildEntry = new Map<string, string>();
493
515
  const namesByBuildEntry = new Map<string, readonly string[]>();
516
+ const membersByBuildEntry = new Map<string, ReadonlyMap<string, GroupedExport>>();
494
517
  const { workspaceRoot } = this.#app.workspace;
495
- const buildEntries = await Promise.all(
496
- entries.map(async (entry) => {
518
+ const byExport = scope === "page" && this.#command === "build";
519
+ const read = await Promise.all(
520
+ entries.map(async (entry): Promise<{ whole?: string; parts: WrappedPart[] }> => {
497
521
  const absEntry = path.resolve(entry);
498
522
  const whole = narrowed?.kept.has(absEntry) ? wholeByOriginal.get(absEntry) : undefined;
499
523
  if (whole) {
500
524
  originalByBuildEntry.set(whole, absEntry);
501
- return [whole];
525
+ return { whole, parts: [] };
502
526
  }
503
527
  const hash = Bun.hash(`${this.#app.name}\n${absEntry}`).toString(36);
504
528
  const base = path.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
505
529
  const source = await Bun.file(absEntry).text();
506
530
  const exportNames = scanUseClientExports(source, absEntry, workspaceRoot);
507
- const byExport = scope === "page" && this.#command === "build" && PartModules.splits(workspaceRoot, absEntry);
508
- const groups = byExport ? RouteClientBuilder.#exportGroups(source, absEntry, exportNames) : [exportNames];
509
- return await Promise.all(
510
- groups.map(async (names, index) => {
511
- const wrapperEntry = path.join(outdir, `${base}-${hash}${groups.length > 1 ? `-${index}` : ""}.tsx`);
512
- await Bun.write(
513
- wrapperEntry,
514
- RouteClientBuilder.createStoreBootstrapEntrySource({
515
- appName: this.#app.name,
516
- originalEntry: absEntry,
517
- exportNames: names,
518
- scope,
519
- }),
520
- );
521
- originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
522
- if (groups.length > 1) namesByBuildEntry.set(path.resolve(wrapperEntry), names);
523
- return wrapperEntry;
524
- }),
525
- );
531
+ const groups =
532
+ byExport && PartModules.splits(workspaceRoot, absEntry)
533
+ ? RouteClientBuilder.#exportGroups(source, absEntry, exportNames)
534
+ : [exportNames];
535
+ const parts = groups.map((names, index) => ({
536
+ entry: absEntry,
537
+ names,
538
+ file: path.join(outdir, `${base}-${hash}${groups.length > 1 ? `-${index}` : ""}.tsx`),
539
+ split: groups.length > 1,
540
+ }));
541
+ return { parts };
526
542
  }),
527
543
  );
528
-
529
- return { buildEntries: buildEntries.flat(), originalByBuildEntry, namesByBuildEntry };
544
+ const parts = read.flatMap((entry) => entry.parts);
545
+ const routes = byExport ? (this.#sizedEntriesByRoute ?? this.#entriesByRoute) : undefined;
546
+ const planned = routes
547
+ ? ClientEntryGroups.plan(parts, ClientEntryGroups.loadedBy(routes, this.#askedByRoute))
548
+ : parts.map((part) => [part]);
549
+ const wrappers = await Promise.all(
550
+ planned.map(async (group) => {
551
+ const [only] = group;
552
+ if (group.length === 1 && only) {
553
+ await Bun.write(
554
+ only.file,
555
+ RouteClientBuilder.createStoreBootstrapEntrySource({
556
+ appName: this.#app.name,
557
+ originalEntry: only.entry,
558
+ exportNames: [...only.names],
559
+ scope,
560
+ }),
561
+ );
562
+ originalByBuildEntry.set(path.resolve(only.file), only.entry);
563
+ if (only.split) namesByBuildEntry.set(path.resolve(only.file), only.names);
564
+ return only.file;
565
+ }
566
+ const exports = ClientEntryGroups.exportsOf(group);
567
+ const held = [...exports.values()].map(({ entry, name }) => `${entry}#${name}`).join("\n");
568
+ const file = path.join(outdir, `group-${Bun.hash(`${this.#app.name}\n${held}`).toString(36)}.tsx`);
569
+ await Bun.write(file, ClientEntryGroups.source(this.#app.name, exports, scope));
570
+ membersByBuildEntry.set(path.resolve(file), exports);
571
+ return file;
572
+ }),
573
+ );
574
+ const kept = read.flatMap(({ whole }) => (whole ? [whole] : []));
575
+ return { buildEntries: [...kept, ...wrappers], originalByBuildEntry, namesByBuildEntry, membersByBuildEntry };
530
576
  }
531
577
 
532
578
  //? Names one part of the file holds share a build entry. The parts are read from the file as written, and a bundle
@@ -644,15 +690,20 @@ export class RouteClientBuilder {
644
690
  originalByBuildEntry: Map<string, string>,
645
691
  clientReferenceIdByBuildEntry: Map<string, string> = new Map(),
646
692
  workspaceRoot = process.cwd(),
693
+ membersByBuildEntry?: ReadonlyMap<string, ReadonlyMap<string, GroupedExport>>,
647
694
  ): { buildEntry: string; originalEntry: string; name: string; key: string } | null {
648
695
  const hashIdx = manifestKey.lastIndexOf("#");
649
696
  if (hashIdx < 0) return null;
650
697
  const buildReferenceId = manifestKey.slice(0, hashIdx);
651
- const name = manifestKey.slice(hashIdx + 1);
698
+ const builtName = manifestKey.slice(hashIdx + 1);
652
699
  const buildEntry =
653
700
  [...clientReferenceIdByBuildEntry.entries()].find(([, referenceId]) => referenceId === buildReferenceId)?.[0] ??
654
701
  buildReferenceId;
655
- const originalEntry = originalByBuildEntry.get(buildEntry) ?? buildEntry;
702
+ const grouped = membersByBuildEntry?.get(buildEntry);
703
+ const member = grouped?.get(builtName);
704
+ if (grouped && !member) return null;
705
+ const name = member?.name ?? builtName;
706
+ const originalEntry = member?.entry ?? originalByBuildEntry.get(buildEntry) ?? buildEntry;
656
707
  const originalReferenceId = toClientReferencePath(originalEntry, workspaceRoot);
657
708
  return { buildEntry, originalEntry, name, key: `${originalReferenceId}#${name}` };
658
709
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.40",
3
+ "version": "3.3.0-rc.42",
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.40",
53
+ "@akanjs/language": "3.3.0-rc.42",
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.40",
62
+ "akanjs": "3.3.0-rc.42",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",