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

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 (48) hide show
  1. package/CHANGELOG.md +37 -2
  2. package/akanApp/akanApp.host.test.ts +21 -4
  3. package/akanApp/akanApp.host.ts +46 -9
  4. package/akanApp/akanApp.host.wiring.test.ts +206 -2
  5. package/akanApp/devBackend.ts +3 -1
  6. package/akanApp/devBuilder.ts +5 -1
  7. package/akanApp/devStartTimeline.test.ts +115 -0
  8. package/akanApp/devStartTimeline.ts +69 -0
  9. package/akanConfig/akanConfig.test.ts +2 -1
  10. package/akanConfig/akanConfig.ts +1 -1
  11. package/app/applicationBuildRunner.test.ts +49 -1
  12. package/app/applicationBuildRunner.ts +3 -1
  13. package/codeAgent/skills/akan-page/SKILL.md +18 -13
  14. package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
  15. package/codeAgent/skills/akan-service/SKILL.md +2 -2
  16. package/docs/apiReference.test.ts +5 -0
  17. package/docs/apiReference.ts +7 -3
  18. package/docs/declarationReader.ts +28 -1
  19. package/executors/appExecutor.ts +35 -11
  20. package/executors/executors.test.ts +30 -3
  21. package/frontendBuild/buildCacheStamp.test.ts +42 -0
  22. package/frontendBuild/buildCacheStamp.ts +23 -0
  23. package/frontendBuild/cssCandidateCache.test.ts +70 -1
  24. package/frontendBuild/cssCandidateCache.ts +17 -10
  25. package/frontendBuild/cssCompiler.test.ts +112 -0
  26. package/frontendBuild/cssCompiler.ts +41 -21
  27. package/frontendBuild/fontOptimizer.test.ts +144 -3
  28. package/frontendBuild/fontOptimizer.ts +103 -18
  29. package/frontendBuild/plainStylesheet.test.ts +155 -0
  30. package/frontendBuild/plainStylesheet.ts +197 -0
  31. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
  32. package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
  33. package/guideline/agentAssets.test.ts +10 -0
  34. package/guideline/agentAssets.ts +52 -11
  35. package/incrementalBuilder/buildBatch.proc.ts +2 -1
  36. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  37. package/incrementalBuilder/builderBoot.ts +9 -2
  38. package/incrementalBuilder/builderChannel.ts +8 -2
  39. package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
  40. package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
  41. package/incrementalBuilder/incrementalBuilder.proc.test.ts +41 -0
  42. package/incrementalBuilder/incrementalBuilder.proc.ts +1 -0
  43. package/mobile/nativeConfig.test.ts +21 -0
  44. package/mobile/nativeConfig.ts +20 -10
  45. package/mobile/nativePublicEnv.ts +2 -1
  46. package/package.json +3 -3
  47. package/util/fileSys.test.ts +13 -0
  48. package/util/fileSys.ts +2 -2
