akanjs 3.2.0-rc.19 → 3.2.0-rc.20

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 (35) hide show
  1. package/CHANGELOG.md +55 -1
  2. package/common/PipelinePlanSchema.ts +2 -2
  3. package/common/pipelinePlan.ts +1 -1
  4. package/common/types.ts +9 -0
  5. package/fetch/client/fetchClient.ts +4 -4
  6. package/package.json +1 -1
  7. package/server/akanApp.ts +4 -2
  8. package/server/akanServer.ts +24 -12
  9. package/server/di/diLifecycle.ts +24 -35
  10. package/server/di/predefinedAdaptor.ts +24 -1
  11. package/server/di/resolveHierarchy.ts +16 -5
  12. package/server/di/utils.ts +7 -3
  13. package/server/flightRowReader.ts +65 -11
  14. package/server/lifecycle/shutdownManager.ts +6 -3
  15. package/server/lifecycle/startGuard.ts +18 -1
  16. package/server/rscClient.tsx +15 -6
  17. package/server/rscClientChunks.ts +5 -1
  18. package/server/rscClientPatch.ts +12 -1
  19. package/server/rscHostReloads.ts +22 -5
  20. package/server/rscHostRenderStream.ts +15 -8
  21. package/server/rscHostRequests.ts +13 -7
  22. package/server/rscWorkerHost.ts +15 -8
  23. package/server/rscWorkerProcess.ts +1 -0
  24. package/server/ssrFromRscRenderer.tsx +18 -18
  25. package/service/predefinedAdaptor/websocket.adaptor.ts +4 -0
  26. package/signal/openapi/openapi.ts +10 -1
  27. package/types/common/types.d.ts +9 -0
  28. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  29. package/types/server/lifecycle/startGuard.d.ts +1 -0
  30. package/types/server/rscClientPatch.d.ts +1 -1
  31. package/types/server/rscHostReloads.d.ts +5 -3
  32. package/types/server/rscHostRenderStream.d.ts +2 -1
  33. package/types/server/rscHostRequests.d.ts +3 -2
  34. package/types/server/rscWorkerProcess.d.ts +1 -0
  35. package/types/server/ssrFromRscRenderer.d.ts +2 -2
package/CHANGELOG.md CHANGED
@@ -125,6 +125,16 @@
125
125
 
126
126
  **`Exception.<Status>.is(error)` type-checks.** `StatusException` now declares `is`, so `Exception.BadRequest.is(error)` narrows `error` to an `Exception` and checks its own class.
127
127
 
128
+ - d79a206: A call a page makes while it renders on the server can leave the page in the route result cache.
129
+
130
+ A `fetch.*` call made during a server render forwards the visitor's session and address, so it reads the page request's headers and cookies. That marks the render dynamic, and the HTML and RSC result caches never store it, even for an anonymous visitor. A page whose only server data is an answer that is the same for everyone was therefore rendered on every request.
131
+
132
+ `{ forwardVisitor: false }` in a call's options sends it without the visitor's session or address, so it answers as it would to a stranger and the render can stay cacheable: `fetch.featureFlags({ forwardVisitor: false })`. Another call in the same render that forwards the visitor still keeps the page out of the cache. An explicit `token` and the `jwt` and `clientIp` a cloned client was given are still sent, and a call made in a browser, or aimed at another origin, is unchanged.
133
+
134
+ Use it only for an endpoint that answers every caller alike, such as a `Public` query that takes no `.with()` argument, and give that endpoint `rateLimit: false` (or exempt it in `option.setRateLimit`) rather than an address budget. Every such call reaches the server from the render's own loopback address, so every visitor's render then shares one budget under that address. Anyone can force a render: a signed-in request or any cookie other than `theme` bypasses the cache, and a new query parameter misses it. Under an address budget, one client forcing renders can spend it, so the call answers 429 for everyone, and the page's fallback for that failure is cached and served to every visitor until the entry expires.
135
+
136
+ **Upgrading.** Nothing changes unless a call passes `forwardVisitor: false`.
137
+
128
138
  - d9f5ad5: Behind the gateway, a WebSocket subscribe is now acknowledged once the gateway routes the room to the replica that holds it. The gateway used to learn of the room in a message the replica sent without waiting, so an event or a live-list write handled by another replica right after the ack could reach the gateway first and be dropped.
129
139
 
130
140
  - `SolidPubSub.joinRoom` sends its `pubsub.subscribe` with an `ack` number and resolves when the gateway answers `pubsub.subscribed`. A replica's messages reach the gateway in order, so the answer also covers the live models it reported before the subscribe.
@@ -384,6 +394,11 @@
384
394
 
385
395
  In `@akanjs/devkit`, `shouldAbandonBackendRecovery` is replaced by `backendRecoveryPolicy`, which gives up after five failed backend restarts as before.
386
396
 
397
+ - 6d449b1: A page that imports anything from `akanjs/common` no longer ships the pipeline plan parser to the browser, so every page loads about 4.8 KB less JS, brotli.
398
+
399
+ - **Before:** `PipelinePlanSchema` builds two key lists with `Object.keys` in static fields, and `pipelinePlan.ts` builds `pipelineActionNames` the same way. The bundler counted those calls as side effects, so it kept `PipelinePlanSchema`, `PipelinePattern`, `PipelineNames`, `PipelineValueReader` and the plan vocabulary in every client bundle, though only the build tooling and the pipeline executor read them.
400
+ - **Now:** those three calls are marked `@__PURE__`, so a client bundle drops the pipeline code it never uses. The parser, `pipelineActionNames` and every other export behave as before.
401
+
387
402
  - 1ebc57a: The `Err` an app imports in client code now has `Err.is(error, ...keys)`, as the `Err` from the app's dictionary (the one services throw) already did. It was missing on the client one, so client code that checked a caught error with it failed to typecheck, or threw a `TypeError` when typed loosely. `Err.is` is true for an `Err`, or for any error carrying a string `error` key, so one restored from a failed `fetch` call passes too; naming keys accepts only those and narrows the error's type to them. Both `Err` classes now run the same check.
388
403
  - c3b5b3c: The framework no longer puts `@akanjs/native/core` on a web page. `isNativeApp()` and the other host checks read the platform the shell writes before the bundle runs, and a native shell still starts core with the page. A file that imports `akanjs/client/native` statically still brings core to every page that reaches it. On the minimal app this takes 15 KB raw (5.6 KB brotli) off the vendor floor and 20 KB raw (6.6 KB brotli) off every route entry. `akan build` also resolves the `production` export condition for the browser, SSR-client, CSR and MCP App view bundles, so a package such as Lexical ships its production build alone. On the minimal app the Agent editor chunk drops from 91 KB to 63 KB brotli. `akan start` is unchanged.
