akanjs 3.1.2-rc.2 → 3.1.2-rc.4

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 (93) hide show
  1. package/README.ko.md +16 -5
  2. package/README.md +17 -5
  3. package/client/makePageProto.tsx +5 -1
  4. package/client/route/RouteHead.ts +23 -0
  5. package/common/akanGraph.ts +75 -0
  6. package/common/appHosts.ts +7 -0
  7. package/common/hasErrKey.ts +8 -0
  8. package/common/index.ts +14 -0
  9. package/common/tunnelWire.ts +3 -2
  10. package/common/websocketContract.ts +15 -0
  11. package/dictionary/trans.ts +2 -4
  12. package/document/dataLoader.ts +20 -5
  13. package/fetch/client/fetchClient.ts +17 -13
  14. package/fetch/client/wsClient.ts +32 -1
  15. package/package.json +1 -1
  16. package/server/akanApp.ts +38 -15
  17. package/server/akanOption.ts +14 -0
  18. package/server/akanServer.ts +7 -0
  19. package/server/artifact/builderRpc.ts +18 -8
  20. package/server/artifact/ipcTypes.ts +23 -1
  21. package/server/devtools/devtoolsRouter.ts +17 -0
  22. package/server/devtools/studio/studioActions.ts +78 -0
  23. package/server/devtools/studio/studioDocument.tsx +276 -0
  24. package/server/devtools/studio/studioLayout.ts +269 -0
  25. package/server/devtools/studio/studioRoute.ts +81 -0
  26. package/server/devtools/studio/studioRuntime.ts +123 -0
  27. package/server/devtools/studio/studioStyle.ts +58 -0
  28. package/server/fallbackHead.tsx +26 -0
  29. package/server/flightRowReader.ts +137 -0
  30. package/server/index.ts +1 -0
  31. package/server/mcp/McpAuth.ts +2 -4
  32. package/server/ops/statusAccess.ts +9 -0
  33. package/server/resolver/database.resolver.ts +4 -2
  34. package/server/routeElementComposer.tsx +33 -17
  35. package/server/routing/apiRouter.ts +4 -0
  36. package/server/routing/appWsData.ts +8 -0
  37. package/server/routing/hostAllowlist.ts +23 -6
  38. package/server/routing/soloAppRoutes.ts +11 -0
  39. package/server/routing/wsCredentialExpiry.ts +32 -0
  40. package/server/rscClientPatch.ts +5 -29
  41. package/server/rscHttp.ts +10 -43
  42. package/server/rscWorker.tsx +58 -28
  43. package/server/rscWorkerHost.ts +6 -2
  44. package/server/sessionRefresh.ts +125 -0
  45. package/server/ssrFromRscRenderer.tsx +10 -34
  46. package/server/tunnel/TunnelHttpStream.ts +4 -1
  47. package/server/tunnel/TunnelWebsocketStream.ts +3 -1
  48. package/server/webRouter.ts +33 -9
  49. package/service/predefinedAdaptor/database.adaptor.ts +34 -10
  50. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +17 -7
  51. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +29 -18
  52. package/service/predefinedAdaptor/sql/types.ts +1 -0
  53. package/types/client/makePageProto.d.ts +7274 -102
  54. package/types/client/route/RouteHead.d.ts +8 -1
  55. package/types/common/akanGraph.d.ts +58 -0
  56. package/types/common/appHosts.d.ts +1 -0
  57. package/types/common/hasErrKey.d.ts +3 -0
  58. package/types/common/index.d.ts +3 -1
  59. package/types/common/tunnelWire.d.ts +3 -2
  60. package/types/common/websocketContract.d.ts +5 -0
  61. package/types/constant/constantRegistry.d.ts +1 -1
  62. package/types/document/dataLoader.d.ts +4 -2
  63. package/types/fetch/client/wsClient.d.ts +6 -0
  64. package/types/server/akanOption.d.ts +8 -0
  65. package/types/server/artifact/builderRpc.d.ts +3 -1
  66. package/types/server/artifact/ipcTypes.d.ts +33 -1
  67. package/types/server/devtools/devtoolsRouter.d.ts +3 -0
  68. package/types/server/devtools/studio/studioActions.d.ts +16 -0
  69. package/types/server/devtools/studio/studioDocument.d.ts +23 -0
  70. package/types/server/devtools/studio/studioLayout.d.ts +40 -0
  71. package/types/server/devtools/studio/studioRoute.d.ts +17 -0
  72. package/types/server/devtools/studio/studioRuntime.d.ts +1 -0
  73. package/types/server/devtools/studio/studioStyle.d.ts +1 -0
  74. package/types/server/fallbackHead.d.ts +10 -0
  75. package/types/server/flightRowReader.d.ts +3 -0
  76. package/types/server/index.d.ts +1 -0
  77. package/types/server/migration/migrationCommand.d.ts +2 -2
  78. package/types/server/migration/migrations.d.ts +1 -1
  79. package/types/server/ops/statusAccess.d.ts +3 -0
  80. package/types/server/routeElementComposer.d.ts +5 -1
  81. package/types/server/routing/appWsData.d.ts +1 -0
  82. package/types/server/routing/hostAllowlist.d.ts +11 -3
  83. package/types/server/routing/soloAppRoutes.d.ts +3 -0
  84. package/types/server/routing/wsCredentialExpiry.d.ts +5 -0
  85. package/types/server/rscWorkerHost.d.ts +2 -0
  86. package/types/server/sessionRefresh.d.ts +11 -0
  87. package/types/server/webRouter.d.ts +5 -2
  88. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +2 -0
  89. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +9 -3
  90. package/types/service/predefinedAdaptor/sql/types.d.ts +1 -0
  91. package/types/ui/recipe/badgeRecipe.d.ts +2 -2
  92. package/types/ui/recipe/buttonRecipe.d.ts +2 -2
  93. package/types/ui/recipe/inputRecipe.d.ts +2 -2
