blob: cd5f29c5e7b8fe0b7924c8dd10464eb1a799e1e3 [file] [log] [blame]
gio5f2f1002025-03-20 18:38:48 +04001import { Category, defaultCategories } from "./categories";
2import { CreateValidators, Validator } from "./config";
gioa71316d2025-05-24 09:41:36 +04003import { GitHubService, GitHubServiceImpl, GitHubRepository } from "./github";
gioc31bf142025-06-16 07:48:20 +00004import type { Edge, OnConnect, OnEdgesChange, OnNodesChange, Viewport as ReactFlowViewport } from "@xyflow/react";
gioaf8db832025-05-13 14:43:05 +00005import {
6 addEdge,
7 applyEdgeChanges,
8 applyNodeChanges,
9 Connection,
10 EdgeChange,
11 useNodes,
12 XYPosition,
13} from "@xyflow/react";
giod0026612025-05-08 13:00:36 +000014import type { DeepPartial } from "react-hook-form";
15import { v4 as uuidv4 } from "uuid";
giod0026612025-05-08 13:00:36 +000016import { create } from "zustand";
gio74c6f752025-07-05 04:10:58 +000017import { AppNode, Env, NodeType, VolumeNode, GatewayTCPData, envSchema, AgentAccess } from "config";
gio5f2f1002025-03-20 18:38:48 +040018
19export function nodeLabel(n: AppNode): string {
gio48fde052025-05-14 09:48:08 +000020 try {
21 switch (n.type) {
22 case "network":
23 return n.data.domain;
24 case "app":
25 return n.data.label || "Service";
26 case "github":
27 return n.data.repository?.fullName || "Github";
28 case "gateway-https": {
gio29050d62025-05-16 04:49:26 +000029 if (n.data && n.data.subdomain) {
30 return `${n.data.subdomain}`;
gio48fde052025-05-14 09:48:08 +000031 } else {
32 return "HTTPS Gateway";
33 }
giod0026612025-05-08 13:00:36 +000034 }
gio48fde052025-05-14 09:48:08 +000035 case "gateway-tcp": {
gio29050d62025-05-16 04:49:26 +000036 if (n.data && n.data.subdomain) {
37 return `${n.data.subdomain}`;
gio48fde052025-05-14 09:48:08 +000038 } else {
39 return "TCP Gateway";
40 }
giod0026612025-05-08 13:00:36 +000041 }
gio48fde052025-05-14 09:48:08 +000042 case "mongodb":
43 return n.data.label || "MongoDB";
44 case "postgresql":
45 return n.data.label || "PostgreSQL";
46 case "volume":
47 return n.data.label || "Volume";
48 case undefined:
gio69148322025-06-19 23:16:12 +040049 throw new Error(`nodeLabel: Node type is undefined. Node ID: ${n.id}, Data: ${JSON.stringify(n.data)}`);
giod0026612025-05-08 13:00:36 +000050 }
gio48fde052025-05-14 09:48:08 +000051 } catch (e) {
52 console.error("opaa", e);
53 } finally {
54 console.log("done");
giod0026612025-05-08 13:00:36 +000055 }
gioa1efbad2025-05-21 07:16:45 +000056 return "Unknown Node";
gio5f2f1002025-03-20 18:38:48 +040057}
58
gio8fad76a2025-05-22 14:01:23 +000059export function nodeLabelFull(n: AppNode): string {
60 if (n.type === "gateway-https") {
61 return `https://${n.data.subdomain}.${n.data.network}`;
62 } else {
63 return nodeLabel(n);
64 }
65}
66
gio5f2f1002025-03-20 18:38:48 +040067export function nodeIsConnectable(n: AppNode, handle: string): boolean {
giod0026612025-05-08 13:00:36 +000068 switch (n.type) {
69 case "network":
70 return true;
71 case "app":
72 if (handle === "ports") {
73 return n.data !== undefined && n.data.ports !== undefined && n.data.ports.length > 0;
74 } else if (handle === "repository") {
75 if (!n.data || !n.data.repository || !n.data.repository.id) {
76 return true;
77 }
78 return false;
79 }
80 return false;
81 case "github":
82 if (n.data.repository?.id !== undefined) {
83 return true;
84 }
85 return false;
86 case "gateway-https":
87 if (handle === "subdomain") {
88 return n.data.network === undefined;
89 }
90 return n.data === undefined || n.data.https === undefined;
91 case "gateway-tcp":
92 if (handle === "subdomain") {
93 return n.data.network === undefined;
94 }
95 return true;
96 case "mongodb":
97 return true;
98 case "postgresql":
99 return true;
100 case "volume":
101 if (n.data === undefined || n.data.type === undefined) {
102 return false;
103 }
104 if (n.data.type === "ReadWriteOnce" || n.data.type === "ReadWriteOncePod") {
105 return n.data.attachedTo === undefined || n.data.attachedTo.length === 0;
106 }
107 return true;
108 case undefined:
gio69148322025-06-19 23:16:12 +0400109 throw new Error(
110 `nodeIsConnectable: Node type is undefined. Node ID: ${n.id}, Handle: ${handle}, Data: ${JSON.stringify(n.data)}`,
111 );
giod0026612025-05-08 13:00:36 +0000112 }
gio5f2f1002025-03-20 18:38:48 +0400113}
114
giob41ecae2025-04-24 08:46:50 +0000115export function nodeEnvVarNamePort(n: AppNode, portName: string): string {
giod0026612025-05-08 13:00:36 +0000116 return `DODO_SERVICE_${n.data.label.toUpperCase()}_ADDRESS_${portName.toUpperCase()}`;
giob41ecae2025-04-24 08:46:50 +0000117}
118
gio5f2f1002025-03-20 18:38:48 +0400119export function nodeEnvVarNames(n: AppNode): string[] {
giod0026612025-05-08 13:00:36 +0000120 switch (n.type) {
121 case "app":
122 return [
123 `DODO_SERVICE_${n.data.label.toUpperCase()}_ADDRESS`,
124 ...(n.data.ports || []).map((p) => nodeEnvVarNamePort(n, p.name)),
125 ];
126 case "github":
127 return [];
128 case "gateway-https":
129 return [];
130 case "gateway-tcp":
131 return [];
132 case "mongodb":
133 return [`DODO_MONGODB_${n.data.label.toUpperCase()}_URL`];
134 case "postgresql":
135 return [`DODO_POSTGRESQL_${n.data.label.toUpperCase()}_URL`];
136 case "volume":
137 return [`DODO_VOLUME_${n.data.label.toUpperCase()}_PATH`];
138 case undefined:
139 throw new Error("MUST NOT REACH");
140 default:
141 throw new Error("MUST NOT REACH");
142 }
gio5f2f1002025-03-20 18:38:48 +0400143}
144
gio5f2f1002025-03-20 18:38:48 +0400145export type MessageType = "INFO" | "WARNING" | "FATAL";
146
147export type Message = {
giod0026612025-05-08 13:00:36 +0000148 id: string;
149 type: MessageType;
150 nodeId?: string;
151 message: string;
152 onHighlight?: (state: AppState) => void;
153 onLooseHighlight?: (state: AppState) => void;
154 onClick?: (state: AppState) => void;
gio5f2f1002025-03-20 18:38:48 +0400155};
156
gio7f98e772025-05-07 11:00:14 +0000157const defaultEnv: Env = {
gioa71316d2025-05-24 09:41:36 +0400158 deployKeyPublic: undefined,
159 instanceId: undefined,
giod0026612025-05-08 13:00:36 +0000160 networks: [],
161 integrations: {
162 github: false,
gio69148322025-06-19 23:16:12 +0400163 gemini: false,
gio69ff7592025-07-03 06:27:21 +0000164 anthropic: false,
giod0026612025-05-08 13:00:36 +0000165 },
gio3a921b82025-05-10 07:36:09 +0000166 services: [],
gio3ed59592025-05-14 16:51:09 +0000167 user: {
168 id: "",
169 username: "",
170 },
giob77cb932025-05-19 09:37:14 +0000171 access: [],
gio7f98e772025-05-07 11:00:14 +0000172};
173
gio5f2f1002025-03-20 18:38:48 +0400174export type Project = {
giod0026612025-05-08 13:00:36 +0000175 id: string;
176 name: string;
177};
gio5f2f1002025-03-20 18:38:48 +0400178
gio7f98e772025-05-07 11:00:14 +0000179export type IntegrationsConfig = {
giod0026612025-05-08 13:00:36 +0000180 github: boolean;
gio7f98e772025-05-07 11:00:14 +0000181};
182
183type NodeUpdate<T extends NodeType> = DeepPartial<Extract<AppNode, { type: T }>>;
184type NodeDataUpdate<T extends NodeType> = DeepPartial<Extract<AppNode, { type: T }>["data"]>;
185
gioaf8db832025-05-13 14:43:05 +0000186type Viewport = {
187 transformX: number;
188 transformY: number;
189 transformZoom: number;
190 width: number;
191 height: number;
192};
193
gio918780d2025-05-22 08:24:41 +0000194let refreshEnvIntervalId: number | null = null;
195
gio5f2f1002025-03-20 18:38:48 +0400196export type AppState = {
giod0026612025-05-08 13:00:36 +0000197 projectId: string | undefined;
gio818da4e2025-05-12 14:45:35 +0000198 mode: "edit" | "deploy";
giod0026612025-05-08 13:00:36 +0000199 projects: Project[];
200 nodes: AppNode[];
201 edges: Edge[];
gio359a6852025-05-14 03:38:24 +0000202 zoom: ReactFlowViewport;
giod0026612025-05-08 13:00:36 +0000203 categories: Category[];
204 messages: Message[];
205 env: Env;
gioaf8db832025-05-13 14:43:05 +0000206 viewport: Viewport;
207 setViewport: (viewport: Viewport) => void;
giod0026612025-05-08 13:00:36 +0000208 githubService: GitHubService | null;
gioa71316d2025-05-24 09:41:36 +0400209 githubRepositories: GitHubRepository[];
210 githubRepositoriesLoading: boolean;
211 githubRepositoriesError: string | null;
giod0026612025-05-08 13:00:36 +0000212 setHighlightCategory: (name: string, active: boolean) => void;
213 onNodesChange: OnNodesChange<AppNode>;
214 onEdgesChange: OnEdgesChange;
215 onConnect: OnConnect;
gioaf8db832025-05-13 14:43:05 +0000216 addNode: (node: Omit<AppNode, "position">) => void;
giod0026612025-05-08 13:00:36 +0000217 setNodes: (nodes: AppNode[]) => void;
218 setEdges: (edges: Edge[]) => void;
gio818da4e2025-05-12 14:45:35 +0000219 setProject: (projectId: string | undefined) => Promise<void>;
220 setMode: (mode: "edit" | "deploy") => void;
giod0026612025-05-08 13:00:36 +0000221 updateNode: <T extends NodeType>(id: string, node: NodeUpdate<T>) => void;
222 updateNodeData: <T extends NodeType>(id: string, data: NodeDataUpdate<T>) => void;
223 replaceEdge: (c: Connection, id?: string) => void;
224 refreshEnv: () => Promise<void>;
gioa71316d2025-05-24 09:41:36 +0400225 fetchGithubRepositories: () => Promise<void>;
gio5f2f1002025-03-20 18:38:48 +0400226};
227
228const projectIdSelector = (state: AppState) => state.projectId;
229const categoriesSelector = (state: AppState) => state.categories;
230const messagesSelector = (state: AppState) => state.messages;
231const envSelector = (state: AppState) => state.env;
gio359a6852025-05-14 03:38:24 +0000232const zoomSelector = (state: AppState) => state.zoom;
gioa71316d2025-05-24 09:41:36 +0400233const githubRepositoriesSelector = (state: AppState) => state.githubRepositories;
234const githubRepositoriesLoadingSelector = (state: AppState) => state.githubRepositoriesLoading;
235const githubRepositoriesErrorSelector = (state: AppState) => state.githubRepositoriesError;
gioaf8db832025-05-13 14:43:05 +0000236
gio359a6852025-05-14 03:38:24 +0000237export function useZoom(): ReactFlowViewport {
238 return useStateStore(zoomSelector);
gioaf8db832025-05-13 14:43:05 +0000239}
gio5f2f1002025-03-20 18:38:48 +0400240
241export function useProjectId(): string | undefined {
giod0026612025-05-08 13:00:36 +0000242 return useStateStore(projectIdSelector);
gio5f2f1002025-03-20 18:38:48 +0400243}
244
giob45b1862025-05-20 11:42:20 +0000245export function useSetProject(): (projectId: string | undefined) => void {
246 return useStateStore((state) => state.setProject);
247}
248
gio5f2f1002025-03-20 18:38:48 +0400249export function useCategories(): Category[] {
giod0026612025-05-08 13:00:36 +0000250 return useStateStore(categoriesSelector);
gio5f2f1002025-03-20 18:38:48 +0400251}
252
253export function useMessages(): Message[] {
giod0026612025-05-08 13:00:36 +0000254 return useStateStore(messagesSelector);
gio5f2f1002025-03-20 18:38:48 +0400255}
256
257export function useNodeMessages(id: string): Message[] {
giod0026612025-05-08 13:00:36 +0000258 return useMessages().filter((m) => m.nodeId === id);
gio5f2f1002025-03-20 18:38:48 +0400259}
260
261export function useNodeLabel(id: string): string {
giod0026612025-05-08 13:00:36 +0000262 return nodeLabel(useNodes<AppNode>().find((n) => n.id === id)!);
gio5f2f1002025-03-20 18:38:48 +0400263}
264
265export function useNodePortName(id: string, portId: string): string {
giod0026612025-05-08 13:00:36 +0000266 return (useNodes<AppNode>().find((n) => n.id === id)!.data.ports || []).find((p) => p.id === portId)!.name;
gio5f2f1002025-03-20 18:38:48 +0400267}
268
gio5f2f1002025-03-20 18:38:48 +0400269export function useEnv(): Env {
giod0026612025-05-08 13:00:36 +0000270 return useStateStore(envSelector);
gio7f98e772025-05-07 11:00:14 +0000271}
272
gio74c6f752025-07-05 04:10:58 +0000273export function useAgents(): AgentAccess[] {
giocc5ce582025-06-25 07:45:21 +0400274 return useStateStore(envSelector).access.filter(
gio74c6f752025-07-05 04:10:58 +0000275 (acc): acc is AgentAccess => acc.type === "https" && acc.agentName != null,
giocc5ce582025-06-25 07:45:21 +0400276 );
277}
278
gio74c6f752025-07-05 04:10:58 +0000279export function useLeadAgent(): AgentAccess | undefined {
280 const agents = useAgents();
281 return agents.find((a) => a.agentName === "dodo") || agents[0];
282}
283
gio69148322025-06-19 23:16:12 +0400284export function useGithubService(): boolean {
285 return useStateStore(envSelector).integrations.github;
286}
287
288export function useGeminiService(): boolean {
289 return useStateStore(envSelector).integrations.gemini;
gio5f2f1002025-03-20 18:38:48 +0400290}
291
gio69ff7592025-07-03 06:27:21 +0000292export function useAnthropicService(): boolean {
293 return useStateStore(envSelector).integrations.anthropic;
294}
295
gioa71316d2025-05-24 09:41:36 +0400296export function useGithubRepositories(): GitHubRepository[] {
297 return useStateStore(githubRepositoriesSelector);
298}
299
300export function useGithubRepositoriesLoading(): boolean {
301 return useStateStore(githubRepositoriesLoadingSelector);
302}
303
304export function useGithubRepositoriesError(): string | null {
305 return useStateStore(githubRepositoriesErrorSelector);
306}
307
308export function useFetchGithubRepositories(): () => Promise<void> {
309 return useStateStore((state) => state.fetchGithubRepositories);
310}
311
gio3ec94242025-05-16 12:46:57 +0000312export function useMode(): "edit" | "deploy" {
313 return useStateStore((state) => state.mode);
314}
315
gio5f2f1002025-03-20 18:38:48 +0400316const v: Validator = CreateValidators();
317
gioaf8db832025-05-13 14:43:05 +0000318function getRandomPosition({ width, height, transformX, transformY, transformZoom }: Viewport): XYPosition {
319 const zoomMultiplier = 1 / transformZoom;
320 const realWidth = width * zoomMultiplier;
321 const realHeight = height * zoomMultiplier;
322 const paddingMultiplier = 0.8;
323 const ret = {
324 x: -transformX * zoomMultiplier + Math.random() * realWidth * paddingMultiplier,
325 y: -transformY * zoomMultiplier + Math.random() * realHeight * paddingMultiplier,
326 };
327 return ret;
328}
329
gio3d0bf032025-06-05 06:57:26 +0000330export const useStateStore = create<AppState>((setOg, get): AppState => {
331 const set = (state: Partial<AppState>) => {
332 setOg(state);
333 };
giod0026612025-05-08 13:00:36 +0000334 const setN = (nodes: AppNode[]) => {
gio34193052025-07-03 03:55:11 +0000335 const env = get().env;
336 console.log("---env", env);
gio4b9b58a2025-05-12 11:46:08 +0000337 set({
giod0026612025-05-08 13:00:36 +0000338 nodes,
gio34193052025-07-03 03:55:11 +0000339 messages: v(nodes, env),
gio4b9b58a2025-05-12 11:46:08 +0000340 });
341 };
342
gio918780d2025-05-22 08:24:41 +0000343 const startRefreshEnvInterval = () => {
344 if (refreshEnvIntervalId) {
345 clearInterval(refreshEnvIntervalId);
346 }
347 if (get().projectId && typeof document !== "undefined" && document.visibilityState === "visible") {
348 console.log("Starting refreshEnv interval for project:", get().projectId);
349 refreshEnvIntervalId = setInterval(async () => {
350 if (get().projectId && typeof document !== "undefined" && document.visibilityState === "visible") {
351 console.log("Interval: Calling refreshEnv for project:", get().projectId);
352 await get().refreshEnv();
353 } else if (refreshEnvIntervalId) {
354 console.log(
355 "Interval: Conditions not met (project removed or tab hidden), stopping interval from inside.",
356 );
357 clearInterval(refreshEnvIntervalId);
358 refreshEnvIntervalId = null;
359 }
360 }, 5000) as unknown as number;
361 } else {
362 console.log(
363 "Not starting refreshEnv interval. Project ID:",
364 get().projectId,
365 "Visibility:",
366 typeof document !== "undefined" ? document.visibilityState : "SSR",
367 );
368 }
369 };
370
371 const stopRefreshEnvInterval = () => {
372 if (refreshEnvIntervalId) {
373 console.log("Stopping refreshEnv interval for project:", get().projectId);
374 clearInterval(refreshEnvIntervalId);
375 refreshEnvIntervalId = null;
376 }
377 };
378
379 if (typeof document !== "undefined") {
380 document.addEventListener("visibilitychange", () => {
381 if (document.visibilityState === "visible") {
382 console.log("Tab became visible, attempting to start refreshEnv interval.");
383 startRefreshEnvInterval();
384 } else {
385 console.log("Tab became hidden, stopping refreshEnv interval.");
386 stopRefreshEnvInterval();
387 }
388 });
389 }
390
gio48fde052025-05-14 09:48:08 +0000391 const injectNetworkNodes = () => {
392 const newNetworks = get().env.networks.filter(
393 (x) => !get().nodes.some((n) => n.type === "network" && n.data.domain === x.domain),
394 );
395 newNetworks.forEach((n) => {
396 get().addNode({
397 id: n.domain,
398 type: "network",
399 connectable: true,
400 data: {
401 domain: n.domain,
402 label: n.domain,
403 envVars: [],
404 ports: [],
405 state: "success", // TODO(gio): monitor network health
406 },
407 });
408 console.log("added network", n.domain);
409 });
410 };
411
gio4b9b58a2025-05-12 11:46:08 +0000412 const restoreSaved = async () => {
gio818da4e2025-05-12 14:45:35 +0000413 const { projectId } = get();
414 const resp = await fetch(`/api/project/${projectId}/saved/${get().mode === "deploy" ? "deploy" : "draft"}`, {
gio4b9b58a2025-05-12 11:46:08 +0000415 method: "GET",
416 });
417 const inst = await resp.json();
gioc31bf142025-06-16 07:48:20 +0000418 setN(inst.state.nodes);
419 set({ edges: inst.state.edges });
gio48fde052025-05-14 09:48:08 +0000420 injectNetworkNodes();
gio359a6852025-05-14 03:38:24 +0000421 if (
gioc31bf142025-06-16 07:48:20 +0000422 get().zoom.x !== inst.state.viewport.x ||
423 get().zoom.y !== inst.state.viewport.y ||
424 get().zoom.zoom !== inst.state.viewport.zoom
gio359a6852025-05-14 03:38:24 +0000425 ) {
gioc31bf142025-06-16 07:48:20 +0000426 set({ zoom: inst.state.viewport });
gio359a6852025-05-14 03:38:24 +0000427 }
giod0026612025-05-08 13:00:36 +0000428 };
gio7f98e772025-05-07 11:00:14 +0000429
giod0026612025-05-08 13:00:36 +0000430 function updateNodeData<T extends NodeType>(id: string, data: NodeDataUpdate<T>): void {
431 setN(
432 get().nodes.map((n) => {
433 if (n.id === id) {
434 return {
435 ...n,
436 data: {
437 ...n.data,
438 ...data,
439 },
440 } as Extract<AppNode, { type: T }>;
441 }
442 return n;
443 }),
444 );
445 }
gio7f98e772025-05-07 11:00:14 +0000446
giod0026612025-05-08 13:00:36 +0000447 function updateNode<T extends NodeType>(id: string, node: NodeUpdate<T>): void {
448 setN(
449 get().nodes.map((n) => {
450 if (n.id === id) {
451 return {
452 ...n,
453 ...node,
454 } as Extract<AppNode, { type: T }>;
455 }
456 return n;
457 }),
458 );
459 }
gio7f98e772025-05-07 11:00:14 +0000460
giod0026612025-05-08 13:00:36 +0000461 function onConnect(c: Connection) {
462 const { nodes, edges } = get();
463 set({
464 edges: addEdge(c, edges),
465 });
466 const sn = nodes.filter((n) => n.id === c.source)[0]!;
467 const tn = nodes.filter((n) => n.id === c.target)[0]!;
468 if (tn.type === "network") {
469 if (sn.type === "gateway-https") {
470 updateNodeData<"gateway-https">(sn.id, {
471 network: tn.data.domain,
472 });
473 } else if (sn.type === "gateway-tcp") {
474 updateNodeData<"gateway-tcp">(sn.id, {
475 network: tn.data.domain,
476 });
477 }
478 }
479 if (tn.type === "app") {
480 if (c.sourceHandle === "env_var" && c.targetHandle === "env_var") {
481 const sourceEnvVars = nodeEnvVarNames(sn);
482 if (sourceEnvVars.length === 0) {
gio69148322025-06-19 23:16:12 +0400483 throw new Error(
484 `onConnect (env_var): Source node ${sn.id} (type: ${sn.type}) has no env vars to connect from.`,
485 );
giod0026612025-05-08 13:00:36 +0000486 }
487 const id = uuidv4();
488 if (sourceEnvVars.length === 1) {
489 updateNode<"app">(c.target, {
490 ...tn,
491 data: {
492 ...tn.data,
493 envVars: [
494 ...(tn.data.envVars || []),
495 {
496 id: id,
497 source: c.source,
498 name: sourceEnvVars[0],
499 isEditting: false,
500 },
501 ],
502 },
503 });
504 } else {
505 updateNode<"app">(c.target, {
506 ...tn,
507 data: {
508 ...tn.data,
509 envVars: [
510 ...(tn.data.envVars || []),
511 {
512 id: id,
513 source: c.source,
514 },
515 ],
516 },
517 });
518 }
519 }
520 if (c.sourceHandle === "ports" && c.targetHandle === "env_var") {
521 const sourcePorts = sn.data.ports || [];
522 const id = uuidv4();
523 if (sourcePorts.length === 1) {
524 updateNode<"app">(c.target, {
525 ...tn,
526 data: {
527 ...tn.data,
528 envVars: [
529 ...(tn.data.envVars || []),
530 {
531 id: id,
532 source: c.source,
533 name: nodeEnvVarNamePort(sn, sourcePorts[0].name),
534 portId: sourcePorts[0].id,
535 isEditting: false,
536 },
537 ],
538 },
539 });
540 }
541 }
gio3d0bf032025-06-05 06:57:26 +0000542 if (c.targetHandle === "repository") {
543 const sourceNode = nodes.find((n) => n.id === c.source);
544 if (sourceNode && sourceNode.type === "github" && sourceNode.data.repository) {
545 updateNodeData<"app">(tn.id, {
546 repository: {
547 id: sourceNode.data.repository.id,
548 repoNodeId: c.source,
549 },
550 });
551 }
552 }
giod0026612025-05-08 13:00:36 +0000553 }
554 if (c.sourceHandle === "volume") {
555 updateNodeData<"volume">(c.source, {
556 attachedTo: ((sn as VolumeNode).data.attachedTo || []).concat(c.source),
557 });
558 }
559 if (c.targetHandle === "volume") {
560 if (tn.type === "postgresql" || tn.type === "mongodb") {
561 updateNodeData(c.target, {
562 volumeId: c.source,
563 });
564 }
565 }
566 if (c.targetHandle === "https") {
567 if ((sn.data.ports || []).length === 1) {
568 updateNodeData<"gateway-https">(c.target, {
569 https: {
570 serviceId: c.source,
571 portId: sn.data.ports![0].id,
572 },
573 });
574 } else {
575 updateNodeData<"gateway-https">(c.target, {
576 https: {
577 serviceId: c.source,
578 portId: "", // TODO(gio)
579 },
580 });
581 }
582 }
583 if (c.targetHandle === "tcp") {
584 const td = tn.data as GatewayTCPData;
585 if ((sn.data.ports || []).length === 1) {
586 updateNodeData<"gateway-tcp">(c.target, {
587 exposed: (td.exposed || []).concat({
588 serviceId: c.source,
589 portId: sn.data.ports![0].id,
590 }),
591 });
592 } else {
593 updateNodeData<"gateway-tcp">(c.target, {
594 selected: {
595 serviceId: c.source,
596 portId: undefined,
597 },
598 });
599 }
600 }
601 if (sn.type === "app") {
602 if (c.sourceHandle === "ports") {
603 updateNodeData<"app">(sn.id, {
604 isChoosingPortToConnect: true,
605 });
606 }
607 }
giod0026612025-05-08 13:00:36 +0000608 }
gioa71316d2025-05-24 09:41:36 +0400609
610 const fetchGithubRepositories = async () => {
611 const { githubService, projectId } = get();
612 if (!githubService || !projectId) {
613 set({
614 githubRepositories: [],
615 githubRepositoriesError: "GitHub service or Project ID not available.",
616 githubRepositoriesLoading: false,
617 });
618 return;
619 }
620
621 set({ githubRepositoriesLoading: true, githubRepositoriesError: null });
622 try {
623 const repos = await githubService.getRepositories();
624 set({ githubRepositories: repos, githubRepositoriesLoading: false });
625 } catch (error) {
626 console.error("Failed to fetch GitHub repositories in store:", error);
627 const errorMessage = error instanceof Error ? error.message : "Unknown error fetching repositories";
628 set({ githubRepositories: [], githubRepositoriesError: errorMessage, githubRepositoriesLoading: false });
629 }
630 };
631
giod0026612025-05-08 13:00:36 +0000632 return {
633 projectId: undefined,
gio818da4e2025-05-12 14:45:35 +0000634 mode: "edit",
giod0026612025-05-08 13:00:36 +0000635 projects: [],
636 nodes: [],
637 edges: [],
638 categories: defaultCategories,
gio34193052025-07-03 03:55:11 +0000639 messages: [],
giod0026612025-05-08 13:00:36 +0000640 env: defaultEnv,
gioaf8db832025-05-13 14:43:05 +0000641 viewport: {
642 transformX: 0,
643 transformY: 0,
644 transformZoom: 1,
645 width: 800,
646 height: 600,
647 },
gio359a6852025-05-14 03:38:24 +0000648 zoom: {
649 x: 0,
650 y: 0,
651 zoom: 1,
652 },
giod0026612025-05-08 13:00:36 +0000653 githubService: null,
gioa71316d2025-05-24 09:41:36 +0400654 githubRepositories: [],
655 githubRepositoriesLoading: false,
656 githubRepositoriesError: null,
gioaf8db832025-05-13 14:43:05 +0000657 setViewport: (viewport) => {
658 const { viewport: vp } = get();
659 if (
660 viewport.transformX !== vp.transformX ||
661 viewport.transformY !== vp.transformY ||
662 viewport.transformZoom !== vp.transformZoom ||
663 viewport.width !== vp.width ||
664 viewport.height !== vp.height
665 ) {
666 set({ viewport });
667 }
668 },
giod0026612025-05-08 13:00:36 +0000669 setHighlightCategory: (name, active) => {
670 set({
671 categories: get().categories.map((c) => {
672 if (c.title.toLowerCase() !== name.toLowerCase()) {
673 return c;
674 } else {
675 return {
676 ...c,
677 active,
678 };
679 }
680 }),
681 });
682 },
683 onNodesChange: (changes) => {
684 const nodes = applyNodeChanges(changes, get().nodes);
685 setN(nodes);
686 },
687 onEdgesChange: (changes) => {
688 set({
689 edges: applyEdgeChanges(changes, get().edges),
690 });
691 },
gioaf8db832025-05-13 14:43:05 +0000692 addNode: (node) => {
693 const { viewport, nodes } = get();
694 setN(
695 nodes.concat({
696 ...node,
697 position: getRandomPosition(viewport),
gioa1efbad2025-05-21 07:16:45 +0000698 } as AppNode),
gioaf8db832025-05-13 14:43:05 +0000699 );
700 },
giod0026612025-05-08 13:00:36 +0000701 setNodes: (nodes) => {
702 setN(nodes);
703 },
704 setEdges: (edges) => {
705 set({ edges });
706 },
707 replaceEdge: (c, id) => {
708 let change: EdgeChange;
709 if (id === undefined) {
710 change = {
711 type: "add",
712 item: {
713 id: uuidv4(),
714 ...c,
715 },
716 };
717 onConnect(c);
718 } else {
719 change = {
720 type: "replace",
721 id,
722 item: {
723 id,
724 ...c,
725 },
726 };
727 }
728 set({
729 edges: applyEdgeChanges([change], get().edges),
730 });
731 },
732 updateNode,
733 updateNodeData,
734 onConnect,
735 refreshEnv: async () => {
736 const projectId = get().projectId;
737 let env: Env = defaultEnv;
giod0026612025-05-08 13:00:36 +0000738 try {
739 if (projectId) {
740 const response = await fetch(`/api/project/${projectId}/env`);
741 if (response.ok) {
742 const data = await response.json();
743 const result = envSchema.safeParse(data);
744 if (result.success) {
745 env = result.data;
746 } else {
747 console.error("Invalid env data:", result.error);
748 }
749 }
750 }
751 } catch (error) {
752 console.error("Failed to fetch integrations:", error);
753 } finally {
gioa71316d2025-05-24 09:41:36 +0400754 const oldEnv = get().env;
755 const oldGithubIntegrationStatus = oldEnv.integrations.github;
756 if (JSON.stringify(oldEnv) !== JSON.stringify(env)) {
gio4b9b58a2025-05-12 11:46:08 +0000757 set({ env });
gio48fde052025-05-14 09:48:08 +0000758 injectNetworkNodes();
gioa71316d2025-05-24 09:41:36 +0400759 let ghService = null;
gio4b9b58a2025-05-12 11:46:08 +0000760 if (env.integrations.github) {
gioa71316d2025-05-24 09:41:36 +0400761 ghService = new GitHubServiceImpl(projectId!);
762 }
763 if (get().githubService !== ghService || (ghService && !get().githubService)) {
764 set({ githubService: ghService });
765 }
766 if (
767 ghService &&
768 (oldGithubIntegrationStatus !== env.integrations.github || !oldEnv.integrations.github)
769 ) {
770 get().fetchGithubRepositories();
771 }
772 if (!env.integrations.github) {
773 set({
774 githubRepositories: [],
775 githubRepositoriesError: null,
776 githubRepositoriesLoading: false,
777 });
gio4b9b58a2025-05-12 11:46:08 +0000778 }
giod0026612025-05-08 13:00:36 +0000779 }
780 }
781 },
gio818da4e2025-05-12 14:45:35 +0000782 setMode: (mode) => {
783 set({ mode });
784 },
785 setProject: async (projectId) => {
gio918780d2025-05-22 08:24:41 +0000786 const currentProjectId = get().projectId;
787 if (projectId === currentProjectId) {
gio359a6852025-05-14 03:38:24 +0000788 return;
789 }
gio918780d2025-05-22 08:24:41 +0000790 stopRefreshEnvInterval();
giod0026612025-05-08 13:00:36 +0000791 set({
792 projectId,
gioa71316d2025-05-24 09:41:36 +0400793 githubRepositories: [],
794 githubRepositoriesLoading: false,
795 githubRepositoriesError: null,
giod0026612025-05-08 13:00:36 +0000796 });
797 if (projectId) {
gio818da4e2025-05-12 14:45:35 +0000798 await get().refreshEnv();
gioa71316d2025-05-24 09:41:36 +0400799 if (get().env.instanceId) {
gio818da4e2025-05-12 14:45:35 +0000800 set({ mode: "deploy" });
801 } else {
802 set({ mode: "edit" });
803 }
gio4b9b58a2025-05-12 11:46:08 +0000804 restoreSaved();
gio918780d2025-05-22 08:24:41 +0000805 startRefreshEnvInterval();
gio4b9b58a2025-05-12 11:46:08 +0000806 } else {
807 set({
808 nodes: [],
809 edges: [],
gio918780d2025-05-22 08:24:41 +0000810 env: defaultEnv,
811 githubService: null,
gioa71316d2025-05-24 09:41:36 +0400812 githubRepositories: [],
813 githubRepositoriesLoading: false,
814 githubRepositoriesError: null,
gio4b9b58a2025-05-12 11:46:08 +0000815 });
giod0026612025-05-08 13:00:36 +0000816 }
817 },
gioa71316d2025-05-24 09:41:36 +0400818 fetchGithubRepositories: fetchGithubRepositories,
giod0026612025-05-08 13:00:36 +0000819 };
gio5f2f1002025-03-20 18:38:48 +0400820});