389
404
  - 6d5b544: A database service now has `create<Model>Many(rows)`. It creates the rows on the same path as `create<Model>`: `_preCreate` and `_postCreate`, the document's save and create hooks, and the live and pubsub events each row's commit fires. Every row's `_preCreate` and document pre hooks run first, so a check there that queries the table does not see the batch's own rows. The rows are then written in one transaction, joining the caller's when one is open, with one multi-row INSERT per 500 rows instead of one statement per row; if the database refuses one row, none is written. Every row's `_postCreate` runs once the transaction commits, as `create<Model>`'s runs once its row is stored, so a `_postCreate` that throws leaves the rows written. A service that already declares a method of that name, itself or in a lib service it extends, keeps its own at runtime, but its signature no longer typechecks against the generated one: rename it.
@@ -410,6 +425,16 @@
410
425
 
411
426
  `FetchPolicy.cache` and `FetchPolicy.partial` are deprecated. Nothing has read them since v2 dropped GraphQL; an endpoint reuses its answer with its own `query(T, { cache })`. `FetchPolicy.onError` is deprecated too, since nothing calls it: catch the call's rejection instead.
412
427
 
428
+ - 0e5db0a: A server-rendered page is smaller, renders faster, and its browser decodes its RSC payload faster. The server used to put every Flight row of the page's payload in its own inline `<script>`. That added up to 4,000 scripts on a 1.1 MB payload, and the HTML of the minimal app's pages on its dev server carried 150 to 400 of them. Each chunk of the payload the server receives now goes out as one script, with its rows unchanged. A typed-array or `ArrayBuffer` row still goes out as a script of its own, so only that row is base64-encoded. On the dev server, the minimal app's pages now carry 1 or 2 scripts each, and their HTML is 5.7–8.1% smaller. Measured in Bun with a 1.1 MB payload:
429
+
430
+ - the server's work from rendering through to the last byte drops by about 15%;
431
+ - in 16 KB chunks, the server-side decode of the payload drops by about 25%, and by less in 1 KB chunks;
432
+ - in 16 KB chunks, the browser's decode of the page's payload drops by about 40%, and by less in 1 KB chunks.
433
+
434
+ The bytes React decodes are unchanged, and so is when a row reaches the page. The first HTML byte leaves as early as before, or earlier.
435
+
436
+ `AKAN_MAX_PENDING_INLINE_RSC_SCRIPTS` is replaced by `AKAN_MAX_PENDING_INLINE_RSC_BYTES` (default 16 KB). It caps how many bytes of the payload the server reads ahead and holds, unencoded, while the page's HTML is still streaming, though a single chunk larger than the cap is still read and held whole. The old variable counted scripts, and it is no longer read.
437
+
413
438
  - c334caf: A root layout's fonts now preload one face per family instead of every face. By default that is the regular face: 400 normal, or the weight a browser draws regular text with when the family has no 400 (500, then lighter, then heavier). Every other weight still has its `@font-face` rule, with `font-display: swap`, and loads when text first uses it. A path set to `preload: true` is preloaded as well, and `preload: false` still never is. The app template's home page declares nine Pretendard weights and preloaded all of them, 166 KB; it now preloads one, 18 KB, and fetches the three other weights it shows when it draws them. To keep a weight the first screen shows preloaded, set `preload: true` on its path; the akanjs.com layout now does that for 700 and 900.
414
439
  - 170be15: A form field setter now costs about one copy of the state, like any other store write. `set<Field>On<Model>`, `add<Field>On<Model>`, `sub<Field>On<Model>`, `writeOn<Model>` and the file upload setters used to hand `set` an updater, which ran immer over the whole state and then compared every key. A keystroke cost 284 µs at 1,740 keys and 600 µs at 3,480. They now produce the new form alone and write it as a patch: 42 µs at 1,740 keys and 79 µs at 3,480, against 37 µs and 74 µs for a bare copy of the state.
415
440
 
@@ -446,6 +471,7 @@
446
471
  - Each error asks about at most the four latest, all at once, and waits for a request another error already has out. The first 404 whose reload is not claimed yet reloads, so a chunk a reload did not fix never hides another.
447
472
  - A recorded failure the server serves is not asked about again. One that answers 404 stays listed, since its reload can be skipped and WebKit does not fetch a module that failed again. One whose request fails or answers another error status, such as a load balancer's 5xx, stays for three requests.
448
473
  - Only WebKit's exact message counts. Its syntax, link, MIME-type and evaluation errors are worded differently and still leave the page alone.
474
+ - **A request the server has not answered after 10 seconds is given up** and counts as failed, like a network failure: it does not reload, and the next error asks again instead of waiting on it.
449
475
  - **The reload is skipped if anything happened while the request was out:**