@@ -12,6 +12,7 @@ import type {
12
12
  import type { McpServerOption } from "./akanServer";
13
13
  import type { WebProxyRegistration } from "./proxy";
14
14
  import { HostBasePathWebProxy, LocaleWebProxy } from "./proxy";
15
+ import type { SessionRefreshHook } from "./sessionRefresh";
15
16
 
16
17
  export interface AdaptorOverride {
17
18
  role: AdaptorCls;
@@ -32,6 +33,7 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
32
33
  #agentQuota: AgentQuotaHook | null | undefined;
33
34
  #crossSite: CrossSiteOption | undefined;
34
35
  #getRateLimit: ((env: Env) => RateLimitSetting | false) | undefined;
36
+ #sessionRefresh: SessionRefreshHook | null | undefined;
35
37
  use(fnOrObject: ((env: Env) => Record<string, PromiseOrObject<unknown>>) | Record<string, PromiseOrObject<unknown>>) {
36
38
  if (typeof fnOrObject === "function")
37
39
  this.#getUses.push(fnOrObject as (env: Env) => Record<string, PromiseOrObject<unknown>>);
@@ -92,6 +94,15 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
92
94
  this.#getRateLimit = typeof settingOrFn === "function" ? settingOrFn : () => settingOrFn;
93
95
  return this;
94
96
  }
97
+ /**
98
+ * Runs before a page or RSC navigation renders, with the request as the browser sent it, and returns `Set-Cookie`
99
+ * values (or none). The render reads the cookies they set and the response carries them, so a session whose access
100
+ * token expired is renewed before a guard sees it. The app's wins over its libs'; `null` clears a lib's.
101
+ */
102
+ setSessionRefresh(hook: SessionRefreshHook | null) {
103
+ this.#sessionRefresh = hook;
104
+ return this;
105
+ }
95
106
  /** Injected into the `LlmAdaptorRole` adaptor as the `llmOption` use; merged in mount order, the app's last. */
96
107
  setLlm<Option extends LlmOption>(llmOrFn: Option | ((env: Env) => Option)) {
97
108
  if (typeof llmOrFn === "function") this.#getLlms.push(llmOrFn);
@@ -151,6 +162,9 @@ export class AkanOption<Env extends BackendEnv = BackendEnv> {
151
162
  getRateLimit(env: Env): RateLimitSetting | false | undefined {
152
163
  return this.#getRateLimit?.(env);
153
164
  }
165
+ getSessionRefresh(): SessionRefreshHook | null | undefined {
166
+ return this.#sessionRefresh;
167
+ }
154
168
  getLlm(env: Env): LlmOption {
155
169
  return Object.assign({}, ...this.#getLlms.map((fn) => fn(env)));
156
170
  }
@@ -51,6 +51,7 @@ import { RoomReplay } from "./routing/roomReplay";
51
51
  import { RouteHosts } from "./routing/routeHosts";
52
52
  import { ServerLimits } from "./routing/serverLimits";
53
53
  import { createSoloAppRoutes } from "./routing/soloAppRoutes";
54
+ import { SessionRefresh } from "./sessionRefresh";
54
55
  import {
55
56
  getWebConfigFromEnv,
56
57
  type HttpRoutes,
@@ -223,6 +224,7 @@ export class AkanServer {
223
224
  this.openapi = options?.openapi ?? this.openapi;
224
225
 
225
226
  EndpointRateLimit.reset();
227
+ SessionRefresh.use(null);
226
228
  libs.forEach((lib) => {
227
229
  const mcp = lib.option.getMcp(this.env);
228
230
  if (mcp !== undefined) this.setMcp(mcp);
@@ -236,6 +238,8 @@ export class AkanServer {
236
238
  if (crossSite !== undefined) CrossSiteGuard.configure(crossSite);
237
239
  const rateLimit = lib.option.getRateLimit(this.env);
238
240
  if (rateLimit !== undefined) EndpointRateLimit.configure(rateLimit);
241
+ const sessionRefresh = lib.option.getSessionRefresh();
242
+ if (sessionRefresh !== undefined) SessionRefresh.use(sessionRefresh);
239
243
  });
240
244
  EndpointRateLimit.applyEnv(process.env.AKAN_RATE_LIMIT, getEnv().environment);
241
245
  this.setMcp(options?.mcp ?? this.mcp);
@@ -763,6 +767,7 @@ export class AkanServer {
763
767
  running: this.status === "running",
764
768
  status: this.status,
765
769
  port: this.#server?.port ?? null,
770
+ rscWorker: webRouter?.rscWorkerStatus ?? null,
766
771
  metrics: this.#lastMetrics,
767
772
  }),
768
773
  this.#logStream,
@@ -782,6 +787,8 @@ export class AkanServer {
782
787
  websocketPrefix: this.websocketPrefix,
783
788
  openapi: this.openapi,
784
789
  getStatus: () => this.status,
790
+ buildGraph: webRouter ? () => webRouter.buildGraph() : undefined,
791
+ buildChanges: webRouter ? (since) => webRouter.buildChanges(since) : undefined,
785
792
  }).createRoutes();
786
793
  return { ...openapiRoutes, ...mcpRoutes, ...devtoolsRoutes, ...soloRoutes };
787
794
  }
@@ -1,11 +1,11 @@
1
1
  import { Logger } from "akanjs/common";
2
2
  import type {
3
- BuilderCsrReq,
4
- BuilderCsrRes,
3
+ BuildChangesPayload,
5
4
  BuilderEvent,
6
5
  BuilderMessage,
7
- BuilderReq,
8
- BuilderRes,
6
+ BuilderRequest,
7
+ BuilderResponse,
8
+ BuildGraphPayload,
9
9
  BuildRouteClientResult,
10
10
  BuildRouteResultPayload,
11
11
  CsrUpdatedPayload,
@@ -31,7 +31,7 @@ export class BuilderRpc {
31
31
  readonly #logger = new Logger("BuilderRpc");
32
32
  readonly #pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
33
33
  readonly #offMessage: () => void;
34
- readonly #send: (msg: BuilderReq | BuilderCsrReq) => void;
34
+ readonly #send: (msg: BuilderRequest) => void;
35
35
  #nextId = 1;
36
36
  #disposed = false;
37
37
 
@@ -40,13 +40,13 @@ export class BuilderRpc {
40
40
  throw new Error("[builder] process.send unavailable — backend must be spawned by the CLI with ipc enabled");
41
41
  this.#send = process.send.bind(process);
42
42
  this.#offMessage = this.#listen((msg) => {
43
- if (msg.type === "build-route-res" || msg.type === "build-csr-res") {
44
- const res = msg as BuilderRes | BuilderCsrRes;
43
+ if (msg.type === "build-route-res" || msg.type === "build-csr-res" || msg.type === "build-graph-res") {
44
+ const res = msg as BuilderResponse;
45
45
  const waiter = this.#pending.get(res.id);
46
46
  if (!waiter) return;
47
47
  this.#pending.delete(res.id);
48
48
  if (!res.ok) waiter.reject(new Error(`[builder] ${res.type} failed: ${res.error}`));
49
- else waiter.resolve(res.type === "build-route-res" ? res.data : undefined);
49
+ else waiter.resolve(res.type === "build-csr-res" ? undefined : res.data);
50
50
  return;
51
51
  }
52
52
  const ev = msg as BuilderEvent;
@@ -114,6 +114,16 @@ export class BuilderRpc {
114
114
  );
115
115
  }
116
116
 
117
+ async buildGraph(): Promise<BuildGraphPayload> {
118
+ return await this.#request<BuildGraphPayload>("build-graph", (id) => this.#send({ type: "build-graph", id }));
119
+ }
120
+
121
+ async buildChanges(since: string | null): Promise<BuildChangesPayload> {
122
+ return await this.#request<BuildChangesPayload>("build-graph changes", (id) =>
123
+ this.#send({ type: "build-graph", id, changes: { since } }),
124
+ );
125
+ }
126
+
117
127
  static #timeoutMs(): number {
118
128
  const configured = Number(process.env.AKAN_BUILDER_RPC_TIMEOUT_MS);
119
129
  if (Number.isFinite(configured) && configured > 0) return configured;
@@ -1,3 +1,4 @@
1
+ import type { AkanChangeMap, AkanGraph } from "akanjs/common";
1
2
  import type { SsrManifest } from "../ssrTypes";
2
3
 
3
4
  export interface BuildRouteResultPayload {
@@ -80,6 +81,23 @@ export type BuilderCsrRes =
80
81
  | { type: "build-csr-res"; id: number; ok: true }
81
82
  | { type: "build-csr-res"; id: number; ok: false; error: string };
82
83
 
84
+ export interface BuildGraphPayload {
85
+ workspaceRoot: string;
86
+ graph: AkanGraph;
87
+ }
88
+
89
+ export interface BuildChangesPayload {
90
+ workspaceRoot: string;
91
+ changes: AkanChangeMap | { error: string };
92
+ }
93
+
94
+ /** `changes` asks for the Change Map since `since`, or since HEAD forked from the default branch when it is null. */
95
+ export type BuilderGraphReq = { type: "build-graph"; id: number; changes?: { since: string | null } };
96
+
97
+ export type BuilderGraphRes =
98
+ | { type: "build-graph-res"; id: number; ok: true; data: BuildGraphPayload | BuildChangesPayload }
99
+ | { type: "build-graph-res"; id: number; ok: false; error: string };
100
+
83
101
  /** Drain and exit (the only way bundler memory returns to the OS); draining, not killing, keeps a rebuild whole. */
84
102
  export type BuilderControl = { type: "builder-shutdown"; reason: string };
85
103
 
@@ -164,7 +182,11 @@ export type BuilderEvent =
164
182
  /** The boot builds settled (the SSR registry's, and CSR's when the env arms it): their workers are a boot's peak. */
165
183
  | { type: "boot-armed" };
166
184
 
167
- export type BuilderMessage = BuilderReq | BuilderRes | BuilderCsrReq | BuilderCsrRes | BuilderControl | BuilderEvent;
185
+ export type BuilderRequest = BuilderReq | BuilderCsrReq | BuilderGraphReq;
186
+
187
+ export type BuilderResponse = BuilderRes | BuilderCsrRes | BuilderGraphRes;
188
+
189
+ export type BuilderMessage = BuilderRequest | BuilderResponse | BuilderControl | BuilderEvent;
168
190
 
169
191
  export interface ClientManifestEntry {
170
192
  id: string;
@@ -2,11 +2,13 @@ import type { BaseEnv } from "akanjs/base";
2
2
  import { Logger } from "akanjs/common";
3
3
  import { DictionaryRegistry, type RootDictionary } from "akanjs/dictionary";
4
4
  import { isLocalDevRuntime } from "../../signal/trace";
5
+ import type { BuildChangesPayload, BuildGraphPayload } from "../artifact";
5
6
  import type { DiLifecycle } from "../di/diLifecycle";
6
7
  import type { HttpRoutes } from "../types";
7
8
  import { ConstantSerializer } from "./constantSerializer";
8
9
  import { DepsSerializer } from "./depsSerializer";
9
10
  import { SignalSerializer } from "./signalSerializer";
11
+ import { StudioRoute } from "./studio/studioRoute";
10
12
  import type { DevtoolsApp, DevtoolsEnvelope, DevtoolsIndex, DictionaryData } from "./types";
11
13
 
12
14
  export interface DevtoolsRouterContext {
@@ -18,6 +20,8 @@ export interface DevtoolsRouterContext {
18
20
  websocketPrefix: string;
19
21
  openapi: boolean;
20
22
  getStatus: () => string;
23
+ buildGraph?: () => Promise<BuildGraphPayload | null>;
24
+ buildChanges?: (since: string | null) => Promise<BuildChangesPayload | null>;
21
25
  }
22
26
 
23
27
  /** Builtin routes, not signals: off `/api` and guards, and never in the `serializedSignal` payload sent to clients. */
@@ -41,7 +45,15 @@ export class DevtoolsRouter {
41
45
 
42
46
  createRoutes(): HttpRoutes {
43
47
  if (!DevtoolsRouter.isEnabled(this.#context.env)) return {};
48
+ const studio = new StudioRoute({
49
+ basePath: `${DevtoolsRouter.basePath}/studio`,
50
+ appName: this.#context.env.appName,
51
+ buildGraph: this.#context.buildGraph ?? null,
52
+ buildChanges: this.#context.buildChanges ?? null,
53
+ });
44
54
  return {
55
+ [`${DevtoolsRouter.basePath}/studio`]: { GET: (req: Request) => this.#gated(() => studio.page(req)) },
56
+ [`${DevtoolsRouter.basePath}/studio/graph`]: { GET: (req: Request) => this.#gated(() => studio.graph(req)) },
45
57
  [`${DevtoolsRouter.basePath}/devtools`]: { GET: () => DevtoolsRouter.#json(this.#index()) },
46
58
  [`${DevtoolsRouter.basePath}/constant`]: {
47
59
  GET: () => this.#respond("constant", () => ConstantSerializer.serialize()),
@@ -100,6 +112,11 @@ export class DevtoolsRouter {
100
112
  }
101
113
  }
102
114
 
115
+ async #gated(respond: () => Promise<Response>): Promise<Response> {
116
+ if (!DevtoolsRouter.isEnabled(this.#context.env)) return DevtoolsRouter.#json({ error: "Not found" }, 404);
117
+ return await respond();
118
+ }
119
+
103
120
  #envelope<Kind extends string, Data>(kind: Kind, data: Data): DevtoolsEnvelope<Kind, Data> {
104
121
  return { kind, version: 1, generatedAt: new Date().toISOString(), app: this.#app(), data };
105
122
  }
@@ -0,0 +1,78 @@
1
+ import type { AkanGraphNode, AkanGraphNodeKind } from "akanjs/common";
2
+
3
+ export type StudioWorkflow =
4
+ | "create-module"
5
+ | "add-field"
6
+ | "add-enum-field"
7
+ | "add-mutation"
8
+ | "add-slice"
9
+ | "create-ui"
10
+ | "rename-key";
11
+
12
+ export interface StudioAction {
13
+ kind: "workflow" | "module";
14
+ workflow?: StudioWorkflow;
15
+ label: string;
16
+ inputs: { [input: string]: string };
17
+ command: string | null;
18
+ }
19
+
20
+ const askedInputs: { [workflow in StudioWorkflow]: string[] } = {
21
+ "create-module": ["module"],
22
+ "add-field": ["field", "type"],
23
+ "add-enum-field": ["field", "values"],
24
+ "add-mutation": ["mutation", "guard"],
25
+ "add-slice": ["slice"],
26
+ "create-ui": ["surface"],
27
+ "rename-key": ["to"],
28
+ };
29
+
30
+ const actionsByKind: { [kind in AkanGraphNodeKind]?: [StudioWorkflow, string][] } = {
31
+ model: [
32
+ ["add-field", "Add field"],
33
+ ["add-enum-field", "Add enum field"],
34
+ ["add-mutation", "Add mutation"],
35
+ ["add-slice", "Add slice"],
36
+ ["create-ui", "Create UI"],
37
+ ],
38
+ };
39
+ const identifier = /^[A-Za-z_$][\w$-]{0,63}$/;
40
+
41
+ const keyInputs: { [kind in AkanGraphNodeKind]?: { input: string; label: string } } = {
42
+ slice: { input: "slice", label: "Rename slice key" },
43
+ query: { input: "query", label: "Rename query" },
44
+ };
45
+
46
+ export class StudioActions {
47
+ static of(node: AkanGraphNode): StudioAction[] {
48
+ const app = node.owner?.split("/").at(-1);
49
+ const { module } = node;
50
+ if (!app || !module || module.startsWith("__") || node.change === "removed") return [];
51
+ if (!identifier.test(app) || !identifier.test(module)) return [];
52
+ const target = { app, module };
53
+ const open: StudioAction = { kind: "module", label: "Open module", inputs: target, command: null };
54
+ return [open, ...StudioActions.#workflowsOf(node, target)];
55
+ }
56
+
57
+ static #workflowsOf(node: AkanGraphNode, target: StudioAction["inputs"]): StudioAction[] {
58
+ const keyed = keyInputs[node.kind];
59
+ if (!keyed)
60
+ return (actionsByKind[node.kind] ?? []).map(([workflow, label]) =>
61
+ StudioActions.#action(workflow, label, target),
62
+ );
63
+ return node.name && identifier.test(node.name)
64
+ ? [StudioActions.#action("rename-key", keyed.label, { ...target, [keyed.input]: node.name })]
65
+ : [];
66
+ }
67
+
68
+ static ofApp(app: string): StudioAction[] {
69
+ return identifier.test(app) ? [StudioActions.#action("create-module", "New module", { app })] : [];
70
+ }
71
+
72
+ static #action(workflow: StudioWorkflow, label: string, inputs: StudioAction["inputs"]): StudioAction {
73
+ const given = Object.entries(inputs).map(([name, value]) => `--${name} ${value}`);
74
+ const asked = askedInputs[workflow].map((name) => `--${name} <${name}>`);
75
+ const command = ["akan workflow plan", workflow, ...given, ...asked].join(" ");
76
+ return { kind: "workflow", workflow, label, inputs, command };
77
+ }
78
+ }
@@ -0,0 +1,276 @@
1
+ import type { AkanChangeMap, AkanGraph, AkanGraphChange, AkanGraphLocation } from "akanjs/common";
2
+ import type { BuildChangesPayload, BuildGraphPayload } from "../../artifact";
3
+ import { StudioActions } from "./studioActions";
4
+ import { type StudioBox, StudioLayout, type StudioScene, type StudioView } from "./studioLayout";
5
+ import { studioRuntime } from "./studioRuntime";
6
+ import { studioStyle } from "./studioStyle";
7
+
8
+ export type StudioEditor = "vscode" | "cursor";
9
+
10
+ export interface StudioQuery {
11
+ view: StudioView;
12
+ module: string | null;
13
+ editor: StudioEditor;
14
+ since: string | null;
15
+ }
16
+
17
+ export interface StudioDocumentProps {
18
+ basePath: string;
19
+ appName: string;
20
+ payload: BuildGraphPayload | BuildChangesPayload;
21
+ query: StudioQuery;
22
+ }
23
+
24
+ const editorLabels: { [editor in StudioEditor]: string } = { vscode: "VS Code", cursor: "Cursor" };
25
+ const viewLabels: { [view in StudioView]: string } = { erd: "ERD", signals: "Signals", changes: "Changes" };
26
+ const changeSigns: { [change in AkanGraphChange]: string } = { added: "+", removed: "−", changed: "~" };
27
+ const charWidth = 7.3;
28
+ const kindShownIn: { [view in StudioView]: Set<string> } = {
29
+ erd: new Set(["model", "scalar", "enum"]),
30
+ signals: new Set(["endpoint", "slice", "query", "model"]),
31
+ changes: new Set(["endpoint", "slice", "query", "model", "scalar", "enum", "guard"]),
32
+ };
33
+ const emptyGraph: AkanGraph = { version: 1, nodes: [], edges: [] };
34
+ const clip = (text: string, max: number) => {
35
+ const room = Math.max(8, max);
36
+ return text.length > room ? `${text.slice(0, room - 1)}…` : text;
37
+ };
38
+
39
+ export class StudioDocument {
40
+ static render({ basePath, appName, payload, query }: StudioDocumentProps) {
41
+ const changes = "changes" in payload ? payload.changes : null;
42
+ const changeMap = changes && "nodes" in changes ? changes : null;
43
+ const graph = "graph" in payload ? payload.graph : (changeMap ?? emptyGraph);
44
+ const listed = StudioLayout.modulesOf(graph);
45
+ const modules = query.module && !listed.includes(query.module) ? [query.module, ...listed] : listed;
46
+ const scene =
47
+ query.view === "erd"
48
+ ? StudioLayout.erd(graph, query.module)
49
+ : query.view === "signals"
50
+ ? StudioLayout.signals(graph, query.module ?? modules[0] ?? null)
51
+ : StudioLayout.changes(graph, query.module);
52
+ const hrefOf = (next: Partial<StudioQuery>) => StudioDocument.href(basePath, { ...query, ...next });
53
+ const openOf = (at: AkanGraphLocation | null) =>
54
+ at ? StudioDocument.editorHref(query.editor, payload.workspaceRoot, at) : undefined;
55
+ const graphHref = query.view === "changes" ? StudioDocument.href(`${basePath}/graph`, query) : `${basePath}/graph`;
56
+ const unmapped = changeMap ? StudioLayout.unmappedIn(changeMap.unmapped, query.module) : [];
57
+ return (
58
+ <html lang="en">
59
+ <head>
60
+ <meta charSet="utf-8" />
61
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
62
+ <title>{`Akan Studio · ${appName}`}</title>
63
+ <style>{studioStyle}</style>
64
+ </head>
65
+ <body>
66
+ <header>
67
+ <strong>Akan Studio</strong>
68
+ <span className="muted">{appName}</span>
69
+ <nav>
70
+ {(["erd", "signals", "changes"] as const).map((view) => (
71
+ <a key={view} href={hrefOf({ view })} aria-current={view === query.view ? "page" : undefined}>
72
+ {viewLabels[view]}
73
+ </a>
74
+ ))}
75
+ </nav>
76
+ <form method="get" action={basePath}>
77
+ <input type="hidden" name="view" value={query.view} />
78
+ <input type="hidden" name="editor" value={query.editor} />
79
+ <select name="module" defaultValue={query.module ?? ""} data-studio-module="">
80
+ {query.view !== "signals" ? <option value="">All modules</option> : null}
81
+ {modules.map((module) => (
82
+ <option key={module} value={module}>
83
+ {module}
84
+ </option>
85
+ ))}
86
+ </select>
87
+ {query.view === "changes" ? (
88
+ <input
89
+ type="text"
90
+ name="since"
91
+ defaultValue={query.since ?? ""}
92
+ placeholder="Since: default branch"
93
+ aria-label="Since"
94
+ />
95
+ ) : query.since ? (
96
+ <input type="hidden" name="since" value={query.since} />
97
+ ) : null}
98
+ <noscript>
99
+ <button type="submit">Show</button>
100
+ </noscript>
101
+ </form>
102
+ <input type="search" placeholder="Filter by name" data-studio-filter="" />
103
+ {changeMap ? <span className="muted">{StudioDocument.#summary(changeMap)}</span> : null}
104
+ <span className="muted">{`${scene.boxes.length} nodes · ${scene.links.length} edges`}</span>
105
+ <div
106
+ className="actions"
107
+ data-studio-actions=""
108
+ data-label={appName}
109
+ data-actions={JSON.stringify(StudioActions.ofApp(appName))}
110
+ />
111
+ <nav className="end">
112
+ {(["vscode", "cursor"] as const).map((editor) => (
113
+ <a key={editor} href={hrefOf({ editor })} aria-current={editor === query.editor ? "true" : undefined}>
114
+ {editorLabels[editor]}
115
+ </a>
116
+ ))}
117
+ <a href={graphHref}>JSON</a>
118
+ </nav>
119
+ </header>
120
+ <main>
121
+ {changes && "error" in changes ? (
122
+ <p className="empty">{changes.error}</p>
123
+ ) : scene.boxes.length ? (
124
+ StudioDocument.#svg(scene, query.view, openOf)
125
+ ) : (
126
+ <p className="empty">
127
+ {changeMap && !query.module
128
+ ? `No node changed since ${changeMap.since}.`
129
+ : "Nothing to draw here. Pick another module or view."}
130
+ </p>
131
+ )}
132
+ {unmapped.length ? (
133
+ <section className="unmapped">
134
+ <h2>Changed files no node covers</h2>
135
+ <ul>
136
+ {unmapped.map(({ file, change }) => (
137
+ <li key={file} className={change}>
138
+ {`${changeSigns[change]} `}
139
+ {change === "removed" ? file : <a href={openOf({ file, line: 1, column: 1 })}>{file}</a>}
140
+ </li>
141
+ ))}
142
+ </ul>
143
+ </section>
144
+ ) : null}
145
+ </main>
146
+ {StudioDocument.#runtime()}
147
+ </body>
148
+ </html>
149
+ );
150
+ }
151
+
152
+ static unavailable(appName: string, reason: string) {
153
+ return (
154
+ <html lang="en">
155
+ <head>
156
+ <meta charSet="utf-8" />
157
+ <title>{`Akan Studio · ${appName}`}</title>
158
+ <style>{studioStyle}</style>
159
+ </head>
160
+ <body>
161
+ <p className="empty">{reason}</p>
162
+ {StudioDocument.#runtime()}
163
+ </body>
164
+ </html>
165
+ );
166
+ }
167
+
168
+ static #runtime() {
169
+ return (
170
+
171
+ <script dangerouslySetInnerHTML={{ __html: `(${studioRuntime.toString()})();` }} />
172
+ );
173
+ }
174
+
175
+ static href(basePath: string, { view, module, editor, since }: StudioQuery): string {
176
+ const search = new URLSearchParams({ view, editor });
177
+ if (module) search.set("module", module);
178
+ if (since) search.set("since", since);
179
+ return `${basePath}?${search.toString()}`;
180
+ }
181
+
182
+ static #summary({ since, summary }: AkanChangeMap): string {
183
+ return `since ${since} · +${summary.added} −${summary.removed} ~${summary.changed}`;
184
+ }
185
+
186
+ static editorHref(editor: StudioEditor, workspaceRoot: string, at: AkanGraphLocation): string {
187
+ const root = workspaceRoot.replace(/\\/g, "/").replace(/\/$/, "");
188
+ const file = `${root.startsWith("/") ? "" : "/"}${root}/${at.file}`;
189
+ return `${editor}://file${encodeURI(file)}:${at.line}:${at.column}`;
190
+ }
191
+
192
+ static #svg(scene: StudioScene, view: StudioView, openOf: (at: AkanGraphLocation | null) => string | undefined) {
193
+ return (
194
+ <svg data-studio="" width={scene.width} height={scene.height} viewBox={`0 0 ${scene.width} ${scene.height}`}>
195
+ <defs>
196
+ <marker id="arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto">
197
+ <path d="M0,0 L8,4 L0,8 z" className="arrow" />
198
+ </marker>
199
+ </defs>
200
+ {scene.columns.map((column) =>
201
+ column.label ? (
202
+ <text key={column.x} className="column" x={column.x} y={24}>
203
+ {column.label}
204
+ </text>
205
+ ) : null,
206
+ )}
207
+ <g>
208
+ {scene.links.map(({ edge, path }) => (
209
+ <path
210
+ key={`${edge.from}>${edge.to}>${edge.kind}>${edge.label ?? ""}`}
211
+ d={path}
212
+ className={edge.change ? `link ${edge.kind} ${edge.change}` : `link ${edge.kind}`}
213
+ data-from={edge.from}
214
+ data-to={edge.to}
215
+ markerEnd="url(#arrow)"
216
+ >
217
+ <title>
218
+ {`${edge.change ? `${edge.change} ` : ""}${edge.kind} ${edge.label ?? ""}${edge.count > 1 ? ` ×${edge.count}` : ""}`}
219
+ </title>
220
+ </path>
221
+ ))}
222
+ </g>
223
+ <g>{scene.boxes.map((box) => StudioDocument.#box(box, view, openOf))}</g>
224
+ </svg>
225
+ );
226
+ }
227
+
228
+ static #box(
229
+ { node, x, y, width, height, rows }: StudioBox,
230
+ view: StudioView,
231
+ openOf: (at: AkanGraphLocation | null) => string | undefined,
232
+ ) {
233
+ const lib = node.owner?.startsWith("libs/") ? node.owner.slice(5) : null;
234
+ const kind = [lib, kindShownIn[view].has(node.kind) ? node.kind : null].filter(Boolean).join(" · ");
235
+ const chars = Math.floor((width - 24) / charWidth);
236
+ const mark = view === "changes" ? (node.change ?? "context") : null;
237
+ const actions = StudioActions.of(node);
238
+ return (
239
+ <g
240
+ key={node.id}
241
+ className={mark ? `box ${node.kind} ${mark}` : `box ${node.kind}`}
242
+ data-node={node.id}
243
+ data-label={node.label}
244
+ data-actions={actions.length ? JSON.stringify(actions) : undefined}
245
+ >
246
+ <title>{node.at ? `${node.label}\n${node.at.file}:${node.at.line}` : node.label}</title>
247
+ <rect x={x} y={y} width={width} height={height} rx={6} />
248
+ <rect className="bar" x={x} y={y} width={4} height={height} rx={2} />
249
+ <a href={openOf(node.change === "removed" ? null : node.at)}>
250
+ <text className="title" x={x + 12} y={y + 18}>
251
+ {clip(
252
+ node.change ? `${changeSigns[node.change]} ${node.label}` : node.label,
253
+ kind ? chars - kind.length - 1 : chars,
254
+ )}
255
+ </text>
256
+ </a>
257
+ <text className="kind" x={x + width - 10} y={y + 18} textAnchor="end">
258
+ {kind}
259
+ </text>
260
+ {rows.map((row, idx) => (
261
+ <a key={idx} href={openOf(row.at)}>
262
+ <text className={row.change} x={x + 12} y={row.y + 4}>
263
+ {clip(
264
+ row.change ? `${changeSigns[row.change]} ${row.text}` : row.text,
265
+ row.hint ? chars - row.hint.length - 1 : chars,
266
+ )}
267
+ </text>
268
+ <text className="hint" x={x + width - 10} y={row.y + 4} textAnchor="end">
269
+ {row.hint}
270
+ </text>
271
+ </a>
272
+ ))}
273
+ </g>
274
+ );
275
+ }
276
+ }