blob: b5eac422007eb2ec56c9d7ebe70654b892100835 [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";
giocc5ce582025-06-25 07:45:21 +040017import { AppNode, Env, NodeType, VolumeNode, GatewayTCPData, envSchema, Access } 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,
giod0026612025-05-08 13:00:36 +0000164 },
gio3a921b82025-05-10 07:36:09 +0000165 services: [],
gio3ed59592025-05-14 16:51:09 +0000166 user: {
167 id: "",
168 username: "",
169 },
giob77cb932025-05-19 09:37:14 +0000170 access: [],
gio7f98e772025-05-07 11:00:14 +0000171};
172
gio5f2f1002025-03-20 18:38:48 +0400173export type Project = {
giod0026612025-05-08 13:00:36 +0000174 id: string;
175 name: string;
176};
gio5f2f1002025-03-20 18:38:48 +0400177
gio7f98e772025-05-07 11:00:14 +0000178export type IntegrationsConfig = {
giod0026612025-05-08 13:00:36 +0000179 github: boolean;
gio7f98e772025-05-07 11:00:14 +0000180};
181
182type NodeUpdate<T extends NodeType> = DeepPartial<Extract<AppNode, { type: T }>>;
183type NodeDataUpdate<T extends NodeType> = DeepPartial<Extract<AppNode, { type: T }>["data"]>;
184
gioaf8db832025-05-13 14:43:05 +0000185type Viewport = {
186 transformX: number;
187 transformY: number;
188 transformZoom: number;
189 width: number;
190 height: number;
191};
192
gio918780d2025-05-22 08:24:41 +0000193let refreshEnvIntervalId: number | null = null;
194
gio5f2f1002025-03-20 18:38:48 +0400195export type AppState = {
giod0026612025-05-08 13:00:36 +0000196 projectId: string | undefined;
gio818da4e2025-05-12 14:45:35 +0000197 mode: "edit" | "deploy";
giod0026612025-05-08 13:00:36 +0000198 projects: Project[];
199 nodes: AppNode[];
200 edges: Edge[];
gio359a6852025-05-14 03:38:24 +0000201 zoom: ReactFlowViewport;
giod0026612025-05-08 13:00:36 +0000202 categories: Category[];
203 messages: Message[];
204 env: Env;
gioaf8db832025-05-13 14:43:05 +0000205 viewport: Viewport;
206 setViewport: (viewport: Viewport) => void;
giod0026612025-05-08 13:00:36 +0000207 githubService: GitHubService | null;
gioa71316d2025-05-24 09:41:36 +0400208 githubRepositories: GitHubRepository[];
209 githubRepositoriesLoading: boolean;
210 githubRepositoriesError: string | null;
giod0026612025-05-08 13:00:36 +0000211 setHighlightCategory: (name: string, active: boolean) => void;
212 onNodesChange: OnNodesChange<AppNode>;
213 onEdgesChange: OnEdgesChange;
214 onConnect: OnConnect;
gioaf8db832025-05-13 14:43:05 +0000215 addNode: (node: Omit<AppNode, "position">) => void;
giod0026612025-05-08 13:00:36 +0000216 setNodes: (nodes: AppNode[]) => void;
217 setEdges: (edges: Edge[]) => void;
gio818da4e2025-05-12 14:45:35 +0000218 setProject: (projectId: string | undefined) => Promise<void>;
219 setMode: (mode: "edit" | "deploy") => void;
giod0026612025-05-08 13:00:36 +0000220 updateNode: <T extends NodeType>(id: string, node: NodeUpdate<T>) => void;
221 updateNodeData: <T extends NodeType>(id: string, data: NodeDataUpdate<T>) => void;
222 replaceEdge: (c: Connection, id?: string) => void;
223 refreshEnv: () => Promise<void>;
gioa71316d2025-05-24 09:41:36 +0400224 fetchGithubRepositories: () => Promise<void>;
gio5f2f1002025-03-20 18:38:48 +0400225};
226
227const projectIdSelector = (state: AppState) => state.projectId;
228const categoriesSelector = (state: AppState) => state.categories;
229const messagesSelector = (state: AppState) => state.messages;
230const envSelector = (state: AppState) => state.env;
gio359a6852025-05-14 03:38:24 +0000231const zoomSelector = (state: AppState) => state.zoom;
gioa71316d2025-05-24 09:41:36 +0400232const githubRepositoriesSelector = (state: AppState) => state.githubRepositories;
233const githubRepositoriesLoadingSelector = (state: AppState) => state.githubRepositoriesLoading;
234const githubRepositoriesErrorSelector = (state: AppState) => state.githubRepositoriesError;
gioaf8db832025-05-13 14:43:05 +0000235
gio359a6852025-05-14 03:38:24 +0000236export function useZoom(): ReactFlowViewport {
237 return useStateStore(zoomSelector);
gioaf8db832025-05-13 14:43:05 +0000238}
gio5f2f1002025-03-20 18:38:48 +0400239
240export function useProjectId(): string | undefined {
giod0026612025-05-08 13:00:36 +0000241 return useStateStore(projectIdSelector);
gio5f2f1002025-03-20 18:38:48 +0400242}
243
giob45b1862025-05-20 11:42:20 +0000244export function useSetProject(): (projectId: string | undefined) => void {
245 return useStateStore((state) => state.setProject);
246}
247
gio5f2f1002025-03-20 18:38:48 +0400248export function useCategories(): Category[] {
giod0026612025-05-08 13:00:36 +0000249 return useStateStore(categoriesSelector);
gio5f2f1002025-03-20 18:38:48 +0400250}
251
252export function useMessages(): Message[] {
giod0026612025-05-08 13:00:36 +0000253 return useStateStore(messagesSelector);
gio5f2f1002025-03-20 18:38:48 +0400254}
255
256export function useNodeMessages(id: string): Message[] {
giod0026612025-05-08 13:00:36 +0000257 return useMessages().filter((m) => m.nodeId === id);
gio5f2f1002025-03-20 18:38:48 +0400258}
259
260export function useNodeLabel(id: string): string {
giod0026612025-05-08 13:00:36 +0000261 return nodeLabel(useNodes<AppNode>().find((n) => n.id === id)!);
gio5f2f1002025-03-20 18:38:48 +0400262}
263
264export function useNodePortName(id: string, portId: string): string {
giod0026612025-05-08 13:00:36 +0000265 return (useNodes<AppNode>().find((n) => n.id === id)!.data.ports || []).find((p) => p.id === portId)!.name;
gio5f2f1002025-03-20 18:38:48 +0400266}
267
gio5f2f1002025-03-20 18:38:48 +0400268export function useEnv(): Env {
giod0026612025-05-08 13:00:36 +0000269 return useStateStore(envSelector);
gio7f98e772025-05-07 11:00:14 +0000270}
271
giocc5ce582025-06-25 07:45:21 +0400272export function useAgents(): Extract<Access, { type: "https" }>[] {
273 return useStateStore(envSelector).access.filter(
274 (acc): acc is Extract<Access, { type: "https" }> => acc.type === "https" && acc.agentName != null,
275 );
276}
277
gio69148322025-06-19 23:16:12 +0400278export function useGithubService(): boolean {
279 return useStateStore(envSelector).integrations.github;
280}
281
282export function useGeminiService(): boolean {
283 return useStateStore(envSelector).integrations.gemini;
gio5f2f1002025-03-20 18:38:48 +0400284}
285
gioa71316d2025-05-24 09:41:36 +0400286export function useGithubRepositories(): GitHubRepository[] {
287 return useStateStore(githubRepositoriesSelector);
288}
289
290export function useGithubRepositoriesLoading(): boolean {
291 return useStateStore(githubRepositoriesLoadingSelector);
292}
293
294export function useGithubRepositoriesError(): string | null {
295 return useStateStore(githubRepositoriesErrorSelector);
296}
297
298export function useFetchGithubRepositories(): () => Promise<void> {
299 return useStateStore((state) => state.fetchGithubRepositories);
300}
301
gio3ec94242025-05-16 12:46:57 +0000302export function useMode(): "edit" | "deploy" {
303 return useStateStore((state) => state.mode);
304}
305
gio5f2f1002025-03-20 18:38:48 +0400306const v: Validator = CreateValidators();
307
gioaf8db832025-05-13 14:43:05 +0000308function getRandomPosition({ width, height, transformX, transformY, transformZoom }: Viewport): XYPosition {
309 const zoomMultiplier = 1 / transformZoom;
310 const realWidth = width * zoomMultiplier;
311 const realHeight = height * zoomMultiplier;
312 const paddingMultiplier = 0.8;
313 const ret = {
314 x: -transformX * zoomMultiplier + Math.random() * realWidth * paddingMultiplier,
315 y: -transformY * zoomMultiplier + Math.random() * realHeight * paddingMultiplier,
316 };
317 return ret;
318}
319
gio3d0bf032025-06-05 06:57:26 +0000320export const useStateStore = create<AppState>((setOg, get): AppState => {
321 const set = (state: Partial<AppState>) => {
322 setOg(state);
323 };
giod0026612025-05-08 13:00:36 +0000324 const setN = (nodes: AppNode[]) => {
gio4b9b58a2025-05-12 11:46:08 +0000325 set({
giod0026612025-05-08 13:00:36 +0000326 nodes,
gio5cf364c2025-05-08 16:01:21 +0000327 messages: v(nodes),
gio4b9b58a2025-05-12 11:46:08 +0000328 });
329 };
330
gio918780d2025-05-22 08:24:41 +0000331 const startRefreshEnvInterval = () => {
332 if (refreshEnvIntervalId) {
333 clearInterval(refreshEnvIntervalId);
334 }
335 if (get().projectId && typeof document !== "undefined" && document.visibilityState === "visible") {
336 console.log("Starting refreshEnv interval for project:", get().projectId);
337 refreshEnvIntervalId = setInterval(async () => {
338 if (get().projectId && typeof document !== "undefined" && document.visibilityState === "visible") {
339 console.log("Interval: Calling refreshEnv for project:", get().projectId);
340 await get().refreshEnv();
341 } else if (refreshEnvIntervalId) {
342 console.log(
343 "Interval: Conditions not met (project removed or tab hidden), stopping interval from inside.",
344 );
345 clearInterval(refreshEnvIntervalId);
346 refreshEnvIntervalId = null;
347 }
348 }, 5000) as unknown as number;
349 } else {
350 console.log(
351 "Not starting refreshEnv interval. Project ID:",
352 get().projectId,
353 "Visibility:",
354 typeof document !== "undefined" ? document.visibilityState : "SSR",
355 );
356 }
357 };
358
359 const stopRefreshEnvInterval = () => {
360 if (refreshEnvIntervalId) {
361 console.log("Stopping refreshEnv interval for project:", get().projectId);
362 clearInterval(refreshEnvIntervalId);
363 refreshEnvIntervalId = null;
364 }
365 };
366
367 if (typeof document !== "undefined") {
368 document.addEventListener("visibilitychange", () => {
369 if (document.visibilityState === "visible") {
370 console.log("Tab became visible, attempting to start refreshEnv interval.");
371 startRefreshEnvInterval();
372 } else {
373 console.log("Tab became hidden, stopping refreshEnv interval.");
374 stopRefreshEnvInterval();
375 }
376 });
377 }
378
gio48fde052025-05-14 09:48:08 +0000379 const injectNetworkNodes = () => {
380 const newNetworks = get().env.networks.filter(
381 (x) => !get().nodes.some((n) => n.type === "network" && n.data.domain === x.domain),
382 );
383 newNetworks.forEach((n) => {
384 get().addNode({
385 id: n.domain,
386 type: "network",
387 connectable: true,
388 data: {
389 domain: n.domain,
390 label: n.domain,
391 envVars: [],
392 ports: [],
393 state: "success", // TODO(gio): monitor network health
394 },
395 });
396 console.log("added network", n.domain);
397 });
398 };
399
gio4b9b58a2025-05-12 11:46:08 +0000400 const restoreSaved = async () => {
gio818da4e2025-05-12 14:45:35 +0000401 const { projectId } = get();
402 const resp = await fetch(`/api/project/${projectId}/saved/${get().mode === "deploy" ? "deploy" : "draft"}`, {
gio4b9b58a2025-05-12 11:46:08 +0000403 method: "GET",
404 });
405 const inst = await resp.json();
gioc31bf142025-06-16 07:48:20 +0000406 setN(inst.state.nodes);
407 set({ edges: inst.state.edges });
gio48fde052025-05-14 09:48:08 +0000408 injectNetworkNodes();
gio359a6852025-05-14 03:38:24 +0000409 if (
gioc31bf142025-06-16 07:48:20 +0000410 get().zoom.x !== inst.state.viewport.x ||
411 get().zoom.y !== inst.state.viewport.y ||
412 get().zoom.zoom !== inst.state.viewport.zoom
gio359a6852025-05-14 03:38:24 +0000413 ) {
gioc31bf142025-06-16 07:48:20 +0000414 set({ zoom: inst.state.viewport });
gio359a6852025-05-14 03:38:24 +0000415 }
giod0026612025-05-08 13:00:36 +0000416 };
gio7f98e772025-05-07 11:00:14 +0000417
giod0026612025-05-08 13:00:36 +0000418 function updateNodeData<T extends NodeType>(id: string, data: NodeDataUpdate<T>): void {
419 setN(
420 get().nodes.map((n) => {
421 if (n.id === id) {
422 return {
423 ...n,
424 data: {
425 ...n.data,
426 ...data,
427 },
428 } as Extract<AppNode, { type: T }>;
429 }
430 return n;
431 }),
432 );
433 }
gio7f98e772025-05-07 11:00:14 +0000434
giod0026612025-05-08 13:00:36 +0000435 function updateNode<T extends NodeType>(id: string, node: NodeUpdate<T>): void {
436 setN(
437 get().nodes.map((n) => {
438 if (n.id === id) {
439 return {
440 ...n,
441 ...node,
442 } as Extract<AppNode, { type: T }>;
443 }
444 return n;
445 }),
446 );
447 }
gio7f98e772025-05-07 11:00:14 +0000448
giod0026612025-05-08 13:00:36 +0000449 function onConnect(c: Connection) {
450 const { nodes, edges } = get();
451 set({
452 edges: addEdge(c, edges),
453 });
454 const sn = nodes.filter((n) => n.id === c.source)[0]!;
455 const tn = nodes.filter((n) => n.id === c.target)[0]!;
456 if (tn.type === "network") {
457 if (sn.type === "gateway-https") {
458 updateNodeData<"gateway-https">(sn.id, {
459 network: tn.data.domain,
460 });
461 } else if (sn.type === "gateway-tcp") {
462 updateNodeData<"gateway-tcp">(sn.id, {
463 network: tn.data.domain,
464 });
465 }
466 }
467 if (tn.type === "app") {
468 if (c.sourceHandle === "env_var" && c.targetHandle === "env_var") {
469 const sourceEnvVars = nodeEnvVarNames(sn);
470 if (sourceEnvVars.length === 0) {
gio69148322025-06-19 23:16:12 +0400471 throw new Error(
472 `onConnect (env_var): Source node ${sn.id} (type: ${sn.type}) has no env vars to connect from.`,
473 );
giod0026612025-05-08 13:00:36 +0000474 }
475 const id = uuidv4();
476 if (sourceEnvVars.length === 1) {
477 updateNode<"app">(c.target, {
478 ...tn,
479 data: {
480 ...tn.data,
481 envVars: [
482 ...(tn.data.envVars || []),
483 {
484 id: id,
485 source: c.source,
486 name: sourceEnvVars[0],
487 isEditting: false,
488 },
489 ],
490 },
491 });
492 } else {
493 updateNode<"app">(c.target, {
494 ...tn,
495 data: {
496 ...tn.data,
497 envVars: [
498 ...(tn.data.envVars || []),
499 {
500 id: id,
501 source: c.source,
502 },
503 ],
504 },
505 });
506 }
507 }
508 if (c.sourceHandle === "ports" && c.targetHandle === "env_var") {
509 const sourcePorts = sn.data.ports || [];
510 const id = uuidv4();
511 if (sourcePorts.length === 1) {
512 updateNode<"app">(c.target, {
513 ...tn,
514 data: {
515 ...tn.data,
516 envVars: [
517 ...(tn.data.envVars || []),
518 {
519 id: id,
520 source: c.source,
521 name: nodeEnvVarNamePort(sn, sourcePorts[0].name),
522 portId: sourcePorts[0].id,
523 isEditting: false,
524 },
525 ],
526 },
527 });
528 }
529 }
gio3d0bf032025-06-05 06:57:26 +0000530 if (c.targetHandle === "repository") {
531 const sourceNode = nodes.find((n) => n.id === c.source);
532 if (sourceNode && sourceNode.type === "github" && sourceNode.data.repository) {
533 updateNodeData<"app">(tn.id, {
534 repository: {
535 id: sourceNode.data.repository.id,
536 repoNodeId: c.source,
537 },
538 });
539 }
540 }
giod0026612025-05-08 13:00:36 +0000541 }
542 if (c.sourceHandle === "volume") {
543 updateNodeData<"volume">(c.source, {
544 attachedTo: ((sn as VolumeNode).data.attachedTo || []).concat(c.source),
545 });
546 }
547 if (c.targetHandle === "volume") {
548 if (tn.type === "postgresql" || tn.type === "mongodb") {
549 updateNodeData(c.target, {
550 volumeId: c.source,
551 });
552 }
553 }
554 if (c.targetHandle === "https") {
555 if ((sn.data.ports || []).length === 1) {
556 updateNodeData<"gateway-https">(c.target, {
557 https: {
558 serviceId: c.source,
559 portId: sn.data.ports![0].id,
560 },
561 });
562 } else {
563 updateNodeData<"gateway-https">(c.target, {
564 https: {
565 serviceId: c.source,
566 portId: "", // TODO(gio)
567 },
568 });
569 }
570 }
571 if (c.targetHandle === "tcp") {
572 const td = tn.data as GatewayTCPData;
573 if ((sn.data.ports || []).length === 1) {
574 updateNodeData<"gateway-tcp">(c.target, {
575 exposed: (td.exposed || []).concat({
576 serviceId: c.source,
577 portId: sn.data.ports![0].id,
578 }),
579 });
580 } else {
581 updateNodeData<"gateway-tcp">(c.target, {
582 selected: {
583 serviceId: c.source,
584 portId: undefined,
585 },
586 });
587 }
588 }
589 if (sn.type === "app") {
590 if (c.sourceHandle === "ports") {
591 updateNodeData<"app">(sn.id, {
592 isChoosingPortToConnect: true,
593 });
594 }
595 }
giod0026612025-05-08 13:00:36 +0000596 }
gioa71316d2025-05-24 09:41:36 +0400597
598 const fetchGithubRepositories = async () => {
599 const { githubService, projectId } = get();
600 if (!githubService || !projectId) {
601 set({
602 githubRepositories: [],
603 githubRepositoriesError: "GitHub service or Project ID not available.",
604 githubRepositoriesLoading: false,
605 });
606 return;
607 }
608
609 set({ githubRepositoriesLoading: true, githubRepositoriesError: null });
610 try {
611 const repos = await githubService.getRepositories();
612 set({ githubRepositories: repos, githubRepositoriesLoading: false });
613 } catch (error) {
614 console.error("Failed to fetch GitHub repositories in store:", error);
615 const errorMessage = error instanceof Error ? error.message : "Unknown error fetching repositories";
616 set({ githubRepositories: [], githubRepositoriesError: errorMessage, githubRepositoriesLoading: false });
617 }
618 };
619
giod0026612025-05-08 13:00:36 +0000620 return {
621 projectId: undefined,
gio818da4e2025-05-12 14:45:35 +0000622 mode: "edit",
giod0026612025-05-08 13:00:36 +0000623 projects: [],
624 nodes: [],
625 edges: [],
626 categories: defaultCategories,
627 messages: v([]),
628 env: defaultEnv,
gioaf8db832025-05-13 14:43:05 +0000629 viewport: {
630 transformX: 0,
631 transformY: 0,
632 transformZoom: 1,
633 width: 800,
634 height: 600,
635 },
gio359a6852025-05-14 03:38:24 +0000636 zoom: {
637 x: 0,
638 y: 0,
639 zoom: 1,
640 },
giod0026612025-05-08 13:00:36 +0000641 githubService: null,
gioa71316d2025-05-24 09:41:36 +0400642 githubRepositories: [],
643 githubRepositoriesLoading: false,
644 githubRepositoriesError: null,
gioaf8db832025-05-13 14:43:05 +0000645 setViewport: (viewport) => {
646 const { viewport: vp } = get();
647 if (
648 viewport.transformX !== vp.transformX ||
649 viewport.transformY !== vp.transformY ||
650 viewport.transformZoom !== vp.transformZoom ||
651 viewport.width !== vp.width ||
652 viewport.height !== vp.height
653 ) {
654 set({ viewport });
655 }
656 },
giod0026612025-05-08 13:00:36 +0000657 setHighlightCategory: (name, active) => {
658 set({
659 categories: get().categories.map((c) => {
660 if (c.title.toLowerCase() !== name.toLowerCase()) {
661 return c;
662 } else {
663 return {
664 ...c,
665 active,
666 };
667 }
668 }),
669 });
670 },
671 onNodesChange: (changes) => {
672 const nodes = applyNodeChanges(changes, get().nodes);
673 setN(nodes);
674 },
675 onEdgesChange: (changes) => {
676 set({
677 edges: applyEdgeChanges(changes, get().edges),
678 });
679 },
gioaf8db832025-05-13 14:43:05 +0000680 addNode: (node) => {
681 const { viewport, nodes } = get();
682 setN(
683 nodes.concat({
684 ...node,
685 position: getRandomPosition(viewport),
gioa1efbad2025-05-21 07:16:45 +0000686 } as AppNode),
gioaf8db832025-05-13 14:43:05 +0000687 );
688 },
giod0026612025-05-08 13:00:36 +0000689 setNodes: (nodes) => {
690 setN(nodes);
691 },
692 setEdges: (edges) => {
693 set({ edges });
694 },
695 replaceEdge: (c, id) => {
696 let change: EdgeChange;
697 if (id === undefined) {
698 change = {
699 type: "add",
700 item: {
701 id: uuidv4(),
702 ...c,
703 },
704 };
705 onConnect(c);
706 } else {
707 change = {
708 type: "replace",
709 id,
710 item: {
711 id,
712 ...c,
713 },
714 };
715 }
716 set({
717 edges: applyEdgeChanges([change], get().edges),
718 });
719 },
720 updateNode,
721 updateNodeData,
722 onConnect,
723 refreshEnv: async () => {
724 const projectId = get().projectId;
725 let env: Env = defaultEnv;
giod0026612025-05-08 13:00:36 +0000726 try {
727 if (projectId) {
728 const response = await fetch(`/api/project/${projectId}/env`);
729 if (response.ok) {
730 const data = await response.json();
731 const result = envSchema.safeParse(data);
732 if (result.success) {
733 env = result.data;
734 } else {
735 console.error("Invalid env data:", result.error);
736 }
737 }
738 }
739 } catch (error) {
740 console.error("Failed to fetch integrations:", error);
741 } finally {
gioa71316d2025-05-24 09:41:36 +0400742 const oldEnv = get().env;
743 const oldGithubIntegrationStatus = oldEnv.integrations.github;
744 if (JSON.stringify(oldEnv) !== JSON.stringify(env)) {
gio4b9b58a2025-05-12 11:46:08 +0000745 set({ env });
gio48fde052025-05-14 09:48:08 +0000746 injectNetworkNodes();
gioa71316d2025-05-24 09:41:36 +0400747 let ghService = null;
gio4b9b58a2025-05-12 11:46:08 +0000748 if (env.integrations.github) {
gioa71316d2025-05-24 09:41:36 +0400749 ghService = new GitHubServiceImpl(projectId!);
750 }
751 if (get().githubService !== ghService || (ghService && !get().githubService)) {
752 set({ githubService: ghService });
753 }
754 if (
755 ghService &&
756 (oldGithubIntegrationStatus !== env.integrations.github || !oldEnv.integrations.github)
757 ) {
758 get().fetchGithubRepositories();
759 }
760 if (!env.integrations.github) {
761 set({
762 githubRepositories: [],
763 githubRepositoriesError: null,
764 githubRepositoriesLoading: false,
765 });
gio4b9b58a2025-05-12 11:46:08 +0000766 }
giod0026612025-05-08 13:00:36 +0000767 }
768 }
769 },
gio818da4e2025-05-12 14:45:35 +0000770 setMode: (mode) => {
771 set({ mode });
772 },
773 setProject: async (projectId) => {
gio918780d2025-05-22 08:24:41 +0000774 const currentProjectId = get().projectId;
775 if (projectId === currentProjectId) {
gio359a6852025-05-14 03:38:24 +0000776 return;
777 }
gio918780d2025-05-22 08:24:41 +0000778 stopRefreshEnvInterval();
giod0026612025-05-08 13:00:36 +0000779 set({
780 projectId,
gioa71316d2025-05-24 09:41:36 +0400781 githubRepositories: [],
782 githubRepositoriesLoading: false,
783 githubRepositoriesError: null,
giod0026612025-05-08 13:00:36 +0000784 });
785 if (projectId) {
gio818da4e2025-05-12 14:45:35 +0000786 await get().refreshEnv();
gioa71316d2025-05-24 09:41:36 +0400787 if (get().env.instanceId) {
gio818da4e2025-05-12 14:45:35 +0000788 set({ mode: "deploy" });
789 } else {
790 set({ mode: "edit" });
791 }
gio4b9b58a2025-05-12 11:46:08 +0000792 restoreSaved();
gio918780d2025-05-22 08:24:41 +0000793 startRefreshEnvInterval();
gio4b9b58a2025-05-12 11:46:08 +0000794 } else {
795 set({
796 nodes: [],
797 edges: [],
gio918780d2025-05-22 08:24:41 +0000798 env: defaultEnv,
799 githubService: null,
gioa71316d2025-05-24 09:41:36 +0400800 githubRepositories: [],
801 githubRepositoriesLoading: false,
802 githubRepositoriesError: null,
gio4b9b58a2025-05-12 11:46:08 +0000803 });
giod0026612025-05-08 13:00:36 +0000804 }
805 },
gioa71316d2025-05-24 09:41:36 +0400806 fetchGithubRepositories: fetchGithubRepositories,
giod0026612025-05-08 13:00:36 +0000807 };
gio5f2f1002025-03-20 18:38:48 +0400808});