@@ -0,0 +1,69 @@
1
+ import type { Logger } from "akanjs/common";
2
+
3
+ type StartMark = "started" | "baseBuilt" | "builderReady" | "backendSpawned" | "backendReady";
4
+
5
+ const BASE_BUILD_PARTS = ["runtime", "routes", "styles", "dictionary", "pages"];
6
+
7
+ export class DevStartTimeline {
8
+ readonly #logger: Logger;
9
+ readonly #now: () => number;
10
+ #marks: Partial<Record<StartMark, number>> = {};
11
+ #basePhaseMs: Partial<Record<string, number>> = {};
12
+ #reported = true;
13
+
14
+ constructor(logger: Logger, now: () => number = () => performance.now()) {
15
+ this.#logger = logger;
16
+ this.#now = now;
17
+ }
18
+
19
+ begin(): void {
20
+ this.#marks = { started: this.#now() };
21
+ this.#basePhaseMs = {};
22
+ this.#reported = false;
23
+ }
24
+
25
+ baseBuilt(phaseMs: Record<string, number>): void {
26
+ if (this.#reported || this.#marks.baseBuilt !== undefined) return;
27
+ this.#basePhaseMs = phaseMs;
28
+ this.#marks.baseBuilt = this.#now();
29
+ }
30
+
31
+ mark(mark: Exclude<StartMark, "started" | "baseBuilt">): void {
32
+ if (this.#reported) return;
33
+ if (mark === "backendSpawned") this.#marks.backendSpawned = this.#now();
34
+ else this.#marks[mark] ??= this.#now();
35
+ this.#report();
36
+ }
37
+
38
+ #report(): void {
39
+ const { started, baseBuilt, builderReady, backendSpawned, backendReady } = this.#marks;
40
+ if (started === undefined || builderReady === undefined || backendReady === undefined) return;
41
+ this.#reported = true;
42
+ const ms = (value: number) => Math.round(value).toString();
43
+ //? The clock counts from the start of the process, so the first mark is what the CLI spent before the host.
44
+ const parts = [`prepare ${ms(started)}`, `builder ${ms(builderReady - started)}${this.#builderParts()}`];
45
+ if (backendSpawned !== undefined) {
46
+ //? Spawned beside the build, most of its time is the wait for the artifact: what it took after that is its own.
47
+ const afterArtifact =
48
+ baseBuilt !== undefined && backendSpawned < baseBuilt && baseBuilt <= backendReady
49
+ ? ` (${ms(backendReady - baseBuilt)} after the artifact)`
50
+ : "";
51
+ parts.push(`backend ${ms(backendReady - backendSpawned)}${afterArtifact}`);
52
+ }
53
+ if (baseBuilt !== undefined) parts.push(`first artifact at ${ms(baseBuilt)}`);
54
+ this.#logger.info(`ready in ${ms(Math.max(builderReady, backendReady))}ms (${parts.join(" · ")})`);
55
+ }
56
+
57
+ #builderParts(): string {
58
+ const { started, baseBuilt, builderReady } = this.#marks;
59
+ if (started === undefined || baseBuilt === undefined || builderReady === undefined) return "";
60
+ const total = this.#basePhaseMs.total ?? 0;
61
+ const base = BASE_BUILD_PARTS.flatMap((part) => {
62
+ const partMs = this.#basePhaseMs[part];
63
+ return partMs === undefined ? [] : [`${part} ${Math.round(partMs)}`];
64
+ });
65
+ const spawn = Math.max(0, Math.round(baseBuilt - started - total));
66
+ const watch = Math.max(0, Math.round(builderReady - baseBuilt));
67
+ return `: spawn ${spawn} + base build ${Math.round(total)} [${base.join(" · ")}] + watch ${watch}`;
68
+ }
69
+ }
@@ -662,7 +662,7 @@ describe("AkanAppConfig", () => {
662
662
  targets: {
663
663
  default: {
664
664
  plugins: ["share"],
665
- ios: { files: { "extra.caf": "assets/extra.caf" } },
665
+ ios: { files: { "extra.caf": "assets/extra.caf" }, hideFormAccessoryBar: true },
666
666
  android: { manifest: ["<uses-feature/>"] },
667
667
  },
668
668
  },
@@ -677,6 +677,7 @@ describe("AkanAppConfig", () => {
677
677
  ios: {
678
678
  infoPlist: { ITSAppUsesNonExemptEncryption: false },
679
679
  files: { "sound.caf": "assets/sound.caf", "extra.caf": "assets/extra.caf" },
680
+ hideFormAccessoryBar: true,
680
681
  },
681
682
  android: {
682
683
  manifest: ["<uses-feature/>"],
@@ -475,7 +475,7 @@ export class AkanAppConfig implements AppConfigResult {
475
475
  "android",
476
476
  "desktop",
477
477
  ],
478
- ios: ["indexPath", "teamId", "infoPlist", "entitlements", "privacy", "files"],
478
+ ios: ["indexPath", "teamId", "infoPlist", "entitlements", "privacy", "files", "hideFormAccessoryBar"],
479
479
  android: [
480
480
  "indexPath",
481
481
  "sha256CertFingerprints",
@@ -439,7 +439,9 @@ console.info(new SampleService().name);
439
439
 
440
440
  expect(proc.exitCode).toBe(1);
441
441
  expect(proc.stdout.toString()).toBe("");
442
- expect(proc.stderr.toString()).toContain("Run `akan build portal` first.");
442
+ expect(proc.stderr.toString()).toContain(
443
+ `${path.join("dist", "verify", "portal")} holds the partial output of akan verify, not a build. Run \`akan build portal\` and start dist/apps/portal.`,
444
+ );
443
445
  expect(await Bun.file(path.join(app.dist.cwdPath, "akan.build.json")).json()).toMatchObject({
444
446
  profile: "verify",
445
447
  });
@@ -452,4 +454,50 @@ console.info(new SampleService().name);
452
454
  await rm(root, { recursive: true, force: true });
453
455
  }
454
456
  });
457
+
458
+ test("a verify build writes to dist/verify/<app> and leaves the full build in dist/apps/<app> as it was", async () => {
459
+ const { root, workspace } = await createTempApp("portal");
460
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
461
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
462
+ const appDir = path.join(root, "apps", "portal");
463
+ await Promise.all(["main.ts", "server.ts"].map((file) => writeFile(path.join(appDir, file), "")));
464
+ await mkdir(path.join(appDir, "public"));
465
+ await writeFile(path.join(appDir, "public", "hero.png"), "image");
466
+ const built = path.join(root, "dist", "apps", "portal");
467
+ const fullBuild = {
468
+ "main.js": 'console.log("booted");\n',
469
+ "akan.build.json": '{ "buildId": "abc123" }\n',
470
+ "akan.env.json": '{ "AKAN_PUBLIC_ENV": "local" }\n',
471
+ "public/hero.png": "image",
472
+ };
473
+ for (const [file, content] of Object.entries(fullBuild)) {
474
+ await mkdir(path.dirname(path.join(built, file)), { recursive: true });
475
+ await writeFile(path.join(built, file), content);
476
+ }
477
+ const app = AppExecutor.from(workspace, "portal");
478
+ const bundle = spyOn(Bun, "build").mockImplementation(
479
+ async () => ({ success: true, outputs: [], logs: [] }) as unknown as Bun.BuildOutput,
480
+ );
481
+ try {
482
+ const { outputDir } = await new ApplicationBuildRunner(app, { verify: true }).build();
483
+
484
+ for (const [file, content] of Object.entries(fullBuild))
485
+ expect(await readFile(path.join(built, file), "utf8").catch(() => null)).toBe(content);
486
+ const verified = path.join(root, "dist", "verify", "portal");
487
+ expect(outputDir).toBe(verified);
488
+ expect(await Bun.file(path.join(verified, "akan.build.json")).json()).toMatchObject({ profile: "verify" });
489
+ expect(await Bun.file(path.join(verified, "console.js")).exists()).toBe(true);
490
+ expect(await Bun.file(path.join(verified, "public", "hero.png")).exists()).toBe(false);
491
+ const outdirs = bundle.mock.calls.map(([config]) => config.outdir);
492
+ expect(outdirs.length).toBeGreaterThan(0);
493
+ expect(outdirs.every((outdir) => outdir === verified)).toBe(true);
494
+ } finally {
495
+ bundle.mockRestore();
496
+ for (const key of keys) {
497
+ if (shellEnv[key] === undefined) delete process.env[key];
498
+ else process.env[key] = shellEnv[key];
499
+ }
500
+ await rm(root, { recursive: true, force: true });
501
+ }
502
+ });
455
503
  });
@@ -164,6 +164,7 @@ export class ApplicationBuildRunner {
164
164
  async build({ spinner = false }: BuildOptions = {}): Promise<BuildResult> {
165
165
  // serial build is needed because of Bun.build is unstable for parallel build
166
166
  this.#spinner = spinner;
167
+ if (this.#verify) this.#app.useVerifyDist();
167
168
  const { web, assets, baseDevEnv } = await this.#app.getConfig();
168
169
  const environment = this.#environment ?? baseDevEnv.env;
169
170
  WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, "akan build");
@@ -370,7 +371,8 @@ export class ApplicationBuildRunner {
370
371
  //? `bun main.js` in dist/apps/<app> is a documented way to run a build, and a verify output has no CSR bundle or
371
372
  //? production env file, so its main.js refuses to boot before any app module runs.
372
373
  #verifyBanner() {
373
- const message = `dist/apps/${this.#app.name} holds the partial output of akan verify, not a build. Run \`akan build ${this.#app.name}\` first.`;
374
+ const { name, dist, workspace } = this.#app;
375
+ const message = `${path.relative(workspace.workspaceRoot, dist.cwdPath)} holds the partial output of akan verify, not a build. Run \`akan build ${name}\` and start dist/apps/${name}.`;
374
376
  return `console.error(${JSON.stringify(message)});process.exit(1);`;
375
377
  }
376
378
 
@@ -26,19 +26,19 @@ export default page()
26
26
  ## Steps
27
27
 
28
28
  1. Place the file: `<route>.tsx` or `<dir>/_index.tsx` serves the path, `_layout.tsx` nests a layout (`layout()`;
29
- the root one is `rootLayout()`), `[id]` is a dynamic segment, `(group)` groups without a segment. `page/` holds
30
- route modules only — no helpers, no `.ts` files.
29
+ the root one is `rootLayout()`), `[id]` is a dynamic segment, `(group)` groups without a segment.
31
30
  2. Name every `[x]` segment with `.param("x", Type)` and read a query key only with `.search("k", Type)`. Values
32
- arrive typed; `lang` reaches every stage and is never declared.
33
- 3. Gate with `.guard(() => signedIn())` on the `_layout.tsx` (a real redirect before anything renders), and repeat
34
- a stricter guard on a page that needs more. The endpoint guards are still the real gate. `signedIn` comes from
35
- `@libs/shared/webkit`, and a new workspace has that lib only with `create-workspace --libs true`.
31
+ arrive typed: `ID` / `String` → string, `Int` / `Float` → number, `Boolean`, `Date` → Dayjs, an `enumOf` class →
32
+ its union, `[T]` → array. A path value the type refuses answers not-found, and a search value that fails is
33
+ dropped. `lang` reaches every stage and is never declared.
34
+ 3. Gate with `.guard(() => signedIn())` on the `_layout.tsx`, and repeat a stricter guard on a page that needs more.
35
+ `.guard((_, { path }) => signedIn({ path }))` sends a refused visitor to `/signin?redirect=<path>`.
36
36
  4. In `.render()`: `usePage()`, then fetch, then return. Hand `fetch.init*` / `view*` / `edit*` fields to sections
37
37
  unawaited; await only what the shell reads, in one `Promise.all`.
38
- 5. `.head()` takes JSX (or a function returning it), never a metadata object. A canonical link comes only from the
39
- page's own head.
38
+ 5. `.head()` takes JSX (or a function returning it), never a metadata object.
40
39
  6. Re-skin an `akanjs/ui` component for a subtree with `_overrides.tsx`:
41
- `export default override({ Slot: AppComponent })`, no logic.
40
+ `export default override({ Slot: AppComponent })`, no logic. Nested ones merge slot by slot, the closest winning;
41
+ `componentRule` lists the slots.
42
42
 
43
43
  ## API at a glance
44
44
 
@@ -50,12 +50,16 @@ declared params and search keys plus `lang`.
50
50
  where `Book` is the `common/` interface for the query's `Any` return (`akan-service`).
51
51
  - Async page: `.render(async ({ id }) => { const book = (await fetch.book(id)) as Book | null; if (!book) return router.notFound(); … })`;
52
52
  the same query in `.head()` and `.render()` is one request.
53
+ - Loading: `.loading(() => <Skeleton />)` on a page or layout is what that level shows until its `.render()` and the
54
+ levels below it resolve; the levels above it stream first.
53
55
  - `router.notFound()` from `.guard()`, `.head()` or `.render()` answers 404 with the nearest layout's `.notFound()`
54
56
  above it (an unmatched URL: the deepest layout covering it), else the built-in 404.
55
57
  - A layout's own 404 and error views: `.notFound(({ pathname }) => …)` and `.error(({ error }) => …)` on `layout()`
56
- or `rootLayout()`.
58
+ or `rootLayout()`. A `<title>` and `<meta>` at the top of what they return replace the page's head:
59
+ `.notFound(() => <><title>Not found</title>…</>)`, except below a `.loading()`, where the head is already out.
57
60
  - `<Link href="/books/OL45804W">`: write the path without the locale; Link adds it, or leaves it off for the default
58
- locale under `i18n.localePrefix: "as-needed"`. `activeClassName` marks the current one.
61
+ locale under `i18n.localePrefix: "as-needed"`. It renders an `<a>` and takes its attributes; `activeClassName`
62
+ marks the current one.
59
63
  - From a handler: `router.push(href)` / `router.replace(href)`; in a server stage, `router.redirect(href)`.
60
64
  - A client filter kept in the URL without reloading the page: ``router.replace(`/books?q=${q}`, { shallow: true,
61
65
  scrollToTop: false })`` in a `"use client"` component, read back with `usePageLocation().searchParams`. Shallow
@@ -68,5 +72,6 @@ declared params and search keys plus `lang`.
68
72
  - `useState`, `useEffect`, comments, a named export beside the chain, or the legacy `export default async function`.
69
73
  - Editing a lib page through its link in `page/(libs)/` — edit the lib's own `page/` source.
70
74
 
71
- Full detail: `get_guideline` with `pageRule`, or `ssrRule` for what may render on the server; every stage's
72
- signature, the router's methods, Link's props and every import path: `akanApi`.
75
+ Full detail: `get_guideline` with `pageRule` (guards in depth, heads, MCP apps, CSR root layouts, lib pages), or
76
+ `ssrRule` for what may render on the server. Every stage's signature, the router's methods, Link's props and every
77
+ import path are in the `akanApi-*` references below.
@@ -5,8 +5,9 @@ description: "Configure how an app runs: web surfaces, route prefixes, gateway v
5
5
 
6
6
  # Akan runtime
7
7
 
8
- Runtime and build settings are declared in `akan.config.ts` and narrowed — never widened — by an env at boot.
9
- Domain code reaches none of them.
8
+ Runtime and build settings are declared in `akan.config.ts`. What must hold when you edit it, `main.ts` or an env
9
+ file — the prefixes, the `main.ts` import, the image, log sinks, the desktop server's guard — is the `config` rule in
10
+ the agent guide's Path Rules table.
10
11
 
11
12
  ## Where each setting lives
12
13
 
@@ -16,28 +17,32 @@ Domain code reaches none of them.
16
17
  | Move the API or websocket mount | `new AkanApp({ prefix, websocketPrefix })` in `main.ts`, mirrored in `api: { … }`; read with `getApiPrefix()` / `getWsPrefix()` |
17
18
  | The production image | `docker: string \| { image, preRuns, postRuns, command }` |
18
19
  | iOS, Android, desktop | the `native` section; `desktop: { server: true }` carries the server |
19
- | SQLite, several databases, a cluster | `database: { modes: [...] }`, picked by `AKAN_DATABASE_MODE` |
20
+ | SQLite, several databases, a cluster | `database: { modes: [...] }` (`single`, `multiple`, `cluster`), picked by `AKAN_DATABASE_MODE` |
20
21
  | URLs without `/<locale>/`: one language, or paths fixed from outside (OAuth callback, QR code, mail link) | `i18n: { localePrefix: "as-needed" }` — the default locale's pages and `<Link>` hrefs drop the prefix, other locales keep it |
21
22
 
22
- - `main.ts` imports `AkanApp` from `akanjs/server/akanApp`, never the barrel.
23
- - Never write `/api` or `/ws` literally, and never pass a prefix as a prop.
24
- - The generated image installs only `ca-certificates` and `tzdata`; add the rest in `preRuns`.
25
- - An app running in two database modes avoids `q.raw`.
26
-
27
23
  ## Running and logs
28
24
 
29
25
  - `akan start <app>` (`a,b` or `all` for several) runs the dev server; `akan build <app>` checks the production
30
- build. A supervised session writes `local/apps/<app>/runtime/dev.log` — hand over that path, not a paste of the
31
- live view. Tail with `akan logs <app>`.
26
+ build. A supervised session writes `local/apps/<app>/runtime/dev.log` (previous: `dev.prev.log`) — hand over that
27
+ path, not a paste of the live view. Tail with `akan logs <app>`.
32
28
  - Run a build without Docker with `cd dist/apps/<app> && bun main.js`: it boots with the env the Dockerfile sets,
33
29
  read from `akan.env.json` beside it, and a variable you set yourself (`PORT=3000`) wins.
34
- - Give every log sink a floor (`Logger.addSink(sink, { minLevel })`) and never log once per delivered record.
35
30
 
36
31
  ## Native and desktop
37
32
 
38
- - `akan start-desktop <app>`, `akan start-ios <app>`, `akan start-android <app>` load pages from a running
39
- `akan start`; a desktop app carrying its server starts it itself.
40
- - A desktop app's carried server listens on a loopback port any local program can call — guard it like a network
41
- server. Read runtime files from `AKAN_APP_DIR`, and keep a user's secret with `NativeSecret`, never in a file.
33
+ A `start-*` command loads its pages from a running `akan start`; a desktop app carrying its server starts it itself.
34
+
35
+ ```bash
36
+ akan start-desktop <app> # Run the desktop app on this computer
37
+ akan start-ios <app> # Run it in a simulator or on an iPhone (start-android alike)
38
+ akan build-desktop <app> # Build it for this computer into dist/native/<app>/<target>/build
39
+ akan build-desktop <app> --installer true # Windows: add a per-user setup program
40
+ akan update-keygen <app> # Make the update signing key once; print its public key
41
+ akan publish-update <app> # Build a key-signed release for updates.url; --sign true also code-signs it
42
+ ```
43
+
44
+ A device capability the framework lacks is a plugin the app owns in `native/<id>/`: `native-plugin.json`,
45
+ `src/index.ts` (the page API, used from a `webkit/` hook), `src/desktop.ts`, Kotlin and Swift.
42
46
 
43
- Full detail: `get_guideline` with `runtimeRule`.
47
+ Full detail: `get_guideline` with `runtimeRule` (keys, `--plain`, boot waves, `--kill`, watch scope, booting a
48
+ server in a test, native targets and updates).
@@ -106,5 +106,5 @@ The page calls it as `await fetch.book(id)` (`fetch` from `@apps/<app>/client`)
106
106
  `common/`, or return a scalar (`akan create-scalar`) for a typed wire shape. A query that answers `null` without
107
107
  `nullable: true` fails the render, naming the endpoint.
108
108
 
109
- Full detail: `get_guideline` with `modelService`; every import path and the exact signatures of serve, adapt,
110
- endpoint and serviceDictionary: `akanApi`.
109
+ Full detail: `get_guideline` with `modelService`. The exact signatures of serve, adapt, endpoint and
110
+ serviceDictionary, and every import path, are in the `akanApi-*` references below.
@@ -28,6 +28,11 @@ describe("ApiReference", () => {
28
28
  expect(rendered).toMatch(/^\/\*\* .+ \*\/\nserverMode\?: "batch" \| "federation";$/m);
29
29
  });
30
30
 
31
+ test("says what Link takes beyond its own props, and names its static parts", () => {
32
+ expect(rendered).toContain('Every prop of `Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href">`, and:');
33
+ expect(rendered).toMatch(/^Link\.Back\(.+\): Element$/m);
34
+ });
35
+
31
36
  test("lists the keys of akan.config.ts, so the web and i18n shapes have a field to belong to", () => {
32
37
  const appConfig = rendered.slice(rendered.indexOf("### `AppConfigInput`"));
33
38
  expect(appConfig).toMatch(/^web\?: AkanWebOption;$/m);
@@ -153,7 +153,7 @@ export class ApiReference {
153
153
  "Generated from the akanjs sources of this release: the import paths and signatures a first app needs, so none of",
154
154
  "them has to be looked up in `node_modules`. A stage's return type is the same chain, left out below.",
155
155
  "",
156
- "## Imports",
156
+ "## Imports (`akanjs/*`, `@apps/<app>/client`, `../cnst`, `../dict`, `../srv`, layer barrels)",
157
157
  "",
158
158
  "```ts",
159
159
  ...importLines,
@@ -183,8 +183,12 @@ export class ApiReference {
183
183
  return [heading, "", "```ts", reader.declarationText(symbol), "```"].join("\n");
184
184
  if (item.show.kind === "signature")
185
185
  return [heading, "", "```ts", ...reader.signatures(symbol, item.name), "```"].join("\n");
186
- if (item.show.kind === "props")
187
- return [heading, "", "```ts", ...reader.props(reader.declaredType(symbol), item.show.omit), "```"].join("\n");
186
+ if (item.show.kind === "props") {
187
+ const bases = reader.foreignBases(symbol).map((base) => `\`${base}\``);
188
+ const inherits = bases.length ? ["", `Every prop of ${bases.join(" and ")}, and:`] : [];
189
+ const props = reader.props(reader.declaredType(symbol), item.show.omit);
190
+ return [heading, ...inherits, "", "```ts", ...props, "```"].join("\n");
191
+ }
188
192
  const members = reader.members(reader.instanceType(symbol), item.show);
189
193
  return [heading, "", "```ts", ...members.map(([, line]) => line), "```"].join("\n");
190
194
  }
@@ -91,7 +91,34 @@ export class DeclarationReader {
91
91
  const type = this.#checker.getTypeOfSymbol(symbol);
92
92
  const signatures = type.getCallSignatures();
93
93
  if (signatures.length === 0) throw new Error(`${name} is not callable`);
94
- return signatures.map((signature) => `${name}${this.#checker.signatureToString(signature, undefined, typeFlags)}`);
94
+ const statics = this.#checker.getPropertiesOfType(type).flatMap((property) => {
95
+ const [declaration] = property.declarations ?? [];
96
+ if (!declaration || DeclarationReader.#isInternalName(property.name)) return [];
97
+ return this.#checker
98
+ .getTypeOfSymbolAtLocation(property, declaration)
99
+ .getCallSignatures()
100
+ .map((each) => `${name}.${property.name}${this.#checker.signatureToString(each, undefined, typeFlags)}`);
101
+ });
102
+ return [
103
+ ...signatures.map((signature) => `${name}${this.#checker.signatureToString(signature, undefined, typeFlags)}`),
104
+ ...statics,
105
+ ];
106
+ }
107
+
108
+ foreignBases(symbol: ts.Symbol): string[] {
109
+ const [declaration] = symbol.declarations ?? [];
110
+ const nodes =
111
+ declaration && ts.isTypeAliasDeclaration(declaration) && ts.isIntersectionTypeNode(declaration.type)
112
+ ? declaration.type.types.filter((each) => !ts.isTypeLiteralNode(each))
113
+ : declaration && ts.isInterfaceDeclaration(declaration)
114
+ ? (declaration.heritageClauses ?? []).flatMap((clause) => [...clause.types])
115
+ : [];
116
+ return nodes
117
+ .filter((node) => {
118
+ const properties = this.#checker.getPropertiesOfType(this.#checker.getTypeFromTypeNode(node));
119
+ return properties.length > 0 && properties.every((each) => !each.declarations?.some((d) => this.#isOwn(d)));
120
+ })
121
+ .map((node) => DeclarationReader.#print(node, node.getSourceFile()));
95
122
  }
96
123
 
97
124
  props(type: ts.Type, omit: string[] = []): string[] {
@@ -1,4 +1,4 @@
1
- import { cp as cpEntry, lstat, mkdir, readdir as readDirEntries, realpath, symlink } from "node:fs/promises";
1
+ import { cp as cpEntry, lstat, mkdir, readdir as readDirEntries, realpath, rm, stat, symlink } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import type { AkanPlugin, AkanSyncContext } from "akanjs";
@@ -44,8 +44,14 @@ export class AppExecutor extends SysExecutor {
44
44
  static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
45
45
  return new AppExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
46
46
  }
47
- //* Not dev output: the downloaded `bin` sources.
48
- static readonly #keptOnStart = [path.join(".akan", "cache", "bin")];
47
+ #verifyBuild: boolean = false;
48
+ //? `akan verify` builds apart: dist/apps/<app> may hold the full build someone is about to start or deploy.
49
+ useVerifyDist() {
50
+ this.dist = new Executor(`dist/verify/${this.name}`, `${this.workspace.workspaceRoot}/dist/verify/${this.name}`);
51
+ this.#verifyBuild = true;
52
+ }
53
+ //* Not dev output: the downloaded `bin` sources, and caches whose entries name the akanjs and Bun that wrote them.
54
+ static readonly #keptOnStart = [path.join(".akan", "cache")];
49
55
  //* Native builds moved to dist/native/<app>; the old folder may hold a signed release nobody uploaded yet.
50
56
  static readonly #legacyNative = path.join(".akan", "native");
51
57
  async #removeDevOutput(dir = ".akan") {
@@ -59,13 +65,28 @@ export class AppExecutor extends SysExecutor {
59
65
  );
60
66
  return;
61
67
  }
62
- if (AppExecutor.#keptOnStart.includes(entry)) return;
68
+ if (AppExecutor.#keptOnStart.includes(entry)) return await this.#removeStaleTemps(entry);
63
69
  if (AppExecutor.#keptOnStart.some((kept) => kept.startsWith(`${entry}${path.sep}`)))
64
70
  return await this.#removeDevOutput(entry);
65
71
  await this.removeDir(entry);
66
72
  }),
67
73
  );
68
74
  }
75
+ //* A start killed between an atomic write and its rename leaves the `.tmp`; a younger one may be another start's.
76
+ static readonly #staleTempMs = 60_000;
77
+ async #removeStaleTemps(dir: string) {
78
+ const root = this.getPath(dir);
79
+ const names = await readDirEntries(root, { recursive: true }).catch(() => [] as string[]);
80
+ await Promise.all(
81
+ names
82
+ .filter((name) => name.endsWith(".tmp"))
83
+ .map(async (name) => {
84
+ const file = path.join(root, name);
85
+ const stats = await stat(file).catch(() => null);
86
+ if (stats?.isFile() && Date.now() - stats.mtimeMs > AppExecutor.#staleTempMs) await rm(file, { force: true });
87
+ }),
88
+ );
89
+ }
69
90
  getEnv() {
70
91
  return WorkspaceExecutor.getBaseDevEnv().env;
71
92
  }
@@ -116,13 +137,16 @@ export class AppExecutor extends SysExecutor {
116
137
  this.#excludeDevOnlyPages = true;
117
138
  this.#pageKeys = null;
118
139
  await this.dist.removeDir(this.dist.cwdPath);
119
- await Promise.all([this.dist.mkdir("private"), this.dist.mkdir("public")]);
120
- //* Lib assets are symlinks, which neither the docker context nor the release tarball follows out of dist.
121
- //* Only the web router reads `public/`, so an api-only build leaves it out.
122
- await Promise.all([
123
- this.cp("private", `${this.dist.cwdPath}/private`, { dereference: true }),
124
- ...(akanConfig.web.ssr ? [this.cp("public", `${this.dist.cwdPath}/public`, { dereference: true })] : []),
125
- ]);
140
+ //? A verify build stops before anything reads these copies; the font optimizer falls back to the app's `public/`.
141
+ if (!this.#verifyBuild) {
142
+ await Promise.all([this.dist.mkdir("private"), this.dist.mkdir("public")]);
143
+ //* Lib assets are symlinks, which neither the docker context nor the release tarball follows out of dist.
144
+ //* Only the web router reads `public/`, so an api-only build leaves it out.
145
+ await Promise.all([
146
+ this.cp("private", `${this.dist.cwdPath}/private`, { dereference: true }),
147
+ ...(akanConfig.web.ssr ? [this.cp("public", `${this.dist.cwdPath}/public`, { dereference: true })] : []),
148
+ ]);
149
+ }
126
150
  } else {
127
151
  await this.#removeDevOutput();
128
152
  //? `akan start` keeps the full dev surface: the incremental builder is also the file watcher.
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, spyOn, test } from "bun:test";
2
2
  import { existsSync } from "node:fs";
3
- import { lstat, mkdir, readFile, readlink, rm, stat, writeFile } from "node:fs/promises";
3
+ import { lstat, mkdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { AkanAppConfig } from "../akanConfig";
6
6
  import { DevGeneratedIndexSync } from "../frontendBuild/devGeneratedIndexSync";
@@ -612,7 +612,7 @@ describe("Workspace and app executor environment contracts", () => {
612
612
  expect(app.getCommandEnv().AKAN_PUBLIC_SERVE_DOMAIN).toBe("example.com");
613
613
  });
614
614
 
615
- test("akan start clears the dev output and keeps the bin downloads and a native folder from before dist/native", async () => {
615
+ test("akan start clears the dev output and keeps the caches and a native folder from before dist/native", async () => {
616
616
  const root = await makeTempRoot();
617
617
  process.env.AKAN_PUBLIC_REPO_NAME = "repo";
618
618
  process.env.AKAN_PUBLIC_SERVE_DOMAIN = "example.com";
@@ -626,11 +626,14 @@ describe("Workspace and app executor environment contracts", () => {
626
626
  "native/desktop/updates/macos-arm64/main.json",
627
627
  "native/desktop/build/macos/App.app",
628
628
  "cache/bin/ffmpeg",
629
+ "cache/cssCandidates.json",
630
+ "cache/fontCache.json",
631
+ "cache/fonts/Assistant-400-normal-abc.woff2",
629
632
  ];
630
633
  const removed = [
631
634
  "artifact/client/app.js",
635
+ "artifact/fontCache.json",
632
636
  "generated/dict/index.ts",
633
- "cache/cssCandidates.json",
634
637
  "desktop/server/main.js",
635
638
  "mobile/desktop/native/macos/App.app",
636
639
  ];
@@ -644,6 +647,30 @@ describe("Workspace and app executor environment contracts", () => {
644
647
  expect(existsSync(path.join(akan, file))).toBe(false);
645
648
  });
646
649
 
650
+ test("akan start removes a cache temp file a killed start left, and keeps one a running start is writing", async () => {
651
+ const root = await makeTempRoot();
652
+ process.env.AKAN_PUBLIC_REPO_NAME = "repo";
653
+ process.env.AKAN_PUBLIC_SERVE_DOMAIN = "example.com";
654
+ process.env.AKAN_PUBLIC_ENV = "local";
655
+ process.env.PORT_OFFSET = "0";
656
+ await writeJson(path.join(root, "package.json"), rootPackageJson());
657
+ await mkdir(path.join(root, "apps/starttemps/page"), { recursive: true });
658
+ await writeFile(path.join(root, "apps/starttemps/akan.config.ts"), "export default {};\n");
659
+ const cache = path.join(root, "apps/starttemps/.akan/cache");
660
+ const stale = ["cssCandidates.json.1.a.tmp", "fonts/x.woff2.1.b.tmp"];
661
+ const fresh = ["fontCache.json.2.c.tmp", "fonts/x.woff2.2.d.tmp"];
662
+ const kept = [...fresh, "cssCandidates.json", "fonts/x.woff2"];
663
+ for (const file of [...stale, ...kept]) await writeText(path.join(cache, file), "x");
664
+ const twoMinutesAgo = new Date(Date.now() - 120_000);
665
+ for (const file of stale) await utimes(path.join(cache, file), twoMinutesAgo, twoMinutesAgo);
666
+
667
+ const app = AppExecutor.from(new WorkspaceExecutor({ workspaceRoot: root, repoName: "repo" }), "starttemps");
668
+ await app.prepareCommand("start");
669
+
670
+ for (const file of stale) expect(existsSync(path.join(cache, file))).toBe(false);
671
+ for (const file of kept) expect(existsSync(path.join(cache, file))).toBe(true);
672
+ });
673
+
647
674
  describe("syncPages", () => {
648
675
  // `AppExecutor.from` memoises by name, so each test needs a name no other test has used.
649
676
  const makeAppWithLibPages = async (
@@ -0,0 +1,42 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { appendFile, utimes, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { tempDirs } from "../test/testHelpers";
5
+ import { buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
6
+
7
+ const tempRoot = tempDirs("akan-devkit-stamp-");
8
+
9
+ const makeProducer = async () => {
10
+ const file = path.join(await tempRoot(), "producer.ts");
11
+ await writeFile(file, "export const regex = /x/;\n");
12
+ await utimes(file, new Date(1_700_000_000_000), new Date(1_700_000_000_000));
13
+ return file;
14
+ };
15
+
16
+ describe("buildCacheStamp", () => {
17
+ test("matches a stamp taken from the same producing file", async () => {
18
+ const file = await makeProducer();
19
+ expect(isBuildCacheStamp(buildCacheStamp([file]), buildCacheStamp([file]))).toBe(true);
20
+ });
21
+
22
+ test("misses when the producing file's mtime moves", async () => {
23
+ const file = await makeProducer();
24
+ const before = buildCacheStamp([file]);
25
+ await utimes(file, new Date(1_700_000_001_000), new Date(1_700_000_001_000));
26
+ expect(isBuildCacheStamp(before, buildCacheStamp([file]))).toBe(false);
27
+ });
28
+
29
+ test("misses when the producing file's size changes under the same mtime", async () => {
30
+ const file = await makeProducer();
31
+ const before = buildCacheStamp([file]);
32
+ await appendFile(file, "export const more = 1;\n");
33
+ await utimes(file, new Date(1_700_000_000_000), new Date(1_700_000_000_000));
34
+ expect(isBuildCacheStamp(before, buildCacheStamp([file]))).toBe(false);
35
+ });
36
+
37
+ test("misses an entry written before the stamp named its producing files", async () => {
38
+ const file = await makeProducer();
39
+ const { code: _, ...older } = buildCacheStamp([file]);
40
+ expect(isBuildCacheStamp(older, buildCacheStamp([file]))).toBe(false);
41
+ });
42
+ });
@@ -0,0 +1,23 @@
1
+ import { statSync } from "node:fs";
2
+ import { AkanAppConfig } from "../akanConfig/akanConfig";
3
+
4
+ export interface BuildCacheStamp {
5
+ akanjs: string;
6
+ bun: string;
7
+ code: string;
8
+ }
9
+
10
+ //? Kept across starts, so another akanjs, Bun or edit of the producing module (run from source) must read as a miss.
11
+ export const buildCacheStamp = (producers: string[]): BuildCacheStamp => ({
12
+ akanjs: AkanAppConfig.akanVersion,
13
+ bun: `${Bun.version}+${Bun.revision}`,
14
+ code: producers
15
+ .map((file) => {
16
+ const stats = statSync(file, { throwIfNoEntry: false });
17
+ return stats ? `${stats.mtimeMs}:${stats.size}` : "missing";
18
+ })
19
+ .join(","),
20
+ });
21
+
22
+ export const isBuildCacheStamp = (value: Partial<BuildCacheStamp> | null | undefined, stamp: BuildCacheStamp) =>
23
+ value?.akanjs === stamp.akanjs && value.bun === stamp.bun && value.code === stamp.code;