450
476
  - any client navigation, including a shallow update, a refresh (the token-refresh timer's too) or a back or forward move;
451
477
  - a `beforeunload` or `pagehide`, which a document load the router never sees fires (a plain link, a form post, `location.assign`).
@@ -539,6 +565,7 @@
539
565
  - Its `noindex` is one `robots` meta that keeps the other directives a layout's `robots` meta gives, such as `nofollow`.
540
566
  - Under a `.loading()` the head is out before the view renders, so its tags stay in the view, as before.
541
567
 
568
+ - 6cdfb73: `/openapi.json` now lists the 404 `base.error.documentNotFound` that a generated `<model>`, `light<Model>`, `update<Model>` or `remove<Model>` can answer when its id names no live document, in the same `AkanError` shape as a declared error. A caller that a resource guard such as `Can<Verb><Model>` refuses still gets the guard's 403, since the guard fails closed when its own load misses. A document with such an endpoint now carries the `AkanError` component. `create<Model>`, the slice reads and custom endpoints are unchanged. Only OpenAPI changes: the MCP `tools/list`, the in-page agent's tools and the server's `errors` checks read none of it, so a tool's description gains no line and `base.error.*` is still never declared in an endpoint's `errors`. The answer itself is unchanged, and so is the level each miss is logged at.
542
569
  - b24fef3: An app that draws no Akan UI component now builds and runs without the UI's optional peers. Before, `akan build` failed with `Could not resolve: "react-icons/ai"` or `"react-spring"` in an app that imported nothing from `akanjs/ui`: the System UI every root layout mounts drew react-icons glyphs and reached the model, list and dialog components through the `Load` and `Button` modules, and the CSR build, on by default, bundled the whole `akanjs/ui` barrel.
543
570
 
544
571
  **Upgrade note.** A workspace can drop `react-spring`, `@react-spring/web`, `@use-gesture/react`, `react-refresh`, `scheduler` and `tailwind-scrollbar` from its `package.json`, unless its own code imports them. `akanjs` now depends on `@react-spring/web`, `@use-gesture/react`, `react-refresh`, `scheduler` and `tailwind-scrollbar` itself, because the System UI, the dev runtime and `akanjs/ui/styles.css` always use them, and nothing uses `react-spring` any more. New workspaces no longer list them. A workspace whose own code keeps `react-spring` or `@react-spring/web` must move it to major 10: an older one installs a second copy under `akanjs`, and a spring value the app makes no longer typechecks on an `animated.*` element from `akanjs/ui`.
@@ -574,6 +601,7 @@
574
601
  - **A PUBLISH a Redis ACL refuses (`NOPERM`) is dropped, not retried.** It used to be retried on a timer, and every event queued behind it waited with it, so one refused channel delayed all cross-server events. A refusal is logged as an error that names the family of channels whose events are being dropped (`<prefix>ws:room` or `<prefix>ws:change`), at most once a minute per family. Other error replies are still retried.
575
602
  - **A shutdown no longer logs the publisher's and subscriber's disconnect warnings.** A link that drops while the server runs still warns, and a dropped publisher now warns once rather than on every failed reconnect attempt.
576
603
 
604
+ - 228b6d7: A server shutting down no longer tells its `pubsub` rooms to resync, or resubscribes to Redis, when the Redis WebSocket adaptor's subscriber reconnects just as the shutdown begins. Its clients used to get `resync` frames, and run `onResync`, for up to a second before the server closed their sockets.
577
605
  - 6b3b4e4: **A graceful shutdown now lets the cross-server events the Redis WebSocket adaptor is still sending reach Redis, within a second.** The adaptor closed its publisher with ioredis `disconnect()`, which returns while the socket is still writing, and the process exits right after a shutdown, so a backlog of events it had published never reached Redis. Nothing was logged, and the other servers' clients missed those events without being told to resync. It now sends `QUIT`, which Redis answers only after every command ahead of it, and disconnects once that answer is in or the link closes. A link that stalls or is too slow to take the backlog gets one second, shared with the drain of the adaptor's own buffer, which had no limit before. Running out of it logs a warning that events still being sent may be lost.
578
606
  - 7f0de74: On the Redis WebSocket adaptor, each room's events and each live-synced model's changes now go out on channels of their own, and a server subscribes only to those of the rooms and models it holds. Both used to go to every server of the app on one channel, `<prefix>ws:broadcast`, which servers no longer publish or listen on.
579
607
 
@@ -608,6 +636,7 @@
608
636
 
609
637
  **Upgrading.** The solid SQLite open used to reject with SQLite's error itself. Code that matched that error's `code` (`SQLITE_BUSY` or `SQLITE_LOCKED`) now finds it on `error.cause`. You can also branch on `AkanError.is(error, "databaseLocked")`.
610
638
 
639
+ - 5757156: During a server render, a `fetch.*` query shares a request only with calls that end up with the same `timeout` and `retry`: the call's own, or else its endpoint's timeout and its client's (`clone({ retry })`, `setTimeout`). Before, the render shared one request between every call with the same endpoint, arguments and credential, from any client, so the first call's deadline and retry policy applied to all of them. A page's `fetch.isMemoOpen({ timeout: 3_000 })` after a layout's `fetch.isMemoOpen()` waited as long as the layout's call did, up to the client's 30 s default, and a page's `fetch.clone({ retry: { attempts: 4 } })` call ran without retries. Calls that pass no options still share one request per render, as before. The browser's in-flight sharing keys the same way, so a call naming `retry: false` (the default) now joins one that names none.
611
640
  - 9a2a8c9: The build refuses a `LevelBoundary` or `McpAppRoot` export on an app's root layout: `page/_layout.tsx`, or a grouped or base-path root layout. Akan.js defines both on the root layout it generates and reads neither from an app's layout, so such an export was silently ignored. The error names the export and the file and says why. Remove the export; it never took effect.
612
641
 
613
642
  `akanjs/common` exports `GENERATED_ROOT_LAYOUT_EXPORTS`, the set of those names.
@@ -678,6 +707,7 @@
678
707
  - **The cache stays bounded at 32 entries.** A patch whose full render can no longer come back is dropped. `clearRscNavigationCache()`, `refreshRsc()`, an HMR refresh and an account change still drop every cached patch.
679
708
  - **The default is unchanged.** Partial commit is still off unless the flag is set.
680
709
 
710
+ - 99e3fd8: With `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a partial navigation whose page redirects or fails in a later chunk of its stream than the first row no longer leaves the patch on screen. Before, the patch was laid and kept: the browser stayed on the page that redirected with the patched part blank, or kept the patch with the error in it. Now a redirect, error or not-found row that arrives before the patch is laid fetches the page whole instead. One that arrives after it, while the patched page is still on screen and no other page is loading, reloads the whole page in place, which follows the redirect or shows the page's error; such a reload, like any refresh, drops the browser's navigation cache. React's dev-only error rows with an empty digest no longer count as errors for a patch. A patch whose stream carried a redirect is no longer replayed from the navigation cache, and a partial navigation waits one browser task after its first row before it is laid.
681
711
  - c723e7a: With `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a Link prefetch now carries the router state, so a prefetched sibling page comes back as a patch. A prefetched patch is used only under the full commit it was requested from, and a link the patch cache would replay is no longer prefetched.
682
712
  - 6c3a303: A page that renders a string of 1024 characters or more, such as a post body or a long comment, now renders and hydrates whatever its lines say. React sends such a string, and every typed array or `ArrayBuffer`, as a length-prefixed Flight row whose raw bytes may hold newlines. The SSR sanitizer, the client navigation redirect guard and the partial-navigation patch check all split the stream on every newline, so they read lines inside the text as rows of their own. A line shaped like a debug row was dropped and a line shaped like a redirect row was rewritten, which broke the render. On a client navigation the guard could act on such a line as a redirect, and a partial navigation fell back to a full one.
683
713
 
@@ -803,6 +833,30 @@
803
833
  - **Links in agent markdown.** `isSafeHref` drops tabs, newlines and leading control characters and spaces before it reads the scheme, as a browser does, so a disguised `javascript:` link is refused.
804
834
  - **CSV export keeps formulas as text.** A text cell that starts with `=`, `+`, `-`, `@`, a tab or a carriage return gets a leading `'`. Numbers are written unchanged.
805
835
 
836
+ - ce35811: `AkanServer`, the DI container, the RSC worker host and `AkanApp` now fail with a coded `AkanError` instead of a bare `Error`. Messages are unchanged, and so is every status a caller is answered with. The error-code reference lists the new codes.
837
+
838
+ - `AkanServer`:
839
+ - `alreadyInitialized` (500): a `set*` config call, or a second `init()`, once `init()` has run.
840
+ - `notInitialized` (500): `listen()` before `init()`, or `get`/`getService`/`getSignal`/`getAdaptor` before the server is initialized.
841
+ - `shutdownTimeout` (500): `stop()` when the teardown outlasts `setShutdownTimeout`.
842
+ - The DI container:
843
+ - `InjectError` `notRegistered` / `notInitialized` (500): a lookup, a plug or memory inject, or the scheduler, with nothing registered or initialized under that name.
844
+ - `invalidConfig` (500): `modules`, `disableModules` or `disableLibs` names an unknown module or lib, an `@<operationMode>` selector matches no module, or the build does not carry the database mode's drivers.
845
+ - `circularDependency` (500): services or adaptors inject each other in a cycle.
846
+ - `duplicateRegistration` (500): two owners claim one adaptor, use, job, fetch handler or socket key.
847
+ - `stageFailed` (500): tasks of a boot stage failed. Its `errors` holds each task's own error.
848
+ - The RSC worker host:
849
+ - `rscWorkerFailed` (500): the worker answered a render, a page prompt or manifest call, its boot or a reload with an error, or exited while it imported the pages bundle. A failed reload still carries `adopted` and `failed`.
850
+ - `rscWorkerStopped` (500): a render, a call or a reload the worker could not answer because it was stopped, exited, or could not be sent the request. A failed reload still carries `adopted` and `failed`.
851
+ - `renderAborted` (499): the request aborted with a reason that is not an `Error`. It is still named `AbortError`, so the page still answers 499.
852
+ - `rscQueueOverflow` (500): the host's chunk queue for a render passed its cap.
853
+ - `invalidRscResponse` (500): the worker sent a redirect or a not-found after the stream started.
854
+ - `AkanApp`:
855
+ - `invalidConfig` (500): a desktop app's server asked for a gateway and replicas.
856
+ - `invalidArtifact` (500): the solo server module exports neither `server` nor `app` with `start()`.
857
+
858
+ **Upgrading.** A failed DI boot stage used to throw an `AggregateError`. It is now an `AkanError` coded `stageFailed`, so `instanceof AggregateError` no longer matches it. Its `errors` still lists each task's error, and you can branch on `AkanError.is(error, "stageFailed")`.
859
+
806
860
  - 463fd1e: The server's own failures now carry an `AkanError` code, and those a caller causes answer with the status that fits instead of a 500. Messages are unchanged. Outside development, the caller still sees only the status reason and the code, never the message.
807
861
 
808
862
  - A WebSocket frame that is not a string, is not JSON, is not an object (`null` included), or names no `key` answers `400 invalidMessage`. A `key` with no route answers `404 routeNotFound` and logs a warning. Only a failure of 500 or above is logged as an error.
@@ -834,7 +888,7 @@
834
888
 
835
889
  - f923ffb: An `AkanServer` stopped while `init()` was still initializing, or while `listen()` was still opening its log transport, no longer goes on to listen and serve: the start tears down what it has brought up and returns, and `stop()` resolves once the server is stopped, which during `init()` means after the container or web router under way finishes starting, beyond `shutdownTimeoutMs`. A replica whose gateway is gone by the time it reports ready no longer runs its init schedules while it shuts down.
836
890
 
837
- Two things follow from a stop waiting on the start under way. A `stop()` awaited from inside a service's or adaptor's init hook never settles, since the hook is the step it waits for: call it without awaiting there. And a replica told to shut down, or orphaned, during `init()` finishes that init and tears down before it exits, where it used to exit at once.
891
+ Two things follow from a stop waiting on the start under way. A `stop()` called from inside a service's or adaptor's init hook cannot wait for the init it is part of, so it resolves at once: the rest of the init still runs, and the start then tears down and returns with the server stopped. That includes a callback the hook registered, such as a timer or a socket's `error` handler, when it fires before the init ends, so a `process.exit()` placed right after that `stop()` runs before the teardown. And a replica told to shut down, or orphaned, during `init()` finishes that init and tears down before it exits, where it used to exit at once.
838
892
 
839
893
  - 802bffe: An `AkanServer` whose `init()`, `listen()` or `start({ listen: false })` throws, for example on a missing route seed index or a port already in use, now tears down what it brought up before the error reaches the caller. That means the web router and its RSC worker, the log transport and its control socket, and the container, destroyed once. It ends `stopped`, so calling `start()` again starts it instead of throwing "already running", and the retried server answers each gateway message once.
840
894
 
@@ -35,7 +35,7 @@ export class PipelinePlanSchema {
35
35
  static readonly #sha256Pattern = /^[0-9a-f]{64}$/;
36
36
  static readonly #idChars = 256;
37
37
  static readonly #maxSeconds = 86_400;
38
- static readonly #shellKeys = Object.keys({
38
+ static readonly #shellKeys = /* @__PURE__ */ Object.keys({
39
39
  id: true,
40
40
  name: true,
41
41
  timeoutSeconds: true,
@@ -48,7 +48,7 @@ export class PipelinePlanSchema {
48
48
  secrets: true,
49
49
  skipExitCodes: true,
50
50
  } satisfies { [key in keyof PipelinePlanShellStep]: true });
51
- static readonly #actionKeys = Object.keys({
51
+ static readonly #actionKeys = /* @__PURE__ */ Object.keys({
52
52
  id: true,
53
53
  name: true,
54
54
  timeoutSeconds: true,
@@ -29,7 +29,7 @@ export const pipelineActions = {
29
29
  ota: { version: 1, milestone: "deploy", name: "OTA" },
30
30
  } as const satisfies Record<string, { version: number; milestone: PipelineMilestone; name: string }>;
31
31
  export type PipelineActionName = keyof typeof pipelineActions;
32
- export const pipelineActionNames = Object.keys(pipelineActions) as readonly PipelineActionName[];
32
+ export const pipelineActionNames = /* @__PURE__ */ Object.keys(pipelineActions) as readonly PipelineActionName[];
33
33
 
34
34
  /** The phones an `ota` action packs for; a desktop app updates itself whole, outside a pipeline. */
35
35
  export const pipelineOtaPlatforms = ["ios", "android"] as const;
package/common/types.ts CHANGED
@@ -46,6 +46,15 @@ export interface FetchPolicy<_Returns = unknown> {
46
46
  * pages a link prefetched survive it, where any other write sends them again.
47
47
  */
48
48
  keepsReads?: boolean;
49
+ /**
50
+ * `false` sends a call made while the server renders a page without the visitor's session or address, so it answers
51
+ * as to a stranger and the render can stay in the route result cache. An explicit `token` and the client's own `jwt`
52
+ * and `clientIp` still go, and a browser's call is unchanged. Only for an endpoint that answers every caller alike:
53
+ * every visitor's render then shares one budget under the server's own address, so give that endpoint
54
+ * `rateLimit: false` (or exempt it) rather than an address budget, or one client forcing renders spends it for
55
+ * everyone.
56
+ */
57
+ forwardVisitor?: boolean;
49
58
  }
50
59
 
51
60
  export type SnakeCase<S extends string> = S extends `${infer T}_${infer U}` ? `${Lowercase<T>}_${SnakeCase<U>}` : S;
@@ -346,7 +346,7 @@ export class FetchClient {
346
346
  }
347
347
 
348
348
  #forwardsVisitor(option?: FetchPolicy) {
349
- return !this.#foreign && this.#ownOrigin(option);
349
+ return option?.forwardVisitor !== false && !this.#foreign && this.#ownOrigin(option);
350
350
  }
