diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 0000000..969ef2d --- /dev/null +++ b/.deepsource.toml @@ -0,0 +1,8 @@ +version = 1 + +[[analyzers]] +name = "javascript" + + [analyzers.meta] + plugins = ["react"] + environment = ["browser"] \ No newline at end of file diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index de6b844..f078145 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,6 +1,31 @@ -FROM mcr.microsoft.com/vscode/devcontainers/typescript-node:latest +FROM node:current-alpine -# Install additional OS packages if needed -# RUN apt-get update && apt-get install -y +# Install necessary packages +RUN apk add --no-cache \ + python3 \ + py3-pip \ + make \ + g++ \ + sqlite \ + git \ + bash \ + lsof \ + libc6-compat +# Install yarn globally +# RUN npm install -g yarn + +# Install node-gyp globally +RUN npm install -g node-gyp + +# Install node-pty globally +RUN npm install -g node-pty + +# Install nodemon globally +RUN npm install -g nodemon + +# Install vite globally +RUN npm install -g vite + +# Set up workspace directory WORKDIR /workspace diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 38ebb1a..90d9e75 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,58 +1,73 @@ { - "name": "intelops-genpod", - "dockerFile": "Dockerfile", - "settings": { - "terminal.integrated.shell.linux": "/bin/bash" - }, - "extensions": [ - "ChakrounAnas.turbo-console-log", - "christian-kohler.npm-intellisense", - "christian-kohler.path-intellisense", - "cmstead.js-codeformer", - "cmstead.jsrefactor", - "dbaeumer.vscode-eslint", - "dsznajder.es7-react-js-snippets", - "eamodio.gitlens", - "esbenp.prettier-vscode", - "firsttris.vscode-jest-runner", - "formulahendry.auto-close-tag", - "formulahendry.auto-rename-tag", - "GitHub.copilot", - "GitHub.copilot-chat", - "GitHub.vscode-pull-request-github", - "jkjustjoshing.vscode-text-pastry", - "jock.svg", - "jrebocho.vscode-random", - "kaiwood.center-editor-window", - "kisstkondoros.vscode-gutter-preview", - "MariusAlchimavicius.json-to-ts", - "mike-co.import-sorter", - "mikestead.dotenv", - "ms-azuretools.vscode-docker", - "ms-vscode.vscode-typescript-next", - "ms-vscode.vscode-typescript-tslint-plugin", - "naumovs.color-highlight", - "nick-lvov-dev.typescript-explicit-types", - "pflannery.vscode-versionlens", - "redhat.vscode-yaml", - "rvest.vs-code-prettier-eslint", - "ryanlaws.toggle-case", - "sburg.vscode-javascript-booster", - "skyran.js-jsx-snippets", - "streetsidesoftware.code-spell-checker", - "styled-components.vscode-styled-components", - "vincaslt.highlight-matching-tag", - "whtouche.vscode-js-console-utils", - "wix.vscode-import-cost", - "xabikos.JavaScriptSnippets" - ], - "forwardPorts": [ - 3000, // Vite - 6006 // Storybook - ], - "remoteUser": "node", - "mounts": [ - "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached" - ], - "postCreateCommand": "yarn install" + "name": "intelops-genpod", + "dockerFile": "Dockerfile", + + "customizations": { + "settings": { + "terminal.integrated.shell.linux": "/bin/bash", + "terminal.integrated.defaultProfile.linux": "bash", + "python.defaultInterpreterPath": "/usr/bin/python3", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": {"source.fixAll.eslint": true} + }, + "vscode": { + "extensions": [ + "meganrogge.template-string-converter", + "vunguyentuan.vscode-css-variables", + "ChakrounAnas.turbo-console-log", + "christian-kohler.npm-intellisense", + "christian-kohler.path-intellisense", + "cmstead.js-codeformer", + "cmstead.jsrefactor", + "dbaeumer.vscode-eslint", + "dsznajder.es7-react-js-snippets", + "eamodio.gitlens", + "esbenp.prettier-vscode", + "firsttris.vscode-jest-runner", + "formulahendry.auto-close-tag", + "formulahendry.auto-rename-tag", + "GitHub.vscode-pull-request-github", + "jkjustjoshing.vscode-text-pastry", + "jock.svg", + "jrebocho.vscode-random", + "kaiwood.center-editor-window", + "kisstkondoros.vscode-gutter-preview", + "MariusAlchimavicius.json-to-ts", + "mike-co.import-sorter", + "mikestead.dotenv", + "ms-azuretools.vscode-docker", + "ms-vscode.vscode-typescript-next", + "ms-vscode.vscode-typescript-tslint-plugin", + "naumovs.color-highlight", + "nick-lvov-dev.typescript-explicit-types", + "pflannery.vscode-versionlens", + "redhat.vscode-yaml", + "rvest.vs-code-prettier-eslint", + "ryanlaws.toggle-case", + "sburg.vscode-javascript-booster", + "skyran.js-jsx-snippets", + "streetsidesoftware.code-spell-checker", + "styled-components.vscode-styled-components", + "vincaslt.highlight-matching-tag", + "whtouche.vscode-js-console-utils", + "wix.vscode-import-cost", + "xabikos.JavaScriptSnippets", + "ms-python.python", + "mtxr.sqltools" + ] + } + }, + "forwardPorts": [ + 3000, // Vite + 6006, // Storybook + 8080 // cypress + ], + "remoteUser": "node", + + "mounts": [ + "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached" + ], + + "postCreateCommand": "yarn install && yarn dev" + } diff --git a/.env b/.env new file mode 100644 index 0000000..33652cf --- /dev/null +++ b/.env @@ -0,0 +1,4 @@ +VITE_BACKEND_URL=http://localhost:5002 +VITE_SOCKET_URL=http://localhost:3002 +VITE_FILE_SERVER_URL=http://localhost:3003 +SOCKET_PORT=3002 diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 29cb6d5..2896f97 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -1,14 +1,23 @@ module.exports = { root: true, env: { browser: true, es2020: true }, - extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended', 'plugin:storybook/recommended'], - ignorePatterns: ['dist', '.eslintrc.cjs'], - parser: '@typescript-eslint/parser', - plugins: ['react-refresh'], + extends: [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:react-hooks/recommended", + "plugin:storybook/recommended", + "plugin:@tanstack/eslint-plugin-query/recommended", + "prettier" + ], + ignorePatterns: ["dist", ".eslintrc.cjs"], + parser: "@typescript-eslint/parser", + plugins: ["react-refresh"], rules: { - 'react-refresh/only-export-components': [ - 'warn', - { allowConstantExport: true }, + "react-refresh/only-export-components": [ + "warn", + { allowConstantExport: true } ], - }, -} + "no-extra-semi": "off", + "wrap-iife": ["error", "inside"] + } +}; diff --git a/.gitignore b/.gitignore index a547bf3..a8420fd 100644 --- a/.gitignore +++ b/.gitignore @@ -8,9 +8,12 @@ pnpm-debug.log* lerna-debug.log* node_modules +**/node_modules dist dist-ssr *.local +coverage +.nyc_output # Editor directories and files .vscode/* diff --git a/.nycrc.json b/.nycrc.json new file mode 100644 index 0000000..bfe1b44 --- /dev/null +++ b/.nycrc.json @@ -0,0 +1,7 @@ +{ + "all": true, + "extends": "@istanbuljs/nyc-config-typescript", + "check-coverage": true, + "include": ["src/**/*.ts", "src/**/*.tsx"], + "exclude": ["cypress/**/*.*", "**/*.d.ts", "**/*.cy.tsx", "**/*.cy.ts"] +} diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..786dbdf --- /dev/null +++ b/.prettierrc @@ -0,0 +1,10 @@ +{ + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true, + "trailingComma": "none", + "bracketSpacing": true, + "arrowParens": "avoid" +} diff --git a/.storybook/main.ts b/.storybook/main.ts index 6d68d18..5dc07ce 100644 --- a/.storybook/main.ts +++ b/.storybook/main.ts @@ -1,19 +1,19 @@ -import type { StorybookConfig } from "@storybook/react-vite"; +import type { StorybookConfig } from '@storybook/react-vite' const config: StorybookConfig = { - stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"], - addons: [ - "@storybook/addon-links", - "@storybook/addon-essentials", - "@storybook/addon-onboarding", - "@storybook/addon-interactions", - ], - framework: { - name: "@storybook/react-vite", - options: {}, - }, - docs: { - autodocs: "tag", - }, -}; -export default config; + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-links', + '@storybook/addon-essentials', + '@storybook/addon-onboarding', + '@storybook/addon-interactions', + ], + framework: { + name: '@storybook/react-vite', + options: {}, + }, + docs: { + autodocs: 'tag', + }, +} +export default config diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index c33ce29..4dacd03 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -1,33 +1,33 @@ // Import styles of packages that you've installed. // All packages except `@mantine/hooks` require styles imports -import '@mantine/core/styles.css' +import '@mantine/core/styles.css'; -import React, { useEffect } from 'react' -import { addons } from '@storybook/preview-api' -import { DARK_MODE_EVENT_NAME } from 'storybook-dark-mode' -import { MantineProvider, useMantineColorScheme } from '@mantine/core' -import theme from '../src/theme' +import React, { ReactNode, useEffect } from 'react'; +import { addons } from '@storybook/preview-api'; +import { DARK_MODE_EVENT_NAME } from 'storybook-dark-mode'; +import { MantineProvider, useMantineColorScheme } from '@mantine/core'; +import theme from '../src/theme'; -const channel = addons.getChannel() +const channel = addons.getChannel(); function ColorSchemeWrapper({ children }: { children: React.ReactNode }) { - const { setColorScheme } = useMantineColorScheme() - const handleColorScheme = (value: boolean) => - setColorScheme(value ? 'dark' : 'light') + const { setColorScheme } = useMantineColorScheme(); + const handleColorScheme = (value: boolean) => + setColorScheme(value ? 'dark' : 'light'); - useEffect(() => { - channel.on(DARK_MODE_EVENT_NAME, handleColorScheme) - return () => channel.off(DARK_MODE_EVENT_NAME, handleColorScheme) - }, [channel]) + useEffect(() => { + channel.on(DARK_MODE_EVENT_NAME, handleColorScheme); + return () => channel.off(DARK_MODE_EVENT_NAME, handleColorScheme); + }, [channel]); - return <>{children} + return children; } export const decorators = [ - (renderStory: any) => ( - {renderStory()} - ), - (renderStory: any) => ( - {renderStory()} - ), -] + (renderStory: () => ReactNode) => ( + {renderStory()} + ), + (renderStory: () => ReactNode) => ( + {renderStory()} + ) +]; diff --git a/.yarnrc.yml b/.yarnrc.yml new file mode 100644 index 0000000..3186f3f --- /dev/null +++ b/.yarnrc.yml @@ -0,0 +1 @@ +nodeLinker: node-modules diff --git a/cypress.config.ts b/cypress.config.ts new file mode 100644 index 0000000..76b391f --- /dev/null +++ b/cypress.config.ts @@ -0,0 +1,29 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { defineConfig } from 'cypress' + +import task from '@cypress/code-coverage/task' + +export default defineConfig({ + env: { + codeCoverage: { + exclude: 'cypress/**/*.*', + }, + }, + e2e: { + baseUrl: 'http://localhost:3000', + setupNodeEvents(on, config) { + task(on, config) + return config + }, + }, + component: { + devServer: { + framework: 'react', + bundler: 'vite', + }, + setupNodeEvents(on, config) { + task(on, config) + return config + }, + }, +}) diff --git a/cypress/e2e/node-form.cy.ts b/cypress/e2e/node-form.cy.ts new file mode 100644 index 0000000..322992c --- /dev/null +++ b/cypress/e2e/node-form.cy.ts @@ -0,0 +1,5 @@ +describe('template spec', () => { + it('passes', () => { + cy.visit('https://example.cypress.io') + }) +}) \ No newline at end of file diff --git a/cypress/support/commands.ts b/cypress/support/commands.ts new file mode 100644 index 0000000..698b01a --- /dev/null +++ b/cypress/support/commands.ts @@ -0,0 +1,37 @@ +/// +// *********************************************** +// This example commands.ts shows you how to +// create various custom commands and overwrite +// existing commands. +// +// For more comprehensive examples of custom +// commands please read more here: +// https://on.cypress.io/custom-commands +// *********************************************** +// +// +// -- This is a parent command -- +// Cypress.Commands.add('login', (email, password) => { ... }) +// +// +// -- This is a child command -- +// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... }) +// +// +// -- This is a dual command -- +// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... }) +// +// +// -- This will overwrite an existing command -- +// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) +// +// declare global { +// namespace Cypress { +// interface Chainable { +// login(email: string, password: string): Chainable +// drag(subject: string, options?: Partial): Chainable +// dismiss(subject: string, options?: Partial): Chainable +// visit(originalFn: CommandOriginalFn, url: string, options: Partial): Chainable +// } +// } +// } \ No newline at end of file diff --git a/cypress/support/component-index.html b/cypress/support/component-index.html new file mode 100644 index 0000000..ac6e79f --- /dev/null +++ b/cypress/support/component-index.html @@ -0,0 +1,12 @@ + + + + + + + Components App + + +
+ + \ No newline at end of file diff --git a/cypress/support/component.ts b/cypress/support/component.ts new file mode 100644 index 0000000..0b80186 --- /dev/null +++ b/cypress/support/component.ts @@ -0,0 +1,39 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +// *********************************************************** +// This example support/component.ts is processed and +// loaded automatically before your test files. +// +// This is a great place to put global configuration and +// behavior that modifies Cypress. +// +// You can change the location of this file or turn off +// automatically serving support files with the +// 'supportFile' configuration option. +// +// You can read more here: +// https://on.cypress.io/configuration +// *********************************************************** + +// Import commands.js using ES2015 syntax: +import './commands'; +import '@cypress/code-coverage/support'; +import '../../src/index.css'; + +// Alternatively you can use CommonJS syntax: +// require('./commands') + +import { mount } from 'cypress/react18'; + +// Augment the Cypress namespace to include type definitions for +// your custom command. +// Alternatively, can be defined in cypress/support/component.d.ts +// with a at the top of your spec. +declare global { + namespace Cypress { + interface Chainable { + mount: typeof mount; + } + } +} + +Cypress.Commands.add('mount', mount); diff --git a/cypress/support/e2e.ts b/cypress/support/e2e.ts new file mode 100644 index 0000000..f80f74f --- /dev/null +++ b/cypress/support/e2e.ts @@ -0,0 +1,20 @@ +// *********************************************************** +// This example support/e2e.ts is processed and +// loaded automatically before your test files. +// +// This is a great place to put global configuration and +// behavior that modifies Cypress. +// +// You can change the location of this file or turn off +// automatically serving support files with the +// 'supportFile' configuration option. +// +// You can read more here: +// https://on.cypress.io/configuration +// *********************************************************** + +// Import commands.js using ES2015 syntax: +import './commands' + +// Alternatively you can use CommonJS syntax: +// require('./commands') \ No newline at end of file diff --git a/docs/ProjectDoc/middleware_doc/README.md b/docs/ProjectDoc/middleware_doc/README.md new file mode 100644 index 0000000..29a61df --- /dev/null +++ b/docs/ProjectDoc/middleware_doc/README.md @@ -0,0 +1,60 @@ +# Middleware Documentation + +This documentation provides a comprehensive overview of the middleware service. + +## Project Overview + +The middleware service is built using Fastify, a modern and fast web framework for Node.js, with TypeScript support. It serves as an intermediary layer handling various functionalities including database operations, request handling, and routing. + +## Project Structure + +``` +middleware/ +├── config/ # Configuration files +├── migrations/ # Database migration files +├── models/ # Database models +├── src/ # Source code +│ ├── db/ # Database related code +│ ├── handlers/ # Request handlers +│ ├── middleware/ # Custom middleware functions +│ ├── routes/ # API route definitions +│ ├── constants.ts +│ ├── index.ts # Main application entry +│ └── logger.ts # Logging configuration +├── package.json # Project dependencies and scripts +└── tsconfig.json # TypeScript configuration +``` + +## Tech Stack + +- **Runtime**: Node.js +- **Framework**: Fastify +- **Language**: TypeScript +- **Database**: SQLite with Sequelize ORM +- **Development Tools**: Nodemon, ts-node + +## Key Dependencies + +- `fastify`: Web framework +- `@fastify/cors`: CORS support +- `@fastify/session`: Session management +- `sequelize`: ORM for database operations +- `sqlite3`: Database engine +- `pino`: Logging library + +## Development + +To run the development server: + +```bash +npm run dev +``` + +This will start the server using nodemon for automatic reloading during development. + +## Documentation Structure + +- [Database Models](./models.md) +- [API Routes](./routes.md) +- [Handlers](./handlers.md) +- [Database Operations](./database.md) diff --git a/docs/ProjectDoc/middleware_doc/database.md b/docs/ProjectDoc/middleware_doc/database.md new file mode 100644 index 0000000..7e902bb --- /dev/null +++ b/docs/ProjectDoc/middleware_doc/database.md @@ -0,0 +1,62 @@ +# Database Operations Documentation + +This document describes the database operations and configuration in the middleware service. + +## Database Overview + +The service uses SQLite as the database engine with Sequelize ORM for: +- Data persistence +- Query operations +- Schema management +- Migrations + +## Database Structure + +### Configuration +Located in the `config` directory: +- Database connection settings +- Environment-specific configurations +- Sequelize options + +### Migrations +Located in the `migrations` directory: +- Schema version control +- Database structure updates +- Data transformations + +## Database Operations + +### Query Operations +- SELECT operations +- INSERT operations +- UPDATE operations +- DELETE operations +- Complex joins and relationships + +### Transaction Management +- ACID compliance +- Transaction isolation +- Rollback handling +- Commit operations + +## Data Access Patterns + +### Direct Model Access +- Model.create() +- Model.findOne() +- Model.findAll() +- Model.update() +- Model.delete() + +### Relations and Associations +- One-to-One relationships +- One-to-Many relationships +- Many-to-Many relationships + +## Best Practices + +- Connection pooling +- Query optimization +- Index management +- Error handling +- Data validation diff --git a/docs/ProjectDoc/middleware_doc/handlers.md b/docs/ProjectDoc/middleware_doc/handlers.md new file mode 100644 index 0000000..600487b --- /dev/null +++ b/docs/ProjectDoc/middleware_doc/handlers.md @@ -0,0 +1,58 @@ +# Request Handlers Documentation + +This document details the request handlers that process incoming API requests in the middleware service. + +## Handler Categories + +### 1. Authentication Handlers (`authHandlers.ts`) +Handles user authentication and authorization: +- Login processing +- Session management +- User verification +- Token management + +### 2. LLM Handlers (`llmHandlers.ts`) +Manages Language Learning Model interactions: +- Model requests +- Response processing +- Error handling +- Model configuration + +### 3. Project Handlers (`projectHandlers.ts`) +Handles project-related operations: +- Project creation +- Project updates +- Project deletion +- Project query operations + +## Handler Structure + +Each handler follows a consistent pattern: +1. Request validation +2. Data processing +3. Error handling +4. Response formatting + +## Common Features + +All handlers implement: +- Type safety (TypeScript) +- Error boundary handling +- Logging +- Input validation +- Response standardization + +## Type Definitions + +Common types and interfaces are defined in `types.ts`: +- Request/Response types +- Data models +- Utility types + +## Error Handling + +Handlers implement comprehensive error handling: +- Input validation errors +- Processing errors +- Database errors +- External service errors diff --git a/docs/ProjectDoc/middleware_doc/models.md b/docs/ProjectDoc/middleware_doc/models.md new file mode 100644 index 0000000..981ba78 --- /dev/null +++ b/docs/ProjectDoc/middleware_doc/models.md @@ -0,0 +1,51 @@ +# Database Models Documentation + +This document describes the database models used in the middleware service. + +## Overview + +The application uses Sequelize as the ORM (Object-Relational Mapping) with SQLite as the database engine. The models are defined using Sequelize's model definition syntax. + +## Models + +### 1. User Model (`user.js`) +Represents user data in the system. + +Key attributes: +- User authentication information +- User profile data +- Session management data + +### 2. Project Model (`project.js`) +Manages project-related data. + +Key attributes: +- Project metadata +- Project configuration +- Project status + +## Model Relationships + +The models are related through Sequelize associations defined in `index.js`. This ensures proper data relationships and referential integrity. + +## Database Configuration + +The database configuration is managed through: +- Sequelize configuration in `config` directory +- Migration files in `migrations` directory +- Model definitions in `models` directory + +## Database Operations + +Models support standard CRUD operations: +- Create: Insert new records +- Read: Query existing records +- Update: Modify existing records +- Delete: Remove records + +## Data Validation + +Each model includes: +- Data type validation +- Required field validation +- Custom validation rules where applicable diff --git a/docs/ProjectDoc/middleware_doc/routes.md b/docs/ProjectDoc/middleware_doc/routes.md new file mode 100644 index 0000000..6907f7d --- /dev/null +++ b/docs/ProjectDoc/middleware_doc/routes.md @@ -0,0 +1,41 @@ +# API Routes Documentation + +This document details all the API routes available in the middleware service. + +## Route Categories + +The API routes are organized into three main categories: + +### 1. Authentication Routes (`authRoutes.ts`) +Handles user authentication and session management. + +### 2. LLM Routes (`llmRoutes.ts`) +Manages interactions with Language Learning Models. + +### 3. Project Routes (`projectRoutes.ts`) +Handles project-related operations and management. + +## Route Implementations + +Each route category is implemented in its own TypeScript file under the `src/routes` directory: + +- `authRoutes.ts`: Authentication endpoints +- `llmRoutes.ts`: LLM interaction endpoints +- `projectRoutes.ts`: Project management endpoints + +## Route Structure + +Each route file follows a consistent structure: +1. Route definition +2. Handler association +3. Input validation +4. Response schema definition + +## Common Route Patterns + +All routes follow these common patterns: +- RESTful design principles +- Consistent error handling +- Authentication middleware where required +- Input validation +- Standardized response format diff --git a/docs/ProjectDoc/socket_doc/README.md b/docs/ProjectDoc/socket_doc/README.md new file mode 100644 index 0000000..1ce4ef2 --- /dev/null +++ b/docs/ProjectDoc/socket_doc/README.md @@ -0,0 +1,53 @@ +# Socket Server Documentation + +This document provides a comprehensive overview of the socket server implementation. + +## Project Overview + +The socket server is built using Node.js with Socket.IO, providing real-time bidirectional communication between clients and the server. It's implemented in TypeScript for type safety and better development experience. + +## Project Structure + +``` +socket-server/ +├── src/ +│ ├── server.ts # Main server implementation +│ └── logger.ts # Logging configuration +├── package.json # Project dependencies and scripts +└── tsconfig.json # TypeScript configuration +``` + +## Tech Stack + +- **Runtime**: Node.js +- **Framework**: Express.js +- **WebSocket**: Socket.IO +- **Language**: TypeScript +- **Terminal Support**: node-pty +- **Logging**: Pino + +## Key Dependencies + +- `socket.io`: WebSocket server implementation +- `express`: Web server framework +- `node-pty`: Terminal emulation support +- `pino`: Logging library +- `cors`: Cross-Origin Resource Sharing support +- `dotenv`: Environment configuration + +## Development + +To run the development server: + +```bash +npm run dev +``` + +This will start the server using ts-node for TypeScript execution. + +## Documentation Structure + +The documentation is organized into the following sections: +- [Server Implementation](./server.md) +- [Logger Configuration](./logger.md) +- [Configuration Guide](./configuration.md) diff --git a/docs/ProjectDoc/socket_doc/configuration.md b/docs/ProjectDoc/socket_doc/configuration.md new file mode 100644 index 0000000..a841de8 --- /dev/null +++ b/docs/ProjectDoc/socket_doc/configuration.md @@ -0,0 +1,76 @@ +# Configuration Guide + +This document provides information about configuring the socket server. + +## Environment Variables + +The server uses environment variables for configuration. Create a `.env` file in the root directory with the following variables: + +```env +PORT=3000 # Primary server port +SOCKET_PORT=3000 # Socket.IO port (if different) +``` + +## TypeScript Configuration + +The project uses TypeScript with the following key configurations in `tsconfig.json`: + +### Compiler Options +- Target: Latest ECMAScript version +- Module: CommonJS +- Strict type checking enabled +- Source maps enabled for debugging + +### Project Structure +- Source files in `src` directory +- Output directory configured for compiled files + +## Dependencies + +### Production Dependencies +- `socket.io`: WebSocket server +- `express`: Web framework +- `node-pty`: Terminal emulation +- `pino`: Logging framework +- `cors`: CORS support +- `dotenv`: Environment configuration + +### Development Dependencies +- `typescript`: TypeScript compiler +- `@types/express`: Express type definitions +- `@types/node`: Node.js type definitions + +## CORS Configuration + +Cross-Origin Resource Sharing is configured to allow: +- All origins (`*`) +- All standard HTTP methods +- Headers for WebSocket support + +## Security Considerations + +1. **CORS Policy** + - Consider restricting allowed origins in production + - Implement appropriate security headers + +2. **Environment Variables** + - Use secure environment variable management + - Don't commit `.env` files to version control + +3. **Terminal Access** + - Implement user authentication if needed + - Restrict terminal capabilities as necessary + +## Development Setup + +1. Install dependencies: + ```bash + npm install + ``` + +2. Create `.env` file with required variables + +3. Start development server: + ```bash + npm run dev + ``` diff --git a/docs/ProjectDoc/socket_doc/logger.md b/docs/ProjectDoc/socket_doc/logger.md new file mode 100644 index 0000000..addec90 --- /dev/null +++ b/docs/ProjectDoc/socket_doc/logger.md @@ -0,0 +1,72 @@ +# Logger Configuration Documentation + +This document details the logging configuration implemented in `logger.ts`. + +## Overview + +The socket server uses Pino as its logging framework, configured with pretty-printing for better development experience. + +## Configuration Details + +### Logger Setup +```typescript +import pino from 'pino'; +const logger = pino({ + transport: { + target: 'pino-pretty', + options: { + colorize: true + } + }, + name: 'socket-server' +}); +``` + +### Components + +1. **Transport Configuration** + - Uses `pino-pretty` for formatted output + - Colorization enabled for better readability + +2. **Logger Identity** + - Name: 'socket-server' + - Helps identify log source in multi-service environments + +## Usage + +### Log Levels +The logger supports multiple log levels: +- `logger.info()`: Information messages +- `logger.warn()`: Warning messages +- `logger.error()`: Error messages +- `logger.debug()`: Debug information +- `logger.trace()`: Detailed debugging + +### Example Usage +```typescript +logger.info('Server started'); +logger.warn('Connection attempt failed'); +logger.error('Critical error occurred'); +``` + +## Features + +- **Pretty Printing**: Human-readable log format +- **Color Coding**: Different colors for different log levels +- **Timestamp**: Automatic timestamp addition +- **Log Level Support**: Multiple severity levels +- **Performance**: High-performance logging + +## Best Practices + +1. **Log Level Selection** + - Use appropriate log levels for different scenarios + - Avoid excessive logging in production + +2. **Error Logging** + - Include stack traces for errors + - Log contextual information + +3. **Performance Considerations** + - Use appropriate log levels + - Avoid logging sensitive information diff --git a/docs/ProjectDoc/socket_doc/server.md b/docs/ProjectDoc/socket_doc/server.md new file mode 100644 index 0000000..e48545a --- /dev/null +++ b/docs/ProjectDoc/socket_doc/server.md @@ -0,0 +1,78 @@ +# Server Implementation Documentation + +This document details the implementation of the Socket.IO server in `server.ts`. + +## Overview + +The server implements a WebSocket-based terminal emulation service using Socket.IO and node-pty. It allows clients to connect and interact with a terminal session in real-time. + +## Key Components + +### Server Setup +- Express application with CORS enabled +- HTTP server creation +- Socket.IO server initialization with CORS configuration +- Static file serving + +### Terminal Emulation +- Uses `node-pty` for terminal process spawning +- Supports both Windows (cmd.exe) and Unix (bash) shells +- Configurable terminal settings: + - Terminal type: xterm-color + - Default dimensions: 80x30 + - Working directory: User's HOME + - Environment variables: Inherited from process + +### WebSocket Events + +#### Server Events +- `connection`: Handles new client connections +- `output`: Emits terminal output to client +- `disconnect`: Cleans up terminal process on client disconnect + +#### Client Events +- `input`: Receives terminal input from client +- `output`: Receives terminal output from server + +### Error Handling +- Graceful server shutdown on SIGTERM +- Process cleanup on client disconnect +- Logging of connection events + +## Configuration + +### Environment Variables +- `PORT`: Server port (default: 3000) +- `SOCKET_PORT`: Alternative port configuration +- `HOME`: Working directory for terminal sessions + +### CORS Configuration +- Origins: All origins allowed ('*') +- Methods: All methods supported +- Credentials: Not required + +## Server Lifecycle + +1. Server Initialization + - Express app creation + - CORS middleware setup + - HTTP server creation + - Socket.IO server setup + +2. Connection Handling + - Client connection establishment + - Terminal process creation + - Event listener setup + - Data streaming setup + +3. Server Shutdown + - SIGTERM signal handling + - Graceful connection termination + - Resource cleanup + +## Best Practices + +- Environment variable configuration +- Cross-origin security handling +- Process cleanup and resource management +- Error logging and monitoring diff --git a/docs/ProjectDoc/src/App.md b/docs/ProjectDoc/src/App.md new file mode 100644 index 0000000..3afe919 --- /dev/null +++ b/docs/ProjectDoc/src/App.md @@ -0,0 +1,92 @@ + + +# src/App.tsx Explanation +===================================== + +The `src/App.tsx` file is the main application component of the React application. It is responsible for rendering the application's routes and providing the necessary context to the application. + +## Imports +------------ + +The file starts by importing the necessary dependencies: + +* `@mantine/code-highlight/styles.css`: imports the CSS styles for code highlighting +* `@mantine/core/styles.css`: imports the CSS styles for Mantine UI +* `@mantine/notifications/styles.css`: imports the CSS styles for notifications +* `reactflow/dist/style.css`: imports the CSS styles for React Flow +* `./App.css`: imports the local CSS styles for the application +* `./styles/tailwindcss.css`: imports the CSS styles for Tailwind CSS +* `react`: imports the React library +* `react-router-dom`: imports the React Router DOM library +* `reactflow`: imports the React Flow library +* `@mantine/modals`: imports the Mantine Modals library +* `@mantine/notifications`: imports the Mantine Notifications library +* `./notifications`: imports the local notifications component +* `./pages`: imports the local pages components +* `./store`: imports the local store components +* `./utils`: imports the local utility components + +## App Component +----------------- + +The `App` component is defined as a functional component using the `function` keyword. It uses the `useEffect` hook to run some initialization code when the component mounts. + +### Initialization Code + +The initialization code runs the following functions: + +* `runEnvVariablesCheck`: This function is not defined in this code snippet, but it's likely responsible for checking environment variables. +* `fetchAllFeatureFlags`: This function is likely responsible for fetching feature flags from a server or storage. +* `initSocket`: This function is likely responsible for initializing a WebSocket connection. + +### Feature Flag Loading + +The component uses the `useFeatureFlagStore` hook to get the `fetchAllFeatureFlags` function and the `areFeatureFlagsLoaded` state. If the feature flags are not loaded, the component returns `null`. + +## Routing +------------ + +The component defines a `BrowserRouter` component, which is the top-level component for React Router DOM. Inside the `BrowserRouter`, it defines a `Routes` component, which contains several `Route` components that define the application's routes. + +### Routes + +The routes defined in the component include: + +* `/`: renders the `Home` component +* `/genval`: renders the `Genval` component +* `/coming-soon`: renders the `ComingSoon` component +* `/test`: renders the `Layout` component +* `/login`: renders the `Login` component +* `/project/:projectId`: renders the `Project` component +* `/project/:projectId/status`: renders the `Status` component +* `/profile`: renders the `Profile` component +* `*`: renders the `PageNotFound` component (catch-all route) + +## Providers +------------- + +The component uses several providers to provide context to the application: + +* `ReactFlowProvider`: provides the React Flow context +* `ModalsProvider`: provides the Mantine Modals context +* `Notifications`: provides the Mantine Notifications context + +## Return Statement +------------------- + +The component returns the `BrowserRouter` component, which contains the `Routes` component and the providers. + +```typescript +return ( + + + + + + {/* routes */} + + + + +); +``` \ No newline at end of file diff --git a/docs/ProjectDoc/src/Main.md b/docs/ProjectDoc/src/Main.md new file mode 100644 index 0000000..78f4aac --- /dev/null +++ b/docs/ProjectDoc/src/Main.md @@ -0,0 +1,59 @@ +Sure, here's an explanation of the `src/main.tsx` file in Markdown format: + +# src/main.tsx Explanation +===================================== + +The `src/main.tsx` file is the entry point of the React application. It is responsible for rendering the application to the DOM. + +## Imports +------------ + +The file starts by importing the necessary dependencies: + +* `./index.css`: imports the global CSS styles for the application +* `createRoot` from `react-dom/client`: imports the `createRoot` function from React DOM, which is used to render the application to the DOM +* `MantineProvider` from `@mantine/core`: imports the `MantineProvider` component from Mantine UI, which is used to provide the application's theme and styling +* `App` from `./App.tsx`: imports the `App` component, which is the main application component +* `initStores` from `./store/initStores.ts`: imports the `initStores` function, which is used to initialize the application's stores +* `theme` and `cssVariableResolver` from `./theme.ts`: imports the application's theme and CSS variable resolver + +## Initialization +----------------- + +The file initializes the application's stores by calling the `initStores` function: + +```typescript +initStores(); +``` + +## Rendering the Application +--------------------------- + +The file renders the application to the DOM using the `createRoot` function: + +```typescript +const rootElement = document.getElementById('root'); +if (rootElement) { + createRoot(rootElement).render( + // + + + + // + ); +} +``` + +Here's what's happening: + +* It gets a reference to the `root` element in the DOM, which is where the application will be rendered. +* It creates a new root element using the `createRoot` function and renders the application to it. +* It wraps the `App` component with the `MantineProvider` component, which provides the application's theme and styling. +* It passes the `theme` and `cssVariableResolver` to the `MantineProvider` component. +* It renders the `App` component inside the `MantineProvider` component. + +Note that the `React.StrictMode` component is commented out. This component is used to enable strict mode in React, which helps with debugging and performance optimization. diff --git a/docs/ProjectDoc/src/SideNavbar.md b/docs/ProjectDoc/src/SideNavbar.md new file mode 100644 index 0000000..829e062 --- /dev/null +++ b/docs/ProjectDoc/src/SideNavbar.md @@ -0,0 +1,105 @@ +`src/components/common/side-nav/SideNavbar.tsx` file: + +```tsx +import { useState } from 'react'; +import { Link } from 'react-router-dom'; +import { useUserOperations } from 'src/api/useUserOperations'; +import GenPodLogo from 'src/assets/logos/GenpodLogo'; +import { FEATURE_FLAG } from 'src/feature-flag-configs/types'; +import { FeatureFlagVariant } from 'src/store/types'; +import { useFeatureFlagStore } from 'src/store/useFeatureFlagStore'; +import useUserStore from 'src/store/userStore'; + +import { + ActionIcon, + Autocomplete, + Burger, + Code, + Group, + rem, + ScrollArea, + Tooltip, + useMantineColorScheme +} from '@mantine/core'; +import { + IconLogout, + IconMenu2, + IconMoon, + IconSearch, + IconSun, + IconUser, + IconX, + IconArrowNarrowLeft +} from '@tabler/icons-react'; + +import { NavBarLinksGroup } from '../nav-links-group/NavLinksGroup'; +import { NavBarLinksGroupForComingSoon } from '../nav-links-group/NavLinksGroupForComingSoon'; +import { SideNavData } from './data'; +import classes from './SideNavbar.module.css'; + +export default function SideNavbar({ data }: SideNavbarProps) { + const [isNavOpen, setIsNavOpen] = useState(true); + const { getFeatureFlag } = useFeatureFlagStore(); + const { colorScheme, setColorScheme } = useMantineColorScheme({ + keepTransitions: true + }); + const flagConfig = getFeatureFlag(FEATURE_FLAG.SIDE_NAV); + const handleNavToggle = () => { + setIsNavOpen(!isNavOpen); + }; + const { logout: clearLocalStorageToLogout } = useUserStore(); + const { logout: networkCallToLogout } = useUserOperations(); + + const links = data.map(item => { + if (flagConfig.features[item.id] === 'hidden') return null; + if (flagConfig.features[item.id] === 'coming-soon') { + const variant: FeatureFlagVariant = + flagConfig.variants && flagConfig.variants[item.id]; + + return ( + ({ + label: 'Coming Soon', + link: variant.url + }))} + variant={variant} + /> + ); + } + return ; + }); + + return ( + + ); +} +``` + +This is a React functional component named `SideNavbar` that serves as the sidebar navigation component of the application. Here's what the code does: + +1. It imports necessary components, hooks, and utilities from other files: + * `useState` from `react` for managing state. + * `Link` from `react-router-dom` for creating links. + * `useUserOperations` from `src/api/useUserOperations` for accessing user operations. + * `GenPodLogo` from `src/assets/logos/GenpodLogo` for displaying the logo. + * `FEATURE_FLAG` from `src/feature-flag-configs/types` for accessing feature flags. + * `FeatureFlagVariant` from `src/store/types` for accessing feature flag variants. + * `useFeatureFlagStore` from `src/store/useFeatureFlagStore` for accessing feature flags. + * `useUserStore` from `src/store/userStore` for accessing user data. + * Various components from `@mantine/core` and `@tabler/icons-react` for rendering UI elements. +2. It defines the `SideNavbar` component as a functional component using the `export default function` syntax. +3. It uses the `useState` hook to manage the `isNavOpen` state, which determines whether the sidebar is open or closed. +4. It uses the `useFeatureFlagStore` hook to access the feature flags and variants. +5. It defines a `handleNavToggle` function that toggles the `isNavOpen` state. +6. It defines a `links` array that maps over the `data` prop and renders either a `NavBarLinksGroup` or a `NavBarLinksGroupForComingSoon` component for each item, depending on the feature flag configuration. +7. It returns a JSX element that renders the sidebar navigation component, including the logo, links, and toggle button. + +In summary, this file defines the sidebar navigation component of the application, which displays a logo, links, and a toggle button, and manages the open/closed state of the sidebar using the `isNavOpen` \ No newline at end of file diff --git a/docs/ProjectDoc/src/canvas/Flow.md b/docs/ProjectDoc/src/canvas/Flow.md new file mode 100644 index 0000000..a31ee9c --- /dev/null +++ b/docs/ProjectDoc/src/canvas/Flow.md @@ -0,0 +1,197 @@ +# Flow Component Documentation + +## Overview +The `Flow` component is the main canvas component that implements the React Flow interface for node-based visual programming. + +## Implementation + +### Core Dependencies +```typescript +import ReactFlow, { + Background, + BackgroundVariant, + Controls, + Panel +} from 'reactflow'; +``` + +### Features +1. Interactive node canvas +2. Custom node types +3. Edge connections +4. Background grid +5. Control panel + +## Component Structure + +### State Management +- Uses Zustand for flow state +- Manages nodes and edges +- Handles active flow selection + +### UI Components +1. ReactFlow canvas +2. Code view drawer +3. Generate code drawer +4. Add node modal +5. Control panels + +### Navigation +- Project-based routing +- Flow selection +- Code generation + +## Functionality + +### Node Management +1. Node addition +2. Node deletion +3. Node positioning +4. Node connections + +### Edge Management +1. Edge creation +2. Edge deletion +3. Edge styling +4. Connection validation + +### Code Integration +1. Code view +2. Code generation +3. Code synchronization +4. Project integration + +## Usage + +### Basic Setup +```typescript + + + +``` + +### Features +1. Node dragging +2. Edge creation +3. Background customization +4. Control panel +5. Code generation + +## State Management + +### Flow Store +- Node state +- Edge state +- Active flow +- Flow operations + +### Project Store +- Project data +- Flow metadata +- Synchronization + +## Event Handling + +### Node Events +1. Position change +2. Selection +3. Deletion +4. Connection + +### Edge Events +1. Creation +2. Deletion +3. Update +4. Validation + +## UI Components + +### Drawers +1. Code view +2. Generate code +3. Node details +4. Settings + +### Modals +1. Add node +2. Edit node +3. Confirmation + +## Best Practices + +### Performance +1. Memoization +2. State optimization +3. Event debouncing +4. Render optimization + +### Error Handling +1. Connection validation +2. State validation +3. User feedback +4. Error recovery + +## Related Components + +### Node Types +- Custom nodes +- Node configuration +- Node styling + +### Edge Types +- Custom edges +- Edge styling +- Edge validation + +## Technical Details + +### Props +- None (uses internal state) + +### State +1. Flow data +2. UI state +3. Node positions +4. Edge connections + +### Effects +1. Flow synchronization +2. Code generation +3. State persistence +4. Error handling + +## Development Guidelines + +### Adding Features +1. State updates +2. UI components +3. Event handling +4. Error handling + +### Testing +1. Component testing +2. Integration testing +3. Event testing +4. State testing + +## Resources + +### Dependencies +1. React Flow +2. Mantine UI +3. Zustand +4. TypeScript + +### Documentation +1. React Flow docs +2. Component API +3. State management +4. Event system diff --git a/docs/ProjectDoc/src/canvas/edges/EdgesGuide.md b/docs/ProjectDoc/src/canvas/edges/EdgesGuide.md new file mode 100644 index 0000000..4cc009a --- /dev/null +++ b/docs/ProjectDoc/src/canvas/edges/EdgesGuide.md @@ -0,0 +1,200 @@ +# Canvas Edges Documentation + +## Overview +The edges system implements custom edge types and functionality for connecting nodes in the visual programming interface. + +## Components + +### CustomEdge +Located in `CustomEdge.tsx` +- Custom edge implementation +- Connection visualization +- Interactive features +- Styling options + +### Edge Drawer +Located in `CustomEdge.drawer.tsx` +- Edge configuration UI +- Property editing +- Style customization +- Connection settings + +### Edge Form +Located in `CustomEdge.drawer.form.tsx` +- Form components +- Validation +- Data handling +- UI elements + +## Implementation + +### Edge Structure +```typescript +interface CustomEdge { + id: string; + source: string; + target: string; + type: string; + data?: EdgeData; +} +``` + +### Edge Types Registry +```typescript +const edgeTypes = { + custom: CustomEdge +}; +``` + +## Features + +### Core Features +1. Connection visualization +2. Interactive editing +3. Style customization +4. Data transfer + +### Edge Properties +1. Connection type +2. Data flow +3. Validation rules +4. Visual style + +### Interactive Features +1. Edge selection +2. Path editing +3. Connection points +4. Validation feedback + +## Usage + +### Edge Creation +```typescript +const edge = { + id: 'edge-1', + source: 'node-1', + target: 'node-2', + type: 'custom', + data: { + // Edge-specific data + } +}; +``` + +### Edge Configuration +1. Connection type +2. Data mapping +3. Validation rules +4. Visual settings + +## Development + +### Custom Edges +1. Edge component +2. Props interface +3. Event handlers +4. Styling + +### Edge Forms +1. Form fields +2. Validation +3. Data handling +4. UI components + +## Best Practices + +### Component Design +1. Reusability +2. Type safety +3. Error handling +4. Performance + +### Edge Validation +1. Connection rules +2. Data validation +3. Error feedback +4. Recovery options + +## Edge Types + +### Connection Types +1. Data flow +2. Control flow +3. Event flow +4. State flow + +### Visual Types +1. Direct +2. Bezier +3. Step +4. Custom path + +## Styling + +### Visual Design +1. Path style +2. Connection points +3. Interactive states +4. Error states + +### Theme Integration +1. Color scheme +2. Line styles +3. Animations +4. Icons + +## Testing + +### Component Tests +1. Rendering +2. Interaction +3. Validation +4. Error states + +### Integration Tests +1. Node connections +2. Data flow +3. Edge creation +4. Error handling + +## Performance + +### Optimization +1. Rendering +2. Path calculation +3. Event handling +4. Memory usage + +### Monitoring +1. Performance metrics +2. Error tracking +3. Usage analytics +4. Debug tools + +## Documentation + +### Requirements +1. Edge purpose +2. Configuration +3. Examples +4. API reference + +### Guidelines +1. Code comments +2. Type definitions +3. Usage examples +4. Error handling + +## Resources + +### Dependencies +1. React Flow +2. TypeScript +3. Styling libraries +4. Testing tools + +### References +1. Edge types +2. API documentation +3. Best practices +4. Examples diff --git a/docs/ProjectDoc/src/canvas/nodes/NodesGuide.md b/docs/ProjectDoc/src/canvas/nodes/NodesGuide.md new file mode 100644 index 0000000..8c410d9 --- /dev/null +++ b/docs/ProjectDoc/src/canvas/nodes/NodesGuide.md @@ -0,0 +1,206 @@ +# Canvas Nodes Documentation + +## Overview +The nodes system implements various node types for the visual programming interface, including client nodes, database nodes, and microservice nodes. + +## Node Types + +### Client Node +Located in `client-node/` +- Frontend client implementation +- UI components +- Client-side logic +- API integration + +### Database Node +Located in `db-node/` +- Database connection +- Schema definition +- Query operations +- Data modeling + +### Microservice Node +Located in `microservice/` +- Service implementation +- API endpoints +- Business logic +- Service communication + +## Implementation + +### Node Structure +```typescript +interface BaseNode { + id: string; + type: string; + position: Position; + data: NodeData; +} +``` + +### Node Types Registry +```typescript +const nodeTypes = { + clientNode: ClientNode, + dbNode: DatabaseNode, + microserviceNode: MicroserviceNode +}; +``` + +## Features + +### Common Features +1. Drag and drop +2. Connection points +3. Configuration +4. Code generation + +### Client Node Features +1. UI components +2. API integration +3. State management +4. Event handling + +### Database Node Features +1. Schema definition +2. Query builder +3. Relationships +4. Data validation + +### Microservice Features +1. API endpoints +2. Service logic +3. Communication +4. Error handling + +## Usage + +### Node Creation +```typescript +const node = { + id: 'node-1', + type: 'clientNode', + position: { x: 0, y: 0 }, + data: { + // Node-specific data + } +}; +``` + +### Node Configuration +1. Properties +2. Connections +3. Validation +4. Code generation + +## Development + +### Adding New Nodes +1. Node component +2. Type definition +3. Registration +4. Documentation + +### Node Components +1. React component +2. Props interface +3. Event handlers +4. Styling + +## Best Practices + +### Component Design +1. Reusability +2. Type safety +3. Error handling +4. Performance + +### Code Generation +1. Template system +2. Code validation +3. Error handling +4. Documentation + +## Node Communication + +### Connection Types +1. HTTP/REST +2. GraphQL +3. WebSocket +4. Message Queue + +### Data Flow +1. Request/Response +2. Event-driven +3. Stream +4. Batch + +## Styling + +### Visual Design +1. Node appearance +2. Connection points +3. Interactive states +4. Error states + +### Theme Integration +1. Color scheme +2. Typography +3. Spacing +4. Icons + +## Testing + +### Component Tests +1. Rendering +2. Interaction +3. Configuration +4. Error states + +### Integration Tests +1. Node connections +2. Data flow +3. Code generation +4. Error handling + +## Performance + +### Optimization +1. Rendering +2. State updates +3. Event handling +4. Memory usage + +### Monitoring +1. Performance metrics +2. Error tracking +3. Usage analytics +4. Debug tools + +## Documentation + +### Requirements +1. Node purpose +2. Configuration +3. Examples +4. API reference + +### Guidelines +1. Code comments +2. Type definitions +3. Usage examples +4. Error handling + +## Resources + +### Dependencies +1. React Flow +2. TypeScript +3. Styling libraries +4. Testing tools + +### References +1. Node types +2. API documentation +3. Best practices +4. Examples diff --git a/docs/ProjectDoc/src/canvas/store/StoreGuide.md b/docs/ProjectDoc/src/canvas/store/StoreGuide.md new file mode 100644 index 0000000..600577e --- /dev/null +++ b/docs/ProjectDoc/src/canvas/store/StoreGuide.md @@ -0,0 +1,198 @@ +# Canvas Store Documentation + +## Overview +The canvas store system manages the state of the flow editor, including nodes, edges, and their relationships. + +## Store Structure + +### Flow Store +Located in `flowstore.ts` +- Node management +- Edge management +- Flow state +- Operations + +### Store Types +Located in `types.store.ts` +- Type definitions +- Interfaces +- Enums +- Constants + +## Implementation + +### Flow Store Interface +```typescript +interface FlowStore { + nodes: Node[]; + edges: Edge[]; + activeFlow: string | null; + onNodesChange: (changes: NodeChange[]) => void; + onEdgesChange: (changes: EdgeChange[]) => void; + onConnect: (connection: Connection) => void; +} +``` + +### State Management +```typescript +const useFlowStore = create((set, get) => ({ + nodes: [], + edges: [], + activeFlow: null, + // Store methods... +})); +``` + +## Features + +### Node Management +1. Node creation +2. Node updates +3. Node deletion +4. Node selection + +### Edge Management +1. Edge creation +2. Edge updates +3. Edge deletion +4. Connection handling + +### Flow Operations +1. Flow selection +2. State persistence +3. Undo/Redo +4. Validation + +## Usage + +### Basic Usage +```typescript +const { + nodes, + edges, + onNodesChange, + onEdgesChange, + onConnect +} = useFlowStore(); +``` + +### Flow Operations +```typescript +const { + setActiveFlow, + clearFlow, + resetFlow +} = useFlowStore(); +``` + +## State Structure + +### Nodes State +1. Node data +2. Position +3. Type +4. Connections + +### Edges State +1. Edge data +2. Source/Target +3. Type +4. Properties + +## Operations + +### Node Operations +1. Add node +2. Update node +3. Delete node +4. Move node + +### Edge Operations +1. Add edge +2. Update edge +3. Delete edge +4. Validate connection + +## Best Practices + +### State Management +1. Immutable updates +2. Type safety +3. Error handling +4. Performance + +### Data Flow +1. Unidirectional flow +2. Action creators +3. Selectors +4. Middleware + +## Testing + +### Unit Tests +1. Store creation +2. State updates +3. Operations +4. Selectors + +### Integration Tests +1. Component integration +2. Flow operations +3. State persistence +4. Error handling + +## Performance + +### Optimization +1. State updates +2. Memoization +3. Batch operations +4. Memory management + +### Monitoring +1. State changes +2. Performance metrics +3. Error tracking +4. Debug tools + +## Error Handling + +### Strategies +1. Validation +2. Error states +3. Recovery +4. Logging + +### Implementation +1. Error actions +2. State recovery +3. User feedback +4. Debug info + +## Documentation + +### Requirements +1. Store purpose +2. API reference +3. Examples +4. Type definitions + +### Guidelines +1. Code comments +2. Type safety +3. Examples +4. Best practices + +## Resources + +### Dependencies +1. Zustand +2. TypeScript +3. React Flow +4. Testing tools + +### References +1. Store API +2. Type definitions +3. Best practices +4. Examples diff --git a/docs/ProjectDoc/src/components/Components.md b/docs/ProjectDoc/src/components/Components.md new file mode 100644 index 0000000..aac8126 --- /dev/null +++ b/docs/ProjectDoc/src/components/Components.md @@ -0,0 +1,177 @@ +# Components Directory Documentation + +## Directory Structure Overview + +The components directory is organized into three main sections: +1. `common/` - Reusable components shared across the application +2. `home/` - Components specific to the home page +3. `user/` - User-related components + +## Common Components (`/common`) + +### Code Editor (`/code-editor`) +- Code editing interface component +- Provides syntax highlighting and editing capabilities + +### Headers (`/headers`) +- Header components for different sections +- Contains default header implementation + +### Layout (`/layout`) +- Layout components for page structure +- Includes main layout and sidebar layout variations + +### Loading (`/loading`) +- Loading state components +- Provides loading indicators and spinners + +### Modal (`/modal`) +- Modal dialog components +- Reusable modal windows for various purposes + +### Nav Links Group (`/nav-links-group`) +- Navigation link grouping components +- Handles navigation menu structure +- Includes collapsible navigation groups + +### Side Nav (`/side-nav`) +- Sidebar navigation components +- Implements collapsible sidebar menu +- Contains navigation data and styling + +### Terminal (`/terminal`) +- Terminal emulator component +- Provides command-line interface functionality + +## Home Components (`/home`) + +### Projects (`/projects`) +- Project management components +- Project listing and display +- Project-related actions and operations +- Snapshot management functionality + +## User Components (`/user`) + +### Projects (`/projects`) +- User-specific project components +- Personal project management +- Project interaction features + +### Index (`index.ts`) +- Main entry point for user components +- Exports user-related components + +## Component Features + +### Common Components + +#### Layout System +- Flexible layout components +- Responsive design support +- Sidebar integration +- Header management + +#### Navigation +- Hierarchical navigation structure +- Collapsible menu groups +- Route management +- Protected route handling + +#### UI Elements +- Modal windows +- Loading indicators +- Code editor interface +- Terminal emulator + +### Home Components + +#### Project Management +- Project creation +- Project listing +- Project navigation +- Snapshot handling + +### User Components + +#### User Interface +- User-specific views +- Personal project management +- User settings and preferences + +## Usage Guidelines + +### Layout Implementation +```tsx +import Layout from 'src/components/common/layout/Layout'; + + + {/* Page content */} + +``` + +### Navigation +```tsx +import SideNavbar from 'src/components/common/side-nav/SideNavbar'; + + +``` + +### Modals +```tsx +import Modal from 'src/components/common/modal/Modal'; + + + {/* Modal content */} + +``` + +## Best Practices + +1. **Component Organization** + - Keep related components together + - Use appropriate directory structure + - Maintain clear component boundaries + +2. **Code Reusability** + - Utilize common components + - Share functionality through hooks + - Maintain consistent interfaces + +3. **State Management** + - Use appropriate state management + - Implement proper data flow + - Handle loading states + +4. **Styling** + - Follow consistent styling patterns + - Use Mantine UI components + - Maintain responsive design + +5. **Security** + - Implement protected routes + - Handle authentication + - Validate user input + +## Component Dependencies + +### UI Framework +- Mantine UI components +- Custom styled components +- Responsive design utilities + +### Routing +- React Router for navigation +- Protected route implementation +- Route management + +### State Management +- Zustand for global state +- React hooks for local state +- Form state management + +### Additional Features +- Code editing capabilities +- Terminal functionality +- Modal management +- Loading state handling diff --git a/docs/ProjectDoc/src/components/Home/AddOrLoadProject.md b/docs/ProjectDoc/src/components/Home/AddOrLoadProject.md new file mode 100644 index 0000000..d9362d7 --- /dev/null +++ b/docs/ProjectDoc/src/components/Home/AddOrLoadProject.md @@ -0,0 +1,161 @@ +# AddOrLoadProject Component Documentation + +## Overview +The `AddOrLoadProject` component is a React component that provides functionality for both creating new projects and loading existing ones. It features a split-view interface with project creation on one side and project loading on the other. + +## Features +- Create new projects with validation +- Load existing projects +- Form validation using Zod +- Automatic project synchronization +- Navigation to project pages + +## Component Structure + +### Dependencies +```typescript +- React (useEffect) +- react-hook-form +- react-hook-form-mantine +- react-router-dom +- @hookform/resolvers/zod +- @mantine/core +- zod +``` + +### State Management +- Uses Zustand through `useProjectStore` +- Form state managed by `react-hook-form` +- Project synchronization via `useSyncActions` + +### Form Validation Schema +```typescript +const resolver = z.object({ + name: z.string().min(1, 'Project Name is required') +}); +``` + +## Component Features + +### Project Creation +1. **Form Handling** + - Project name input with validation + - Submit button for creation + - Error handling and feedback + +2. **Data Flow** + - Form submission handling + - Project creation through API + - Automatic synchronization after creation + +### Project Loading +1. **Project List** + - Display of existing projects + - Click-to-load functionality + - Dynamic project navigation + +2. **Navigation** + - Automatic navigation to project page + - Project state management + - URL-based routing + +## UI Components + +### Layout +- Split view design (50/50) +- Dark themed forms +- Responsive layout + +### Form Section +```tsx + +
+ + + +
+``` + +### Project List Section +```tsx + + Load Project + + {projects.map(project => ( + + ))} + + +``` + +## State and Data Flow + +### Project Creation Flow +1. User enters project name +2. Form validates input +3. On submit: + - Creates project object + - Posts to API + - Syncs project list + - Handles errors + +### Project Loading Flow +1. Component loads existing projects +2. User clicks project button +3. System: + - Sets active project + - Navigates to project page + - Updates URL + +## Usage Example +```tsx +import AddOrLoadProject from './AddOrLoadProject'; + +function HomePage() { + return ( +
+ +
+ ); +} +``` + +## Props +The component doesn't accept any props as it's self-contained with internal state management. + +## Styling +- Uses CSS modules (`AddOrLoadProject.module.css`) +- Mantine UI components +- Responsive design +- Dark theme integration + +## Error Handling +- Form validation errors +- API error handling +- Project creation error feedback +- Loading state management + +## Best Practices +1. **Form Validation** + - Required field validation + - Real-time validation feedback + - Error message display + +2. **State Management** + - Centralized project state + - Form state isolation + - Synchronization handling + +3. **User Experience** + - Clear interface division + - Intuitive project loading + - Responsive feedback + - Error state handling diff --git a/docs/ProjectDoc/src/components/Home/Snapshots.md b/docs/ProjectDoc/src/components/Home/Snapshots.md new file mode 100644 index 0000000..57747e2 --- /dev/null +++ b/docs/ProjectDoc/src/components/Home/Snapshots.md @@ -0,0 +1,175 @@ +# Snapshots Component Documentation + +## Overview +The `Snapshots` component is a React component that displays and manages project snapshots in a tabular format. It provides functionality to view, select, and load project snapshots with a user-friendly interface. + +## Features +- Display project snapshots in a table +- Select multiple snapshots +- Load specific snapshots +- Real-time notifications +- Project navigation links +- Timestamp formatting + +## Component Structure + +### Dependencies +```typescript +- React (useEffect, useState) +- @mantine/core +- @mantine/notifications +- react-router-dom +``` + +### State Management +- Local state for snapshots using `useState` +- Local state for selected rows +- Project state through `useProjectStore` +- API operations via `useProjectOperations` + +### Data Types +```typescript +interface ProjectSnapshot { + id: string; + version: string; + projectId: string; + userId: string; + createdAt: string; +} +``` + +## Component Features + +### Snapshot Fetching +1. **Initialization** + - Automatically fetches snapshots on component mount + - Handles active project context + - Provides feedback through notifications + +2. **Error Handling** + - Success notifications + - Error notifications + - Null state handling + +### Table Features +1. **Columns** + - Selection checkbox + - Version + - Project ID (with link) + - User ID + - Creation timestamp + - Actions + +2. **Row Features** + - Row selection + - Background highlighting for selected rows + - Load snapshot action + - Project navigation link + +## UI Components + +### Table Structure +```tsx + + + + + Version + Project ID + User ID + Created At + Actions + + + {rows} +
+``` + +### Row Component +```tsx + + + + + {snapshot.version} + + + {snapshot.projectId} + + + {/* Other cells */} + +``` + +## State and Data Flow + +### Data Fetching Flow +1. Component mounts +2. Checks for active project +3. Fetches snapshots if project exists +4. Updates state and shows notification + +### Selection Management +1. User clicks checkbox +2. Updates selected rows state +3. Updates row styling +4. Maintains selection across renders + +## Usage Example +```tsx +import Snapshots from './Snapshots'; + +function ProjectPage() { + return ( +
+ +
+ ); +} +``` + +## Props +The component doesn't accept any props as it uses internal state management and context. + +## Styling +- Mantine UI components +- Dynamic row highlighting +- Scrollable table area +- Responsive design + +## Notifications +1. **Success Notification** + - Green color + - Success message + - Snapshot data confirmation + +2. **Error Notification** + - Red color + - Error message + - Error details + +## Best Practices +1. **Data Handling** + - Null checks + - Loading states + - Error boundaries + +2. **User Experience** + - Clear selection feedback + - Easy navigation + - Action confirmation + - Timestamp formatting + +3. **Performance** + - Efficient state updates + - Optimized rendering + - Proper cleanup + +## Error Handling +- API error handling +- Null snapshot handling +- Loading state management +- User feedback through notifications diff --git a/docs/ProjectDoc/src/components/common/CodeEditor.md b/docs/ProjectDoc/src/components/common/CodeEditor.md new file mode 100644 index 0000000..0142bac --- /dev/null +++ b/docs/ProjectDoc/src/components/common/CodeEditor.md @@ -0,0 +1,182 @@ +# CodeEditor Component Documentation + +## Overview +The `CodeEditor` component is a React-based code editor implementation using CodeMirror. It provides a feature-rich editing experience with syntax highlighting, autocompletion, and YAML language support. + +## Features +- Syntax highlighting +- Autocompletion +- YAML language support +- Bracket matching +- Dark theme +- Customizable height +- Event handling + +## Component Structure + +### Dependencies +```typescript +- @codemirror/autocomplete +- @uiw/codemirror-extensions-langs +- @uiw/react-codemirror +``` + +### Props Interface +```typescript +interface CodeEditorProps extends ReactCodeMirrorProps { + value: string; + onChange?: (value: string, viewUpdate: ViewUpdate) => void; + height?: string; +} +``` + +## Component Features + +### Code Editor Setup +1. **Basic Configuration** + - Dark theme + - Full width layout + - Customizable height (default: 88vh) + - YAML language support + +2. **Editor Extensions** + - Basic setup with autocompletion + - Bracket matching + - Close brackets + - Default keymap + +### Autocompletion +1. **Custom Completions** + ```typescript + const myCompletions = (context: CompletionContext) => { + const word = context.matchBefore(/\w*/); + if (!word) return null; + if (word.from == word.to && !context.explicit) return null; + return { + from: word.from, + options: [ + { label: 'name', type: 'variable' }, + { + label: 'version', + type: 'variable', + info: 'enter the kubernetes version' + } + ] + }; + }; + ``` + +2. **Completion Features** + - Word matching + - Variable suggestions + - Contextual information + - Custom trigger conditions + +## Usage Example +```tsx +import CodeEditor from './CodeEditor'; + +function MyComponent() { + const [code, setCode] = useState(''); + + const handleChange = (value: string) => { + setCode(value); + }; + + return ( + + ); +} +``` + +## Props +1. **Required Props** + - `value`: Current editor content + +2. **Optional Props** + - `onChange`: Change event handler + - `height`: Editor height + - All other CodeMirror props + +## Editor Configuration + +### Basic Setup +```typescript +basicSetup({ + autocompletion: true, + bracketMatching: true, + closeBrackets: true, + defaultKeymap: true +}) +``` + +### Language Support +```typescript +langs.yaml().data.of({ + autocomplete: myCompletions +}) +``` + +### Autocompletion Setup +```typescript +autocompletion({ + override: [myCompletions] +}) +``` + +## Styling +- Dark theme by default +- Full width layout +- Customizable height +- Responsive design + +## Event Handling +1. **Change Events** + - Triggered on content changes + - Provides updated value + - Includes view update information + +2. **View Updates** + - Cursor position + - Selection changes + - Viewport changes + +## Best Practices +1. **Performance** + - Efficient update handling + - Optimized rendering + - Proper cleanup + +2. **User Experience** + - Immediate feedback + - Smooth editing + - Helpful suggestions + +3. **Integration** + - Clean props interface + - Flexible configuration + - Easy customization + +## Error Handling +- Null checks for completions +- Safe event handling +- Proper prop validation + +## Customization +1. **Theme Options** + - Dark theme default + - Customizable through props + +2. **Layout** + - Adjustable height + - Full width by default + - Flexible container + +3. **Extensions** + - Custom completions + - Language support + - Editor features diff --git a/docs/ProjectDoc/src/components/common/Loading.md b/docs/ProjectDoc/src/components/common/Loading.md new file mode 100644 index 0000000..0932396 --- /dev/null +++ b/docs/ProjectDoc/src/components/common/Loading.md @@ -0,0 +1,98 @@ + + +Here's an explanation of the `Loading` component in `src/components/common/loading/Loading.tsx`: + +**Loading Component Explanation** +===================================== + +The `Loading` component is a functional component that displays a loading indicator with an optional text message. It is designed to be used as a placeholder while data is being loaded or processed. + +**Imports** +------------ + +The component imports the following dependencies: + +* `Flex`, `Loader`, and `Text` from `@mantine/core` + +**Component Functionality** +--------------------------- + +The component has the following functionality: + +* Displays a loading indicator (a spinning wheel) using the `Loader` component from `@mantine/core`. +* Optionally displays a text message next to the loading indicator. +* Allows the user to customize the color of the loading indicator. +* Allows the user to customize the text message displayed next to the loading indicator. + +**Component Structure** +----------------------- + +The component consists of the following sections: + +* A `Flex` container that wraps the loading indicator and text message. +* A `Loader` component that displays the loading indicator. +* A `Text` component that displays the text message. + +**Props** +--------- + +The component accepts the following props: + +* `color`: The color of the loading indicator. Defaults to `'orange'`. +* `loadingText`: The text message to display next to the loading indicator. Defaults to `'Loading ...'`. +* `showLoadingText`: A boolean indicating whether to display the text message. Defaults to `true`. + +**Example Usage** +----------------- + +Here's an example of how to use the `Loading` component: +```tsx +import Loading from 'src/components/common/loading/Loading'; + +function MyComponent() { + return ( + + ); +} +``` +**Markdown File** +----------------- + +Here's an example of how you can create a Markdown file to document this component: +```markdown +# Loading Component + +## Overview + +The `Loading` component displays a loading indicator with an optional text message. + +## Functionality + +* Displays a loading indicator (a spinning wheel) +* Optionally displays a text message next to the loading indicator +* Allows customization of the loading indicator color +* Allows customization of the text message + +## Structure + +* Flex container wrapping the loading indicator and text message +* Loader component displaying the loading indicator +* Text component displaying the text message + +## Props + +* `color`: Color of the loading indicator (defaults to `'orange'`) +* `loadingText`: Text message to display next to the loading indicator (defaults to `'Loading ...'`) +* `showLoadingText`: Boolean indicating whether to display the text message (defaults to `true`) + +## Example Usage + +```tsx +import Loading from 'src/components/common/loading/Loading'; + +function MyComponent() { + return ( + + ); +} +``` \ No newline at end of file diff --git a/docs/ProjectDoc/src/components/common/headers/header-default/HeaderDefault.md b/docs/ProjectDoc/src/components/common/headers/header-default/HeaderDefault.md new file mode 100644 index 0000000..13869b7 --- /dev/null +++ b/docs/ProjectDoc/src/components/common/headers/header-default/HeaderDefault.md @@ -0,0 +1,214 @@ +# HeaderDefault Component Documentation + +## Overview +The `HeaderDefault` component is a React-based header component that implements the main navigation bar for the GenPod application. It provides essential navigation features, user controls, and theme management in a clean, modern interface. + +## Features +- Application logo and branding +- Global search functionality +- User profile navigation +- Settings and logout options +- Theme toggle (dark/light mode) +- Notification access +- Responsive design + +## Technical Implementation + +### Dependencies +```typescript +import { ActionIcon, Autocomplete, Group, Menu, Tooltip } from '@mantine/core'; +import { IconBell, IconLogout, IconMoon, IconSearch, IconSettings, IconSun, IconUser } from '@tabler/icons-react'; +import { Link, useNavigate } from 'react-router-dom'; +import GenPodLogo from 'src/assets/logos/GenpodLogo'; +``` + +### State Management +```typescript +const { colorScheme, setColorScheme } = useMantineColorScheme({ + keepTransitions: true +}); +const { logout } = useUserStore(); +const navigate = useNavigate(); +``` + +## Component Structure + +### Layout +```tsx +
+
+ {/* Logo Section */} + + + + + + + {/* Navigation and Controls */} + + {/* Search Bar */} + {/* Navigation Links */} + {/* Theme Toggle */} + +
+
+``` + +### Key Features + +#### 1. Search Bar +```tsx +} +/> +``` + +#### 2. Navigation Links +- Profile +- Settings +- Notifications +- Theme Toggle + +#### 3. Settings Menu +```tsx + + + + + + + + + + {/* Settings and Logout Options */} + + +``` + +#### 4. Theme Toggle +```tsx + + {colorScheme === 'dark' ? ( + setColorScheme('light')}> + + + ) : ( + setColorScheme('dark')}> + + + )} + +``` + +## Styling + +### CSS Module Implementation +```css +.header { + width: 100vw; + background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6)); + border-bottom: rem(1px) solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4)); + padding: var(--mantine-spacing-md); + display: flex; + align-items: center; + justify-content: space-evenly; +} + +.inner { + height: rem(56px); + flex: 1; + display: flex; + justify-content: space-between; + align-items: center; +} +``` + +### Design Features +- Responsive layout +- Theme-aware colors +- Consistent spacing +- Smooth transitions +- Interactive hover states + +## Functionality + +### Navigation +- Home route (`/`) +- Profile route (`/profile`) +- Settings route (`/settings`) +- Notifications route (`/notifications`) +- Login route (`/login`) after logout + +### Theme Management +- Dark/light mode toggle +- Persistent theme selection +- Smooth theme transitions + +### User Authentication +- Logout functionality +- Session management +- Protected route navigation + +## Usage Example +```tsx +import { HeaderDefault } from './HeaderDefault'; + +function Layout() { + return ( +
+ + {/* Application Content */} +
+ ); +} +``` + +## Best Practices + +### Accessibility +- Tooltip labels for icons +- Semantic HTML structure +- Keyboard navigation +- ARIA attributes + +### Performance +- Optimized imports +- Efficient state updates +- Smooth transitions +- Responsive design + +### User Experience +- Clear navigation +- Consistent styling +- Visual feedback +- Intuitive controls + +## Error Handling +- Authentication state management +- Navigation guards +- Theme persistence +- Route protection + +## Customization +1. **Theme** + - Color scheme toggle + - Custom gradients + - Icon variations + +2. **Layout** + - Flexible spacing + - Responsive design + - Component alignment + +3. **Interactions** + - Hover effects + - Click feedback + - Transition animations + +## Security Considerations +- Protected routes +- Secure logout +- Session management +- Navigation guards diff --git a/docs/ProjectDoc/src/components/common/layout/Layout.md b/docs/ProjectDoc/src/components/common/layout/Layout.md new file mode 100644 index 0000000..9a9cfcd --- /dev/null +++ b/docs/ProjectDoc/src/components/common/layout/Layout.md @@ -0,0 +1,225 @@ +# Layout Component Documentation + +## Overview +The `Layout` component is a foundational React component that provides a consistent page structure across the application. It implements a vertical stack layout with a persistent header and flexible content area. + +## Features +- Consistent page structure +- Persistent header navigation +- Flexible content area +- Vertical stack layout +- TypeScript support + +## Technical Implementation + +### Dependencies +```typescript +import { Stack } from '@mantine/core' +import { HeaderDefault } from '../headers/header-default/HeaderDefault' +``` + +### Type Definitions +```typescript +interface LayoutProps { + children?: React.ReactNode | React.ReactNode[] | null +} +``` + +### Component Structure +```tsx +export default function Layout({ children }: LayoutProps) { + return ( + + + {children} + + ); +} +``` + +## Component Architecture + +### 1. Layout Structure +- Uses Mantine's `Stack` component for vertical layout +- Consistent spacing and alignment +- Flexible content rendering + +### 2. Header Integration +- Persistent `HeaderDefault` component +- Consistent navigation across pages +- Theme-aware styling + +### 3. Content Area +- Flexible children rendering +- Support for multiple child components +- Null-safe implementation + +## Usage + +### Basic Usage +```tsx +import Layout from './Layout'; + +function App() { + return ( + +
Page Content
+
+ ); +} +``` + +### With Multiple Children +```tsx +function ComplexPage() { + return ( + +
+ +