akanjs 3.3.0-rc.59 → 3.3.0-rc.60

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 (39) hide show
  1. package/client/appOpenedTab.ts +2 -1
  2. package/client/nativeHost.ts +2 -31
  3. package/client/nativeShell.ts +32 -0
  4. package/client/router.ts +2 -2
  5. package/constant/immerable.ts +2 -0
  6. package/constant/immerify.ts +1 -1
  7. package/constant/via.ts +1 -1
  8. package/package.json +1 -1
  9. package/server/akanApp.ts +7 -5
  10. package/server/akanServer.ts +87 -35
  11. package/server/devtools/devtoolsRouter.ts +27 -16
  12. package/server/gateway/childSupervisor.ts +8 -4
  13. package/server/gateway/gatewayChildren.ts +1 -0
  14. package/server/hmr/devBaseArtifact.ts +5 -1
  15. package/server/htmlResultCache.ts +7 -1
  16. package/server/lifecycle/parentChannel.ts +11 -4
  17. package/server/logging/serverLogging.ts +24 -10
  18. package/server/routing/devBuild.ts +4 -0
  19. package/server/routing/devSurfacePolicy.ts +2 -1
  20. package/server/routing/serverListener.ts +106 -55
  21. package/server/routing/webSurfaceHold.ts +117 -0
  22. package/server/scriptPolicy.ts +2 -2
  23. package/server/types.tsx +4 -2
  24. package/server/webRouteContext.ts +12 -3
  25. package/service/ipcTypes.ts +2 -0
  26. package/types/client/nativeHost.d.ts +1 -6
  27. package/types/client/nativeShell.d.ts +10 -0
  28. package/types/client/router.d.ts +1 -1
  29. package/types/constant/immerable.d.ts +1 -0
  30. package/types/server/gateway/gatewayChildren.d.ts +1 -0
  31. package/types/server/hmr/devBaseArtifact.d.ts +1 -0
  32. package/types/server/lifecycle/parentChannel.d.ts +2 -2
  33. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  34. package/types/server/logging/serverLogging.d.ts +1 -0
  35. package/types/server/routing/devBuild.d.ts +3 -0
  36. package/types/server/routing/serverListener.d.ts +3 -1
  37. package/types/server/routing/webSurfaceHold.d.ts +13 -0
  38. package/types/server/types.d.ts +4 -1
  39. package/types/service/ipcTypes.d.ts +2 -0
@@ -1,5 +1,6 @@
1
1
  import { Href } from "./href";
2
- import { isNativeShell } from "./nativeHost";
2
+
3
+ import { isNativeShell } from "./nativeShell";
3
4
 