351
351
  #makeAuthHeaders(option?: FetchPolicy): Record<string, string> {
352
352
  if (option?.token) return { Authorization: `Bearer ${option.token}` };
@@ -445,10 +445,10 @@ export class FetchClient {
445
445
  requestQuery: (signal?: AbortSignal) => Promise<unknown>,
446
446
  { signal, timeout, retry }: { signal?: AbortSignal; timeout?: number | false; retry?: RetryPolicy | false },
447
447
  ) {
448
- if (getRequestStore()) return claimRequestQuery(cacheKey, () => requestQuery());
448
+ const claimKey = `${cacheKey}\n${timeout ?? this.http.timeout}\n${JSON.stringify(retry ?? this.http.retry)}`;
449
+ if (getRequestStore()) return claimRequestQuery(claimKey, () => requestQuery());
449
450
  if (typeof window === "undefined") return { value: requestQuery(signal), owned: true };
450
- const inflightKey = `${cacheKey}\n${JSON.stringify([timeout ?? null, retry ?? null])}`;
451
- return { value: this.#inflight.claim(inflightKey, requestQuery, signal), owned: true };
451
+ return { value: this.#inflight.claim(claimKey, requestQuery, signal), owned: true };
452
452
  }
453
453
  #untilAborted<T>(promise: Promise<T>, signal?: AbortSignal) {
454
454
  return AbortSignals.race(promise, signal).catch((error: unknown) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.19",
3
+ "version": "3.2.0-rc.20",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/server/akanApp.ts CHANGED
@@ -1,5 +1,6 @@
1
1
 
2
2
  import "./lifecycle/loadBuildEnv";
3
+ import { AkanError } from "akanjs/base";
3
4
  import { Logger, TrustedProxy } from "akanjs/common";
4
5
  import type { AkanIpcMessage } from "akanjs/service";
5
6
  import { resetEnvCache } from "../base/baseEnv";
@@ -93,7 +94,8 @@ export class AkanApp {
93
94
  }
94
95
  if (this.#config.solo) return await this.#startSolo();
95
96
  if (SelfExec.carried)
96
- throw new Error(
97
+ throw new AkanError(
98
+ "invalidConfig",
97
99
  "A desktop app's server runs in one process, and this one was asked for a gateway and replicas, which would start with the `bun` on the user's PATH: by `replica` or `solo: false` in main.ts, or by AKAN_SOLO=false, an AKAN_REPLICA other than one traffic replica, or AKAN_COMMAND_TYPE=start in its env. Leave them out of the app the desktop build carries.",
98
100
  );
99
101
  Logger.role = "gateway";
@@ -144,7 +146,7 @@ export class AkanApp {
144
146
  this.logger.info(`Starting ${role} replica in this process (solo); set AKAN_SOLO=false for the gateway`);
145
147
  const mod = (await import(this.#config.serverPath)) as { server?: SoloServer; app?: SoloServer };
146
148
  const server = mod.server ?? mod.app;
147
- if (!server?.start) throw new Error("server.ts must export server or app with start()");
149
+ if (!server?.start) throw new AkanError("invalidArtifact", "server.ts must export server or app with start()");
148
150
  await server.start({ listen: true });
149
151
  }
150
152
 
@@ -1,5 +1,5 @@
1
1
  import type { AkanWebConfig, AkanWebOption } from "akanjs";
2
- import { type BackendEnv, type BaseEnv, getApiPrefix, getEnv, getWsPrefix } from "akanjs/base";
2
+ import { AkanError, type BackendEnv, type BaseEnv, getApiPrefix, getEnv, getWsPrefix } from "akanjs/base";
3
3
  import { Logger } from "akanjs/common";
4
4
  import type { Adaptor, AdaptorCls, DatabaseConfig, Service, ServiceCls, SolidConfig } from "akanjs/service";
5
5
  import type { ServerSignal, ServerSignalCls } from "akanjs/signal";
@@ -204,28 +204,33 @@ export class AkanServer {
204
204
  });
205
205
  }
206
206
  setPrefix(prefix: string) {
207
- if (this.status !== "stopped") throw new Error("Route prefix must be set before app initialization.");
207
+ if (this.status !== "stopped")
208
+ throw new AkanError("alreadyInitialized", "Route prefix must be set before app initialization.");
208
209
  this.prefix = ServerConfig.requireRoutePrefix(prefix, "prefix");
209
210
  return this;
210
211
  }
211
212
  setWebsocketPrefix(websocketPrefix: string) {
212
- if (this.status !== "stopped") throw new Error("Websocket prefix must be set before app initialization.");
213
+ if (this.status !== "stopped")
214
+ throw new AkanError("alreadyInitialized", "Websocket prefix must be set before app initialization.");
213
215
  this.websocketPrefix = ServerConfig.requireRoutePrefix(websocketPrefix, "websocketPrefix");
214
216
  return this;
215
217
  }
216
218
  setOpenApi(openapi = true) {
217
- if (this.status !== "stopped") throw new Error("OpenAPI config must be set before app initialization.");
219
+ if (this.status !== "stopped")
220
+ throw new AkanError("alreadyInitialized", "OpenAPI config must be set before app initialization.");
218
221
  this.openapi = openapi;
219
222
  return this;
220
223
  }
221
224
  /** Narrows the web surface; never widens it past what the build produced. */
222
225
  setWeb(web: AkanWebOption = true) {
223
- if (this.status !== "stopped") throw new Error("Web config must be set before app initialization.");
226
+ if (this.status !== "stopped")
227
+ throw new AkanError("alreadyInitialized", "Web config must be set before app initialization.");
224
228
  this.web = ServerConfig.narrowWeb(this.web, web);
225
229
  return this;
226
230
  }
227
231
  setMcp(mcp: boolean | McpServerOption = true) {
228
- if (this.status !== "stopped") throw new Error("MCP config must be set before app initialization.");
232
+ if (this.status !== "stopped")
233
+ throw new AkanError("alreadyInitialized", "MCP config must be set before app initialization.");
229
234
 
230
235
  const requested = typeof mcp === "boolean" ? mcp : (mcp.enabled ?? this.mcp);
231
236
  this.mcp = requested && !ServerConfig.isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
@@ -248,12 +253,14 @@ export class AkanServer {
248
253
  return this.#builtinRoutes.mcpRouter;
249
254
  }
250
255
  setDatabaseConfig(database: DatabaseConfig) {
251
- if (this.status !== "stopped") throw new Error("Database config must be set before app initialization.");
256
+ if (this.status !== "stopped")
257
+ throw new AkanError("alreadyInitialized", "Database config must be set before app initialization.");
252
258
  this.env.database = database;
253
259
  return this;
254
260
  }
255
261
  setSolidConfig(solid: SolidConfig) {
256
- if (this.status !== "stopped") throw new Error("Solid config must be set before app initialization.");
262
+ if (this.status !== "stopped")
263
+ throw new AkanError("alreadyInitialized", "Solid config must be set before app initialization.");
257
264
  this.env.solid = solid;
258
265
  return this;
259
266
  }
@@ -310,7 +317,8 @@ export class AkanServer {
310
317
  }
311
318
 
312
319
  async init(option: { routes?: boolean; web?: AkanWebOption } = {}) {
313
- if (this.status !== "stopped") throw new Error("AkanServer is not able to init. It is already running.");
320
+ if (this.status !== "stopped")
321
+ throw new AkanError("alreadyInitialized", "AkanServer is not able to init. It is already running.");
314
322
  ServerConfig.assertPrefixClearsBasePaths(this.prefix);
315
323
  const start = performance.now();
316
324
  this.#initTimings.clear();
@@ -389,7 +397,7 @@ export class AkanServer {
389
397
  async listen() {
390
398
  const prepared = this.#prepared;
391
399
  if (this.status !== "initialized" || !prepared)
392
- throw new Error("AkanServer is not able to listen. Call `init` first.");
400
+ throw new AkanError("notInitialized", "AkanServer is not able to listen. Call `init` first.");
393
401
  this.status = "starting";
394
402
  Logger.role = this.serverMode;
395
403
  return await this.#start.unwound(() => this.#listen(prepared));
@@ -492,7 +500,8 @@ export class AkanServer {
492
500
  const assertCanGet = (status: AkanServer["status"], type = "Dependency", refName?: string) => {
493
501
  if (status === "initialized" || status === "running") return;
494
502
  const target = refName ? `${type} "${refName}"` : type;
495
- throw new Error(
503
+ throw new AkanError(
504
+ "notInitialized",
496
505
  `${target} is not initialized while AkanServer status is "${status}". ` +
497
506
  "Call server.start() or server.init() first.",
498
507
  );
@@ -504,7 +513,10 @@ const withShutdownTimeout = async <T>(promise: Promise<T>, timeoutMs: number) =>
504
513
  return await Promise.race([
505
514
  promise,
506
515
  new Promise<T>((_, reject) => {
507
- timeout = setTimeout(() => reject(new Error(`Shutdown timed out after ${timeoutMs}ms`)), timeoutMs);
516
+ timeout = setTimeout(
517
+ () => reject(new AkanError("shutdownTimeout", `Shutdown timed out after ${timeoutMs}ms`)),
518
+ timeoutMs,
519
+ );
508
520
  }),
509
521
  ]);
510
522
  } finally {
@@ -1,4 +1,4 @@
1
- import { type BackendEnv, DatabaseModes, getEnv, INTERNAL_META } from "akanjs/base";
1
+ import { AkanError, type BackendEnv, DatabaseModes, getEnv, INTERNAL_META } from "akanjs/base";
2
2
  import { Logger } from "akanjs/common";
3
3
  import { ConstantRegistry } from "akanjs/constant";
4
4
  import { FetchClient } from "akanjs/fetch";
@@ -7,6 +7,7 @@ import {
7
7
  type AdaptorCls,
8
8
  getDefaultInjectRegistry,
9
9
  getDefaultLiveRegistry,
10
+ InjectError,
10
11
  InjectInfo,
11
12
  type Scheduler,
12
13
  type Service,
@@ -29,7 +30,12 @@ import { MachineAccount } from "../machine/machineAccount";
29
30
  import type { WebProxyRegistration } from "../proxy";
30
31
  import { CascadeRunner, DatabaseResolver, ServiceResolver, SignalResolver } from "../resolver";
31
32
  import type { SignalRoutes, WebsocketRoutes } from "../types";
32
- import { collectPredefinedDependencies, getPredefinedAdaptor, predefinedAdaptorRole } from "./predefinedAdaptor";
33
+ import {
34
+ collectPredefinedDependencies,
35
+ getPredefinedAdaptor,
36
+ predefinedAdaptorRole,
37
+ resolveDatabaseMode,
38
+ } from "./predefinedAdaptor";
33
39
  import { collectAdaptors, resolveAdaptorHierarchy, resolveServiceHierarchy } from "./resolveHierarchy";
34
40
  import {
35
41
  assertUniqueRegistrations,
@@ -95,28 +101,6 @@ export class DiLifecycle {
95
101
  return [...this.#service.values(), ...this.#database.values()];
96
102
  }
97
103
 
98
- static #databaseMode() {
99
- const { environment, operationMode } = getEnv();
100
- const mode = DatabaseModes.resolve({
101
- requested: process.env.AKAN_DATABASE_MODE,
102
- declared: process.env.AKAN_DATABASE_MODES,
103
- local: environment === "local" || operationMode === "local",
104
- });
105
- const missing = DatabaseModes.drivers[mode].filter((driver) => {
106
- try {
107
- import.meta.resolve(driver);
108
- return false;
109
- } catch {
110
- return true;
111
- }
112
- });
113
- if (missing.length)
114
- throw new Error(
115
- `The ${mode} database mode imports ${missing.join(", ")}, which this build does not carry. Declare "${mode}" in database.modes of akan.config.ts: akan build bundles the drivers of every declared mode, and akan start installs them.`,
116
- );
117
- return mode;
118
- }
119
-
120
104
  static #envOn(...names: string[]) {
121
105
  return !names.some((name) => process.env[name] === "false" || process.env[name] === "0");
122
106
  }
@@ -125,7 +109,7 @@ export class DiLifecycle {
125
109
 
126
110
  ConstantRegistry.assertConsistentRefNames(disableLibs);
127
111
  this.#env = env;
128
- const databaseMode = DiLifecycle.#databaseMode();
112
+ const databaseMode = resolveDatabaseMode();
129
113
  this.logger.debug(`Database mode: ${DatabaseModes.describe(databaseMode)}`);
130
114
 
131
115
  this.#predefinedAdaptor = { ...getPredefinedAdaptor(databaseMode) };
@@ -381,7 +365,8 @@ export class DiLifecycle {
381
365
  .filter(({ module }) => module.service.srv.operationMode?.includes(mode))
382
366
  .map(({ refName }) => refName);
383
367
  if (!tagged.length)
384
- throw new Error(
368
+ throw new AkanError(
369
+ "invalidConfig",
385
370
  `[DI:${option}] "${name}" names no module: no serve() in this app or its libs lists operationMode "${mode}".`,
386
371
  );
387
372
  return tagged;
@@ -394,7 +379,10 @@ export class DiLifecycle {
394
379
  const unknown = names.filter((name) => !known.has(name));
395
380
  if (!unknown.length) return;
396
381
  const listed = [...known].sort((a, b) => a.localeCompare(b)).join(", ");
397
- throw new Error(`${unknownLabel} ${unknown.map((name) => `"${name}"`).join(", ")}. ${knownLabel}: ${listed}`);
382
+ throw new AkanError(
383
+ "invalidConfig",
384
+ `${unknownLabel} ${unknown.map((name) => `"${name}"`).join(", ")}. ${knownLabel}: ${listed}`,
385
+ );
398
386
  }
399
387
 
400
388
  async initializeAll(): Promise<SignalRoutes> {
@@ -512,7 +500,7 @@ export class DiLifecycle {
512
500
  for (const internalCls of internals) {
513
501
  try {
514
502
  const internal = this.registry.internal.get(internalCls);
515
- if (!internal) throw new Error(`Internal "${internalCls.refName}" is not registered`);
503
+ if (!internal) throw new InjectError("notRegistered", `Internal "${internalCls.refName}" is not registered`);
516
504
  SignalResolver.resolveSchedule(internalCls, internal as Internal, serverMode);
517
505
  } catch (err) {
518
506
  failures.push({ label: `schedule:${internalCls.refName}`, reason: err });
@@ -585,7 +573,7 @@ export class DiLifecycle {
585
573
  const adaptor = this.registry.adaptor.get(adaptorCls);
586
574
  if (adaptor) return adaptor;
587
575
 
588
- throw new Error(`Dependency "${cls.refName}" is not initialized.`);
576
+ throw new InjectError("notInitialized", `Dependency "${cls.refName}" is not initialized.`);
589
577
  }
590
578
 
591
579
  getService<T = Service>(refName: string): T {
@@ -605,16 +593,16 @@ export class DiLifecycle {
605
593
 
606
594
  static #lookup<C, I>(label: string, refName: string, classes: Map<string, C>, instances: Map<C, I>): I {
607
595
  const cls = classes.get(refName);
608
- if (!cls) throw new Error(`${label} "${refName}" is not registered.`);
596
+ if (!cls) throw new InjectError("notRegistered", `${label} "${refName}" is not registered.`);
609
597
  const instance = instances.get(cls);
610
- if (!instance) throw new Error(`${label} "${refName}" is not initialized.`);
598
+ if (!instance) throw new InjectError("notInitialized", `${label} "${refName}" is not initialized.`);
611
599
  return instance;
612
600
  }
613
601
 
614
602
  #getScheduler(): Scheduler {
615
603
  const adaptorCls = this.registry.adaptorRole.get(predefinedAdaptorRole.schedule);
616
604
  const scheduler = adaptorCls ? this.registry.adaptor.get(adaptorCls) : undefined;
617
- if (!scheduler) throw new Error("Scheduler is not registered");
605
+ if (!scheduler) throw new InjectError("notRegistered", "Scheduler is not registered");
618
606
  return scheduler as Scheduler;
619
607
  }
620
608
 
@@ -663,7 +651,7 @@ export class DiLifecycle {
663
651
  label: `adaptor:${refName}`,
664
652
  run: async () => {
665
653
  const adaptorCls = adaptorMap.get(refName);
666
- if (!adaptorCls) throw new Error(`Adaptor "${refName}" is not registered`);
654
+ if (!adaptorCls) throw new InjectError("notRegistered", `Adaptor "${refName}" is not registered`);
667
655
  const adaptor = new adaptorCls();
668
656
  await InjectInfo.resolveInjection(adaptor, adaptorCls, this.registry, this.#env);
669
657
  const start = Date.now();
@@ -717,10 +705,11 @@ export class DiLifecycle {
717
705
  label: `service:${refName}`,
718
706
  run: async () => {
719
707
  const serviceCls = serviceMap.get(refName);
720
- if (!serviceCls) throw new Error(`Service "${refName}" is not registered`);
708
+ if (!serviceCls) throw new InjectError("notRegistered", `Service "${refName}" is not registered`);
721
709
  if (serviceCls.type === "database") {
722
710
  const databaseModule = this.#database.get(serviceCls.refName);
723
- if (!databaseModule) throw new Error(`Database "${serviceCls.refName}" is not registered`);
711
+ if (!databaseModule)
712
+ throw new InjectError("notRegistered", `Database "${serviceCls.refName}" is not registered`);
724
713
  ServiceResolver.resolveDatabaseService(databaseModule.database, serviceCls, this.#cascade);
725
714
  }
726
715
  const service = new serviceCls();
@@ -1,5 +1,5 @@
1
1
  import type { DatabaseMode } from "akanjs";
2
- import { DatabaseModes } from "akanjs/base";
2
+ import { AkanError, DatabaseModes, getEnv } from "akanjs/base";
3
3
  import {
4
4
  type AdaptorCls,
5
5
  BlobStorage,
@@ -87,3 +87,26 @@ export const getPredefinedAdaptor = (mode: DatabaseMode = "single"): PredefinedA
87
87
  websocket: WebSocketRedisAdaptor,
88
88
  };
89
89
  };
90
+
91
+ export const resolveDatabaseMode = (): DatabaseMode => {
92
+ const { environment, operationMode } = getEnv();
93
+ const mode = DatabaseModes.resolve({
94
+ requested: process.env.AKAN_DATABASE_MODE,
95
+ declared: process.env.AKAN_DATABASE_MODES,
96
+ local: environment === "local" || operationMode === "local",
97
+ });
98
+ const missing = DatabaseModes.drivers[mode].filter((driver) => {
99
+ try {
100
+ import.meta.resolve(driver);
101
+ return false;
102
+ } catch {
103
+ return true;
104
+ }
105
+ });
106
+ if (missing.length)
107
+ throw new AkanError(
108
+ "invalidConfig",
109
+ `The ${mode} database mode imports ${missing.join(", ")}, which this build does not carry. Declare "${mode}" in database.modes of akan.config.ts: akan build bundles the drivers of every declared mode, and akan start installs them.`,
110
+ );
111
+ return mode;
112
+ };
@@ -1,5 +1,12 @@
1
- import { INJECT_META } from "akanjs/base";
2
- import { type AdaptorCls, AgentToolsRole, CacheAdaptorRole, type InjectInfo, type ServiceCls } from "akanjs/service";
1
+ import { AkanError, INJECT_META } from "akanjs/base";
2
+ import {
3
+ type AdaptorCls,
4
+ AgentToolsRole,
5
+ CacheAdaptorRole,
6
+ InjectError,
7
+ type InjectInfo,
8
+ type ServiceCls,
9
+ } from "akanjs/service";
3
10
 
4
11
  export interface DependencyNode {
5
12
  key: string;
@@ -47,7 +54,7 @@ export function topologicalStages<T extends DependencyNode>(graph: Map<string, T
47
54
  if (processed !== graph.size) {
48
55
  const remaining = [...graph.keys()].filter((k) => (inDegree.get(k) ?? 0) > 0);
49
56
  const cycle = traceCycle(graph, remaining);
50
- throw new Error(`Circular dependency detected: ${cycle.join(" → ")}`);
57
+ throw new AkanError("circularDependency", `Circular dependency detected: ${cycle.join(" → ")}`);
51
58
  }
52
59
 
53
60
  return stages;
@@ -172,7 +179,8 @@ export function resolveAdaptorHierarchy(
172
179
  if (!injectInfo.adaptor || injectInfo.adaptor === AgentToolsRole) continue;
173
180
  const depKey = classToKey.get(injectInfo.adaptor);
174
181
  if (!depKey) {
175
- throw new Error(
182
+ throw new InjectError(
183
+ "notRegistered",
176
184
  `Adaptor "${key}" has a plug dependency (property "${propKey}") ` +
177
185
  `on adaptor "${injectInfo.adaptor.refName}" which is not registered.`,
178
186
  );
@@ -185,7 +193,10 @@ export function resolveAdaptorHierarchy(
185
193
  } else if (injectInfo.type === "memory") {
186
194
  const depKey = classToKey.get(CacheAdaptorRole);
187
195
  if (!depKey) {
188
- throw new Error(`Adaptor "${key}" has a memory dependency but cache adaptor role is not registered.`);
196
+ throw new InjectError(
197
+ "notRegistered",
198
+ `Adaptor "${key}" has a memory dependency but cache adaptor role is not registered.`,
199
+ );
189
200
  }
190
201
  addDependency(depKey);
191
202
  }
@@ -1,4 +1,4 @@
1
- import { FIELD_META, INJECT_META } from "akanjs/base";
1
+ import { AkanError, FIELD_META, INJECT_META } from "akanjs/base";
2
2
  import { lowerlize, toError } from "akanjs/common";
3
3
  import { ConstantRegistry, type FieldObject } from "akanjs/constant";
4
4
  import type { InjectInfo } from "akanjs/service";
@@ -118,7 +118,10 @@ export const assertUniqueRegistrations = (kind: string, registrations: Registrat
118
118
  else claimed.set(`${scope}\0${key}`, owner);
119
119
  }
120
120
  if (!clashes.length) return;
121
- throw new Error(`[DI:${kind}] ${clashes.length} duplicate registration(s):\n${clashes.join("\n")}`);
121
+ throw new AkanError(
122
+ "duplicateRegistration",
123
+ `[DI:${kind}] ${clashes.length} duplicate registration(s):\n${clashes.join("\n")}`,
124
+ );
122
125
  };
123
126
 
124
127
  export const runStage = async (stageLabel: string, tasks: StageTask[]): Promise<void> => {
@@ -138,7 +141,8 @@ export const throwStageFailures = (
138
141
  if (failures.length === 0) return;
139
142
  const summary = failures.map((f) => ` • ${f.label}: ${reasonMessage(f.reason)}`).join("\n");
140
143
  const errors = failures.map((f) => toError(f.reason));
141
- throw new AggregateError(errors, `[DI:${stageLabel}] ${failures.length}/${total} task(s) failed:\n${summary}`);
144
+ const message = `[DI:${stageLabel}] ${failures.length}/${total} task(s) failed:\n${summary}`;
145
+ throw Object.assign(new AkanError("stageFailed", message), { errors });
142
146
  };
143
147
 
144
148
  export const reasonMessage = (reason: unknown): string => {