4
5
  export const closeAppOpenedTab = (): boolean => {
5
6
  const win = globalThis.window;
@@ -1,36 +1,7 @@
1
- import type { Platform } from "../vendor/@akanjs/native/packages/core/src/index.ts";
2
1
  import { Logger } from "akanjs/common";
2
+ import { isNativeApp, shellPlatform } from "./nativeShell";
3
3
 
4
- type ShellPlatform = Exclude<Platform, "web">;
5
-
6
- const shellPlatforms = { macos: true, windows: true, linux: true, ios: true, android: true } satisfies Record<
7
- ShellPlatform,
8
- true
9
- >;
10
-
11
- const isShellPlatform = (value: unknown): value is ShellPlatform =>
12
- typeof value === "string" && Object.hasOwn(shellPlatforms, value);
13
-
14
- const shellPlatform = (): ShellPlatform | null => {
15
- const platform = (globalThis as { __AKAN_NATIVE__?: { platform?: unknown } }).__AKAN_NATIVE__?.platform;
16
- return isShellPlatform(platform) ? platform : null;
17
- };
18
-
19
- /** Inside an iOS or Android shell of the native runtime; a mobile target opened in a browser is not. */
20
- export const isNativeApp = () => nativePlatform() !== null;
21
-
22
- /** Inside any shell of the native runtime, desktop included. */
23
- export const isNativeShell = () => shellPlatform() !== null;
24
-
25
- export const nativePlatform = () => {
26
- const platform = shellPlatform();
27
- return platform === "ios" || platform === "android" ? platform : null;
28
- };
29
-
30
- export const desktopPlatform = () => {
31
- const platform = shellPlatform();
32
- return platform === "macos" || platform === "windows" || platform === "linux" ? platform : null;
33
- };
4
+ export { desktopPlatform, isNativeApp, isNativeShell, nativePlatform } from "./nativeShell";
34
5
 
35
6
  if (shellPlatform())
36
7
  import("./nativeBoot").catch((error: unknown) => {
@@ -0,0 +1,32 @@
1
+ import type { Platform } from "../vendor/@akanjs/native/packages/core/src/index.ts";
2
+
3
+ type ShellPlatform = Exclude<Platform, "web">;
4
+
5
+ const shellPlatforms = { macos: true, windows: true, linux: true, ios: true, android: true } satisfies Record<
6
+ ShellPlatform,
7
+ true
8
+ >;
9
+
10
+ const isShellPlatform = (value: unknown): value is ShellPlatform =>
11
+ typeof value === "string" && Object.hasOwn(shellPlatforms, value);
12
+
13
+ export const shellPlatform = (): ShellPlatform | null => {
14
+ const platform = (globalThis as { __AKAN_NATIVE__?: { platform?: unknown } }).__AKAN_NATIVE__?.platform;
15
+ return isShellPlatform(platform) ? platform : null;
16
+ };
17
+
18
+ /** Inside an iOS or Android shell of the native runtime; a mobile target opened in a browser is not. */
19
+ export const isNativeApp = () => nativePlatform() !== null;
20
+
21
+ /** Inside any shell of the native runtime, desktop included. */
22
+ export const isNativeShell = () => shellPlatform() !== null;
23
+
24
+ export const nativePlatform = () => {
25
+ const platform = shellPlatform();
26
+ return platform === "ios" || platform === "android" ? platform : null;
27
+ };
28
+
29
+ export const desktopPlatform = () => {
30
+ const platform = shellPlatform();
31
+ return platform === "macos" || platform === "windows" || platform === "linux" ? platform : null;
32
+ };
package/client/router.ts CHANGED
@@ -651,8 +651,8 @@ class Router {
651
651
  * than stacking it, and a visitor may have opened this address directly, so `back()` alone would leave the page.
652
652
  * Only the one entry under this one is looked at, and the rewrite keeps the scroll unless `scrollToTop` is set.
653
653
  */
654
- backTo(href: string, routeOptions?: RouteOptions) {
655
- if (getEnv().side === "server") throw new Error("backTo is only available in client side");
654
+ backOrReplace(href: string, routeOptions?: RouteOptions) {
655
+ if (getEnv().side === "server") throw new Error("backOrReplace is only available in client side");
656
656
  this.#checkInitialized();
657
657
 
658
658
  if (csrLocation.isLeaving()) return undefined as never;
@@ -0,0 +1,2 @@
1
+
2
+ export const immerable: unique symbol = Symbol.for("immer-draftable");
@@ -1,6 +1,6 @@
1
1
  import { FIELD_META } from "akanjs/base";
2
2
  import { plainFieldsOf } from "akanjs/common";
3
- import { immerable } from "immer";
3
+ import { immerable } from "./immerable";
4
4
  import type { ConstantModelRef } from "./via";
5
5
 
6
6
  export const immerify = <T extends object>(modelRef: ConstantModelRef, objOrArr: T): T => {
package/constant/via.ts CHANGED
@@ -12,7 +12,6 @@ import {
12
12
  SERVER_VALUE,
13
13
  } from "akanjs/base";
14
14
  import { applyMixins, plainFieldsOf } from "akanjs/common";
15
- import { immerable } from "immer";
16
15
  import { CascadePaths } from "./cascadePaths";
17
16
  import { ConstantRegistry } from "./constantRegistry";
18
17
  import { dateAccessorOf, isDateSlotField } from "./dateSlot";
@@ -30,6 +29,7 @@ import {
30
29
  import { FieldPlan } from "./fieldPlan";
31
30
  import { getDefault } from "./getDefault";
32
31
  import { HydrationPlan } from "./hydrationPlan";
32
+ import { immerable } from "./immerable";
33
33
  import { makePurify, type PurifiedModel, type PurifyFunc } from "./purify";
34
34
  import { TextFieldPaths } from "./textFieldPaths";
35
35
  import type { BaseInsight, BaseObject, ConstantType, DefaultOf, DefaultOfSchema, NonFunctionalKeys } from "./types";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.59",
3
+ "version": "3.3.0-rc.60",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/server/akanApp.ts CHANGED
@@ -285,11 +285,13 @@ export class AkanApp {
285
285
  if (!message || typeof message !== "object") return;
286
286
  switch (message.type) {
287
287
  case "ready":
288
-
289
- if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
290
- this.#routeHostsPending = false;
291
-
292
- delete process.env.AKAN_DEV_AWAIT_ARTIFACT;
288
+ if (!message.webPending) {
289
+
290
+ if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
291
+ this.#routeHostsPending = false;
292
+
293
+ delete process.env.AKAN_DEV_AWAIT_ARTIFACT;
294
+ }
293
295
  this.#supervisor.markReady(idx, message);
294
296
  return;
295
297
  case "pubsub.publish":
@@ -4,6 +4,7 @@ import { Logger } from "akanjs/common";
4
4
  import {
5
5
  type Adaptor,
6
6
  type AdaptorCls,
7
+ type AkanRscWorkerStatus,
7
8
  type DatabaseConfig,
8
9
  LiveRoomLimit,
9
10
  type Service,
@@ -30,6 +31,7 @@ import { SignalResolver } from "./resolver";
30
31
  import { BuiltinRoutes } from "./routing/builtinRoutes";
31
32
  import { RouteHosts } from "./routing/routeHosts";
32
33
  import { type AkanAppPrepared, ServerListener } from "./routing/serverListener";
34
+ import type { WebSurfaceHold } from "./routing/webSurfaceHold";
33
35
  import { ServerConfig } from "./serverConfig";
34
36
  import { ServerMetrics } from "./serverMetrics";
35
37
  import { SessionRefresh } from "./sessionRefresh";
@@ -128,6 +130,7 @@ export class AkanServer {
128
130
  status: "stopped" | "initializing" | "initialized" | "starting" | "running" | "stopping" = "stopped";
129
131
  #prepared: AkanAppPrepared | null = null;
130
132
  #webRouter: WebRouter | null = null;
133
+ #webHold: { hold: WebSurfaceHold; web: AkanWebConfig } | null = null;
131
134
  readonly logger: Logger;
132
135
  readonly name: string;
133
136
  readonly libs: AkanLib[];
@@ -223,7 +226,7 @@ export class AkanServer {
223
226
  const webRouter = () => this.#webRouter;
224
227
  this.#listener = new ServerListener(this, this.#di, solo);
225
228
  this.#metrics = new ServerMetrics(this, this.#listener, webRouter);
226
- this.#parent = new ParentChannel(this, this.#logging, webRouter);
229
+ this.#parent = new ParentChannel(this, this.#logging, webRouter, () => this.#rscWorkerStatus());
227
230
  this.#builtinRoutes = new BuiltinRoutes({
228
231
  owner: this,
229
232
  di: this.#di,
@@ -347,18 +350,26 @@ export class AkanServer {
347
350
  }
348
351
 
349
352
  async init(option: { routes?: boolean; web?: AkanWebOption } = {}) {
353
+ return await this.#initialize(option, false);
354
+ }
355
+
356
+ async #initialize(option: { routes?: boolean; web?: AkanWebOption }, listensBeforeWeb: boolean) {
350
357
  if (this.status !== "stopped")
351
358
  throw new AkanError("alreadyInitialized", "AkanServer is not able to init. It is already running.");
352
359
  ServerConfig.assertPrefixClearsBasePaths(this.prefix);
353
360
  const start = performance.now();
354
361
  this.#initTimings.clear();
355
- if (await this.#start.unwound(() => this.#start.stoppedDuring(() => this.#init(option)))) return this;
362
+ const init = () => this.#init(option, listensBeforeWeb);
363
+ if (await this.#start.unwound(() => this.#start.stoppedDuring(init))) return this;
356
364
  const stages = [...this.#di.initTimings, ...this.#initTimings].map(([stage, ms]) => `${stage} ${ms.toFixed(1)}`);
357
365
  this.logger.debug(`Initialized in ${(performance.now() - start).toFixed(1)}ms (${stages.join(" · ")})`);
358
366
  return this;
359
367
  }
360
368
 
361
- async #init({ routes: initRoutes = true, web }: { routes?: boolean; web?: AkanWebOption }) {
369
+ async #init(
370
+ { routes: initRoutes = true, web }: { routes?: boolean; web?: AkanWebOption },
371
+ listensBeforeWeb: boolean,
372
+ ) {
362
373
  this.status = "initializing";
363
374
  AgentTools.provide(this.#di, this);
364
375
  const { routes, wsRoutes, routeOptions } = await this.#di.initializeAll().catch((error: unknown) => {
@@ -372,32 +383,39 @@ export class AkanServer {
372
383
  this.status = "initialized";
373
384
  return this;
374
385
  }
375
- const artifactWaitMs = await DevBaseArtifact.arrived({ stopped: () => this.#start.stopHeld });
376
- if (this.#start.stopHeld) return this;
377
- if (artifactWaitMs > 0) this.#initTimings.set("artifact", artifactWaitMs);
378
- RouteHosts.declare();
379
386
  const requestedWeb = ServerConfig.narrowWeb(this.web, web);
380
- const noWeb = () => {
381
- this.#prepared = {
382
- routes,
383
- routeOptions,
384
- wsRoutes,
385
- builtinRoutes: this.#builtinRoutes.timed(null, this.#initTimings),
386
- renderEnvRoutes: {},
387
- hmrHub: null,
388
- webProxyRunner: null,
389
- };
387
+
388
+ if (listensBeforeWeb && DevBaseArtifact.awaited()) {
389
+ const { WebSurfaceHold } = await import("./routing/webSurfaceHold");
390
+ this.#webHold = { hold: new WebSurfaceHold(), web: requestedWeb };
391
+ this.#prepared = this.#apiOnly({ routes, wsRoutes, routeOptions }, {});
390
392
  this.status = "initialized";
391
393
  return this;
392
- };
394
+ }
395
+ const prepared = await this.#mountWeb({ routes, wsRoutes, routeOptions }, requestedWeb);
396
+ if (!prepared) return this;
397
+ this.#prepared = prepared;
398
+ this.status = "initialized";
399
+ return this;
400
+ }
401
+
402
+ #apiOnly(base: ApiSurface, builtinRoutes: AkanAppPrepared["builtinRoutes"]): AkanAppPrepared {
403
+ return { ...base, builtinRoutes, renderEnvRoutes: {}, hmrHub: null, webProxyRunner: null };
404
+ }
405
+
406
+ async #mountWeb(base: ApiSurface, requestedWeb: AkanWebConfig): Promise<AkanAppPrepared | null> {
407
+ const artifactWaitMs = await DevBaseArtifact.arrived({ stopped: () => this.#start.stopHeld });
408
+ if (this.#start.stopHeld) return null;
409
+ if (artifactWaitMs > 0) this.#initTimings.set("artifact", artifactWaitMs);
410
+ RouteHosts.declare();
393
411
  if (!requestedWeb.ssr) {
394
412
  this.web = requestedWeb;
395
413
  this.logger.debug("web off: serving api only (AKAN_SSR=false, or a build with `web: false`)");
396
- return noWeb();
414
+ return this.#apiOnly(base, this.#builtinRoutes.timed(null, this.#initTimings));
397
415
  }
398
416
  const webStart = performance.now();
399
417
  const { WebRouter } = await import("./webRouter");
400
- if (this.#start.stopHeld) return this;
418
+ if (this.#start.stopHeld) return null;
401
419
  const webRouter = await WebRouter.create({
402
420
  web: requestedWeb,
403
421
  upgradeHmrWs: (req, data) => this.#listener.upgradeHmrWs(req, data),
@@ -406,25 +424,20 @@ export class AkanServer {
406
424
  if (!webRouter) {
407
425
  this.web = { ssr: false, csr: false };
408
426
  this.logger.warn("web off: no build artifact under .akan/artifact; serving api only");
409
- return noWeb();
427
+ return this.#apiOnly(base, this.#builtinRoutes.timed(null, this.#initTimings));
410
428
  }
411
429
  this.#webRouter = webRouter;
412
430
  this.web = webRouter.web;
413
431
  this.logger.verbose(`web on: ssr=${this.web.ssr} csr=${this.web.csr}`);
414
432
  const { renderEnvRoutes, hmrHub } = await webRouter.initializeRoute();
415
433
  this.#initTimings.set("web", performance.now() - webStart);
416
- const webProxyRunner = WebProxyRunner.create(this.#di.webProxies);
417
- this.#prepared = {
418
- routes,
419
- routeOptions,
420
- wsRoutes,
434
+ return {
435
+ ...base,
421
436
  builtinRoutes: this.#builtinRoutes.timed(webRouter, this.#initTimings),
422
437
  renderEnvRoutes,
423
438
  hmrHub,
424
- webProxyRunner,
439
+ webProxyRunner: WebProxyRunner.create(this.#di.webProxies),
425
440
  };
426
- this.status = "initialized";
427
- return this;
428
441
  }
429
442
 
430
443
  async listen() {
@@ -440,11 +453,48 @@ export class AkanServer {
440
453
  async #listen(prepared: AkanAppPrepared) {
441
454
  if (await this.#start.stoppedDuring(() => this.#logging.startTransport(this.#webRouter))) return this;
442
455
  this.#logging.startFileLogging(this.serverMode);
443
- const { unix, port } = this.#listener.listen(prepared, this.#webRouter);
456
+ const { unix, port } = this.#listener.listen(prepared, this.#webRouter, this.#webHold?.hold ?? null);
444
457
  this.status = "running";
445
458
  this.#metrics.start();
446
459
  if (this.#schedules) this.#di.registerSchedule(this.serverMode);
447
460
  this.logger.verbose(`🚀 ${this.name} is running on ${unix ? `unix://${unix}` : `port ${port}`}`);
461
+ this.#sendReady(unix, port);
462
+ if (this.#webHold) {
463
+ if (await this.#start.stoppedDuring(() => this.#attachWeb())) return this;
464
+ this.#sendReady(unix, port);
465
+ }
466
+ if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
467
+ ShutdownManager.register(this.logger, () => this.stop());
468
+ return this;
469
+ }
470
+
471
+ async #attachWeb() {
472
+ const held = this.#webHold;
473
+ const base = this.#prepared;
474
+ if (!held || !base) return;
475
+ const start = performance.now();
476
+ this.#initTimings.clear();
477
+ try {
478
+ const prepared = await this.#mountWeb(base, held.web);
479
+ if (!prepared || this.#start.stopHeld) return;
480
+ this.#prepared = prepared;
481
+ this.#listener.attachWeb(prepared, this.#webRouter);
482
+ this.#logging.attachWeb(this.#webRouter);
483
+ held.hold.open();
484
+ } catch (error) {
485
+ held.hold.fail(error instanceof Error ? error.message : String(error));
486
+ throw error;
487
+ }
488
+ const stages = [...this.#initTimings].map(([stage, ms]) => `${stage} ${ms.toFixed(1)}`);
489
+ this.logger.debug(`Web surface attached in ${(performance.now() - start).toFixed(1)}ms (${stages.join(" · ")})`);
490
+ }
491
+
492
+ #rscWorkerStatus(): AkanRscWorkerStatus {
493
+ if (this.#webHold?.hold.pending) return "starting";
494
+ return this.#webRouter?.rscWorkerStatus ?? null;
495
+ }
496
+
497
+ #sendReady(unix: string | undefined, port: number | undefined) {
448
498
  const wsPort = this.#listener.wsPort;
449
499
  this.#parent.sendReady({
450
500
  type: "ready",
@@ -455,11 +505,9 @@ export class AkanServer {
455
505
  wsUpstream: typeof wsPort === "number" ? { type: "tcp", host: "127.0.0.1", port: wsPort } : undefined,
456
506
  healthPath: "/_akan/app/child-health",
457
507
  crossSite: CrossSiteGuard.option(),
458
- rscWorker: this.#webRouter?.rscWorkerStatus ?? null,
508
+ rscWorker: this.#rscWorkerStatus(),
509
+ ...(this.#webHold?.hold.pending ? { webPending: true } : {}),
459
510
  });
460
- if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
461
- ShutdownManager.register(this.logger, () => this.stop());
462
- return this;
463
511
  }
464
512
 
465
513
  /**
@@ -472,7 +520,7 @@ export class AkanServer {
472
520
  const shouldListen = (listen ?? !isNoListenCommand) && this.serverMode !== "batch";
473
521
 
474
522
  if (shouldListen || !isNoListenCommand) this.#parent.register();
475
- await this.init({ routes: shouldListen, web });
523
+ await this.#initialize({ routes: shouldListen, web }, shouldListen);
476
524
  if (this.#parent.gone || this.status !== "initialized") return this;
477
525
  if (shouldListen) return this.listen();
478
526
  return await this.#start.unwound(async () => {
@@ -513,6 +561,8 @@ export class AkanServer {
513
561
  this.status = "stopping";
514
562
  this.#metrics.stop();
515
563
  this.#di.getWebsocketAdaptor()?.clearEventHandler();
564
+ await this.#webHold?.hold.settle("the server stopped before the first base build finished");
565
+ this.#webHold = null;
516
566
  this.#listener.close();
517
567
 
518
568
  this.#webRouter?.dispose();
@@ -534,6 +584,8 @@ export class AkanServer {
534
584
  }
535
585
  }
536
586
 
587
+ type ApiSurface = Pick<AkanAppPrepared, "routes" | "routeOptions" | "wsRoutes">;
588
+
537
589
  const assertCanGet = (status: AkanServer["status"], type = "Dependency", refName?: string) => {
538
590
  if (status === "initialized" || status === "running") return;
539
591
  const target = refName ? `${type} "${refName}"` : type;
@@ -10,7 +10,7 @@ import { ConstantSerializer } from "./constantSerializer";
10
10
  import { DepsSerializer } from "./depsSerializer";
11
11
  import { DevtoolsAccess } from "./devtoolsAccess";
12
12
  import { SignalSerializer } from "./signalSerializer";
13
- import { StudioRoute } from "./studio/studioRoute";
13
+ import type { StudioRoute } from "./studio/studioRoute";
14
14
  import type { DepsData, DevtoolsApp, DevtoolsEnvelope, DevtoolsIndex, DictionaryData, SignalData } from "./types";
15
15
 
16
16
  export interface DevtoolsRouterContext {
@@ -60,23 +60,12 @@ export class DevtoolsRouter {
60
60
  const closedReason = DevtoolsAccess.closedReason(env);
61
61
  if (closedReason) DevtoolsRouter.logger.warn(closedReason);
62
62
  if (!DevtoolsRouter.isEnabled(env)) return {};
63
- const studio = new StudioRoute({
64
- basePath: `${DevtoolsRouter.basePath}/studio`,
65
- appName: this.#context.env.appName,
66
- web: this.#context.web ?? true,
67
- buildGraph: this.#context.buildGraph ?? null,
68
- buildChanges: this.#context.buildChanges ?? null,
69
- buildFramework: this.#context.buildFramework ?? null,
70
- runtime: () => ({
71
- app: this.#app(),
72
- deps: DevtoolsRouter.#attempt("studio runtime (deps)", () => this.#deps()),
73
- signal: DevtoolsRouter.#attempt("studio runtime (signal)", () => this.#signal()),
74
- }),
75
- });
76
63
  return DevRoutes.mount(
77
64
  {
78
- [`${DevtoolsRouter.basePath}/studio`]: { GET: (req: Request) => studio.page(req) },
79
- [`${DevtoolsRouter.basePath}/studio/graph`]: { GET: (req: Request) => studio.graph(req) },
65
+ [`${DevtoolsRouter.basePath}/studio`]: { GET: async (req: Request) => (await this.#studio()).page(req) },
66
+ [`${DevtoolsRouter.basePath}/studio/graph`]: {
67
+ GET: async (req: Request) => (await this.#studio()).graph(req),
68
+ },
80
69
  [`${DevtoolsRouter.basePath}/devtools`]: { GET: () => DevtoolsRouter.#json(this.#index()) },
81
70
  [`${DevtoolsRouter.basePath}/constant`]: {
82
71
  GET: () => this.#respond("constant", () => ConstantSerializer.serialize()),
@@ -98,6 +87,28 @@ export class DevtoolsRouter {
98
87
  );
99
88
  }
100
89
 
90
+ #studioRoute: Promise<StudioRoute> | null = null;
91
+
92
+ #studio(): Promise<StudioRoute> {
93
+ this.#studioRoute ??= import("./studio/studioRoute").then(
94
+ ({ StudioRoute }) =>
95
+ new StudioRoute({
96
+ basePath: `${DevtoolsRouter.basePath}/studio`,
97
+ appName: this.#context.env.appName,
98
+ web: this.#context.web ?? true,
99
+ buildGraph: this.#context.buildGraph ?? null,
100
+ buildChanges: this.#context.buildChanges ?? null,
101
+ buildFramework: this.#context.buildFramework ?? null,
102
+ runtime: () => ({
103
+ app: this.#app(),
104
+ deps: DevtoolsRouter.#attempt("studio runtime (deps)", () => this.#deps()),
105
+ signal: DevtoolsRouter.#attempt("studio runtime (signal)", () => this.#signal()),
106
+ }),
107
+ }),
108
+ );
109
+ return this.#studioRoute;
110
+ }
111
+
101
112
  #signal(): SignalData {
102
113
  const { di, serverMode, prefix, websocketPrefix } = this.#context;
103
114
  return SignalSerializer.serialize({ di, serverMode, prefix, websocketPrefix });
@@ -247,22 +247,26 @@ export class ChildSupervisor {
247
247
  child.wsUpstream = message.wsUpstream;
248
248
  child.healthPath = message.healthPath;
249
249
  child.rscWorker = message.rscWorker;
250
+ child.webPending = message.webPending === true;
250
251
  if (message.crossSite) CrossSiteGuard.configure(message.crossSite);
251
252
  child.lastPongAtMono = performance.now();
252
- child.restart.reset();
253
+
254
+ if (!child.webPending) child.restart.reset();
253
255
 
254
256
  const hub = this.#logging.hub;
255
257
  if (hub && hub.floor !== null) this.#children.send(child, { type: "log.level", minSev: hub.floor });
256
258
  child.restartPending = false;
257
- child.lastErrorMessage = undefined;
259
+ if (!child.webPending) child.lastErrorMessage = undefined;
258
260
  this.#children.invalidateFederation();
259
261
 
260
262
  const trafficChildren = [...this.#children.values()].filter((item) => item.role !== "batch");
261
263
 
262
- if (!this.#children.stopping && child.role !== "batch" && trafficChildren.every((item) => item.ready)) {
264
+ const settled = (item: ChildState) => item.ready && !item.webPending;
265
+
266
+ if (!this.#children.stopping && child.role !== "batch" && trafficChildren.every(settled)) {
263
267
  process.send?.({ type: "backend-ready", pid: process.pid } satisfies BuilderMessage);
264
268
  }
265
- if ([...this.#children.values()].every((item) => item.ready)) {
269
+ if (!child.webPending && [...this.#children.values()].every((item) => item.ready)) {
266
270
  this.#logger.verbose(`All ${this.#children.size} child process(es) are ready`);
267
271
  }
268
272
  }
@@ -23,6 +23,7 @@ export interface ChildState {
23
23
  healthPath?: string;
24
24
 
25
25
  rscWorker?: AkanRscWorkerStatus;
26
+ webPending?: boolean;
26
27
  metrics: AkanMetricsReport;
27
28
  /** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
28
29
  lastPongAtMono?: number;
@@ -6,6 +6,10 @@ import { resolveArtifactDir } from "../proxy/hostBasePathWebProxy";
6
6
  export class DevBaseArtifact {
7
7
  static readonly #pollMs = 20;
8
8
 
9
+ static awaited(env: Record<string, string | undefined> = process.env) {
10
+ return env.AKAN_DEV_AWAIT_ARTIFACT === "1";
11
+ }
12
+
9
13
  static async arrived({
10
14
  artifactDir = resolveArtifactDir(),
11
15
  env = process.env,
@@ -19,7 +23,7 @@ export class DevBaseArtifact {
19
23
  warnAfterMs?: number;
20
24
  warn?: (message: string) => void;
21
25
  } = {}): Promise<number> {
22
- if (env.AKAN_DEV_AWAIT_ARTIFACT !== "1") return 0;
26
+ if (!DevBaseArtifact.awaited(env)) return 0;
23
27
  const file = path.join(artifactDir, "base-artifact.json");
24
28
  const started = performance.now();
25
29
  let warned = false;
@@ -34,6 +34,8 @@ const HELD_SKIP_REASONS = [
34
34
  "body-too-large",
35
35
  ];
36
36
 
37
+ const NOT_FOUND_SKIP_HOLD_SECONDS = 60;
38
+
37
39
  interface HtmlCacheStreamOptions {
38
40
  shouldCache?: () => boolean | Promise<boolean>;
39
41
  maxBodyBytes?: number | null;
@@ -294,7 +296,11 @@ export class HtmlResultCache {
294
296
  onSkip: (reason) => {
295
297
  const why = reason === "store-skip" ? skipReason : reason;
296
298
  if (HELD_SKIP_REASONS.includes(why))
297
- this.#skips.set(htmlStoreKey, { reason: why, ...htmlCacheMetadata }, entry.ttl);
299
+ this.#skips.set(
300
+ htmlStoreKey,
301
+ { reason: why, ...htmlCacheMetadata },
302
+ why === "render-not-found" ? Math.min(entry.ttl, NOT_FOUND_SKIP_HOLD_SECONDS) : entry.ttl,
303
+ );
298
304
  logger.verbose(`html cache store skipped pathname=${pathname} reason=${why}`);
299
305
  },
300
306
  },
@@ -1,5 +1,5 @@
1
1
  import type { Logger } from "akanjs/common";
2
- import type { AkanIpcMessage } from "akanjs/service";
2
+ import type { AkanIpcMessage, AkanRscWorkerStatus } from "akanjs/service";
3
3
  import type { AkanServer } from "../akanServer";
4
4
  import type { ServerLogging } from "../logging/serverLogging";
5
5
  import type { WebRouter } from "../webRouter";
@@ -10,16 +10,23 @@ type ParentChannelOwner = Pick<AkanServer, "logger" | "shutdownTimeoutMs" | "sto
10
10
  export class ParentChannel {
11
11
  readonly #owner: ParentChannelOwner;
12
12
  readonly #logger: Logger;
13
- readonly #logging: ServerLogging;
13
+ readonly #logging: Pick<ServerLogging, "setMinSev">;
14
14
  readonly #webRouter: () => WebRouter | null;
15
+ readonly #rscWorker: () => AkanRscWorkerStatus;
15
16
  #parentGone: boolean = false;
16
17
  #orphanExiting = false;
17
18
 
18
- constructor(owner: ParentChannelOwner, logging: ServerLogging, webRouter: () => WebRouter | null) {
19
+ constructor(
20
+ owner: ParentChannelOwner,
21
+ logging: Pick<ServerLogging, "setMinSev">,
22
+ webRouter: () => WebRouter | null,
23
+ rscWorker: () => AkanRscWorkerStatus = () => webRouter()?.rscWorkerStatus ?? null,
24
+ ) {
19
25
  this.#owner = owner;
20
26
  this.#logger = owner.logger;
21
27
  this.#logging = logging;
22
28
  this.#webRouter = webRouter;
29
+ this.#rscWorker = rscWorker;
23
30
  }
24
31
 
25
32
  get gone() {
@@ -64,7 +71,7 @@ export class ParentChannel {
64
71
  nonce: message.nonce,
65
72
  sentAt: message.sentAt,
66
73
  pid: process.pid,
67
- rscWorker: this.#webRouter()?.rscWorkerStatus ?? null,
74
+ rscWorker: this.#rscWorker(),
68
75
  } satisfies AkanIpcMessage);
69
76
  else if (message.type === "log.level") {
70
77
  this.#logging.setMinSev(message.minSev);
@@ -17,6 +17,7 @@ export class ServerLogging {
17
17
  #logControl: LogControlSocket | null = null;
18
18
  #logForwarder: LogForwarder | null = null;
19
19
  #logStream: LogStreamRoute | null = null;
20
+ #minSev: number | null | undefined;
20
21
 
21
22
  constructor(solo: boolean, logger: Logger) {
22
23
  this.#solo = solo;
@@ -29,27 +30,40 @@ export class ServerLogging {
29
30
  }
30
31
 
31
32
  setMinSev(minSev: number | null) {
33
+ this.#minSev = minSev;
32
34
  this.#logForwarder?.setMinSev(minSev);
33
35
  }
34
36
 
35
37
  async startTransport(webRouter: WebRouter | null = null) {
36
38
  if (this.#logHub || this.#logForwarder) return;
37
39
  if (this.#solo) {
38
- const hub = LogHub.attach();
39
- this.#logHub = hub;
40
- hub.onFloorChange((minSev) => webRouter?.setLogLevel(minSev));
41
- webRouter?.onLogRecords((records, dropped) => {
40
+ this.#logHub = LogHub.attach();
41
+ this.attachWeb(webRouter);
42
+ this.#logControl = await LogControlSocket.open(this.#logHub, resolveRuntimeDir(), this.#logger);
43
+ return;
44
+ }
45
+
46
+ if (Logger.isNdjson) Logger.consoleOutput = false;
47
+ this.#logForwarder = new LogForwarder((message, onSent) => process.send?.(message, undefined, undefined, onSent));
48
+ this.attachWeb(webRouter);
49
+ }
50
+
51
+ attachWeb(webRouter: WebRouter | null) {
52
+ if (!webRouter) return;
53
+ const hub = this.#logHub;
54
+ if (hub) {
55
+ hub.onFloorChange((minSev) => webRouter.setLogLevel(minSev));
56
+ if (hub.floor !== null) webRouter.setLogLevel(hub.floor);
57
+ webRouter.onLogRecords((records, dropped) => {
42
58
  hub.ingestMany(records);
43
59
  if (dropped) this.#logger.warn(`RSC worker dropped ${dropped} log records (ipc backpressure)`);
44
60
  });
45
- this.#logControl = await LogControlSocket.open(hub, resolveRuntimeDir(), this.#logger);
46
61
  return;
47
62
  }
48
-
49
- if (Logger.isNdjson) Logger.consoleOutput = false;
50
- const forwarder = new LogForwarder((message, onSent) => process.send?.(message, undefined, undefined, onSent));
51
- this.#logForwarder = forwarder;
52
- webRouter?.onLogRecords((records) => forwarder.pushMany(records));
63
+ const forwarder = this.#logForwarder;
64
+ if (!forwarder) return;
65
+ if (this.#minSev !== undefined) webRouter.setLogLevel(this.#minSev);
66
+ webRouter.onLogRecords((records) => forwarder.pushMany(records));
53
67
  }
54
68
 
55
69
  startFileLogging(role: string) {
@@ -0,0 +1,4 @@
1
+ type Env = Record<string, string | undefined>;
2
+
3
+ export const isDevBuild = (env: Env = process.env): boolean =>
4
+ env.NODE_ENV !== "production" || env.AKAN_COMMAND_TYPE === "start";
@@ -1,5 +1,6 @@
1
1
  import { AkanError } from "akanjs/base";
2
2
  import { DevtoolsAccess, type DevtoolsEnv } from "../devtools/devtoolsAccess";
3
+ import { isDevBuild } from "./devBuild";
3
4
  import { type DevSurface, DevSurfaces } from "./devSurfaces";
4
5
 
5
6
  type Env = Record<string, string | undefined>;
@@ -8,7 +9,7 @@ export class DevSurfacePolicy {
8
9
  static readonly #mounted = new WeakSet<object>();
9
10
 
10
11
  static isDevBuild(env: Env = process.env): boolean {
11
- return env.NODE_ENV !== "production" || env.AKAN_COMMAND_TYPE === "start";
12
+ return isDevBuild(env);
12
13
  }
13
14
 
14
15
  static opens(surface: DevSurface, env: DevtoolsEnv = {}): boolean {
@@ -18,6 +18,7 @@ import { HostAllowlist } from "./hostAllowlist";
18
18
  import { localRoomsOf } from "./localRooms";
19
19
  import { RoomReplay } from "./roomReplay";
20
20
  import { ServerLimits } from "./serverLimits";
21
+ import type { WebSurfaceHold } from "./webSurfaceHold";
21
22
 
22
23
  export interface AkanAppPrepared {
23
24
  routes: SignalRoutes["routes"];
@@ -31,7 +32,14 @@ export interface AkanAppPrepared {
31
32
 
32
33
  type ListenerOwner = Pick<AkanServer, "name" | "logger" | "prefix" | "websocketPrefix">;
33
34
  type AppServer = Bun.Server<AppWsData | HmrWsData>;
34
- type BuildRoutes = (upgradeAppWs: ApiRouteInputs["upgradeAppWs"], allowlist: HostAllowlist | null) => NonNullHttpRoutes;
35
+
36
+ interface ListenSite {
37
+ unix: string | undefined;
38
+ limits: ServerLimits;
39
+ hostAllowlist: HostAllowlist | null;
40
+ idleTimeout: number;
41
+ hold: WebSurfaceHold | null;
42
+ }
35
43
 
36
44
  export class ServerListener {
37
45
  readonly #owner: ListenerOwner;
@@ -44,6 +52,8 @@ export class ServerListener {
44
52
  #localPublish: LocalPublish | null = null;
45
53
  #roomReplay: RoomReplay | null = null;
46
54
  #websocket: WebsocketAdaptor | null = null;
55
+ #site: ListenSite | null = null;
56
+ #attached: { main: NonNullHttpRoutes; ws: NonNullHttpRoutes | null } | null = null;
47
57
 
48
58
  constructor(owner: ListenerOwner, di: DiLifecycle, solo: boolean) {
49
59
  this.#owner = owner;
@@ -87,95 +97,127 @@ export class ServerListener {
87
97
  this.#localPublish?.(roomId, data);
88
98
  }
89
99
 
90
- listen(prepared: AkanAppPrepared, webRouter: WebRouter | null) {
100
+ listen(prepared: AkanAppPrepared, webRouter: WebRouter | null, hold: WebSurfaceHold | null = null) {
91
101
  const port = process.env.AKAN_CHILD_SOCKET
92
102
  ? undefined
93
103
  : Number(process.env.AKAN_CHILD_WS_PORT || process.env.PORT || 8282);
94
104
  const unix = process.env.AKAN_CHILD_SOCKET || undefined;
95
105
  this.#logger.verbose(`${this.#owner.name} is serving on ${unix ? `unix://${unix}` : `port ${port}`}`);
96
- const { routes, routeOptions, wsRoutes, builtinRoutes, renderEnvRoutes, hmrHub, webProxyRunner } = prepared;
97
106
  const limits = new ServerLimits();
98
- const websocketHandlers = {
99
- ...ApiRouter.buildWebsocketHandlers({
100
- wsRoutes,
101
- registry: this.#di.registry,
102
- live: this.#di.live,
103
- hmrHub,
104
- hmrState: webRouter
105
- ? {
106
- state: webRouter.renderState,
107
- refresh: () => webRouter.refreshHmrState(),
108
- errors: () => webRouter.hmrBuildErrors(),
109
- }
110
- : null,
111
- logger: this.#logger,
112
- onDrain: () => this.#binaryPubsub.flush(),
113
- }),
114
- idleTimeout: limits.wsIdleTimeout,
115
- data: {},
116
- } as Bun.WebSocketHandler<AppWsData | HmrWsData>;
117
-
118
- const hostAllowlist = unix ? null : HostAllowlist.fromEnv();
107
+ const site: ListenSite = {
108
+ unix,
109
+ limits,
110
+
111
+ hostAllowlist: unix ? null : HostAllowlist.fromEnv(),
112
+
113
+ idleTimeout: unix ? 0 : limits.idleTimeout,
114
+ hold,
115
+ };
116
+ this.#site = site;
117
+ const websocket = this.#websocketHandlers(prepared, webRouter, limits);
119
118
  const hostname = ServerLimits.listenHostname();
120
-
121
- const idleTimeout = unix ? 0 : limits.idleTimeout;
122
- const buildRoutes: BuildRoutes = (upgradeAppWs, allowlist) =>
123
- ApiRouter.buildRoutes({
124
- prefix: this.#owner.prefix,
125
- websocketPrefix: this.#owner.websocketPrefix,
126
- routes,
127
- builtinRoutes,
128
- routeOptions,
129
- renderEnvRoutes,
130
- upgradeAppWs,
131
- webProxyRunner,
132
- hostAllowlist: allowlist,
133
- bodyLimits: limits,
134
- countChunkedBodies: !unix,
135
- idleTimeout,
136
- });
137
119
  const serve = () =>
138
120
  Bun.serve({
139
- idleTimeout,
121
+ idleTimeout: site.idleTimeout,
140
122
  maxRequestBodySize: limits.uploadBodyBytes,
141
123
  ...(unix ? { unix } : { port, hostname }),
142
- routes: buildRoutes((req, data) => this.#server?.upgrade(req, { data }) ?? false, hostAllowlist),
143
- websocket: websocketHandlers,
124
+ routes: this.#routeTable(site, prepared, "main"),
125
+ websocket,
144
126
  } as Parameters<typeof Bun.serve>[0]);
145
127
  this.#server = unix ? ServerLimits.serveOwnerOnly(unix, serve) : serve();
146
- if (unix && process.env.AKAN_CHILD_WS_PORT) this.#serveWsFallback(buildRoutes, websocketHandlers);
128
+ if (unix && process.env.AKAN_CHILD_WS_PORT) this.#serveWsFallback(site, prepared, websocket);
147
129
 
148
130
  const server = this.#server;
149
131
  const wsServer = this.#wsServer;
150
132
 
151
133
  SignalContext.setHttpPeerResolver((req) => server?.requestIP(req as Bun.BunRequest) ?? (unix ? null : undefined));
152
- hmrHub?.setPublisher((topic, payload) => {
153
- server?.publish(topic, payload);
154
- wsServer?.publish(topic, payload);
155
- });
134
+ this.#publishHmr(prepared.hmrHub);
156
135
  this.#bindLocalPublish(server, wsServer);
157
136
  return { unix, port };
158
137
  }
159
138
 
139
+ attachWeb(prepared: AkanAppPrepared, webRouter: WebRouter | null) {
140
+ const held = this.#site;
141
+ if (!held) return;
142
+ const site: ListenSite = { ...held, hold: null };
143
+ this.#site = site;
144
+ const websocket = this.#websocketHandlers(prepared, webRouter, site.limits);
145
+ const main = this.#routeTable(site, prepared, "main");
146
+ const ws = this.#wsServer ? this.#routeTable(site, prepared, "ws") : null;
147
+ this.#attached = { main, ws };
148
+ this.#server?.reload({ routes: main, websocket } as Parameters<AppServer["reload"]>[0]);
149
+ if (ws) this.#wsServer?.reload({ routes: ws, websocket } as Parameters<AppServer["reload"]>[0]);
150
+ this.#publishHmr(prepared.hmrHub);
151
+ }
152
+
160
153
  close() {
161
154
  this.#server?.stop(true);
162
155
  this.#wsServer?.stop(true);
163
156
  this.#server = null;
164
157
  this.#wsServer = null;
158
+ this.#site = null;
159
+ this.#attached = null;
165
160
  SignalContext.setHttpPeerResolver(null);
166
161
  }
167
162
 
168
- #serveWsFallback(buildRoutes: BuildRoutes, websocketHandlers: Bun.WebSocketHandler<AppWsData | HmrWsData>) {
169
- const preferredWsPort = Number(process.env.AKAN_CHILD_WS_PORT);
163
+ #websocketHandlers(prepared: AkanAppPrepared, webRouter: WebRouter | null, limits: ServerLimits) {
164
+ return {
165
+ ...ApiRouter.buildWebsocketHandlers({
166
+ wsRoutes: prepared.wsRoutes,
167
+ registry: this.#di.registry,
168
+ live: this.#di.live,
169
+ hmrHub: prepared.hmrHub,
170
+ hmrState: webRouter
171
+ ? {
172
+ state: webRouter.renderState,
173
+ refresh: () => webRouter.refreshHmrState(),
174
+ errors: () => webRouter.hmrBuildErrors(),
175
+ }
176
+ : null,
177
+ logger: this.#logger,
178
+ onDrain: () => this.#binaryPubsub.flush(),
179
+ }),
180
+ idleTimeout: limits.wsIdleTimeout,
181
+ data: {},
182
+ } as Bun.WebSocketHandler<AppWsData | HmrWsData>;
183
+ }
184
+
185
+ #routeTable(site: ListenSite, prepared: AkanAppPrepared, kind: "main" | "ws"): NonNullHttpRoutes {
170
186
 
187
+ const allowlist = kind === "main" ? site.hostAllowlist : new HostAllowlist([AKAN_CHILD_HOST]);
188
+ const upgradeAppWs: ApiRouteInputs["upgradeAppWs"] = (req, data) =>
189
+ (kind === "main" ? this.#server : this.#wsServer)?.upgrade(req, { data }) ?? false;
190
+ const { hold } = site;
191
+ const routes = ApiRouter.buildRoutes({
192
+ prefix: this.#owner.prefix,
193
+ websocketPrefix: this.#owner.websocketPrefix,
194
+ routes: prepared.routes,
195
+ builtinRoutes: prepared.builtinRoutes,
196
+ routeOptions: prepared.routeOptions,
197
+ renderEnvRoutes: prepared.renderEnvRoutes,
198
+ upgradeAppWs,
199
+ webProxyRunner: prepared.webProxyRunner,
200
+ hostAllowlist: hold ? null : allowlist,
201
+ bodyLimits: site.limits,
202
+ countChunkedBodies: !site.unix,
203
+ idleTimeout: site.idleTimeout,
204
+ });
205
+ if (!hold) return routes;
206
+ const held = hold.route(() => this.#attached?.[kind] ?? null);
207
+ return hold.guard({ ...routes, "/*": held } as NonNullHttpRoutes, allowlist, held);
208
+ }
209
+
210
+ #serveWsFallback(
211
+ site: ListenSite,
212
+ prepared: AkanAppPrepared,
213
+ websocketHandlers: Bun.WebSocketHandler<AppWsData | HmrWsData>,
214
+ ) {
215
+ const preferredWsPort = Number(process.env.AKAN_CHILD_WS_PORT);
171
216
  const wsServeOptions = (port: number) => ({
172
217
  idleTimeout: 0,
173
218
  port,
174
219
  hostname: "127.0.0.1",
175
- routes: buildRoutes(
176
- (req, data) => this.#wsServer?.upgrade(req, { data }) ?? false,
177
- new HostAllowlist([AKAN_CHILD_HOST]),
178
- ),
220
+ routes: this.#routeTable(site, prepared, "ws"),
179
221
  websocket: websocketHandlers,
180
222
  });
181
223
  try {
@@ -189,6 +231,15 @@ export class ServerListener {
189
231
  this.#logger.verbose(`${this.#owner.name} websocket fallback is serving on port ${this.#wsServer.port}`);
190
232
  }
191
233
 
234
+ #publishHmr(hmrHub: HmrWsHub | null) {
235
+ const server = this.#server;
236
+ const wsServer = this.#wsServer;
237
+ hmrHub?.setPublisher((topic, payload) => {
238
+ server?.publish(topic, payload);
239
+ wsServer?.publish(topic, payload);
240
+ });
241
+ }
242
+
192
243
  #bindLocalPublish(server: AppServer | null, wsServer: AppServer | null) {
193
244
  const websocket = this.#di.getWebsocketAdaptor();
194
245
  if (!websocket) throw new AkanError("invalidConfig", "WebSocket Redis adaptor is not registered");
@@ -0,0 +1,117 @@
1
+ import { GatewayStatusPage } from "../gateway/gatewayStatusPage";
2
+ import type { NonNullHttpRoutes } from "./apiRouter";
3
+ import type { HostAllowlist } from "./hostAllowlist";
4
+
5
+ type RouteValue = NonNullHttpRoutes[keyof NonNullHttpRoutes];
6
+ export type HoldHandler = (
7
+ req: Request,
8
+ server: Bun.Server<unknown>,
9
+ ) => Response | Promise<Response | undefined> | undefined;
10
+
11
+ export class WebSurfaceHold {
12
+ readonly #arrival = Promise.withResolvers<void>();
13
+ #pending = true;
14
+ #failure: string | null = null;
15
+
16
+ get pending() {
17
+ return this.#pending;
18
+ }
19
+
20
+ open() {
21
+ if (!this.#pending) return;
22
+ this.#pending = false;
23
+ this.#arrival.resolve();
24
+ }
25
+
26
+ fail(reason: string) {
27
+ if (!this.#pending) return;
28
+ this.#pending = false;
29
+ this.#failure = reason;
30
+ this.#arrival.resolve();
31
+ }
32
+
33
+ async settle(reason: string) {
34
+ this.fail(reason);
35
+ await this.#arrival.promise;
36
+ await new Promise<void>((resolve) => setImmediate(resolve));
37
+ }
38
+
39
+ route(table: () => NonNullHttpRoutes | null): HoldHandler {
40
+ return async (req, server) => {
41
+ await this.#arrival.promise;
42
+ const routes = table();
43
+ if (this.#failure !== null || !routes) return this.#unavailable(req);
44
+ return await WebSurfaceHold.dispatch(routes, req, server);
45
+ };
46
+ }
47
+
48
+ guard(routes: NonNullHttpRoutes, allowlist: HostAllowlist | null, held: HoldHandler): NonNullHttpRoutes {
49
+ if (!allowlist) return routes;
50
+ const guarded =
51
+ (handler: HoldHandler): HoldHandler =>
52
+ (req, server) => {
53
+ if (allowlist.allows(req)) return handler(req, server);
54
+ return this.#pending ? held(req, server) : allowlist.refuse();
55
+ };
56
+ return Object.fromEntries(
57
+ Object.entries(routes).map(([path, route]) => [path, WebSurfaceHold.#mapRoute(route, guarded)]),
58
+ ) as NonNullHttpRoutes;
59
+ }
60
+
61
+ static dispatch(routes: NonNullHttpRoutes, req: Request, server: Bun.Server<unknown>) {
62
+ const { pathname } = new URL(req.url);
63
+ const wildcards = Object.keys(routes)
64
+ .filter((key) => key.endsWith("*") && pathname.startsWith(key.slice(0, -1)))
65
+ .sort((a, b) => b.length - a.length);
66
+ const candidates = Object.hasOwn(routes, pathname) ? [pathname, ...wildcards] : wildcards;
67
+ for (const key of candidates) {
68
+ const handler = WebSurfaceHold.#handlerOf(routes[key as keyof NonNullHttpRoutes], req.method);
69
+ if (handler) return handler(req, server);
70
+ }
71
+ return new Response("Not Found", { status: 404 });
72
+ }
73
+
74
+ static #handlerOf(route: RouteValue, method: string): HoldHandler | null {
75
+ if (route instanceof Response) return () => route.clone();
76
+ if (typeof route === "function") return route as HoldHandler;
77
+ if (!route || typeof route !== "object") return null;
78
+ const handler = (route as Record<string, unknown>)[method];
79
+ if (handler instanceof Response) return () => handler.clone();
80
+ return typeof handler === "function" ? (handler as HoldHandler) : null;
81
+ }
82
+
83
+ static #mapRoute(route: RouteValue, wrap: (handler: HoldHandler) => HoldHandler): RouteValue {
84
+ if (route instanceof Response) return wrap(() => route.clone()) as RouteValue;
85
+ if (typeof route === "function") return wrap(route as HoldHandler) as RouteValue;
86
+ if (!route || typeof route !== "object") return route;
87
+ return Object.fromEntries(
88
+ Object.entries(route).map(([method, handler]) => [
89
+ method,
90
+ handler instanceof Response
91
+ ? wrap(() => handler.clone())
92
+ : typeof handler === "function"
93
+ ? wrap(handler as HoldHandler)
94
+ : handler,
95
+ ]),
96
+ ) as RouteValue;
97
+ }
98
+
99
+ #unavailable(req: Request) {
100
+ const detail = `The web surface did not start: ${this.#failure ?? "the server stopped"}`;
101
+ if (req.headers.get("accept")?.includes("text/html"))
102
+ return new Response(
103
+ GatewayStatusPage.html({
104
+ heading: "Web surface did not start",
105
+ detail,
106
+ note: "The first base build did not finish here — this page reloads itself as soon as a server answers.",
107
+ }),
108
+ { status: 503, headers: GatewayStatusPage.headers("text/html; charset=utf-8") },
109
+ );
110
+ const headers = { "cache-control": "no-store" };
111
+ if (!req.headers.get("accept")?.includes("application/json")) return new Response(detail, { status: 503, headers });
112
+ return Response.json(
113
+ { error: "base.error.serverUnavailable", statusCode: 503, data: { status: 503 }, details: detail },
114
+ { status: 503, headers },
115
+ );
116
+ }
117
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
- import { DevSurfacePolicy } from "./routing/devSurfacePolicy";
2
+ import { isDevBuild } from "./routing/devBuild";
3
3
 
4
4
  export const SCRIPT_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only";
5
5
  export const SCRIPT_POLICY_REPORT_GROUP = "akan-csp";
@@ -110,7 +110,7 @@ export class ScriptPolicy {
110
110
  const extra = ScriptPolicy.extraSources(env.AKAN_CONTENT_SECURITY_POLICY_SCRIPT_SRC?.trim());
111
111
  const named = new Set([...(nonce ? [`'nonce-${nonce}'`] : []), ...hashes, ...extra]);
112
112
  const sources = ["'self'", ...named, "'strict-dynamic'"];
113
- if (DevSurfacePolicy.isDevBuild(env)) sources.push("'unsafe-eval'");
113
+ if (isDevBuild(env)) sources.push("'unsafe-eval'");
114
114
  const reportUri = ScriptPolicy.reportUri(env.AKAN_CONTENT_SECURITY_POLICY_REPORT_URI?.trim());
115
115
  const report = reportUri ? `; report-uri ${reportUri}; report-to ${SCRIPT_POLICY_REPORT_GROUP}` : "";
116
116
  return `script-src ${sources.join(" ")}${report}`;
package/server/types.tsx CHANGED
@@ -167,10 +167,12 @@ export interface CssAsset {
167
167
  export interface DictAsset {
168
168
  url: string;
169
169
  relPath: string;
170
+ /** What a browser downloads of the page file: its brotli sidecar's size, or the file's own when that is no smaller. */
171
+ bytes?: number;
170
172
  /** The files this locale's dictionary left out, by name, loaded where a page shows them. */
171
173
  parts?: Record<string, { url: string; relPath: string }>;
172
- /** The page file cut into the files routes load; `table` names each group's file. */
173
- routeParts?: { table: { url: string; relPath: string }; files: { url: string; relPath: string }[] };
174
+ /** The page file cut into the files routes load; `table` names each group's file. Each file's `bytes` as above. */
175
+ routeParts?: { table: { url: string; relPath: string }; files: { url: string; relPath: string; bytes?: number }[] };
174
176
  }
175
177
 
176
178
  export interface RenderState {
@@ -21,7 +21,7 @@ import { RscRenderRefusal } from "./rscRenderRefusal";
21
21
  import type { ScriptPolicySources } from "./scriptPolicy";
22
22
  import { getPathnameLocale } from "./systemPageDocument";
23
23
  import { createSystemPageResponse, getSystemPageHomeHref } from "./systemPages";
24
- import type { BaseBuildArtifact, RenderState } from "./types";
24
+ import type { BaseBuildArtifact, DictAsset, RenderState } from "./types";
25
25
 
26
26
  const CLIENT_CLOSED_REQUEST_STATUS = 499;
27
27
 
@@ -124,8 +124,17 @@ export class WebRouteContext {
124
124
  const asset = assets[locale] ?? assets[i18n.defaultLocale];
125
125
  if (!asset) return [];
126
126
  const files = routeId ? (this.artifact.dictRoutes?.[routeId] ?? this.#builtFilesOf(routeId)) : undefined;
127
- const urls = files?.flatMap((idx) => asset.routeParts?.files[idx]?.url ?? []) ?? [];
128
- return urls.length && urls.length === files?.length ? urls : [asset.url];
127
+ const picked = files?.flatMap((idx) => asset.routeParts?.files[idx] ?? []) ?? [];
128
+ if (!picked.length || picked.length !== files?.length) return [asset.url];
129
+ return WebRouteContext.#underWhole(asset, picked).map(({ url }) => url);
130
+ }
131
+
132
+ static #underWhole(asset: DictAsset, picked: { url: string; bytes?: number }[]): { url: string }[] {
133
+ const apiUrl = asset.parts?.api?.url;
134
+ const page = picked.filter(({ url }) => url !== apiUrl);
135
+ if (asset.bytes === undefined || page.some(({ bytes }) => bytes === undefined)) return picked;
136
+ const pageBytes = page.reduce((sum, { bytes = 0 }) => sum + bytes, 0);
137
+ return pageBytes < asset.bytes ? picked : [asset, ...picked.filter(({ url }) => url === apiUrl)];
129
138
  }
130
139
 
131
140
  #builtFilesOf(routeId: string): number[] | undefined {
@@ -206,6 +206,8 @@ export type AkanIpcMessage =
206
206
  healthPath?: string;
207
207
  crossSite?: { allowedOrigins: string[]; enabled: boolean };
208
208
  rscWorker?: AkanRscWorkerStatus;
209
+ /** Sent first by a dev replica booted beside the first base build: its api answers, its pages wait. */
210
+ webPending?: boolean;
209
211
  }
210
212
  | { type: "pubsub.publish"; roomId: string; data: object | object[]; origin?: string }
211
213
  | { type: "pubsub.deliver"; roomId: string; data: object | object[]; origin?: string }
@@ -1,8 +1,3 @@
1
- /** Inside an iOS or Android shell of the native runtime; a mobile target opened in a browser is not. */
2
- export declare const isNativeApp: () => boolean;
3
- /** Inside any shell of the native runtime, desktop included. */
4
- export declare const isNativeShell: () => boolean;
5
- export declare const nativePlatform: () => "ios" | "android" | null;
6
- export declare const desktopPlatform: () => "macos" | "windows" | "linux" | null;
1
+ export { desktopPlatform, isNativeApp, isNativeShell, nativePlatform } from "./nativeShell.d.ts";
7
2
  /** http(s) in the in-app browser, anything else (mailto:, tel:) in the app the system picks. */
8
3
  export declare const openExternalUrl: (url: string) => Promise<void>;
@@ -0,0 +1,10 @@
1
+ import type { Platform } from "../vendor/@akanjs/native/packages/core/src/index.d.ts";
2
+ type ShellPlatform = Exclude<Platform, "web">;
3
+ export declare const shellPlatform: () => ShellPlatform | null;
4
+ /** Inside an iOS or Android shell of the native runtime; a mobile target opened in a browser is not. */
5
+ export declare const isNativeApp: () => boolean;
6
+ /** Inside any shell of the native runtime, desktop included. */
7
+ export declare const isNativeShell: () => boolean;
8
+ export declare const nativePlatform: () => "ios" | "android" | null;
9
+ export declare const desktopPlatform: () => "macos" | "windows" | "linux" | null;
10
+ export {};
@@ -121,7 +121,7 @@ declare class Router {
121
121
  * than stacking it, and a visitor may have opened this address directly, so `back()` alone would leave the page.
122
122
  * Only the one entry under this one is looked at, and the rewrite keeps the scroll unless `scrollToTop` is set.
123
123
  */
124
- backTo(href: string, routeOptions?: RouteOptions): never;
124
+ backOrReplace(href: string, routeOptions?: RouteOptions): never;
125
125
  back(routeOptions?: RouteOptions): never;
126
126
  refresh(): never;
127
127
  /** Client-side redirects so far: a render that saw this change while it ran redirected instead of drawing. A method
@@ -0,0 +1 @@
1
+ export declare const immerable: unique symbol;
@@ -16,6 +16,7 @@ export interface ChildState {
16
16
  }>;
17
17
  healthPath?: string;
18
18
  rscWorker?: AkanRscWorkerStatus;
19
+ webPending?: boolean;
19
20
  metrics: AkanMetricsReport;
20
21
  /** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
21
22
  lastPongAtMono?: number;
@@ -1,5 +1,6 @@
1
1
  export declare class DevBaseArtifact {
2
2
  #private;
3
+ static awaited(env?: Record<string, string | undefined>): boolean;
3
4
  static arrived({ artifactDir, env, stopped, warnAfterMs, warn, }?: {
4
5
  artifactDir?: string;
5
6
  env?: Record<string, string | undefined>;
@@ -1,11 +1,11 @@
1
- import type { AkanIpcMessage } from "akanjs/service";
1
+ import type { AkanIpcMessage, AkanRscWorkerStatus } from "akanjs/service";
2
2
  import type { AkanServer } from "../akanServer.d.ts";
3
3
  import type { ServerLogging } from "../logging/serverLogging.d.ts";
4
4
  import type { WebRouter } from "../webRouter.d.ts";
5
5
  type ParentChannelOwner = Pick<AkanServer, "logger" | "shutdownTimeoutMs" | "stop">;
6
6
  export declare class ParentChannel {
7
7
  #private;
8
- constructor(owner: ParentChannelOwner, logging: ServerLogging, webRouter: () => WebRouter | null);
8
+ constructor(owner: ParentChannelOwner, logging: Pick<ServerLogging, "setMinSev">, webRouter: () => WebRouter | null, rscWorker?: () => AkanRscWorkerStatus);
9
9
  get gone(): boolean;
10
10
  register(): void;
11
11
  sendReady(message: AkanIpcMessage): void;
@@ -19,5 +19,5 @@ export declare class RotatingLogWriter {
19
19
  static sanitizeFilePart(value: string): string;
20
20
  write(processKey: string, chunk: string): void;
21
21
  close(): Promise<void>;
22
- static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#182@#defaultWarn): number;
22
+ static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#177@#defaultWarn): number;
23
23
  }
@@ -7,6 +7,7 @@ export declare class ServerLogging {
7
7
  get stream(): LogStreamRoute | null;
8
8
  setMinSev(minSev: number | null): void;
9
9
  startTransport(webRouter?: WebRouter | null): Promise<void>;
10
+ attachWeb(webRouter: WebRouter | null): void;
10
11
  startFileLogging(role: string): void;
11
12
  stop(): Promise<void>;
12
13
  }
@@ -0,0 +1,3 @@
1
+ type Env = Record<string, string | undefined>;
2
+ export declare const isDevBuild: (env?: Env) => boolean;
3
+ export {};
@@ -4,6 +4,7 @@ import type { HmrWsData, HmrWsHub } from "../hmr/wsHub.d.ts";
4
4
  import type { WebProxyRunner } from "../proxy.d.ts";
5
5
  import type { HttpRoutes, LocalPublish, SignalRoutes, WebsocketRoutes } from "../types.d.ts";
6
6
  import type { WebRouter } from "../webRouter.d.ts";
7
+ import type { WebSurfaceHold } from "./webSurfaceHold.d.ts";
7
8
  export interface AkanAppPrepared {
8
9
  routes: SignalRoutes["routes"];
9
10
  routeOptions: SignalRoutes["routeOptions"];
@@ -25,10 +26,11 @@ export declare class ServerListener {
25
26
  get pubsubBufferedCount(): number | undefined;
26
27
  upgradeHmrWs(req: Request, data: HmrWsData): boolean;
27
28
  publishLocal(roomId: string, data: Parameters<LocalPublish>[1]): void;
28
- listen(prepared: AkanAppPrepared, webRouter: WebRouter | null): {
29
+ listen(prepared: AkanAppPrepared, webRouter: WebRouter | null, hold?: WebSurfaceHold | null): {
29
30
  unix: string | undefined;
30
31
  port: number | undefined;
31
32
  };
33
+ attachWeb(prepared: AkanAppPrepared, webRouter: WebRouter | null): void;
32
34
  close(): void;
33
35
  }
34
36
  export {};
@@ -0,0 +1,13 @@
1
+ import type { NonNullHttpRoutes } from "./apiRouter.d.ts";
2
+ import type { HostAllowlist } from "./hostAllowlist.d.ts";
3
+ export type HoldHandler = (req: Request, server: Bun.Server<unknown>) => Response | Promise<Response | undefined> | undefined;
4
+ export declare class WebSurfaceHold {
5
+ #private;
6
+ get pending(): boolean;
7
+ open(): void;
8
+ fail(reason: string): void;
9
+ settle(reason: string): Promise<void>;
10
+ route(table: () => NonNullHttpRoutes | null): HoldHandler;
11
+ guard(routes: NonNullHttpRoutes, allowlist: HostAllowlist | null, held: HoldHandler): NonNullHttpRoutes;
12
+ static dispatch(routes: NonNullHttpRoutes, req: Request, server: Bun.Server<unknown>): Response | Promise<Response | undefined> | undefined;
13
+ }
@@ -104,12 +104,14 @@ export interface CssAsset {
104
104
  export interface DictAsset {
105
105
  url: string;
106
106
  relPath: string;
107
+ /** What a browser downloads of the page file: its brotli sidecar's size, or the file's own when that is no smaller. */
108
+ bytes?: number;
107
109
  /** The files this locale's dictionary left out, by name, loaded where a page shows them. */
108
110
  parts?: Record<string, {
109
111
  url: string;
110
112
  relPath: string;
111
113
  }>;
112
- /** The page file cut into the files routes load; `table` names each group's file. */
114
+ /** The page file cut into the files routes load; `table` names each group's file. Each file's `bytes` as above. */
113
115
  routeParts?: {
114
116
  table: {
115
117
  url: string;
@@ -118,6 +120,7 @@ export interface DictAsset {
118
120
  files: {
119
121
  url: string;
120
122
  relPath: string;
123
+ bytes?: number;
121
124
  }[];
122
125
  };
123
126
  }
@@ -225,6 +225,8 @@ export type AkanIpcMessage = {
225
225
  enabled: boolean;
226
226
  };
227
227
  rscWorker?: AkanRscWorkerStatus;
228
+ /** Sent first by a dev replica booted beside the first base build: its api answers, its pages wait. */
229
+ webPending?: boolean;
228
230
  } | {
229
231
  type: "pubsub.publish";
230
232
  roomId: string;